-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
2067 lines (1898 loc) · 68.3 KB
/
index.js
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
'use strict';
import dotenv from 'dotenv';
dotenv.config();
import express from 'express';
import axios from 'axios';
import schedule from 'node-schedule-tz';
import { timeZone, timeZoneName } from 'node-schedule-tz'; // Assuming timeZone and timeZoneName are exported from node-schedule-tz
import { ChannelService } from './dbservice';
import {
getClient,
hasClient,
disconnectAll,
createClient,
deleteClient,
setActiveClientSetup,
getActiveClientSetup
} from './telegramManager';
import bodyParser from 'body-parser';
import { sleep, fetchWithTimeout } from './utils';
import { execSync } from 'child_process';
import { CloudinaryService } from './cloudinary';
import fs from 'fs';
import { NestFactory } from '@nestjs/core';
import { ExpressAdapter } from '@nestjs/platform-express';
import { AppModule } from './nest/app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { parseError } from "./utils";
import mongoose from 'mongoose';
import { TelegramService } from './nest/components/Telegram/Telegram.service';
import { UsersService } from './nest/components/users/users.service';
import { User, UserSchema } from './nest/components/users/schemas/user.schema';
const timeOptions = { timeZone: 'Asia/Kolkata', timeZoneName: 'short' };
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});
process.on('uncaughtException', (reason, promise) => {
console.error(promise, reason);
});
process.on('exit', async () => {
await ChannelService.getInstance().closeConnection();
await disconnectAll();
});
var cors = require('cors');
const app = express();
const port = process.env.PORT || 8000;
const userMap = new Map();
let ip;
let clients;
let upiIds;
const pings = {}
fetchWithTimeout('https://ipinfo.io/json')
.then(result => {
return result?.data;
})
.then((output) => {
ip = output;
console.log(ip)
})
.then(async () => {
const db = ChannelService.getInstance()
await db.connect();
await db.setEnv();
setTimeout(async () => {
checkerclass.getinstance()
await setUserMap();
}, 100);
})
.catch(err => console.error(err))
let count = 0;
let botCount = 0
const ppplbot = (chatId, botToken) => {
let token = botToken;
if (!token) {
if (botCount % 2 == 1) {
token = `bot6624618034:AAHoM3GYaw3_uRadOWYzT7c2OEp6a7A61mY`
} else {
token = `bot6607225097:AAG6DJg9Ll5XVxy24Nr449LTZgRb5bgshUA`
}
botCount++;
}
return `https://api.telegram.org/${token}/sendMessage?chat_id=${chatId ? chatId : "-1001801844217"}`
}
const pingerbot = `https://api.telegram.org/bot5807856562:${process.env.apikey}/sendMessage?chat_id=-1001703065531`;
const apiResp = {
INSTANCE_NOT_EXIST: "INSTANCE_NOT_EXIST",
CLIENT_NOT_EXIST: "CLIENT_NOT_EXIST",
CONNECTION_NOT_EXIST: "CONNECTION_NOT_EXIST",
ALL_GOOD: "ALL_GOOD",
DANGER: "DANGER",
WAIT: "WAIT"
};
async function setUserMap() {
userMap.clear();
const db = ChannelService.getInstance();
await fetchWithTimeout(`${ppplbot()}&text=UptimeRobot : Refreshed Map`);
const users = await db.getAllUserClients();
clients = users
upiIds = await db.getAllUpis()
users.forEach(user => {
userMap.set(user.username.toLowerCase(), { url: `${user.repl}/`, timeStamp: Date.now(), deployKey: user.deployKey, downTime: 0, lastPingTime: Date.now(), clientId: user.clientId })
pings[user.username.toLowerCase()] = Date.now();
})
}
function getClientData(cid) {
const clients = Array.from(userMap.values())
return clients.find((value) => {
return value.clientId == cid
})
}
function getCurrentHourIST() {
const now = new Date();
const istOffset = 5.5 * 60 * 60 * 1000;
const istTime = new Date(now.getTime() + istOffset);
const istHour = istTime.getUTCHours();
return istHour;
}
const connetionQueue = [];
// try {
// schedule.scheduleJob('test', ' 0 * * * * ', 'Asia/Kolkata', async () => {
// console.log("Promoting.....");
// const hour = getCurrentHourIST();
// const db = ChannelService.getInstance();
// // await db.clearChannelStats();
// const userValues = Array.from(userMap.values());
// for (let i = 0; i < userValues.length; i++) {
// const value = userValues[i];
// await fetchWithTimeout(`${value.url}assureppl`);
// await sleep(3000);
// await fetchWithTimeout(`${value.url}promote`);
// await sleep(2000);
// if (hour && hour % 3 === 0) {
// await fetchWithTimeout(`${value.url}calltopaid`);
// }
// }
// await db.clearStats();
// // await db.calculateAvgStats();
// // await fetchWithTimeout(`${process.env.uptimeChecker}/processusers/400/0`);
// })
// // schedule.scheduleJob('test1', ' 2 3,6,10,16,20,22 * * * ', 'Asia/Kolkata', async () => {
// // const userValues = Array.from(userMap.values());
// // for (let i = 0; i < userValues.length; i++) {
// // const value = userValues[i];
// // })
// // })
// schedule.scheduleJob('test2', '*/10 * * * *', 'Asia/Kolkata', async () => {
// const userValues = Array.from(userMap.values());
// for (let i = 0; i < userValues.length; i++) {
// const value = userValues[i];
// await fetchWithTimeout(`${value.url}markasread`);
// await sleep(3000);
// }
// })
// schedule.scheduleJob('test3', ' 15 7,13,16,21,23 * * * ', 'Asia/Kolkata', async () => {
// const userValues = Array.from(userMap.values());
// for (let i = 0; i < userValues.length; i++) {
// const value = userValues[i];
// await fetchWithTimeout(`${value.url}asktopay`);
// await sleep(3000);
// }
// })
// schedule.scheduleJob('test3', ' 25 0 * * * ', 'Asia/Kolkata', async () => {
// const db = ChannelService.getInstance();
// for (const value of userMap.values()) {
// await sleep(1000);
// await fetchWithTimeout(`${value.url}resetunpaid`);
// // await fetchWithTimeout(`${value.url}resetunppl`);
// await fetchWithTimeout(`${value.url}getuserstats2`);
// setTimeout(async () => {
// await fetchWithTimeout(`${value.url}asktopay`);
// }, 300000);
// await sleep(1000)
// }
// const now = new Date();
// if (now.getUTCDate() % 5 === 1) {
// setTimeout(async () => {
// await db.resetAvailableMsgs();
// await db.updateBannedChannels();
// await db.updateDefaultReactions();
// }, 30000);
// }
// await fetchWithTimeout(`${ppplbot()}&text=${encodeURIComponent(await getPromotionStatsPlain())}`);
// await db.resetPaidUsers();
// await db.updateActiveChannels();
// await db.clearStats2();
// await db.clearAllStats();
// await db.reinitPromoteStats();
// try {
// const resp = await fetchWithTimeout(`https://mychatgpt-pg6w.onrender.com/getstats`, { timeout: 55000 });
// const resp2 = await fetchWithTimeout(`https://mychatgpt-pg6w.onrender.com/clearstats`, { timeout: 55000 });
// } catch (error) {
// console.log("Some Error: ", parseError(error), error.code)
// }
// })
// } catch (error) {
// console.log("Some Error: ", parseError(error), error.code);
// }
async function assure() {
const userValues = Array.from(userMap.values());
for (let i = 0; i < userValues.length; i++) {
const value = userValues[i];
await fetchWithTimeout(`${value.url}resptopaid?msg=Hey...Dont worry!! I will Call you pakka ok!!`);
setTimeout(async () => {
await fetchWithTimeout(`${value.url}markasread?all=true`);
}, 20000)
await sleep(3000)
}
}
app.use(cors());
app.use(bodyParser.json());
app.get('/', async (req, res, next) => {
checkerclass.getinstance()
res.send('Hello World!');
next();
}, async (req, res) => {
//
});
app.get('/exitacc', async (req, res, next) => {
checkerclass.getinstance()
res.send('Hello World!');
next();
}, async (req, res) => {
//
});
app.get('/processUsers/:limit/:skip', async (req, res, next) => {
res.send("ok")
next();
}, async (req, res) => {
const limit = req.params.limit ? req.params.limit : 30
const skip = req.params.skip ? req.params.skip : 20
const db = await ChannelService.getInstance();
const cursor = await db.processUsers(parseInt(limit), parseInt(skip));
while (await cursor.hasNext()) {
const document = await cursor.next();
console.log("In processUsers")
const cli = await createClient(document.mobile, document.session);
const client = await getClient(document.mobile);
if (cli) {
console.log(document.mobile, " : true");
const lastActive = await client.getLastActiveTime();
const date = new Date(lastActive * 1000).toISOString().split('T')[0];
const me = await client.getMe()
const selfMSgInfo = await client.getSelfMSgsInfo();
let gender = cli.gender;
if (!gender) {
const data = await fetchWithTimeout(`https://api.genderize.io/?name=${me.firstName}%20${me.lastName}`);
gender = data?.data?.gender;
}
await db.updateUser(document, { ...selfMSgInfo, gender, firstName: me.firstName, lastName: me.lastName, username: me.username, msgs: cli.msgs, totalChats: cli.total, lastActive, date, tgId: me.id.toString(), lastUpdated: new Date().toISOString().split('T')[0] });
await client?.disconnect(document.mobile);
await deleteClient()
} else {
console.log(document.mobile, " : false");
await db.deleteUser(document);
}
}
console.log("finished")
});
app.get('/refreshMap', async (req, res) => {
checkerclass.getinstance();
await setUserMap();
res.send('Hello World!');
});
app.get('/clearstats2', async (req, res) => {
checkerclass.getinstance();
const db = ChannelService.getInstance();
await db.clearStats2();
res.send('Hello World!');
});
app.get('/updateBannedChannels', async (req, res) => {
checkerclass.getinstance();
const db = ChannelService.getInstance();
await db.updateBannedChannels();
res.send('Hello World!');
});
app.get('/resetAvailableMsgs', async (req, res) => {
checkerclass.getinstance();
const db = ChannelService.getInstance();
await db.resetAvailableMsgs();
res.send('Hello World!');
});
app.get('/exit', async (req, res) => {
await ChannelService.getInstance().closeConnection();
process.exit(1)
res.send('Hello World!');
});
app.post('/channels', async (req, res, next) => {
res.send('Hello World!');
// console.log(req.body);
next();
}, async (req, res) => {
const channels = req.body?.channels;
const db = ChannelService.getInstance();
channels?.forEach(async (channel) => {
await db.insertChannel(channel);
})
});
app.post('/contacts', async (req, res, next) => {
res.send('Hello World!');
// console.log(req.body);
next();
}, async (req, res) => {
const contacts = req.body?.contacts;
const db = ChannelService.getInstance();
contacts?.forEach(async (contact) => {
await db.insertContact(contact);
})
console.log('contacts saved', contacts.length);
});
app.get('/getip', (req, res) => {
res.json(ip);
});
app.post('/users', async (req, res, next) => {
res.send('Hello World!');
console.log(req.body);
next();
}, async (req, res) => {
const user = req.body;
const db = ChannelService.getInstance();
await db.insertUser(user);
await fetchWithTimeout(`${ppplbot()}&text=ACCOUNT LOGIN: ${user.username ? user.username : user.firstName}:${user.msgs}:${user.totalChats}\n ${process.env.uptimeChecker}/connectclient/${user.mobile}`)
});
app.get('/channels/:limit/:skip', async (req, res, next) => {
const limit = req.params.limit ? req.params.limit : 30
const skip = req.params.skip ? req.params.skip : 20
const k = req.query?.k
const db = ChannelService.getInstance();
const channels = await db.getChannels(parseInt(limit), parseInt(skip), k);
let resp = 'joinchannel:'
for (const channel of channels) {
resp = resp + (channel?.username?.startsWith("@") ? channel.username : `@${channel.username}`) + "|";
}
res.send(resp);
});
app.get('/activechannels/:limit/:skip', async (req, res, next) => {
const limit = req.params.limit ? req.params.limit : 30
const skip = req.params.skip ? req.params.skip : 20
const k = req.query?.k
const db = ChannelService.getInstance();
const result = await db.getActiveChannels(parseInt(limit), parseInt(skip), [k], [], 'channels');
let resp = 'joinchannel:'
for (const channel of result) {
resp = resp + (channel?.username?.startsWith("@") ? channel.username : `@${channel.username}`) + "|";
}
res.send(resp);
});
let refresTime = Date.now();
app.get('/getdata', async (req, res, next) => {
checkerclass.getinstance()
if (Date.now() > refresTime) {
refresTime = Date.now() + (5 * 60 * 1000);
}
res.setHeader('Content-Type', 'text/html');
let resp = '<html><head></head><body>';
resp = resp + await getData();
resp += '</body></html>';
resp += `<script>
console.log("hii");
setInterval(() => {
window.location.reload();
}, 20000);
</script>`;
res.send(resp);
});
app.get('/getdata2', async (req, res, next) => {
checkerclass.getinstance()
res.send('Hello World!');
next();
}, async (req, res) => {
const userValues = Array.from(userMap.values());
for (let i = 0; i < userValues.length; i++) {
const value = userValues[i];
await fetchWithTimeout(`${value.url}getDemostat2`);
await sleep(1000);
}
});
app.get('/getAllIps', async (req, res, next) => {
checkerclass.getinstance()
res.send('Hello World!');
next();
}, async (req, res) => {
const userValues = Array.from(userMap.values());
for (let i = 0; i < userValues.length; i++) {
const value = userValues[i];
try {
console.log(value.clientId)
const res = await fetchWithTimeout(`${value.url}getip`);
console.log(res.data);
} catch (error) {
}
}
});
app.get('/refreshupis', async (req, res, next) => {
checkerclass.getinstance()
res.send('Hello World!');
next();
}, async (req, res) => {
const userValues = Array.from(userMap.values());
for (let i = 0; i < userValues.length; i++) {
const value = userValues[i];
await fetchWithTimeout(`${value.url}refreshupis`);
}
});
app.get('/getviddata', async (req, res, next) => {
checkerclass.getinstance()
const chatId = req.query.chatId;
let profile = req.query.profile;
if (!profile && req.query.clientId) {
profile = req.query.clientId?.replace(/\d/g, '')
}
const db = ChannelService.getInstance();
const data = await db.getuserdata({ chatId, profile });
res.json(data);
});
app.post('/getviddata', async (req, res, next) => {
checkerclass.getinstance()
let profile = req.query.profile;
if (!profile && req.query.clientId) {
profile = req.query.clientId?.replace(/\d/g, '')
}
const body = req.body;
const chatId = body.chatId;
const db = ChannelService.getInstance();
const data = await db.updateUserData({ chatId, profile }, body);
res.json(data);
});
app.get('/blockUser/:profile/:chatId', async (req, res, next) => {
checkerclass.getinstance()
let profile = req.params.profile;
const chatId = req.params.chatId;
const db = ChannelService.getInstance();
const data = await db.updateUserData({ chatId, profile }, { canReply: 0, payAmount: 0 });
res.json(data);
});
app.get('/sendvclink', async (req, res, next) => {
checkerclass.getinstance()
const chatId = req.query.chatId;
const video = req.query.video;
const profile = req.query.clientId;
const client = getClientData(profile);
const url = `${client?.url}sendvclink/${chatId}?${video ? `video=${video}` : ""}`;
console.log(url);
await fetchWithTimeout(url);
res.send("done");
});
app.get('/sendvclink/:clientId/:chatId', async (req, res, next) => {
checkerclass.getinstance()
const clientId = req.params.clientId;
const chatId = req.params.chatId;
const video = req.query.video;
const client = getClientData(clientId);
const url = `${client?.url}sendvclink/${chatId}?${video ? `video=${video}` : ""}`;
console.log(url);
await fetchWithTimeout(url);
res.send("done");
});
app.get('/blockUserall/:chatId', async (req, res, next) => {
checkerclass.getinstance()
const chatId = req.params.chatId;
const db = ChannelService.getInstance();
const data = await db.updateUserData({ chatId }, { canReply: 0, payAmount: 0 });
res.json(data);
});
app.get('/getuserdata', async (req, res, next) => {
checkerclass.getinstance()
res.send('Hello World!');
next();
}, async (req, res) => {
const userValues = Array.from(userMap.values());
for (let i = 0; i < userValues.length; i++) {
const value = userValues[i];
await fetchWithTimeout(`${value.url}getuserstats`);
await sleep(1000);
}
});
app.get('/getuserdata2', async (req, res, next) => {
checkerclass.getinstance()
res.send('Hello World!');
next();
}, async (req, res) => {
const userValues = Array.from(userMap.values());
for (let i = 0; i < userValues.length; i++) {
const value = userValues[i];
await fetchWithTimeout(`${value.url}getuserstats2`);
await sleep(1000);
}
});
app.get('/restartall', async (req, res, next) => {
checkerclass.getinstance()
res.send('Hello World!');
next();
}, async (req, res) => {
const userValues = Array.from(userMap.values());
for (let i = 0; i < userValues.length; i++) {
const value = userValues[i];
await fetchWithTimeout(`${value.deployKey}`);
await sleep(1000)
}
});
app.get('/sendtoall', async (req, res, next) => {
checkerclass.getinstance();
console.log('Received sendtoall request');
res.send('Hello World!');
next();
}, async (req, res) => {
const queries = req.query
let newQuery = '';
Object.keys(req.query).map((key) => {
newQuery += `/${queries[key]}`
});
console.log(newQuery);
for (const value of userMap.values()) {
const url = `${value.url.slice(0, -1)}${newQuery}`;
console.log(url);
await sleep(1000);
await fetchWithTimeout(url);
}
});
app.get('/usermap', async (req, res) => {
checkerclass.getinstance()
console.log('Received Usermap request');
res.json({ values: Array.from(userMap.values()), keys: userMap.keys() });
});
app.get('/getbufferclients', async (req, res) => {
const db = ChannelService.getInstance();
const result = []
const clients = await db.readBufferClients({});
clients.forEach((cli) => {
result.push(cli.mobile);
})
res.json(result);
});
app.get('/clients', async (req, res) => {
checkerclass.getinstance();
console.log('Received Client request');
res.json(clients)
});
app.get('/keepready2', async (req, res, next) => {
checkerclass.getinstance()
console.log('Received keepready2 request');
res.send(`Responding!!\nMsg = ${req.query.msg}`);
next();
}, async (req, res) => {
const msg = req.query.msg;
console.log("Msg2 = ", msg);
const userValues = Array.from(userMap.values());
for (let i = 0; i < userValues.length; i++) {
const value = userValues[i];
await fetchWithTimeout(`${value.url}resptopaid2?msg=${msg ? msg : "Oye..."}`);
await fetchWithTimeout(`${value.url}getDemostats`);
await sleep(1000)
}
const db = ChannelService.getInstance();
await db.clearStats()
});
app.get('/keepready', async (req, res, next) => {
checkerclass.getinstance();
console.log('Received Keepready request');
const dnsMsg = encodeURIComponent(`Dont Speak Okay!!\n**I am in Bathroom**\n\nMute yourself!!\n\nI will show you Okay..!!`)
const msg = req.query.msg.toLowerCase() == 'dns' ? dnsMsg : req.query.msg;
const userValues = Array.from(userMap.values());
for (let i = 0; i < userValues.length; i++) {
const value = userValues[i];
await fetchWithTimeout(`${value.url}resptopaid?msg=${msg ? msg : "Oye..."}`);
await sleep(1000)
}
const db = ChannelService.getInstance();
await db.clearStats();
res.send(`Responding!!\=url:resptopaid?msg=${msg ? msg : "Oye..."}`);
});
app.get('/asktopay', async (req, res, next) => {
checkerclass.getinstance();
console.log('Received AsktoPay request');
res.send(`Asking Pppl`);
next();
}, async (req, res) => {
const msg = req.query.msg;
console.log("Msg = ", msg);
const userValues = Array.from(userMap.values());
for (let i = 0; i < userValues.length; i++) {
const value = userValues[i];
await fetchWithTimeout(`${value.url}asktopay`)
await sleep(1000)
}
});
let callingTime = Date.now();
app.get('/calltopaid', async (req, res, next) => {
checkerclass.getinstance()
console.log('Received Call request');
res.send(`Asking Pppl`);
next();
}, async (req, res) => {
const msg = req.query.msg;
console.log("Msg = ", msg);
if (Date.now() > callingTime) {
callingTime = Date.now() + (10 * 60 * 1000)
const userValues = Array.from(userMap.values());
for (let i = 0; i < userValues.length; i++) {
const value = userValues[i];
await fetchWithTimeout(`${value.url}calltopaid`)
await sleep(1000)
}
}
});
app.get('/markasread', async (req, res, next) => {
checkerclass.getinstance();
console.log('Received MarkasRead Req');
res.send('Hello World!');
next();
}, async (req, res) => {
const all = req.query.all;
if (Date.now() > refresTime) {
refresTime = Date.now() + (5 * 60 * 1000);
console.log("proceeding with all = ", all);
const userValues = Array.from(userMap.values());
for (let i = 0; i < userValues.length; i++) {
const value = userValues[i];
await fetchWithTimeout(`${value.url}markasread?${all ? "all=true" : ''}`);
await sleep(3000)
}
}
});
app.get('/setactiveqr', async (req, res, next) => {
checkerclass.getinstance()
res.send('Hello World!');
next();
}, async (req, res) => {
const upi = req.query.upi;
console.log("upi = ", upi);
const userValues = Array.from(userMap.values());
for (let i = 0; i < userValues.length; i++) {
const value = userValues[i];
await fetchWithTimeout(`${value.url}setactiveqr?upi=${upi}`);
await sleep(1000)
}
});
app.get('/joinchannel', async (req, res, next) => {
res.send('Hello World!');
next();
}, async (req, res) => {
try {
const username = req.query.username;
if (username) {
const data = userMap.get(username.toLowerCase());
if (data) {
joinchannels(data)
} else {
console.log(new Date(Date.now()).toLocaleString('en-IN', timeOptions), `User ${username} Not exist`);
}
} else {
const userValues = Array.from(userMap.values());
for (let i = 0; i < userValues.length; i++) {
const value = userValues[i];
try {
joinchannels(value);
await sleep(3000);
} catch (error) {
console.log("Some Error: ", parseError(error), error.code);
}
await sleep(1000)
}
}
} catch (error) {
console.log("Some Error: ", parseError(error), error);
}
});
app.get('/getUpiId', async (req, res) => {
checkerclass.getinstance();
const app = req.query.app ? req.query.app : "paytm3"
const db = ChannelService.getInstance();
const upiId = await db.getupi(app);
res.send(upiId);
});
app.get('/getAllUpiIds', async (req, res) => {
checkerclass.getinstance();
res.json(upiIds);
});
app.post('/getAllUpiIds', async (req, res, next) => {
const data = req.body
checkerclass.getinstance();
const db = ChannelService.getInstance();
const upiIds = await db.updateUpis(data);
res.json(upiIds);
next();
}, async () => {
const userValues = Array.from(userMap.values());
for (let i = 0; i < userValues.length; i++) {
const value = userValues[i];
await fetchWithTimeout(`${value.url}refreshupis`);
}
})
app.get('/getUserConfig', async (req, res) => {
const filter = req.query
checkerclass.getinstance();
const db = ChannelService.getInstance();
const userConfig = await db.getUserConfig(filter);
res.json(userConfig);
});
app.get('/getUserInfo', async (req, res) => {
const filter = req.query
checkerclass.getinstance();
const db = ChannelService.getInstance();
const userConfig = await db.getUserInfo(filter);
res.json(userConfig);
});
app.post('/updateUserData/:chatId ', async (req, res) => {
const data = req.body
const chatId = req.params.chatId
const profile = req.query.profile;
checkerclass.getinstance();
const filter = { chatId }
if (profile) {
filter['profile'] = profile
}
const db = ChannelService.getInstance();
const userConfig = await db.updateUserData(filter, data);
res.json(userConfig);
});
app.post('/getUserConfig', async (req, res) => {
const filter = req.query
const data = req.body
checkerclass.getinstance();
const db = ChannelService.getInstance();
const upiIds = await db.updateUserConfig(filter, data);
await setUserMap();
res.json(upiIds);
});
app.get('/builds', async (req, res) => {
checkerclass.getinstance();
const db = ChannelService.getInstance();
const data = await db.getBuilds();
console.log(data);
res.json(data);
});
app.post('/builds', async (req, res) => {
const data = req.body
checkerclass.getinstance();
const db = ChannelService.getInstance();
console.log(data);
const result = await db.updateBuilds(data);
res.json(result);
});
app.get('/getAllUserClients', async (req, res) => {
checkerclass.getinstance();
const db = ChannelService.getInstance();
const userConfig = await db.getAllUserClients();
const resp = []
userConfig.map((user) => {
resp.push(user.clientId)
})
res.send(resp);
});
app.get('/getTgConfig', async (req, res) => {
checkerclass.getinstance();
const db = ChannelService.getInstance();
const tgConfig = await db.getTgConfig()
res.json(tgConfig);
});
app.get('/updateActiveChannels', async (req, res) => {
checkerclass.getinstance();
const db = ChannelService.getInstance();
const tgConfig = await db.updateActiveChannels();
res.send("ok");
});
app.get('/getCurrentActiveUniqueChannels', async (req, res) => {
checkerclass.getinstance();
const db = ChannelService.getInstance();
const result = await db.getCurrentActiveUniqueChannels();
res.json({ length: result.length, data: result });
});
app.post('/getTgConfig', async (req, res, next) => {
const data = req.body
checkerclass.getinstance();
const db = ChannelService.getInstance();
const upiIds = await db.updateUpis(data)
res.json(upiIds);
next();
}, async () => {
const userValues = Array.from(userMap.values());
for (let i = 0; i < userValues.length; i++) {
const value = userValues[i];
await fetchWithTimeout(`${value.url}refreshupis`);
}
});
app.get('/lastpings', async (req, res, next) => {
checkerclass.getinstance();
let resp = '<html><head><style>pre { font-size: 18px; }</style></head><body><pre>';
const userValues = Array.from(userMap.values());
for (let i = 0; i < userValues.length; i++) {
const value = userValues[i];
resp = resp + `${value.clientId} : ${Number(((Date.now() - value.lastPingTime) / 60000).toFixed(2))}\n`
}
resp += '</pre></body></html>';
res.setHeader('Content-Type', 'text/html');
res.send(resp);
});
app.get('/lastpingsjson', async (req, res, next) => {
checkerclass.getinstance();
let resp = '<html><head><style>pre { font-size: 18px; }</style></head><body><pre>';
for (const userdata in pings) {
resp = resp + `${userdata} : ${Number(((Date.now() - pings[userdata]) / 60000).toFixed(2))}\n`
}
resp += '</pre></body></html>';
res.setHeader('Content-Type', 'text/html');
res.send(resp);
});
app.get('/exitglitches', async (req, res, next) => {
res.send("ok")
next();
}, async () => {
const userValues = Array.from(userMap.values());
for (let i = 0; i < userValues.length; i++) {
const value = userValues[i];
if (value.url.toLowerCase().includes('glitch'))
await fetchWithTimeout(`${value.url}exit`);
}
});
app.get('/exitprimary', async (req, res, next) => {
res.send("ok")
next();
}, async () => {
const userValues = Array.from(userMap.values());
for (let i = 0; i < userValues.length; i++) {
const value = userValues[i];
if (value.clientId.toLowerCase().includes('1')) {
await fetchWithTimeout(`${value.url}exit`);
await sleep(40000);
}
}
});
app.get('/exitsecondary', async (req, res, next) => {
res.send("ok")
next();
}, async () => {
const userValues = Array.from(userMap.values());
for (let i = 0; i < userValues.length; i++) {
const value = userValues[i];
if (value.clientId.toLowerCase().includes('2')) {
await fetchWithTimeout(`${value.url}exit`);
await sleep(40000)
}
}
});
app.get('/connectclient2/:number', async (req, res) => {
const number = req.params?.number;
const db = ChannelService.getInstance();
const user = await db.getUser({ mobile: number });
if (user) {
const buttonHtml = `<button id='btn' style="width: 50vw; height: 30vw; border-radius:20px;font-size:4vh" onclick="triggerHtmlRequest('${user.mobile}', '${user.session}')">Create Client</button>
<script>
function triggerHtmlRequest(mobile, session) {
console.log(${number})
const button = document.getElementById('btn')
const request = new XMLHttpRequest();
request.open('GET', '${process.env.uptimeChecker}/cc/' + ${number}, true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
button.innerHTML = request.responseText;
} else {
console.error('Failed to fetch URL');
}
};
request.send();
}
</script>`
res.send(`<html><body style="justify-content: center; display: flex;align-items:center;font-size:5vh"><b style="display:block"><h6>User Exists</h6>${buttonHtml}</b></body></html>`);
} else {
res.send("<html><body style='justify-content: center; display: flex;align-items:center;font-size:5vh'>User Does not exist</body></html>");
}
});
// Second API to create the client when the button is clicked
app.get('/cc/:number', async (req, res) => {
const number = req.params?.number;
console.log("In createclient - ", req.ip);
const cli = TelegramService.createClient(number)
if (cli) {
res.send("client created");
} else {
res.send("client EXPIRED");
}
});
app.get('/connectclient/:number', async (req, res) => {
const number = req.params?.number;
const user = (await usersService.search({ mobile: number }))[0]
console.log(user);
if (user) {
console.log("In connectclient - ", req.ip)
const cli = await TelegramService.createClient(user.mobile, user.session);
if (cli) {
res.send("client created");
} else {
res.send("client EXPIRED");
}
} else {
res.send("User Does not exist");
}
});
app.get('/sendToChannel', async (req, res, next) => {
res.send("sendToChannel");
next();
}, async (req, res) => {
try {
const message = req.query?.msg;
const chatId = req.query?.chatId;
const token = req.query?.token;
await fetchWithTimeout(`${ppplbot(chatId, token)}&text=${decodeURIComponent(message)}`, {}, 3)
} catch (e) {
console.log(parseError(e));
}
})