-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
411 lines (333 loc) · 11 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
package main
import (
"context"
"fmt"
"log"
"net/http"
"net/url"
"os"
"os/signal"
"path/filepath"
"sort"
"strings"
"syscall"
"time"
"github.com/go-telegram/bot"
"github.com/go-telegram/bot/models"
"github.com/joho/godotenv"
"github.com/mkevac/markodownloadbot/stats"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
var (
adminUsername string
adminChatID int64
tmpDir string
isLocal bool
)
func main() {
if err := godotenv.Load(); err != nil {
log.Printf("Error loading .env file: %v", err)
}
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()
adminUsername = os.Getenv("ADMIN_USERNAME")
log.Printf("Admin username: %s", adminUsername)
isLocal = os.Getenv("IS_LOCAL") == "true"
dirBase := "/app/data"
if isLocal {
dirBase = "./data"
}
// Initialize the stats package with the calculated dirBase
stats.Init(dirBase)
var err error
tmpDir, err = os.MkdirTemp(dirBase, "telegram-bot-api-*")
if err != nil {
log.Fatalf("Failed to create temporary directory: %v", err)
}
if err := os.Chmod(tmpDir, 0755); err != nil {
log.Fatalf("Failed to set permissions on temporary directory: %v", err)
}
defer func() {
log.Printf("Removing temporary directory: %s", tmpDir)
if err := os.RemoveAll(tmpDir); err != nil {
log.Printf("Failed to remove temporary directory: %v", err)
}
}()
log.Printf("Using temporary directory: %s", tmpDir)
// Use http.FileServer to serve files from the specified directory
fileServer := http.FileServer(http.Dir(tmpDir))
// Handle all requests by serving the file from the directory
http.Handle("/", fileServer)
log.Println("Serving files on :8080")
go http.ListenAndServe(":8080", nil)
serverURL := "http://telegram-bot-api:8081"
if isLocal {
serverURL = "http://localhost:8081"
}
opts := []bot.Option{
bot.WithDefaultHandler(handler),
bot.WithServerURL(serverURL),
}
var b *bot.Bot
for {
b, err = bot.New(os.Getenv("TELEGRAM_BOT_API_TOKEN"), opts...)
if err != nil {
log.Printf("Error creating bot: %s", err)
time.Sleep(time.Second * 5)
} else {
break
}
}
b.RegisterHandler(bot.HandlerTypeMessageText, "/stats", bot.MatchTypeExact, statsHandler)
b.RegisterHandler(bot.HandlerTypeMessageText, "/audio", bot.MatchTypePrefix, audioHandler)
b.RegisterHandler(bot.HandlerTypeMessageText, "/help", bot.MatchTypeExact, helpHandler)
b.RegisterHandler(bot.HandlerTypeMessageText, "/start", bot.MatchTypeExact, helpHandler)
success, err := b.SetMyCommands(ctx, &bot.SetMyCommandsParams{
Commands: []models.BotCommand{
{Command: "start", Description: "Start the bot"},
{Command: "help", Description: "Show help information"},
{Command: "audio", Description: "Download audio"},
{Command: "stats", Description: "Show stats (admin only)"},
},
})
if err != nil {
log.Printf("Error setting bot commands: %v", err)
} else if !success {
log.Println("SetMyCommands did not return true")
} else {
log.Println("Bot commands set successfully")
}
go b.Start(ctx)
<-ctx.Done()
log.Println("Received interrupt signal")
}
func saveAdminChatID(username string, chatID int64) {
if adminUsername != "" && adminUsername == username {
adminChatID = chatID
}
}
func sendMessageToAdmin(ctx context.Context, b *bot.Bot, text string) {
if adminChatID == 0 {
return
}
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: adminChatID,
Text: text,
})
}
func cleanupAndVerifyInput(input string) (string, error) {
byLines := strings.Split(input, "\n")
if len(byLines) > 1 {
return "", fmt.Errorf("input should be a single line")
}
// remove leading and trailing whitespaces
input = strings.TrimSpace(input)
// remove leading and trailing quotes
input = strings.Trim(input, "\"")
// check if input is a valid URL
u, err := url.Parse(input)
if err != nil || u.Scheme == "" || u.Host == "" {
return "", fmt.Errorf("invalid URL")
}
return input, nil
}
func statsHandler(ctx context.Context, b *bot.Bot, update *models.Update) {
log.Printf("[%s]: received stats command", update.Message.From.Username)
saveAdminChatID(update.Message.From.Username, update.Message.Chat.ID)
if update.Message.From.Username != adminUsername {
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: "You are not authorized to use this command",
})
sendMessageToAdmin(ctx, b, fmt.Sprintf("Unauthorized access to /stats command from @%s", update.Message.From.Username))
return
}
periods := []string{"day", "week", "month", "overall"}
// Send summary stats first
var summaryMsg strings.Builder
summaryMsg.WriteString("*Summary Stats*\n\n")
for _, period := range periods {
stats := stats.GetStats(period)
totalVideoRequests := sum(stats.VideoRequests)
totalAudioRequests := sum(stats.AudioRequests)
caser := cases.Title(language.English)
summaryMsg.WriteString(fmt.Sprintf("*%s:* V:`%d` A:`%d` E:`%d`\n",
caser.String(period),
totalVideoRequests,
totalAudioRequests,
sum(stats.DownloadErrors)))
}
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: summaryMsg.String(),
ParseMode: models.ParseModeMarkdown,
})
// Send detailed per-period stats
for _, period := range periods {
stats := stats.GetStats(period)
var detailMsg strings.Builder
detailMsg.WriteString(fmt.Sprintf("*Detailed Stats \\- %s*\n\n", cases.Title(language.English).String(period)))
// Get top 10 users by total activity
type userStats struct {
username string
total int
}
users := make([]userStats, 0)
for username, videoCount := range stats.VideoRequests {
total := videoCount +
stats.AudioRequests[username] +
stats.DownloadErrors[username] +
stats.UnrecognizedCommands[username]
users = append(users, userStats{username, total})
}
// Sort users by total activity
sort.Slice(users, func(i, j int) bool {
return users[i].total > users[j].total
})
// Show top 10 users
maxUsers := 10
if len(users) < maxUsers {
maxUsers = len(users)
}
detailMsg.WriteString("Top Users:\n")
for i := 0; i < maxUsers; i++ {
username := users[i].username
escapedUsername := bot.EscapeMarkdown(username)
detailMsg.WriteString(fmt.Sprintf("@%s: V:`%d` A:`%d` E:`%d`\n",
escapedUsername,
stats.VideoRequests[username],
stats.AudioRequests[username],
stats.DownloadErrors[username]))
}
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: detailMsg.String(),
ParseMode: models.ParseModeMarkdown,
})
}
}
func handler(ctx context.Context, b *bot.Bot, update *models.Update) {
if update.Message == nil {
log.Println("Received update with nil Message")
return
}
handleDownload(ctx, b, update, update.Message.Text, false)
}
func audioHandler(ctx context.Context, b *bot.Bot, update *models.Update) {
if update.Message == nil {
log.Println("Received audio command with nil Message")
return
}
input := strings.TrimSpace(strings.TrimPrefix(update.Message.Text, "/audio"))
handleDownload(ctx, b, update, input, true)
}
func handleDownload(ctx context.Context, b *bot.Bot, update *models.Update, input string, audioOnly bool) {
log.Printf("[%s]: received message: '%s'", update.Message.From.Username, update.Message.Text)
saveAdminChatID(update.Message.From.Username, update.Message.Chat.ID)
input, err := cleanupAndVerifyInput(input)
if err != nil {
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: "Please send me a valid video or audio link",
})
sendMessageToAdmin(ctx, b, fmt.Sprintf("Unrecognized command from @%s: %s", update.Message.From.Username, update.Message.Text))
stats.AddUnrecognizedCommand(update.Message.From.Username)
return
}
if audioOnly {
stats.AddAudioRequest(update.Message.From.Username)
} else {
stats.AddVideoRequest(update.Message.From.Username)
}
var mediaType string
if audioOnly {
mediaType = "audio"
} else {
mediaType = "video"
}
log.Printf("[%s]: %s url: '%s'", update.Message.From.Username, mediaType, input)
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: fmt.Sprintf("I will download the %s and send it to you shortly.", mediaType),
})
cookiesFile := os.Getenv("COOKIES_FILE")
if cookiesFile == "" {
cookiesFile = "/app/cookies.txt"
}
log.Printf("Using cookies file: %s", cookiesFile)
media, err := DownloadMedia(input, update.Message.From.Username, tmpDir, cookiesFile, audioOnly)
if err != nil {
log.Printf("Error downloading %s: %s", mediaType, err)
stats.AddDownloadError(update.Message.From.Username)
errorMsg := fmt.Sprintf("I'm sorry, @%s. I'm afraid I can't do that. Error downloading %s from %s: %s",
update.Message.From.Username, mediaType, input, err.Error())
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: errorMsg,
})
sendMessageToAdmin(ctx, b, errorMsg)
return
}
fileSize, err := media.GetFileSize()
if err != nil {
log.Printf("Error getting file size: %s", err)
} else {
log.Printf("[%s]: %s downloaded to '%s' (size: %d bytes)", update.Message.From.Username, mediaType, media.Path, fileSize)
}
// fix media path if local
var pathToSend string
if isLocal {
pathToSend = filepath.Join("/app", media.Path)
} else {
pathToSend = media.Path
}
log.Printf("[%s]: media path to send: %s", update.Message.From.Username, pathToSend)
if audioOnly {
b.SendAudio(ctx, &bot.SendAudioParams{
ChatID: update.Message.Chat.ID,
Audio: &models.InputFileString{Data: "file://" + pathToSend},
})
} else {
b.SendVideo(ctx, &bot.SendVideoParams{
ChatID: update.Message.Chat.ID,
Video: &models.InputFileString{Data: "file://" + pathToSend},
Width: media.Width,
Height: media.Height,
Duration: (int)(media.Duration),
})
}
log.Printf("[%s]: %s sent", update.Message.From.Username, mediaType)
if err := media.Delete(); err != nil {
log.Printf("Error removing %s file: %s", mediaType, err)
}
log.Printf("[%s]: %s removed", update.Message.From.Username, mediaType)
}
func helpHandler(ctx context.Context, b *bot.Bot, update *models.Update) {
log.Printf("[%s]: received message: '%s'", update.Message.From.Username, update.Message.Text)
helpMessage := `<b>Welcome to the Marko Download Bot!</b>
Here's how you can use me:
1. <b>Download Video:</b>
Simply send a video URL, and I'll download and send the video to you.
2. <code>/audio [URL]</code>:
Use this command followed by an audio URL to download and receive audio files.
3. <code>/stats</code>:
(Admin only) View usage statistics of the bot.
4. <code>/help</code> or <code>/start</code>:
Display this help message.
To download media, just send me a valid video or audio link. I'll take care of the rest!
Note: Please ensure you have the rights to download and use the media you request.`
b.SendMessage(ctx, &bot.SendMessageParams{
ChatID: update.Message.Chat.ID,
Text: helpMessage,
ParseMode: models.ParseModeHTML,
})
}
// Helper function to sum map values
func sum(m map[string]int) int {
total := 0
for _, v := range m {
total += v
}
return total
}