codebydante commited on
Commit
ba57bbb
·
verified ·
1 Parent(s): 3b42e05

Delete internal

Browse files
internal/bot/client.go DELETED
@@ -1,58 +0,0 @@
1
- package bot
2
-
3
- import (
4
- "EverythingSuckz/fsb/config"
5
- "EverythingSuckz/fsb/internal/commands"
6
- "context"
7
- "time"
8
-
9
- "go.uber.org/zap"
10
-
11
- "github.com/celestix/gotgproto"
12
- "github.com/celestix/gotgproto/sessionMaker"
13
- "github.com/glebarez/sqlite"
14
- )
15
-
16
- var Bot *gotgproto.Client
17
-
18
- func StartClient(log *zap.Logger) (*gotgproto.Client, error) {
19
- ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
20
- defer cancel()
21
- resultChan := make(chan struct {
22
- client *gotgproto.Client
23
- err error
24
- })
25
- go func(ctx context.Context) {
26
- client, err := gotgproto.NewClient(
27
- int(config.ValueOf.ApiID),
28
- config.ValueOf.ApiHash,
29
- gotgproto.ClientTypeBot(config.ValueOf.BotToken),
30
- &gotgproto.ClientOpts{
31
- Session: sessionMaker.SqlSession(
32
- sqlite.Open("fsb.session"),
33
- ),
34
- DisableCopyright: true,
35
- },
36
- )
37
- resultChan <- struct {
38
- client *gotgproto.Client
39
- err error
40
- }{client, err}
41
- }(ctx)
42
-
43
- select {
44
- case <-ctx.Done():
45
- return nil, ctx.Err()
46
- case result := <-resultChan:
47
- if result.err != nil {
48
- return nil, result.err
49
- }
50
- commands.Load(log, result.client.Dispatcher)
51
- if err := commands.RegisterCommands(); err != nil {
52
- log.Error("Failed to register commands", zap.Error(err))
53
- }
54
- log.Info("Client started", zap.String("username", result.client.Self.Username))
55
- Bot = result.client
56
- return result.client, nil
57
- }
58
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
internal/bot/middleware.go DELETED
@@ -1,20 +0,0 @@
1
- package bot
2
-
3
- import (
4
- "time"
5
-
6
- "github.com/gotd/contrib/middleware/floodwait"
7
- "github.com/gotd/contrib/middleware/ratelimit"
8
- "github.com/gotd/td/telegram"
9
- "go.uber.org/zap"
10
- "golang.org/x/time/rate"
11
- )
12
-
13
- func GetFloodMiddleware(log *zap.Logger) []telegram.Middleware {
14
- waiter := floodwait.NewSimpleWaiter().WithMaxRetries(50)
15
- ratelimiter := ratelimit.New(rate.Every(time.Millisecond*50), 10)
16
- return []telegram.Middleware{
17
- waiter,
18
- ratelimiter,
19
- }
20
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
internal/bot/userbot.go DELETED
@@ -1,119 +0,0 @@
1
- package bot
2
-
3
- import (
4
- "EverythingSuckz/fsb/config"
5
- "errors"
6
-
7
- "github.com/celestix/gotgproto"
8
- "github.com/celestix/gotgproto/sessionMaker"
9
- "github.com/gotd/td/tg"
10
- "go.uber.org/zap"
11
- )
12
-
13
- type UserBotStruct struct {
14
- log *zap.Logger
15
- client *gotgproto.Client
16
- }
17
-
18
- var UserBot *UserBotStruct = &UserBotStruct{}
19
-
20
- func StartUserBot(l *zap.Logger) {
21
- log := l.Named("USERBOT")
22
- if config.ValueOf.UserSession == "" {
23
- log.Warn("User session is empty")
24
- return
25
- }
26
- log.Sugar().Infoln("Starting userbot")
27
- client, err := gotgproto.NewClient(
28
- int(config.ValueOf.ApiID),
29
- config.ValueOf.ApiHash,
30
- gotgproto.ClientTypePhone(""),
31
- &gotgproto.ClientOpts{
32
- Session: sessionMaker.PyrogramSession(config.ValueOf.UserSession),
33
- DisableCopyright: true,
34
- },
35
- )
36
- if err != nil {
37
- log.Error("Failed to start userbot", zap.Error(err))
38
- return
39
- }
40
- UserBot.log = log
41
- UserBot.client = client
42
- log.Info("Userbot started", zap.String("username", client.Self.Username), zap.String("FirstName", client.Self.FirstName), zap.String("LastName", client.Self.LastName))
43
- if err := UserBot.AddBotsAsAdmins(); err != nil {
44
- log.Error("Failed to add bots as admins", zap.Error(err))
45
- return
46
- }
47
- }
48
-
49
- func (u *UserBotStruct) AddBotsAsAdmins() error {
50
- u.log.Info("Preparing to add bots as admins")
51
- ctx := u.client.CreateContext()
52
- channel := config.ValueOf.LogChannelID
53
- channelInfos, err := u.client.API().ChannelsGetChannels(
54
- ctx,
55
- []tg.InputChannelClass{
56
- &tg.InputChannel{
57
- ChannelID: channel,
58
- },
59
- },
60
- )
61
- if err != nil {
62
- u.log.Error("Failed to get channel info", zap.Error(err))
63
- return errors.New("failed to get channel info")
64
- }
65
- if len(channelInfos.GetChats()) == 0 {
66
- return errors.New("no channels found")
67
- }
68
- inputChannel := channelInfos.GetChats()[0].(*tg.Channel).AsInput()
69
- currentAdmins := []int64{}
70
- admins, err := u.client.API().ChannelsGetParticipants(ctx, &tg.ChannelsGetParticipantsRequest{
71
- Channel: inputChannel,
72
- Filter: &tg.ChannelParticipantsAdmins{},
73
- Offset: 0,
74
- Limit: 100,
75
- })
76
- if err != nil {
77
- u.log.Error("Failed to get admins", zap.Error(err))
78
- return err
79
- }
80
- for _, admin := range admins.(*tg.ChannelsChannelParticipants).Participants {
81
- if user, ok := admin.(*tg.ChannelParticipantAdmin); ok {
82
- currentAdmins = append(currentAdmins, user.UserID)
83
- }
84
- }
85
- for _, bot := range Workers.Bots {
86
- isAdmin := false
87
- for _, admin := range currentAdmins {
88
- if admin == bot.Self.ID {
89
- u.log.Sugar().Infof("Bot @%s is already an admin", bot.Self.Username)
90
- isAdmin = true
91
- continue
92
- }
93
- }
94
- if isAdmin {
95
- continue
96
- }
97
- botInfo, err := ctx.ResolveUsername(bot.Self.Username)
98
- if err != nil {
99
- u.log.Warn(err.Error())
100
- }
101
- _, err = u.client.API().ChannelsEditAdmin(
102
- u.client.CreateContext().Context,
103
- &tg.ChannelsEditAdminRequest{
104
- Channel: inputChannel,
105
- UserID: botInfo.GetInputUser(),
106
- AdminRights: tg.ChatAdminRights{
107
- PostMessages: true,
108
- },
109
- Rank: "admin",
110
- },
111
- )
112
- if err != nil {
113
- u.log.Sugar().Warnf("Failed to add @%s as admin", bot.Self.Username)
114
- u.log.Warn(err.Error())
115
- }
116
- u.log.Sugar().Infof("Added @%s as admin", bot.Self.Username)
117
- }
118
- return nil
119
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
internal/bot/workers.go DELETED
@@ -1,334 +0,0 @@
1
- package bot
2
-
3
- import (
4
- "EverythingSuckz/fsb/config"
5
- "context"
6
- "fmt"
7
- "os"
8
- "path/filepath"
9
- "strings"
10
- "sync"
11
- "sync/atomic"
12
- "time"
13
-
14
- firebase "firebase.google.com/go/v4"
15
- "google.golang.org/api/option"
16
-
17
- "github.com/celestix/gotgproto"
18
- "github.com/celestix/gotgproto/sessionMaker"
19
- "github.com/glebarez/sqlite"
20
- "github.com/gotd/td/tg"
21
- "go.uber.org/zap"
22
- )
23
-
24
- type Worker struct {
25
- ID int
26
- Client *gotgproto.Client
27
- Self *tg.User
28
- Token string
29
- log *zap.Logger
30
- }
31
-
32
- func (w *Worker) String() string {
33
- return fmt.Sprintf("{Worker (%d|@%s)}", w.ID, w.Self.Username)
34
- }
35
-
36
- type BotWorkers struct {
37
- Bots []*Worker
38
- starting int
39
- index int
40
- mut sync.Mutex
41
- log *zap.Logger
42
- }
43
-
44
- var Workers *BotWorkers = &BotWorkers{
45
- log: nil,
46
- Bots: make([]*Worker, 0),
47
- }
48
-
49
- func (w *BotWorkers) Init(log *zap.Logger) {
50
- w.log = log.Named("Workers")
51
- }
52
-
53
- func (w *BotWorkers) AddDefaultClient(client *gotgproto.Client, self *tg.User) {
54
- if w.Bots == nil {
55
- w.Bots = make([]*Worker, 0)
56
- }
57
- w.incStarting()
58
- w.Bots = append(w.Bots, &Worker{
59
- Client: client,
60
- ID: w.starting,
61
- Self: self,
62
- Token: config.ValueOf.BotToken,
63
- log: w.log,
64
- })
65
- w.log.Sugar().Info("Default bot loaded")
66
- }
67
-
68
- func (w *BotWorkers) incStarting() {
69
- w.mut.Lock()
70
- defer w.mut.Unlock()
71
- w.starting++
72
- }
73
-
74
- func (w *BotWorkers) Add(token string) (string, error) {
75
- w.mut.Lock()
76
- for _, b := range w.Bots {
77
- if b.Token == token {
78
- w.mut.Unlock()
79
- return "", fmt.Errorf("el token ya existe en la lista de workers")
80
- }
81
- }
82
- w.mut.Unlock()
83
-
84
- w.incStarting()
85
- var botID int = w.starting
86
- client, err := startWorker(w.log, token, botID)
87
- if err != nil {
88
- return "", err
89
- }
90
- w.log.Sugar().Infof("Bot @%s loaded with ID %d", client.Self.Username, botID)
91
- w.mut.Lock()
92
- w.Bots = append(w.Bots, &Worker{
93
- Client: client,
94
- ID: botID,
95
- Self: client.Self,
96
- Token: token,
97
- log: w.log,
98
- })
99
-
100
- w.mut.Unlock()
101
-
102
- return client.Self.Username, nil
103
- }
104
-
105
- func GetNextWorker() *Worker {
106
- Workers.mut.Lock()
107
- defer Workers.mut.Unlock()
108
- index := (Workers.index + 1) % len(Workers.Bots)
109
- Workers.index = index
110
- worker := Workers.Bots[index]
111
- Workers.log.Sugar().Debugf("Using worker %d", worker.ID)
112
- return worker
113
- }
114
-
115
- func StartWorkers(log *zap.Logger) (*BotWorkers, error) {
116
- Workers.Init(log)
117
-
118
- // Fetch dynamic tokens from Firebase
119
- var dynamicTokens []string
120
- if config.ValueOf.FirebaseJSON != "" {
121
- dynamicTokens, _ = Workers.LoadTokensFromFirebase()
122
- }
123
-
124
- allTokens := append(config.ValueOf.MultiTokens, dynamicTokens...)
125
-
126
- if len(allTokens) == 0 {
127
- Workers.log.Sugar().Info("No worker bot tokens provided, skipping worker initialization")
128
- return Workers, nil
129
- }
130
- Workers.log.Sugar().Info("Starting workers")
131
- if config.ValueOf.UseSessionFile {
132
- Workers.log.Sugar().Info("Using session file for workers")
133
- newpath := filepath.Join(".", "sessions")
134
- if err := os.MkdirAll(newpath, os.ModePerm); err != nil {
135
- Workers.log.Error("Failed to create sessions directory", zap.Error(err))
136
- return nil, err
137
- }
138
- }
139
-
140
- var wg sync.WaitGroup
141
- var successfulStarts int32
142
- totalBots := len(allTokens)
143
-
144
- for i := 0; i < totalBots; i++ {
145
- wg.Add(1)
146
- go func(i int) {
147
- defer wg.Done()
148
-
149
- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
150
- defer cancel()
151
-
152
- done := make(chan error, 1)
153
- go func() {
154
- _, err := Workers.Add(allTokens[i])
155
- done <- err
156
- }()
157
-
158
- select {
159
- case err := <-done:
160
- if err != nil {
161
- Workers.log.Error("Failed to start worker", zap.Int("index", i), zap.Error(err))
162
- } else {
163
- atomic.AddInt32(&successfulStarts, 1)
164
- }
165
- case <-ctx.Done():
166
- Workers.log.Error("Timed out starting worker", zap.Int("index", i))
167
- }
168
- }(i)
169
- }
170
-
171
- wg.Wait() // Wait for all goroutines to finish
172
- Workers.log.Sugar().Infof("Successfully started %d/%d bots", successfulStarts, totalBots)
173
-
174
- if len(dynamicTokens) > 0 {
175
- fmt.Println("\n🔥 [Firebase] Conectado exitosamente a Firestore.")
176
- fmt.Println(Workers.GetWorkerListText(true))
177
- }
178
- return Workers, nil
179
- }
180
-
181
- func (w *BotWorkers) GetWorkerListText(onlyDynamic bool) string {
182
- w.mut.Lock()
183
- defer w.mut.Unlock()
184
-
185
- var envBots []*Worker
186
- var dynamicBots []*Worker
187
-
188
- envTokensMap := make(map[string]bool)
189
- for _, t := range config.ValueOf.MultiTokens {
190
- envTokensMap[t] = true
191
- }
192
-
193
- for _, b := range w.Bots {
194
- if b.Token == config.ValueOf.BotToken {
195
- continue
196
- }
197
- if envTokensMap[b.Token] {
198
- envBots = append(envBots, b)
199
- } else {
200
- dynamicBots = append(dynamicBots, b)
201
- }
202
- }
203
-
204
- var sb strings.Builder
205
- if len(envBots) > 0 {
206
- sb.WriteString(fmt.Sprintf("⚙️ **Lista de %d Tokens Estáticos (.env):**\n\n", len(envBots)))
207
- for i, b := range envBots {
208
- sb.WriteString(fmt.Sprintf("%d️��� @%s\n`%s`\n\n", i+1, b.Self.Username, b.Token))
209
- }
210
- }
211
-
212
- if len(dynamicBots) > 0 {
213
- sb.WriteString(fmt.Sprintf("📋 **Lista de %d Tokens Dinámicos (Firebase):**\n\n", len(dynamicBots)))
214
- for i, b := range dynamicBots {
215
- sb.WriteString(fmt.Sprintf("%d️⃣ @%s\n`%s`\n\n", i+1, b.Self.Username, b.Token))
216
- }
217
- } else if len(envBots) == 0 {
218
- return "ℹ️ No hay tokens adicionales configurados (ni dinámicos ni estáticos)."
219
- }
220
-
221
- return strings.TrimSpace(sb.String())
222
- }
223
-
224
- func startWorker(l *zap.Logger, botToken string, index int) (*gotgproto.Client, error) {
225
- log := l.Named("Worker").Sugar()
226
- log.Infof("Starting worker with index - %d", index)
227
- var sessionType sessionMaker.SessionConstructor
228
- if config.ValueOf.UseSessionFile {
229
- // Use the Bot ID (first part of token) as the session filename
230
- // This prevents sessions from shuffling if order changes, which causes wrong usernames.
231
- sessionID := fmt.Sprintf("%d", index)
232
- if parts := strings.Split(botToken, ":"); len(parts) == 2 {
233
- sessionID = parts[0]
234
- }
235
- sessionType = sessionMaker.SqlSession(sqlite.Open(fmt.Sprintf("sessions/worker-%s.session", sessionID)))
236
- } else {
237
- sessionType = sessionMaker.SimpleSession()
238
- }
239
- client, err := gotgproto.NewClient(
240
- int(config.ValueOf.ApiID),
241
- config.ValueOf.ApiHash,
242
- gotgproto.ClientTypeBot(botToken),
243
- &gotgproto.ClientOpts{
244
- Session: sessionType,
245
- DisableCopyright: true,
246
- Middlewares: GetFloodMiddleware(log.Desugar()),
247
- },
248
- )
249
- if err != nil {
250
- return nil, err
251
- }
252
- return client, nil
253
- }
254
-
255
- // SaveTokenToFirebase connects to Firestore and saves a bot token.
256
- func (w *BotWorkers) SaveTokenToFirebase(token string) error {
257
- if config.ValueOf.FirebaseJSON == "" {
258
- return fmt.Errorf("FIREBASE_JSON env var is empty, cannot save token dynamically")
259
- }
260
-
261
- ctx := context.Background()
262
- opt := option.WithCredentialsJSON([]byte(config.ValueOf.FirebaseJSON))
263
- app, err := firebase.NewApp(ctx, nil, opt)
264
- if err != nil {
265
- return fmt.Errorf("error initializing firebase: %v", err)
266
- }
267
-
268
- client, err := app.Firestore(ctx)
269
- if err != nil {
270
- return fmt.Errorf("error connecting to firestore: %v", err)
271
- }
272
- defer client.Close()
273
-
274
- // Check if token already exists to avoid duplication
275
- iter := client.Collection("brody_tokens").Where("token", "==", token).Documents(ctx)
276
- docs, err := iter.GetAll()
277
- if err == nil && len(docs) > 0 {
278
- return fmt.Errorf("el token ya existe en la base de datos de Firebase")
279
- }
280
-
281
- // Use a new document ID
282
- docRef := client.Collection("brody_tokens").NewDoc()
283
- _, err = docRef.Set(ctx, map[string]interface{}{
284
- "token": token,
285
- "created_at": time.Now(),
286
- })
287
- return err
288
- }
289
-
290
- // LoadTokensFromFirebase connects to Firestore and reads all saved bot tokens.
291
- func (w *BotWorkers) LoadTokensFromFirebase() ([]string, error) {
292
- if config.ValueOf.FirebaseJSON == "" {
293
- return nil, nil
294
- }
295
-
296
- w.log.Sugar().Info("Loading tokens from Firebase Firestore...")
297
- ctx := context.Background()
298
- opt := option.WithCredentialsJSON([]byte(config.ValueOf.FirebaseJSON))
299
- app, err := firebase.NewApp(ctx, nil, opt)
300
- if err != nil {
301
- w.log.Sugar().Warnf("error initializing firebase to load tokens: %v", err)
302
- return nil, err
303
- }
304
-
305
- client, err := app.Firestore(ctx)
306
- if err != nil {
307
- w.log.Sugar().Warnf("error connecting to firestore to load tokens: %v", err)
308
- return nil, err
309
- }
310
- defer client.Close()
311
-
312
- iter := client.Collection("brody_tokens").Documents(ctx)
313
- docs, err := iter.GetAll()
314
- if err != nil {
315
- w.log.Sugar().Warnf("error fetching tokens from firestore: %v", err)
316
- return nil, err
317
- }
318
-
319
- var tokens []string
320
- seen := make(map[string]bool)
321
- for _, doc := range docs {
322
- if t, ok := doc.Data()["token"].(string); ok && t != "" {
323
- if !seen[t] {
324
- tokens = append(tokens, t)
325
- seen[t] = true
326
- } else {
327
- // Remove duplicated keys from firestore automatically
328
- doc.Ref.Delete(ctx)
329
- }
330
- }
331
- }
332
- w.log.Sugar().Infof("Successfully loaded %d dynamic tokens from Firebase", len(tokens))
333
- return tokens, nil
334
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
internal/cache/cache.go DELETED
@@ -1,68 +0,0 @@
1
- package cache
2
-
3
- import (
4
- "EverythingSuckz/fsb/internal/types"
5
- "bytes"
6
- "encoding/gob"
7
- "sync"
8
-
9
- "github.com/coocood/freecache"
10
- "github.com/gotd/td/tg"
11
- "go.uber.org/zap"
12
- )
13
-
14
- var cache *Cache
15
-
16
- type Cache struct {
17
- cache *freecache.Cache
18
- mu sync.RWMutex
19
- log *zap.Logger
20
- }
21
-
22
- func InitCache(log *zap.Logger) {
23
- log = log.Named("cache")
24
- gob.Register(types.File{})
25
- gob.Register(tg.InputDocumentFileLocation{})
26
- gob.Register(tg.InputPhotoFileLocation{})
27
- defer log.Sugar().Info("Initialized")
28
- cache = &Cache{cache: freecache.NewCache(10 * 1024 * 1024), log: log}
29
- }
30
-
31
- func GetCache() *Cache {
32
- return cache
33
- }
34
-
35
- func (c *Cache) Get(key string, value *types.File) error {
36
- c.mu.RLock()
37
- defer c.mu.RUnlock()
38
- data, err := cache.cache.Get([]byte(key))
39
- if err != nil {
40
- return err
41
- }
42
- dec := gob.NewDecoder(bytes.NewReader(data))
43
- err = dec.Decode(&value)
44
- if err != nil {
45
- return err
46
- }
47
- return nil
48
- }
49
-
50
- func (c *Cache) Set(key string, value *types.File, expireSeconds int) error {
51
- c.mu.Lock()
52
- defer c.mu.Unlock()
53
- var buf bytes.Buffer
54
- enc := gob.NewEncoder(&buf)
55
- err := enc.Encode(value)
56
- if err != nil {
57
- return err
58
- }
59
- cache.cache.Set([]byte(key), buf.Bytes(), expireSeconds)
60
- return nil
61
- }
62
-
63
- func (c *Cache) Delete(key string) error {
64
- c.mu.Lock()
65
- defer c.mu.Unlock()
66
- cache.cache.Del([]byte(key))
67
- return nil
68
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
internal/cache/disk_cache.go DELETED
@@ -1,204 +0,0 @@
1
- package cache
2
-
3
- import (
4
- "EverythingSuckz/fsb/config"
5
- "context"
6
- "fmt"
7
- "io"
8
- "os"
9
- "path/filepath"
10
- "strconv"
11
- "time"
12
-
13
- "github.com/nickalie/go-webpbin"
14
- "go.uber.org/zap"
15
- "golang.org/x/sync/singleflight"
16
- )
17
-
18
- var (
19
- Disk *DiskCache
20
- )
21
-
22
- type DiskCache struct {
23
- dir string
24
- sf singleflight.Group
25
- log *zap.Logger
26
- downloadSem chan struct{}
27
- }
28
-
29
- func InitDiskCache(log *zap.Logger) error {
30
- dir := config.ValueOf.CacheDir
31
- if err := os.MkdirAll(dir, 0755); err != nil {
32
- return fmt.Errorf("failed to create cache directory: %w", err)
33
- }
34
-
35
- Disk = &DiskCache{
36
- dir: dir,
37
- log: log.Named("DiskCache"),
38
- downloadSem: make(chan struct{}, config.ValueOf.MaxConcurrentDownloads),
39
- }
40
-
41
- // Start cache sweeper (every 1 hour, delete files older than 24h)
42
- go Disk.startSweeper()
43
-
44
- Disk.log.Info("Disk cache initialized", zap.String("dir", dir), zap.Int("max_downloads", config.ValueOf.MaxConcurrentDownloads))
45
- return nil
46
- }
47
-
48
- // GetOrDownload returns the path to the cached original file.
49
- // If not exists, executes the fetcher under a singleflight lock and a semaphore.
50
- func (c *DiskCache) GetOrDownload(ctx context.Context, messageID int, fetcher func() (io.ReadCloser, error)) (string, error) {
51
- filename := strconv.Itoa(messageID)
52
- path := filepath.Join(c.dir, filename)
53
-
54
- if c.fileExists(path) {
55
- // return directly
56
- return path, nil
57
- }
58
-
59
- // fetch with singleflight to avoid duplicated downloads
60
- result, err, _ := c.sf.Do(filename, func() (interface{}, error) {
61
- if c.fileExists(path) {
62
- return path, nil
63
- }
64
-
65
- c.log.Sugar().Infof("Starting download to disk cache: %s", filename)
66
-
67
- // Acquire semaphore
68
- select {
69
- case c.downloadSem <- struct{}{}:
70
- case <-ctx.Done():
71
- return nil, ctx.Err()
72
- }
73
- defer func() { <-c.downloadSem }()
74
-
75
- reader, err := fetcher()
76
- if err != nil {
77
- return nil, err
78
- }
79
- defer reader.Close()
80
-
81
- tempPath := path + ".tmp"
82
- fw, err := os.Create(tempPath)
83
- if err != nil {
84
- return nil, err
85
- }
86
-
87
- if _, err := io.Copy(fw, reader); err != nil {
88
- fw.Close()
89
- os.Remove(tempPath)
90
- return nil, err
91
- }
92
- fw.Close()
93
-
94
- if err := os.Rename(tempPath, path); err != nil {
95
- os.Remove(tempPath)
96
- return nil, err
97
- }
98
-
99
- c.log.Sugar().Infof("Cached file saved: %s", filename)
100
- return path, nil
101
- })
102
-
103
- if err != nil {
104
- return "", err
105
- }
106
-
107
- return result.(string), nil
108
- }
109
-
110
- // GetOrConvertWebP returns the path to the cached WebP file.
111
- // It uses GetOrDownload first to ensure the original is present, then converts.
112
- func (c *DiskCache) GetOrConvertWebP(ctx context.Context, messageID int, fetcher func() (io.ReadCloser, error)) (string, error) {
113
- webpFilename := strconv.Itoa(messageID) + "_webp"
114
- webpPath := filepath.Join(c.dir, webpFilename)
115
-
116
- if c.fileExists(webpPath) {
117
- return webpPath, nil
118
- }
119
-
120
- result, err, _ := c.sf.Do(webpFilename, func() (interface{}, error) {
121
- if c.fileExists(webpPath) {
122
- return webpPath, nil
123
- }
124
-
125
- // First, get the original file
126
- origPath, err := c.GetOrDownload(ctx, messageID, fetcher)
127
- if err != nil {
128
- return nil, err
129
- }
130
-
131
- c.log.Sugar().Infof("Starting WebP conversion for: %s", webpFilename)
132
-
133
- tempPath := webpPath + ".tmp"
134
-
135
- err = webpbin.NewCWebP().
136
- Quality(uint(config.ValueOf.WebPQuality)).
137
- InputFile(origPath).
138
- OutputFile(tempPath).
139
- Run()
140
-
141
- if err != nil {
142
- return nil, fmt.Errorf("failed to encode webp: %w", err)
143
- }
144
-
145
- if err := os.Rename(tempPath, webpPath); err != nil {
146
- os.Remove(tempPath)
147
- return nil, err
148
- }
149
-
150
- c.log.Sugar().Infof("WebP cached file saved: %s", webpFilename)
151
- return webpPath, nil
152
- })
153
-
154
- if err != nil {
155
- return "", err
156
- }
157
-
158
- return result.(string), nil
159
- }
160
-
161
- func (c *DiskCache) fileExists(path string) bool {
162
- info, err := os.Stat(path)
163
- if err == nil && !info.IsDir() {
164
- return true
165
- }
166
- return false
167
- }
168
-
169
- func (c *DiskCache) startSweeper() {
170
- ticker := time.NewTicker(time.Hour)
171
- defer ticker.Stop()
172
-
173
- for range ticker.C {
174
- c.log.Info("Running cache cleanup sweeper")
175
- threshold := time.Now().Add(-24 * time.Hour)
176
-
177
- entries, err := os.ReadDir(c.dir)
178
- if err != nil {
179
- c.log.Error("Failed to read cache dir for sweep", zap.Error(err))
180
- continue
181
- }
182
-
183
- count := 0
184
- for _, e := range entries {
185
- if e.IsDir() {
186
- continue
187
- }
188
- path := filepath.Join(c.dir, e.Name())
189
- info, err := e.Info()
190
- if err != nil {
191
- continue
192
- }
193
-
194
- if info.ModTime().Before(threshold) {
195
- os.Remove(path)
196
- count++
197
- }
198
- }
199
-
200
- if count > 0 {
201
- c.log.Sugar().Infof("Cleared %d old files from disk cache", count)
202
- }
203
- }
204
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
internal/commands/add_token.go DELETED
@@ -1,109 +0,0 @@
1
- package commands
2
-
3
- import (
4
- "fmt"
5
- "regexp"
6
- "strings"
7
-
8
- "github.com/celestix/gotgproto/dispatcher"
9
- "github.com/celestix/gotgproto/dispatcher/handlers"
10
- "github.com/celestix/gotgproto/ext"
11
- "go.uber.org/zap"
12
- )
13
-
14
- var (
15
- isAddTokenMode = false
16
- botTokenRegex = regexp.MustCompile(`^\d{9,10}:[A-Za-z0-9_-]{35}$`) // Standard Telegram bot token format
17
- )
18
-
19
- func (c *command) AddTokenOn(d dispatcher.Dispatcher) {
20
- d.AddHandler(handlers.NewCommand("add_token_on", func(ctx *ext.Context, u *ext.Update) error {
21
- isAddTokenMode = true
22
- c.log.Sugar().Info("Add token mode activated")
23
- _, err := ctx.Reply(u, ext.ReplyTextString("✅ Modo para añadir tokens activado. Envía tokens de bot (uno por mensaje) y los guardaré en la base de datos de Firebase."), nil)
24
- return err
25
- }))
26
- }
27
-
28
- func (c *command) AddTokenOff(d dispatcher.Dispatcher) {
29
- d.AddHandler(handlers.NewCommand("add_token_off", func(ctx *ext.Context, u *ext.Update) error {
30
- isAddTokenMode = false
31
- c.log.Sugar().Info("Add token mode deactivated")
32
- _, err := ctx.Reply(u, ext.ReplyTextString("❌ Modo para añadir tokens desactivado."), nil)
33
- return err
34
- }))
35
- }
36
-
37
- func (c *command) ListTokens(d dispatcher.Dispatcher) {
38
- d.AddHandler(handlers.NewCommand("list", func(ctx *ext.Context, u *ext.Update) error {
39
- if GetWorkerListFunc == nil {
40
- _, err := ctx.Reply(u, ext.ReplyTextString("❌ El sistema de lista de tokens no está conectado."), nil)
41
- return err
42
- }
43
- listText := GetWorkerListFunc(true)
44
- _, err := ctx.Reply(u, ext.ReplyTextString(listText), nil)
45
- return err
46
- }))
47
- }
48
-
49
- func (c *command) HandleBotTokenMessage(d dispatcher.Dispatcher) {
50
- d.AddHandlerToGroup(
51
- handlers.NewMessage(nil, func(ctx *ext.Context, u *ext.Update) error {
52
- if !isAddTokenMode {
53
- return nil
54
- }
55
-
56
- if u.EffectiveMessage == nil {
57
- return nil
58
- }
59
-
60
- messageText := u.EffectiveMessage.Message.Message
61
- if messageText == "" {
62
- return nil
63
- }
64
-
65
- // Validate if message looks like a token
66
- token := strings.TrimSpace(messageText)
67
- if !botTokenRegex.MatchString(token) {
68
- // Not a token, ignore
69
- return nil
70
- }
71
-
72
- c.log.Sugar().Infof("Received a new bot token: %s", token)
73
-
74
- if SaveTokenFunc == nil || StartWorkerFunc == nil {
75
- _, err := ctx.Reply(u, ext.ReplyTextString("❌ El sistema de tokens dinámicos no está listo."), nil)
76
- return err
77
- }
78
-
79
- // 1. Save it to Firebase
80
- err := SaveTokenFunc(token)
81
- if err != nil {
82
- if strings.Contains(err.Error(), "ya existe") {
83
- _, _ = ctx.Reply(u, ext.ReplyTextString("⚠️ Este token ya está registrado en Firebase."), nil)
84
- } else {
85
- c.log.Error("Failed to save token to firebase", zap.Error(err))
86
- _, _ = ctx.Reply(u, ext.ReplyTextString("❌ Error al guardar el token en Firebase: "+err.Error()), nil)
87
- }
88
- return nil
89
- }
90
-
91
- // Respond immediately to stop the webhook from retrying and causing duplicates
92
- _, _ = ctx.Reply(u, ext.ReplyTextString("⏳ El token ha sido guardado exitosamente en Firebase. Conectando al Servidor de Telegram..."), nil)
93
-
94
- // 2. Add it to the dynamic worker pool in the background
95
- go func(t string) {
96
- username, startErr := StartWorkerFunc(t)
97
- if startErr != nil {
98
- c.log.Error("Failed to start worker with new token", zap.Error(startErr))
99
- _, _ = ctx.Reply(u, ext.ReplyTextString("⚠️ El bot se guardó, pero falló al unirse (¿Token inválido?): "+startErr.Error()), nil)
100
- } else {
101
- successText := fmt.Sprintf("@%s\n`%s`\n\nse agrego correctamente al fire base", username, t)
102
- _, _ = ctx.Reply(u, ext.ReplyTextString(successText), nil)
103
- }
104
- }(token)
105
-
106
- return nil
107
-
108
- }), -1) // Group -1 para que atrape los mensajes ANTES que el handler de streams del Group 0
109
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
internal/commands/commands.go DELETED
@@ -1,91 +0,0 @@
1
- package commands
2
-
3
- import (
4
- "EverythingSuckz/fsb/config"
5
- "encoding/json"
6
- "fmt"
7
- "io"
8
- "net/http"
9
- "reflect"
10
-
11
- "github.com/celestix/gotgproto/dispatcher"
12
- "go.uber.org/zap"
13
- )
14
-
15
- var (
16
- SaveTokenFunc func(string) error
17
- StartWorkerFunc func(token string) (string, error)
18
- LoadTokensFunc func() ([]string, error)
19
- GetWorkerListFunc func(bool) string
20
- )
21
-
22
- type command struct {
23
- log *zap.Logger
24
- }
25
-
26
- func Load(log *zap.Logger, dispatcher dispatcher.Dispatcher) {
27
- log = log.Named("commands")
28
- defer log.Info("Initialized all command handlers")
29
- Type := reflect.TypeOf(&command{log})
30
- Value := reflect.ValueOf(&command{log})
31
- for i := 0; i < Type.NumMethod(); i++ {
32
- Type.Method(i).Func.Call([]reflect.Value{Value, reflect.ValueOf(dispatcher)})
33
- }
34
- }
35
-
36
- func RegisterCommands() error {
37
- type botCommand struct {
38
- Command string `json:"command"`
39
- Description string `json:"description"`
40
- }
41
-
42
- commands := []botCommand{
43
- {
44
- Command: "start",
45
- Description: "⚙️ Menú Principal",
46
- },
47
- {
48
- Command: "mangaflow_on",
49
- Description: "✅ Activar MangaFlow",
50
- },
51
- {
52
- Command: "mangaflow_off",
53
- Description: "❌ Desactivar MangaFlow",
54
- },
55
- {
56
- Command: "file_id_stream_on",
57
- Description: "✅ Activar File Stream",
58
- },
59
- {
60
- Command: "file_id_stream_off",
61
- Description: "❌ Desactivar File Stream",
62
- },
63
- {
64
- Command: "add_token_on",
65
- Description: "📝 Añadir Token Extra",
66
- },
67
- {
68
- Command: "add_token_off",
69
- Description: "❌ Desactivar Añadir Token",
70
- },
71
- {
72
- Command: "list",
73
- Description: "📋 Lista de Tokens Dinámicos",
74
- },
75
- }
76
-
77
- cmdBytes, _ := json.Marshal(commands)
78
- url := fmt.Sprintf("https://api.telegram.org/bot%s/setMyCommands?commands=%s", config.ValueOf.BotToken, string(cmdBytes))
79
-
80
- resp, err := http.Get(url)
81
- if err != nil {
82
- return err
83
- }
84
- defer resp.Body.Close()
85
-
86
- if resp.StatusCode != http.StatusOK {
87
- body, _ := io.ReadAll(resp.Body)
88
- return fmt.Errorf("failed to set commands: %s", string(body))
89
- }
90
- return nil
91
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
internal/commands/file_stream.go DELETED
@@ -1,294 +0,0 @@
1
- package commands
2
-
3
- import (
4
- "bufio"
5
- "bytes"
6
- "fmt"
7
- "sort"
8
- "strconv"
9
- "strings"
10
- "sync"
11
- "time"
12
-
13
- "EverythingSuckz/fsb/config"
14
- "EverythingSuckz/fsb/internal/utils"
15
-
16
- "github.com/celestix/gotgproto/dispatcher"
17
- "github.com/celestix/gotgproto/ext"
18
- "github.com/gotd/td/telegram/downloader"
19
- "github.com/gotd/td/tg"
20
- "go.uber.org/zap"
21
- )
22
-
23
- type FileStreamSession struct {
24
- Active bool
25
- mu sync.Mutex
26
- }
27
-
28
- var (
29
- fileStreamSessions = make(map[int64]*FileStreamSession)
30
- fileStreamMu sync.Mutex
31
- )
32
-
33
- func ToggleFileStream(ctx *ext.Context, u *ext.Update) error {
34
- chatId := u.EffectiveChat().GetID()
35
- messageText := u.EffectiveMessage.Message.Message
36
- args := strings.Split(messageText, " ")
37
- cmd := strings.ToLower(args[0])
38
-
39
- var state string
40
- if strings.Contains(cmd, "on") {
41
- state = "on"
42
- } else if strings.Contains(cmd, "off") {
43
- state = "off"
44
- }
45
-
46
- if state == "" {
47
- _, _ = ctx.Reply(u, ext.ReplyTextString("Uso: /file_id_stream_on o /file_id_stream_off"), nil)
48
- return dispatcher.EndGroups
49
- }
50
-
51
- fileStreamMu.Lock()
52
- session, ok := fileStreamSessions[chatId]
53
- if !ok {
54
- session = &FileStreamSession{Active: false}
55
- fileStreamSessions[chatId] = session
56
- }
57
- fileStreamMu.Unlock()
58
-
59
- session.mu.Lock()
60
- defer session.mu.Unlock()
61
-
62
- if state == "on" {
63
- if session.Active {
64
- _, _ = ctx.Reply(u, ext.ReplyTextString("File Stream ya está activado."), nil)
65
- return dispatcher.EndGroups
66
- }
67
- session.Active = true
68
- _, _ = ctx.Reply(u, ext.ReplyTextString("✅ File Stream activado. Envía tu archivo .txt con File IDs."), nil)
69
- return dispatcher.EndGroups
70
- } else if state == "off" {
71
- if !session.Active {
72
- _, _ = ctx.Reply(u, ext.ReplyTextString("File Stream ya está desactivado."), nil)
73
- return dispatcher.EndGroups
74
- }
75
- session.Active = false
76
- _, _ = ctx.Reply(u, ext.ReplyTextString("❌ File Stream desactivado."), nil)
77
- return dispatcher.EndGroups
78
- }
79
-
80
- return dispatcher.EndGroups
81
- }
82
-
83
- func GetFileStreamSession(chatId int64) *FileStreamSession {
84
- fileStreamMu.Lock()
85
- defer fileStreamMu.Unlock()
86
- return fileStreamSessions[chatId]
87
- }
88
-
89
- type ParsedFileItem struct {
90
- Type string // "ORIGINAL" or "WEBP"
91
- Name string
92
- MessageID int
93
- HFLink string
94
- LocalLink string
95
- }
96
-
97
- func HandleFileStreamFile(chatId int64, ctx *ext.Context, u *ext.Update, fileMedia interface{}) error {
98
- fileDoc, err := utils.FileFromMedia(fileMedia.(tg.MessageMediaClass))
99
- if err != nil {
100
- _, _ = ctx.Reply(u, ext.ReplyTextString(fmt.Sprintf("Error obteniendo media de telegram: %v", err)), nil)
101
- return err
102
- }
103
-
104
- // Download the .txt file
105
- d := downloader.NewDownloader()
106
- var docBuf bytes.Buffer
107
- _, err = d.Download(ctx.Raw, fileDoc.Location).Stream(ctx.Context, &docBuf)
108
- if err != nil {
109
- _, _ = ctx.Reply(u, ext.ReplyTextString(fmt.Sprintf("Error descargando el archivo: %v", err)), nil)
110
- return err
111
- }
112
-
113
- fileBytes := docBuf.Bytes()
114
-
115
- // Parse the .txt content
116
- scanner := bufio.NewScanner(bytes.NewReader(fileBytes))
117
- var title string = "FileStream_Collection"
118
- var currentItem *ParsedFileItem
119
- var items []ParsedFileItem
120
-
121
- for scanner.Scan() {
122
- line := strings.TrimSpace(scanner.Text())
123
- if line == "" || strings.HasPrefix(line, "--") {
124
- continue
125
- }
126
-
127
- if strings.HasPrefix(line, "=== Datos del ZIP: ") {
128
- titleRaw := strings.TrimPrefix(line, "=== Datos del ZIP: ")
129
- titleRaw = strings.TrimSuffix(titleRaw, " ===")
130
- title = strings.TrimSuffix(titleRaw, ".zip")
131
- title = strings.TrimSpace(title)
132
- continue
133
- }
134
-
135
- if strings.HasPrefix(line, "[ORIGINAL]") {
136
- if currentItem != nil && currentItem.MessageID != 0 {
137
- items = append(items, *currentItem)
138
- }
139
- currentItem = &ParsedFileItem{
140
- Type: "ORIGINAL",
141
- Name: strings.TrimSpace(strings.TrimPrefix(line, "[ORIGINAL]")),
142
- }
143
- continue
144
- }
145
-
146
- if strings.HasPrefix(line, "[WEBP]") {
147
- if currentItem != nil && currentItem.MessageID != 0 {
148
- items = append(items, *currentItem)
149
- }
150
- currentItem = &ParsedFileItem{
151
- Type: "WEBP",
152
- Name: strings.TrimSpace(strings.TrimPrefix(line, "[WEBP]")),
153
- }
154
- continue
155
- }
156
-
157
- if strings.HasPrefix(line, "Message ID (Canal):") {
158
- if currentItem != nil {
159
- idStr := strings.TrimSpace(strings.TrimPrefix(line, "Message ID (Canal):"))
160
- id, err := strconv.Atoi(idStr)
161
- if err == nil {
162
- currentItem.MessageID = id
163
- }
164
- }
165
- continue
166
- }
167
- }
168
- if currentItem != nil && currentItem.MessageID != 0 {
169
- items = append(items, *currentItem)
170
- }
171
-
172
- if len(items) == 0 {
173
- _, _ = ctx.Reply(u, ext.ReplyTextString("No se encontraron elementos válidos (Message ID) en el txt."), nil)
174
- return nil
175
- }
176
-
177
- // Send processing message
178
- loadingMsg, err := ctx.Reply(u, ext.ReplyTextString(fmt.Sprintf("Procesando %d archivos... Por favor espera.", len(items))), nil)
179
-
180
- channel, err := utils.GetLogChannelPeer(ctx.Context, ctx.Raw, ctx.PeerStorage)
181
- if err != nil {
182
- _, _ = ctx.Reply(u, ext.ReplyTextString(fmt.Sprintf("Error obteniendo el canal de log: %v", err)), nil)
183
- return err
184
- }
185
-
186
- for i := range items {
187
- // Add small delay to avoid hitting FloodWait limit too fast
188
- time.Sleep(200 * time.Millisecond)
189
-
190
- inputMessageID := tg.InputMessageClass(&tg.InputMessageID{ID: items[i].MessageID})
191
- messageRequest := tg.ChannelsGetMessagesRequest{Channel: channel, ID: []tg.InputMessageClass{inputMessageID}}
192
- res, err := ctx.Raw.ChannelsGetMessages(ctx.Context, &messageRequest)
193
- if err != nil {
194
- utils.Logger.Error("Failed to fetch message", zap.Error(err))
195
- continue
196
- }
197
- messages, ok := res.(*tg.MessagesChannelMessages)
198
- if !ok || len(messages.Messages) == 0 {
199
- utils.Logger.Error("Message not found or bad response")
200
- continue
201
- }
202
- message, ok := messages.Messages[0].(*tg.Message)
203
- if !ok {
204
- utils.Logger.Error("Message cast failed")
205
- continue
206
- }
207
-
208
- fileInfo, err := utils.FileFromMedia(message.Media)
209
- if err != nil {
210
- utils.Logger.Error("Failed to parse file media", zap.Error(err))
211
- continue
212
- }
213
- if err != nil {
214
- utils.Logger.Error("Failed to fetch message details for stream generation", zap.Int("messageId", items[i].MessageID), zap.Error(err))
215
- continue
216
- }
217
- fullHash := utils.PackFile(
218
- fileInfo.FileName,
219
- fileInfo.FileSize,
220
- fileInfo.MimeType,
221
- fileInfo.ID,
222
- )
223
- hash := utils.GetShortHash(fullHash)
224
-
225
- items[i].LocalLink = fmt.Sprintf("http://127.0.0.1:%d/stream/%d?hash=%s", config.ValueOf.Port, items[i].MessageID, hash)
226
- items[i].HFLink = fmt.Sprintf("https://codebydante-brodyfilestreambot.hf.space/stream/%d?hash=%s", items[i].MessageID, hash)
227
- }
228
-
229
- // Generate Text Content Output
230
- var webpItems []ParsedFileItem
231
- var originalItems []ParsedFileItem
232
-
233
- // Sort by name if desired, keeping original logic if preferred. User wants alphabetical "ordenando alfabeticamente" -> Yes we can do that!
234
- for _, it := range items {
235
- if it.LocalLink == "" {
236
- continue // skip failed ones
237
- }
238
- if it.Type == "WEBP" {
239
- webpItems = append(webpItems, it)
240
- } else {
241
- originalItems = append(originalItems, it)
242
- }
243
- }
244
-
245
- sort.Slice(webpItems, func(i, j int) bool {
246
- return webpItems[i].Name < webpItems[j].Name
247
- })
248
- sort.Slice(originalItems, func(i, j int) bool {
249
- return originalItems[i].Name < originalItems[j].Name
250
- })
251
-
252
- var buf bytes.Buffer
253
- buf.WriteString(fmt.Sprintf("==== %s ====\n\n", title))
254
-
255
- if len(webpItems) > 0 {
256
- buf.WriteString("---- WEB P LINKS ----\n\n")
257
- buf.WriteString("🚀 Para Hugging Face (Público):\n")
258
- for i, f := range webpItems {
259
- buf.WriteString(fmt.Sprintf("(%d) %s = %s\n", i+1, f.Name, f.HFLink))
260
- }
261
- buf.WriteString("\n🖥 Para tu PC Local (Pruebas):\n")
262
- for i, f := range webpItems {
263
- buf.WriteString(fmt.Sprintf("(%d) %s = %s\n", i+1, f.Name, f.LocalLink))
264
- }
265
- buf.WriteString("\n----------------------------------\n\n")
266
- }
267
-
268
- if len(originalItems) > 0 {
269
- buf.WriteString("---- ORIGINAL LINKS ----\n\n")
270
- buf.WriteString("🚀 Para Hugging Face (Público):\n")
271
- for i, f := range originalItems {
272
- buf.WriteString(fmt.Sprintf("(%d) %s = %s\n", i+1, f.Name, f.HFLink))
273
- }
274
- buf.WriteString("\n🖥 Para tu PC Local (Pruebas):\n")
275
- for i, f := range originalItems {
276
- buf.WriteString(fmt.Sprintf("(%d) %s = %s\n", i+1, f.Name, f.LocalLink))
277
- }
278
- }
279
- buf.WriteString("\n")
280
-
281
- // Save and send back text
282
- filename := title + ".txt"
283
- if err := utils.UploadToTG(ctx, chatId, buf.Bytes(), filename); err != nil {
284
- utils.Logger.Error("Failed to upload fileStream txt", zap.Error(err))
285
- _, _ = ctx.Reply(u, ext.ReplyTextString(fmt.Sprintf("Error enviando el archivo generado: %v", err)), nil)
286
- }
287
-
288
- // Delete loading msg
289
- if loadingMsg != nil {
290
- ctx.DeleteMessages(chatId, []int{loadingMsg.ID})
291
- }
292
-
293
- return nil
294
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
internal/commands/mangaflow.go DELETED
@@ -1,231 +0,0 @@
1
- package commands
2
-
3
- import (
4
- "bytes"
5
- "fmt"
6
- "regexp"
7
- "sort"
8
- "strings"
9
- "sync"
10
- "time"
11
-
12
- "EverythingSuckz/fsb/internal/utils"
13
-
14
- "github.com/celestix/gotgproto/dispatcher"
15
- "github.com/celestix/gotgproto/ext"
16
- "go.uber.org/zap"
17
- )
18
-
19
- type MangaFile struct {
20
- OriginalName string
21
- IsWebP bool
22
- LocalLink string
23
- LocalDownload string
24
- HFLink string
25
- HFDownload string
26
- }
27
-
28
- type MangaSession struct {
29
- Active bool
30
- Timer *time.Timer
31
- Files []MangaFile
32
- Ctx *ext.Context
33
- Update *ext.Update
34
- mu sync.Mutex
35
- }
36
-
37
- var (
38
- mangaflowSessions = make(map[int64]*MangaSession)
39
- mangaflowMu sync.Mutex
40
- )
41
-
42
- func (m *command) LoadMangaFlow(dispatcher dispatcher.Dispatcher) {
43
- // Logic is now integrated into stream.go and start.go
44
- }
45
-
46
- func ToggleMangaFlow(ctx *ext.Context, u *ext.Update) error {
47
- chatId := u.EffectiveChat().GetID()
48
- messageText := u.EffectiveMessage.Message.Message
49
- args := strings.Split(messageText, " ")
50
- cmd := strings.ToLower(args[0])
51
-
52
- var state string
53
- if strings.Contains(cmd, "on") {
54
- state = "on"
55
- } else if strings.Contains(cmd, "off") {
56
- state = "off"
57
- } else if len(args) >= 2 {
58
- state = strings.ToLower(args[1])
59
- }
60
-
61
- if state == "" {
62
- _, _ = ctx.Reply(u, ext.ReplyTextString("Uso: /twistedbrodymangaflow on|off o usa los comandos rápidos del menú."), nil)
63
- return dispatcher.EndGroups
64
- }
65
-
66
- mangaflowMu.Lock()
67
- session, ok := mangaflowSessions[chatId]
68
- if !ok {
69
- session = &MangaSession{Active: false}
70
- mangaflowSessions[chatId] = session
71
- }
72
- mangaflowMu.Unlock()
73
-
74
- session.mu.Lock()
75
- defer session.mu.Unlock()
76
-
77
- if state == "on" {
78
- if session.Active {
79
- _, _ = ctx.Reply(u, ext.ReplyTextString("MangaFlow ya está activado."), nil)
80
- return dispatcher.EndGroups
81
- }
82
- session.Active = true
83
- _, _ = ctx.Reply(u, ext.ReplyTextString("✅ MangaFlow activado. Envía tus imágenes."), nil)
84
- return dispatcher.EndGroups
85
- } else if state == "off" {
86
- if !session.Active {
87
- _, _ = ctx.Reply(u, ext.ReplyTextString("MangaFlow ya está desactivado."), nil)
88
- return dispatcher.EndGroups
89
- }
90
- if session.Timer != nil {
91
- session.Timer.Stop()
92
- session.Timer = nil
93
- }
94
- // Process remaining files if any
95
- if len(session.Files) > 0 {
96
- go finishMangaSession(chatId, session)
97
- }
98
- session.Active = false
99
- _, _ = ctx.Reply(u, ext.ReplyTextString("❌ MangaFlow desactivado."), nil)
100
- return dispatcher.EndGroups
101
- }
102
-
103
- _, _ = ctx.Reply(u, ext.ReplyTextString("Uso: /twistedbrodymangaflow on|off"), nil)
104
- return dispatcher.EndGroups
105
- }
106
-
107
- func GetMangaSession(chatId int64) *MangaSession {
108
- mangaflowMu.Lock()
109
- defer mangaflowMu.Unlock()
110
- return mangaflowSessions[chatId]
111
- }
112
-
113
- func HandleMangaFlowFile(chatId int64, session *MangaSession, file MangaFile, ctx *ext.Context, u *ext.Update) {
114
- session.mu.Lock()
115
- defer session.mu.Unlock()
116
-
117
- session.Files = append(session.Files, file)
118
- session.Ctx = ctx
119
- session.Update = u
120
-
121
- if session.Timer != nil {
122
- session.Timer.Stop()
123
- }
124
-
125
- session.Timer = time.AfterFunc(2*time.Second, func() {
126
- finishMangaSession(chatId, session)
127
- })
128
- }
129
-
130
- func generateMangaText(files []MangaFile) string {
131
- // Sort files by OriginalName
132
- sort.Slice(files, func(i, j int) bool {
133
- return files[i].OriginalName < files[j].OriginalName
134
- })
135
-
136
- var webpFiles []MangaFile
137
- var originalFiles []MangaFile
138
-
139
- // Heuristic for title
140
- title := "MangaFlow_Collection"
141
- if len(files) > 0 {
142
- baseName := files[0].OriginalName
143
- re := regexp.MustCompile(`(?i)_pagina_\d+.*$`)
144
- cleaned := re.ReplaceAllString(baseName, "")
145
- if cleaned == "" {
146
- re2 := regexp.MustCompile(`(?i)\.(png|webp|jpg|jpeg)$`)
147
- cleaned = re2.ReplaceAllString(baseName, "")
148
- }
149
- if cleaned != "" {
150
- title = strings.TrimSuffix(cleaned, "_")
151
- title = strings.TrimSpace(title)
152
- }
153
- }
154
-
155
- for _, f := range files {
156
- if f.IsWebP {
157
- webpFiles = append(webpFiles, f)
158
- } else {
159
- originalFiles = append(originalFiles, f)
160
- }
161
- }
162
-
163
- var buf bytes.Buffer
164
- buf.WriteString(fmt.Sprintf("==== %s ====\n\n", title))
165
-
166
- if len(webpFiles) > 0 {
167
- buf.WriteString("---- WEB P LINKS ----\n\n")
168
- buf.WriteString("🚀 Para Hugging Face (Público):\n")
169
- for i, f := range webpFiles {
170
- buf.WriteString(fmt.Sprintf("(%d) %s = %s\n", i+1, f.OriginalName, f.HFLink))
171
- }
172
- buf.WriteString("\n🖥 Para tu PC Local (Pruebas):\n")
173
- for i, f := range webpFiles {
174
- buf.WriteString(fmt.Sprintf("(%d) %s = %s\n", i+1, f.OriginalName, f.LocalLink))
175
- }
176
- buf.WriteString("\n----------------------------------\n\n")
177
- }
178
-
179
- if len(originalFiles) > 0 {
180
- buf.WriteString("---- ORIGINAL LINKS ----\n\n")
181
- buf.WriteString("🚀 Para Hugging Face (Público):\n")
182
- for i, f := range originalFiles {
183
- buf.WriteString(fmt.Sprintf("(%d) %s = %s\n", i+1, f.OriginalName, f.HFLink))
184
- }
185
- buf.WriteString("\n🖥 Para tu PC Local (Pruebas):\n")
186
- for i, f := range originalFiles {
187
- buf.WriteString(fmt.Sprintf("(%d) %s = %s\n", i+1, f.OriginalName, f.LocalLink))
188
- }
189
- }
190
- buf.WriteString("\n")
191
-
192
- return buf.String()
193
- }
194
-
195
- func finishMangaSession(chatId int64, session *MangaSession) {
196
- session.mu.Lock()
197
- files := session.Files
198
- session.Files = nil
199
- session.Timer = nil
200
- ctx := session.Ctx
201
- u := session.Update
202
- session.mu.Unlock()
203
-
204
- if len(files) == 0 {
205
- return
206
- }
207
-
208
- textContent := generateMangaText(files)
209
-
210
- // Determine fileName
211
- fileName := "MangaFlow_Links.txt"
212
- if len(files) > 0 {
213
- baseName := files[0].OriginalName
214
- re := regexp.MustCompile(`(?i)_pagina_\d+.*$`)
215
- cleaned := re.ReplaceAllString(baseName, "")
216
- if cleaned == "" {
217
- re2 := regexp.MustCompile(`(?i)\.(png|webp|jpg|jpeg)$`)
218
- cleaned = re2.ReplaceAllString(baseName, "")
219
- }
220
- if cleaned != "" {
221
- fileName = fmt.Sprintf("%s.txt", strings.TrimSuffix(cleaned, "_"))
222
- }
223
- }
224
-
225
- // Send file back to user
226
- err := utils.UploadToTG(ctx, chatId, []byte(textContent), fileName)
227
- if err != nil {
228
- utils.Logger.Error("Failed to upload mangaflow txt", zap.Error(err))
229
- _, _ = ctx.Reply(u, ext.ReplyTextString(fmt.Sprintf("Error enviando el archivo: %v", err)), nil)
230
- }
231
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
internal/commands/start.go DELETED
@@ -1,41 +0,0 @@
1
- package commands
2
-
3
- import (
4
- "EverythingSuckz/fsb/config"
5
- "EverythingSuckz/fsb/internal/utils"
6
-
7
- "github.com/celestix/gotgproto/dispatcher"
8
- "github.com/celestix/gotgproto/dispatcher/handlers"
9
- "github.com/celestix/gotgproto/ext"
10
- "github.com/celestix/gotgproto/storage"
11
- )
12
-
13
- func (m *command) LoadStart(dispatcher dispatcher.Dispatcher) {
14
- log := m.log.Named("start")
15
- defer log.Sugar().Info("Loaded")
16
- dispatcher.AddHandler(handlers.NewCommand("start", start))
17
- dispatcher.AddHandler(handlers.NewCommand("twistedbrodymangaflow", ToggleMangaFlow))
18
- dispatcher.AddHandler(handlers.NewCommand("mangaflow_on", ToggleMangaFlow))
19
- dispatcher.AddHandler(handlers.NewCommand("mangaflow_off", ToggleMangaFlow))
20
- dispatcher.AddHandler(handlers.NewCommand("file_id_stream_on", ToggleFileStream))
21
- dispatcher.AddHandler(handlers.NewCommand("file_id_stream_off", ToggleFileStream))
22
- }
23
-
24
- func start(ctx *ext.Context, u *ext.Update) error {
25
- chatId := u.EffectiveChat().GetID()
26
- peerChatId := ctx.PeerStorage.GetPeerById(chatId)
27
- if peerChatId.Type != int(storage.TypeUser) {
28
- return dispatcher.EndGroups
29
- }
30
- if len(config.ValueOf.AllowedUsers) != 0 && !utils.Contains(config.ValueOf.AllowedUsers, chatId) {
31
- _, _ = ctx.Reply(u, ext.ReplyTextString("No tienes permiso para usar este bot."), nil)
32
- return dispatcher.EndGroups
33
- }
34
-
35
- _, _ = ctx.Reply(u, ext.ReplyTextString("Hola, envíame cualquier archivo para obtener un enlace directo a ese archivo."), nil)
36
- return dispatcher.EndGroups
37
- }
38
-
39
- func twistedbrodymangaflow(ctx *ext.Context, u *ext.Update) error {
40
- return ToggleMangaFlow(ctx, u)
41
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
internal/commands/stream.go DELETED
@@ -1,216 +0,0 @@
1
- package commands
2
-
3
- import (
4
- "fmt"
5
- "strings"
6
-
7
- "EverythingSuckz/fsb/config"
8
-
9
- "EverythingSuckz/fsb/internal/utils"
10
-
11
- "github.com/celestix/gotgproto/dispatcher"
12
- "github.com/celestix/gotgproto/dispatcher/handlers"
13
- "github.com/celestix/gotgproto/ext"
14
- "github.com/celestix/gotgproto/storage"
15
- "github.com/celestix/gotgproto/types"
16
- "github.com/gotd/td/tg"
17
- )
18
-
19
- func (m *command) LoadStream(dispatcher dispatcher.Dispatcher) {
20
- log := m.log.Named("start")
21
- defer log.Sugar().Info("Loaded")
22
- dispatcher.AddHandler(
23
- handlers.NewMessage(nil, sendLink),
24
- )
25
- }
26
-
27
- func supportedMediaFilter(m *types.Message) (bool, error) {
28
- if not := m.Media == nil; not {
29
- return false, dispatcher.EndGroups
30
- }
31
- switch media := m.Media.(type) {
32
- case *tg.MessageMediaDocument:
33
- if doc, ok := media.Document.AsNotEmpty(); ok {
34
- for _, attr := range doc.Attributes {
35
- if filename, ok := attr.(*tg.DocumentAttributeFilename); ok {
36
- if strings.HasSuffix(strings.ToLower(filename.FileName), ".txt") {
37
- return false, dispatcher.EndGroups
38
- }
39
- }
40
- }
41
- }
42
- return true, nil
43
- case *tg.MessageMediaPhoto:
44
- return true, nil
45
- case tg.MessageMediaClass:
46
- return false, dispatcher.EndGroups
47
- default:
48
- return false, nil
49
- }
50
- }
51
-
52
- func sendLink(ctx *ext.Context, u *ext.Update) error {
53
- chatId := u.EffectiveChat().GetID()
54
- peerChatId := ctx.PeerStorage.GetPeerById(chatId)
55
- if peerChatId.Type != int(storage.TypeUser) {
56
- return dispatcher.EndGroups
57
- }
58
- if len(config.ValueOf.AllowedUsers) != 0 && !utils.Contains(config.ValueOf.AllowedUsers, chatId) {
59
- ctx.Reply(u, ext.ReplyTextString("No tienes permiso para usar este bot."), nil)
60
- return dispatcher.EndGroups
61
- }
62
-
63
- // --- FileStream Interception ---
64
- if session := GetFileStreamSession(chatId); session != nil && session.Active {
65
- if u.EffectiveMessage.Media != nil {
66
- if docMedia, ok := u.EffectiveMessage.Media.(*tg.MessageMediaDocument); ok {
67
- if doc, ok := docMedia.Document.AsNotEmpty(); ok {
68
- for _, attr := range doc.Attributes {
69
- if filename, ok := attr.(*tg.DocumentAttributeFilename); ok {
70
- if strings.HasSuffix(strings.ToLower(filename.FileName), ".txt") {
71
- err := HandleFileStreamFile(chatId, ctx, u, u.EffectiveMessage.Media)
72
- if err != nil {
73
- utils.Logger.Sugar().Error(err)
74
- }
75
- return dispatcher.EndGroups
76
- }
77
- }
78
- }
79
- }
80
- }
81
- }
82
- }
83
- // -------------------------------
84
-
85
- supported, err := supportedMediaFilter(u.EffectiveMessage)
86
- if err != nil {
87
- return err
88
- }
89
- if !supported {
90
- ctx.Reply(u, ext.ReplyTextString("Lo siento, este tipo de archivo no es compatible."), nil)
91
- return dispatcher.EndGroups
92
- }
93
-
94
- update, err := utils.ForwardMessages(ctx, chatId, config.ValueOf.LogChannelID, u.EffectiveMessage.ID)
95
- if err != nil {
96
- utils.Logger.Sugar().Error(err)
97
- ctx.Reply(u, ext.ReplyTextString(fmt.Sprintf("Error - %s", err.Error())), nil)
98
- return dispatcher.EndGroups
99
- }
100
- if len(update.Updates) < 2 {
101
- ctx.Reply(u, ext.ReplyTextString("Error - estructura de actualización de Telegram inesperada"), nil)
102
- return dispatcher.EndGroups
103
- }
104
- msgIDUpdate, ok := update.Updates[0].(*tg.UpdateMessageID)
105
- if !ok {
106
- ctx.Reply(u, ext.ReplyTextString("Error - tipo de actualización inesperado"), nil)
107
- return dispatcher.EndGroups
108
- }
109
- messageID := msgIDUpdate.ID
110
- newMsg, ok := update.Updates[1].(*tg.UpdateNewChannelMessage)
111
- if !ok {
112
- ctx.Reply(u, ext.ReplyTextString("Error - mensaje de canal inesperado"), nil)
113
- return dispatcher.EndGroups
114
- }
115
- msg, ok := newMsg.Message.(*tg.Message)
116
- if !ok {
117
- ctx.Reply(u, ext.ReplyTextString("Error - tipo de mensaje inesperado"), nil)
118
- return dispatcher.EndGroups
119
- }
120
- doc := msg.Media
121
- file, err := utils.FileFromMedia(doc)
122
- if err != nil {
123
- ctx.Reply(u, ext.ReplyTextString(fmt.Sprintf("Error - %s", err.Error())), nil)
124
- return dispatcher.EndGroups
125
- }
126
- fullHash := utils.PackFile(
127
- file.FileName,
128
- file.FileSize,
129
- file.MimeType,
130
- file.ID,
131
- )
132
- hash := utils.GetShortHash(fullHash)
133
-
134
- localLink := fmt.Sprintf("http://127.0.0.1:%d/stream/%d?hash=%s", config.ValueOf.Port, messageID, hash)
135
- hfLink := fmt.Sprintf("https://codebydante-brodyfilestreambot.hf.space/stream/%d?hash=%s", messageID, hash)
136
-
137
- localDownloadText := localLink + "&d=true"
138
- hfDownloadText := hfLink + "&d=true"
139
-
140
- // --- MangaFlow Interception ---
141
- if session := GetMangaSession(chatId); session != nil && session.Active {
142
- mangaFile := MangaFile{
143
- OriginalName: file.FileName,
144
- IsWebP: strings.HasSuffix(strings.ToLower(file.FileName), ".webp"),
145
- LocalLink: localLink,
146
- LocalDownload: localDownloadText,
147
- HFLink: hfLink,
148
- HFDownload: hfDownloadText,
149
- }
150
- HandleMangaFlowFile(chatId, session, mangaFile, ctx, u)
151
- return dispatcher.EndGroups
152
- }
153
- // ------------------------------
154
-
155
- var textLines []string
156
- textLines = append(textLines, "🖥 Para tu PC Local (Pruebas):")
157
- textLines = append(textLines, "📁 Descargar:")
158
- textLines = append(textLines, localDownloadText)
159
- textLines = append(textLines, "📁 Reproducir / Ver:")
160
- textLines = append(textLines, localLink)
161
-
162
- textLines = append(textLines, "\n🚀 Para Hugging Face (Público):")
163
- textLines = append(textLines, "📁 Descargar:")
164
- textLines = append(textLines, hfDownloadText)
165
- textLines = append(textLines, "📁 Reproducir / Ver:")
166
- textLines = append(textLines, hfLink)
167
-
168
- textPlain := strings.Join(textLines, "\n")
169
-
170
- var rows []tg.KeyboardButtonRow
171
-
172
- // Fila Local
173
- localRow := tg.KeyboardButtonRow{
174
- Buttons: []tg.KeyboardButtonClass{
175
- &tg.KeyboardButtonURL{
176
- Text: "🖥 Descargar",
177
- URL: localDownloadText,
178
- },
179
- &tg.KeyboardButtonURL{
180
- Text: "🖥 Ver / Reproducir",
181
- URL: localLink,
182
- },
183
- },
184
- }
185
- rows = append(rows, localRow)
186
-
187
- // Fila Hugging Face
188
- hfRow := tg.KeyboardButtonRow{
189
- Buttons: []tg.KeyboardButtonClass{
190
- &tg.KeyboardButtonURL{
191
- Text: "🚀 Descargar",
192
- URL: hfDownloadText,
193
- },
194
- &tg.KeyboardButtonURL{
195
- Text: "🚀 Ver / Reproducir",
196
- URL: hfLink,
197
- },
198
- },
199
- }
200
- rows = append(rows, hfRow)
201
-
202
- markup := &tg.ReplyInlineMarkup{
203
- Rows: rows,
204
- }
205
-
206
- _, err = ctx.Reply(u, ext.ReplyTextString(textPlain), &ext.ReplyOpts{
207
- Markup: markup,
208
- NoWebpage: true,
209
- ReplyToMessageId: u.EffectiveMessage.ID,
210
- })
211
- if err != nil {
212
- utils.Logger.Sugar().Error(err)
213
- ctx.Reply(u, ext.ReplyTextString(fmt.Sprintf("Error - %s", err.Error())), nil)
214
- }
215
- return dispatcher.EndGroups
216
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
internal/routes/routes.go DELETED
@@ -1,33 +0,0 @@
1
- package routes
2
-
3
- import (
4
- "reflect"
5
-
6
- "github.com/gin-gonic/gin"
7
- "go.uber.org/zap"
8
- )
9
-
10
- type Route struct {
11
- Name string
12
- Engine *gin.Engine
13
- }
14
-
15
- func (r *Route) Init(engine *gin.Engine) {
16
- r.Engine = engine
17
- }
18
-
19
- type allRoutes struct {
20
- log *zap.Logger
21
- }
22
-
23
- func Load(log *zap.Logger, r *gin.Engine) {
24
- log = log.Named("routes")
25
- defer log.Sugar().Info("Loaded all API Routes")
26
- route := &Route{Name: "/", Engine: r}
27
- route.Init(r)
28
- Type := reflect.TypeOf(&allRoutes{log})
29
- Value := reflect.ValueOf(&allRoutes{log})
30
- for i := 0; i < Type.NumMethod(); i++ {
31
- Type.Method(i).Func.Call([]reflect.Value{Value, reflect.ValueOf(route)})
32
- }
33
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
internal/routes/stream.go DELETED
@@ -1,147 +0,0 @@
1
- package routes
2
-
3
- import (
4
- "EverythingSuckz/fsb/internal/bot"
5
- "EverythingSuckz/fsb/internal/stream"
6
- "EverythingSuckz/fsb/internal/types"
7
- "EverythingSuckz/fsb/internal/utils"
8
- "fmt"
9
- "io"
10
- "net/http"
11
- "strconv"
12
-
13
- "github.com/gotd/td/tg"
14
- range_parser "github.com/quantumsheep/range-parser"
15
- "go.uber.org/zap"
16
-
17
- "github.com/gin-gonic/gin"
18
- )
19
-
20
- var log *zap.Logger
21
-
22
- func (e *allRoutes) LoadHome(r *Route) {
23
- log = e.log.Named("Stream")
24
- defer log.Info("Loaded stream route")
25
- r.Engine.GET("/stream/:messageID", getStreamRoute)
26
- }
27
-
28
- func getStreamRoute(ctx *gin.Context) {
29
- w := ctx.Writer
30
- r := ctx.Request
31
-
32
- messageIDParm := ctx.Param("messageID")
33
- messageID, err := strconv.Atoi(messageIDParm)
34
- if err != nil {
35
- http.Error(w, err.Error(), http.StatusBadRequest)
36
- return
37
- }
38
-
39
- authHash := ctx.Query("hash")
40
- if authHash == "" {
41
- http.Error(w, "missing hash param", http.StatusBadRequest)
42
- return
43
- }
44
-
45
- worker := bot.GetNextWorker()
46
- log.Sugar().Infof("✅ Asignando petición de stream (MessageID: %d) al worker: @%s", messageID, worker.Self.Username)
47
-
48
- reqCtx := r.Context()
49
-
50
- file, err := utils.TimeFuncWithResult(log, "FileFromMessage", func() (*types.File, error) {
51
- // Pasa el contexto de la petición real para que si el cliente cierra la ventana, se aborte el fetch
52
- return utils.FileFromMessage(reqCtx, worker.Client, messageID)
53
- })
54
- if err != nil {
55
- http.Error(w, err.Error(), http.StatusBadRequest)
56
- return
57
- }
58
-
59
- expectedHash := utils.PackFile(
60
- file.FileName,
61
- file.FileSize,
62
- file.MimeType,
63
- file.ID,
64
- )
65
- if !utils.CheckHash(authHash, expectedHash) {
66
- http.Error(w, "invalid hash", http.StatusBadRequest)
67
- return
68
- }
69
-
70
- // for photo messages
71
- if file.FileSize == 0 {
72
- res, err := worker.Client.API().UploadGetFile(reqCtx, &tg.UploadGetFileRequest{
73
- Location: file.Location,
74
- Offset: 0,
75
- Limit: 1024 * 1024,
76
- })
77
- if err != nil {
78
- http.Error(w, err.Error(), http.StatusInternalServerError)
79
- return
80
- }
81
- result, ok := res.(*tg.UploadFile)
82
- if !ok {
83
- http.Error(w, "unexpected response", http.StatusInternalServerError)
84
- return
85
- }
86
- fileBytes := result.GetBytes()
87
- ctx.Header("Content-Disposition", fmt.Sprintf("inline; filename=\"%s\"", file.FileName))
88
- if r.Method != "HEAD" {
89
- ctx.Data(http.StatusOK, file.MimeType, fileBytes)
90
- }
91
- return
92
- }
93
-
94
- ctx.Header("Accept-Ranges", "bytes")
95
- var start, end int64
96
- rangeHeader := r.Header.Get("Range")
97
-
98
- if rangeHeader == "" {
99
- start = 0
100
- end = file.FileSize - 1
101
- w.WriteHeader(http.StatusOK)
102
- } else {
103
- ranges, err := range_parser.Parse(file.FileSize, r.Header.Get("Range"))
104
- if err != nil {
105
- http.Error(w, err.Error(), http.StatusBadRequest)
106
- return
107
- }
108
- start = ranges[0].Start
109
- end = ranges[0].End
110
- ctx.Header("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, file.FileSize))
111
- log.Info("Content-Range", zap.Int64("start", start), zap.Int64("end", end), zap.Int64("fileSize", file.FileSize))
112
- w.WriteHeader(http.StatusPartialContent)
113
- }
114
-
115
- contentLength := end - start + 1
116
- mimeType := file.MimeType
117
-
118
- if mimeType == "" {
119
- mimeType = "application/octet-stream"
120
- }
121
-
122
- ctx.Header("Content-Type", mimeType)
123
- ctx.Header("Content-Length", strconv.FormatInt(contentLength, 10))
124
-
125
- disposition := "inline"
126
-
127
- if ctx.Query("d") == "true" {
128
- disposition = "attachment"
129
- }
130
-
131
- ctx.Header("Content-Disposition", fmt.Sprintf("%s; filename=\"%s\"", disposition, file.FileName))
132
-
133
- if r.Method != "HEAD" {
134
- // Pasamos el reqCtx aquí para que corte la Tubería y las peticiones si el usuario se desconecta
135
- pipe, err := stream.NewStreamPipe(reqCtx, worker.Client, file.Location, start, end, log)
136
- if err != nil {
137
- log.Error("Failed to create stream pipe", zap.Error(err))
138
- return
139
- }
140
- defer pipe.Close()
141
- if _, err := io.CopyN(w, pipe, contentLength); err != nil {
142
- if !utils.IsClientDisconnectError(err) && err != stream.ErrPipeDrained {
143
- log.Error("Error while copying stream", zap.Error(err))
144
- }
145
- }
146
- }
147
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
internal/routes/upload.go DELETED
@@ -1,131 +0,0 @@
1
- package routes
2
-
3
- import (
4
- "bytes"
5
- "encoding/json"
6
- "fmt"
7
- "io"
8
- "mime/multipart"
9
- "net/http"
10
- "os"
11
-
12
- "EverythingSuckz/fsb/config"
13
- "EverythingSuckz/fsb/internal/bot"
14
- "EverythingSuckz/fsb/internal/utils"
15
-
16
- "github.com/gin-gonic/gin"
17
- "go.uber.org/zap"
18
- )
19
-
20
- type tgResponse struct {
21
- Ok bool `json:"ok"`
22
- Description string `json:"description"`
23
- ErrorCode int `json:"error_code"`
24
- Result struct {
25
- MessageID int `json:"message_id"`
26
- } `json:"result"`
27
- }
28
-
29
- func (e *allRoutes) LoadUpload(r *Route) {
30
- log = e.log.Named("Upload")
31
- r.Engine.POST("/upload", uploadStreamRoute)
32
- }
33
-
34
- func uploadStreamRoute(ctx *gin.Context) {
35
- file, header, err := ctx.Request.FormFile("file")
36
- if err != nil {
37
- ctx.JSON(http.StatusBadRequest, gin.H{"success": false, "error": "Falta el archivo en el campo 'file'"})
38
- return
39
- }
40
- defer file.Close()
41
-
42
- log.Sugar().Infof("Archivo recibido para subir: %s (Tamaño: %d)", header.Filename, header.Size)
43
-
44
- body := &bytes.Buffer{}
45
- writer := multipart.NewWriter(body)
46
-
47
- logChannel := os.Getenv("LOG_CHANNEL")
48
- if logChannel == "" {
49
- logChannel = fmt.Sprintf("-100%d", config.ValueOf.LogChannelID)
50
- }
51
-
52
- err = writer.WriteField("chat_id", logChannel)
53
- if err != nil {
54
- ctx.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "Error interno"})
55
- return
56
- }
57
-
58
- part, err := writer.CreateFormFile("document", header.Filename)
59
- if err != nil {
60
- ctx.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "Error interno creando documento"})
61
- return
62
- }
63
-
64
- _, err = io.Copy(part, file)
65
- if err != nil {
66
- ctx.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "Error leyendo archivo"})
67
- return
68
- }
69
- writer.Close()
70
-
71
- url := fmt.Sprintf("https://api.telegram.org/bot%s/sendDocument", config.ValueOf.BotToken)
72
- req, err := http.NewRequest("POST", url, body)
73
- if err != nil {
74
- ctx.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "Error preparando petici\u00f3n a Telegram"})
75
- return
76
- }
77
- req.Header.Set("Content-Type", writer.FormDataContentType())
78
-
79
- client := &http.Client{}
80
- resp, err := client.Do(req)
81
- if err != nil {
82
- log.Error("Error enviando a Telegram", zap.Error(err))
83
- ctx.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "Error enviando a Telegram"})
84
- return
85
- }
86
- defer resp.Body.Close()
87
-
88
- bodyBytes, _ := io.ReadAll(resp.Body)
89
- var tgRes tgResponse
90
- if err := json.Unmarshal(bodyBytes, &tgRes); err != nil {
91
- log.Error("Error decoding Telegram response", zap.Error(err), zap.String("body", string(bodyBytes)))
92
- ctx.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "Error decodificando respuesta de Telegram"})
93
- return
94
- }
95
-
96
- if !tgRes.Ok || tgRes.Result.MessageID == 0 {
97
- log.Error("Telegram rejected the file or upload failed", zap.Any("response", tgRes))
98
- errorMsg := fmt.Sprintf("Telegram rechazó el archivo: %s (Code: %d)", tgRes.Description, tgRes.ErrorCode)
99
- ctx.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": errorMsg})
100
- return
101
- }
102
-
103
- messageID := tgRes.Result.MessageID
104
- worker := bot.GetNextWorker()
105
-
106
- tgFile, err := utils.FileFromMessage(ctx.Request.Context(), worker.Client, messageID)
107
- if err != nil {
108
- log.Error("Failed to get file properties", zap.Error(err))
109
- ctx.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "Error obteniendo propiedades de Telegram. " + err.Error()})
110
- return
111
- }
112
-
113
- expectedHash := utils.PackFile(
114
- tgFile.FileName,
115
- tgFile.FileSize,
116
- tgFile.MimeType,
117
- tgFile.ID,
118
- )
119
- hash := utils.GetShortHash(expectedHash)
120
-
121
- localLink := fmt.Sprintf("http://127.0.0.1:%d/stream/%d?hash=%s", config.ValueOf.Port, messageID, hash)
122
- hfLink := fmt.Sprintf("https://codebydante-brodyfilestreambot.hf.space/stream/%d?hash=%s", messageID, hash)
123
-
124
- ctx.JSON(http.StatusOK, gin.H{
125
- "success": true,
126
- "message_id": messageID,
127
- "hash": hash,
128
- "url": hfLink,
129
- "local_url": localLink,
130
- })
131
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
internal/stream/errors.go DELETED
@@ -1,17 +0,0 @@
1
- package stream
2
-
3
- import "errors"
4
-
5
- var (
6
- // the client disconnected before the stream completed.
7
- ErrStreamClosed = errors.New("stream closed by client")
8
-
9
- // a block fetch exceeded the timeout.
10
- ErrBlockTimeout = errors.New("block fetch timed out")
11
-
12
- // all retry attempts failed.
13
- ErrMaxRetriesExceeded = errors.New("max retries exceeded")
14
-
15
- // the pipe was closed and all data was consumed.
16
- ErrPipeDrained = errors.New("pipe drained")
17
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
internal/stream/pipe.go DELETED
@@ -1,340 +0,0 @@
1
- package stream
2
-
3
- import (
4
- "EverythingSuckz/fsb/config"
5
- "EverythingSuckz/fsb/internal/utils"
6
- "context"
7
- "fmt"
8
- "io"
9
- "strings"
10
- "sync"
11
- "time"
12
-
13
- "github.com/celestix/gotgproto"
14
- "github.com/gotd/td/tg"
15
- "github.com/gotd/td/tgerr"
16
- "go.uber.org/zap"
17
- )
18
-
19
- func calculateBlockSize(start, end int64) int64 {
20
- size := end - start + 1
21
-
22
- switch {
23
- case size < 512*1024: // < 512KB
24
- return 64 * 1024 // 64KB blocks
25
- case size < 1024*1024: // < 1MB
26
- return 256 * 1024 // 256KB blocks
27
- default:
28
- // Para imágenes pesadas (>1MB), pedimos pedazos de 1MB a la vez.
29
- // Telegram rate-limitea por cantidad de peticiones concurrentes, no tanto por Mbps.
30
- // Al pedir 1MB en vez de 512KB, cortamos a la mitad la cantidad de peticiones a la API.
31
- return 1024 * 1024 // 1MB blocks by default
32
- }
33
- }
34
-
35
- // StreamPipe reads data from Telegram with concurrent prefetching. implements `io.ReadCloser`.
36
- // credits: [teldrive](https://github.com/tgdrive/teldrive/blob/1071a6e8b5a4076cacc5a0989ef245fae517d837/internal/reader/tg_reader.go)
37
- type StreamPipe struct {
38
- ctx context.Context
39
- cancel context.CancelFunc
40
- log *zap.Logger
41
-
42
- // tg connection
43
- client *gotgproto.Client
44
- location tg.InputFileLocationClass
45
-
46
- // range stuff
47
- start int64
48
- end int64
49
- blockSize int64
50
- totalBytes int64
51
-
52
- // prefetch pipeline
53
- blockQueue chan []byte
54
-
55
- // current read state
56
- currentBlock []byte
57
- blockOffset int64
58
- bytesRead int64
59
-
60
- // lifecycle
61
- closeOnce sync.Once
62
- }
63
-
64
- // class function which creates a StreamPipe with default configuration.
65
- func NewStreamPipe(
66
- ctx context.Context,
67
- client *gotgproto.Client,
68
- location tg.InputFileLocationClass,
69
- start, end int64,
70
- log *zap.Logger,
71
- ) (io.ReadCloser, error) {
72
-
73
- if start > end {
74
- return nil, fmt.Errorf("invalid range: start (%d) > end (%d)", start, end)
75
- }
76
-
77
- ctx, cancel := context.WithCancel(ctx)
78
-
79
- totalBytes := end - start + 1
80
- blockSize := calculateBlockSize(start, end)
81
-
82
- p := &StreamPipe{
83
- ctx: ctx,
84
- cancel: cancel,
85
- log: log.Named("StreamPipe"),
86
- client: client,
87
- location: location,
88
- start: start,
89
- end: end,
90
- blockSize: blockSize,
91
- totalBytes: totalBytes,
92
- blockQueue: make(chan []byte, config.ValueOf.StreamBufferCount),
93
- }
94
-
95
- // start prefetching in background
96
- go p.prefetch()
97
-
98
- return p, nil
99
- }
100
-
101
- // Read implements io.Reader
102
- func (p *StreamPipe) Read(buf []byte) (n int, err error) {
103
- if p.bytesRead >= p.totalBytes {
104
- p.log.Sugar().Debug("EOF (bytesread == contentLength)")
105
- return 0, io.EOF
106
- }
107
-
108
- // need a new block?
109
- if p.blockOffset >= int64(len(p.currentBlock)) {
110
- select {
111
- case block, ok := <-p.blockQueue:
112
- if !ok {
113
- if p.bytesRead >= p.totalBytes {
114
- return 0, io.EOF
115
- }
116
- return 0, ErrPipeDrained
117
- }
118
- p.currentBlock = block
119
- p.blockOffset = 0
120
- case <-p.ctx.Done():
121
- return 0, p.ctx.Err()
122
- }
123
- }
124
-
125
- // copy available data
126
- n = copy(buf, p.currentBlock[p.blockOffset:])
127
- p.blockOffset += int64(n)
128
- p.bytesRead += int64(n)
129
-
130
- return n, nil
131
- }
132
-
133
- // Close implements io.Closer.
134
- // it cancels prefetching and releases resources.
135
- func (p *StreamPipe) Close() error {
136
- p.closeOnce.Do(func() {
137
- p.cancel()
138
- })
139
- return nil
140
- }
141
-
142
- // prefetch runs in a goroutine, fetching blocks concurrently and sending to blockQueue.
143
- func (p *StreamPipe) prefetch() {
144
- defer close(p.blockQueue)
145
-
146
- // calc block boundaries
147
- alignedStart := p.start - (p.start % p.blockSize)
148
- leftTrim := p.start - alignedStart
149
- rightTrim := (p.end % p.blockSize) + 1
150
- totalBlocks := int((p.end - alignedStart + p.blockSize) / p.blockSize)
151
-
152
- currentBlock := 0
153
- offset := alignedStart
154
-
155
- for currentBlock < totalBlocks {
156
- // check for cancellation
157
- select {
158
- case <-p.ctx.Done():
159
- return
160
- default:
161
- }
162
-
163
- // fetch a batch of blocks concurrently
164
- batchSize := min(config.ValueOf.StreamConcurrency, totalBlocks-currentBlock)
165
- blocks := make([][]byte, batchSize)
166
-
167
- var wg sync.WaitGroup
168
- var fetchErr error
169
- var errMu sync.Mutex
170
-
171
- for i := range batchSize {
172
- wg.Add(1)
173
- go func(idx int) {
174
- defer wg.Done()
175
-
176
- blockNum := currentBlock + idx
177
- blockOffset := offset + int64(idx)*p.blockSize
178
-
179
- data, err := p.downloadBlockWithRetry(blockOffset)
180
- dataLen := int64(len(data))
181
-
182
- if err != nil {
183
- errMu.Lock()
184
- if fetchErr == nil {
185
- fetchErr = err
186
- }
187
- errMu.Unlock()
188
- return
189
- }
190
-
191
- // trim first/last block to exact range
192
- if totalBlocks == 1 {
193
- if dataLen < rightTrim {
194
- rightTrim = dataLen
195
- }
196
- if leftTrim > dataLen {
197
- leftTrim = dataLen
198
- }
199
- data = data[leftTrim:rightTrim]
200
- } else if blockNum == 0 {
201
- if leftTrim > dataLen {
202
- leftTrim = dataLen
203
- }
204
- data = data[leftTrim:]
205
- } else if blockNum == totalBlocks-1 {
206
- if dataLen > rightTrim {
207
- data = data[:rightTrim]
208
- }
209
- }
210
-
211
- blocks[idx] = data
212
- }(i)
213
- }
214
-
215
- wg.Wait()
216
-
217
- // handle errors
218
- // ignore context cancellation cuz it's expected on disconnect
219
- if fetchErr != nil {
220
- if p.ctx.Err() == nil {
221
- p.log.Error("block download failed", zap.Error(fetchErr))
222
- }
223
- return
224
- }
225
-
226
- // send blocks to queue in order
227
- for _, block := range blocks {
228
- if block == nil {
229
- // a fetch failure that wasn't captured, should not happen but just in case.
230
- p.log.Error("unexpected nil block in batch, aborting prefetch")
231
- return
232
- }
233
- select {
234
- case p.blockQueue <- block:
235
- case <-p.ctx.Done():
236
- return
237
- }
238
- }
239
-
240
- currentBlock += batchSize
241
- offset += p.blockSize * int64(batchSize)
242
- }
243
- }
244
-
245
- // downloadBlockWithRetry fetches a block with exponential backoff retry.
246
- // it also handles FLOOD_WAIT errors specifically by waiting for the required time.
247
- func (p *StreamPipe) downloadBlockWithRetry(offset int64) ([]byte, error) {
248
- var lastErr error
249
-
250
- // TODO: make configurable later
251
- backoff := 150 * time.Millisecond // initial backoff = 150ms
252
- const maxBackoff = 30 * time.Second // max backoff = 30s
253
-
254
- for attempt := 0; attempt < config.ValueOf.StreamMaxRetries; attempt++ {
255
- // check context before each attempt
256
- if p.ctx.Err() != nil {
257
- return nil, p.ctx.Err()
258
- }
259
-
260
- ctx, cancel := context.WithTimeout(p.ctx, time.Duration(config.ValueOf.StreamTimeoutSec)*time.Second)
261
- data, err := utils.TimeFuncWithResult(p.log, "downloadBlock", func() ([]byte, error) {
262
- return p.downloadBlock(ctx, offset)
263
- })
264
- cancel()
265
-
266
- if err == nil {
267
- return data, nil
268
- }
269
-
270
- lastErr = err
271
-
272
- // don't retry on context cancellation
273
- if p.ctx.Err() != nil {
274
- return nil, p.ctx.Err()
275
- }
276
-
277
- // handle FLOOD_WAIT specifically
278
- if waitSec, ok := tgerr.AsFloodWait(err); ok {
279
- p.log.Sugar().Warnf("FLOOD_WAIT detected: waiting for %v before retrying block at %d", waitSec, offset)
280
- select {
281
- case <-time.After(waitSec + 1*time.Second): // add a tiny buffer
282
- // reset backoff since we handled this specifically
283
- backoff = 150 * time.Millisecond
284
- // do not count FLOOD_WAIT against max retries
285
- attempt--
286
- continue
287
- case <-p.ctx.Done():
288
- return nil, p.ctx.Err()
289
- }
290
- }
291
-
292
- // general error handling with exponential backoff
293
- p.log.Sugar().Warnf("Retrying block download at %d (attempt %d/%d) due to error: %v", offset, attempt+1, config.ValueOf.StreamMaxRetries, err)
294
-
295
- // if it's a connection drop/engine closed, gotd takes a sec to reconnect.
296
- // make sure we don't blow through retries too fast.
297
- if strings.Contains(err.Error(), "engine forcibly closed") && backoff < 2*time.Second {
298
- backoff = 2 * time.Second
299
- }
300
-
301
- // exponential backoff
302
- select {
303
- case <-time.After(backoff):
304
- backoff *= 2
305
- // making sure backoff doesn't grow indefinitely in case of persistent failures
306
- if backoff > maxBackoff {
307
- backoff = maxBackoff
308
- }
309
- case <-p.ctx.Done():
310
- return nil, p.ctx.Err()
311
- }
312
- }
313
-
314
- return nil, fmt.Errorf("%w: %v", ErrMaxRetriesExceeded, lastErr)
315
- }
316
-
317
- // downloadBlock fetches a single block from Telegram.
318
- func (p *StreamPipe) downloadBlock(ctx context.Context, offset int64) ([]byte, error) {
319
- p.log.Sugar().Debugf("Downloading block at offset %d (block size: %d)", offset, p.blockSize)
320
- res, err := p.client.API().UploadGetFile(ctx, &tg.UploadGetFileRequest{
321
- Offset: offset,
322
- Limit: int(p.blockSize),
323
- Location: p.location,
324
- })
325
-
326
- if err != nil {
327
- return nil, err
328
- }
329
-
330
- switch result := res.(type) {
331
- case *tg.UploadFile:
332
- return result.Bytes, nil
333
- case *tg.UploadFileCDNRedirect:
334
- // handle CDN redirect if needed (not implemented here, but could be added)
335
- // https://core.telegram.org/cdn
336
- return nil, fmt.Errorf("CDN redirect not supported in this implementation (redirect to DC %d)", result.DCID)
337
- default:
338
- return nil, fmt.Errorf("unexpected response type: %T", res)
339
- }
340
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
internal/types/file.go DELETED
@@ -1,44 +0,0 @@
1
- package types
2
-
3
- import (
4
- "crypto/md5"
5
- "encoding/hex"
6
- "reflect"
7
- "strconv"
8
-
9
- "github.com/gotd/td/tg"
10
- )
11
-
12
- type File struct {
13
- Location tg.InputFileLocationClass
14
- FileSize int64
15
- FileName string
16
- MimeType string
17
- ID int64
18
- }
19
-
20
- type HashableFileStruct struct {
21
- FileName string
22
- FileSize int64
23
- MimeType string
24
- FileID int64
25
- }
26
-
27
- func (f *HashableFileStruct) Pack() string {
28
- hasher := md5.New()
29
- val := reflect.ValueOf(*f)
30
- for i := 0; i < val.NumField(); i++ {
31
- field := val.Field(i)
32
-
33
- var fieldValue []byte
34
- switch field.Kind() {
35
- case reflect.String:
36
- fieldValue = []byte(field.String())
37
- case reflect.Int64:
38
- fieldValue = []byte(strconv.FormatInt(field.Int(), 10))
39
- }
40
-
41
- hasher.Write(fieldValue)
42
- }
43
- return hex.EncodeToString(hasher.Sum(nil))
44
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
internal/types/response.go DELETED
@@ -1,8 +0,0 @@
1
- package types
2
-
3
- type RootResponse struct {
4
- Message string `json:"message"`
5
- Ok bool `json:"ok"`
6
- Uptime string `json:"uptime"`
7
- Version string `json:"version"`
8
- }
 
 
 
 
 
 
 
 
 
internal/utils/hashing.go DELETED
@@ -1,18 +0,0 @@
1
- package utils
2
-
3
- import (
4
- "EverythingSuckz/fsb/config"
5
- "EverythingSuckz/fsb/internal/types"
6
- )
7
-
8
- func PackFile(fileName string, fileSize int64, mimeType string, fileID int64) string {
9
- return (&types.HashableFileStruct{FileName: fileName, FileSize: fileSize, MimeType: mimeType, FileID: fileID}).Pack()
10
- }
11
-
12
- func GetShortHash(fullHash string) string {
13
- return fullHash[:config.ValueOf.HashLength]
14
- }
15
-
16
- func CheckHash(inputHash string, expectedHash string) bool {
17
- return inputHash == GetShortHash(expectedHash)
18
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
internal/utils/helpers.go DELETED
@@ -1,226 +0,0 @@
1
- package utils
2
-
3
- import (
4
- "EverythingSuckz/fsb/config"
5
- "EverythingSuckz/fsb/internal/cache"
6
- "EverythingSuckz/fsb/internal/types"
7
- "context"
8
- "errors"
9
- "fmt"
10
- "math/rand"
11
- "strings"
12
-
13
- "github.com/celestix/gotgproto"
14
- "github.com/celestix/gotgproto/ext"
15
- "github.com/celestix/gotgproto/storage"
16
- "github.com/gotd/td/telegram/uploader"
17
- "github.com/gotd/td/tg"
18
- "go.uber.org/zap"
19
- )
20
-
21
- // https://stackoverflow.com/a/70802740/15807350
22
- func Contains[T comparable](s []T, e T) bool {
23
- for _, v := range s {
24
- if v == e {
25
- return true
26
- }
27
- }
28
- return false
29
- }
30
-
31
- // IsClientDisconnectError checks if the error is due to client disconnecting
32
- // e.g. user seeking in video, stopping playback, or network issues on client side
33
- func IsClientDisconnectError(err error) bool {
34
- if err == nil {
35
- return false
36
- }
37
- errStr := err.Error()
38
- return strings.Contains(errStr, "connection was aborted") ||
39
- strings.Contains(errStr, "connection reset by peer") ||
40
- strings.Contains(errStr, "broken pipe") ||
41
- strings.Contains(errStr, "forcibly closed")
42
- }
43
-
44
- // telegram helper functions
45
- // TODO: move these to a separate package if they grow too large
46
-
47
- func GetTGMessage(ctx context.Context, client *gotgproto.Client, messageID int) (*tg.Message, error) {
48
- inputMessageID := tg.InputMessageClass(&tg.InputMessageID{ID: messageID})
49
- channel, err := GetLogChannelPeer(ctx, client.API(), client.PeerStorage)
50
- if err != nil {
51
- return nil, err
52
- }
53
- messageRequest := tg.ChannelsGetMessagesRequest{Channel: channel, ID: []tg.InputMessageClass{inputMessageID}}
54
- res, err := client.API().ChannelsGetMessages(ctx, &messageRequest)
55
- if err != nil {
56
- return nil, err
57
- }
58
- messages := res.(*tg.MessagesChannelMessages)
59
- message := messages.Messages[0]
60
- if _, ok := message.(*tg.Message); ok {
61
- return message.(*tg.Message), nil
62
- } else {
63
- return nil, fmt.Errorf("this file was deleted")
64
- }
65
- }
66
-
67
- func FileFromMedia(media tg.MessageMediaClass) (*types.File, error) {
68
- switch media := media.(type) {
69
- case *tg.MessageMediaDocument:
70
- document, ok := media.Document.AsNotEmpty()
71
- if !ok {
72
- return nil, fmt.Errorf("unexpected type %T", media)
73
- }
74
- var fileName string
75
- for _, attribute := range document.Attributes {
76
- if name, ok := attribute.(*tg.DocumentAttributeFilename); ok {
77
- fileName = name.FileName
78
- break
79
- }
80
- }
81
- return &types.File{
82
- Location: document.AsInputDocumentFileLocation(),
83
- FileSize: document.Size,
84
- FileName: fileName,
85
- MimeType: document.MimeType,
86
- ID: document.ID,
87
- }, nil
88
- case *tg.MessageMediaPhoto:
89
- photo, ok := media.Photo.AsNotEmpty()
90
- if !ok {
91
- return nil, fmt.Errorf("unexpected type %T", media)
92
- }
93
- sizes := photo.Sizes
94
- if len(sizes) == 0 {
95
- return nil, errors.New("photo has no sizes")
96
- }
97
- photoSize := sizes[len(sizes)-1]
98
- size, ok := photoSize.AsNotEmpty()
99
- if !ok {
100
- return nil, errors.New("photo size is empty")
101
- }
102
- location := new(tg.InputPhotoFileLocation)
103
- location.ID = photo.GetID()
104
- location.AccessHash = photo.GetAccessHash()
105
- location.FileReference = photo.GetFileReference()
106
- location.ThumbSize = size.GetType()
107
- return &types.File{
108
- Location: location,
109
- FileSize: 0, // caller should judge if this is a photo or not
110
- FileName: fmt.Sprintf("photo_%d.jpg", photo.GetID()),
111
- MimeType: "image/jpeg",
112
- ID: photo.GetID(),
113
- }, nil
114
- }
115
- return nil, fmt.Errorf("unexpected type %T", media)
116
- }
117
-
118
- func FileFromMessage(ctx context.Context, client *gotgproto.Client, messageID int) (*types.File, error) {
119
- key := fmt.Sprintf("file:%d:%d", messageID, client.Self.ID)
120
- log := Logger.Named("GetMessageMedia")
121
- var cachedMedia types.File
122
- err := cache.GetCache().Get(key, &cachedMedia)
123
- if err == nil {
124
- log.Debug("Using cached media message properties", zap.Int("messageID", messageID), zap.Int64("clientID", client.Self.ID))
125
- return &cachedMedia, nil
126
- }
127
- log.Debug("Fetching file properties from message ID", zap.Int("messageID", messageID), zap.Int64("clientID", client.Self.ID))
128
- message, err := GetTGMessage(ctx, client, messageID)
129
- if err != nil {
130
- return nil, err
131
- }
132
- file, err := FileFromMedia(message.Media)
133
- if err != nil {
134
- return nil, err
135
- }
136
- err = cache.GetCache().Set(
137
- key,
138
- file,
139
- 3600,
140
- )
141
- if err != nil {
142
- return nil, err
143
- }
144
- return file, nil
145
- }
146
-
147
- func GetLogChannelPeer(ctx context.Context, api *tg.Client, peerStorage *storage.PeerStorage) (*tg.InputChannel, error) {
148
- cachedInputPeer := peerStorage.GetInputPeerById(config.ValueOf.LogChannelID)
149
-
150
- switch peer := cachedInputPeer.(type) {
151
- case *tg.InputPeerEmpty:
152
- break
153
- case *tg.InputPeerChannel:
154
- return &tg.InputChannel{
155
- ChannelID: peer.ChannelID,
156
- AccessHash: peer.AccessHash,
157
- }, nil
158
- default:
159
- return nil, errors.New("unexpected type of input peer")
160
- }
161
- inputChannel := &tg.InputChannel{
162
- ChannelID: config.ValueOf.LogChannelID,
163
- }
164
- channels, err := api.ChannelsGetChannels(ctx, []tg.InputChannelClass{inputChannel})
165
- if err != nil {
166
- return nil, err
167
- }
168
- if len(channels.GetChats()) == 0 {
169
- return nil, errors.New("no channels found")
170
- }
171
- channel, ok := channels.GetChats()[0].(*tg.Channel)
172
- if !ok {
173
- return nil, errors.New("type assertion to *tg.Channel failed")
174
- }
175
- // Bruh, I literally have to call library internal functions at this point
176
- peerStorage.AddPeer(channel.GetID(), channel.AccessHash, storage.TypeChannel, "")
177
- return channel.AsInput(), nil
178
- }
179
-
180
- func ForwardMessages(ctx *ext.Context, fromChatId, toChatId int64, messageID int) (*tg.Updates, error) {
181
- fromPeer := ctx.PeerStorage.GetInputPeerById(fromChatId)
182
- if fromPeer.Zero() {
183
- return nil, fmt.Errorf("fromChatId: %d is not a valid peer", fromChatId)
184
- }
185
- toPeer, err := GetLogChannelPeer(ctx, ctx.Raw, ctx.PeerStorage)
186
- if err != nil {
187
- return nil, err
188
- }
189
- update, err := ctx.Raw.MessagesForwardMessages(ctx, &tg.MessagesForwardMessagesRequest{
190
- RandomID: []int64{rand.Int63()},
191
- FromPeer: fromPeer,
192
- ID: []int{messageID},
193
- ToPeer: &tg.InputPeerChannel{ChannelID: toPeer.ChannelID, AccessHash: toPeer.AccessHash},
194
- })
195
- if err != nil {
196
- return nil, err
197
- }
198
- return update.(*tg.Updates), nil
199
- }
200
-
201
- // UploadToTG uploads a file to Telegram using MTProto directly and returns error if any.
202
- func UploadToTG(ctx *ext.Context, chatID int64, fileData []byte, fileName string) error {
203
- u := uploader.NewUploader(ctx.Raw)
204
- // uploader.FromBytes handles the chunking and uploading logic via MTProto
205
- file, err := u.FromBytes(ctx.Context, fileName, fileData)
206
- if err != nil {
207
- return fmt.Errorf("failed to upload via MTProto: %v", err)
208
- }
209
-
210
- media := &tg.InputMediaUploadedDocument{
211
- File: file,
212
- MimeType: "text/plain",
213
- Attributes: []tg.DocumentAttributeClass{
214
- &tg.DocumentAttributeFilename{FileName: fileName},
215
- },
216
- }
217
-
218
- _, err = ctx.SendMedia(chatID, &tg.MessagesSendMediaRequest{
219
- Media: media,
220
- })
221
- if err != nil {
222
- return fmt.Errorf("failed to send media via MTProto: %v", err)
223
- }
224
-
225
- return nil
226
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
internal/utils/logger.go DELETED
@@ -1,52 +0,0 @@
1
- package utils
2
-
3
- import (
4
- "os"
5
- "time"
6
-
7
- "go.uber.org/zap"
8
- "go.uber.org/zap/zapcore"
9
- "gopkg.in/natefinch/lumberjack.v2"
10
- )
11
-
12
- var Logger *zap.Logger
13
-
14
- func InitLogger(debugMode bool) {
15
- customTimeEncoder := func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
16
- layout := "02/01/2006 03:04:05 PM"
17
- if debugMode {
18
- layout = "02/01/2006 03:04:05.000 PM"
19
- }
20
- enc.AppendString(t.Format(layout))
21
- }
22
- consoleConfig := zap.NewDevelopmentEncoderConfig()
23
- consoleConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
24
- consoleConfig.EncodeTime = customTimeEncoder
25
- consoleEncoder := zapcore.NewConsoleEncoder(consoleConfig)
26
-
27
- fileEncoderConfig := zap.NewProductionEncoderConfig()
28
- fileEncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
29
- fileEncoder := zapcore.NewJSONEncoder(fileEncoderConfig)
30
-
31
- fileWriter := zapcore.AddSync(&lumberjack.Logger{
32
- Filename: "logs/app.log",
33
- MaxSize: 10,
34
- MaxBackups: 3,
35
- MaxAge: 7,
36
- Compress: true,
37
- })
38
-
39
- var consoleLevel zapcore.Level
40
- if debugMode {
41
- consoleLevel = zapcore.DebugLevel
42
- } else {
43
- consoleLevel = zapcore.InfoLevel
44
- }
45
-
46
- core := zapcore.NewTee(
47
- zapcore.NewCore(consoleEncoder, zapcore.AddSync(os.Stdout), consoleLevel),
48
- zapcore.NewCore(fileEncoder, fileWriter, zapcore.DebugLevel),
49
- )
50
-
51
- Logger = zap.New(core, zap.AddStacktrace(zapcore.FatalLevel))
52
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
internal/utils/time_format.go DELETED
@@ -1,42 +0,0 @@
1
- package utils
2
-
3
- import (
4
- "fmt"
5
- "math/bits"
6
- )
7
-
8
- func TimeFormat(seconds uint64) (timeStr string) {
9
- hours, remainder := bits.Div64(0, seconds, 3600)
10
- minutes, seconds := bits.Div64(0, remainder, 60)
11
- days, hours := bits.Div64(0, hours, 24)
12
- timeStr = ""
13
- if days > 0 {
14
- if days == 1 {
15
- timeStr += fmt.Sprintf("%d day, ", days)
16
- } else {
17
- timeStr += fmt.Sprintf("%d days, ", days)
18
- }
19
- }
20
- if hours > 0 {
21
- if hours == 1 {
22
- timeStr += fmt.Sprintf("%d hour, ", hours)
23
- } else {
24
- timeStr += fmt.Sprintf("%d hours, ", hours)
25
- }
26
- }
27
- if minutes > 0 {
28
- if minutes == 1 {
29
- timeStr += fmt.Sprintf("%d minute, ", minutes)
30
- } else {
31
- timeStr += fmt.Sprintf("%d minutes, ", minutes)
32
- }
33
- }
34
- if seconds > 0 {
35
- if seconds == 1 {
36
- timeStr += fmt.Sprintf("%d second", seconds)
37
- } else {
38
- timeStr += fmt.Sprintf("%d seconds", seconds)
39
- }
40
- }
41
- return timeStr
42
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
internal/utils/timing.go DELETED
@@ -1,17 +0,0 @@
1
- package utils
2
-
3
- import (
4
- "time"
5
-
6
- "go.uber.org/zap"
7
- )
8
-
9
- // TimeFuncWithResult wraps a function call and logs its execution time, returning a result
10
- func TimeFuncWithResult[T any](log *zap.Logger, funcName string, fn func() (T, error)) (T, error) {
11
- start := time.Now()
12
- defer func() {
13
- duration := time.Since(start).Milliseconds()
14
- log.Debug(funcName+" executed", zap.Int64("duration_ms", duration))
15
- }()
16
- return fn()
17
- }