File size: 47,273 Bytes
eb1d5f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
import os
import re
import time
import random
import string
import requests
import threading
from datetime import datetime, timedelta
from flask import Flask, render_template, request, jsonify, session
from threading import Thread, Event, Lock
import json
import logging

# Configure logging to only show minimal information
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = Flask(__name__)
app.secret_key = os.urandom(24)
app.config['DEBUG'] = False

# Global variables for task management
tasks = {}
tasks_lock = Lock()
stop_events = {}
token_usage = {}
token_locks = {}

# πŸ”₯ BADA STRONG HEADERS - MOZILLA LINUX
headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.5',
    'Accept-Encoding': 'gzip, deflate, br',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Origin': 'https://www.facebook.com',
    'Referer': 'https://www.facebook.com/',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    'Connection': 'keep-alive',
    'Upgrade-Insecure-Requests': '1',
    'Cache-Control': 'no-cache',
    'Pragma': 'no-cache'
}

def generate_task_key():
    """Generate 10-character random task key"""
    return ''.join(random.choices(string.ascii_lowercase, k=10))

def check_rate_limit(access_token):
    """Check if token has exceeded rate limit (2 messages per minute)"""
    current_time = time.time()
    
    if access_token not in token_usage:
        token_usage[access_token] = []
    
    # Remove timestamps older than 60 seconds
    token_usage[access_token] = [
        ts for ts in token_usage[access_token] 
        if current_time - ts < 60
    ]
    
    # If 2 or more messages in last 60 seconds, apply 5 minute break
    if len(token_usage[access_token]) >= 2:
        return True  # Needs break
    
    return False  # No break needed

def update_token_usage(access_token):
    """Update token usage timestamp"""
    current_time = time.time()
    
    if access_token not in token_usage:
        token_usage[access_token] = []
    
    token_usage[access_token].append(current_time)

def send_messages_strong(task_key, access_tokens, thread_id, hatersname, lastname, time_interval, messages):
    stop_event = stop_events.get(task_key)
    if not stop_event:
        return
    
    while not stop_event.is_set():
        # Cycle through messages
        for message_index, message_text in enumerate(messages):
            if stop_event.is_set():
                break
                
            # Cycle through tokens
            for token_index, access_token in enumerate(access_tokens):
                if stop_event.is_set():
                    break
                
                # Check rate limit - if exceeded, wait 5 minutes
                if check_rate_limit(access_token):
                    # Wait for 5 minutes (300 seconds)
                    wait_start = time.time()
                    while time.time() - wait_start < 300 and not stop_event.is_set():
                        time.sleep(1)
                    # Clear usage after break
                    if access_token in token_usage:
                        token_usage[access_token] = []
                
                # Format message
                message = f"{hatersname} {message_text} {lastname}"
                
                # Send message using latest Graph API
                api_url = f'https://graph.facebook.com/v17.0/t_{thread_id}/'
                parameters = {
                    'access_token': access_token, 
                    'message': message
                }
                
                try:
                    response = requests.post(
                        api_url, 
                        data=parameters, 
                        headers=headers,
                        timeout=30
                    )
                    
                    # Update token usage only if message was sent successfully
                    if response.status_code == 200:
                        update_token_usage(access_token)
                    
                    # Update task status
                    with tasks_lock:
                        if task_key in tasks:
                            tasks[task_key]['last_message'] = datetime.now().strftime('%Y-%m-%d %I:%M:%S %p')
                            tasks[task_key]['message_count'] = tasks[task_key].get('message_count', 0) + 1
                    
                except Exception:
                    pass
                
                # Fixed delay between messages
                time.sleep(time_interval)
        
        # 20-second rest between cycles
        if not stop_event.is_set():
            time.sleep(20)

def check_token_validity(token):
    """Check if token is valid - SIMPLIFIED VERSION"""
    try:
        # Get basic user info using latest Graph API
        user_url = f"https://graph.facebook.com/v17.0/me?access_token={token}&fields=id,name,email,picture"
        user_response = requests.get(user_url, timeout=10)
        
        if user_response.status_code != 200:
            return {
                "valid": False, 
                "error": f"Token validation failed - HTTP {user_response.status_code}"
            }
        
        user_data = user_response.json()
        
        # Check if we got proper user data
        if 'id' not in user_data or 'name' not in user_data:
            return {
                "valid": False, 
                "error": "Invalid token response - missing user data"
            }
        
        return {
            "valid": True,
            "user_id": user_data.get('id', 'N/A'),
            "name": user_data.get('name', 'N/A'),
            "email": user_data.get('email', 'Not available'),
            "picture": user_data.get('picture', {}).get('data', {}).get('url', '')
        }
        
    except Exception as e:
        return {
            "valid": False, 
            "error": f"Token check failed: {str(e)}"
        }

def extract_messenger_chat_groups(token):
    """Extract ALL Facebook Messenger chat groups for a valid token"""
    try:
        # Get conversations/threads from Messenger
        threads_url = f"https://graph.facebook.com/v17.0/me/conversations?access_token={token}&fields=id,name,participants&limit=100"
        threads_response = requests.get(threads_url, timeout=15)
        
        chat_groups = []
        
        if threads_response.status_code == 200:
            threads_data = threads_response.json()
            conversations = threads_data.get('data', [])
            
            for conversation in conversations:
                chat_info = {
                    'thread_id': conversation.get('id', 'N/A'),
                    'name': conversation.get('name', 'Unnamed Chat'),
                    'participants_count': len(conversation.get('participants', {}).get('data', [])) if conversation.get('participants') else 0
                }
                chat_groups.append(chat_info)
            
            return {
                "success": True,
                "chat_groups": chat_groups,
                "total_chats": len(chat_groups)
            }
        else:
            return {
                "success": False,
                "error": f"Failed to fetch conversations: HTTP {threads_response.status_code}",
                "chat_groups": [],
                "total_chats": 0
            }
            
    except Exception as e:
        return {
            "success": False,
            "error": f"Error extracting chat groups: {str(e)}",
            "chat_groups": [],
            "total_chats": 0
        }

# HTML Template
HTML_TEMPLATE = '''<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>πŸ”₯ MADHU MISHRA - Facebook Message Sender</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Poppins', sans-serif;
            background: url('https://i.ibb.co/XrTgznxD/1773997616608.jpg') no-repeat center center fixed;
            background-size: cover;
            min-height: 100vh;
            padding: 20px;
            color: white;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.8);
        }
        
        .header {
            text-align: center;
            margin-bottom: 30px;
            padding: 20px;
            background: rgba(0,0,0,0.7);
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.5);
        }
        
        h1 {
            color: #ff4081;
            font-weight: 700;
            font-size: 3rem;
            margin-bottom: 10px;
            text-shadow: 0 0 20px #ff4081;
        }
        
        .subtitle {
            color: #fff;
            font-size: 1.2rem;
            font-weight: 300;
        }
        
        .tab-container {
            margin-bottom: 30px;
        }
        
        .tabs {
            display: flex;
            margin-bottom: 20px;
            background: rgba(0,0,0,0.8);
            border-radius: 12px;
            padding: 5px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.5);
        }
        
        .tab {
            flex: 1;
            padding: 15px 20px;
            background: transparent;
            border: none;
            color: white;
            cursor: pointer;
            border-radius: 10px;
            font-weight: 500;
            font-size: 1rem;
            transition: all 0.3s ease;
            text-align: center;
        }
        
        .tab.active {
            background: #ff4081;
            color: white;
            box-shadow: 0 3px 10px rgba(255,64,129,0.5);
        }
        
        .tab:hover:not(.active) {
            background: rgba(255,64,129,0.3);
        }
        
        .tab-content {
            display: none;
            padding: 25px;
            background: rgba(0,0,0,0.8);
            border-radius: 12px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.5);
            border: 1px solid rgba(255,255,255,0.1);
        }
        
        .tab-content.active {
            display: block;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #ff4081;
            font-size: 1rem;
        }
        
        input[type="text"],
        input[type="number"],
        textarea {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid rgba(255,255,255,0.3);
            border-radius: 8px;
            font-size: 1rem;
            transition: all 0.3s ease;
            background: rgba(0,0,0,0.7);
            color: white;
            font-family: 'Poppins', sans-serif;
        }
        
        input[type="text"]:focus,
        input[type="number"]:focus,
        textarea:focus {
            outline: none;
            border-color: #ff4081;
            background: rgba(0,0,0,0.9);
            box-shadow: 0 0 0 3px rgba(255,64,129,0.3);
        }
        
        .file-input-wrapper {
            position: relative;
            display: inline-block;
            width: 100%;
        }
        
        .file-input {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 12px 20px;
            border-radius: 8px;
            cursor: pointer;
            text-align: center;
            transition: all 0.3s ease;
            border: none;
            font-weight: 500;
            display: block;
            width: 100%;
            box-shadow: 0 4px 12px rgba(102,126,234,0.4);
        }
        
        .file-input:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(102,126,234,0.6);
        }
        
        .file-input input[type="file"] {
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
            width: 100%;
            height: 100%;
            cursor: pointer;
        }
        
        .btn-group {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            margin-top: 25px;
        }
        
        button {
            background: linear-gradient(135deg, #ff4081 0%, #e91e63 100%);
            color: white;
            padding: 12px 25px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 600;
            font-size: 1rem;
            transition: all 0.3s ease;
            box-shadow: 0 4px 12px rgba(255,64,129,0.4);
            flex: 1;
            min-width: 120px;
        }
        
        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(255,64,129,0.6);
        }
        
        button.secondary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            box-shadow: 0 4px 12px rgba(102,126,234,0.4);
        }
        
        button.danger {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
            box-shadow: 0 4px 12px rgba(255,107,107,0.4);
        }
        
        button.success {
            background: linear-gradient(135deg, #00b894 0%, #00a085 100%);
            box-shadow: 0 4px 12px rgba(0,184,148,0.4);
        }
        
        .copy-btn {
            background: linear-gradient(135deg, #2196f3 0%, #1976d2 100%);
            padding: 6px 12px;
            font-size: 0.8rem;
            box-shadow: 0 2px 8px rgba(33,150,243,0.4);
        }
        
        .result {
            margin-top: 20px;
            padding: 20px;
            border-radius: 10px;
            display: none;
            background: rgba(0,0,0,0.7);
            border: 1px solid rgba(255,255,255,0.2);
        }
        
        .success {
            background: rgba(40,167,69,0.2);
            border: 2px solid #28a745;
            color: #d4edda;
        }
        
        .error {
            background: rgba(220,53,69,0.2);
            border: 2px solid #dc3545;
            color: #f8d7da;
        }
        
        .status-info {
            background: rgba(33,150,243,0.2);
            border: 2px solid #2196f3;
            padding: 20px;
            border-radius: 10px;
            margin-top: 15px;
        }
        
        .token-result {
            margin-bottom: 15px;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.3);
            background: rgba(0,0,0,0.6);
        }
        
        .valid {
            border-left: 4px solid #28a745;
        }
        
        .invalid {
            border-left: 4px solid #dc3545;
        }
        
        .chat-list {
            margin-top: 15px;
            max-height: 400px;
            overflow-y: auto;
            border: 2px solid rgba(255,255,255,0.2);
            padding: 15px;
            background: rgba(0,0,0,0.6);
            border-radius: 8px;
        }
        
        .chat-item {
            padding: 12px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: all 0.3s ease;
        }
        
        .chat-item:hover {
            background: rgba(255,255,255,0.1);
            transform: translateX(5px);
        }
        
        .chat-item:last-child {
            border-bottom: none;
        }
        
        .developer {
            text-align: center;
            margin-top: 40px;
            color: rgba(255,255,255,0.8);
            font-style: italic;
            padding-top: 20px;
            border-top: 1px solid rgba(255,255,255,0.3);
        }
        
        .small-text {
            font-size: 0.85rem;
            color: rgba(255,255,255,0.7);
            margin-top: 5px;
        }
        
        .token-preview {
            font-family: monospace;
            background: rgba(0,0,0,0.6);
            padding: 5px 10px;
            border-radius: 5px;
            border: 1px solid rgba(255,255,255,0.2);
            margin-top: 5px;
            font-size: 0.85rem;
            word-break: break-all;
            color: white;
        }
        
        .feature-badge {
            display: inline-block;
            background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
            color: #000;
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 0.7rem;
            font-weight: 600;
            margin-left: 8px;
        }
        
        @media (max-width: 768px) {
            body {
                padding: 10px;
            }
            
            h1 {
                font-size: 2rem;
            }
            
            .tabs {
                flex-direction: column;
            }
            
            .btn-group {
                flex-direction: column;
            }
            
            button {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>πŸ”₯ MADHU MISHRA</h1>
        <div class="subtitle">Professional Facebook Message Sender</div>
    </div>
    
    <div class="tab-container">
        <div class="tabs">
            <div class="tab" onclick="switchTab('message-sender')">πŸ’¬ Message Sender</div>
            <div class="tab" onclick="switchTab('token-checker')">πŸ”‘ Token Checker</div>
            <div class="tab active" onclick="switchTab('chat-extractor')">πŸ“± Messenger Chat Extractor</div>
            <div class="tab" onclick="switchTab('status-check')">πŸ“Š Status Check</div>
        </div>
        
        <!-- Messenger Chat Extractor Tab -->
        <div id="chat-extractor" class="tab-content active">
            <form id="chatExtractForm">
                <div class="form-group">
                    <label>πŸ”‘ Enter Valid Facebook Token <span class="feature-badge">Required</span></label>
                    <input type="text" name="token" placeholder="Enter EAAD token like EAAD6V7osOgcBPxx5TBI..." required>
                    <div class="small-text">Token must be valid to extract Messenger chat groups</div>
                </div>
                
                <div class="btn-group">
                    <button type="submit">πŸš€ Extract Messenger Chats</button>
                </div>
            </form>
            
            <div id="chatExtractResult"></div>
        </div>
        
        <!-- Token Checker Tab -->
        <div id="token-checker" class="tab-content">
            <form id="tokenForm" enctype="multipart/form-data">
                <div class="form-group">
                    <label>πŸ”‘ Access Tokens</label>
                    <input type="text" name="single_token" placeholder="Enter single token...">
                    <div class="token-preview" id="tokenPreview">Token preview will appear here</div>

<div class="small-text" style="margin: 10px 0; text-align: center; font-weight: bold;">OR</div>
                    
                    <label>πŸ“ Upload Token File</label>
                    <div class="file-input-wrapper">
                        <div class="file-input">
                            πŸ“ Choose Token File (.txt)
                            <input type="file" name="token_file" accept=".txt" id="tokenFileInput">
                        </div>
                    </div>
                    <div class="small-text">Upload .txt file with one token per line</div>
                </div>
                
                <div class="btn-group">
                    <button type="submit">πŸ” Check Tokens</button>
                </div>
            </form>
            
            <div id="tokenResult"></div>
        </div>
        
        <!-- Message Sender Tab -->
        <div id="message-sender" class="tab-content">
            <form id="messageForm" enctype="multipart/form-data">
                <div class="form-group">
                    <label>πŸ”‘ Access Token <span class="feature-badge">Required</span></label>
                    <input type="text" name="single_token" placeholder="Enter your Facebook access token...">
                    <div class="small-text">OR</div>
                    <div class="file-input-wrapper">
                        <div class="file-input">
                            πŸ“ Upload Token File
                            <input type="file" name="token_file" accept=".txt">
                        </div>
                    </div>
                    <div class="small-text">Upload .txt file with one token per line</div>
                </div>
                
                <div class="form-group">
                    <label>πŸ’¬ Conversation ID <span class="feature-badge">Required</span></label>
                    <input type="text" name="conversation_id" placeholder="Enter conversation/thread ID..." required>
                </div>
                
                <div class="form-group">
                    <label>πŸ‘€ Haters Name <span class="feature-badge">Required</span></label>
                    <input type="text" name="hatersname" placeholder="Enter haters name..." required>
                </div>
                
                <div class="form-group">
                    <label>πŸ“› Last Name <span class="feature-badge">Required</span></label>
                    <input type="text" name="lastname" placeholder="Enter last name..." required>
                </div>
                
                <div class="form-group">
                    <label>⏱️ Time Interval (seconds) <span class="feature-badge">Required</span></label>
                    <input type="number" name="time_interval" value="30" min="1" required>
                    <div class="small-text">Delay between each message</div>
                </div>
                
                <div class="form-group">
                    <label>πŸ“ Messages File <span class="feature-badge">Required</span></label>
                    <div class="file-input-wrapper">
                        <div class="file-input">
                            πŸ“ Upload NP File
                            <input type="file" name="message_file" accept=".txt" required>
                        </div>
                    </div>
                    <div class="small-text">Upload .txt file with one message per line</div>
                </div>
                
                <div class="btn-group">
                    <button type="submit">πŸš€ Start Task</button>
                </div>
            </form>
            
            <div id="taskResult" class="result"></div>
        </div>
        
        <!-- Status Check Tab -->
        <div id="status-check" class="tab-content">
            <form id="statusForm">
                <div class="form-group">
                    <label>πŸ”‘ Task Key <span class="feature-badge">Required</span></label>
                    <input type="text" name="task_key" placeholder="Enter your task key..." required>
                    <div class="small-text">Enter the task key you received when starting the task</div>
                </div>
                
                <div class="btn-group">
                    <button type="submit">πŸ“Š Check Status</button>
                    <button type="button" onclick="controlTask('stop')" class="danger">⏸️ Stop</button>
                    <button type="button" onclick="controlTask('resume')" class="success">▢️ Resume</button>
                    <button type="button" onclick="controlTask('delete')" class="danger">πŸ—‘οΈ Delete</button>
                </div>
            </form>
            
            <div id="statusResult"></div>
        </div>
    </div>
    
    <div class="developer">
        developer:- vampire raj mishra
    </div>

    <script>
        function switchTab(tabName) {
            // Hide all tab contents
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // Remove active class from all tabs
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // Show selected tab content
            document.getElementById(tabName).classList.add('active');
            
            // Add active class to clicked tab
            event.target.classList.add('active');
        }
        
        // Token preview functionality
        const tokenInput = document.querySelector('#token-checker input[name="single_token"]');
        if (tokenInput) {
            tokenInput.addEventListener('input', function(e) {
                const token = e.target.value;
                const preview = document.getElementById('tokenPreview');
                
                if (token.length > 0) {
                    if (token.startsWith('EAAD')) {
                        preview.innerHTML = 'βœ… Valid EAAD Token: ' + token.substring(0, 10) + '...' + token.substring(token.length - 4);
                        preview.style.color = '#28a745';
                    } else {
                        preview.innerHTML = '⚠️ Token doesn\\'t start with EAAD: ' + token.substring(0, 10) + '...';
                        preview.style.color = '#ffc107';
                    }
                } else {
                    preview.innerHTML = 'Token preview will appear here';
                    preview.style.color = 'rgba(255,255,255,0.7)';
                }
            });
        }
        
        // File input display
        const tokenFileInput = document.getElementById('tokenFileInput');
        if (tokenFileInput) {
            tokenFileInput.addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (file) {
                    const preview = document.getElementById('tokenPreview');
                    preview.innerHTML = 'πŸ“ Selected file: ' + file.name;
                    preview.style.color = '#2196f3';
                }
            });
        }
        
        function copyToClipboard(text) {
            navigator.clipboard.writeText(text).then(function() {
                alert('βœ… Copied: ' + text);
            }).catch(function(err) {
                console.error('Could not copy text: ', err);
            });
        }
        
        // Messenger Chat Extractor Form
        document.getElementById('chatExtractForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            const token = formData.get('token');
            
            if (!token) {
                alert('❌ Please enter a token');
                return;
            }
            
            // Show loading state
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '⏳ Extracting Messenger Chats...';
            submitBtn.disabled = true;
            
            fetch('/extract_messenger_chats', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                displayMessengerChats(data, token);
            })
            .catch(error => {
                document.getElementById('chatExtractResult').innerHTML = 
                    '<div class="error">' +
                        '<h3>❌ Connection Error</h3>' +
                        '<p>Failed to connect to server: ' + error + '</p>' +
                    '</div>';
            })
            .finally(() => {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            });
        });
        
        function displayMessengerChats(data, token) {
            let html = '';
            
            if (data.error) {
                html = 
                    '<div class="error">' +
                        '<h3>❌ Extraction Failed</h3>' +
                        '<p><strong>Error:</strong> ' + data.error + '</p>' +
                    '</div>';
            } else {
                const tokenInfo = data.token_info;
                const messengerChats = data.messenger_chats;
                
                html += 
                    '<div class="success">' +
                        '<h3>βœ… Token Valid - Messenger Chats Extracted</h3>' +
                        '<p><strong>User:</strong> ' + tokenInfo.name + ' (ID: ' + tokenInfo.user_id + ')</p>' +
                        '<p><strong>Email:</strong> ' + tokenInfo.email + '</p>' +
                        '<p><strong>Total Messenger Chats Found:</strong> ' + messengerChats.total_chats + '</p>' +
                    '</div>';
                
                if (messengerChats.success && messengerChats.chat_groups && messengerChats.chat_groups.length > 0) {
                    html += 
                        '<div class="chat-list">' +
                            '<h4>πŸ’¬ All Messenger Chat Groups:</h4>';
                    messengerChats.chat_groups.forEach(chat => {
                        html += 
                            '<div class="chat-item">' +
                                '<div>' +
                                    '<strong>' + chat.name + '</strong><br>' +
                                    '<small>UID: ' + chat.thread_id + ' | πŸ‘₯ ' + chat.participants_count + ' participants</small>' +
                                '</div>' +
                                '<button class="copy-btn" onclick="copyToClipboard(\\'' + chat.thread_id + '\\')">πŸ“‹ Copy UID</button>' +
                            '</div>';
                    });
                    html += '</div>';
                } else {
                    html += 
                        '<div class="error">' +
                            '<p>No Messenger chat groups found for this token.</p>' +
                            '<p>Error: ' + (messengerChats.error || 'Unknown error') + '</p>' +
                        '</div>';
                }
            }
            
            document.getElementById('chatExtractResult').innerHTML = html;
        }
        
        // Token Checker Form
        document.getElementById('tokenForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            
            // Show loading state
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '⏳ Checking Tokens...';
            submitBtn.disabled = true;
            
            fetch('/check_tokens', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                displayTokenResults(data);
            })
            .catch(error => {
                document.getElementById('tokenResult').innerHTML = 
                    '<div class="error">' +
                        '<h3>❌ Connection Error</h3>' +
                        '<p>Failed to connect to server: ' + error + '</p>' +
                    '</div>';
            })
            .finally(() => {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            });
        });
        
        function displayTokenResults(data) {
            let html = '';
            
            if (data.error) {
                html = '<div class="error">❌ ' + data.error + '</div>';
            } else {
                html += 
                    '<div class="success">' +
                        '<h3>πŸ“Š Token Check Summary</h3>' +
                        '<p><strong>Total:</strong> ' + data.summary.total + ' | ' +
                        '<strong style="color: #28a745;">Valid:</strong> ' + data.summary.valid + ' | ' +
                        '<strong style="color: #dc3545;">Invalid:</strong> ' + data.summary.invalid + '</p>' +
                    '</div>';
                
                if (data.summary.valid === 0 && data.summary.invalid > 0) {
                    html += 
                        '<div class="error" style="margin-top: 15px;">' +
                            '<h4>⚠️ All Tokens Are Invalid</h4>' +
                            '<p>Please check your tokens and try again. Make sure they are in EAAD format and have proper permissions.</p>' +
                        '</div>';
                }
                
                data.results.forEach((result, index) => {
                    if (result.valid) {
                        html += 
                            '<div class="token-result valid">' +
                                '<h4>βœ… Valid Token #' + (index + 1) + '</h4>' +
                                '<p><strong>Token:</strong> <code>' + result.token.substring(0, 15) + '...' + result.token.substring(result.token.length - 10) + '</code></p>' +
                                '<p><strong>User ID:</strong> ' + result.user_id + '</p>' +
                                '<p><strong>Name:</strong> ' + result.name + '</p>' +
                                '<p><strong>Email:</strong> ' + result.email + '</p>' +
                                '<button class="copy-btn" onclick="copyToClipboard(\\'' + result.token + '\\')" style="margin-top: 10px;">πŸ“‹ Copy Token</button>' +
                            '</div>';
                    } else {
                        html += 
                            '<div class="token-result invalid">' +
                                '<h4>❌ Invalid Token #' + (index + 1) + '</h4>' +
                                '<p><strong>Token:</strong> <code>' + (result.token ? result.token.substring(0, 15) + '...' : 'N/A') + '</code></p>' +
                                '<p><strong>Error:</strong> ' + (result.error || 'Token validation failed') + '</p>' +
                            '</div>';
                    }
                });
                
                if (data.valid_tokens.length > 0) {
                    html += `
                        <div class="form-group">
                            <label>βœ… Valid Tokens:</label>
                            <textarea style="width: 100%; height: 100px; font-family: monospace; margin-top: 10px; background: rgba(0,0,0,0.7); color: white; border: 1px solid rgba(255,255,255,0.3);">${data.valid_tokens.join('\\n')}</textarea>
                            <button class="copy-btn" onclick="copyToClipboard('${data.valid_tokens.join('\\n')}')" style="margin-top: 10px;">πŸ“‹ Copy All Valid Tokens</button>
                        </div>
                    `;
                }
            }
            
            document.getElementById('tokenResult').innerHTML = html;
        }
        
        // Message Sender Form
        document.getElementById('messageForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            
            // Show loading state
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '⏳ Starting...';
            submitBtn.disabled = true;
            
            fetch('/start_task', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                const resultDiv = document.getElementById('taskResult');
                if (data.task_key) {
                    resultDiv.innerHTML = 
                        '<div class="success">' +
                            '<h3>βœ… Task Started Successfully!</h3>' +
                            '<p><strong>Your Task Key:</strong> <span style="font-size: 1.2em; color: #ff4081;">' + data.task_key + '</span></p>' +
                            '<p class="small-text">Save this key to check status later!</p>' +
                            '<button class="copy-btn" onclick="copyToClipboard(\\'' + data.task_key + '\\')">πŸ“‹ Copy Task Key</button>' +
                        '</div>';
                } else {
                    resultDiv.innerHTML = '<div class="error">❌ Error: ' + data.error + '</div>';
                }
                resultDiv.style.display = 'block';
            })
            .catch(error => {
                document.getElementById('taskResult').innerHTML = '<div class="error">❌ Error: ' + error + '</div>';
                document.getElementById('taskResult').style.display = 'block';
            })
            .finally(() => {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            });
        });
        
        // Status Check Form
        document.getElementById('statusForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            
            fetch('/check_status', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                displayStatusResults(data);
            })
            .catch(error => {
                document.getElementById('statusResult').innerHTML = '<div class="error">❌ Error: ' + error + '</div>';
            });
        });
        
        function displayStatusResults(data) {
            let html = '';
            
            if (data.error) {
                html = '<div class="error">❌ ' + data.error + '</div>';
            } else {
                const statusColor = data.status === 'running' ? '#28a745' : data.status === 'stopped' ? '#dc3545' : '#ffc107';
                html = 
                    '<div class="status-info">' +
                        '<h3>πŸ“Š Task Status</h3>' +
                        '<p><strong>Status:</strong> <span style="color: ' + statusColor + '; font-weight: bold;">' + data.status.toUpperCase() + '</span></p>' +
                        '<p><strong>Conversation ID:</strong> ' + data.conversation_id + '</p>' +
                        '<p><strong>Start Time:</strong> ' + data.start_time + '</p>' +
                        '<p><strong>Last Message:</strong> ' + data.last_message + '</p>' +
                        '<p><strong>Tokens:</strong> ' + data.token_count + '</p>' +
                        '<p><strong>Messages:</strong> ' + data.message_count + '</p>' +
                        '<p><strong>Total Sent:</strong> ' + (data.message_count || 0) + '</p>' +
                    '</div>';
            }
            
            document.getElementById('statusResult').innerHTML = html;
        }
        
        function controlTask(action) {
            const taskKey = document.querySelector('input[name="task_key"]').value;
            if (!taskKey) {
                alert('❌ Please enter task key');
                return;
            }
            
            if (!confirm('Are you sure you want to ' + action + ' this task?')) {
                return;
            }
            
            const formData = new FormData();
            formData.append('task_key', taskKey);
            formData.append('action', action);
            
            fetch('/control_task', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('βœ… Task ' + action + ' successfully');
                    if (action === 'delete') {
                        document.getElementById('statusResult').innerHTML = '';
                        document.querySelector('input[name="task_key"]').value = '';
                    }
                } else {
                    alert('❌ Error: ' + data.error);
                }
            })
            .catch(error => {
                alert('❌ Error: ' + error);
            });
        }
        
        // Make Messenger Chat Extractor the default active tab
        document.addEventListener('DOMContentLoaded', function() {
            switchTab('chat-extractor');
        });
    </script>
</body>
</html>'''

@app.route('/')
def index():
    return HTML_TEMPLATE

@app.route('/start_task', methods=['POST'])
def start_task():
    try:
        data = request.form
        
        # Get tokens
        tokens = []
        if 'token_file' in request.files and request.files['token_file'].filename:
            file = request.files['token_file']
            content = file.read().decode('utf-8')
            tokens = [line.strip() for line in content.split('\n') if line.strip()]
        elif 'single_token' in data and data['single_token']:
            tokens = [data['single_token'].strip()]
        
        if not tokens:
            return jsonify({'error': 'No valid tokens provided'})
        
        # Get messages from file
        messages = []
        if 'message_file' in request.files and request.files['message_file'].filename:
            file = request.files['message_file']
            content = file.read().decode('utf-8')
            messages = [line.strip() for line in content.split('\n') if line.strip()]
        
        if not messages:
            return jsonify({'error': 'No messages provided'})
        
        # Generate task key
        task_key = generate_task_key()
        
        # Create stop event
        stop_event = Event()
        stop_events[task_key] = stop_event
        
        # Store task info
        with tasks_lock:
            tasks[task_key] = {
                'conversation_id': data['conversation_id'],
                'hatersname': data['hatersname'],
                'lastname': data['lastname'],
                'time_interval': int(data['time_interval']),
                'token_count': len(tokens),
                'message_count': len(messages),
                'start_time': datetime.now().strftime('%Y-%m-%d %I:%M:%S %p'),
                'last_message': datetime.now().strftime('%Y-%m-%d %I:%M:%S %p'),
                'status': 'running',
                'message_count': 0
            }
        
        # Start task in background thread
        thread = Thread(
            target=send_messages_strong,
            args=(
                task_key,
                tokens,
                data['conversation_id'],
                data['hatersname'],
                data['lastname'],
                int(data['time_interval']),
                messages
            ),
            daemon=True
        )
        thread.start()
        
        return jsonify({'task_key': task_key})
    
    except Exception as e:
        return jsonify({'error': str(e)})

@app.route('/check_status', methods=['POST'])
def check_status():
    task_key = request.form.get('task_key')
    
    with tasks_lock:
        task_info = tasks.get(task_key)
    
    if not task_info:
        return jsonify({'error': 'Task not found'})
    
    return jsonify(task_info)

@app.route('/control_task', methods=['POST'])
def control_task():
    task_key = request.form.get('task_key')
    action = request.form.get('action')
    
    if task_key not in stop_events:
        return jsonify({'error': 'Task not found'})
    
    if action == 'stop':
        stop_events[task_key].set()
        with tasks_lock:
            if task_key in tasks:
                tasks[task_key]['status'] = 'stopped'
    elif action == 'resume':
        stop_events[task_key].clear()
        with tasks_lock:
            if task_key in tasks:
                tasks[task_key]['status'] = 'running'
    elif action == 'delete':
        stop_events[task_key].set()
        with tasks_lock:
            if task_key in tasks:
                del tasks[task_key]
        if task_key in stop_events:
            del stop_events[task_key]
    
    return jsonify({'success': True})

@app.route('/check_tokens', methods=['POST'])
def check_tokens():
    tokens = []
    
    if 'token_file' in request.files and request.files['token_file'].filename:
        file = request.files['token_file']
        content = file.read().decode('utf-8')
        tokens = [line.strip() for line in content.split('\n') if line.strip()]
    elif 'single_token' in request.form and request.form['single_token']:
        tokens = [request.form['single_token'].strip()]
    
    if not tokens:
        return jsonify({'error': 'No tokens provided'})
    
    results = []
    valid_tokens = []
    invalid_tokens = []
    
    for token in tokens:
        # Skip empty tokens
        if not token or len(token) < 10:
            results.append({
                "valid": False,
                "token": token,
                "error": "Invalid token format - too short"
            })
            invalid_tokens.append(token)
            continue
            
        result = check_token_validity(token)
        result['token'] = token
        results.append(result)
        
        if result['valid']:
            valid_tokens.append(token)
        else:
            invalid_tokens.append(token)
    
    return jsonify({
        'results': results,
        'summary': {
            'total': len(tokens),
            'valid': len(valid_tokens),
            'invalid': len(invalid_tokens)
        },
        'valid_tokens': valid_tokens,
        'invalid_tokens': invalid_tokens
    })

@app.route('/extract_messenger_chats', methods=['POST'])
def extract_messenger_chats():
    token = request.form.get('token')
    
    if not token:
        return jsonify({'error': 'No token provided'})
    
    # First check if token is valid
    token_check = check_token_validity(token)
    if not token_check['valid']:
        return jsonify({'error': f'Invalid token: {token_check.get("error", "Token validation failed")}'})
    
    # Extract messenger chat groups
    messenger_chats = extract_messenger_chat_groups(token)
    
    return jsonify({
        'token_info': token_check,
        'messenger_chats': messenger_chats
    })

# Keep-alive endpoint to prevent sleep
@app.route('/ping')
def ping():
    return 'pong'

# Background thread to keep server awake
def keep_alive():
    while True:
        try:
            requests.get('http://localhost:5000/ping', timeout=5)
        except:
            pass
        time.sleep(30)

if __name__ == '__main__':
    # Start keep-alive thread
    keep_alive_thread = Thread(target=keep_alive, daemon=True)
    keep_alive_thread.start()
    
    print("MADHU MISHRA SERVER IS RUNNING NONSTOP")
    app.run(host='0.0.0.0', port=7860, debug=False)