-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGrabber.py
More file actions
3120 lines (2861 loc) · 128 KB
/
Copy pathGrabber.py
File metadata and controls
3120 lines (2861 loc) · 128 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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# CopyLeft 2026 github.com/i-execute
# Author: I_execute.t.me
# Licensed under AGPLv3.
__version__ = (4, 1, 0)
# meta developer: Execute_forge.t.me
# meta banner: https://raw.githubusercontent.com/i-execute/Modules/main/Storage/Grabber/MetaBanner.jpeg
import os
import io
import re
import time
import json
import asyncio
import logging
import shutil
import tempfile
import sys
import concurrent.futures
import threading
try:
import herokutl.tl.tlobject as tlobj
tlobj.TLObject._assert_constructor_allowed = lambda self: None
tlobj.TLObject._assert_no_forbidden_constructors = lambda self: None
tlobj._raise_if_forbidden_constructor = lambda cls: None
tlobj._raise_if_forbidden_serialized_request = lambda *a, **k: None
from herokutl.network import requeststate as _rs
_rs._raise_if_forbidden_serialized_request = lambda *a, **k: None
except Exception:
pass
from telethon import TelegramClient, events, Button
from telethon.tl import functions, types
from telethon.tl.types import (
DocumentAttributeVideo,
DocumentAttributeAudio,
DocumentAttributeFilename,
ReactionEmoji,
)
from telethon.tl.functions.messages import SendReactionRequest, EditMessageRequest
from telethon.tl.types import InputMediaWebPage
from telethon.errors import (
MessageNotModifiedError,
FloodWaitError,
)
from .. import loader, utils
try:
from PIL import Image
except ImportError:
Image = None
try:
import aiohttp
except ImportError:
aiohttp = None
logger = logging.getLogger(__name__)
_URL_PATTERN = re.compile(r'https?://[^\s<>"\']+', re.IGNORECASE)
_BOT_TOKEN_RE = re.compile(r'\b\d{8,10}:[A-Za-z0-9_-]{35}\b')
OG_IMAGE_RE = re.compile(
r'<meta\s+(?:property|name)=["\']og:image["\']\s+content=["\']([^"\']+)["\']',
re.IGNORECASE,
)
OG_IMAGE_RE2 = re.compile(
r'<meta\s+content=["\']([^"\']+)["\']\s+(?:property|name)=["\']og:image["\']',
re.IGNORECASE,
)
GRABBER_TOPIC_ICON = 5303138391162919957
RELOADING_MEDIA_URL = "https://raw.githubusercontent.com/i-execute/Modules/main/Storage/Grabber/Reloading.jpeg"
def _escape_html(t):
if not t:
return ""
return str(t).replace("&", "&").replace("<", "<").replace(">", ">")
def _sanitize_fn(n):
return re.sub(r'[<>:"/\\|?*\x00-\x1f]', "_", n).strip(". ")[:180] or "track"
def _fmt_dur(s):
if not s or s <= 0:
return "0:00"
s = int(s)
if s < 3600:
m, sec = divmod(s, 60)
return f"{m}:{sec:02d}"
h, rem = divmod(s, 3600)
m, sec = divmod(rem, 60)
return f"{h}:{m:02d}:{sec:02d}"
def _fmt_speed(b):
if not b:
return "..."
if b < 1024:
return f"{b:.0f} B/s"
if b < 1024 * 1024:
return f"{b / 1024:.1f} KB/s"
return f"{b / 1024 / 1024:.1f} MB/s"
def _fmt_elapsed(s):
if not s or s <= 0:
return "0s"
s = int(s)
if s < 60:
return f"{s}s"
if s < 3600:
m, sec = divmod(s, 60)
return f"{m}m {sec}s" if sec else f"{m}m"
h, rem = divmod(s, 3600)
m, sec = divmod(rem, 60)
parts = [f"{h}h"]
if m:
parts.append(f"{m}m")
if sec:
parts.append(f"{sec}s")
return " ".join(parts)
def normalize_cover(raw, max_size=None, force_jpeg=False):
if not raw or len(raw) < 100:
return None
if not Image:
return raw
try:
img = Image.open(io.BytesIO(raw))
w, h = img.size
needs_resize = max_size and (w > max_size or h > max_size)
if force_jpeg:
img = img.convert("RGB")
if needs_resize:
ratio = min(max_size / w, max_size / h)
img = img.resize((int(w * ratio), int(h * ratio)), Image.LANCZOS)
buf = io.BytesIO()
img.save(buf, format="JPEG", quality=95)
result = buf.getvalue()
return result if len(result) >= 100 else None
is_png = raw[:8] == b'\x89PNG\r\n\x1a\n'
if is_png and not needs_resize:
return raw
img = img.convert("RGB")
if needs_resize:
ratio = min(max_size / w, max_size / h)
img = img.resize((int(w * ratio), int(h * ratio)), Image.LANCZOS)
buf = io.BytesIO()
img.save(buf, format="JPEG", quality=95)
result = buf.getvalue()
return result if len(result) >= 100 else None
except Exception:
return raw
async def _download_url(url, timeout=20):
if not url or not aiohttp:
return None
try:
async with aiohttp.ClientSession() as s:
async with s.get(url, timeout=aiohttp.ClientTimeout(total=timeout)) as r:
if r.status != 200:
return None
data = await r.read()
return data if data and len(data) >= 100 else None
except Exception:
return None
async def _upload_to_x0(data, filename, content_type="application/octet-stream"):
if not aiohttp:
return ""
try:
form = aiohttp.FormData()
form.add_field("file", data, filename=filename, content_type=content_type)
async with aiohttp.ClientSession() as s:
async with s.post(
"https://x0.at",
data=form,
timeout=aiohttp.ClientTimeout(total=60),
) as r:
text = (await r.text()).strip()
return text if text.startswith("http") else ""
except Exception:
return ""
async def _fetch_og_image(url):
if not aiohttp:
return None
try:
async with aiohttp.ClientSession() as s:
async with s.get(
url,
headers={"User-Agent": "facebookexternalhit/1.1"},
timeout=aiohttp.ClientTimeout(total=15),
allow_redirects=True,
) as r:
if r.status != 200:
return None
html = await r.text(errors="replace")
for pat in [OG_IMAGE_RE, OG_IMAGE_RE2]:
m = pat.search(html)
if m:
return m.group(1).replace("&", "&")
except Exception:
pass
return None
_VK_SUBS_PATCH_APPLIED = False
def _sanitize_vk_subs_payload(obj):
if isinstance(obj, dict):
if "title" in obj and obj["title"] is None and "url" in obj:
obj["title"] = ".srt"
for v in obj.values():
_sanitize_vk_subs_payload(v)
elif isinstance(obj, list):
for item in obj:
_sanitize_vk_subs_payload(item)
return obj
def _patch_vk_extractor():
global _VK_SUBS_PATCH_APPLIED
if _VK_SUBS_PATCH_APPLIED:
return
try:
from yt_dlp.extractor.vk import VKBaseIE
_orig_download_payload = VKBaseIE._download_payload
def _patched_download_payload(self, path, video_id, data, fatal=True):
payload = _orig_download_payload(self, path, video_id, data, fatal=fatal)
try:
_sanitize_vk_subs_payload(payload)
except Exception:
pass
return payload
VKBaseIE._download_payload = _patched_download_payload
_VK_SUBS_PATCH_APPLIED = True
except Exception as e:
logger.debug(f"[GRABBER] vk extractor patch failed: {e}")
def _get_best_thumb_url(info):
if not info:
return None
thumbs = info.get("thumbnails")
if thumbs and isinstance(thumbs, list):
best_url = None
best_pref = -9999
best_res = 0
for t in thumbs:
url = t.get("url")
if not url:
continue
w = t.get("width") or 0
h = t.get("height") or 0
pref = t.get("preference") or 0
res = w * h
if pref > best_pref or (pref == best_pref and res > best_res):
best_pref = pref
best_res = res
best_url = url
if best_url:
return best_url
return info.get("thumbnail")
class SafeList:
def __init__(self):
self._list = []
self._lock = threading.Lock()
def append(self, item):
with self._lock:
self._list.append(item)
def pop_first(self):
with self._lock:
return self._list.pop(0) if self._list else None
def clear(self):
with self._lock:
self._list.clear()
def __len__(self):
with self._lock:
return len(self._list)
class SafeSet:
def __init__(self):
self._set = set()
self._lock = threading.Lock()
def add(self, item):
with self._lock:
if item in self._set:
return False
self._set.add(item)
return True
def remove(self, item):
with self._lock:
self._set.discard(item)
def clear(self):
with self._lock:
self._set.clear()
async def _embed_cover_ffmpeg(audio_path, cover_path, output_path):
cmd = [
"ffmpeg", "-y",
"-i", audio_path,
"-i", cover_path,
"-map", "0:a",
"-map", "1:0",
"-c", "copy",
"-id3v2_version", "3",
"-metadata:s:v", "title=Album cover",
"-metadata:s:v", "comment=Cover (front)",
output_path,
]
try:
proc = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
await proc.communicate()
return proc.returncode == 0
except Exception:
return False
DEPS = ["yt-dlp", "Pillow", "aiohttp", "mutagen"]
def _install_deps():
import importlib, subprocess
pip = __import__('os').path.join(__import__('os').path.dirname(sys.executable), "pip")
if not __import__('os').path.exists(pip):
pip = "pip"
in_venv = sys.prefix != sys.base_prefix
imp_map = {
"yt-dlp": "yt_dlp", "Pillow": "PIL",
"aiohttp": "aiohttp", "mutagen": "mutagen",
}
ver_attr = {
"yt_dlp": "version.__version__",
"mutagen": "version.version_string",
}
lines = [f"venv: {'yes' if in_venv else 'no'} ({sys.prefix})"]
for pkg in DEPS:
try:
subprocess.run([pip, "install", "-U", pkg, "--break-system-packages", "-q"],
capture_output=True, text=True, timeout=120)
try:
imp_name = imp_map.get(pkg, pkg)
importlib.invalidate_caches()
mod = importlib.import_module(imp_name)
if imp_name in ver_attr:
parts = ver_attr[imp_name].split(".")
obj = mod
for part in parts:
obj = getattr(obj, part, None)
if obj is None:
break
ver = str(obj) if obj else getattr(mod, "__version__", "?")
else:
ver = getattr(mod, "__version__", "?")
lines.append(f"{pkg}: OK ({ver})")
except ImportError:
lines.append(f"{pkg}: FAIL (import error)")
except Exception as e:
lines.append(f"{pkg}: FAIL ({e})")
return lines
@loader.tds
class Grabber(loader.Module):
"""Universal media downloader"""
strings = {
"name": "Grabber",
"reloaded": "<blockquote><b>Grabber module successfully reloaded, everything works</b></blockquote>",
"btn_video": "Video",
"btn_audio": "Audio (MP3)",
"btn_cancel": "Cancel",
"btn_back": "Back",
"btn_orig_thumb": "With cover",
"btn_orig_clean": "Without cover",
"btn_custom": "Editor",
"btn_no_cover": "No cover",
"btn_confirm": "Download",
"btn_retry": "Retry",
"no_token": (
"<b>Bot token not set!</b>\n"
"<blockquote>Use: <code>{prefix}grab token [token]</code></blockquote>"
),
"token_stored": (
"<b>Token saved!</b>\n"
"<blockquote expandable>Startup log:\n{log}</blockquote>"
),
"token_started": (
"<b>Grabber started!</b>\n"
"<blockquote expandable>Startup log:\n{log}</blockquote>"
),
"need_token": "<b>Specify token or reply to message with it!</b>",
"already_running": "<b>Already running!</b>",
"not_running": "<b>Bot not running!</b>",
"start_failed": (
"<b>Start error:</b>\n"
"<blockquote><code>{error}</code>\nUse <code>{prefix}unextarnal Grabber</code> to reload.</blockquote>"
),
"reboot_start": "<b>REBOOT...</b>",
"reboot_done": "<b>Reboot complete!</b>",
"reboot_no_token": "<b>No token for restart!</b>",
"clear_done": "<b>Factory reset complete!</b>",
"cookie_saved": "<b>Cookies saved!</b>",
"cookie_cleared": "<b>Cookies deleted!</b>",
"cookie_empty": "Not set",
"cookie_ok": "Installed",
"no_reply_file": "<b>Reply to .txt file with cookies!</b>",
"invalid_ext": "<b>File must have .txt extension!</b>",
"cookie_err": "<b>Cookie save error:</b>\n<blockquote><code>{}</code></blockquote>",
"cookie_invalid_format": "<b>Invalid cookie format!</b>\n<blockquote>Expected Netscape format.</blockquote>",
"status_template": (
"<b>Grabber Status</b>\n"
"<blockquote><b>Status:</b> {status}\n"
"<b>Cookies:</b> {cookies}\n"
"<b>In queue:</b> {pending}\n"
"<b>Active tasks:</b> {active}\n"
"<b>Completed:</b> {completed}\n"
"<b>Errors:</b> {errors}</blockquote>"
),
"status_running": "Running",
"status_stopped": "Stopped",
"no_active_process": "<b>No active process</b>",
"analyzing": "<b>Analyzing...</b>",
"found_media": "<b>{title}</b>\n<blockquote><b>Duration:</b> {duration}\nSelect format:</blockquote>",
"found_media_group": "<b>{title}</b>\n<blockquote><b>Duration:</b> {duration}</blockquote>",
"grab_failed": "<b>Error</b>\n<blockquote><code>{error}</code></blockquote>",
"queue_pos": "<b>Queue: #{pos}</b>",
"starting": "<b>Starting download!</b>",
"too_large_bot": "<b>File too large for bot API</b>\n<blockquote>{size_mb:.1f} MB — uploading via userbot...</blockquote>",
"too_large_no_premium": "<b>File too large</b>\n<blockquote>{size_mb:.1f} MB — Telegram Premium required on userbot account.</blockquote>",
"too_large_over_limit": "<b>File too large</b>\n<blockquote>{size_mb:.1f} MB — max is 4096 MB.</blockquote>",
"cancelled": "<b>Cancelled</b>",
"already_processing": "Already processing!",
"hello": "<b>Hello, {user_link}!</b>\n<blockquote>Send a video link!</blockquote>",
"hello_fallback": "<b>Hello!</b>\n<blockquote>Send a video link!</blockquote>",
"hello_group": "<b>Bot activated in this group!</b>\n<blockquote>Send video links.</blockquote>",
"hello_topic": "<b>Bot activated in this topic!</b>\n<blockquote>Send video links.</blockquote>",
"hello_group_off": "<b>Bot deactivated in this group.</b>",
"hello_topic_off": "<b>Bot deactivated in this topic.</b>",
"file_caption": (
"<blockquote><b>{title}</b></blockquote>\n"
"<pre><code class=\"language-grabber\">{size_mb:.1f} MB | {width}x{height} | {elapsed}</code></pre>"
),
"calc_label": "calculating",
"audio_caption": (
"<blockquote><b>{title}</b></blockquote>\n"
"<pre><code class=\"language-grabber\">{size_mb:.1f} MB</code></pre>"
),
"progress_title": "<b>{title}</b>",
"dl_waiting": "Downloading: waiting...",
"dl_progress": "Downloading: {pct:.1f}% ({size:.1f}/{total:.1f} MB)",
"dl_done": "Downloading: done {size:.1f} MB",
"merge_waiting": "Merge: waiting...",
"merge_done": "Merge: done {size:.1f} MB",
"merge_active": "Merge: FFmpeg working...",
"convert_waiting": "Convert: waiting...",
"convert_done": "Convert: done {size:.1f} MB",
"convert_active": "Convert: FFmpeg...",
"upload_waiting": "Telegram: waiting...",
"upload_progress": "Telegram: {pct:.1f}% ({cur:.1f}/{total:.1f} MB)",
"upload_success": "Telegram: done {elapsed:.1f}s",
"stage_init": "Initializing...",
"stage_video": "Downloading video...",
"stage_audio": "Downloading audio...",
"stage_ffmpeg": "FFmpeg processing...",
"stage_probe": "Analyzing file...",
"stage_upload": "Uploading to Telegram...",
"stage_done_success": "Successfully uploaded!",
"time_stage": "Time: {elapsed:.1f}s | {stage_text}",
"audio_menu": "<b>Select option:</b>",
"editor_mode": "<b>Editor mode</b>\n<blockquote>Send TRACK NAME:</blockquote>",
"edit_title_done": "<b>Title:</b> {}\n<blockquote>Now enter ARTIST name:</blockquote>",
"edit_artist_done": "<b>Artist:</b> {}\n<blockquote>Now send COVER (PNG/JPEG as FILE!):</blockquote>",
"only_image": "<b>Only PNG or JPEG as FILE!</b>",
"downloading_image": "<b>Downloading image...</b>",
"text_needed_image": "<b>Need PNG/JPEG file, not text!</b>",
"confirm_menu": (
"<b>Check data:</b>\n"
"<blockquote><b>Track:</b> {title}\n"
"<b>Artist:</b> {artist}\n"
"<b>Cover:</b> {thumb}</blockquote>"
),
"thumb_yes": "Yes",
"thumb_no": "No",
"op_cancelled": "<b>Operation cancelled.</b>",
"not_your_editor": "<b>This is not your editor!</b>",
"session_expired": "Session expired",
"quality_menu": "<b>Select quality:</b>",
"react_ok": "\U0001F44C",
"react_fail": "\U0001F971",
"usage": (
"<b>Grabber - Universal media downloader</b>\n\n"
"<code>{prefix}grab token [token]</code> - Set bot token\n"
"<code>{prefix}grab reboot</code> - Clear cache and restart\n"
"<code>{prefix}grab clear</code> - Factory reset\n"
"<code>{prefix}grab cookies add</code> - Add cookies (reply to .txt)\n"
"<code>{prefix}grab cookies remove</code> - Remove cookies\n"
"<code>{prefix}grab status</code> - Status\n"
),
"log_processing": "<b>Processing:</b> {title}\n<blockquote>From: {user}\nURL: <code>{url}</code></blockquote>",
"log_done": "<b>Done:</b> {title} | {size_mb:.1f} MB",
"log_error": "<b>Error:</b> {title}\n<blockquote><code>{error}</code></blockquote>",
"log_large": "<b>Large file ({size_mb:.1f} MB)</b>\n<blockquote>Uploading via userbot...</blockquote>",
"main_menu": (
"<b>Grabber</b>\n"
"<blockquote><b>Status:</b> {status}\n"
"<b>Token:</b> {token}\n"
"<b>Cookies:</b> {cookies}\n"
"<b>Queue:</b> {pending} | <b>Active:</b> {active}\n"
"<b>Done:</b> {completed} | <b>Errors:</b> {errors}</blockquote>"
),
"token_menu": "<b>Token</b>\n<blockquote>Set bot token below:</blockquote>",
"clear_confirm": "<b>Factory reset?</b>\n<blockquote>All data will be deleted.</blockquote>",
"cookies_menu": "<b>Cookies</b>\n<blockquote><b>File:</b> {file_status}\n<b>Active:</b> {enabled}</blockquote>",
"btn_status": "Refresh",
"btn_settings": "Settings",
"settings_menu": (
"<b>Settings</b>\n"
"<blockquote><b>Workers:</b> {workers}\n"
"<b>Max file:</b> {max_file} MB\n"
"<b>Update interval:</b> {delay}s\n"
"<b>Autostart:</b> {autostart}</blockquote>"
),
"btn_workers": "Workers: {val}",
"btn_max_file": "Max file: {val} MB",
"btn_delay": "Interval: {val}s",
"btn_autostart": "Autostart: {val}",
"input_workers": "Enter number of workers (1-10):",
"input_max_file": "Enter max file size in MB (50-4096):",
"input_delay": "Enter update interval in seconds (1-30):",
"setting_saved": "Saved! Will apply after current task finishes.",
"setting_saved_instant": "Saved!",
"setting_invalid": "Invalid value!",
"btn_token": "Token",
"btn_cookies": "Cookies",
"btn_reboot": "Reboot",
"btn_clear": "Reset",
"btn_close": "Close",
"btn_start": "Start",
"btn_stop": "Stop",
"btn_set_token": "Set token",
"btn_remove_cookies": "Remove cookies",
"btn_toggle_cookies": "Cookies: {val}",
"btn_confirm_reboot": "Confirm",
"btn_confirm_clear": "Confirm reset",
"input_token": "Paste bot token:",
"installing": "Installing...",
"cookie_cleared_short": "Cookies removed!",
}
strings_ru = {
"name": "Grabber",
"reloaded": "<blockquote><b>Модуль Grabber был успешно перезагружен, все воркает</b></blockquote>",
"btn_video": "Видео",
"btn_audio": "Аудио (MP3)",
"btn_cancel": "Отмена",
"btn_back": "Назад",
"btn_orig_thumb": "С обложкой",
"btn_orig_clean": "Без обложки",
"btn_custom": "Редактор",
"btn_no_cover": "Без обложки",
"btn_confirm": "Скачать",
"btn_retry": "Заново",
"no_token": (
"<b>Токен бота не задан!</b>\n"
"<blockquote>Используй: <code>{prefix}grab token [токен]</code></blockquote>"
),
"token_stored": (
"<b>Токен сохранён!</b>\n"
"<blockquote expandable>Лог запуска:\n{log}</blockquote>"
),
"token_started": (
"<b>Grabber запущен!</b>\n"
"<blockquote expandable>Лог запуска:\n{log}</blockquote>"
),
"need_token": "<b>Укажи токен или ответь на сообщение с ним!</b>",
"already_running": "<b>Уже запущен!</b>",
"not_running": "<b>Бот не запущен!</b>",
"start_failed": (
"<b>Ошибка запуска:</b>\n"
"<blockquote><code>{error}</code>\nИспользуй <code>{prefix}unextarnal Grabber</code>.</blockquote>"
),
"reboot_start": "<b>ПЕРЕЗАГРУЗКА...</b>",
"reboot_done": "<b>Перезагрузка завершена!</b>",
"reboot_no_token": "<b>Нет токена для перезапуска!</b>",
"clear_done": "<b>Сброс к заводским настройкам!</b>",
"cookie_saved": "<b>Куки сохранены!</b>",
"cookie_cleared": "<b>Куки удалены!</b>",
"cookie_empty": "Не установлены",
"cookie_ok": "Установлены",
"no_reply_file": "<b>Ответь на .txt файл с куки!</b>",
"invalid_ext": "<b>Файл должен иметь расширение .txt!</b>",
"cookie_err": "<b>Ошибка сохранения куки:</b>\n<blockquote><code>{}</code></blockquote>",
"cookie_invalid_format": "<b>Неверный формат куки!</b>\n<blockquote>Ожидается формат Netscape.</blockquote>",
"status_template": (
"<b>Статус Grabber</b>\n"
"<blockquote><b>Статус:</b> {status}\n"
"<b>Куки:</b> {cookies}\n"
"<b>В очереди:</b> {pending}\n"
"<b>Активно задач:</b> {active}\n"
"<b>Завершено:</b> {completed}\n"
"<b>Ошибки:</b> {errors}</blockquote>"
),
"status_running": "Работает",
"status_stopped": "Остановлен",
"no_active_process": "<b>Нет активного процесса</b>",
"analyzing": "<b>Анализ...</b>",
"found_media": "<b>{title}</b>\n<blockquote><b>Длительность:</b> {duration}\nВыберите формат:</blockquote>",
"found_media_group": "<b>{title}</b>\n<blockquote><b>Длительность:</b> {duration}</blockquote>",
"grab_failed": "<b>Ошибка</b>\n<blockquote><code>{error}</code></blockquote>",
"queue_pos": "<b>Очередь: #{pos}</b>",
"starting": "<b>Начинаю загрузку!</b>",
"too_large_bot": "<b>Файл слишком большой для bot API</b>\n<blockquote>{size_mb:.1f} МБ — загружаю через юзербот...</blockquote>",
"too_large_no_premium": "<b>Файл слишком большой</b>\n<blockquote>{size_mb:.1f} МБ — нужен Telegram Premium на аккаунте юзербота.</blockquote>",
"too_large_over_limit": "<b>Файл слишком большой</b>\n<blockquote>{size_mb:.1f} МБ — максимум 4096 МБ.</blockquote>",
"cancelled": "<b>Отменено</b>",
"already_processing": "Уже обрабатывается!",
"hello": "<b>Привет, {user_link}!</b>\n<blockquote>Отправь ссылку на видео!</blockquote>",
"hello_fallback": "<b>Привет!</b>\n<blockquote>Отправь ссылку на видео!</blockquote>",
"hello_group": "<b>Бот активирован в этой группе!</b>\n<blockquote>Отправляйте ссылки на видео.</blockquote>",
"hello_topic": "<b>Бот активирован в этом топике!</b>\n<blockquote>Отправляйте ссылки на видео.</blockquote>",
"hello_group_off": "<b>Бот деактивирован в этой группе.</b>",
"hello_topic_off": "<b>Бот деактивирован в этом топике.</b>",
"file_caption": (
"<blockquote><b>{title}</b></blockquote>\n"
"<pre><code class=\"language-grabber\">{size_mb:.1f} MB | {width}x{height} | {elapsed}</code></pre>"
),
"calc_label": "вычисление",
"audio_caption": (
"<blockquote><b>{title}</b></blockquote>\n"
"<pre><code class=\"language-grabber\">{size_mb:.1f} MB</code></pre>"
),
"progress_title": "<b>{title}</b>",
"video_waiting": "Видео: ожидание...",
"video_done": "Видео: готово {size:.1f} MB",
"video_progress": "Видео: {pct:.1f}% ({size:.1f}/{total:.1f} MB) | {speed}",
"audio_waiting": "Аудио: ожидание...",
"audio_done": "Аудио: готово {size:.1f} MB",
"audio_progress": "Аудио: {pct:.1f}% ({size:.1f}/{total:.1f} MB) | {speed}",
"merge_waiting": "Слияние: ожидание...",
"merge_done": "Слияние: готово {size:.1f} MB",
"merge_active": "Слияние: FFmpeg работает...",
"merge_starting": "Слияние: запуск...",
"convert_waiting": "Конвертация: ожидание...",
"convert_done": "Конвертация: готово {size:.1f} MB",
"convert_active": "Конвертация: FFmpeg...",
"upload_waiting": "Telegram: ожидание...",
"upload_progress": "Telegram: {pct:.1f}% ({cur:.1f}/{total:.1f} MB)",
"upload_success": "Telegram: готово {elapsed:.1f}с",
"stage_init": "Инициализация...",
"stage_video": "Загрузка видео...",
"stage_audio": "Загрузка аудио...",
"stage_ffmpeg": "Обработка FFmpeg...",
"stage_probe": "Анализ файла...",
"stage_upload": "Загрузка в Telegram...",
"stage_done_success": "Успешно загружено!",
"time_stage": "Время: {elapsed:.1f}с | {stage_text}",
"audio_menu": "<b>Выберите вариант:</b>",
"editor_mode": "<b>Режим редактора</b>\n<blockquote>Отправьте НАЗВАНИЕ ТРЕКА:</blockquote>",
"edit_title_done": "<b>Название:</b> {}\n<blockquote>Теперь введите ИМЯ АРТИСТА:</blockquote>",
"edit_artist_done": "<b>Артист:</b> {}\n<blockquote>Теперь отправьте ОБЛОЖКУ (PNG/JPEG как ФАЙЛ!):</blockquote>",
"only_image": "<b>Только PNG или JPEG как ФАЙЛ!</b>",
"downloading_image": "<b>Загрузка изображения...</b>",
"text_needed_image": "<b>Нужен PNG/JPEG файл, не текст!</b>",
"confirm_menu": (
"<b>Проверьте данные:</b>\n"
"<blockquote><b>Трек:</b> {title}\n"
"<b>Артист:</b> {artist}\n"
"<b>Обложка:</b> {thumb}</blockquote>"
),
"thumb_yes": "Да",
"thumb_no": "Нет",
"op_cancelled": "<b>Операция отменена.</b>",
"not_your_editor": "<b>Это не ваш редактор!</b>",
"session_expired": "Сессия истекла",
"quality_menu": "<b>Выберите качество:</b>",
"react_ok": "\U0001F44C",
"react_fail": "\U0001F971",
"usage": (
"<b>Grabber - Универсальный загрузчик медиа</b>\n\n"
"<code>{prefix}grab token [токен]</code> - Установить токен бота\n"
"<code>{prefix}grab reboot</code> - Очистить кеш и перезапустить\n"
"<code>{prefix}grab clear</code> - Сброс к заводским\n"
"<code>{prefix}grab cookies add</code> - Добавить куки (реплай на .txt)\n"
"<code>{prefix}grab cookies remove</code> - Удалить куки\n"
"<code>{prefix}grab status</code> - Статус\n"
),
"log_processing": "<b>Обработка:</b> {title}\n<blockquote>От: {user}\nURL: <code>{url}</code></blockquote>",
"log_done": "<b>Готово:</b> {title} | {size_mb:.1f} MB",
"log_error": "<b>Ошибка:</b> {title}\n<blockquote><code>{error}</code></blockquote>",
"log_large": "<b>Большой файл ({size_mb:.1f} МБ)</b>\n<blockquote>Загружаю через юзербот...</blockquote>",
"main_menu": (
"<b>Grabber</b>\n"
"<blockquote><b>Статус:</b> {status}\n"
"<b>Токен:</b> {token}\n"
"<b>Куки:</b> {cookies}\n"
"<b>Очередь:</b> {pending} | <b>Активно:</b> {active}\n"
"<b>Готово:</b> {completed} | <b>Ошибки:</b> {errors}</blockquote>"
),
"token_menu": "<b>Токен</b>\n<blockquote>Введи токен бота:</blockquote>",
"cookies_menu": "<b>Куки</b>\n<blockquote><b>Файл:</b> {file_status}\n<b>Активны:</b> {enabled}</blockquote>",
"clear_confirm": "<b>Сброс к заводским?</b>\n<blockquote>Все данные будут удалены.</blockquote>",
"btn_status": "Обновить",
"btn_settings": "Настройки",
"settings_menu": (
"<b>Настройки</b>\n"
"<blockquote><b>Воркеры:</b> {workers}\n"
"<b>Макс. файл:</b> {max_file} МБ\n"
"<b>Интервал обновления:</b> {delay}с\n"
"<b>Автозапуск:</b> {autostart}</blockquote>"
),
"btn_workers": "Воркеры: {val}",
"btn_max_file": "Макс. файл: {val} МБ",
"btn_delay": "Интервал: {val}с",
"btn_autostart": "Автозапуск: {val}",
"input_workers": "Введи количество воркеров (1-10):",
"input_max_file": "Введи максимальный размер файла в МБ (50-4096):",
"input_delay": "Введи интервал обновления в секундах (1-30):",
"setting_saved": "Сохранено! Применится после завершения текущей задачи.",
"setting_saved_instant": "Сохранено!",
"setting_invalid": "Недопустимое значение!",
"btn_token": "Токен",
"btn_cookies": "Куки",
"btn_reboot": "Перезагрузка",
"btn_clear": "Сброс",
"btn_close": "Закрыть",
"btn_start": "Старт",
"btn_stop": "Стоп",
"btn_set_token": "Установить токен",
"btn_remove_cookies": "Удалить куки",
"btn_toggle_cookies": "Куки: {val}",
"btn_confirm_reboot": "Подтвердить",
"btn_confirm_clear": "Подтвердить сброс",
"input_token": "Вставьте токен бота:",
"installing": "Установка...",
"cookie_cleared_short": "Куки удалены!",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"BOT_TOKEN",
"",
"Bot token for Grabber",
validator=loader.validators.Hidden(),
),
loader.ConfigValue(
"ACTIVE_GROUPS",
[],
"Groups where bot is active (managed automatically)",
validator=loader.validators.Series(loader.validators.Integer()),
),
loader.ConfigValue(
"ACTIVE_TOPICS",
{},
"Topics where bot is active (managed automatically)",
),
)
self._settings_defaults = {
"AUTORUNNER": False,
"MAX_FILE_MB": 2000,
"MAX_WORKERS": 1,
"ACTION_DELAY": 3,
"COOKIES_ENABLED": True,
}
self._bot = None
self._running = False
self._download_queue = asyncio.Queue()
self._queue_items = SafeList()
self._processed_buttons = SafeSet()
self._worker_tasks = []
self._stats = {"completed": 0, "errors": 0}
self._root = None
self._cache_dir = None
self._session_dir = None
self._cookie_dir = None
self._cookie_path = None
self._lock = asyncio.Lock()
self._edit_lock = asyncio.Lock()
self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=4)
self._active_worker_count = 0
self._active_processes = []
self._edit_state = {}
self._active_groups = set()
self._active_topics = {}
self._current_downloads = {}
self._og_cache = {}
self._grabber_topic_id = None
def _get_setting(self, key):
val = self._db.get("Grabber", f"setting_{key}", None)
if val is None:
return self._settings_defaults[key]
return val
def _set_setting(self, key, value):
self._db.set("Grabber", f"setting_{key}", value)
async def _apply_settings_now(self):
if not self._running:
return
num_workers = max(1, self._get_setting("MAX_WORKERS"))
current_workers = len(self._worker_tasks)
if num_workers == current_workers:
return
for t in self._worker_tasks:
t.cancel()
try:
await t
except Exception:
pass
self._worker_tasks.clear()
try:
self._executor.shutdown(wait=False)
except Exception:
pass
self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=num_workers)
self._worker_tasks = [asyncio.create_task(self._queue_worker()) for _ in range(num_workers)]
async def _apply_settings_deferred_or_now(self):
if self._active_worker_count == 0:
await self._apply_settings_now()
def _empty_progress(self):
return {
"active": False, "title": "", "start_time": 0, "is_audio_only": False,
"dl_percent": 0.0, "dl_size": 0.0, "dl_total": 0.0, "dl_speed_bytes": 0.0, "dl_done": False,
"ffmpeg_active": False, "ffmpeg_done": False,
"upload_started": False, "upload_elapsed": 0.0,
"upload_current": 0.0, "upload_total": 0.0, "upload_speed": "N/A",
"final_size": 0.0, "stage": "init", "og_url": None,
}
def _get_elapsed(self, task_id):
start = self._current_downloads.get(task_id, {}).get("start_time", 0)
return time.time() - start if start > 0 else 0.0
def _build_status_message(self, task_id):
d = self._current_downloads.get(task_id, self._empty_progress())
stage = d.get("stage", "init")
is_audio = d.get("is_audio_only", False)
title = _escape_html(d.get("title", "Unknown")[:80])
elapsed = self._get_elapsed(task_id)
inner = ["---------------------------"]
if d.get("dl_done"):
dl_display = d.get("final_size") or d.get("dl_total") or d.get("dl_size", 0)
inner.append(self.strings["dl_done"].format(size=dl_display))
elif d.get("dl_percent", 0) > 0 or d.get("dl_size", 0) > 0:
pct = d.get("dl_percent", 0)
sz = d.get("dl_size", 0)
total = d.get("dl_total", 0)
inner.append(self.strings["dl_progress"].format(pct=pct, size=sz, total=total if total > 0 else sz))
else:
inner.append(self.strings["dl_waiting"])
if not is_audio:
if d.get("ffmpeg_done"):
inner.append(self.strings["merge_done"].format(size=d.get("final_size", 0)))
elif d.get("ffmpeg_active") or stage == "ffmpeg":
inner.append(self.strings["merge_active"])
else:
inner.append(self.strings["merge_waiting"])
else:
if d.get("ffmpeg_done"):
inner.append(self.strings["convert_done"].format(size=d.get("final_size", 0)))
elif d.get("ffmpeg_active") or stage == "ffmpeg":
inner.append(self.strings["convert_active"])
else:
inner.append(self.strings["convert_waiting"])
if stage == "done":
inner.append(self.strings["upload_success"].format(elapsed=d.get("upload_elapsed", 0)))
elif stage == "upload" or d.get("upload_started"):
cur = d.get("upload_current", 0.0)
total = d.get("upload_total", 0.0)
pct = (cur / total * 100) if total > 0 else 0.0
inner.append(self.strings["upload_progress"].format(
pct=pct, cur=cur, total=total if total > 0 else cur))
else:
inner.append(self.strings["upload_waiting"])
inner.append("---------------------------")
if stage in ("ffmpeg", "probe"):
speed_str = "N/A"
elif stage == "upload" or d.get("upload_started"):
speed_str = d.get("upload_speed", "N/A")
else:
speed_str = _fmt_speed(d.get("dl_speed_bytes", 0))
inner.append(self.strings["time_stage"].format(elapsed=elapsed, stage_text=f"Speed: {speed_str}"))
title_block = f"<b>{title}</b>"
debug_block = f'<pre><code class="language-grabber">{chr(10).join(inner)}</code></pre>'
return f"{title_block}\n{debug_block}"
def _make_progress_hook(self, task_id, final=True):
def _hook(d):
dl = self._current_downloads.get(task_id)
if not dl:
return
status = d.get("status")
base = dl.get("_dl_base_mb", 0.0)
if status == "downloading":
total = d.get("total_bytes") or d.get("total_bytes_estimate") or 0
downloaded = d.get("downloaded_bytes", 0)
speed = d.get("speed") or 0
cur_total_mb = total / 1024 / 1024 if total > 0 else 0
dl["dl_size"] = base + downloaded / 1024 / 1024
dl["dl_total"] = base + cur_total_mb if cur_total_mb else dl["dl_size"]
dl["dl_percent"] = (dl["dl_size"] / dl["dl_total"] * 100) if dl["dl_total"] > 0 else 0
dl["dl_speed_bytes"] = speed
dl["stage"] = "dl"
dl["active"] = True
elif status == "finished":
total = d.get("total_bytes") or d.get("total_bytes_estimate") or 0
size_mb = total / 1024 / 1024
new_base = base + size_mb if size_mb > 0 else base
dl["_dl_base_mb"] = new_base
dl["dl_size"] = new_base
dl["dl_total"] = new_base
dl["dl_percent"] = 100.0
if final:
dl["dl_done"] = True
return _hook
def _make_pp_hook(self, task_id):
def _hook(d):
dl = self._current_downloads.get(task_id)
if not dl:
return
if d.get("status") == "started":
dl["ffmpeg_active"] = True
dl["stage"] = "ffmpeg"
elif d.get("status") == "finished":
dl["ffmpeg_done"] = True
dl["ffmpeg_active"] = False
return _hook
def _extract_url(self, text):
if not text:
return None
m = _URL_PATTERN.search(text)
return m.group(0) if m else None
def _extract_bot_token(self, text):
if not text:
return None
m = _BOT_TOKEN_RE.search(text)
return m.group(0) if m else None
def _get_topic_id(self, event):
reply_to = getattr(event, "reply_to", None)
if reply_to:
return getattr(reply_to, "reply_to_top_id", None) or getattr(reply_to, "reply_to_msg_id", None)
return None
def _is_forum(self, chat):
return getattr(chat, "forum", False)
def _make_workdir(self):
name = f"job_{int(time.time() * 1000)}_{os.getpid()}"
path = os.path.join(self._cache_dir, name)
os.makedirs(path, exist_ok=True)
return path