Repository navigation
Expand file tree
/
Copy pathhandlers.py
More file actions
726 lines (598 loc) · 29.2 KB
/
Copy pathhandlers.py
File metadata and controls
726 lines (598 loc) · 29.2 KB
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
"""
Bot handlers module for YTDL Telegram Bot.
Contains all Telegram command and callback handlers.
"""
import os
import gc
import asyncio
import time
import logging
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import ContextTypes
from config import load_config, is_user_allowed, check_disk_space, check_ffmpeg
from database import (
add_subscription, remove_subscription, get_user_subscriptions,
get_all_subscriptions, get_user_settings, update_user_settings,
remove_legacy_numeric_subscriptions,
)
from downloader import (
download_content, get_video_info,
get_channel_info, get_playlist_info, is_playlist, is_twitch_channel_id,
is_legacy_numeric_channel_id,
)
from uploader import upload_video_streaming, upload_audio_streaming, split_video, crop_to_square
from telegram_utils import tg_retry
from upgrader import upgrade_yt_dlp
from cookie_manager import MAX_COOKIE_BYTES, is_cookie_admin, install_cookies
logger = logging.getLogger(__name__)
# Track cancelled tasks
cancelled_tasks = set()
# Track "stop & upload" requests for live recordings
stopped_tasks = set()
# --- Command Handlers ---
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /start and /help commands."""
chat_id = update.effective_chat.id
if not is_user_allowed(chat_id):
await context.bot.send_message(chat_id=chat_id, text="Sorry, you are not authorized to use this bot.")
return
help_text = """🎬 **YouTube Downloader Bot**
Send me a URL to download in 1080p (default).
**Video Quality Commands:**
• `/1080 <URL>` - Download in 1080p
• `/720 <URL>` - Download in 720p
• `/480 <URL>` - Download in 480p
• `/240 <URL>` - Download in 240p
**Audio Command:**
• `/music <URL>` - Download audio only (M4A)
**Playlist Command:**
• `/playlist <URL>` - Download entire playlist
**Maintenance Command:**
• `/upgrade` - Upgrade yt-dlp to the nightly channel
• Cookie admins: privately send cookie.txt / cookies.txt to update cookies
**Subscription Commands:**
• `/subscribe <channel_url>` - Subscribe to a channel
• `/unsubscribe <channel_url>` - Unsubscribe from a channel
• `/subscriptions` - List your subscriptions
Or just send a URL directly for 1080p video.
"""
await context.bot.send_message(chat_id=chat_id, text=help_text, parse_mode='Markdown')
async def handle_upgrade(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /upgrade by updating yt-dlp without blocking the bot event loop."""
chat_id = update.effective_chat.id
message_id = update.message.message_id
if not is_user_allowed(chat_id):
await tg_retry(
context.bot.send_message,
chat_id=chat_id,
text="Sorry, you are not authorized.",
reply_to_message_id=message_id,
)
return
has_active_downloads = context.application.bot_data.get(
'has_active_downloads'
)
if has_active_downloads and has_active_downloads():
await tg_retry(
context.bot.send_message,
chat_id=chat_id,
text=(
"⛔ yt-dlp upgrade blocked because a download task is active. "
"Please try again after all tasks finish."
),
reply_to_message_id=message_id,
)
return
status_msg = await tg_retry(
context.bot.send_message,
chat_id=chat_id,
text="⬆️ Upgrading yt-dlp to nightly...",
reply_to_message_id=message_id,
)
loop = asyncio.get_running_loop()
success, output = await loop.run_in_executor(None, upgrade_yt_dlp)
# Telegram messages are limited to 4096 characters; retain the useful tail.
output = output[-3500:]
if success:
text = f"✅ yt-dlp nightly upgrade completed.\n\n{output}"
else:
text = f"❌ yt-dlp nightly upgrade failed.\n\n{output}"
await tg_retry(status_msg.edit_text, text)
async def handle_music_command(update: Update, context: ContextTypes.DEFAULT_TYPE, request_queue):
"""Handle /music command for audio-only downloads."""
chat_id = update.effective_chat.id
message_id = update.message.message_id
if not is_user_allowed(chat_id):
await context.bot.send_message(chat_id=chat_id, text="Sorry, you are not authorized.", reply_to_message_id=message_id)
return
if not context.args:
await context.bot.send_message(chat_id=chat_id, text="Usage: `/music <URL>`", reply_to_message_id=message_id, parse_mode='Markdown')
return
url = context.args[0]
if not url.startswith(('http://', 'https://')):
await context.bot.send_message(chat_id=chat_id, text="Please send a valid URL.", reply_to_message_id=message_id)
return
status_msg = await context.bot.send_message(chat_id=chat_id, text="🔍 Analyzing URL...", reply_to_message_id=message_id)
loop = asyncio.get_running_loop()
is_pl = await loop.run_in_executor(None, is_playlist, url)
if is_pl:
await status_msg.edit_text("📋 Audio Playlist detected. Adding to queue...")
playlist_queue = context.application.bot_data.get('playlist_queue')
if playlist_queue:
await playlist_queue.put((chat_id, url, message_id, -1, status_msg))
await status_msg.edit_text("📋 Audio Playlist added to queue. Sequential processing started...")
else:
await status_msg.edit_text("❌ Error getting playlist queue.")
else:
await status_msg.edit_text("🎵 Adding to queue (Audio M4A)...")
await request_queue.put((chat_id, url, message_id, -1, status_msg))
q_size = request_queue.qsize()
await status_msg.edit_text(f"🎵 Added to queue (Audio M4A). Queue Depth: {q_size}")
async def handle_mp3_command(update: Update, context: ContextTypes.DEFAULT_TYPE, request_queue):
"""Handle /mp3 command for MP3 audio downloads."""
chat_id = update.effective_chat.id
message_id = update.message.message_id
if not is_user_allowed(chat_id):
await context.bot.send_message(chat_id=chat_id, text="Sorry, you are not authorized.", reply_to_message_id=message_id)
return
if not context.args:
await context.bot.send_message(chat_id=chat_id, text="Usage: `/mp3 <URL>`", reply_to_message_id=message_id, parse_mode='Markdown')
return
url = context.args[0]
if not url.startswith(('http://', 'https://')):
await context.bot.send_message(chat_id=chat_id, text="Please send a valid URL.", reply_to_message_id=message_id)
return
status_msg = await context.bot.send_message(chat_id=chat_id, text="🔍 Analyzing URL...", reply_to_message_id=message_id)
loop = asyncio.get_running_loop()
is_pl = await loop.run_in_executor(None, is_playlist, url)
if is_pl:
await status_msg.edit_text("📋 Audio Playlist detected. Adding to queue...")
playlist_queue = context.application.bot_data.get('playlist_queue')
if playlist_queue:
await playlist_queue.put((chat_id, url, message_id, -2, status_msg))
await status_msg.edit_text("📋 Audio Playlist added to queue. Sequential processing started...")
else:
await status_msg.edit_text("❌ Error getting playlist queue.")
else:
await status_msg.edit_text("🎵 Adding to queue (Audio MP3)...")
await request_queue.put((chat_id, url, message_id, -2, status_msg))
q_size = request_queue.qsize()
await status_msg.edit_text(f"🎵 Added to queue (Audio MP3). Queue Depth: {q_size}")
async def handle_quality_command(update: Update, context: ContextTypes.DEFAULT_TYPE, request_queue):
"""Handle quality-specific download commands like /720, /480, /240."""
chat_id = update.effective_chat.id
message_id = update.message.message_id
if not is_user_allowed(chat_id):
await context.bot.send_message(chat_id=chat_id, text="Sorry, you are not authorized.", reply_to_message_id=message_id)
return
command = update.message.text.split()[0].lower()
quality_map = {'/download': 1080, '/1080': 1080, '/720': 720, '/480': 480, '/360': 360, '/240': 240}
max_height = quality_map.get(command, 1080)
if not context.args:
await context.bot.send_message(chat_id=chat_id, text=f"Usage: `{command} <URL>`", reply_to_message_id=message_id, parse_mode='Markdown')
return
url = context.args[0]
if not url.startswith(('http://', 'https://')):
await context.bot.send_message(chat_id=chat_id, text="Please send a valid URL.", reply_to_message_id=message_id)
return
status_msg = await context.bot.send_message(chat_id=chat_id, text=f"📥 Adding to queue ({max_height}p)...", reply_to_message_id=message_id)
await request_queue.put((chat_id, url, message_id, max_height, status_msg))
q_size = request_queue.qsize()
await status_msg.edit_text(f"📥 Added to queue ({max_height}p). Queue Depth: {q_size}")
async def handle_playlist_command(update: Update, context: ContextTypes.DEFAULT_TYPE, playlist_queue):
"""Handle /playlist command for downloading playlists."""
chat_id = update.effective_chat.id
message_id = update.message.message_id
if not is_user_allowed(chat_id):
await context.bot.send_message(chat_id=chat_id, text="Sorry, you are not authorized.", reply_to_message_id=message_id)
return
if not context.args:
await context.bot.send_message(chat_id=chat_id, text="Usage: `/playlist <URL>`", reply_to_message_id=message_id, parse_mode='Markdown')
return
url = context.args[0]
max_height = 1080
# Optional quality argument
if len(context.args) > 1:
try:
max_height = int(context.args[1])
except ValueError:
pass
if not url.startswith(('http://', 'https://')):
await context.bot.send_message(chat_id=chat_id, text="Please send a valid URL.", reply_to_message_id=message_id)
return
# Get playlist info first
try:
status_msg = await context.bot.send_message(chat_id=chat_id, text="📋 Getting playlist info...", reply_to_message_id=message_id)
loop = asyncio.get_running_loop()
info = await loop.run_in_executor(None, lambda: get_playlist_info(url))
await status_msg.edit_text(
f"📋 **Playlist Found**\n\n"
f"📁 {info['title']}\n"
f"🎬 {info['count']} videos\n\n"
f"Starting download in {max_height}p..."
)
except Exception as e:
await context.bot.send_message(chat_id=chat_id, text=f"❌ Failed to get playlist info: {e}", reply_to_message_id=message_id)
return
await playlist_queue.put((chat_id, url, message_id, max_height, status_msg))
await status_msg.edit_text(f"📋 Playlist added to queue ({max_height}p). Sequential processing started...")
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE, request_queue):
"""Handle direct URL messages."""
chat_id = update.effective_chat.id
message_id = update.message.message_id
if not is_user_allowed(chat_id):
await context.bot.send_message(chat_id=chat_id, text="Sorry, you are not authorized.", reply_to_message_id=message_id)
return
url = update.message.text
if not url.startswith(('http://', 'https://')):
await context.bot.send_message(chat_id=chat_id, text="Please send a valid URL.", reply_to_message_id=message_id)
return
status_msg = await context.bot.send_message(chat_id=chat_id, text="🔍 Analyzing URL...", reply_to_message_id=message_id)
loop = asyncio.get_running_loop()
is_pl = await loop.run_in_executor(None, is_playlist, url)
# Fetch user settings
settings = get_user_settings(chat_id)
mode = settings.get('download_mode', 'video')
res = settings.get('resolution', 1080)
if is_pl:
final_res = -1 if mode == 'audio' else res
mode_str = "Audio M4A" if mode == 'audio' else f"{res}p"
await status_msg.edit_text(f"📋 Playlist detected. Adding to queue ({mode_str})...")
await context.application.bot_data['playlist_queue'].put((chat_id, url, message_id, final_res, status_msg))
await status_msg.edit_text(f"📋 Playlist added to queue ({mode_str}).")
else:
# If mode is audio, set resolution to -1 (marker for audio in our processor)
final_res = -1 if mode == 'audio' else res
await request_queue.put((chat_id, url, message_id, final_res, status_msg))
q_size = request_queue.qsize()
mode_str = "Audio M4A" if mode == 'audio' else f"{res}p"
await status_msg.edit_text(f"📥 Added to queue ({mode_str}). Queue Depth: {q_size}")
# --- Subscription Handlers ---
async def handle_subscribe_video(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /subvideo command."""
await _perform_subscribe(update, context, sub_type='video')
async def handle_subscribe_live(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /sublive command."""
await _perform_subscribe(update, context, sub_type='live')
async def _perform_subscribe(update: Update, context: ContextTypes.DEFAULT_TYPE, sub_type='video'):
"""Shared logic for subscriptions."""
chat_id = update.effective_chat.id
message_id = update.message.message_id
if not is_user_allowed(chat_id):
await context.bot.send_message(chat_id=chat_id, text="Sorry, you are not authorized.", reply_to_message_id=message_id)
return
if not context.args:
cmd = "/subvideo" if sub_type == 'video' else "/sublive"
await context.bot.send_message(
chat_id=chat_id,
text=f"Usage: `{cmd} <channel_url> [quality]`\n\nExample:\n`{cmd} https://www.youtube.com/@ChannelName 1080`",
reply_to_message_id=message_id,
parse_mode='Markdown'
)
return
channel_url = context.args[0]
max_quality = 1080
if len(context.args) > 1:
try:
max_quality = int(context.args[1])
except ValueError:
pass
status_msg = await tg_retry(
context.bot.send_message,
chat_id=chat_id,
text="🔍 Getting channel info...",
reply_to_message_id=message_id,
)
try:
loop = asyncio.get_running_loop()
channel_info = await loop.run_in_executor(None, lambda: get_channel_info(channel_url))
# Twitch channels do not expose an upload feed that this bot monitors.
# Treat any Twitch subscription as a live-stream subscription, even
# when the legacy /subscribe alias was used.
effective_sub_type = 'live' if is_twitch_channel_id(channel_info['channel_id']) else sub_type
success = add_subscription(
channel_id=channel_info['channel_id'],
channel_name=channel_info['channel_name'],
chat_id=chat_id,
max_quality=max_quality,
sub_type=effective_sub_type
)
if success:
type_str = "Videos" if effective_sub_type == 'video' else "Live Streams"
platform_note = (
"\n\nTwitch is checked for live streams automatically."
if is_twitch_channel_id(channel_info['channel_id']) else ""
)
await tg_retry(status_msg.edit_text,
f"✅ **Subscribed ({type_str})!**\n\n"
f"📺 Channel: {channel_info['channel_name']}\n"
f"🎬 Quality: {max_quality}p\n\n"
f"You'll receive {type_str.lower()} automatically!{platform_note}",
parse_mode='Markdown'
)
else:
await tg_retry(status_msg.edit_text, "❌ Failed to save subscription.")
except Exception as e:
await tg_retry(status_msg.edit_text, f"❌ Error: {e}")
async def handle_unsubscribe(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /unsubscribe command."""
chat_id = update.effective_chat.id
message_id = update.message.message_id
if not is_user_allowed(chat_id):
return
if not context.args:
await context.bot.send_message(
chat_id=chat_id,
text="Usage: `/unsubscribe <channel_url>`",
reply_to_message_id=message_id,
parse_mode='Markdown'
)
return
channel_url = context.args[0]
# Detect sub_type from command
cmd = update.message.text.split()[0].lower()
sub_type = 'live' if 'live' in cmd else 'video'
if is_legacy_numeric_channel_id(channel_url):
removed = remove_legacy_numeric_subscriptions(channel_url, chat_id)
text = (
f"✅ Removed {removed} stale subscription(s) for ID {channel_url}.\n"
"Subscribe again with the Twitch channel URL, for example "
"`/sublive https://www.twitch.tv/channelname`."
if removed else
f"No stale subscription found for ID {channel_url}. "
"Use the Twitch channel URL to unsubscribe."
)
await tg_retry(context.bot.send_message, chat_id=chat_id, text=text,
reply_to_message_id=message_id, parse_mode='Markdown')
return
try:
loop = asyncio.get_running_loop()
channel_info = await loop.run_in_executor(None, lambda: get_channel_info(channel_url))
effective_sub_type = 'live' if is_twitch_channel_id(channel_info['channel_id']) else sub_type
success = remove_subscription(channel_info['channel_id'], chat_id, sub_type=effective_sub_type)
if success:
type_str = "Live Streams" if effective_sub_type == 'live' else "Videos"
await context.bot.send_message(
chat_id=chat_id,
text=f"✅ Unsubscribed from {type_str} for: {channel_info['channel_name']}",
reply_to_message_id=message_id
)
else:
await context.bot.send_message(
chat_id=chat_id,
text=f"❌ No active {sub_type} subscription found.",
reply_to_message_id=message_id
)
except Exception as e:
await context.bot.send_message(chat_id=chat_id, text=f"❌ Error: {e}", reply_to_message_id=message_id)
async def handle_subscriptions(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /subscriptions command to list all subscriptions."""
chat_id = update.effective_chat.id
message_id = update.message.message_id
if not is_user_allowed(chat_id):
return
subs = get_user_subscriptions(chat_id)
if not subs:
await context.bot.send_message(
chat_id=chat_id,
text="📭 You have no subscriptions.\n\nUse `/subscribe <channel_url>` to add one.",
reply_to_message_id=message_id,
parse_mode='Markdown'
)
return
text = "📺 **Your Subscriptions**\n\n"
for channel_id, channel_name, max_quality, sub_type, created_at in subs:
if is_legacy_numeric_channel_id(channel_id):
text += (
f"• ⚠️ Invalid old subscription ID `{channel_id}`. "
"Remove with `/unsubscribe " + channel_id + "` and add the Twitch URL again.\n"
)
continue
icon = "🔴 Live" if sub_type == 'live' or is_twitch_channel_id(channel_id) else "📹 Video"
text += f"• {icon}: **{channel_name}** ({max_quality}p)\n"
text += f"\n_Total: {len(subs)} subscriptions_"
await context.bot.send_message(chat_id=chat_id, text=text, reply_to_message_id=message_id, parse_mode='Markdown')
# --- Settings Handlers ---
def get_settings_keyboard(chat_id):
"""Create settings keyboard based on user preferences."""
settings = get_user_settings(chat_id)
mode = settings.get('download_mode', 'video')
res = settings.get('resolution', 1080)
# Mode buttons
mode_text = "🎬 Video" if mode == 'video' else "🎵 Audio (M4A)"
mode_btn = InlineKeyboardButton(f"Mode: {mode_text}", callback_data="set_mode")
# Resolution buttons (only relevant for video)
res_buttons = []
if mode == 'video':
for r in [1080, 720, 480, 360, 240]:
label = f"✅ {r}p" if r == res else f"{r}p"
res_buttons.append(InlineKeyboardButton(label, callback_data=f"set_res:{r}"))
# Arrange keyboard
keyboard = [[mode_btn]]
if res_buttons:
# Split resolutions into rows of 3
keyboard.append(res_buttons[:3])
keyboard.append(res_buttons[3:])
return InlineKeyboardMarkup(keyboard)
async def handle_settings(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle /settings command."""
chat_id = update.effective_chat.id
if not is_user_allowed(chat_id):
return
await context.bot.send_message(
chat_id=chat_id,
text="⚙️ **Bot Settings**\nConfigure your default download preferences:",
reply_markup=get_settings_keyboard(chat_id),
parse_mode='Markdown'
)
async def settings_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle settings button clicks."""
query = update.callback_query
chat_id = query.message.chat_id
data = query.data
if data == "set_mode":
current = get_user_settings(chat_id).get('download_mode', 'video')
new_mode = 'audio' if current == 'video' else 'video'
update_user_settings(chat_id, download_mode=new_mode)
await query.answer(f"Mode changed to {new_mode}")
elif data.startswith("set_res:"):
new_res = int(data.split(':')[1])
update_user_settings(chat_id, resolution=new_res)
await query.answer(f"Resolution set to {new_res}p")
else:
return
# Update the keyboard
try:
await query.edit_message_reply_markup(reply_markup=get_settings_keyboard(chat_id))
except Exception:
pass
# --- Callback Handlers ---
async def cancel_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle cancel button callback."""
query = update.callback_query
await query.answer("Cancelling...")
data = query.data
if not data.startswith("cancel:"):
return
task_id = data[7:]
cancelled_tasks.add(task_id)
try:
await query.message.delete()
except Exception as e:
logger.warning(f"Could not delete cancel message: {e}")
async def retry_upload_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Immediately resume a retained upload from its first failed part."""
query = update.callback_query
data = query.data or ""
if not data.startswith("retryupload:"):
return
chat_id = query.message.chat_id
if not is_user_allowed(chat_id):
await tg_retry(query.answer, "You are not authorized.", show_alert=True)
return
retry_func = context.application.bot_data.get('retry_upload_job')
if not retry_func:
await tg_retry(query.answer, "Upload retry is unavailable after restart.", show_alert=True)
return
started, message = await retry_func(data[len("retryupload:"):])
await tg_retry(query.answer, message, show_alert=not started)
async def stop_live_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle stop & upload button for live recordings."""
query = update.callback_query
await query.answer("Stopping recording, will upload...")
data = query.data
if not data.startswith("stoplive:"):
return
task_id = data[9:]
stopped_tasks.add(task_id)
async def fromstart_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle stale From Start buttons from recordings created before auto-archive."""
query = update.callback_query
await tg_retry(query.answer, "From-start archive is already running.")
async def audio_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle Audio download button callback."""
query = update.callback_query
await query.answer()
chat_id = query.message.chat_id
if not is_user_allowed(chat_id):
await query.edit_message_reply_markup(reply_markup=None)
return
data = query.data
if not data.startswith("audio:"):
return
url = data[6:]
await query.edit_message_reply_markup(reply_markup=InlineKeyboardMarkup([
[InlineKeyboardButton("🎵 Converting to Audio...", callback_data="noop")]
]))
try:
loop = asyncio.get_running_loop()
status_msg = await context.bot.send_message(chat_id=chat_id, text="🎵 Downloading audio...")
last_progress_update = 0
def progress_cb(d):
nonlocal last_progress_update
if d['status'] == 'downloading':
now = time.time()
if now - last_progress_update < 20:
return
p = d.get('_percent_str', '0%')
asyncio.run_coroutine_threadsafe(
status_msg.edit_text(f"🎵 Downloading audio: {p}"),
loop
)
last_progress_update = now
file_path, title, video_id, thumb_path = await loop.run_in_executor(None, lambda: download_content(url, progress_cb, audio_only=True))
await status_msg.edit_text("⬆️ Uploading audio...")
config = load_config()
api_url = config.get('api_url', '')
bot_token = config.get('bot_token', '')
is_local_api = api_url and 'api.telegram.org' not in api_url
full_caption = f"{title}\n{url}"
reply_id = query.message.reply_to_message.message_id if query.message.reply_to_message else None
if is_local_api:
await upload_audio_streaming(bot_token, api_url, chat_id, file_path, title, full_caption, reply_to_message_id=reply_id, thumb_path=thumb_path)
else:
# Attempt to reply to the original user source message
with open(file_path, 'rb') as f:
if thumb_path and os.path.exists(thumb_path):
thumb_path = crop_to_square(thumb_path)
thumb = open(thumb_path, 'rb')
else:
thumb = None
await tg_retry(context.bot.send_audio, chat_id=chat_id, audio=f, title=title, caption=full_caption, reply_to_message_id=reply_id, thumbnail=thumb)
if thumb: thumb.close()
# Cleanup
if os.path.exists(file_path):
os.remove(file_path)
if thumb_path and os.path.exists(thumb_path):
try: os.remove(thumb_path)
except: pass
# Delete status message upon completion
try:
await tg_retry(status_msg.delete)
except: pass
await query.edit_message_reply_markup(reply_markup=None)
except Exception as e:
logger.error(f"Audio conversion failed: {e}")
await context.bot.send_message(chat_id=chat_id, text=f"❌ Audio download failed: {e}")
retry_cb = f"audio:{url}"
if len(retry_cb.encode('utf-8')) <= 64:
await query.edit_message_reply_markup(reply_markup=InlineKeyboardMarkup([
[InlineKeyboardButton("🎵 Download Audio (Retry)", callback_data=retry_cb)]
]))
finally:
gc.collect()
async def handle_cookie_document(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Only explicitly configured users may replace the shared account cookies."""
message = update.effective_message
user = update.effective_user
chat = update.effective_chat
if not message or not message.document or not chat:
return
if chat.type != 'private' or not user or not is_cookie_admin(user.id):
await tg_retry(message.reply_text, '⛔ 僅 COOKIE_ADMIN_IDS 指定的管理者可透過私訊上傳 cookies。')
return
document = message.document
if (document.file_name or '').lower() not in ('cookie.txt', 'cookies.txt'):
await tg_retry(message.reply_text, '請上傳名為 cookie.txt 或 cookies.txt 的 Netscape 格式檔案。')
return
if document.file_size is None or not 0 < document.file_size <= MAX_COOKIE_BYTES:
await tg_retry(message.reply_text, '❌ Cookies 檔案不可為空,且不得超過 1 MiB。')
return
status = await tg_retry(message.reply_text, '🔍 正在檢查 cookies 檔案…')
try:
remote = await tg_retry(document.get_file)
data = await tg_retry(remote.download_as_bytearray)
count, expired = await asyncio.get_running_loop().run_in_executor(
None, install_cookies, bytes(data)
)
except ValueError as exc:
await tg_retry(status.edit_text, f'❌ {exc}\n原有 cookies 未變更。')
return
except Exception:
# Exceptions from file APIs/parsers may contain private paths or secrets.
logger.warning('Cookie upload failed; details withheld to protect credentials')
await tg_retry(status.edit_text, '❌ 無法下載或儲存 cookies,請確認檔案服務與 data 目錄權限後重試。')
return
await tg_retry(status.edit_text,
f'✅ 已更新 cookies({count} 筆,其中 {expired} 筆已到期)。新下載會自動使用,不需重啟。\n'
'格式與到期時間檢查通過,但不保證登入仍有效;網站可能提前撤銷登入,請傳送影片網址實測。')