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

Upload 114 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. bin/fsb.exe +3 -0
  2. cmd/fsb/main.go +37 -0
  3. cmd/fsb/run.go +87 -0
  4. cmd/fsb/session.go +41 -0
  5. config/config.go +306 -0
  6. fsb.sample.env +60 -0
  7. fsb.session +0 -0
  8. go.mod +137 -0
  9. go.sum +372 -0
  10. goreleaser.Dockerfile +5 -0
  11. internal/bot/client.go +58 -0
  12. internal/bot/middleware.go +20 -0
  13. internal/bot/userbot.go +119 -0
  14. internal/bot/workers.go +334 -0
  15. internal/cache/cache.go +68 -0
  16. internal/commands/add_token.go +109 -0
  17. internal/commands/commands.go +91 -0
  18. internal/commands/file_stream.go +294 -0
  19. internal/commands/mangaflow.go +231 -0
  20. internal/commands/start.go +41 -0
  21. internal/commands/stream.go +216 -0
  22. internal/routes/routes.go +33 -0
  23. internal/routes/stream.go +147 -0
  24. internal/routes/upload.go +131 -0
  25. internal/stream/errors.go +17 -0
  26. internal/stream/pipe.go +340 -0
  27. internal/types/file.go +44 -0
  28. internal/types/response.go +8 -0
  29. internal/utils/hashing.go +18 -0
  30. internal/utils/helpers.go +226 -0
  31. internal/utils/logger.go +52 -0
  32. internal/utils/time_format.go +42 -0
  33. internal/utils/timing.go +17 -0
  34. logs/app.log +0 -0
  35. pkg/qrlogin/encoder.go +52 -0
  36. pkg/qrlogin/qrcode.go +152 -0
  37. sessions/worker-8351384724.session +0 -0
  38. sessions/worker-8494492850.session +0 -0
  39. sessions/worker-8610183721.session +0 -0
  40. sessions/worker-8672752909.session +0 -0
  41. sessions/worker-8688814148.session +0 -0
  42. sessions/worker-8707468210.session +0 -0
  43. sessions/worker-8710408202.session +0 -0
  44. sessions/worker-8721328807.session +0 -0
  45. sessions/worker-8735857251.session +0 -0
  46. sessions/worker-8739944102.session +0 -0
  47. test-clone/.gitattributes +3 -0
  48. test-clone/.github/workflows/notify.yml +27 -0
  49. test-clone/.github/workflows/release.yml +59 -0
  50. test-clone/.gitignore +33 -0
bin/fsb.exe ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9fd941606508a5ccc4d6ac6a862fc81c90172972e9dcaf736108e48ab47bc352
3
+ size 70734848
cmd/fsb/main.go ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import (
4
+ "EverythingSuckz/fsb/config"
5
+ "fmt"
6
+ "os"
7
+
8
+ "github.com/spf13/cobra"
9
+ )
10
+
11
+ const versionString = "3.2.0"
12
+
13
+ var rootCmd = &cobra.Command{
14
+ Use: "fsb [command]",
15
+ Short: "Telegram File Stream Bot",
16
+ Long: "Telegram Bot to generate direct streamable links for telegram media.",
17
+ Example: "fsb run --port 8080",
18
+ Version: versionString,
19
+ CompletionOptions: cobra.CompletionOptions{DisableDefaultCmd: true},
20
+ Run: func(cmd *cobra.Command, args []string) {
21
+ cmd.Help()
22
+ },
23
+ }
24
+
25
+ func init() {
26
+ config.SetFlagsFromConfig(runCmd)
27
+ rootCmd.AddCommand(runCmd)
28
+ rootCmd.AddCommand(sessionCmd)
29
+ rootCmd.SetVersionTemplate(fmt.Sprintf(`Telegram File Stream Bot version %s`, versionString))
30
+ }
31
+
32
+ func main() {
33
+ if err := rootCmd.Execute(); err != nil {
34
+ fmt.Println(err)
35
+ os.Exit(1)
36
+ }
37
+ }
cmd/fsb/run.go ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import (
4
+ "EverythingSuckz/fsb/config"
5
+ "EverythingSuckz/fsb/internal/bot"
6
+ "EverythingSuckz/fsb/internal/cache"
7
+ "EverythingSuckz/fsb/internal/commands"
8
+ "EverythingSuckz/fsb/internal/routes"
9
+ "EverythingSuckz/fsb/internal/types"
10
+ "EverythingSuckz/fsb/internal/utils"
11
+ "fmt"
12
+ "net/http"
13
+ "time"
14
+
15
+ "github.com/spf13/cobra"
16
+
17
+ "github.com/gin-gonic/gin"
18
+ "go.uber.org/zap"
19
+ )
20
+
21
+ var runCmd = &cobra.Command{
22
+ Use: "run",
23
+ Short: "Run the bot with the given configuration.",
24
+ DisableSuggestions: false,
25
+ Run: runApp,
26
+ }
27
+
28
+ var startTime time.Time = time.Now()
29
+
30
+ func runApp(cmd *cobra.Command, args []string) {
31
+ // initialize logger early so config loading is logged to file
32
+ utils.InitLogger(false)
33
+ config.Load(utils.Logger, cmd)
34
+ // reinitialize with correct dev mode
35
+ utils.InitLogger(config.ValueOf.Dev)
36
+ log := utils.Logger
37
+ mainLogger := log.Named("Main")
38
+ mainLogger.Info("Starting server")
39
+ router := getRouter(log)
40
+
41
+ mainBot, err := bot.StartClient(log)
42
+ if err != nil {
43
+ log.Sugar().Fatalf("Failed to start main bot: %v", err)
44
+ }
45
+ cache.InitCache(log)
46
+ workers, err := bot.StartWorkers(log)
47
+ if err != nil {
48
+ log.Sugar().Fatalf("Failed to start workers: %v", err)
49
+ }
50
+
51
+ commands.SaveTokenFunc = workers.SaveTokenToFirebase
52
+ commands.StartWorkerFunc = workers.Add
53
+ commands.LoadTokensFunc = workers.LoadTokensFromFirebase
54
+ commands.GetWorkerListFunc = workers.GetWorkerListText
55
+
56
+ workers.AddDefaultClient(mainBot, mainBot.Self)
57
+ bot.StartUserBot(log)
58
+ fmt.Println("\n✅ Bot Conectado y Listo.")
59
+ fmt.Printf("🌍 Servidor Fantasma Aiohttp activo en puerto %d\n\n", config.ValueOf.Port)
60
+ mainLogger.Info("Server started", zap.Int("port", config.ValueOf.Port))
61
+ mainLogger.Info("File Stream Bot", zap.String("version", versionString))
62
+ mainLogger.Sugar().Infof("Server is running at %s", config.ValueOf.Host)
63
+ err = router.Run(fmt.Sprintf("0.0.0.0:%d", config.ValueOf.Port))
64
+ if err != nil {
65
+ mainLogger.Sugar().Fatalf("Server failed to start: %v", err)
66
+ }
67
+ }
68
+
69
+ func getRouter(log *zap.Logger) *gin.Engine {
70
+ if config.ValueOf.Dev {
71
+ gin.SetMode(gin.DebugMode)
72
+ } else {
73
+ gin.SetMode(gin.ReleaseMode)
74
+ }
75
+ router := gin.Default()
76
+ router.Use(gin.ErrorLogger())
77
+ router.GET("/", func(ctx *gin.Context) {
78
+ ctx.JSON(http.StatusOK, types.RootResponse{
79
+ Message: "Server is running.",
80
+ Ok: true,
81
+ Uptime: utils.TimeFormat(uint64(time.Since(startTime).Seconds())),
82
+ Version: versionString,
83
+ })
84
+ })
85
+ routes.Load(log, router)
86
+ return router
87
+ }
cmd/fsb/session.go ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import (
4
+ "fmt"
5
+
6
+ "EverythingSuckz/fsb/pkg/qrlogin"
7
+
8
+ "github.com/spf13/cobra"
9
+ )
10
+
11
+ var sessionCmd = &cobra.Command{
12
+ Use: "session",
13
+ Short: "Generate a string session.",
14
+ DisableSuggestions: false,
15
+ Run: generateSession,
16
+ }
17
+
18
+ func init() {
19
+ sessionCmd.Flags().StringP("login-type", "T", "qr", "The login type to use. Can be either 'qr' or 'phone'")
20
+ sessionCmd.Flags().Int32P("api-id", "I", 0, "The API ID to use for the session (required).")
21
+ sessionCmd.Flags().StringP("api-hash", "H", "", "The API hash to use for the session (required).")
22
+ sessionCmd.MarkFlagRequired("api-id")
23
+ sessionCmd.MarkFlagRequired("api-hash")
24
+ }
25
+
26
+ func generateSession(cmd *cobra.Command, args []string) {
27
+ loginType, _ := cmd.Flags().GetString("login-type")
28
+ apiId, _ := cmd.Flags().GetInt32("api-id")
29
+ apiHash, _ := cmd.Flags().GetString("api-hash")
30
+ if loginType == "qr" {
31
+ qrlogin.GenerateQRSession(int(apiId), apiHash)
32
+ } else if loginType == "phone" {
33
+ generatePhoneSession()
34
+ } else {
35
+ fmt.Println("Invalid login type. Please use either 'qr' or 'phone'")
36
+ }
37
+ }
38
+
39
+ func generatePhoneSession() {
40
+ fmt.Println("Phone session is not implemented yet.")
41
+ }
config/config.go ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package config
2
+
3
+ import (
4
+ "errors"
5
+ "io"
6
+ "net"
7
+ "net/http"
8
+ "os"
9
+ "path/filepath"
10
+ "reflect"
11
+ "regexp"
12
+ "strconv"
13
+ "strings"
14
+
15
+ "github.com/joho/godotenv"
16
+ "github.com/kelseyhightower/envconfig"
17
+ "github.com/spf13/cobra"
18
+ "go.uber.org/zap"
19
+ )
20
+
21
+ var ValueOf = &config{}
22
+
23
+ type allowedUsers []int64
24
+
25
+ func (au *allowedUsers) Decode(value string) error {
26
+ if value == "" {
27
+ return nil
28
+ }
29
+ ids := strings.Split(string(value), ",")
30
+ for _, id := range ids {
31
+ idInt, err := strconv.ParseInt(id, 10, 64)
32
+ if err != nil {
33
+ return err
34
+ }
35
+ *au = append(*au, idInt)
36
+ }
37
+ return nil
38
+ }
39
+
40
+ type config struct {
41
+ ApiID int32 `envconfig:"API_ID" required:"true"`
42
+ ApiHash string `envconfig:"API_HASH" required:"true"`
43
+ BotToken string `envconfig:"BOT_TOKEN" required:"true"`
44
+ LogChannelID int64 `envconfig:"LOG_CHANNEL" required:"true"`
45
+ Dev bool `envconfig:"DEV" default:"false"`
46
+ Port int `envconfig:"PORT" default:"8080"`
47
+ Host string `envconfig:"HOST" default:""`
48
+ HashLength int `envconfig:"HASH_LENGTH" default:"6"`
49
+ UseSessionFile bool `envconfig:"USE_SESSION_FILE" default:"true"`
50
+ UserSession string `envconfig:"USER_SESSION"`
51
+ UsePublicIP bool `envconfig:"USE_PUBLIC_IP" default:"false"`
52
+ AllowedUsers allowedUsers `envconfig:"ALLOWED_USERS"`
53
+ MultiTokens []string
54
+ FirebaseJSON string `envconfig:"FIREBASE_JSON"`
55
+
56
+ // stream specific config
57
+ StreamConcurrency int `envconfig:"STREAM_CONCURRENCY" default:"8"`
58
+ StreamBufferCount int `envconfig:"STREAM_BUFFER_COUNT" default:"16"`
59
+ StreamTimeoutSec int `envconfig:"STREAM_TIMEOUT_SEC" default:"30"`
60
+ StreamMaxRetries int `envconfig:"STREAM_MAX_RETRIES" default:"10"`
61
+ }
62
+
63
+ var botTokenRegex = regexp.MustCompile(`MULTI\_TOKEN\d+=(.*)`)
64
+
65
+ func (c *config) loadFromEnvFile(log *zap.Logger) {
66
+ envPath := filepath.Clean("fsb.env")
67
+ log.Sugar().Infof("Trying to load ENV vars from %s", envPath)
68
+ err := godotenv.Load(envPath)
69
+ if err != nil {
70
+ if os.IsNotExist(err) {
71
+ log.Sugar().Errorf("ENV file not found: %s", envPath)
72
+ log.Sugar().Info("Please create fsb.env file")
73
+ log.Sugar().Info("For more info, refer: https://github.com/EverythingSuckz/TG-FileStreamBot/tree/golang#setting-up-things")
74
+ log.Sugar().Info("Please ignore this message if you are hosting it in a service like Heroku or other alternatives.")
75
+ } else {
76
+ log.Fatal("Unknown error while parsing env file.", zap.Error(err))
77
+ }
78
+ }
79
+ }
80
+
81
+ func SetFlagsFromConfig(cmd *cobra.Command) {
82
+ cmd.Flags().Int32("api-id", ValueOf.ApiID, "Telegram API ID")
83
+ cmd.Flags().String("api-hash", ValueOf.ApiHash, "Telegram API Hash")
84
+ cmd.Flags().String("bot-token", ValueOf.BotToken, "Telegram Bot Token")
85
+ cmd.Flags().Int64("log-channel", ValueOf.LogChannelID, "Telegram Log Channel ID")
86
+ cmd.Flags().Bool("dev", ValueOf.Dev, "Enable development mode")
87
+ cmd.Flags().IntP("port", "p", ValueOf.Port, "Server port")
88
+ cmd.Flags().String("host", ValueOf.Host, "Server host that will be included in links")
89
+ cmd.Flags().Int("hash-length", ValueOf.HashLength, "Hash length in links")
90
+ cmd.Flags().Bool("use-session-file", ValueOf.UseSessionFile, "Use session files")
91
+ cmd.Flags().String("user-session", ValueOf.UserSession, "Pyrogram user session")
92
+ cmd.Flags().Bool("use-public-ip", ValueOf.UsePublicIP, "Use public IP instead of local IP")
93
+ cmd.Flags().String("multi-token-txt-file", "", "Multi token txt file (Not implemented)")
94
+ cmd.Flags().Int("stream-concurrency", ValueOf.StreamConcurrency, "Number of parallel block fetches")
95
+ cmd.Flags().Int("stream-buffer-count", ValueOf.StreamBufferCount, "Number of blocks to prefetch")
96
+ cmd.Flags().Int("stream-timeout-sec", ValueOf.StreamTimeoutSec, "Maximum time to wait for a single block (in seconds)")
97
+ cmd.Flags().Int("stream-max-retries", ValueOf.StreamMaxRetries, "Number of retry attempts for failed fetches")
98
+ }
99
+
100
+ func (c *config) loadConfigFromArgs(log *zap.Logger, cmd *cobra.Command) {
101
+ apiID, _ := cmd.Flags().GetInt32("api-id")
102
+ if apiID != 0 {
103
+ os.Setenv("API_ID", strconv.Itoa(int(apiID)))
104
+ }
105
+ apiHash, _ := cmd.Flags().GetString("api-hash")
106
+ if apiHash != "" {
107
+ os.Setenv("API_HASH", apiHash)
108
+ }
109
+ botToken, _ := cmd.Flags().GetString("bot-token")
110
+ if botToken != "" {
111
+ os.Setenv("BOT_TOKEN", botToken)
112
+ }
113
+ logChannelID, _ := cmd.Flags().GetString("log-channel")
114
+ if logChannelID != "" {
115
+ os.Setenv("LOG_CHANNEL", logChannelID)
116
+ }
117
+ dev, _ := cmd.Flags().GetBool("dev")
118
+ if dev {
119
+ os.Setenv("DEV", strconv.FormatBool(dev))
120
+ }
121
+ port, _ := cmd.Flags().GetInt("port")
122
+ if port != 0 {
123
+ os.Setenv("PORT", strconv.Itoa(port))
124
+ }
125
+ host, _ := cmd.Flags().GetString("host")
126
+ if host != "" {
127
+ os.Setenv("HOST", host)
128
+ }
129
+ hashLength, _ := cmd.Flags().GetInt("hash-length")
130
+ if hashLength != 0 {
131
+ os.Setenv("HASH_LENGTH", strconv.Itoa(hashLength))
132
+ }
133
+ useSessionFile, _ := cmd.Flags().GetBool("use-session-file")
134
+ if useSessionFile {
135
+ os.Setenv("USE_SESSION_FILE", strconv.FormatBool(useSessionFile))
136
+ }
137
+ userSession, _ := cmd.Flags().GetString("user-session")
138
+ if userSession != "" {
139
+ os.Setenv("USER_SESSION", userSession)
140
+ }
141
+ usePublicIP, _ := cmd.Flags().GetBool("use-public-ip")
142
+ if usePublicIP {
143
+ os.Setenv("USE_PUBLIC_IP", strconv.FormatBool(usePublicIP))
144
+ }
145
+ multiTokens, _ := cmd.Flags().GetString("multi-token-txt-file")
146
+ if multiTokens != "" {
147
+ os.Setenv("MULTI_TOKEN_TXT_FILE", multiTokens)
148
+ // TODO: Add support for importing tokens from a separate file
149
+ }
150
+ streamConcurrency, _ := cmd.Flags().GetInt("stream-concurrency")
151
+ if streamConcurrency != 0 {
152
+ os.Setenv("STREAM_CONCURRENCY", strconv.Itoa(streamConcurrency))
153
+ }
154
+ streamBufferCount, _ := cmd.Flags().GetInt("stream-buffer-count")
155
+ if streamBufferCount != 0 {
156
+ os.Setenv("STREAM_BUFFER_COUNT", strconv.Itoa(streamBufferCount))
157
+ }
158
+ streamTimeoutSec, _ := cmd.Flags().GetInt("stream-timeout-sec")
159
+ if streamTimeoutSec != 0 {
160
+ os.Setenv("STREAM_TIMEOUT_SEC", strconv.Itoa(streamTimeoutSec))
161
+ }
162
+ streamMaxRetries, _ := cmd.Flags().GetInt("stream-max-retries")
163
+ if streamMaxRetries != 0 {
164
+ os.Setenv("STREAM_MAX_RETRIES", strconv.Itoa(streamMaxRetries))
165
+ }
166
+ }
167
+
168
+ func (c *config) setupEnvVars(log *zap.Logger, cmd *cobra.Command) {
169
+ c.loadFromEnvFile(log)
170
+ c.loadConfigFromArgs(log, cmd)
171
+ err := envconfig.Process("", c)
172
+ if err != nil {
173
+ log.Fatal("Error while parsing env variables", zap.Error(err))
174
+ }
175
+ var ipBlocked bool
176
+ ip, err := getIP(c.UsePublicIP)
177
+ if err != nil {
178
+ log.Error("Error while getting IP", zap.Error(err))
179
+ ipBlocked = true
180
+ }
181
+ if c.Host == "" {
182
+ c.Host = "http://" + ip + ":" + strconv.Itoa(c.Port)
183
+ if c.UsePublicIP {
184
+ if ipBlocked {
185
+ log.Sugar().Warn("Can't get public IP, using local IP")
186
+ } else {
187
+ log.Sugar().Warn("You are using a public IP, please be aware of the security risks while exposing your IP to the internet.")
188
+ log.Sugar().Warn("Use 'HOST' variable to set a domain name")
189
+ }
190
+ }
191
+ log.Sugar().Info("HOST not set, automatically set to " + c.Host)
192
+ }
193
+ val := reflect.ValueOf(c).Elem()
194
+ for _, env := range os.Environ() {
195
+ if strings.HasPrefix(env, "MULTI_TOKEN") {
196
+ c.MultiTokens = append(c.MultiTokens, botTokenRegex.FindStringSubmatch(env)[1])
197
+ }
198
+ }
199
+ val.FieldByName("MultiTokens").Set(reflect.ValueOf(c.MultiTokens))
200
+ }
201
+
202
+ func Load(log *zap.Logger, cmd *cobra.Command) {
203
+ log = log.Named("Config")
204
+ defer log.Info("Loaded config")
205
+ ValueOf.setupEnvVars(log, cmd)
206
+ ValueOf.LogChannelID = int64(stripInt(log, int(ValueOf.LogChannelID)))
207
+ if ValueOf.HashLength == 0 {
208
+ log.Sugar().Info("HASH_LENGTH can't be 0, defaulting to 6")
209
+ ValueOf.HashLength = 6
210
+ }
211
+ if ValueOf.HashLength > 32 {
212
+ log.Sugar().Info("HASH_LENGTH can't be more than 32, changing to 32")
213
+ ValueOf.HashLength = 32
214
+ }
215
+ if ValueOf.HashLength < 5 {
216
+ log.Sugar().Info("HASH_LENGTH can't be less than 5, defaulting to 6")
217
+ ValueOf.HashLength = 6
218
+ }
219
+ if ValueOf.StreamConcurrency <= 0 {
220
+ log.Sugar().Info("STREAM_CONCURRENCY must be greater than 0, defaulting to 8")
221
+ ValueOf.StreamConcurrency = 8
222
+ }
223
+ if ValueOf.StreamBufferCount <= 0 {
224
+ log.Sugar().Info("STREAM_BUFFER_COUNT must be greater than 0, defaulting to 16")
225
+ ValueOf.StreamBufferCount = 16
226
+ }
227
+ if ValueOf.StreamTimeoutSec <= 0 {
228
+ log.Sugar().Info("STREAM_TIMEOUT_SEC must be greater than 0, defaulting to 30 seconds")
229
+ ValueOf.StreamTimeoutSec = 30
230
+ }
231
+ if ValueOf.StreamMaxRetries <= 0 {
232
+ log.Sugar().Info("STREAM_MAX_RETRIES must be greater than 0, defaulting to 10")
233
+ ValueOf.StreamMaxRetries = 10
234
+ }
235
+ }
236
+
237
+ func getIP(public bool) (string, error) {
238
+ var ip string
239
+ var err error
240
+ if public {
241
+ ip, err = GetPublicIP()
242
+ } else {
243
+ ip, err = getInternalIP()
244
+ }
245
+ if ip == "" {
246
+ ip = "localhost"
247
+ }
248
+ if err != nil {
249
+ return "localhost", err
250
+ }
251
+ return ip, nil
252
+ }
253
+
254
+ // https://stackoverflow.com/a/23558495/15807350
255
+ func getInternalIP() (string, error) {
256
+ conn, err := net.Dial("udp", "8.8.8.8:80")
257
+ if err != nil {
258
+ return "", errors.New("no internet connection")
259
+ }
260
+ defer conn.Close()
261
+ localAddr := conn.LocalAddr().(*net.UDPAddr)
262
+ return localAddr.IP.String(), nil
263
+ }
264
+
265
+ func GetPublicIP() (string, error) {
266
+ resp, err := http.Get("https://api.ipify.org?format=text")
267
+ if err != nil {
268
+ return "", err
269
+ }
270
+ defer resp.Body.Close()
271
+ ip, err := io.ReadAll(resp.Body)
272
+ if err != nil {
273
+ return "", err
274
+ }
275
+ if !checkIfIpAccessible(string(ip)) {
276
+ return string(ip), errors.New("PORT is blocked by firewall")
277
+ }
278
+ return string(ip), nil
279
+ }
280
+
281
+ func checkIfIpAccessible(ip string) bool {
282
+ conn, err := net.Dial("tcp", ip+":80")
283
+ if err != nil {
284
+ return false
285
+ }
286
+ defer conn.Close()
287
+ return true
288
+ }
289
+
290
+ func stripInt(log *zap.Logger, a int) int {
291
+ strA := strconv.Itoa(abs(a))
292
+ lastDigits := strings.Replace(strA, "100", "", 1)
293
+ result, err := strconv.Atoi(lastDigits)
294
+ if err != nil {
295
+ log.Sugar().Fatalln(err)
296
+ return 0
297
+ }
298
+ return result
299
+ }
300
+
301
+ func abs(x int) int {
302
+ if x < 0 {
303
+ return -x
304
+ }
305
+ return x
306
+ }
fsb.sample.env ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Required Variables (DO NOT SKIP THESE)
2
+
3
+ API_ID=
4
+ API_HASH=
5
+ BOT_TOKEN=
6
+ LOG_CHANNEL=
7
+
8
+ # Optional Variables
9
+
10
+ DEV=false
11
+ PORT=8080
12
+
13
+ # The length of the hash in your URLs
14
+ # https://domain.tld/1254?hash=asd45a
15
+ # ^^^^^^
16
+ # /
17
+ # This is the hash
18
+
19
+ HASH_LENGTH=6
20
+
21
+ # you can use IP address
22
+ # HOST=http://<ip address>:<PORT>
23
+ # Or you can also use a domain name
24
+ # HOST=https://example.com
25
+
26
+ # Use public IP while auto-generating HOST (not recommended unless needed)
27
+ USE_PUBLIC_IP=false
28
+
29
+ # Reuse worker sessions from files (faster startup)
30
+ USE_SESSION_FILE=true
31
+
32
+ # Optional user session string for userbot features
33
+ # USER_SESSION=
34
+
35
+ # Optional allowlist of Telegram user IDs (comma-separated)
36
+ # ALLOWED_USERS=12345,67890
37
+
38
+ # Stream performance tuning
39
+ # STREAM_CONCURRENCY = parallel Telegram chunk downloads per stream request
40
+ # STREAM_BUFFER_COUNT = how many chunks to keep ready in memory
41
+ # STREAM_TIMEOUT_SEC = per-chunk timeout (seconds)
42
+ # STREAM_MAX_RETRIES = retries per failed chunk
43
+ #
44
+ # Good default:
45
+ # STREAM_CONCURRENCY=4
46
+ # STREAM_BUFFER_COUNT=8
47
+ # STREAM_TIMEOUT_SEC=30
48
+ # STREAM_MAX_RETRIES=3
49
+ STREAM_CONCURRENCY=4
50
+ STREAM_BUFFER_COUNT=8
51
+ STREAM_TIMEOUT_SEC=30
52
+ STREAM_MAX_RETRIES=3
53
+
54
+ # For muti token support
55
+ # Refer https://github.com/EverythingSuckz/TG-FileStreamBot/tree/golang#use-multiple-bots-to-speed-up
56
+
57
+ # MULTI_TOKEN1=1857821156:AAEvrINCsduhjkjhahadvHRdk7oF46KZnc
58
+ # MULTI_TOKEN2=1355359001:AAF4dgddVVxDCt51FZqy1unh9h0SOTw0gU
59
+ # MULTI_TOKEN3=6941936497:AAGJzfoMHXshS8gVcsefUzpwyrbfU7gKRMM
60
+ # MULTI_TOKEN4=6546079247:AAF2k3uvO9Hqadfhjaskjds8jnzOAfQYUzTZ
fsb.session ADDED
Binary file (24.6 kB). View file
 
go.mod ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ module EverythingSuckz/fsb
2
+
3
+ go 1.25.0
4
+
5
+ require (
6
+ firebase.google.com/go/v4 v4.19.0
7
+ github.com/celestix/gotgproto v1.0.0-beta21
8
+ github.com/gin-gonic/gin v1.9.1
9
+ github.com/glebarez/sqlite v1.11.0
10
+ github.com/gotd/td v0.132.0
11
+ github.com/joho/godotenv v1.5.1
12
+ github.com/kelseyhightower/envconfig v1.4.0
13
+ github.com/quantumsheep/range-parser v1.1.0
14
+ github.com/spf13/cobra v1.8.0
15
+ google.golang.org/api v0.272.0
16
+ )
17
+
18
+ require (
19
+ cel.dev/expr v0.25.1 // indirect
20
+ cloud.google.com/go v0.123.0 // indirect
21
+ cloud.google.com/go/auth v0.18.2 // indirect
22
+ cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect
23
+ cloud.google.com/go/compute/metadata v0.9.0 // indirect
24
+ cloud.google.com/go/firestore v1.21.0 // indirect
25
+ cloud.google.com/go/iam v1.5.3 // indirect
26
+ cloud.google.com/go/longrunning v0.8.0 // indirect
27
+ cloud.google.com/go/monitoring v1.24.3 // indirect
28
+ cloud.google.com/go/storage v1.56.0 // indirect
29
+ github.com/AnimeKaizoku/cacher v1.0.3 // indirect
30
+ github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0 // indirect
31
+ github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53.0 // indirect
32
+ github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0 // indirect
33
+ github.com/MicahParks/keyfunc v1.9.0 // indirect
34
+ github.com/cenkalti/backoff/v4 v4.3.0 // indirect
35
+ github.com/cespare/xxhash/v2 v2.3.0 // indirect
36
+ github.com/chenzhuoyu/iasm v0.9.1 // indirect
37
+ github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 // indirect
38
+ github.com/coder/websocket v1.8.14 // indirect
39
+ github.com/dlclark/regexp2 v1.11.5 // indirect
40
+ github.com/dustin/go-humanize v1.0.1 // indirect
41
+ github.com/envoyproxy/go-control-plane/envoy v1.36.0 // indirect
42
+ github.com/envoyproxy/protoc-gen-validate v1.3.0 // indirect
43
+ github.com/fatih/color v1.18.0 // indirect
44
+ github.com/felixge/httpsnoop v1.0.4 // indirect
45
+ github.com/ghodss/yaml v1.0.0 // indirect
46
+ github.com/glebarez/go-sqlite v1.22.0 // indirect
47
+ github.com/go-faster/errors v0.7.1 // indirect
48
+ github.com/go-faster/jx v1.1.0 // indirect
49
+ github.com/go-faster/xor v1.0.0 // indirect
50
+ github.com/go-faster/yaml v0.4.6 // indirect
51
+ github.com/go-jose/go-jose/v4 v4.1.3 // indirect
52
+ github.com/go-logr/logr v1.4.3 // indirect
53
+ github.com/go-logr/stdr v1.2.2 // indirect
54
+ github.com/golang-jwt/jwt/v4 v4.5.2 // indirect
55
+ github.com/golang/protobuf v1.5.4 // indirect
56
+ github.com/google/s2a-go v0.1.9 // indirect
57
+ github.com/google/uuid v1.6.0 // indirect
58
+ github.com/googleapis/enterprise-certificate-proxy v0.3.14 // indirect
59
+ github.com/googleapis/gax-go/v2 v2.18.0 // indirect
60
+ github.com/gotd/ige v0.2.2 // indirect
61
+ github.com/gotd/neo v0.1.5 // indirect
62
+ github.com/inconshreveable/mousetrap v1.1.0 // indirect
63
+ github.com/jinzhu/inflection v1.0.0 // indirect
64
+ github.com/jinzhu/now v1.1.5 // indirect
65
+ github.com/klauspost/compress v1.18.0 // indirect
66
+ github.com/mattn/go-colorable v0.1.14 // indirect
67
+ github.com/ncruces/go-strftime v1.0.0 // indirect
68
+ github.com/ogen-go/ogen v1.16.0 // indirect
69
+ github.com/pkg/errors v0.9.1 // indirect
70
+ github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect
71
+ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
72
+ github.com/segmentio/asm v1.2.1 // indirect
73
+ github.com/shopspring/decimal v1.4.0 // indirect
74
+ github.com/spf13/pflag v1.0.5 // indirect
75
+ github.com/spiffe/go-spiffe/v2 v2.6.0 // indirect
76
+ go.opentelemetry.io/auto/sdk v1.2.1 // indirect
77
+ go.opentelemetry.io/contrib/detectors/gcp v1.39.0 // indirect
78
+ go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 // indirect
79
+ go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 // indirect
80
+ go.opentelemetry.io/otel v1.39.0 // indirect
81
+ go.opentelemetry.io/otel/metric v1.39.0 // indirect
82
+ go.opentelemetry.io/otel/sdk v1.39.0 // indirect
83
+ go.opentelemetry.io/otel/sdk/metric v1.39.0 // indirect
84
+ go.opentelemetry.io/otel/trace v1.39.0 // indirect
85
+ go.uber.org/atomic v1.11.0 // indirect
86
+ go.uber.org/multierr v1.11.0 // indirect
87
+ golang.org/x/exp v0.0.0-20251009144603-d2f985daa21b // indirect
88
+ golang.org/x/mod v0.33.0 // indirect
89
+ golang.org/x/oauth2 v0.36.0 // indirect
90
+ golang.org/x/sync v0.20.0 // indirect
91
+ golang.org/x/tools v0.42.0 // indirect
92
+ google.golang.org/appengine/v2 v2.0.6 // indirect
93
+ google.golang.org/genproto v0.0.0-20260217215200-42d3e9bedb6d // indirect
94
+ google.golang.org/genproto/googleapis/api v0.0.0-20260217215200-42d3e9bedb6d // indirect
95
+ google.golang.org/genproto/googleapis/rpc v0.0.0-20260311181403-84a4fc48630c // indirect
96
+ google.golang.org/grpc v1.79.2 // indirect
97
+ gopkg.in/yaml.v2 v2.4.0 // indirect
98
+ gorm.io/gorm v1.31.0 // indirect
99
+ modernc.org/libc v1.66.10 // indirect
100
+ modernc.org/mathutil v1.7.1 // indirect
101
+ modernc.org/memory v1.11.0 // indirect
102
+ modernc.org/sqlite v1.39.1 // indirect
103
+ rsc.io/qr v0.2.0 // indirect
104
+ )
105
+
106
+ require (
107
+ github.com/bytedance/sonic v1.10.2 // indirect
108
+ github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect
109
+ github.com/coocood/freecache v1.2.4
110
+ github.com/gabriel-vasile/mimetype v1.4.3 // indirect
111
+ github.com/gin-contrib/sse v0.1.0 // indirect
112
+ github.com/go-playground/locales v0.14.1 // indirect
113
+ github.com/go-playground/universal-translator v0.18.1 // indirect
114
+ github.com/go-playground/validator/v10 v10.18.0 // indirect
115
+ github.com/goccy/go-json v0.10.2 // indirect
116
+ github.com/gotd/contrib v0.19.0
117
+ github.com/json-iterator/go v1.1.12 // indirect
118
+ github.com/klauspost/cpuid/v2 v2.2.7 // indirect
119
+ github.com/leodido/go-urn v1.4.0 // indirect
120
+ github.com/mattn/go-isatty v0.0.20 // indirect
121
+ github.com/mdp/qrterminal v1.0.1
122
+ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
123
+ github.com/modern-go/reflect2 v1.0.2 // indirect
124
+ github.com/pelletier/go-toml/v2 v2.1.1 // indirect
125
+ github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
126
+ github.com/ugorji/go/codec v1.2.12 // indirect
127
+ go.uber.org/zap v1.27.0
128
+ golang.org/x/arch v0.7.0 // indirect
129
+ golang.org/x/crypto v0.49.0 // indirect
130
+ golang.org/x/net v0.52.0 // indirect
131
+ golang.org/x/sys v0.42.0 // indirect
132
+ golang.org/x/text v0.35.0 // indirect
133
+ golang.org/x/time v0.15.0
134
+ google.golang.org/protobuf v1.36.11 // indirect
135
+ gopkg.in/natefinch/lumberjack.v2 v2.2.1
136
+ gopkg.in/yaml.v3 v3.0.1 // indirect
137
+ )
go.sum ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4=
2
+ cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
3
+ cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE=
4
+ cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU=
5
+ cloud.google.com/go/auth v0.18.2 h1:+Nbt5Ev0xEqxlNjd6c+yYUeosQ5TtEUaNcN/3FozlaM=
6
+ cloud.google.com/go/auth v0.18.2/go.mod h1:xD+oY7gcahcu7G2SG2DsBerfFxgPAJz17zz2joOFF3M=
7
+ cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc=
8
+ cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c=
9
+ cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs=
10
+ cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10=
11
+ cloud.google.com/go/firestore v1.21.0 h1:BhopUsx7kh6NFx77ccRsHhrtkbJUmDAxNY3uapWdjcM=
12
+ cloud.google.com/go/firestore v1.21.0/go.mod h1:1xH6HNcnkf/gGyR8udd6pFO4Z7GWJSwLKQMx/u6UrP4=
13
+ cloud.google.com/go/iam v1.5.3 h1:+vMINPiDF2ognBJ97ABAYYwRgsaqxPbQDlMnbHMjolc=
14
+ cloud.google.com/go/iam v1.5.3/go.mod h1:MR3v9oLkZCTlaqljW6Eb2d3HGDGK5/bDv93jhfISFvU=
15
+ cloud.google.com/go/logging v1.13.2 h1:qqlHCBvieJT9Cdq4QqYx1KPadCQ2noD4FK02eNqHAjA=
16
+ cloud.google.com/go/logging v1.13.2/go.mod h1:zaybliM3yun1J8mU2dVQ1/qDzjbOqEijZCn6hSBtKak=
17
+ cloud.google.com/go/longrunning v0.8.0 h1:LiKK77J3bx5gDLi4SMViHixjD2ohlkwBi+mKA7EhfW8=
18
+ cloud.google.com/go/longrunning v0.8.0/go.mod h1:UmErU2Onzi+fKDg2gR7dusz11Pe26aknR4kHmJJqIfk=
19
+ cloud.google.com/go/monitoring v1.24.3 h1:dde+gMNc0UhPZD1Azu6at2e79bfdztVDS5lvhOdsgaE=
20
+ cloud.google.com/go/monitoring v1.24.3/go.mod h1:nYP6W0tm3N9H/bOw8am7t62YTzZY+zUeQ+Bi6+2eonI=
21
+ cloud.google.com/go/storage v1.56.0 h1:iixmq2Fse2tqxMbWhLWC9HfBj1qdxqAmiK8/eqtsLxI=
22
+ cloud.google.com/go/storage v1.56.0/go.mod h1:Tpuj6t4NweCLzlNbw9Z9iwxEkrSem20AetIeH/shgVU=
23
+ cloud.google.com/go/trace v1.11.7 h1:kDNDX8JkaAG3R2nq1lIdkb7FCSi1rCmsEtKVsty7p+U=
24
+ cloud.google.com/go/trace v1.11.7/go.mod h1:TNn9d5V3fQVf6s4SCveVMIBS2LJUqo73GACmq/Tky0s=
25
+ firebase.google.com/go/v4 v4.19.0 h1:f5NMlC2YHFsncz00c2+ecBr+ZYlRMhKIhj1z8Iz0lD8=
26
+ firebase.google.com/go/v4 v4.19.0/go.mod h1:P7UfBpzc8+Z3MckX79+zsWzKVfpGryr6HLbAe7gCWfs=
27
+ github.com/AnimeKaizoku/cacher v1.0.3 h1:foNAmLfY/DXfA4yEy4uP6WK2Ni7JC+s3QhZv72Dn6zs=
28
+ github.com/AnimeKaizoku/cacher v1.0.3/go.mod h1:jw0de/b0K6W7Y3T9rHCMGVKUf6oG7hENNcssxYcZTCc=
29
+ github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0 h1:sBEjpZlNHzK1voKq9695PJSX2o5NEXl7/OL3coiIY0c=
30
+ github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0/go.mod h1:P4WPRUkOhJC13W//jWpyfJNDAIpvRbAUIYLX/4jtlE0=
31
+ github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53.0 h1:owcC2UnmsZycprQ5RfRgjydWhuoxg71LUfyiQdijZuM=
32
+ github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53.0/go.mod h1:ZPpqegjbE99EPKsu3iUWV22A04wzGPcAY/ziSIQEEgs=
33
+ github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.53.0 h1:4LP6hvB4I5ouTbGgWtixJhgED6xdf67twf9PoY96Tbg=
34
+ github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.53.0/go.mod h1:jUZ5LYlw40WMd07qxcQJD5M40aUxrfwqQX1g7zxYnrQ=
35
+ github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0 h1:Ron4zCA/yk6U7WOBXhTJcDpsUBG9npumK6xw2auFltQ=
36
+ github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0/go.mod h1:cSgYe11MCNYunTnRXrKiR/tHc0eoKjICUuWpNZoVCOo=
37
+ github.com/MicahParks/keyfunc v1.9.0 h1:lhKd5xrFHLNOWrDc4Tyb/Q1AJ4LCzQ48GVJyVIID3+o=
38
+ github.com/MicahParks/keyfunc v1.9.0/go.mod h1:IdnCilugA0O/99dW+/MkvlyrsX8+L8+x95xuVNtM5jw=
39
+ github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
40
+ github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM=
41
+ github.com/bytedance/sonic v1.10.2 h1:GQebETVBxYB7JGWJtLBi07OVzWwt+8dWA00gEVW2ZFE=
42
+ github.com/bytedance/sonic v1.10.2/go.mod h1:iZcSUejdk5aukTND/Eu/ivjQuEL0Cu9/rf50Hi0u/g4=
43
+ github.com/celestix/gotgproto v1.0.0-beta21 h1:VUuAC/Kj5Sdu/WZan3ZUb0GFNAavFxMYxmHAhCBX0J8=
44
+ github.com/celestix/gotgproto v1.0.0-beta21/go.mod h1:viDkHe9rBegJoEE/jNuFfbBM0XZ3pSx/ugjaNaVnbvU=
45
+ github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
46
+ github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
47
+ github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
48
+ github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
49
+ github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
50
+ github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
51
+ github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=
52
+ github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d h1:77cEq6EriyTZ0g/qfRdp61a3Uu/AWrgIq2s0ClJV1g0=
53
+ github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d/go.mod h1:8EPpVsBuRksnlj1mLy4AWzRNQYxauNi62uWcE3to6eA=
54
+ github.com/chenzhuoyu/iasm v0.9.0/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog=
55
+ github.com/chenzhuoyu/iasm v0.9.1 h1:tUHQJXo3NhBqw6s33wkGn9SP3bvrWLdlVIJ3hQBL7P0=
56
+ github.com/chenzhuoyu/iasm v0.9.1/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog=
57
+ github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 h1:6xNmx7iTtyBRev0+D/Tv1FZd4SCg8axKApyNyRsAt/w=
58
+ github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5/go.mod h1:KdCmV+x/BuvyMxRnYBlmVaq4OLiKW6iRQfvC62cvdkI=
59
+ github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g=
60
+ github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
61
+ github.com/coocood/freecache v1.2.4 h1:UdR6Yz/X1HW4fZOuH0Z94KwG851GWOSknua5VUbb/5M=
62
+ github.com/coocood/freecache v1.2.4/go.mod h1:RBUWa/Cy+OHdfTGFEhEuE1pMCMX51Ncizj7rthiQ3vk=
63
+ github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
64
+ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
65
+ github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
66
+ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
67
+ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
68
+ github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=
69
+ github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
70
+ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
71
+ github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
72
+ github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwBIfQawTkC++2HA=
73
+ github.com/envoyproxy/go-control-plane v0.14.0/go.mod h1:NcS5X47pLl/hfqxU70yPwL9ZMkUlwlKxtAohpi2wBEU=
74
+ github.com/envoyproxy/go-control-plane/envoy v1.36.0 h1:yg/JjO5E7ubRyKX3m07GF3reDNEnfOboJ0QySbH736g=
75
+ github.com/envoyproxy/go-control-plane/envoy v1.36.0/go.mod h1:ty89S1YCCVruQAm9OtKeEkQLTb+Lkz0k8v9W0Oxsv98=
76
+ github.com/envoyproxy/go-control-plane/ratelimit v0.1.0 h1:/G9QYbddjL25KvtKTv3an9lx6VBE2cnb8wp1vEGNYGI=
77
+ github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4=
78
+ github.com/envoyproxy/protoc-gen-validate v1.3.0 h1:TvGH1wof4H33rezVKWSpqKz5NXWg5VPuZ0uONDT6eb4=
79
+ github.com/envoyproxy/protoc-gen-validate v1.3.0/go.mod h1:HvYl7zwPa5mffgyeTUHA9zHIH36nmrm7oCbo4YKoSWA=
80
+ github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
81
+ github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
82
+ github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
83
+ github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
84
+ github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
85
+ github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
86
+ github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk=
87
+ github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
88
+ github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
89
+ github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
90
+ github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
91
+ github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
92
+ github.com/glebarez/go-sqlite v1.22.0 h1:uAcMJhaA6r3LHMTFgP0SifzgXg46yJkgxqyuyec+ruQ=
93
+ github.com/glebarez/go-sqlite v1.22.0/go.mod h1:PlBIdHe0+aUEFn+r2/uthrWq4FxbzugL0L8Li6yQJbc=
94
+ github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw=
95
+ github.com/glebarez/sqlite v1.11.0/go.mod h1:h8/o8j5wiAsqSPoWELDUdJXhjAhsVliSn7bWZjOhrgQ=
96
+ github.com/go-faster/errors v0.7.1 h1:MkJTnDoEdi9pDabt1dpWf7AA8/BaSYZqibYyhZ20AYg=
97
+ github.com/go-faster/errors v0.7.1/go.mod h1:5ySTjWFiphBs07IKuiL69nxdfd5+fzh1u7FPGZP2quo=
98
+ github.com/go-faster/jx v1.1.0 h1:ZsW3wD+snOdmTDy9eIVgQdjUpXRRV4rqW8NS3t+20bg=
99
+ github.com/go-faster/jx v1.1.0/go.mod h1:vKDNikrKoyUmpzaJ0OkIkRQClNHFX/nF3dnTJZb3skg=
100
+ github.com/go-faster/xor v0.3.0/go.mod h1:x5CaDY9UKErKzqfRfFZdfu+OSTfoZny3w5Ak7UxcipQ=
101
+ github.com/go-faster/xor v1.0.0 h1:2o8vTOgErSGHP3/7XwA5ib1FTtUsNtwCoLLBjl31X38=
102
+ github.com/go-faster/xor v1.0.0/go.mod h1:x5CaDY9UKErKzqfRfFZdfu+OSTfoZny3w5Ak7UxcipQ=
103
+ github.com/go-faster/yaml v0.4.6 h1:lOK/EhI04gCpPgPhgt0bChS6bvw7G3WwI8xxVe0sw9I=
104
+ github.com/go-faster/yaml v0.4.6/go.mod h1:390dRIvV4zbnO7qC9FGo6YYutc+wyyUSHBgbXL52eXk=
105
+ github.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs=
106
+ github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
107
+ github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
108
+ github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
109
+ github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
110
+ github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
111
+ github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
112
+ github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
113
+ github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
114
+ github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
115
+ github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
116
+ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
117
+ github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
118
+ github.com/go-playground/validator/v10 v10.18.0 h1:BvolUXjp4zuvkZ5YN5t7ebzbhlUtPsPm2S9NAZ5nl9U=
119
+ github.com/go-playground/validator/v10 v10.18.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
120
+ github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
121
+ github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
122
+ github.com/golang-jwt/jwt/v4 v4.4.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
123
+ github.com/golang-jwt/jwt/v4 v4.5.2 h1:YtQM7lnr8iZ+j5q71MGKkNw9Mn7AjHM68uc9g5fXeUI=
124
+ github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
125
+ github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
126
+ github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
127
+ github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
128
+ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
129
+ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
130
+ github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
131
+ github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
132
+ github.com/google/martian/v3 v3.3.3 h1:DIhPTQrbPkgs2yJYdXU/eNACCG5DVQjySNRNlflZ9Fc=
133
+ github.com/google/martian/v3 v3.3.3/go.mod h1:iEPrYcgCF7jA9OtScMFQyAlZZ4YXTKEtJ1E6RWzmBA0=
134
+ github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
135
+ github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
136
+ github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=
137
+ github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
138
+ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
139
+ github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
140
+ github.com/googleapis/enterprise-certificate-proxy v0.3.14 h1:yh8ncqsbUY4shRD5dA6RlzjJaT4hi3kII+zYw8wmLb8=
141
+ github.com/googleapis/enterprise-certificate-proxy v0.3.14/go.mod h1:vqVt9yG9480NtzREnTlmGSBmFrA+bzb0yl0TxoBQXOg=
142
+ github.com/googleapis/gax-go/v2 v2.18.0 h1:jxP5Uuo3bxm3M6gGtV94P4lliVetoCB4Wk2x8QA86LI=
143
+ github.com/googleapis/gax-go/v2 v2.18.0/go.mod h1:uSzZN4a356eRG985CzJ3WfbFSpqkLTjsnhWGJR6EwrE=
144
+ github.com/gotd/contrib v0.19.0 h1:O6GvMrRVeFslIHLUcpaHVzcl9/5PcgR2jQTIIeTyds0=
145
+ github.com/gotd/contrib v0.19.0/go.mod h1:LzPxzRF0FvtpBt/WyODWQnPpk0tm/G9z6RHUoPqMakU=
146
+ github.com/gotd/ige v0.2.2 h1:XQ9dJZwBfDnOGSTxKXBGP4gMud3Qku2ekScRjDWWfEk=
147
+ github.com/gotd/ige v0.2.2/go.mod h1:tuCRb+Y5Y3eNTo3ypIfNpQ4MFjrnONiL2jN2AKZXmb0=
148
+ github.com/gotd/neo v0.1.5 h1:oj0iQfMbGClP8xI59x7fE/uHoTJD7NZH9oV1WNuPukQ=
149
+ github.com/gotd/neo v0.1.5/go.mod h1:9A2a4bn9zL6FADufBdt7tZt+WMhvZoc5gWXihOPoiBQ=
150
+ github.com/gotd/td v0.132.0 h1:Iqm3S2b+8kDgA9237IDXRxj7sryUpvy+4Cr50/0tpx4=
151
+ github.com/gotd/td v0.132.0/go.mod h1:4CDGYS+rDtOqotRheGaF9MS5g6jaUewvSXqBNJnx8SQ=
152
+ github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
153
+ github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
154
+ github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
155
+ github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
156
+ github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
157
+ github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
158
+ github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
159
+ github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
160
+ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
161
+ github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
162
+ github.com/kelseyhightower/envconfig v1.4.0 h1:Im6hONhd3pLkfDFsbRgu68RDNkGF1r3dvMUtDTo2cv8=
163
+ github.com/kelseyhightower/envconfig v1.4.0/go.mod h1:cccZRl6mQpaq41TPp5QxidR+Sa3axMbJDNb//FQX6Gg=
164
+ github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
165
+ github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
166
+ github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
167
+ github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
168
+ github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
169
+ github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
170
+ github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
171
+ github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
172
+ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
173
+ github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
174
+ github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
175
+ github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
176
+ github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
177
+ github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
178
+ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
179
+ github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
180
+ github.com/mdp/qrterminal v1.0.1 h1:07+fzVDlPuBlXS8tB0ktTAyf+Lp1j2+2zK3fBOL5b7c=
181
+ github.com/mdp/qrterminal v1.0.1/go.mod h1:Z33WhxQe9B6CdW37HaVqcRKzP+kByF3q/qLxOGe12xQ=
182
+ github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
183
+ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
184
+ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
185
+ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
186
+ github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
187
+ github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
188
+ github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
189
+ github.com/ogen-go/ogen v1.16.0 h1:fKHEYokW/QrMzVNXId74/6RObRIUs9T2oroGKtR25Iw=
190
+ github.com/ogen-go/ogen v1.16.0/go.mod h1:s3nWiMzybSf8fhxckyO+wtto92+QHpEL8FmkPnhL3jI=
191
+ github.com/pelletier/go-toml/v2 v2.1.1 h1:LWAJwfNvjQZCFIDKWYQaM62NcYeYViCmWIwmOStowAI=
192
+ github.com/pelletier/go-toml/v2 v2.1.1/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=
193
+ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
194
+ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
195
+ github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo=
196
+ github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8=
197
+ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
198
+ github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
199
+ github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
200
+ github.com/quantumsheep/range-parser v1.1.0 h1:k4f1F58f8FF54FBYc9dYBRM+8JkAxFo11gC3IeMH4rU=
201
+ github.com/quantumsheep/range-parser v1.1.0/go.mod h1:acv4Vt2PvpGvRsvGju7Gk2ahKluZJsIUNR69W53J22I=
202
+ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
203
+ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
204
+ github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
205
+ github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
206
+ github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
207
+ github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0=
208
+ github.com/segmentio/asm v1.2.1/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=
209
+ github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=
210
+ github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
211
+ github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
212
+ github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
213
+ github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
214
+ github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
215
+ github.com/spiffe/go-spiffe/v2 v2.6.0 h1:l+DolpxNWYgruGQVV0xsfeya3CsC7m8iBzDnMpsbLuo=
216
+ github.com/spiffe/go-spiffe/v2 v2.6.0/go.mod h1:gm2SeUoMZEtpnzPNs2Csc0D/gX33k1xIx7lEzqblHEs=
217
+ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
218
+ github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
219
+ github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
220
+ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
221
+ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
222
+ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
223
+ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
224
+ github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
225
+ github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
226
+ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
227
+ github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
228
+ github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
229
+ github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
230
+ github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
231
+ github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
232
+ github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
233
+ go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
234
+ go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
235
+ go.opentelemetry.io/contrib/detectors/gcp v1.39.0 h1:kWRNZMsfBHZ+uHjiH4y7Etn2FK26LAGkNFw7RHv1DhE=
236
+ go.opentelemetry.io/contrib/detectors/gcp v1.39.0/go.mod h1:t/OGqzHBa5v6RHZwrDBJ2OirWc+4q/w2fTbLZwAKjTk=
237
+ go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 h1:q4XOmH/0opmeuJtPsbFNivyl7bCt7yRBbeEm2sC/XtQ=
238
+ go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo=
239
+ go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6hwnZ41NSFTO5q4LYDtJRXBf2PD0rNBkeB/lus=
240
+ go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q=
241
+ go.opentelemetry.io/otel v1.39.0 h1:8yPrr/S0ND9QEfTfdP9V+SiwT4E0G7Y5MO7p85nis48=
242
+ go.opentelemetry.io/otel v1.39.0/go.mod h1:kLlFTywNWrFyEdH0oj2xK0bFYZtHRYUdv1NklR/tgc8=
243
+ go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.36.0 h1:rixTyDGXFxRy1xzhKrotaHy3/KXdPhlWARrCgK+eqUY=
244
+ go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.36.0/go.mod h1:dowW6UsM9MKbJq5JTz2AMVp3/5iW5I/TStsk8S+CfHw=
245
+ go.opentelemetry.io/otel/metric v1.39.0 h1:d1UzonvEZriVfpNKEVmHXbdf909uGTOQjA0HF0Ls5Q0=
246
+ go.opentelemetry.io/otel/metric v1.39.0/go.mod h1:jrZSWL33sD7bBxg1xjrqyDjnuzTUB0x1nBERXd7Ftcs=
247
+ go.opentelemetry.io/otel/sdk v1.39.0 h1:nMLYcjVsvdui1B/4FRkwjzoRVsMK8uL/cj0OyhKzt18=
248
+ go.opentelemetry.io/otel/sdk v1.39.0/go.mod h1:vDojkC4/jsTJsE+kh+LXYQlbL8CgrEcwmt1ENZszdJE=
249
+ go.opentelemetry.io/otel/sdk/metric v1.39.0 h1:cXMVVFVgsIf2YL6QkRF4Urbr/aMInf+2WKg+sEJTtB8=
250
+ go.opentelemetry.io/otel/sdk/metric v1.39.0/go.mod h1:xq9HEVH7qeX69/JnwEfp6fVq5wosJsY1mt4lLfYdVew=
251
+ go.opentelemetry.io/otel/trace v1.39.0 h1:2d2vfpEDmCJ5zVYz7ijaJdOF59xLomrvj7bjt6/qCJI=
252
+ go.opentelemetry.io/otel/trace v1.39.0/go.mod h1:88w4/PnZSazkGzz/w84VHpQafiU4EtqqlVdxWy+rNOA=
253
+ go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
254
+ go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
255
+ go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
256
+ go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
257
+ go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
258
+ go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
259
+ go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
260
+ go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
261
+ golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
262
+ golang.org/x/arch v0.7.0 h1:pskyeJh/3AmoQ8CPE95vxHLqp1G1GfGNXTmcl9NEKTc=
263
+ golang.org/x/arch v0.7.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
264
+ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
265
+ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
266
+ golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
267
+ golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
268
+ golang.org/x/exp v0.0.0-20251009144603-d2f985daa21b h1:18qgiDvlvH7kk8Ioa8Ov+K6xCi0GMvmGfGW0sgd/SYA=
269
+ golang.org/x/exp v0.0.0-20251009144603-d2f985daa21b/go.mod h1:j/pmGrbnkbPtQfxEe5D0VQhZC6qKbfKifgD0oM7sR70=
270
+ golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
271
+ golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=
272
+ golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
273
+ golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
274
+ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
275
+ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
276
+ golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
277
+ golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
278
+ golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
279
+ golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
280
+ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
281
+ golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
282
+ golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
283
+ golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
284
+ golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
285
+ golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
286
+ golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
287
+ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
288
+ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
289
+ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
290
+ golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
291
+ golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
292
+ golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
293
+ golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
294
+ golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
295
+ golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
296
+ golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
297
+ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
298
+ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
299
+ golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
300
+ golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
301
+ golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
302
+ golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
303
+ golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
304
+ golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
305
+ golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
306
+ golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
307
+ golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
308
+ golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
309
+ golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
310
+ golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
311
+ gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
312
+ gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
313
+ google.golang.org/api v0.272.0 h1:eLUQZGnAS3OHn31URRf9sAmRk3w2JjMx37d2k8AjJmA=
314
+ google.golang.org/api v0.272.0/go.mod h1:wKjowi5LNJc5qarNvDCvNQBn3rVK8nSy6jg2SwRwzIA=
315
+ google.golang.org/appengine/v2 v2.0.6 h1:LvPZLGuchSBslPBp+LAhihBeGSiRh1myRoYK4NtuBIw=
316
+ google.golang.org/appengine/v2 v2.0.6/go.mod h1:WoEXGoXNfa0mLvaH5sV3ZSGXwVmy8yf7Z1JKf3J3wLI=
317
+ google.golang.org/genproto v0.0.0-20260217215200-42d3e9bedb6d h1:vsOm753cOAMkt76efriTCDKjpCbK18XGHMJHo0JUKhc=
318
+ google.golang.org/genproto v0.0.0-20260217215200-42d3e9bedb6d/go.mod h1:0oz9d7g9QLSdv9/lgbIjowW1JoxMbxmBVNe8i6tORJI=
319
+ google.golang.org/genproto/googleapis/api v0.0.0-20260217215200-42d3e9bedb6d h1:EocjzKLywydp5uZ5tJ79iP6Q0UjDnyiHkGRWxuPBP8s=
320
+ google.golang.org/genproto/googleapis/api v0.0.0-20260217215200-42d3e9bedb6d/go.mod h1:48U2I+QQUYhsFrg2SY6r+nJzeOtjey7j//WBESw+qyQ=
321
+ google.golang.org/genproto/googleapis/rpc v0.0.0-20260311181403-84a4fc48630c h1:xgCzyF2LFIO/0X2UAoVRiXKU5Xg6VjToG4i2/ecSswk=
322
+ google.golang.org/genproto/googleapis/rpc v0.0.0-20260311181403-84a4fc48630c/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
323
+ google.golang.org/grpc v1.79.2 h1:fRMD94s2tITpyJGtBBn7MkMseNpOZU8ZxgC3MMBaXRU=
324
+ google.golang.org/grpc v1.79.2/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=
325
+ google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
326
+ google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
327
+ google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
328
+ google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
329
+ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
330
+ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
331
+ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
332
+ gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
333
+ gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
334
+ gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
335
+ gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
336
+ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
337
+ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
338
+ gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
339
+ gorm.io/gorm v1.31.0 h1:0VlycGreVhK7RF/Bwt51Fk8v0xLiiiFdbGDPIZQ7mJY=
340
+ gorm.io/gorm v1.31.0/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
341
+ modernc.org/cc/v4 v4.26.5 h1:xM3bX7Mve6G8K8b+T11ReenJOT+BmVqQj0FY5T4+5Y4=
342
+ modernc.org/cc/v4 v4.26.5/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
343
+ modernc.org/ccgo/v4 v4.28.1 h1:wPKYn5EC/mYTqBO373jKjvX2n+3+aK7+sICCv4Fjy1A=
344
+ modernc.org/ccgo/v4 v4.28.1/go.mod h1:uD+4RnfrVgE6ec9NGguUNdhqzNIeeomeXf6CL0GTE5Q=
345
+ modernc.org/fileutil v1.3.40 h1:ZGMswMNc9JOCrcrakF1HrvmergNLAmxOPjizirpfqBA=
346
+ modernc.org/fileutil v1.3.40/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc=
347
+ modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
348
+ modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
349
+ modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
350
+ modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
351
+ modernc.org/libc v1.66.10 h1:yZkb3YeLx4oynyR+iUsXsybsX4Ubx7MQlSYEw4yj59A=
352
+ modernc.org/libc v1.66.10/go.mod h1:8vGSEwvoUoltr4dlywvHqjtAqHBaw0j1jI7iFBTAr2I=
353
+ modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
354
+ modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
355
+ modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
356
+ modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
357
+ modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
358
+ modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
359
+ modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
360
+ modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
361
+ modernc.org/sqlite v1.39.1 h1:H+/wGFzuSCIEVCvXYVHX5RQglwhMOvtHSv+VtidL2r4=
362
+ modernc.org/sqlite v1.39.1/go.mod h1:9fjQZ0mB1LLP0GYrp39oOJXx/I2sxEnZtzCmEQIKvGE=
363
+ modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
364
+ modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
365
+ modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
366
+ modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
367
+ nhooyr.io/websocket v1.8.17 h1:KEVeLJkUywCKVsnLIDlD/5gtayKp8VoCkksHCGGfT9Y=
368
+ nhooyr.io/websocket v1.8.17/go.mod h1:rN9OFWIUwuxg4fR5tELlYC04bXYowCP9GX47ivo2l+c=
369
+ nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
370
+ rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
371
+ rsc.io/qr v0.2.0 h1:6vBLea5/NRMVTz8V66gipeLycZMl/+UlFmk8DvqQ6WY=
372
+ rsc.io/qr v0.2.0/go.mod h1:IF+uZjkb9fqyeF/4tlBoynqmQxUoPfWEKh921coOuXs=
goreleaser.Dockerfile ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ FROM scratch
2
+ ARG TARGETOS
3
+ ARG TARGETARCH
4
+ COPY ${TARGETOS}/${TARGETARCH}/fsb /app/fsb
5
+ ENTRYPOINT ["/app/fsb", "run"]
internal/bot/client.go ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/commands/add_token.go ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ }
logs/app.log ADDED
The diff for this file is too large to render. See raw diff
 
pkg/qrlogin/encoder.go ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is a part of EverythingSuckz/TG-FileStreamBot
2
+ // And is licenced under the Affero General Public License.
3
+ // Any distributions of this code MUST be accompanied by a copy of the AGPL
4
+ // with proper attribution to the original author(s).
5
+
6
+ package qrlogin
7
+
8
+ import (
9
+ "bytes"
10
+ "encoding/base64"
11
+ "encoding/binary"
12
+ "errors"
13
+ "strings"
14
+
15
+ "github.com/gotd/td/session"
16
+ )
17
+
18
+ func EncodeToPyrogramSession(data *session.Data, appID int32) (string, error) {
19
+ buf := new(bytes.Buffer)
20
+ if err := buf.WriteByte(byte(data.DC)); err != nil {
21
+ return "", err
22
+ }
23
+ if err := binary.Write(buf, binary.BigEndian, appID); err != nil {
24
+ return "", err
25
+ }
26
+ var testMode byte
27
+ if data.Config.TestMode {
28
+ testMode = 1
29
+ }
30
+ if err := buf.WriteByte(testMode); err != nil {
31
+ return "", err
32
+ }
33
+ if len(data.AuthKey) != 256 {
34
+ return "", errors.New("auth key must be 256 bytes long")
35
+ }
36
+ if _, err := buf.Write(data.AuthKey); err != nil {
37
+ return "", err
38
+ }
39
+ if len(data.AuthKeyID) != 8 {
40
+ return "", errors.New("auth key ID must be 8 bytes long")
41
+ }
42
+ if _, err := buf.Write(data.AuthKeyID); err != nil {
43
+ return "", err
44
+ }
45
+ if err := buf.WriteByte(0); err != nil {
46
+ return "", err
47
+ }
48
+ // Convert the bytes buffer to a base64 string
49
+ encodedString := base64.URLEncoding.EncodeToString(buf.Bytes())
50
+ trimmedEncoded := strings.TrimRight(encodedString, "=")
51
+ return trimmedEncoded, nil
52
+ }
pkg/qrlogin/qrcode.go ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // This file is a part of EverythingSuckz/TG-FileStreamBot
2
+ // And is licenced under the Affero General Public License.
3
+ // Any distributions of this code MUST be accompanied by a copy of the AGPL
4
+ // with proper attribution to the original author(s).
5
+
6
+ package qrlogin
7
+
8
+ import (
9
+ "bufio"
10
+ "context"
11
+ "encoding/json"
12
+ "errors"
13
+ "fmt"
14
+ "os"
15
+ "runtime"
16
+ "strings"
17
+ "time"
18
+
19
+ "github.com/gotd/td/session"
20
+ "github.com/gotd/td/telegram"
21
+ "github.com/gotd/td/telegram/auth/qrlogin"
22
+ "github.com/gotd/td/tg"
23
+ "github.com/gotd/td/tgerr"
24
+ "github.com/mdp/qrterminal"
25
+ )
26
+
27
+ type CustomWriter struct {
28
+ LineLength int
29
+ }
30
+
31
+ func (w *CustomWriter) Write(p []byte) (n int, err error) {
32
+ for _, c := range p {
33
+ if c == '\n' {
34
+ w.LineLength++
35
+ }
36
+ }
37
+ return os.Stdout.Write(p)
38
+ }
39
+
40
+ func printQrCode(data string, writer *CustomWriter) {
41
+ qrterminal.GenerateHalfBlock(data, qrterminal.L, writer)
42
+ }
43
+
44
+ func clearQrCode(writer *CustomWriter) {
45
+ for i := 0; i < writer.LineLength; i++ {
46
+ fmt.Printf("\033[F\033[K")
47
+ }
48
+ writer.LineLength = 0
49
+ }
50
+
51
+ func GenerateQRSession(apiId int, apiHash string) error {
52
+ ctx, cancel := context.WithCancel(context.Background())
53
+ defer cancel()
54
+ fmt.Println("Generating QR session...")
55
+ reader := bufio.NewReader(os.Stdin)
56
+ dispatcher := tg.NewUpdateDispatcher()
57
+ loggedIn := qrlogin.OnLoginToken(dispatcher)
58
+ sessionStorage := &session.StorageMemory{}
59
+ client := telegram.NewClient(apiId, apiHash, telegram.Options{
60
+ UpdateHandler: dispatcher,
61
+ SessionStorage: sessionStorage,
62
+ Device: telegram.DeviceConfig{
63
+ DeviceModel: "Pyrogram",
64
+ SystemVersion: runtime.GOOS,
65
+ AppVersion: "2.0",
66
+ },
67
+ })
68
+ var stringSession string
69
+ qrWriter := &CustomWriter{}
70
+ tickerCtx, cancelTicker := context.WithCancel(context.Background())
71
+ err := client.Run(ctx, func(ctx context.Context) error {
72
+ authorization, err := client.QR().Auth(ctx, loggedIn, func(ctx context.Context, token qrlogin.Token) error {
73
+ if qrWriter.LineLength == 0 {
74
+ fmt.Printf("\033[F\033[K")
75
+ }
76
+ clearQrCode(qrWriter)
77
+ printQrCode(token.URL(), qrWriter)
78
+ qrWriter.Write([]byte("\nTo log in, Open your Telegram app and go to Settings > Devices > Scan QR and scan the QR code.\n"))
79
+ go func(ctx context.Context) {
80
+ ticker := time.NewTicker(1 * time.Second)
81
+ defer ticker.Stop()
82
+ for {
83
+ select {
84
+ case <-ctx.Done():
85
+ return
86
+ case <-ticker.C:
87
+ expiresIn := time.Until(token.Expires())
88
+ if expiresIn <= 0 {
89
+ return
90
+ }
91
+ fmt.Printf("\rThis code expires in %s", expiresIn.Truncate(time.Second))
92
+ }
93
+ }
94
+ }(tickerCtx)
95
+ return nil
96
+ })
97
+ if err != nil {
98
+ if tgerr.Is(err, "SESSION_PASSWORD_NEEDED") {
99
+ cancelTicker()
100
+ fmt.Println("\n2FA password is required, enter it below: ")
101
+ passkey, _ := reader.ReadString('\n')
102
+ strippedPasskey := strings.TrimSpace(passkey)
103
+ authorization, err = client.Auth().Password(ctx, strippedPasskey)
104
+ if err != nil {
105
+ if err.Error() == "invalid password" {
106
+ fmt.Println("Invalid password, please try again.")
107
+ }
108
+ fmt.Println("Error while logging in: ", err)
109
+ return nil
110
+ }
111
+ }
112
+ }
113
+ if authorization == nil {
114
+ cancel()
115
+ return errors.New("authorization is nil")
116
+ }
117
+ user, err := client.Self(ctx)
118
+ if err != nil {
119
+ return err
120
+ }
121
+ if user.Username == "" {
122
+ fmt.Println("Logged in as ", user.FirstName, user.LastName)
123
+ } else {
124
+ fmt.Println("Logged in as @", user.Username)
125
+ }
126
+ res, _ := sessionStorage.LoadSession(ctx)
127
+ type jsonDataStruct struct {
128
+ Version int
129
+ Data session.Data
130
+ }
131
+ var jsonData jsonDataStruct
132
+ json.Unmarshal(res, &jsonData)
133
+ stringSession, err = EncodeToPyrogramSession(&jsonData.Data, int32(apiId))
134
+ if err != nil {
135
+ return err
136
+ }
137
+ fmt.Println("Your pyrogram session string:", stringSession)
138
+ client.API().MessagesSendMessage(
139
+ ctx,
140
+ &tg.MessagesSendMessageRequest{
141
+ NoWebpage: true,
142
+ Peer: &tg.InputPeerSelf{},
143
+ Message: "Your pyrogram session string: " + stringSession,
144
+ },
145
+ )
146
+ return nil
147
+ })
148
+ if err != nil {
149
+ return err
150
+ }
151
+ return nil
152
+ }
sessions/worker-8351384724.session ADDED
Binary file (24.6 kB). View file
 
sessions/worker-8494492850.session ADDED
Binary file (24.6 kB). View file
 
sessions/worker-8610183721.session ADDED
Binary file (24.6 kB). View file
 
sessions/worker-8672752909.session ADDED
Binary file (24.6 kB). View file
 
sessions/worker-8688814148.session ADDED
Binary file (24.6 kB). View file
 
sessions/worker-8707468210.session ADDED
Binary file (24.6 kB). View file
 
sessions/worker-8710408202.session ADDED
Binary file (24.6 kB). View file
 
sessions/worker-8721328807.session ADDED
Binary file (24.6 kB). View file
 
sessions/worker-8735857251.session ADDED
Binary file (24.6 kB). View file
 
sessions/worker-8739944102.session ADDED
Binary file (24.6 kB). View file
 
test-clone/.gitattributes ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Auto detect text files and perform LF normalization
2
+ * text=auto
3
+ fsb.exe filter=lfs diff=lfs merge=lfs -text
test-clone/.github/workflows/notify.yml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Notify on Telegram
2
+
3
+ on:
4
+ push:
5
+ release:
6
+ types: published
7
+ issue_comment:
8
+ types: created
9
+ watch:
10
+ types: started
11
+ pull_request_review_comment:
12
+ types: created
13
+ pull_request:
14
+ types: [opened, closed, reopened]
15
+ issues:
16
+ types: [opened, pinned, closed, reopened]
17
+ jobs:
18
+ notify:
19
+ runs-on: ubuntu-latest
20
+ steps:
21
+ - uses: actions/checkout@v6
22
+ - name: Notify the commit on Telegram.
23
+ uses: EverythingSuckz/github-telegram-notify@main
24
+ with:
25
+ bot_token: '${{ secrets.BOT_TOKEN }}'
26
+ chat_id: '${{ secrets.CHAT_ID }}'
27
+ topic_id: '${{ secrets.TOPIC_ID }}'
test-clone/.github/workflows/release.yml ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Goreleaser
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ inputs:
6
+ goReleaserArgs:
7
+ description: "Args goreleaser"
8
+ required: false
9
+ default: "--clean"
10
+ push:
11
+ tags:
12
+ - "v*"
13
+
14
+ permissions:
15
+ contents: write
16
+ packages: write
17
+
18
+ jobs:
19
+ goreleaser:
20
+ runs-on: ubuntu-latest
21
+ steps:
22
+ - name: Checkout
23
+ uses: actions/checkout@v6
24
+ with:
25
+ fetch-depth: 0
26
+ - run: git fetch --force --tags
27
+ - name: Set up QEMU
28
+ uses: docker/setup-qemu-action@v3
29
+ with:
30
+ platforms: arm64
31
+ - name: Set up Docker Buildx
32
+ uses: docker/setup-buildx-action@v3
33
+ with:
34
+ driver: docker-container
35
+ - name: Set up Go
36
+ uses: actions/setup-go@v6
37
+ with:
38
+ go-version: 1.25
39
+ - name: Import GPG key
40
+ id: import_gpg
41
+ uses: crazy-max/ghaction-import-gpg@v6
42
+ with:
43
+ gpg_private_key: ${{ secrets.GPG_PRIVATE_KEY }}
44
+ passphrase: ${{ secrets.PASSPHRASE }}
45
+ - name: Log in to GHCR
46
+ uses: docker/login-action@v3
47
+ with:
48
+ registry: ghcr.io
49
+ username: ${{ github.actor }}
50
+ password: ${{ secrets.GITHUB_TOKEN }}
51
+ - name: Run GoReleaser
52
+ uses: goreleaser/goreleaser-action@v6
53
+ with:
54
+ distribution: goreleaser
55
+ version: latest
56
+ args: release ${{ github.event.inputs.goReleaserArgs }}
57
+ env:
58
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
59
+ GPG_FINGERPRINT: ${{ steps.import_gpg.outputs.fingerprint }}
test-clone/.gitignore ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Binaries for programs and plugins
2
+ *.exe
3
+ *.exe~
4
+ *.dll
5
+ *.so
6
+ *.dylib
7
+
8
+ # Test binary, built with `go test -c`
9
+ *.test
10
+
11
+ # Output of the go coverage tool, specifically when used with LiteIDE
12
+ *.out
13
+
14
+ # Dependency directories
15
+ vendor/
16
+
17
+ # Go workspace file
18
+ go.work
19
+
20
+ # Env files
21
+ fsb.env
22
+ .env
23
+
24
+ # Session files
25
+ *.session*
26
+ sessons/
27
+
28
+ # build folder
29
+ dist/
30
+
31
+ # logs folder
32
+ logs/
33
+ *.log