-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
1523 lines (1329 loc) · 55.2 KB
/
Copy pathserver.ts
File metadata and controls
1523 lines (1329 loc) · 55.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import express from "express";
import path from "path";
import axios from "axios";
import dotenv from "dotenv";
import multer from "multer";
import FormData from "form-data";
import fs from "fs";
import os from "os";
import { GoogleAuth } from "google-auth-library";
import { GoogleGenAI } from "@google/genai";
import { TelegramClient, Api } from "telegram";
import { StringSession } from "telegram/sessions";
// Temporary in-memory storage cache for active Telegram MTProto clients and verification hashes
const activeTelegramClients = new Map<string, TelegramClient>();
const activeTelegramHashes = new Map<string, string>();
// Inline stubs to replace removed heavy C++ native packages or obsolete platform SDKs
class AccessToken {
constructor(...args: any[]) {}
addGrant(...args: any[]) {}
toJwt() { return Promise.resolve("mock-livekit-token-sandbox"); }
}
const createClient = (...args: any[]) => ({
from: (table: string) => ({
select: (fields?: string) => Promise.resolve({ data: [], error: null }),
update: (data: any) => ({
eq: (col: string, val: any) => Promise.resolve({ error: null })
})
})
});
dotenv.config();
const app = express();
app.use(express.json({ limit: '50mb' }));
// GitHub OAuth Config
const GITHUB_CLIENT_ID = process.env.GITHUB_CLIENT_ID;
const GITHUB_CLIENT_SECRET = process.env.GITHUB_CLIENT_SECRET;
// Configure Multer for temporary storage in the OS temp directory
const upload = multer({
dest: os.tmpdir(),
limits: { fileSize: 100 * 1024 * 1024 } // 100MB limit
});
// API routes
app.get("/api/health", (req, res) => {
res.json({ status: "ok", message: "IndoGram Server is running" });
});
// Real Telegram MTProto OTP Dispatch Router
app.post("/api/telegram/send-code", async (req, res) => {
try {
const { phone, apiId: customApiId, apiHash: customApiHash } = req.body;
if (!phone) {
return res.status(400).json({ error: "Phone number is required" });
}
// Capture standard or custom credentials
const apiIdStr = customApiId || process.env.VITE_TELEGRAM_API_ID;
const apiHashStr = customApiHash || process.env.VITE_TELEGRAM_API_HASH;
if (!apiIdStr || !apiHashStr) {
return res.json({
success: false,
error: "credentials_missing",
message: "Telegram API ID and API Hash are not configured yet. Please open the Settings menu or configure them locally on IndoGram."
});
}
const apiId = Number(apiIdStr);
if (isNaN(apiId)) {
return res.status(400).json({ error: "Invalid API ID format. Must be a numeric identifier." });
}
// Disconnect existing active connection for this phone to prevent leaks
const existingClient = activeTelegramClients.get(phone);
if (existingClient) {
try {
await existingClient.disconnect();
} catch (_) {}
activeTelegramClients.delete(phone);
}
console.log(`[MTProto Server] Initiating active client connect sequence for phone: ${phone}...`);
const client = new TelegramClient(new StringSession(""), apiId, apiHashStr, {
connectionRetries: 5,
});
// Set _loopStarted to true to completely bypass GramJS background updates loop (which is prone to timeouts under container/sandboxes)
(client as any)._loopStarted = true;
await client.connect();
console.log(`[MTProto Server] Triggering real-time auth.sendCode call...`);
const { phoneCodeHash } = await client.sendCode(
{
apiId,
apiHash: apiHashStr,
},
phone
);
// Save client instance and active hash state
activeTelegramClients.set(phone, client);
activeTelegramHashes.set(phone, phoneCodeHash);
console.log(`[MTProto Server] Success! Real OTP has been dispatched to phone: ${phone}`);
return res.json({
success: true,
message: "API auth code successfully requested from Telegram!",
phoneCodeHash,
});
} catch (err: any) {
console.error("[MTProto Server Error] Failed to send Telegram OTP Code:", err);
return res.json({
success: false,
error: err.message || "Failed to dispatch verification code via MTProto broker."
});
}
});
// Real Telegram MTProto OTP Verify and Auth Session Complete
app.post("/api/telegram/verify-code", async (req, res) => {
try {
const { phone, code, apiId: customApiId, apiHash: customApiHash } = req.body;
if (!phone || !code) {
return res.status(400).json({ error: "Missing required parameters phone or validation code." });
}
const client = activeTelegramClients.get(phone);
const phoneCodeHash = activeTelegramHashes.get(phone);
if (!client || !phoneCodeHash) {
return res.json({
success: false,
error: "session_expired",
message: "Verification session expired or does not exist. Please trigger a new OTP code send."
});
}
const apiIdStr = customApiId || process.env.VITE_TELEGRAM_API_ID;
const apiHashStr = customApiHash || process.env.VITE_TELEGRAM_API_HASH;
console.log(`[MTProto Server] Directing client.signIn authentication attempt for ${phone}...`);
await client.invoke(
new Api.auth.SignIn({
phoneNumber: phone,
phoneCodeHash,
phoneCode: code,
})
);
// Save authenticated connection Session string
const stringSession = (client.session.save() as unknown) as string;
// Optional grab of current profile to populate local app database
let me: any = null;
try {
me = await client.getMe();
} catch (meError) {
console.warn("Could not retrieve me profile info in current environment:", meError);
}
// Disconnect active client from server memory since state is loaded by stringSession
try {
await client.disconnect();
} catch (_) {}
activeTelegramClients.delete(phone);
activeTelegramHashes.delete(phone);
console.log(`[MTProto Server] Login successful for user: ${phone}`);
return res.json({
success: true,
message: "Authentication with Telegram verified!",
sessionString: stringSession,
user: me ? {
id: me.id?.toString() || "",
firstName: me.firstName || "",
lastName: me.lastName || "",
username: me.username || "",
phone: me.phone || phone,
} : { phone }
});
} catch (err: any) {
console.error("[MTProto Server Error] Authentication sign-in failed:", err);
return res.json({
success: false,
error: err.message || "Invalid or expired verification code."
});
}
});
// Helper to instantiate temporary live MTProto Telegram Client safely
async function getTelegramClient(sessionString: string): Promise<TelegramClient> {
const apiIdStr = process.env.VITE_TELEGRAM_API_ID || "2040";
const apiHashStr = process.env.VITE_TELEGRAM_API_HASH || "indogram_sandbox_hash";
const apiId = Number(apiIdStr);
const client = new TelegramClient(new StringSession(sessionString), apiId, apiHashStr, {
connectionRetries: 3,
});
(client as any)._loopStarted = true;
await client.connect();
return client;
}
// Helper to identify if a peer ID is a mock/local-only target and shouldn't call GramJS
function isMockPeer(peerId: any): boolean {
if (!peerId) return true;
const peerStr = String(peerId).trim();
const mockList = [
"tg_news_channel", "indo_ai_bot", "indo_dev_group", "pavel_durov", "indo_support",
"user_durov", "user_alice", "user_nikolai", "user_elena", "user_viktor", "user_clara",
"indogram_news", "indogram_devs", "ai_chat"
];
if (mockList.includes(peerStr)) return true;
if (peerStr.startsWith("user_") || peerStr.startsWith("msg_") || peerStr.startsWith("mock_") || peerStr.startsWith("gx_")) {
return true;
}
if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(peerStr)) {
return true;
}
return false;
}
// Convert numeric string to appropriate types for GramJS, falling back to string
function prepareTelegramPeer(peerId: any): any {
if (!peerId) return peerId;
const peerStr = String(peerId).trim();
if (/^-?\d+$/.test(peerStr)) {
try {
return BigInt(peerStr);
} catch {
return Number(peerStr);
}
}
return peerStr;
}
// 0. Download Profile Avatar Endpoint
app.get("/api/telegram/avatar/:id", async (req, res) => {
const { id } = req.params;
const sessionString = (req.query.session as string) || req.headers.authorization;
if (!sessionString) {
return res.status(400).send("Session string is required as query param ?session=<string>");
}
try {
const client = await getTelegramClient(sessionString);
const cleanPeer = prepareTelegramPeer(id);
const buffer = await client.downloadProfilePhoto(cleanPeer);
await client.disconnect();
if (buffer) {
res.setHeader("Content-Type", "image/jpeg");
res.setHeader("Cache-Control", "public, max-age=86400"); // Cache inside client browser for 24h
return res.end(buffer);
} else {
return res.status(404).send("No profile icon found");
}
} catch (err: any) {
console.warn(`[MTProto Avatar Download Warning for peer ${id}]:`, err.message);
return res.status(404).send("Fallback image placeholder needed");
}
});
// Download Message Media Endpoint
app.get("/api/telegram/media/:peerId/:messageId", async (req, res) => {
const { peerId, messageId } = req.params;
const sessionString = (req.query.session as string) || req.headers.authorization;
if (!sessionString) {
return res.status(400).send("Session string is required");
}
try {
const client = await getTelegramClient(sessionString);
const cleanPeer = prepareTelegramPeer(peerId);
// Get the specific message
const messages = await client.getMessages(cleanPeer, { ids: [parseInt(messageId)] });
if (!messages || messages.length === 0) {
await client.disconnect();
return res.status(404).send("Message not found");
}
const m = messages[0];
if (!m.media) {
await client.disconnect();
return res.status(400).send("Message has no media");
}
// Determine the mime type to set correct headers
let contentType = "application/octet-stream";
const mediaAny = m.media as any;
const className = mediaAny.className || mediaAny.constructor?.name;
if (className === "MessageMediaPhoto" || mediaAny.photo) {
contentType = "image/jpeg";
} else if (className === "MessageMediaDocument" || mediaAny.document) {
contentType = mediaAny.document.mimeType || "application/octet-stream";
}
// Download the media to a buffer
const buffer = await client.downloadMedia(m.media);
await client.disconnect();
if (buffer) {
res.setHeader("Content-Type", contentType);
res.setHeader("Cache-Control", "public, max-age=86400"); // Cache inside client browser for 24h
return res.end(buffer);
} else {
return res.status(404).send("Failed to download media");
}
} catch (err: any) {
console.warn(`[MTProto Media Download Warning for peer ${peerId}, msg ${messageId}]:`, err.message);
return res.status(404).send("Failed to retrieve media");
}
});
// 1. Get Live Dialogs / Conversations
app.post("/api/telegram/get-dialogs", async (req, res) => {
const { sessionString } = req.body;
if (!sessionString) {
return res.status(400).json({ error: "Session string is required" });
}
try {
const client = await getTelegramClient(sessionString);
const dialogs = await client.getDialogs({ limit: 40 });
const formatted = dialogs.map((d: any) => {
const id = d.id?.toString() || "";
const name = d.name || "Telegram User";
const unreadCount = d.unreadCount || 0;
let lastMsg = d.message?.message || "";
if (!lastMsg && d.message) {
let actionDesc = "";
if (d.message.action) {
const className = d.message.action.className || d.message.action.constructor?.name || "";
if (className.includes("ContactSignUp")) {
actionDesc = "joined Telegram";
} else if (className.includes("ChatAddUser") || className.includes("ChatJoinedByLink")) {
actionDesc = "joined the group";
} else if (className.includes("ChatCreate")) {
actionDesc = "created the group";
} else if (className.includes("PinMessage") || className.includes("Pinned")) {
actionDesc = "pinned a message";
} else {
actionDesc = "performed a service action";
}
}
if (actionDesc) {
const sName = d.message.sender
? `${d.message.sender.firstName || ""} ${d.message.sender.lastName || ""}`.trim() || d.message.sender.username || ""
: "";
lastMsg = sName ? `${sName} ${actionDesc}` : actionDesc;
} else {
lastMsg = "No messages";
}
}
const lastMsgAt = d.message?.date ? new Date(d.message.date * 1000).toISOString() : new Date().toISOString();
const isOnline = false;
const isGroup = d.isGroup || d.isChannel;
return {
id,
type: isGroup ? 'group' : 'direct',
otherUserId: id,
user: name,
username: d.peer?.username || "",
fullName: name,
lastMsg,
lastMsgAt,
time: d.message?.date ? new Date(d.message.date * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : "",
avatar: d.peer?.photo ? `/api/telegram/avatar/${id}?session=${encodeURIComponent(sessionString)}` : `https://images.unsplash.com/photo-1542751371-adc38448a05e?w=150`,
unread: unreadCount > 0,
unreadCount,
isOnline,
lastMsgStatus: 'Received'
};
});
await client.disconnect();
return res.json({ success: true, conversations: formatted });
} catch (err: any) {
console.warn("[MTProto Server] Failing gracefully getting dialogs:", err.message);
return res.json({ success: true, conversations: [], error: err.message });
}
});
// 2. Get Live Messages for Peer
app.post("/api/telegram/get-messages", async (req, res) => {
const { sessionString, peerId, limit = 50 } = req.body;
if (!sessionString || !peerId) {
return res.status(400).json({ error: "Session string and peerId are required" });
}
// Gracefully skip calling MTProto if it's a local/mock peer
if (isMockPeer(peerId)) {
console.log(`[MTProto Server] Bypassing get-messages API call for mock peer target: ${peerId}`);
return res.json({ success: true, messages: [] });
}
try {
const client = await getTelegramClient(sessionString);
const cleanPeer = prepareTelegramPeer(peerId);
const messages = await client.getMessages(cleanPeer, { limit });
const formatted = messages.map((m: any) => {
const actualSenderId = m.senderId?.toString() || m.fromId?.toString() || "";
const senderId = m.out ? "me" : actualSenderId;
const firstName = m.sender?.firstName || "";
const lastName = m.sender?.lastName || "";
const displayName = (firstName + " " + lastName).trim() || m.sender?.username || "Telegram User";
let mediaUrl = null;
let mediaType = null;
if (m.media) {
const mediaAny = m.media as any;
const className = mediaAny.className || mediaAny.constructor?.name;
if (className === "MessageMediaPhoto" || mediaAny.photo) {
mediaType = "image";
mediaUrl = `/api/telegram/media/${encodeURIComponent(peerId)}/${m.id}?session=${encodeURIComponent(sessionString)}`;
} else if (className === "MessageMediaDocument" || mediaAny.document) {
const mime = mediaAny.document?.mimeType || "";
if (mime.startsWith("image/")) {
mediaType = "image";
} else if (mime.startsWith("video/")) {
mediaType = "video";
} else if (mime.startsWith("audio/") || mime === "application/ogg") {
mediaType = mime.includes("voice") ? "voice" : "audio";
} else {
mediaType = "file";
}
mediaUrl = `/api/telegram/media/${encodeURIComponent(peerId)}/${m.id}?session=${encodeURIComponent(sessionString)}`;
} else if (className === "MessageMediaGeo" || className === "MessageMediaGeoLive" || mediaAny.geo) {
mediaType = "location";
}
}
let replyToMsgId = null;
if (m.replyTo) {
const r = m.replyTo as any;
replyToMsgId = r.replyToMsgId || r.replyToHeader?.replyToMsgId;
} else if ((m as any).replyToHeader) {
replyToMsgId = (m as any).replyToHeader.replyToMsgId;
}
return {
id: m.id?.toString() || `msg_${Date.now()}_${Math.random()}`,
text: m.message || "",
created_at: new Date(m.date * 1000).toISOString(),
sender_id: senderId,
sender_name: displayName,
senderName: displayName,
avatar: m.sender?.photo ? `/api/telegram/avatar/${senderId}?session=${encodeURIComponent(sessionString)}` : `https://images.unsplash.com/photo-1542751371-adc38448a05e?w=50`,
media_url: mediaUrl,
media_type: mediaType,
reply_to: replyToMsgId ? replyToMsgId.toString() : null
};
});
await client.disconnect();
return res.json({ success: true, messages: formatted });
} catch (err: any) {
console.warn(`[MTProto Server] Bypassing get-messages failure for peer ${peerId}:`, err.message);
return res.json({ success: true, messages: [], error: err.message });
}
});
// 3. Send Live Message
app.post("/api/telegram/send-message", async (req, res) => {
const { sessionString, peerId, message, mediaUrl, mediaType, replyToMsgId } = req.body;
if (!sessionString || !peerId || (!message && !mediaUrl)) {
return res.status(400).json({ error: "Session string, peerId and either message or mediaUrl are required" });
}
if (isMockPeer(peerId)) {
console.log(`[MTProto Server] Intercepting mock peer target send-message call for: ${peerId}`);
return res.json({
success: true,
message: {
id: `mock_msg_${Date.now()}`,
text: message || "",
created_at: new Date().toISOString(),
sender_id: "me",
sender_name: "Me",
media_url: mediaUrl || null,
media_type: mediaType || null,
reply_to: replyToMsgId || null,
}
});
}
try {
const client = await getTelegramClient(sessionString);
const cleanPeer = prepareTelegramPeer(peerId);
let sent;
const parsedReplyTo = replyToMsgId ? parseInt(replyToMsgId) : undefined;
if (mediaUrl) {
let fileToUpload: any = mediaUrl;
if (mediaUrl.startsWith('http')) {
try {
const response = await axios.get(mediaUrl, { responseType: 'arraybuffer' });
fileToUpload = Buffer.from(response.data);
// Attach dummy name with the correct extension so GramJS is happy
const ext = mediaType === 'image' ? 'jpg' : mediaType === 'video' ? 'mp4' : mediaType === 'voice' ? 'ogg' : 'bin';
(fileToUpload as any).name = `file.${ext}`;
} catch (err) {
console.error('[MTProto] Failed to pre-fetch media URL buffer:', err);
}
}
sent = await client.sendFile(cleanPeer, {
file: fileToUpload,
caption: message || "",
replyTo: parsedReplyTo,
});
} else {
sent = await client.sendMessage(cleanPeer, {
message,
replyTo: parsedReplyTo,
});
}
const msgObj = Array.isArray(sent) ? sent[0] : sent;
const formatted = {
id: msgObj?.id?.toString() || `msg_${Date.now()}`,
text: msgObj?.message || message || "",
created_at: msgObj?.date ? new Date(msgObj.date * 1000).toISOString() : new Date().toISOString(),
sender_id: "me",
sender_name: "Me",
media_url: mediaUrl || null,
media_type: mediaType || null,
reply_to: replyToMsgId || null,
};
await client.disconnect();
return res.json({ success: true, message: formatted });
} catch (err: any) {
console.warn(`[MTProto Server] Bypassing send-message failure for peer ${peerId}:`, err.message);
return res.json({
success: true,
message: {
id: `failed_fallback_msg_${Date.now()}`,
text: message || "",
created_at: new Date().toISOString(),
sender_id: "me",
sender_name: "Me",
media_url: mediaUrl || null,
media_type: mediaType || null,
reply_to: replyToMsgId || null,
deliveryFailed: true,
},
error: err.message
});
}
});
// 4. Delete Live Message
app.post("/api/telegram/delete-message", async (req, res) => {
const { sessionString, peerId, messageId } = req.body;
if (!sessionString || !peerId || !messageId) {
return res.status(400).json({ error: "Session string, peerId and messageId are required" });
}
if (isMockPeer(peerId)) {
return res.json({ success: true });
}
try {
const client = await getTelegramClient(sessionString);
const cleanPeer = prepareTelegramPeer(peerId);
const msgIdNum = Number(messageId);
await client.deleteMessages(cleanPeer, [msgIdNum], { revoke: true });
await client.disconnect();
return res.json({ success: true });
} catch (err: any) {
console.warn(`[MTProto Server] Delete message exception bypassed for peer ${peerId}:`, err.message);
return res.json({ success: true, error: err.message });
}
});
// 5. Edit Live Message
app.post("/api/telegram/edit-message", async (req, res) => {
const { sessionString, peerId, messageId, text } = req.body;
if (!sessionString || !peerId || !messageId || !text) {
return res.status(400).json({ error: "sessionString, peerId, messageId, and text are required" });
}
if (isMockPeer(peerId)) {
return res.json({ success: true });
}
try {
const client = await getTelegramClient(sessionString);
const cleanPeer = prepareTelegramPeer(peerId);
const msgIdNum = Number(messageId);
await client.editMessage(cleanPeer, { message: msgIdNum, text });
await client.disconnect();
return res.json({ success: true });
} catch (err: any) {
console.warn(`[MTProto Server] Edit message exception bypassed for peer ${peerId}:`, err.message);
return res.json({ success: true, error: err.message });
}
});
// 6. Global Search for Users
app.post("/api/telegram/search-global", async (req, res) => {
const { sessionString, query } = req.body;
if (!sessionString || !query) {
return res.status(400).json({ error: "Session string and query are required" });
}
try {
const client = await getTelegramClient(sessionString);
const result = await client.invoke(
new Api.contacts.Search({
q: query,
limit: 20
})
);
const users = (result.users || []).map((u: any) => {
const id = u.id?.toString() || "";
const name = `${u.firstName || ""} ${u.lastName || ""}`.trim() || u.username || "Telegram User";
return {
id,
email: `${u.username || id}@indogram.org`,
username: u.username || "",
full_name: name,
bio: u.about || "Telegram User",
photo_url: `https://images.unsplash.com/photo-1542751371-adc38448a05e?w=150`,
status: u.status?._ === 'userStatusOnline' ? 'online' : 'offline',
is_online: u.status?._ === 'userStatusOnline'
};
});
await client.disconnect();
return res.json({ success: true, users });
} catch (err: any) {
console.error("[MTProto Server] Error searching global users:", err);
return res.status(500).json({ success: false, error: err.message });
}
});
// 7. Get Live Call Logs from Telegram
app.post("/api/telegram/get-calls", async (req, res) => {
const { sessionString, limit = 50 } = req.body;
if (!sessionString) {
return res.status(400).json({ error: "Session string is required" });
}
try {
const client = await getTelegramClient(sessionString);
const result: any = await client.invoke(
new Api.messages.Search({
peer: new Api.InputPeerEmpty(),
q: "",
filter: new Api.InputMessagesFilterPhoneCalls({}),
minDate: 0,
maxDate: 0,
offsetId: 0,
addOffset: 0,
limit: limit,
maxId: 0,
minId: 0,
hash: BigInt(0) as any,
})
);
const callList: any[] = [];
if (result && result.messages) {
const usersMap = new Map<string, any>();
if (result.users && Array.isArray(result.users)) {
result.users.forEach((u: any) => {
usersMap.set(u.id?.toString(), u);
});
}
result.messages.forEach((m: any) => {
// Only care about messages with call actions
let isCall = false;
if (m.action && m.action.className && m.action.className.includes("PhoneCall")) {
isCall = true;
} else {
const actName = m.action?.constructor?.name || "";
if (actName.includes("PhoneCall") || actName.includes("Phone")) {
isCall = true;
}
}
if (!isCall) return;
const isOutgoing = m.out || false;
// Find other participant's user ID
let otherUserId = "";
if (m.peerId && m.peerId.userId) {
otherUserId = m.peerId.userId.toString();
} else if (m.fromId && m.fromId.userId) {
otherUserId = m.fromId.userId.toString();
} else if (m.senderId) {
otherUserId = m.senderId.toString();
}
if (!otherUserId) return;
const userObj = usersMap.get(otherUserId);
const firstName = userObj?.firstName || "";
const lastName = userObj?.lastName || "";
const displayName = (firstName + " " + lastName).trim() || userObj?.username || "Telegram User";
const avatar = userObj?.photo ? `/api/telegram/avatar/${otherUserId}?session=${encodeURIComponent(sessionString)}` : `https://images.unsplash.com/photo-1542751371-adc38448a05e?w=50`;
const isVideo = m.action?.video || false;
const isMissed = m.action?.reason?.className?.toLowerCase().includes("missed") || false;
callList.push({
id: m.id?.toString() || `call_${Date.now()}_${Math.random()}`,
otherUserId,
user: displayName,
avatar,
type: isVideo ? 'video' : 'voice',
isIncoming: !isOutgoing,
isMissed,
time: m.date ? new Date(m.date * 1000).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', hour12: true }) : new Date().toLocaleString()
});
});
}
await client.disconnect();
return res.json({ success: true, callList });
} catch (err: any) {
console.warn("[MTProto Server] get-calls fallback warning:", err.message);
// Return empty array on failure/unsupported instead of crashing
return res.json({ success: true, callList: [] });
}
});
// LiveKit Token generation endpoint
app.post("/api/livekit-token", async (req, res) => {
try {
const { roomName, participantIdentity } = req.body;
if (!roomName || !participantIdentity) {
return res.status(400).json({ error: "Missing roomName or participantIdentity parameters" });
}
const apiKey = process.env.LIVEKIT_API_KEY;
const apiSecret = process.env.LIVEKIT_API_SECRET;
if (!apiKey || !apiSecret) {
console.warn("FCM Server: LIVEKIT_API_KEY or LIVEKIT_API_SECRET is missing. Proceeding with standard sandbox mock tokens.");
return res.json({
success: false,
error: "LiveKit server credentials are not configured. Please define LIVEKIT_API_KEY and LIVEKIT_API_SECRET in settings.",
token: "mock-livekit-token-sandbox"
});
}
const at = new AccessToken(apiKey, apiSecret, {
identity: participantIdentity,
});
at.addGrant({
roomJoin: true,
room: roomName,
canPublish: true,
canSubscribe: true,
});
const token = await at.toJwt();
return res.json({ success: true, token });
} catch (error: any) {
console.error("LiveKit token generation exception:", error);
return res.status(500).json({ error: error.message || "Failed to generate LiveKit token" });
}
});
// Sitemap route for SEO
app.get("/sitemap.xml", (req, res) => {
res.setHeader("Content-Type", "application/xml");
res.send(`<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>https://indogram.gothwad.workers.dev/</loc><priority>1.0</priority><changefreq>daily</changefreq></url>
<url><loc>https://indogram.gothwad.workers.dev/tools</loc><priority>0.8</priority><changefreq>weekly</changefreq></url>
<url><loc>https://indogram.gothwad.workers.dev/chats</loc><priority>0.9</priority><changefreq>always</changefreq></url>
<url><loc>https://indogram.gothwad.workers.dev/reels</loc><priority>0.8</priority><changefreq>always</changefreq></url>
</urlset>`);
});
// Digital Asset Links for Android PWA/TWA verification
app.get("/.well-known/assetlinks.json", (req, res) => {
res.setHeader("Content-Type", "application/json");
const assetlinksPath = fs.existsSync(path.resolve(process.cwd(), "dist/.well-known/assetlinks.json"))
? path.resolve(process.cwd(), "dist/.well-known/assetlinks.json")
: path.resolve(process.cwd(), "public/.well-known/assetlinks.json");
if (fs.existsSync(assetlinksPath)) {
res.sendFile(assetlinksPath);
} else {
// Graceful fallback with standard placeholders matching the public file
res.json([
{
"relation": ["delegate_permission/common.handle_all_urls"],
"target": {
"namespace": "android_app",
"package_name": "com.gothwad.indogram",
"sha256_cert_fingerprints": [
"F1:A1:DA:3C:A9:74:9C:13:B9:92:EF:CD:AA:E1:92:BB:D4:57:3E:04:9E:FC:D7:E5:A9:DF:11:80:FF:E3:A3:AA"
]
}
}
]);
}
});
// Helper to remove invalid/expired FCM tokens from the user profile database
async function removeInvalidFcmToken(badTokenStr: string) {
const supabaseUrl = process.env.VITE_SUPABASE_URL;
const supabaseKey = process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.VITE_SUPABASE_ANON_KEY;
if (!supabaseUrl || !supabaseKey) {
console.warn("FCM Server Cleanup: Unable to initialize Supabase client for FCM token cleanup (missing credentials).");
return;
}
try {
const supabaseServer = createClient(supabaseUrl, supabaseKey);
// Find all users who have this token in their fcm_tokens array and remove it
const { data: users, error: fetchErr } = await supabaseServer
.from("users")
.select("id, fcm_tokens");
if (fetchErr || !users) {
console.warn("FCM Server Cleanup: Failed to fetch users for token pruning:", fetchErr);
return;
}
for (const u of users) {
if (Array.isArray(u.fcm_tokens) && u.fcm_tokens.includes(badTokenStr)) {
const filtered = u.fcm_tokens.filter((t: string) => t !== badTokenStr);
console.log(`FCM Server Cleanup: Removing stale/invalid FCM token from user ${u.id}`);
const { error: updateErr } = await supabaseServer
.from("users")
.update({ fcm_tokens: filtered })
.eq("id", u.id);
if (updateErr) {
console.warn(`FCM Server Cleanup: Failed to update user ${u.id} FCM tokens:`, updateErr);
}
}
}
} catch (err: any) {
console.warn("FCM Server Cleanup: Exception in removeInvalidFcmToken:", err.message);
}
}
// Send Notification Proxy using Firebase Cloud Messaging HTTP v1 API
app.post("/api/send-notification", async (req, res) => {
try {
if (!req.body) {
return res.status(400).json({ error: "Missing request body" });
}
const { tokens, title, body, data } = req.body;
if (!tokens || !Array.isArray(tokens) || tokens.length === 0) {
return res.status(400).json({ error: "Missing recipient registration tokens" });
}
// Ensure all tokens are valid non-empty strings
const validTokens = tokens.filter(t => typeof t === 'string' && t.trim().length > 0);
if (validTokens.length === 0) {
return res.status(400).json({ error: "No valid recipient registration tokens provided" });
}
const serviceAccountJson = process.env.FIREBASE_SERVICE_ACCOUNT;
if (!serviceAccountJson) {
console.warn("FCM Server: FIREBASE_SERVICE_ACCOUNT variable not set. Simulating push notification dispatch in terminal logs.");
console.log(`[PUSH NOTIFICATION SIMULATION]`);
console.log(`Title: ${title}`);
console.log(`Body: ${body}`);
console.log(`Tokens:`, validTokens);
return res.json({
success: true,
simulated: true,
message: "Push simulate successful. Configure FIREBASE_SERVICE_ACCOUNT in env to enable active Google FCM sending."
});
}
let credentials: any;
try {
credentials = JSON.parse(serviceAccountJson);
if (typeof credentials === 'string') {
credentials = JSON.parse(credentials);
}
} catch (parseErr: any) {
console.error("FCM Server: Failed to parse FIREBASE_SERVICE_ACCOUNT env value:", parseErr);
return res.status(500).json({ error: `FIREBASE_SERVICE_ACCOUNT JSON parse failure: ${parseErr.message}` });
}
const projectId = credentials?.project_id;
if (!projectId) {
throw new Error("project_id missing from FIREBASE_SERVICE_ACCOUNT credentials");
}
// Automatically heal literal '\n' sequences in the private key if stored as an escaped string
if (credentials.private_key && typeof credentials.private_key === 'string') {
credentials.private_key = credentials.private_key.replace(/\\n/g, '\n');
}
// Authenticate with Google APIs scope for Firebase Cloud Messaging
const auth = new GoogleAuth({
credentials,
scopes: ['https://www.googleapis.com/auth/firebase.messaging'],
});
const client = await auth.getClient();
const accessTokenObj = await client.getAccessToken();
const accessToken = accessTokenObj.token;
if (!accessToken) {
throw new Error("Failed to retrieve Google Access Token for FCM scope");
}
console.log(`FCM Server: Dispatching push alerts to ${validTokens.length} registration tokens.`);
const results = await Promise.all(
validTokens.map(async (token) => {
try {
const payload = {
message: {
token,
notification: { title, body },
data: {
click_action: data?.click_action || '/chats',
conversationId: data?.conversationId || '',
senderId: data?.senderId || '',
...(data || {})
}
}
};
const response = await axios.post(
`https://fcm.googleapis.com/v1/projects/${projectId}/messages:send`,
payload,
{
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
}
}
);
return { token, success: true, messageId: response.data?.name };
} catch (err: any) {
const safeTokenStr = (typeof token === 'string') ? token.substring(0, 10) : String(token);
console.error(`FCM Server: Failed to send to token: ${safeTokenStr}... Error:`, err.response?.data || err.message);
const isInvalidToken =
err.response?.status === 400 ||
err.response?.status === 404 ||
(err.response?.data?.error?.status === 'INVALID_ARGUMENT') ||
(err.response?.data?.error?.status === 'NOT_FOUND') ||
(err.response?.data?.error?.status === 'UNREGISTERED') ||
(err.response?.data?.error?.message && (
err.response.data.error.message.includes('not a valid FCM registration token') ||
err.response.data.error.message.includes('Requested entity was not found')
));
if (isInvalidToken) {
removeInvalidFcmToken(token).catch(e => {
console.error("FCM Token Cleanup trigger failed:", e);
});
}
return { token, success: false, error: err.response?.data || err.message };
}
})
);
const successCount = results.filter(r => r.success).length;
res.json({
success: true,
total: validTokens.length,
sentCount: successCount,
results
});
} catch (error: any) {
console.error("FCM Send Notification failed:", error);