Skip to content

Commit 4fac507

Browse files
committed
feat: optimize file handling in Telegram storage by using ReadFile and caching mechanism
1 parent 2976097 commit 4fac507

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

storage/telegram/telegram.go

+16-3
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
package telegram
22

33
import (
4+
"bytes"
45
"context"
56
"encoding/json"
67
"os"
78
"path/filepath"
9+
"time"
810

911
"github.com/krau/ManyACG/common"
1012
"github.com/krau/ManyACG/config"
@@ -39,11 +41,11 @@ func (t *TelegramStorage) Init() {
3941

4042
func (t *TelegramStorage) Save(ctx context.Context, filePath string, _ string) (*types.StorageDetail, error) {
4143
common.Logger.Debugf("saving file %s", filePath)
42-
file, err := os.Open(filePath)
44+
fileBytes, err := os.ReadFile(filePath)
4345
if err != nil {
4446
return nil, err
4547
}
46-
msg, err := Bot.SendDocument(telegoutil.Document(ChatID, telegoutil.File(telegoutil.NameReader(file, filepath.Base(filePath)))))
48+
msg, err := Bot.SendDocument(telegoutil.Document(ChatID, telegoutil.File(telegoutil.NameReader(bytes.NewReader(fileBytes), filepath.Base(filePath)))))
4749
if err != nil {
4850
return nil, err
4951
}
@@ -56,6 +58,8 @@ func (t *TelegramStorage) Save(ctx context.Context, filePath string, _ string) (
5658
if err != nil {
5759
return nil, err
5860
}
61+
cachePath := filepath.Join(config.Cfg.Storage.CacheDir, common.MD5Hash(fileMessage.FileID))
62+
go common.MkCache(cachePath, fileBytes, time.Duration(config.Cfg.Storage.CacheTTL)*time.Second)
5963
return &types.StorageDetail{
6064
Type: types.StorageTypeTelegram,
6165
Path: string(data),
@@ -68,13 +72,22 @@ func (t *TelegramStorage) GetFile(ctx context.Context, detail *types.StorageDeta
6872
return nil, err
6973
}
7074
common.Logger.Debugf("getting file %s", file.String())
75+
cachePath := filepath.Join(config.Cfg.Storage.CacheDir, common.MD5Hash(file.FileID))
76+
if data, err := os.ReadFile(cachePath); err == nil {
77+
return data, nil
78+
}
7179
tgFile, err := Bot.GetFile(&telego.GetFileParams{
7280
FileID: file.FileID,
7381
})
7482
if err != nil {
7583
return nil, err
7684
}
77-
return telegoutil.DownloadFile(Bot.FileDownloadURL(tgFile.FilePath))
85+
data, err := telegoutil.DownloadFile(Bot.FileDownloadURL(tgFile.FilePath))
86+
if err != nil {
87+
return nil, err
88+
}
89+
go common.MkCache(cachePath, data, time.Duration(config.Cfg.Storage.CacheTTL)*time.Second)
90+
return data, nil
7891
}
7992

8093
func (t *TelegramStorage) Delete(ctx context.Context, detail *types.StorageDetail) error {

0 commit comments

Comments
 (0)