-
Notifications
You must be signed in to change notification settings - Fork 1
/
bot.py
1777 lines (1683 loc) · 77.1 KB
/
bot.py
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
from datetime import datetime
import os
from time import time
import logging
import time as _time
from Utils.commons import load_yaml, pretty_time, threaded
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, BotCommand
from pyrogram import Client, filters
from Clients.DramaClient import DramaClient
import shutil
import asyncio
from dotenv import load_dotenv
import html
from pyrogram.enums import ParseMode
from Clients.BaseClient import BaseClient
import pyrogram.errors
import zipfile
from db import usersettings_collection as dbmongo
from bson.binary import Binary
import re
import math
from pymediainfo import MediaInfo
import sys
from io import BytesIO
import subprocess
from Utils.logger import logger
last_update_time = 0
waiting_for_photo = False
waiting_for_caption = False
waiting_for_search_drama = False
waiting_for_new_caption = False
waiting_for_user_ep_range = False
waiting_for_mirror = False
telegram_upload = False
waiting_for_zip_mirror = False
ongoing_task = False
base_client = BaseClient()
config_file = "config_udb.yaml"
config = load_yaml(config_file)
downloader_config = config["DownloaderConfig"]
max_parallel_downloads = downloader_config["max_parallel_downloads"]
thumbpath = downloader_config["thumbpath"]
ep_range_msg = None
search_res_msg = None
select_res_msg = None
send_caption_msg = None
proceed_msg = None
user_ep_range = None
caption_view_msg = None
def is_file_in_directory(filename, directory):
return 1 if os.path.isfile(os.path.join(directory, filename)) else 0
def is_thumb_in_db():
doc = dbmongo.find_one()
encoded_image = doc["thumbnail"]
if encoded_image is not None:
return 1
else:
return 0
def check_caption():
if dbmongo is not None:
document = dbmongo.find_one()
if document is not None:
caption = document["caption"]
if caption is None:
return 0
else:
return 1
else:
return 0
def convert_size(size_bytes):
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size_bytes, 1024)))
p = math.pow(1024, i)
s = round(size_bytes / p, 2)
return "%s %s" % (s, size_name[i])
if not os.path.exists(downloader_config["download_dir"]):
logger.debug(f"Creating download directory:{downloader_config['download_dir']}...")
os.makedirs(downloader_config["download_dir"])
if not os.path.exists(thumbpath):
print(f"Creating thumbnail directory:{thumbpath}...")
os.makedirs(thumbpath)
load_dotenv("config.env", override=True)
BOT_TOKEN = os.getenv("BOT_TOKEN")
if not BOT_TOKEN:
logger.error("No bot token provided.")
sys.exit(1)
OWNER_ID = int(os.getenv("OWNER_ID"))
if not BOT_TOKEN:
logger.error("No Owner id provided.")
sys.exit(1)
API_ID = os.getenv("API_ID")
if not API_ID:
logger.error("No API ID provided.")
sys.exit(1)
API_HASH = os.getenv("API_HASH")
if not API_HASH:
logger.error("No API hash provided.")
sys.exit(1)
DEFAULT_RCLONE_PATH = os.getenv("DEFAULT_RCLONE_PATH")
if not DEFAULT_RCLONE_PATH:
logger.info("No rclone path provided. Cloud upload won't work.")
RCLONE_CONF_PATH = os.getenv("RCLONE_CONF_PATH")
rclone_conf_file_path = os.path.join(RCLONE_CONF_PATH, "rclone.conf")
if not RCLONE_CONF_PATH or not os.path.isfile(rclone_conf_file_path):
logger.info("No rclone.conf found. Cloud upload won't work.")
app = Client(
"my_bot",
api_id=API_ID,
api_hash=API_HASH,
bot_token=BOT_TOKEN,
max_concurrent_transmissions=16,
)
def get_resolutions(items):
"""
genarator function to yield the resolutions of available episodes
"""
for item in items:
yield [i for i in item.keys() if i not in ("error", "original")]
def downloader(ep_details, dl_config):
"""
download function where Download Client initialization and download happens.
Accepts two dicts: download config, episode details. Returns download status.
"""
get_current_time = lambda fmt="%F %T": datetime.now().strftime(fmt)
start = get_current_time()
start_epoch = int(time())
out_file = ep_details["episodeName"]
if "downloadLink" not in ep_details:
return f'[{start}] Download skipped for {out_file}, due to error: {ep_details.get("error", "Unknown")}'
download_link = ep_details["downloadLink"]
download_type = ep_details["downloadType"]
referer = ep_details["refererLink"]
out_dir = dl_config["download_dir"]
if download_type == "hls":
logger.debug(f"Creating HLS download client for {out_file}")
from Utils.HLSDownloader import HLSDownloader
dlClient = HLSDownloader(dl_config, referer, out_file)
elif download_type == "mp4":
logger.debug(f"Creating MP4 download client for {out_file}")
from Utils.BaseDownloader import BaseDownloader
dlClient = BaseDownloader(dl_config, referer, out_file)
else:
return (3,f"[{start}] Download skipped for {out_file}, due to unknown download type [{download_type}]",)
logger.debug(f"Download started for {out_file}...")
logger.info(f"Download started for {out_file}...")
if os.path.isfile(os.path.join(f"{out_dir}", f"{out_file}")):
return 0, f"[{start}] Download skipped for {out_file}. File already exists!"
else:
try:
status, msg = dlClient.start_download(download_link)
except Exception as e:
status, msg = 1, str(e)
dlClient._cleanup_out_dirs()
end = get_current_time()
if status != 0:
return 1, f"[{end}] Download failed for {out_file}, with error: {msg}"
end_epoch = int(time())
download_time = pretty_time(end_epoch - start_epoch, fmt="h m s")
return 2, f"[{end}] Download completed for {out_file} in {download_time}!"
def batch_downloader(download_fn, links, dl_config, max_parallel_downloads):
@threaded(
max_parallel=max_parallel_downloads,
thread_name_prefix="udb-",
print_status=False,
)
def call_downloader(link, dl_config):
result = download_fn(link, dl_config)
print("results from batch-downloader", result)
return result
dl_status = call_downloader(links.values(), dl_config)
logger.debug(f"Download status: {dl_status}")
# while not all(isinstance(result, tuple) and result[0] in {0, 1} for result in dl_status):
# total_progress = sum(dl[1].get_progress_percentage() for dl in dl_status if isinstance(dl, tuple) and dl[0] == 2)
# avg_progress = total_progress / len(dl_status)
# print(f"Overall Progress: {avg_progress:.2f}%")
# _time.sleep(10)
# status_str = f"Download Summary:"
# for status in dl_status:
# status_str += f"\n{status}"
return dl_status
class DramaBot:
def __init__(self, config):
self.DCL = DramaClient(config["drama"])
self.default_ep_range = "1-16"
self.reset()
self.semaphore = asyncio.Semaphore(16)
def reset(self):
logger.info("Resetting DramaBot...")
self.waiting_for_ep_range = False
self.ep_range = None
self.ep_start = None
self.ep_end = None
self.specific_eps = []
self.target_series = None
self.episode_links = {}
self.ep_infos = None
self.target_dl_links = {}
self.series_title = None
self.episode_prefix = None
self.search_results_message_id = None
self.search_id = int(_time.time())
self.search_results = {}
self.DCL.udb_episode_dict.clear()
base_client.udb_episode_dict.clear()
if not os.path.exists(downloader_config["download_dir"]):
logger.debug(f"Creating download directory:{downloader_config['download_dir']}...")
os.makedirs(downloader_config["download_dir"])
if not os.path.exists(thumbpath):
print(f"Creating thumbnail directory:{thumbpath}...")
os.makedirs(thumbpath)
async def drama(self, client, message):
self.reset()
global ongoing_task
global search_res_msg
global waiting_for_search_drama
keyword = " ".join(message.command[1:])
if not keyword.strip():
await message.reply_text("No search keyword provided.")
ongoing_task = False
return
try:
search_results = self.DCL.search(keyword)
logger.info(f"Search results: {search_results}")
logger.info(f"Search results: {search_results}")
self.search_results = {
i + 1: result for i, result in enumerate(search_results.values())
}
except Exception as e:
logger.error(f"An error occurred during search: {e}")
await message.reply_text("An error occurred during the search.")
ongoing_task = False
self.reset()
return
if not self.search_results:
await message.reply_text("No results found.")
ongoing_task = False
self.reset()
return
keyboard = [
[
InlineKeyboardButton(
f"{result['title']} ({result['year']})",
callback_data=f"{self.search_id}:{i+1}",
)
]
for i, result in enumerate(self.search_results.values())
]
reply_markup = InlineKeyboardMarkup(keyboard)
search_res_msg = await message.reply_text(
"Search Results:", reply_markup=reply_markup
)
waiting_for_search_drama = True
async def shell(self,client, message):
try:
cmd = message.text.split(maxsplit=1)
if len(cmd) == 1:
await message.reply_text("No command to execute was given.")
return
process = await asyncio.create_subprocess_exec(
*cmd[1].split(),
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await process.communicate()
reply = ''
if stdout:
reply += f"*Stdout*\n{stdout.decode()}\n"
logger.info(f"Shell - {cmd} - {stdout.decode()}")
if stderr:
reply += f"*Stderr*\n{stderr.decode()}"
logger.error(f"Shell - {cmd} - {stderr.decode()}")
if len(reply) > 3000:
with BytesIO(str.encode(reply)) as out_file:
out_file.name = "shell_output.txt"
await app.send_document(message.chat.id, out_file)
elif len(reply) != 0:
await message.reply_text(reply)
else:
await message.reply_text('No Reply')
except Exception as e:
logger.error(f"Error in executing shell command: {e}")
await message.reply_text(f"An error occurred: {e}")
async def on_callback_query(self, client, callback_query):
global ongoing_task
global search_res_msg
global waiting_for_search_drama
search_id, series_index = map(int, callback_query.data.split(":"))
if search_id != self.search_id:
await client.answer_callback_query(
callback_query.id,
"Cannot perform search on previous results.",
show_alert=True,
)
return
await callback_query.message.edit_reply_markup(reply_markup=None)
await app.delete_messages(callback_query.message.chat.id, search_res_msg.id)
self.episode_links = {}
self.ep_infos = None
self.target_dl_links = {}
self.series_title = None
self.episode_prefix = None
episodes = []
logger.info(f"{series_index=}")
self.target_series = self.search_results[series_index]
title = self.target_series["title"]
logger.info(f"{title=}")
try:
episodes = self.DCL.fetch_episodes_list(self.target_series)
except Exception as e:
logger.error(f"An error occurred during episode fetch: {e}")
await callback_query.message.reply_text(
"An error occurred during episode fetch."
)
ongoing_task = False
return
try:
episodes_message = self.DCL.show_episode_results(
episodes, (self.ep_start, self.ep_end)
)
except Exception as e:
logger.error(f"An error occurred during episode fetch: {e}")
await callback_query.message.reply_text(
"An error occurred during episode fetch."
)
ongoing_task = False
return
global ep_message_ids
ep_message_ids = []
if episodes_message:
messages = [
episodes_message[i: i + 4096]
for i in range(0, len(episodes_message), 4096)
]
for message in messages:
logger.info("Getting episodes")
ep_msg = await callback_query.message.reply_text(message)
ep_message_ids.append(ep_msg.id)
else:
await callback_query.message.reply_text("No episodes found.")
await self.get_ep_range(client, callback_query.message, "Enter", None)
waiting_for_search_drama = False
async def on_message(self, client, message):
global ep_message_ids
global ep_range_msg
global ongoing_task
try:
for ep_msg_id in ep_message_ids:
await app.delete_messages(message.chat.id, ep_msg_id)
await app.delete_messages(message.chat.id, ep_range_msg.id)
except:
pass
if self.waiting_for_ep_range:
self.waiting_for_ep_range = False
self.ep_range = message.text or "all"
if str(self.ep_range).lower() == "all":
self.ep_range = self.default_ep_range
self.mode = "all"
else:
self.mode = "custom"
logger.info(f"Selected episode range ({self.mode=}): {self.ep_range=}")
if self.ep_range.count("-") > 1:
logger.error("Invalid input! You must specify only one range.")
return
self.ep_start, self.ep_end, self.specific_eps = 0, 0, []
for ep_range in self.ep_range.split(","):
if "-" in ep_range:
ep_range = ep_range.split("-")
if ep_range[0] == "":
ep_range[0] = self.default_ep_range.split("-")[0]
if ep_range[1] == "":
ep_range[1] = self.default_ep_range.split("-")[1]
self.ep_start, self.ep_end = map(float, ep_range)
else:
self.specific_eps.append(float(ep_range))
try:
episodes = self.DCL.fetch_episodes_list(self.target_series)
except Exception as e:
logger.error(f"An error occurred during episode fetch: {e}")
await message.reply_text("An error occurred during episode fetch.")
ongoing_task = False
return
await self.show_episode_links(
client, message, episodes, self.ep_start, self.ep_end, self.specific_eps
)
async def show_episode_links(
self, client, message, episodes, ep_start, ep_end, specific_eps
):
global select_res_msg
global ep_infos_msg_id
global ongoing_task
message_patience = await message.reply_text(
"Fetching episode links, Be patience😊😊😊..."
)
try:
self.episode_links, self.ep_infos = self.DCL.fetch_episode_links(
episodes, ep_start, ep_end, specific_eps
)
except Exception as e:
logger.error(f"An error occurred during episode fetch: {e}")
await message.reply_text("An error occurred during episode fetch.")
ongoing_task = False
return
try:
await app.delete_messages(message.chat.id, user_ep_range)
await app.delete_messages(message.chat.id, message_patience.id)
except:
pass
info_text = "\n".join(self.ep_infos)
info_texts = [info_text[i: i + 4096]
for i in range(0, len(info_text), 4096)]
ep_infos_msg_id = []
for info in info_texts:
ep_info_msg = await message.reply_text(info)
ep_infos_msg_id.append(ep_info_msg.id)
valid_resolutions = []
valid_resolutions_gen = get_resolutions(self.episode_links.values())
for _valid_res in valid_resolutions_gen:
valid_resolutions = _valid_res
if len(valid_resolutions) > 0:
break
else:
valid_resolutions = ["360", "480", "720", "1080"]
self.series_title, self.episode_prefix = self.DCL.set_out_names(
self.target_series
)
downloader_config["download_dir"] = os.path.join( f"{downloader_config['download_dir']}", f"{self.series_title}")
logger.info(f"{valid_resolutions=}")
keyboard = InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
text=res, callback_data=f"{self.search_id}:{res}"
)
]
for res in valid_resolutions
]
)
select_res_msg = await message.reply_text(
"Please select a resolution:", reply_markup=keyboard
)
async def get_ep_range(self, client, message, mode="Enter", _episodes_predef=None):
global ep_range_msg
global waiting_for_user_ep_range
if _episodes_predef:
self.ep_range = _episodes_predef
else:
ep_range_msg = await message.reply_text(
f"\n{mode} episodes to download (ex: 1-16): "
)
self.waiting_for_ep_range = True
waiting_for_user_ep_range = True
async def on_callback_query_resoloution(self, client, callback_query):
global ep_details_msg_ids
global select_res_msg
global ep_infos_msg_id
ep_details_msg_ids = []
global proceed_msg
global ongoing_task
await callback_query.message.edit_reply_markup(reply_markup=None)
await app.delete_messages(callback_query.message.chat.id, select_res_msg.id)
for ep_info_msg_id in ep_infos_msg_id:
await app.delete_messages(callback_query.message.chat.id, ep_info_msg_id)
search_id, resint = map(int, callback_query.data.split(":"))
resolution = str(resint)
if search_id != self.search_id:
await client.answer_callback_query(
callback_query.id,
"Cannot select resolution on previous results.",
show_alert=True,
)
return
try:
self.target_dl_links = self.DCL.fetch_m3u8_links(
self.episode_links, resolution, self.episode_prefix
)
except Exception as e:
logger.error(f"An error occurred during episode fetch: {e}")
await callback_query.message.reply_text(
"An error occurred during episode fetch."
)
ongoing_task = False
return
all_ep_details_text = ""
for ep, details in self.target_dl_links.items():
episode_name = details["episodeName"]
episode_subs = details["episodeSubs"]
ep_details_text = (
f"Episode {ep}:\nName: {episode_name}\nSubs: {episode_subs}"
)
all_ep_details_text += ep_details_text
all_ep_details_texts = [
all_ep_details_text[i: i + 4096]
for i in range(0, len(all_ep_details_text), 4096)
]
for text in all_ep_details_texts:
ep_details_msg = await callback_query.message.reply_text(text)
ep_details_msg_ids.append(ep_details_msg.id)
available_dl_count = len(
[
k
for k, v in self.target_dl_links.items()
if v.get("downloadLink") is not None
]
)
logger.info("Links Found!!")
msg = f"Episodes available for download [{available_dl_count}/{len(self.target_dl_links)}].Proceed to download?"
keyboard = InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
"Yes", callback_data=f"{self.search_id}:download_yes"
),
InlineKeyboardButton(
"No", callback_data=f"{self.search_id}:download_no"
),
]
]
)
proceed_msg = await callback_query.message.reply_text(
msg, reply_markup=keyboard
)
if len(self.target_dl_links) == 0:
logger.error("No episodes available to download! Exiting.")
await callback_query.message.reply_text(
"No episodes available to download! Exiting."
)
await callback_query.message.edit_reply_markup(reply_markup=None)
ongoing_task = False
return
async def on_callbackquery_download(self, client, callback_query):
global telegram_upload
global waiting_for_mirror
global waiting_for_zip_mirror
global ongoing_task
if telegram_upload:
async def send_document(
client,
chat_id,
document,
progress,
progress_args,
thumb=None,
caption=None,
parse_mode=None,
):
async with self.semaphore:
filename = os.path.basename(document)
logger.debug(f"Uploading {filename} with {os.getpid()}")
await asyncio.sleep(1)
message = await client.send_message(
chat_id, f"Starting upload of {filename}"
)
try:
return await client.send_document(
chat_id,
document=document,
progress=progress,
progress_args=(
message,
*progress_args,
),
thumb=thumb,
caption=caption,
parse_mode=parse_mode,
)
finally:
await client.delete_messages(chat_id, message.id)
search_id, action = callback_query.data.split(":")
int_search_id = int(search_id)
if int_search_id != self.search_id:
await client.answer_callback_query(
callback_query.id,
"Cannot download previous selections",
show_alert=True,
)
return
if action == "download_yes":
await callback_query.message.edit_reply_markup(reply_markup=None)
await app.delete_messages(
callback_query.message.chat.id, proceed_msg.id
)
for ep_details_msg_id in ep_details_msg_ids:
await app.delete_messages(
callback_query.message.chat.id, ep_details_msg_id
)
start_msg = await callback_query.message.reply_text(
"Downloading episodes..."
)
logger.info("Downloading episodes...")
download_results = batch_downloader(
downloader,
self.target_dl_links,
downloader_config,
max_parallel_downloads,
)
status_message_ids = []
for status, message in download_results:
sent_message = await callback_query.message.reply_text(message)
status_message_ids.append(sent_message.id)
await client.delete_messages(
callback_query.message.chat.id, start_msg.id
)
directory = downloader_config["download_dir"]
last_update_times = {}
async def progress(current, total, message, filename):
now = _time.time()
pct = current * 100 / total
pct_str = f"{filename} : {pct:.1f}%"
convert_total = convert_size(total)
convert_current = convert_size(current)
pct = float(str(pct).strip("%"))
p = min(max(pct, 0), 100)
cFull = int(p // 8)
cPart = int(p % 8 - 1)
p_str = "■" * cFull
if cPart >= 0:
p_str += ["▤", "▥", "▦", "▧", "▨", "▩", "■"][cPart]
p_str += "□" * (12 - cFull)
progress_bar = f"[{p_str}]"
progress_text = f"Uploading to telegram {pct_str} {progress_bar} {convert_current}/{convert_total}"
if message.text != progress_text:
if (
filename not in last_update_times
or now - last_update_times[filename] > 10
):
try:
await message.edit_text(progress_text)
last_update_times[filename] = now
except (
pyrogram.errors.exceptions.bad_request_400.MessageNotModified
):
pass
await asyncio.sleep(1)
try:
upload_tasks = []
for filename in os.listdir(directory):
filepath = os.path.join(directory, filename)
if os.path.isfile(filepath) and filename.endswith(".mp4"):
media_info = MediaInfo.parse(filepath)
for track in media_info.tracks:
if track.track_type == "Video":
milliseconds = track.duration
if milliseconds is not None:
seconds, milliseconds = divmod(
milliseconds, 1000
)
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
if hours > 0:
duration = f"{hours}h{minutes}m{seconds}s"
elif minutes > 0:
duration = f"{minutes}m{seconds}s"
else:
duration = f"{seconds}s"
else:
duration = "Unknown"
file_size = os.path.getsize(filepath)
print(f"File size: {file_size}")
file_size_con = convert_size(file_size)
break
doc = dbmongo.find_one()
encoded_image = doc["thumbnail"]
known_keys = {"filename", "size", "duration"}
def format_caption(caption, **kwargs):
try:
return caption.format(**kwargs)
except KeyError as e:
print(f"Caption contains unrecognized format: {e}")
unrecognized_key = str(e).strip("'")
# Remove the unrecognized format placeholder
return re.sub(rf"\{{{unrecognized_key}\}}", "", caption)
unformat_caption_db = doc["caption"]
caption_db = format_caption(unformat_caption_db, filename=filename, size=file_size_con, duration=duration)
if encoded_image is not None and caption_db is None:
with open("thumbnail.jpg", "wb") as f:
f.write(encoded_image)
task = send_document(
client,
callback_query.from_user.id,
document=filepath,
progress=progress,
progress_args=(
os.path.basename(filename),),
thumb="thumbnail.jpg",
)
upload_tasks.append(
asyncio.create_task(task))
elif encoded_image is None and caption_db is None:
task = send_document(
client,
callback_query.from_user.id,
document=filepath,
progress=progress,
progress_args=(
os.path.basename(filename),),
)
upload_tasks.append(asyncio.create_task(task))
elif encoded_image is not None and caption_db is not None:
file_name = html.escape(
os.path.basename(filepath))
caption = caption_db.format(
filename=html.escape(file_name),
size=html.escape(file_size_con),
duration=html.escape(duration),
)
with open("thumbnail.jpg", "wb") as f:
f.write(encoded_image)
task = send_document(
client,
callback_query.from_user.id,
document=filepath,
progress=progress,
progress_args=(
os.path.basename(filename),),
thumb="thumbnail.jpg",
caption=caption,
parse_mode=ParseMode.HTML,
)
upload_tasks.append(
asyncio.create_task(task))
elif encoded_image is None and caption_db is not None:
file_name = html.escape(
os.path.basename(filepath))
caption = caption_db.format(
filename=html.escape(file_name),
size=html.escape(file_size_con),
duration=html.escape(duration),
)
task = send_document(
client,
callback_query.from_user.id,
document=filepath,
progress=progress,
progress_args=(
os.path.basename(filename),),
caption=caption,
parse_mode=ParseMode.HTML,
)
upload_tasks.append(asyncio.create_task(task))
try:
await asyncio.gather(*upload_tasks)
except Exception as e:
logger.error(
f"An error occurred while sending files: {e}")
await app.send_message(
callback_query.message.chat.id,
f"An error occurred while sending files.",
)
finally:
self.reset()
telegram_upload = False
ongoing_task = False
except Exception as e:
logger.error(f"An error occurred while sending files: {e}")
await app.send_message(
callback_query.message.chat.id,
"An error occurred while sending files.",
)
ongoing_task = False
telegram_upload = False
finally:
if os.path.exists(directory):
try:
shutil.rmtree(directory)
logger.info(f"Deleted {directory}")
ongoing_task = False
telegram_upload = False
await app.send_message(
callback_query.message.chat.id,
"All Episodes Uploaded.",
)
for status_msg_id in status_message_ids:
await app.delete_messages(
callback_query.message.chat.id, status_msg_id
)
await asyncio.sleep(1)
except Exception as e:
logger.error(f"An error occurred while deleting {directory}: {e}")
await app.send_message(
callback_query.message.chat.id,f"An error occurred while deleting {directory}.",)
ongoing_task = False
telegram_upload = False
else:
await callback_query.message.reply_text("Download cancelled.")
await callback_query.message.edit_reply_markup(reply_markup=None)
await app.delete_messages(
callback_query.message.chat.id, proceed_msg.id
)
for ep_details_msg_id in ep_details_msg_ids:
await app.delete_messages(
callback_query.message.chat.id, ep_details_msg_id
)
self.reset()
logger.info("Download cancelled.")
ongoing_task = False
telegram_upload = False
try:
if os.path.exists(directory):
shutil.rmtree(directory)
except Exception as e:
logger.error(f"An error occurred while deleting {directory}: {e}")
elif waiting_for_mirror:
search_id, action = callback_query.data.split(":")
int_search_id = int(search_id)
if int_search_id != self.search_id:
await client.answer_callback_query(
callback_query.id,
"Cannot download previous selections",
show_alert=True,
)
return
if action == "download_yes":
await callback_query.message.edit_reply_markup(reply_markup=None)
await app.delete_messages(
callback_query.message.chat.id, proceed_msg.id
)
for ep_details_msg_id in ep_details_msg_ids:
await app.delete_messages(
callback_query.message.chat.id, ep_details_msg_id
)
start_msg = await callback_query.message.reply_text(
"Downloading episodes..."
)
logger.debug("Downloading episodes...")
download_results = batch_downloader(
downloader,
self.target_dl_links,
downloader_config,
max_parallel_downloads,
)
status_message_ids = []
for status, message in download_results:
sent_message = await callback_query.message.reply_text(message)
status_message_ids.append(sent_message.id)
await client.delete_messages(
callback_query.message.chat.id, start_msg.id
)
directory = downloader_config["download_dir"]
def get_progress_bar_string(pct):
pct = float(str(pct).strip("%"))
p = min(max(pct, 0), 100)
cFull = int(p // 8)
cPart = int(p % 8 - 1)
p_str = "■" * cFull
if cPart >= 0:
p_str += ["▤", "▥", "▦", "▧", "▨", "▩", "■"][cPart]
p_str += "□" * (12 - cFull)
return f"[{p_str}]"
async def rclone_copy(filepath, upload_msg, filename):
cmd = [
"rclone",
"copy",
f"--config={RCLONE_CONF_PATH}rclone.conf",
filepath,
f"{DEFAULT_RCLONE_PATH}",
"-P",
]
logger.debug(cmd)
process = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
progress_regex = re.compile(
r"Transferred:\s+([\d.]+\s*\w+)\s+/\s+([\d.]+\s*\w+),\s+([\d.]+%)\s*,\s+([\d.]+\s*\w+/s),\s+ETA\s+([\dwdhms]+)"
)
last_progress = None
update_interval = 10
last_update_time = _time.time()
while True:
line = await process.stdout.readline()
if not line:
break
line = line.decode().strip()
print("lines", line)
match = progress_regex.findall(line)
if match:
transferred, total, percent, speed, eta = match[0]
progress_bar = get_progress_bar_string(percent)
current_progress = f"Transferred: {transferred}, Total: {total}, Percent: {percent}, Speed: {speed}, ETA: {eta}"
if current_progress != last_progress:
if _time.time() - last_update_time >= update_interval:
try:
await app.edit_message_text(
callback_query.message.chat.id,
upload_msg.id,
f"Upload progress of {filename}: {progress_bar}Transferred {transferred} out of Total {total} {percent} ETA: {eta} Speed: {speed}",)
last_update_time = _time.time()
except pyrogram.errors.MessageNotModified:
pass
last_progress = current_progress
await process.wait()
if process.returncode != 0:
logger.debug(f"Error copying file {filepath}")
else:
logger.debug(f"Successfully copied file {filepath}")
return process.returncode
async def upload_files(directory):
global waiting_for_mirror
global ongoing_task
try:
files = [
os.path.join(directory, filename)
for filename in os.listdir(directory)
if os.path.isfile(os.path.join(directory, filename))
and filename.endswith(".mp4")
]
semaphore = asyncio.Semaphore(16)
async def upload_file(filepath):
async with semaphore:
filename = os.path.basename(filepath)
upload_msg = await app.send_message(
callback_query.message.chat.id,
f"Starting upload of {os.path.basename(filepath)}...",)
return_code = await rclone_copy(
filepath, upload_msg, filename
)
if return_code == 0:
await app.edit_message_text(
callback_query.message.chat.id,
upload_msg.id,
f"Upload of {filename} is completed.",
)
else:
await app.edit_message_text(
callback_query.message.chat.id,
upload_msg.id,
f"Error uploading {filename}.",
)
tasks = [upload_file(filepath) for filepath in files]
await asyncio.gather(*tasks)
await app.send_message(
callback_query.message.chat.id,
"All uploads completed",
)
for status_msg_id in status_message_ids:
await app.delete_messages(
callback_query.message.chat.id, status_msg_id
)
await asyncio.sleep(1)
shutil.rmtree(directory)
waiting_for_mirror = False
ongoing_task = False
except Exception as e:
logger.error(f"An error occurred while uploading files: {e}")
await app.send_message(
callback_query.message.chat.id,
"An error occurred while uploading files.",
)
waiting_for_mirror = False
ongoing_task = False