1
1
package telegram
2
2
3
3
import (
4
+ "bytes"
4
5
"context"
5
6
"encoding/json"
6
7
"os"
7
8
"path/filepath"
9
+ "time"
8
10
9
11
"github.com/krau/ManyACG/common"
10
12
"github.com/krau/ManyACG/config"
@@ -39,11 +41,11 @@ func (t *TelegramStorage) Init() {
39
41
40
42
func (t * TelegramStorage ) Save (ctx context.Context , filePath string , _ string ) (* types.StorageDetail , error ) {
41
43
common .Logger .Debugf ("saving file %s" , filePath )
42
- file , err := os .Open (filePath )
44
+ fileBytes , err := os .ReadFile (filePath )
43
45
if err != nil {
44
46
return nil , err
45
47
}
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 )))))
47
49
if err != nil {
48
50
return nil , err
49
51
}
@@ -56,6 +58,8 @@ func (t *TelegramStorage) Save(ctx context.Context, filePath string, _ string) (
56
58
if err != nil {
57
59
return nil , err
58
60
}
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 )
59
63
return & types.StorageDetail {
60
64
Type : types .StorageTypeTelegram ,
61
65
Path : string (data ),
@@ -68,13 +72,22 @@ func (t *TelegramStorage) GetFile(ctx context.Context, detail *types.StorageDeta
68
72
return nil , err
69
73
}
70
74
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
+ }
71
79
tgFile , err := Bot .GetFile (& telego.GetFileParams {
72
80
FileID : file .FileID ,
73
81
})
74
82
if err != nil {
75
83
return nil , err
76
84
}
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
78
91
}
79
92
80
93
func (t * TelegramStorage ) Delete (ctx context.Context , detail * types.StorageDetail ) error {
0 commit comments