File size: 50,459 Bytes
7c86d85
 
 
 
 
743df0a
3845bb3
abc3ce6
7709415
 
7c86d85
 
caa3da8
52e9f8b
caa3da8
 
52e9f8b
caa3da8
52e9f8b
caa3da8
7c86d85
 
 
fc029b5
eaebdc4
7c86d85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f32a467
 
 
 
7c86d85
52e9f8b
 
7709415
 
 
 
 
 
 
 
 
64e75b2
 
7709415
 
 
64e75b2
7709415
 
64e75b2
 
 
7709415
 
 
 
 
caa3da8
743df0a
 
 
 
 
 
 
 
 
 
 
 
 
097a907
 
 
 
 
 
 
 
 
da70714
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6857dad
3845bb3
da70714
 
 
 
 
 
 
 
 
 
 
caa3da8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da70714
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4d03e6
da70714
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3845bb3
da70714
eda0c59
da70714
3845bb3
da70714
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4d03e6
da70714
 
f4d03e6
 
 
 
da70714
 
 
 
 
f4d03e6
da70714
 
 
 
 
 
 
 
 
 
 
f4d03e6
da70714
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
caa3da8
 
 
 
 
7c86d85
 
3845bb3
7709415
3845bb3
 
7709415
 
 
3845bb3
 
 
c70ee3d
 
3845bb3
 
7c86d85
7709415
 
3845bb3
 
7c86d85
0057bca
7709415
3845bb3
 
7c86d85
7709415
 
0057bca
7c86d85
 
 
 
caa3da8
097a907
caa3da8
7c86d85
 
097a907
3845bb3
7c86d85
 
 
 
 
097a907
 
caa3da8
7c86d85
caa3da8
7c86d85
 
 
caa3da8
 
 
 
 
7c86d85
 
 
e437188
7c86d85
7709415
3845bb3
7709415
 
eda0c59
7709415
 
7c86d85
 
 
 
caa3da8
 
7c86d85
3845bb3
7c86d85
7709415
 
 
 
 
 
7c86d85
 
 
caa3da8
 
7c86d85
caa3da8
 
7c86d85
3845bb3
7709415
 
 
 
 
 
 
 
7c86d85
 
 
 
caa3da8
64e75b2
c70ee3d
caa3da8
 
7c86d85
caa3da8
64e75b2
 
 
 
 
 
 
 
 
 
 
097a907
 
 
64e75b2
 
097a907
64e75b2
 
 
 
 
7c86d85
64e75b2
7c86d85
64e75b2
 
 
 
 
3845bb3
7c86d85
 
 
7709415
 
7c86d85
7709415
caa3da8
743df0a
 
 
 
097a907
 
 
743df0a
7c86d85
097a907
64e75b2
 
 
 
 
 
 
 
 
 
 
 
743df0a
 
 
097a907
743df0a
7709415
097a907
 
743df0a
097a907
 
3845bb3
 
 
 
 
 
743df0a
 
 
7709415
 
097a907
 
743df0a
7709415
 
64e75b2
743df0a
097a907
743df0a
 
7709415
 
097a907
 
7709415
743df0a
 
 
 
 
 
da70714
 
743df0a
 
 
da70714
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
743df0a
 
3845bb3
743df0a
3845bb3
64e75b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
743df0a
7709415
743df0a
 
64e75b2
743df0a
 
097a907
743df0a
 
64e75b2
743df0a
 
 
 
 
64e75b2
097a907
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
743df0a
 
097a907
743df0a
 
64e75b2
743df0a
 
 
 
 
 
 
 
7709415
743df0a
64e75b2
743df0a
 
 
 
 
097a907
 
 
743df0a
 
 
 
 
 
 
64e75b2
743df0a
 
 
7c86d85
da70714
 
7c86d85
 
 
 
 
 
 
 
 
7709415
7c86d85
 
f4d03e6
 
7c86d85
64e75b2
 
 
 
 
52e9f8b
7c86d85
caa3da8
7c86d85
 
 
 
e437188
7c86d85
e437188
7c86d85
e437188
 
3845bb3
7c86d85
097a907
7c86d85
 
 
 
f4d03e6
7c86d85
 
 
64e75b2
7709415
64e75b2
7709415
f32a467
7709415
 
 
 
52e9f8b
7709415
 
f4d03e6
 
caa3da8
3845bb3
7709415
f4d03e6
64e75b2
 
 
 
 
 
8de7108
64e75b2
7709415
 
 
 
 
 
 
f32a467
 
7709415
f4d03e6
 
 
 
 
 
8de7108
f4d03e6
 
 
e4dda13
f4d03e6
 
7709415
caa3da8
f4d03e6
7709415
 
 
 
 
 
 
 
 
 
7c86d85
 
 
 
f4d03e6
f32a467
6857dad
f32a467
6857dad
 
 
f4d03e6
6857dad
 
 
f4d03e6
f32a467
 
f4d03e6
f32a467
f4d03e6
7c86d85
 
52e9f8b
7c86d85
52e9f8b
7c86d85
52e9f8b
7c86d85
52e9f8b
7c86d85
52e9f8b
7c86d85
52e9f8b
7c86d85
52e9f8b
 
 
 
 
 
caa3da8
097a907
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abc3ce6
 
 
caa3da8
3845bb3
 
 
 
 
 
f4d03e6
 
3845bb3
 
7709415
743df0a
3845bb3
 
 
7709415
 
 
 
6857dad
3845bb3
 
7709415
 
7c86d85
caa3da8
7c86d85
 
52e9f8b
7c86d85
64e75b2
8de7108
f4d03e6
64e75b2
f4d03e6
8de7108
 
 
 
 
 
 
 
 
 
f4d03e6
8de7108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
caa3da8
 
 
 
f32a467
ec84a1e
7c86d85
f4d03e6
3d43e7e
caa3da8
7c86d85
64e75b2
 
 
 
 
7c86d85
743df0a
 
 
 
 
 
 
 
7c86d85
 
caa3da8
3845bb3
7c86d85
52e9f8b
f4d03e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52e9f8b
 
 
 
 
3845bb3
 
52e9f8b
 
f32a467
3845bb3
 
c8efef9
f4d03e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f32a467
 
 
 
 
 
 
c8efef9
f4d03e6
 
7c86d85
f4d03e6
 
52e9f8b
 
 
 
743df0a
52e9f8b
 
 
 
7c86d85
7709415
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
1001
1002
import os
import asyncio 
import time
import math
import re
import subprocess
from pyrogram import Client, filters, enums
from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
from pyrogram.errors import FloodWait, RPCError
from config import API_ID, API_HASH, ADMINS, CHANNEL_ID, WAITING_TIME
from db import db

try:
    from TechVJ.TechVJ.fast_download import fast_download_file
except ImportError:
    try:
        from TechVJ.fast_download import fast_download_file
    except ImportError:
        from fast_download import fast_download_file

class batch_temp(object):
    IS_BATCH = {}
    CLONE_DATA = {}
    LAST_SAVED_ID = {}

def humanbytes(size):
    if not size:
        return "0 B"
    power = 1024
    t_n = 0
    power_labels = {0: ' ', 1: 'K', 2: 'M', 3: 'G', 4: 'T'}
    while size > power:
        size /= power
        t_n += 1
    return f"{round(size, 2)} {power_labels[t_n]}B"

def time_formatter(seconds: int) -> str:
    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)
    days, hours = divmod(hours, 24)
    tmp = ((str(days) + "d, ") if days else "") + \
        ((str(hours) + "h, ") if hours else "") + \
        ((str(minutes) + "m, ") if minutes else "") + \
        ((str(seconds) + "s") if seconds else "")
    return tmp if tmp else "0s"

async def progress_bar(current, total, ud_type, message, start, fname="", current_idx=1, total_count=1, user_id=None):
    if user_id and batch_temp.IS_BATCH.get(user_id):
        raise asyncio.CancelledError("Task cancelled by user.")

    now = time.time()
    diff = max(1e-3, now - start)
    if round(diff % 2.0) == 0 or current == total:
        percentage = current * 100 / total if total > 0 else 0
        speed = current / diff if diff > 0 else 0
        elapsed_time = round(diff)
        eta = round((total - current) / speed) if speed > 0 else 0

        bar_length = 10
        filled_length = int(bar_length * current // total) if total > 0 else 0
        bar = '▰' * filled_length + '▱' * (bar_length - filled_length)

        fname_text = f"📁 **फ़ाइल:** `{fname[:30]}...`\n" if fname else ""
        remaining = max(0, total_count - current_idx)

        status_text = (
            f"**{ud_type}**\n"
            f"📊 **प्रगति:** `[{current_idx}/{total_count}]` | ⏳ **शेष:** `{remaining}`\n"
            f"{fname_text}"
            f"[{bar}] {percentage:.1f}%\n"
            f"⚡ **स्पीड:** {humanbytes(speed)}/s\n"
            f"📦 **डन:** {humanbytes(current)} / {humanbytes(total)}\n"
            f"⏱️ **ETA:** {time_formatter(eta)} | **समय:** {time_formatter(elapsed_time)}"
        )
        try:
            await message.edit_text(status_text)
        except Exception:
            pass

def generate_auto_thumb(video_path: str, thumb_path: str):
    try:
        cmd = [
            "ffmpeg", "-ss", "00:00:02", "-i", video_path,
            "-vframes", "1", "-q:v", "2", thumb_path, "-y"
        ]
        subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        if os.path.exists(thumb_path):
            return thumb_path
    except Exception:
        pass
    return None

def strip_all_urls(text: str) -> str:
    if not text:
        return ""
    text = re.sub(r'\[([^\]]+)\]\((https?://[^\)]+|t\.me/[^\)]+)\)', r'\1', text)
    text = re.sub(r'https?://\S+|www\.\S+', '', text)
    text = re.sub(r't\.me/\S+', '', text)
    text = re.sub(r'\n{3,}', '\n\n', text).strip()
    return text

# ==================== सामान्य व सूचना कमांड्स ====================

@Client.on_message(filters.command("start") & filters.private)
async def start_msg_handler(client: Client, message: Message):
    user_id = message.from_user.id
    name = message.from_user.first_name
    db.add_user(user_id, name)
    
    start_text = (
        f"👋 **नमस्ते {name}!**\n\n"
        "🚀 **SRC Content Cloner & Forwarder Bot** में आपका स्वागत है।\n"
        "इस बॉट के माध्यम से आप किसी भी पब्लिक, प्राइवेट चैनल, ग्रुप, टॉपिक या बॉट से फ़ाइलें सीधे अपने चैनल/ग्रुप में क्लोन कर सकते हैं।\n\n"
        "📌 **मुख्य फीचर्स:**\n"
        "• सुपरफास्ट डाउनलोडिंग व अपलोडिंग\n"
        "• टॉपिक (Forum Topics) सपोर्ट\n"
        "• कैप्शन रिप्लेसमेंट, लिंक्स रिमूवर व हाइपरलिंक टूल\n"
        "• ऑटो थंबनेल व रेज़्यूम सपोर्ट\n\n"
        "👉 शुरू करने के लिए **/clone** लिखें या नीचे दिए गए बटन्स का उपयोग करें।"
    )
    buttons = InlineKeyboardMarkup([
        [InlineKeyboardButton("📖 उपयोग कैसे करें (Guide)", callback_data="nav_howtouse"),
         InlineKeyboardButton("💎 VIP प्लान्स", callback_data="nav_plans")],
        [InlineKeyboardButton("📢 चैनल में अपलोड हेल्प", callback_data="nav_channelhelp"),
         InlineKeyboardButton("⚡ स्पीड गाइड", callback_data="nav_speedhelp")],
        [InlineKeyboardButton("👤 मेरा VIP स्टेटस", callback_data="nav_myplan"),
         InlineKeyboardButton("🌐 भाषा (Language)", callback_data="nav_lang")]
    ])
    await message.reply_text(start_text, reply_markup=buttons)

@Client.on_message(filters.command("id"))
async def get_id(client: Client, message: Message):
    chat_id = message.chat.id
    user_id = message.from_user.id if message.from_user else (message.sender_chat.id if message.sender_chat else "Unknown")
    thread_id = getattr(message, "message_thread_id", None)
    
    response = f"📍 **चैट/ग्रुप ID:** `{chat_id}`\n👤 **आपकी ID:** `{user_id}`"
    if thread_id:
        response += f"\n🧵 **टॉपिक/थ्रेड ID:** `{thread_id}`"
        
    if message.reply_to_message:
        rep = message.reply_to_message
        rep_user = rep.from_user.id if rep.from_user else (rep.sender_chat.id if rep.sender_chat else "Anonymous")
        response += f"\n\n↩️ **रिप्लाई यूजर ID:** `{rep_user}`"
        if rep.forward_from_chat:
            response += f"\n📢 **फॉरवर्ड चैट ID:** `{rep.forward_from_chat.id}`"
    await message.reply_text(response)

@Client.on_message(filters.command(["plans"]) & filters.private)
async def plans_handler(client: Client, message: Message):
    plans = db.get_all_plans()
    text = (
        "💎 **उपलब्ध VIP प्लान्स और कीमतें:**\n"
        "━━━━━━━━━━━━━━━━━━━━\n"
        f"🔹 **1 दिन (Trial):** ₹{plans.get('1day', '20')}\n"
        f"🔹 **5 दिन:** ₹{plans.get('5days', '50')}\n"
        f"🔹 **15 दिन:** ₹{plans.get('15days', '120')}\n"
        f"🔹 **30 दिन (महीना):** ₹{plans.get('30days', '199')}\n"
        "━━━━━━━━━━━━━━━━━━━━\n"
        "💳 पेमेंट करने के लिए **/pay** या **/buy** कमांड भेजें।"
    )
    await message.reply_text(text)

@Client.on_message(filters.command(["myplan", "info"]) & filters.private)
async def myplan_handler(client: Client, message: Message):
    user_id = message.from_user.id
    is_vip = db.is_user_vip(user_id, ADMINS)
    user_data = db.get_user(user_id)
    
    if user_id in ADMINS:
        return await message.reply_text("👑 **आप बॉट के एडमिन हैं!** आपके पास आजीवन असीमित VIP एक्सेस है।")
        
    if is_vip and user_data and user_data.get("plan_expiry"):
        exp = str(user_data["plan_expiry"])[:19].replace("T", " ")
        await message.reply_text(f"✅ **आप एक एक्टिव VIP मेंबर हैं!**\n\n⏳ **वैधता (Expiry):** `{exp} UTC`")
    else:
        await message.reply_text("❌ **आपके पास वर्तमान में कोई एक्टिव VIP प्लान नहीं है।**\n\nप्लान देखने के लिए /plans और खरीदने के लिए /pay भेजें।")

@Client.on_message(filters.command(["pay", "buy", "payment"]) & filters.private)
async def pay_handler(client: Client, message: Message):
    pay_text = (
        "💳 **VIP सब्सक्रिप्शन पेमेंट निर्देश:**\n"
        "━━━━━━━━━━━━━━━━━━━━\n"
        "1. नीचे दिए गए UPI QR कोड या UPI ID पर भुगतान करें:\n"
        "👉 UPI ID: `sachin4sharma1210@sbi` (या एडमिन से संपर्क करें)\n\n"
        "2. भुगतान पूरा होने के बाद उसका **स्क्रीनशॉट (Screenshot)** और अपनी **User ID** एडमिन को भेजें।\n\n"
        "👨‍💻 **एडमिन संपर्क:** @Sachin4Sharma1210\n"
        "━━━━━━━━━━━━━━━━━━━━\n"
        "वेरिफिकेशन के 5-10 मिनट के अंदर आपका VIP प्लान एक्टिव कर दिया जाएगा।"
    )
    await message.reply_text(pay_text)

@Client.on_message(filters.command(["howtouse", "help"]) & filters.private)
async def howtouse_handler(client: Client, message: Message):
    help_text = (
        "📖 **बॉट का उपयोग कैसे करें? (Quick Guide)**\n"
        "━━━━━━━━━━━━━━━━━━━━\n"
        "1️⃣ सबसे पहले **/login** कमांड भेजकर अपना टेलीग्राम अकाउंट बॉट से कनेक्ट करें।\n"
        "2️⃣ इसके बाद **/clone** कमांड भेजें।\n"
        "3️⃣ जहाँ से कंटेंट कॉपी करना है, उसकी **पहली लिंक (Start Link)** भेजें।\n"
        "4️⃣ इसके बाद **अंतिम लिंक (End Link)** भेजें (अगर एक ही मैसेज चाहिए तो `/single` लिखें)।\n"
        "5️⃣ जिस चैनल में अपलोड करना है, उसका लिंक/आईडी भेजें (सीधे बॉट में पाने के लिए `/skip` लिखें)।\n"
        "6️⃣ कस्टमाइज़ेशन मेन्यू खुलेगा, जहाँ आप नया कैप्शन, वर्ड रिप्लेसमेंट, लिंक्स रिमूवर या थंबनेल सेट करके **🚀 Confirm & Start** दबाएँ।"
    )
    await message.reply_text(help_text)

@Client.on_message(filters.command(["channelhelp"]) & filters.private)
async def channelhelp_handler(client: Client, message: Message):
    text = (
        "📢 **चैनल/ग्रुप में अपलोडिंग सेटअप गाइड:**\n"
        "━━━━━━━━━━━━━━━━━━━━\n"
        "यदि आप फाइल्स को सीधे अपने किसी चैनल या ग्रुप में भेजना चाहते हैं, तो:\n\n"
        "1. अपने चैनल/ग्रुप में **बॉट** और **अपने उस अकाउंट (जिससे लॉगिन किया है)** दोनों को **Admin** बनाएँ।\n"
        "2. एडमिन बनाते समय **'Post Messages'** की अनुमति अवश्य दें।\n"
        "3. स्टेप 3 में चैनल की ID (जैसे: `-1001234567890`) या पब्लिक यूज़रनेम (जैसे: `@mychannel`) भेजें।"
    )
    await message.reply_text(text)

@Client.on_message(filters.command(["speedhelp", "slowspeed"]) & filters.private)
async def speedhelp_handler(client: Client, message: Message):
    text = (
        "⚡ **स्पीड और परफॉरमेंस से जुड़ी जानकारी:**\n"
        "━━━━━━━━━━━━━━━━━━━━\n"
        "• बॉट मल्टी-थ्रेडेड और फ़ास्ट ट्रांसमिशन मोड पर काम करता है।\n"
        "• टेलीग्राम सर्वर के नियमों के अनुसार बड़ी फाइल्स ट्रांसफर करते समय बीच में 2-3 सेकंड का सेफ टाइमआउट आवश्यक होता है ताकि आपका अकाउंट बैन या म्यूट न हो।\n"
        "• यदि स्पीड धीमी लगे, तो कृपया सुनिश्चित करें कि जिस सोर्स चैनल से कंटेंट आ रहा है, उसका सर्वर लोड कम हो।"
    )
    await message.reply_text(text)

@Client.on_message(filters.command(["lang", "language"]) & filters.private)
async def lang_handler(client: Client, message: Message):
    markup = InlineKeyboardMarkup([
        [InlineKeyboardButton("🇮🇳 हिन्दी (Hindi)", callback_data="setlang_hi"),
         InlineKeyboardButton("🇬🇧 English", callback_data="setlang_en")]
    ])
    await message.reply_text("🌐 **कृपया बॉट की भाषा चुनें / Choose Language:**", reply_markup=markup)

# ==================== एडमिन कमांड्स ====================

@Client.on_message(filters.command("users") & filters.private)
async def users_admin_handler(client: Client, message: Message):
    user_id = message.from_user.id
    if user_id not in ADMINS:
        return
    users = db.get_all_users()
    vip_count = 0
    for u in users:
        if u.get("plan_expiry"):
            vip_count += 1
    await message.reply_text(f"📊 **बॉट आँकड़े (Admin Panel):**\n\n👥 कुल रजिस्टर्ड यूजर्स: `{len(users)}`\n💎 एक्टिव VIP यूजर्स: `{vip_count}`")

@Client.on_message(filters.command("setprice") & filters.private)
async def setprice_handler(client: Client, message: Message):
    user_id = message.from_user.id
    if user_id not in ADMINS:
        return
    args = message.text.split()
    if len(args) != 3:
        return await message.reply_text("⚠️ **उपयोग:** `/setprice <plan_key> <price>`\n(Keys: `1day`, `5days`, `15days`, `30days`)")
    key, price = args[1], args[2]
    db.set_plan_price(key, price)
    await message.reply_text(f"✅ प्लान `{key}` की कीमत सफलतापूर्वक ₹`{price}` सेट कर दी गई है।")

@Client.on_message(filters.command("broadcast") & filters.private)
async def broadcast_handler(client: Client, message: Message):
    user_id = message.from_user.id
    if user_id not in ADMINS:
        return
    if not message.reply_to_message:
        return await message.reply_text("⚠️ कृपया जिस मैसेज को ब्रॉडकास्ट करना है, उसे रिप्लाई करते हुए `/broadcast` लिखें।")
    
    users = db.get_all_users()
    msg = message.reply_to_message
    status = await message.reply_text(f"📢 ब्रॉडकास्ट शुरू हो रहा है (कुल यूजर्स: {len(users)})...")
    
    done = 0
    failed = 0
    for u in users:
        uid = u.get("user_id")
        try:
            await msg.copy(chat_id=uid)
            done += 1
            await asyncio.sleep(0.05)
        except Exception:
            failed += 1
            
    await status.edit_text(f"✅ **ब्रॉडकास्ट संपन्न!**\n\nसफल: `{done}`\nअसफल/ब्लॉक: `{failed}`")

# ==================== टास्क नियंत्रण व क्लोनिंग ====================

@Client.on_message(filters.command(["cancel"]))
async def send_cancel(client: Client, message: Message):
    user_id = message.from_user.id
    batch_temp.IS_BATCH[user_id] = True
    await message.reply_text("🛑 **टास्क तुरंत रोक दिया गया है।** यदि इसे वापस वहीं से चलाना हो तो `/resume` भेजें।")

def parse_telegram_link(link: str):
    link = link.strip().replace("?single", "")
    
    # 1. प्राइवेट फोरम टॉपिक लिंक: t.me/c/1234567/5/100
    c_topic = re.search(r"t\.me/c/(\d+)/(\d+)/(\d+)", link)
    if c_topic:
        return int("-100" + c_topic.group(1)), int(c_topic.group(3)), int(c_topic.group(2))
        
    # 2. पब्लिक फोरम टॉपिक लिंक: t.me/channelname/5/100
    p_topic = re.search(r"t\.me/([^/]+)/(\d+)/(\d+)", link)
    if p_topic and p_topic.group(1) not in ["c", "b"]:
        return p_topic.group(1), int(p_topic.group(3)), int(p_topic.group(2))

    # 3. प्राइवेट सामान्य लिंक: t.me/c/1234567/100
    c_match = re.search(r"t\.me/c/(\d+)/(\d+)", link)
    if c_match:
        return int("-100" + c_match.group(1)), int(c_match.group(2)), None
        
    # 4. बॉट लिंक: t.me/b/username/100
    b_match = re.search(r"t\.me/b/([^/]+)/(\d+)", link)
    if b_match:
        return b_match.group(1), int(b_match.group(2)), None
        
    # 5. पब्लिक सामान्य लिंक: t.me/username/100
    p_match = re.search(r"t\.me/([^/]+)/(\d+)", link)
    if p_match:
        return p_match.group(1), int(p_match.group(2)), None
        
    return None, None, None

@Client.on_message(filters.command(["resume"]) & filters.private)
async def resume_command(client: Client, message: Message):
    user_id = message.from_user.id
    if not db.is_user_vip(user_id, ADMINS):
        return await message.reply_text("🔒 आपका VIP एक्सेस सक्रिय नहीं है।")
        
    task = batch_temp.CLONE_DATA.get(user_id)
    last_id = batch_temp.LAST_SAVED_ID.get(user_id)
    if not task or last_id is None:
        return await message.reply_text("⚠️ कोई रुका हुआ पिछला टास्क नहीं मिला। नया टास्क शुरू करने के लिए `/clone` करें।")
    
    if last_id >= task["end_id"]:
        return await message.reply_text("✅ पिछला टास्क पहले ही पूरा हो चुका था।")

    task["start_id"] = last_id + 1
    total_remaining = (task["end_id"] - task["start_id"]) + 1
    await message.reply_text(f"🔄 **टास्क रिज्यूम किया जा रहा है...** (ID `{task['start_id']}` से `{task['end_id']}` तक, शेष: {total_remaining})")
    await start_clone_task(client, user_id)

@Client.on_message(filters.command(["clone", "clon"]) & filters.private)
async def clone_command(client: Client, message: Message):
    user_id = message.from_user.id
    if not db.is_user_vip(user_id, ADMINS):
        return await message.reply_text(
            "🔒 **यह फीचर केवल एक्टिव VIP मेंबर्स के लिए है!**\n\nप्लान देखने के लिए /plans और पेमेंट के लिए /pay भेजें।"
        )
    if batch_temp.IS_BATCH.get(user_id) == False:
        return await message.reply_text("⚠️ आपका एक टास्क पहले से चल रहा है। इंतज़ार करें या `/cancel` करें।")

    user_session = db.get_session(user_id)
    if not user_session:
        return await message.reply_text("🔑 पहले **/login** करें ताकि आपके अकाउंट से फाइल्स ट्रांसफर हो सकें।")

    guide_text = (
        "📖 **कंटेंट क्लोनिंग निर्देश:**\n"
        "━━━━━━━━━━━━━━━━━━━━\n"
        "👉 **स्टेप 1:** जहाँ से कॉपी करना है, उसकी **पहली लिंक (Start Link)** भेजें:\n"
        "(पब्लिक, प्राइवेट, बॉट लिंक या टॉपिक लिंक मान्य हैं)\n"
        "(रद्द करने के लिए /cancel लिखें)"
    )
    first_msg = await client.ask(user_id, guide_text, filters=filters.text, timeout=300)
    if first_msg.text == "/cancel":
        return await first_msg.reply("❌ प्रोसेस रद्द कर दिया गया।")
    
    start_link = first_msg.text.strip()
    s_chat, s_id, s_topic = parse_telegram_link(start_link)
    if not s_id:
        return await first_msg.reply("❌ अमान्य टेलीग्राम लिंक! दोबारा /clone करें।")

    last_msg = await client.ask(
        user_id, 
        "👉 **स्टेप 2:** अब **अंतिम लिंक (End Link)** भेजें:\n(सिंगल पोस्ट के लिए `/single` लिखें)",
        filters=filters.text, 
        timeout=300
    )
    if last_msg.text == "/cancel":
        return await last_msg.reply("❌ प्रोसेस रद्द कर दिया गया।")
    
    if last_msg.text.strip().lower() == "/single":
        e_chat, e_id, e_topic = s_chat, s_id, s_topic
    else:
        end_link = last_msg.text.strip()
        e_chat, e_id, e_topic = parse_telegram_link(end_link)
        if not e_id:
            return await last_msg.reply("❌ अमान्य अंतिम लिंक! दोबारा /clone करें।")

    dest_msg = await client.ask(
        user_id,
        "👉 **स्टेप 3:** जहाँ अपलोड करवाना है, उस **चैनल/ग्रुप का लिंक या ID** भेजें:\n"
        "(सीधे इसी बॉट में पाने के लिए `/skip` लिखें)",
        filters=filters.text,
        timeout=300
    )
    if dest_msg.text == "/cancel":
        return await dest_msg.reply("❌ प्रोसेस रद्द कर दिया गया।")

    dest_val = dest_msg.text.strip()
    is_direct_bot = False
    target_chat = None
    target_topic_id = None

    if dest_val.lower() == "/skip":
        target_chat = user_id
        is_direct_bot = True
        batch_temp.CLONE_DATA[user_id] = {
            "source_chat": s_chat,
            "start_id": min(s_id, e_id),
            "end_id": max(s_id, e_id),
            "target_chat": target_chat,
            "target_topic_id": None,
            "is_direct_bot": is_direct_bot,
            "custom_caption": None,
            "extra_caption": None,
            "replace_find": None,
            "replace_with": None,
            "strip_links": False,
            "hyperlink_word": None,
            "hyperlink_url": None,
            "thumb_path": None
        }
        batch_temp.LAST_SAVED_ID[user_id] = min(s_id, e_id) - 1
        return await show_customization_menu(client, user_id)

    if ":" in dest_val:
        parts = dest_val.split(":")
        dest_val = parts[0]
        try:
            target_topic_id = int(parts[1])
        except ValueError:
            target_topic_id = None

    try:
        target_chat = int(dest_val)
    except ValueError:
        target_chat = dest_val.replace("https://t.me/", "@")

    batch_temp.CLONE_DATA[user_id] = {
        "source_chat": s_chat,
        "start_id": min(s_id, e_id),
        "end_id": max(s_id, e_id),
        "target_chat": target_chat,
        "target_topic_id": target_topic_id,
        "is_direct_bot": is_direct_bot,
        "custom_caption": None,
        "extra_caption": None,
        "replace_find": None,
        "replace_with": None,
        "strip_links": False,
        "hyperlink_word": None,
        "hyperlink_url": None,
        "thumb_path": None
    }
    batch_temp.LAST_SAVED_ID[user_id] = min(s_id, e_id) - 1

    topic_markup = InlineKeyboardMarkup([
        [
            InlineKeyboardButton("✅ हाँ (Yes)", callback_data="ask_topic_yes"),
            InlineKeyboardButton("❌ नहीं (No)", callback_data="ask_topic_no")
        ]
    ])
    await client.send_message(
        user_id,
        "🧵 **क्या आप इसे किसी विशेष टॉपिक (Forum Topic) में अपलोड करवाना चाहते हैं?**",
        reply_markup=topic_markup
    )

async def show_customization_menu(client: Client, user_id: int):
    data = batch_temp.CLONE_DATA.get(user_id, {})
    cap_status = "कस्टम सेट है ✅" if data.get("custom_caption") else "ओरिजिनल"
    ext_status = "सेट है ✅" if data.get("extra_caption") else "कोई नहीं"
    thm_status = "सेट है ✅" if data.get("thumb_path") else "डिफ़ॉल्ट"
    strip_status = "हटाएँगे 🗑️" if data.get("strip_links") else "सुरक्षित रखेंगे"
    
    rep_status = f"`{data.get('replace_find')}` ➔ `{data.get('replace_with')}`" if data.get("replace_find") else "कोई नहीं"
    link_attach_status = f"[{data.get('hyperlink_word')}]({data.get('hyperlink_url')})" if data.get("hyperlink_word") else "कोई नहीं"

    dest_display = "सीधे बॉट चैट (Direct Bot)" if data.get("is_direct_bot") else f"`{data.get('target_chat')}`"
    if data.get("target_topic_id"):
        dest_display += f" (टॉपिक ID: `{data.get('target_topic_id')}`)"

    total_msgs = (data.get('end_id', 0) - data.get('start_id', 0)) + 1

    panel_text = (
        "⚙️ **कंटेंट कस्टमाइज़ेशन सेटिंग्स:**\n"
        "━━━━━━━━━━━━━━━━━━━━\n"
        f"📝 नया कैप्शन: `{cap_status}`\n"
        f"🔄 रिप्लेस: {rep_status}\n"
        f"🚫 लिंक्स हटाना: `{strip_status}`\n"
        f"📎 हाइपरलिंक जोड़ना: {link_attach_status}\n"
        f"➕ अतिरिक्त कैप्शन: `{ext_status}`\n"
        f"🖼️ थंबनेल: `{thm_status}`\n"
        f"🎯 टारगेट: {dest_display}\n"
        f"📊 रेंज: `{data.get('start_id')}` से `{data.get('end_id')}` (कुल {total_msgs} मैसेज)\n"
        "━━━━━━━━━━━━━━━━━━━━\n"
        "कस्टमाइज़ करें या तुरंत प्रोसेस के लिए **🚀 Confirm & Start** दबाएँ:"
    )
    buttons = InlineKeyboardMarkup([
        [InlineKeyboardButton("📝 Edit Full Caption", callback_data="set_caption"),
         InlineKeyboardButton("🔄 Replace in Caption", callback_data="set_replace")],
        [InlineKeyboardButton("🚫 Remove All Links", callback_data="toggle_strip_links"),
         InlineKeyboardButton("📎 Attach Hyperlink", callback_data="set_hyperlink")],
        [InlineKeyboardButton("➕ Add Extra Caption", callback_data="set_extra"),
         InlineKeyboardButton("🖼️ Set Thumbnail", callback_data="set_thumb")],
        [InlineKeyboardButton("🗑️ Clear Settings", callback_data="clear_settings"),
         InlineKeyboardButton("🚀 Confirm & Start", callback_data="confirm_start")]
    ])
    await client.send_message(user_id, panel_text, reply_markup=buttons)

# ==================== कॉलबैक हैंडलर ====================

@Client.on_callback_query()
async def callback_handler(client: Client, query: CallbackQuery):
    user_id = query.from_user.id
    data = query.data

    if data == "nav_howtouse":
        return await howtouse_handler(client, query.message)
    elif data == "nav_plans":
        return await plans_handler(client, query.message)
    elif data == "nav_channelhelp":
        return await channelhelp_handler(client, query.message)
    elif data == "nav_speedhelp":
        return await speedhelp_handler(client, query.message)
    elif data == "nav_myplan":
        return await myplan_handler(client, query.message)
    elif data == "nav_lang":
        return await lang_handler(client, query.message)
    elif data.startswith("setlang_"):
        lang_code = data.split("_")[1]
        db.set_lang(user_id, lang_code)
        lang_name = "हिन्दी" if lang_code == "hi" else "English"
        return await query.message.edit_text(f"✅ भाषा बदलकर **{lang_name}** कर दी गई है!")

    if user_id not in batch_temp.CLONE_DATA:
        return await query.answer("⚠️ सेशन एक्सपायर हो गया, दोबारा /clone करें।", show_alert=True)

    if data == "ask_topic_yes":
        await query.message.delete()
        t_msg = await client.ask(
            user_id,
            "👉 कृपया उस **Topic ID (थ्रेड ID)** को दर्ज करें:\n(उदाहरण: `45`)",
            filters=filters.text,
            timeout=180
        )
        if t_msg.text != "/cancel":
            try:
                batch_temp.CLONE_DATA[user_id]["target_topic_id"] = int(t_msg.text.strip())
            except ValueError:
                await t_msg.reply_text("⚠️ अमान्य संख्या! टॉपिक आईडी छोड़ दी गई।")
        await show_customization_menu(client, user_id)

    elif data == "ask_topic_no":
        await query.message.delete()
        await show_customization_menu(client, user_id)

    elif data == "set_caption":
        await query.message.delete()
        msg = await client.ask(user_id, "✍️ **नया कस्टम कैप्शन भेजें** (हाइपरलिंक मान्य हैं):", filters=filters.text, timeout=180)
        batch_temp.CLONE_DATA[user_id]["custom_caption"] = msg.text.markdown
        await show_customization_menu(client, user_id)

    elif data == "set_replace":
        await query.message.delete()
        find_msg = await client.ask(user_id, "🔍 क्या खोजना/हटाना चाहते हैं? वह शब्द/टेक्स्ट भेजें:", filters=filters.text, timeout=180)
        if find_msg.text == "/cancel":
            return await show_customization_menu(client, user_id)
        with_msg = await client.ask(user_id, f"✏️ `{find_msg.text}` की जगह क्या लगाना चाहते हैं? (हटाने/खाली रखने के लिए `/empty`):", filters=filters.text, timeout=180)
        if with_msg.text == "/cancel":
            return await show_customization_menu(client, user_id)
        batch_temp.CLONE_DATA[user_id]["replace_find"] = find_msg.text
        batch_temp.CLONE_DATA[user_id]["replace_with"] = "" if with_msg.text.strip() == "/empty" else with_msg.text.markdown
        await show_customization_menu(client, user_id)

    elif data == "toggle_strip_links":
        curr = batch_temp.CLONE_DATA[user_id].get("strip_links", False)
        batch_temp.CLONE_DATA[user_id]["strip_links"] = not curr
        await query.answer("लिंक हटाने का विकल्प अपडेट हुआ!")
        await query.message.delete()
        await show_customization_menu(client, user_id)

    elif data == "set_hyperlink":
        await query.message.delete()
        w_msg = await client.ask(user_id, "✍️ कैप्शन के किस **शब्द (Word/Text)** पर लिंक लगानी है?", filters=filters.text, timeout=180)
        if w_msg.text == "/cancel":
            return await show_customization_menu(client, user_id)
        u_msg = await client.ask(user_id, f"🔗 `{w_msg.text}` के लिए **URL (वेबसाइट/चैनल लिंक)** भेजें:", filters=filters.text, timeout=180)
        if u_msg.text == "/cancel":
            return await show_customization_menu(client, user_id)
        batch_temp.CLONE_DATA[user_id]["hyperlink_word"] = w_msg.text.strip()
        batch_temp.CLONE_DATA[user_id]["hyperlink_url"] = u_msg.text.strip()
        await show_customization_menu(client, user_id)

    elif data == "set_extra":
        await query.message.delete()
        msg = await client.ask(user_id, "✍️ **अतिरिक्त कैप्शन भेजें** (हाइपरलिंक मान्य हैं):", filters=filters.text, timeout=180)
        batch_temp.CLONE_DATA[user_id]["extra_caption"] = msg.text.markdown
        await show_customization_menu(client, user_id)

    elif data == "set_thumb":
        await query.message.delete()
        msg = await client.ask(user_id, "🖼️ **थंबनेल के लिए फ़ोटो भेजें:**", filters=filters.photo, timeout=180)
        user_thumb_dir = os.path.join("thumbs", str(user_id))
        os.makedirs(user_thumb_dir, exist_ok=True)
        thumb_file = os.path.join(user_thumb_dir, "thumb.jpg")
        await client.download_media(msg.photo, file_name=thumb_file)
        batch_temp.CLONE_DATA[user_id]["thumb_path"] = thumb_file
        await msg.reply_text("✅ आपका थंबनेल सुरक्षित सेव कर लिया गया!")
        await show_customization_menu(client, user_id)

    elif data == "clear_settings":
        batch_temp.CLONE_DATA[user_id]["custom_caption"] = None
        batch_temp.CLONE_DATA[user_id]["extra_caption"] = None
        batch_temp.CLONE_DATA[user_id]["replace_find"] = None
        batch_temp.CLONE_DATA[user_id]["replace_with"] = None
        batch_temp.CLONE_DATA[user_id]["strip_links"] = False
        batch_temp.CLONE_DATA[user_id]["hyperlink_word"] = None
        batch_temp.CLONE_DATA[user_id]["hyperlink_url"] = None
        tpath = batch_temp.CLONE_DATA[user_id].get("thumb_path")
        if tpath and os.path.exists(tpath):
            os.remove(tpath)
        batch_temp.CLONE_DATA[user_id]["thumb_path"] = None
        await query.answer("सेटिंग्स रीसेट हो गईं।")
        await query.message.delete()
        await show_customization_menu(client, user_id)

    elif data == "confirm_start":
        await query.message.delete()
        await start_clone_task(client, user_id)

# ==================== कोर इंजन और मीडिया प्रोसेसिंग ====================

async def start_clone_task(client: Client, user_id: int):
    task = batch_temp.CLONE_DATA.get(user_id)
    if not task:
        return await client.send_message(user_id, "❌ कोई सक्रिय टास्क नहीं मिला।")

    source_chat = task["source_chat"]
    start_id = task["start_id"]
    end_id = task["end_id"]
    target_chat = task["target_chat"]
    target_topic_id = task.get("target_topic_id")

    user_session = db.get_session(user_id)
    user_api_id = db.get_api_id(user_id)
    user_api_hash = db.get_api_hash(user_id)

    total_count = (end_id - start_id) + 1
    status_msg = await client.send_message(
        user_id, 
        f"🚀 **कंटेंट ट्रांसफर शुरू हो रहा है...**\n📊 **कुल फाइल्स/मैसेज:** `{total_count}`"
    )

    acc = Client(
        f"user_session_{user_id}", 
        session_string=user_session, 
        api_hash=user_api_hash, 
        api_id=user_api_id, 
        in_memory=True,
        workers=8
    )
    
    try:
        await asyncio.wait_for(acc.start(), timeout=20.0)
    except asyncio.TimeoutError:
        return await status_msg.edit_text("❌ टेलीग्राम सेशन टाइमआउट हो गया। कृपया दोबारा /clone करें।")
    except Exception as e:
        return await status_msg.edit_text(f"❌ सेशन कनेक्ट एरर (कृपया दोबारा /login करें): `{e}`")

    batch_temp.IS_BATCH[user_id] = False
    success = 0
    not_found = 0
    retrying = 0
    total_bytes = 0
    start_time = time.time()

    current_idx = 0
    for msgid in range(start_id, end_id + 1):
        current_idx += 1
        if batch_temp.IS_BATCH.get(user_id):
            await status_msg.edit_text("🛑 **टास्क पूरी तरह रोक दिया गया है।**")
            break

        if not db.is_user_vip(user_id, ADMINS):
            batch_temp.IS_BATCH[user_id] = True
            await status_msg.edit_text("🚫 **आपका VIP एक्सेस समाप्त या हटा दिया गया है।**")
            break

        attempts = 0
        while attempts < 3:
            if batch_temp.IS_BATCH.get(user_id):
                break
            try:
                # बड़ी 2GB तक की फाइल्स के लिए पर्याप्त समय सीमा (1800 सेकंड / 30 मिनट)
                ok, sz = await asyncio.wait_for(
                    process_media(
                        client, acc, user_id, source_chat, msgid, 
                        target_chat, target_topic_id, task, status_msg, 
                        current_idx, total_count
                    ),
                    timeout=1800.0
                )
                if ok:
                    success += 1
                    total_bytes += sz
                    batch_temp.LAST_SAVED_ID[user_id] = msgid
                else:
                    not_found += 1
                break
            except asyncio.CancelledError:
                break
            except FloodWait as fw:
                await status_msg.edit_text(f"⏳ **Rate-limit:** {fw.value} सेकंड इंतज़ार कर रहे हैं...")
                await asyncio.sleep(fw.value + 1)
                attempts += 1
            except asyncio.TimeoutError:
                attempts += 1
                await asyncio.sleep(2)
            except Exception as e:
                print(f"Error on msg {msgid}: {e}")
                retrying += 1
                break

        if batch_temp.IS_BATCH.get(user_id):
            await status_msg.edit_text("🛑 **टास्क पूरी तरह रोक दिया गया है।**")
            break

        await asyncio.sleep(WAITING_TIME)

    try:
        await acc.stop()
    except Exception:
        pass

    batch_temp.IS_BATCH[user_id] = True
    tpath = task.get("thumb_path")
    if tpath and os.path.exists(tpath):
        os.remove(tpath)

    elapsed_time = max(1, int(time.time() - start_time))
    avg_speed = f"{humanbytes(total_bytes / elapsed_time)}/s"

    if not batch_temp.IS_BATCH.get(user_id, False):
        summary_card = (
            "🏁 **Transfer Finished**\n"
            "━━━━━━━━━━━━━━━━━━━━\n"
            f"📊 Total Messages:  {total_count}\n"
            f"✅ Success:         {success}\n"
            f"🗑️ Empty/Skipped:   {not_found}\n"
            f"🔁 Retrying:        {retrying}\n"
            f"📦 Total Size:      {humanbytes(total_bytes)}\n"
            f"⚡ Avg Speed:       {avg_speed}\n"
            f"⏱️ Time:            {time_formatter(elapsed_time)}\n"
            "━━━━━━━━━━━━━━━━━━━━"
        )
        try:
            await status_msg.edit_text(summary_card)
        except Exception:
            pass

def get_file_name_from_msg(msg: Message) -> str:
    name = None
    if msg.document and msg.document.file_name:
        name = msg.document.file_name
    elif msg.video and msg.video.file_name:
        name = msg.video.file_name
    elif msg.video:
        name = f"video_{msg.id}.mp4"
    elif msg.audio and msg.audio.file_name:
        name = msg.audio.file_name
    elif msg.audio:
        name = f"audio_{msg.id}.mp3"
    elif msg.photo:
        name = f"photo_{msg.id}.jpg"
    else:
        name = f"file_{msg.id}.bin"

    clean_name = re.sub(r"^\d+_", "", name)
    return clean_name if clean_name else name

def format_caption_text(raw_text: str, task: dict) -> str:
    if not raw_text:
        raw_text = ""
        
    final_text = raw_text

    if task.get("custom_caption"):
        final_text = task["custom_caption"]
    else:
        if task.get("strip_links"):
            final_text = strip_all_urls(final_text)

        if task.get("replace_find"):
            find_w = task["replace_find"]
            with_w = task.get("replace_with") or ""
            if find_w in final_text:
                final_text = final_text.replace(find_w, with_w)

        if task.get("hyperlink_word") and task.get("hyperlink_url"):
            target_word = task["hyperlink_word"]
            target_url = task["hyperlink_url"]
            if target_word in final_text:
                final_text = final_text.replace(target_word, f"[{target_word}]({target_url})", 1)

    if task.get("extra_caption"):
        if final_text.strip():
            final_text = f"{final_text}\n\n{task['extra_caption']}"
        else:
            final_text = task["extra_caption"]

    return final_text

async def process_media(client: Client, acc: Client, user_id: int, source_chat, msgid: int, target_chat, target_topic_id, task: dict, status_msg: Message, current_idx: int, total_count: int):
    if batch_temp.IS_BATCH.get(user_id):
        raise asyncio.CancelledError()

    msg = None
    try:
        msg = await asyncio.wait_for(acc.get_messages(source_chat, msgid), timeout=25.0)
    except Exception:
        try:
            msg = await asyncio.wait_for(client.get_messages(source_chat, msgid), timeout=25.0)
        except Exception:
            return False, 0

    if not msg or msg.empty or msg.service:
        return False, 0

    raw_caption = msg.caption.markdown if msg.caption else ""
    final_caption = format_caption_text(raw_caption, task)

    is_direct_bot = task.get("is_direct_bot", False)
    sender_client = client if is_direct_bot else acc
    topic_kwargs = {"message_thread_id": target_topic_id} if target_topic_id and not is_direct_bot else {}

    # सादा टेक्स्ट मैसेज
    if msg.text:
        text_to_send = format_caption_text(msg.text.markdown, task)
        await sender_client.send_message(target_chat, text_to_send, parse_mode=enums.ParseMode.MARKDOWN, **topic_kwargs)
        return True, len(text_to_send.encode('utf-8'))

    file_name = get_file_name_from_msg(msg)
    user_down_dir = os.path.join("downloads", str(user_id))
    os.makedirs(user_down_dir, exist_ok=True)
    down_path = os.path.join(user_down_dir, file_name)

    remaining = max(0, total_count - current_idx)
    
    # 1. अगर फ़ाइल पहले से पूरी डाउनलोड है, तो दोबारा डाउनलोड करने की ज़रूरत नहीं
    file_path = None
    if os.path.exists(down_path) and os.path.getsize(down_path) > 1024:
        file_path = down_path
    else:
        down_start = time.time()
        await status_msg.edit_text(
            f"📥 **Downloading ID:** `{msgid}`\n"
            f"📊 **प्रगति:** `[{current_idx}/{total_count}]` | ⏳ **शेष:** `{remaining}`\n"
            f"📁 **फ़ाइल:** `{file_name}`..."
        )

        try:
            if msg.photo:
                file_path = await acc.download_media(msg, file_name=down_path)
            else:
                try:
                    file_path = await fast_download_file(
                        acc,
                        msg,
                        out_path=down_path,
                        progress_func=progress_bar,
                        progress_args=("📥 Downloading ID: " + str(msgid), status_msg, down_start, file_name, current_idx, total_count, user_id)
                    )
                except Exception:
                    file_path = await acc.download_media(
                        msg,
                        file_name=down_path,
                        progress=progress_bar,
                        progress_args=("📥 Downloading ID: " + str(msgid), status_msg, down_start, file_name, current_idx, total_count, user_id)
                    )
        except asyncio.CancelledError:
            if os.path.exists(down_path):
                try:
                    os.remove(down_path)
                except Exception:
                    pass
            raise asyncio.CancelledError()

    if batch_temp.IS_BATCH.get(user_id):
        if file_path and os.path.exists(file_path):
            os.remove(file_path)
        raise asyncio.CancelledError()

    if not file_path or not os.path.exists(file_path):
        return False, 0

    size = os.path.getsize(file_path)
    up_start = time.time()
    await status_msg.edit_text(
        f"📤 **Uploading ID:** `{msgid}`\n"
        f"📊 **प्रगति:** `[{current_idx}/{total_count}]` | ⏳ **शेष:** `{remaining}`\n"
        f"📁 **फ़ाइल:** `{file_name}`..."
    )

    thumb_to_use = task.get("thumb_path")
    created_temp_thumb = None

    if not thumb_to_use and msg.video:
        auto_thumb_path = os.path.join(user_down_dir, f"thumb_{msgid}.jpg")
        created_temp_thumb = generate_auto_thumb(file_path, auto_thumb_path)
        thumb_to_use = created_temp_thumb

    try:
        if msg.photo:
            await sender_client.send_photo(
                target_chat, file_path, caption=final_caption, parse_mode=enums.ParseMode.MARKDOWN, **topic_kwargs
            )
        elif msg.video:
            # बड़ी वीडियो के लिए अपलोड प्रयास
            for up_retry in range(3):
                try:
                    await sender_client.send_video(
                        target_chat,
                        video=file_path,
                        thumb=thumb_to_use,
                        caption=final_caption,
                        parse_mode=enums.ParseMode.MARKDOWN,
                        duration=getattr(msg.video, "duration", 0) or 0,
                        width=getattr(msg.video, "width", 0) or 0,
                        height=getattr(msg.video, "height", 0) or 0,
                        progress=progress_bar,
                        progress_args=(f"📤 Uploading ID: {msgid}", status_msg, up_start, file_name, current_idx, total_count, user_id),
                        **topic_kwargs
                    )
                    break
                except FloodWait as f:
                    await asyncio.sleep(f.value + 1)
                except Exception as ex:
                    if up_retry == 2:
                        raise ex
                    await asyncio.sleep(3)
        elif msg.audio:
            await sender_client.send_audio(
                target_chat,
                audio=file_path,
                thumb=thumb_to_use,
                caption=final_caption,
                parse_mode=enums.ParseMode.MARKDOWN,
                duration=getattr(msg.audio, "duration", 0) or 0,
                progress=progress_bar,
                progress_args=(f"📤 Uploading ID: {msgid}", status_msg, up_start, file_name, current_idx, total_count, user_id),
                **topic_kwargs
            )
        else:
            for up_retry in range(3):
                try:
                    await sender_client.send_document(
                        target_chat,
                        document=file_path,
                        thumb=thumb_to_use,
                        caption=final_caption,
                        parse_mode=enums.ParseMode.MARKDOWN,
                        progress=progress_bar,
                        progress_args=(f"📤 Uploading ID: {msgid}", status_msg, up_start, file_name, current_idx, total_count, user_id),
                        **topic_kwargs
                    )
                    break
                except FloodWait as f:
                    await asyncio.sleep(f.value + 1)
                except Exception as ex:
                    if up_retry == 2:
                        raise ex
                    await asyncio.sleep(3)
    except asyncio.CancelledError:
        if os.path.exists(file_path):
            try:
                os.remove(file_path)
            except Exception:
                pass
        raise asyncio.CancelledError()
    except Exception as e:
        print(f"Upload error on msg {msgid}: {e}")
        return False, 0
    finally:
        # केवल तभी फ़ाइल डिलीट होगी जब वह सुरक्षित सेंड हो जाए या पूरी तरह कैंसल हो
        if os.path.exists(file_path):
            try:
                os.remove(file_path)
            except Exception:
                pass
        if created_temp_thumb and os.path.exists(created_temp_thumb):
            try:
                os.remove(created_temp_thumb)
            except Exception:
                pass

    return True, size