-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmod_telegram.cpp
More file actions
3818 lines (3364 loc) · 147 KB
/
mod_telegram.cpp
File metadata and controls
3818 lines (3364 loc) · 147 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
/*
* FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application
* Copyright (C) 2005-2024, Anthony Minessale II <anthm@freeswitch.org>
*
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application
*
* The Initial Developer of the Original Code is
* Anthony Minessale II <anthm@freeswitch.org>
* Portions created by the Initial Developer are Copyright (C)
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Konstantin S. Vishnivetskii <konstantinvishnivetsky@gmail.com>
*
* mod_telegram.cpp -- Telegram Endpoint Module
*
* Bridges FreeSWITCH calls to/from Telegram voice calls via TDLib.
* Dial string format: telegram/<profile>/<user_id>
* Config file: autoload_configs/telegram.conf.xml
*/
#include <switch.h>
#include <td/telegram/Client.h>
#include <td/telegram/td_api.hpp>
#include <rtc_base/logging.h>
#include <tgcalls/Instance.h>
#include <tgcalls/InstanceImpl.h>
#include <tgcalls/v2/InstanceV2Impl.h>
#include <tgcalls/v2/InstanceV2ReferenceImpl.h>
#include <tgcalls/FakeAudioDeviceModule.h>
#include <atomic>
#include <mutex>
#include <memory>
#include <cinttypes>
#include <unordered_map>
#include <string>
#define DC_SERVER_TEST "149.154.167.40:443"
#define DC_SERVER_PROD "149.154.167.50:443"
/* Audio format shared by the FreeSWITCH codec and the tgcalls ADM. */
#define TG_AUDIO_RATE 48000
#define TG_FRAME_MS 20
#define TG_FRAME_SAMPLES (TG_AUDIO_RATE * TG_FRAME_MS / 1000) /* 960 */
#define TG_FRAME_BYTES (TG_FRAME_SAMPLES * 2) /* 1920 */
#define TG_ADM_SAMPLES (TG_AUDIO_RATE * 10 / 1000) /* 480, 10 ms ADM tick */
#define TG_ADM_BYTES (TG_ADM_SAMPLES * 2) /* 960 bytes */
#ifdef _WIN32
# include <windows.h>
# define TG_PATH_MAX MAX_PATH
#else
# include <limits.h>
# define TG_PATH_MAX PATH_MAX
#endif
/* Module entry points must have C linkage so FreeSWITCH can locate them via dlsym. */
SWITCH_BEGIN_EXTERN_C
SWITCH_MODULE_LOAD_FUNCTION(mod_telegram_load);
SWITCH_MODULE_SHUTDOWN_FUNCTION(mod_telegram_shutdown);
SWITCH_MODULE_RUNTIME_FUNCTION(mod_telegram_runtime);
SWITCH_MODULE_DEFINITION(mod_telegram, mod_telegram_load, mod_telegram_shutdown, mod_telegram_runtime);
SWITCH_END_EXTERN_C
static switch_endpoint_interface_t *telegram_endpoint_interface;
static switch_memory_pool_t *module_pool = NULL;
static int running = 1;
static td::ClientManager *telegram_client_manager = nullptr;
/* Monotonic counter for TDLib request IDs — 0 means fire-and-forget. */
static std::atomic<uint64_t> tg_next_request_id{1};
static uint64_t tg_new_request_id() { return tg_next_request_id.fetch_add(1); }
/* ── Logging hooks ──────────────────────────────────────────────────────────── */
static switch_log_level_t tg_tdlib_level(int v)
{
if (v <= 0) return SWITCH_LOG_CRIT;
if (v == 1) return SWITCH_LOG_ERROR;
if (v == 2) return SWITCH_LOG_WARNING;
if (v == 3) return SWITCH_LOG_INFO;
return SWITCH_LOG_DEBUG;
}
static switch_log_level_t tg_rtc_level(rtc::LoggingSeverity s)
{
switch (s) {
case rtc::LS_ERROR: return SWITCH_LOG_ERROR;
case rtc::LS_WARNING: return SWITCH_LOG_WARNING;
case rtc::LS_INFO: return SWITCH_LOG_INFO;
default: return SWITCH_LOG_DEBUG;
}
}
static void tdlib_log_callback(int verbosity_level, const char *message)
{
switch_log_printf(SWITCH_CHANNEL_LOG, tg_tdlib_level(verbosity_level), "[TDLib] %s", message);
}
class TelegramRtcLogSink : public rtc::LogSink {
public:
void OnLogMessage(const std::string &message) override {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "[tgcalls] %s", message.c_str());
}
void OnLogMessage(const std::string &message, rtc::LoggingSeverity severity) override {
switch_log_printf(SWITCH_CHANNEL_LOG, tg_rtc_level(severity), "[tgcalls] %s", message.c_str());
}
};
static TelegramRtcLogSink g_rtc_log_sink;
/* ── Channel flags ──────────────────────────────────────────────────────────── */
typedef enum {
TFLAG_IO = (1 << 0),
TFLAG_INBOUND = (1 << 1),
TFLAG_OUTBOUND = (1 << 2),
TFLAG_DTMF = (1 << 3),
TFLAG_VOICE = (1 << 4),
TFLAG_HANGUP = (1 << 5),
TFLAG_LINEAR = (1 << 6),
TFLAG_CODEC = (1 << 7),
TFLAG_BREAK = (1 << 8)
} TFLAGS;
/* ── Profile ────────────────────────────────────────────────────────────────── */
typedef enum {
TG_PROFILE_STATUS_DOWN,
TG_PROFILE_STATUS_CONNECTING,
TG_PROFILE_STATUS_UP,
TG_PROFILE_STATUS_ERROR
} tg_profile_status_t;
typedef struct {
switch_bool_t tg_profile_enabled;
char *tg_profile_name;
tg_profile_status_t tg_profile_status;
char *tg_profile_server;
char *tg_profile_api_id;
char *tg_profile_api_hash;
char *tg_profile_database_dir;
char *tg_profile_files_dir;
/* NULL = use TDLib's allow_p2p; "true"/"false" = override per-profile */
char *tg_profile_allow_p2p;
/* Optional: colon-separated list of allowed tgcalls versions, e.g. "2.7.7:5.0.0".
* NULL = all available versions allowed. Overridable per-call via telegram_versions. */
char *tg_profile_versions;
/* Optional: auto-submit phone number and 2FA password during authentication */
char *tg_profile_login;
char *tg_profile_password;
/* dest_proto passed to switch_core_chat_deliver for inbound text messages (default: "telegram") */
char *tg_inbound_dest_proto;
td::ClientManager::ClientId tg_client_id;
switch_hash_t *calls;
switch_mutex_t *calls_mutex;
char pending_outgoing_uuid[SWITCH_UUID_FORMATTED_LENGTH + 1];
} tg_profile_t;
typedef tg_profile_t *tg_profile_p;
static void tg_profile_set_default_dirs(tg_profile_t *profile)
{
char path[TG_PATH_MAX];
if (!profile->tg_profile_database_dir) {
snprintf(path, sizeof(path), "%s/telegram/%s",
SWITCH_GLOBAL_dirs.db_dir, profile->tg_profile_name);
profile->tg_profile_database_dir = strdup(path);
}
if (!profile->tg_profile_files_dir) {
snprintf(path, sizeof(path), "%s/telegram/%s/files",
SWITCH_GLOBAL_dirs.db_dir, profile->tg_profile_name);
profile->tg_profile_files_dir = strdup(path);
}
switch_dir_make_recursive(profile->tg_profile_database_dir, SWITCH_DEFAULT_DIR_PERMS, module_pool);
switch_dir_make_recursive(profile->tg_profile_files_dir, SWITCH_DEFAULT_DIR_PERMS, module_pool);
}
static void tg_profile_free(tg_profile_t *p)
{
if (!p) return;
if (p->calls) {
switch_hash_index_t *hi;
const void *key;
void *val;
for (hi = switch_core_hash_first(p->calls); hi; hi = switch_core_hash_next(&hi)) {
switch_core_hash_this(hi, &key, NULL, &val);
free(val);
}
switch_core_hash_destroy(&p->calls);
}
switch_safe_free(p->tg_profile_name);
switch_safe_free(p->tg_profile_server);
switch_safe_free(p->tg_profile_api_id);
switch_safe_free(p->tg_profile_api_hash);
switch_safe_free(p->tg_profile_database_dir);
switch_safe_free(p->tg_profile_files_dir);
switch_safe_free(p->tg_profile_allow_p2p);
switch_safe_free(p->tg_profile_versions);
switch_safe_free(p->tg_profile_login);
switch_safe_free(p->tg_profile_password);
switch_safe_free(p->tg_inbound_dest_proto);
free(p);
}
/* ── Globals ────────────────────────────────────────────────────────────────── */
static struct {
int debug;
char *server;
char *dialplan;
char *context;
char *destination;
unsigned int flags;
int calls;
switch_mutex_t *mutex;
switch_hash_t *profiles;
switch_mutex_t *profiles_mutex;
} globals;
/* ── Pending file downloads ─────────────────────────────────────────────────── */
struct tg_pending_download {
char profile_name[64];
int64_t chat_id;
int64_t from_user_id;
int64_t msg_id;
int32_t file_id;
char file_type[32]; /* "document" "photo" "audio" "video" "voice" "video_note" */
char file_name[512]; /* original filename for documents */
char caption[1024]; /* caption text */
char mime_type[128];
char audio_title[256];
char audio_performer[256];
int32_t duration; /* seconds */
int32_t width;
int32_t height;
};
static std::unordered_map<std::string, tg_pending_download> tg_pending_downloads;
static switch_mutex_t *tg_pending_downloads_mutex = nullptr;
static switch_core_db_t *tg_dl_db = nullptr;
static switch_mutex_t *tg_dl_db_mutex = nullptr;
/* ── Inline query flow tracker ───────────────────────────────────────────────── */
struct tg_inline_flow {
uint32_t tg_client_id;
int64_t chat_id;
std::string query;
enum { SEARCHING, QUERYING } phase;
};
static std::unordered_map<uint64_t, tg_inline_flow> tg_inline_flows;
static switch_mutex_t *tg_inline_flows_mutex = nullptr;
/* ── Profile lookup helpers ─────────────────────────────────────────────────── */
static tg_profile_t *tg_find_profile(const char *name)
{
tg_profile_t *p = NULL;
switch_mutex_lock(globals.profiles_mutex);
p = (tg_profile_t *)switch_core_hash_find(globals.profiles, name);
switch_mutex_unlock(globals.profiles_mutex);
return p;
}
static tg_profile_t *tg_find_profile_by_client_id(td::ClientManager::ClientId client_id)
{
tg_profile_t *found = NULL;
switch_hash_index_t *hi;
const void *key;
void *val;
switch_mutex_lock(globals.profiles_mutex);
for (hi = switch_core_hash_first(globals.profiles); hi; hi = switch_core_hash_next(&hi)) {
switch_core_hash_this(hi, &key, NULL, &val);
tg_profile_t *p = (tg_profile_t *)val;
if (p->tg_client_id == client_id) {
found = p;
switch_core_hash_next(&hi); /* free iterator */
break;
}
}
switch_mutex_unlock(globals.profiles_mutex);
return found;
}
/* ── Pending download DB helpers ────────────────────────────────────────────── */
/* Escape a string for use inside single-quoted SQL literals. */
static std::string tg_sql_str(const char *s)
{
if (!s) s = "";
std::string r = "'";
for (const char *p = s; *p; ++p) {
if (*p == '\'') r += "''";
else r += *p;
}
return r + "'";
}
static const char *TG_DL_CREATE_SQL =
"CREATE TABLE IF NOT EXISTS tg_pending_downloads ("
" map_key TEXT PRIMARY KEY,"
" profile_name TEXT NOT NULL DEFAULT '',"
" chat_id INTEGER NOT NULL DEFAULT 0,"
" from_user_id INTEGER NOT NULL DEFAULT 0,"
" msg_id INTEGER NOT NULL DEFAULT 0,"
" file_id INTEGER NOT NULL DEFAULT 0,"
" file_type TEXT NOT NULL DEFAULT '',"
" file_name TEXT NOT NULL DEFAULT '',"
" caption TEXT NOT NULL DEFAULT '',"
" mime_type TEXT NOT NULL DEFAULT '',"
" audio_title TEXT NOT NULL DEFAULT '',"
" audio_performer TEXT NOT NULL DEFAULT '',"
" duration INTEGER NOT NULL DEFAULT 0,"
" width INTEGER NOT NULL DEFAULT 0,"
" height INTEGER NOT NULL DEFAULT 0"
");";
static void tg_db_open(void)
{
char path[TG_PATH_MAX];
snprintf(path, sizeof(path), "%s%smod_telegram.db",
SWITCH_GLOBAL_dirs.db_dir, SWITCH_PATH_SEPARATOR);
if (switch_core_db_open(path, &tg_dl_db) != SWITCH_STATUS_SUCCESS) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,
"Telegram: failed to open download DB at %s\n", path);
tg_dl_db = nullptr;
return;
}
char *err = nullptr;
switch_core_db_exec(tg_dl_db, TG_DL_CREATE_SQL, nullptr, nullptr, &err);
if (err) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,
"Telegram: DB create table error: %s\n", err);
switch_core_db_free(err);
}
}
static void tg_db_close(void)
{
if (tg_dl_db) {
switch_core_db_close(tg_dl_db);
tg_dl_db = nullptr;
}
}
static void tg_db_insert(const char *key, const tg_pending_download &pd)
{
if (!tg_dl_db) return;
char sql[4096];
snprintf(sql, sizeof(sql),
"INSERT OR REPLACE INTO tg_pending_downloads VALUES ("
"%s, %s, %" PRId64 ", %" PRId64 ", %" PRId64 ", %d, "
"%s, %s, %s, %s, %s, %s, %d, %d, %d);",
tg_sql_str(key).c_str(),
tg_sql_str(pd.profile_name).c_str(),
pd.chat_id, pd.from_user_id, pd.msg_id, pd.file_id,
tg_sql_str(pd.file_type).c_str(),
tg_sql_str(pd.file_name).c_str(),
tg_sql_str(pd.caption).c_str(),
tg_sql_str(pd.mime_type).c_str(),
tg_sql_str(pd.audio_title).c_str(),
tg_sql_str(pd.audio_performer).c_str(),
pd.duration, pd.width, pd.height);
char *err = nullptr;
switch_mutex_lock(tg_dl_db_mutex);
switch_core_db_exec(tg_dl_db, sql, nullptr, nullptr, &err);
switch_mutex_unlock(tg_dl_db_mutex);
if (err) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,
"Telegram: DB insert error: %s\n", err);
switch_core_db_free(err);
}
}
static void tg_db_delete(const char *key)
{
if (!tg_dl_db) return;
char sql[256];
snprintf(sql, sizeof(sql),
"DELETE FROM tg_pending_downloads WHERE map_key=%s;",
tg_sql_str(key).c_str());
char *err = nullptr;
switch_mutex_lock(tg_dl_db_mutex);
switch_core_db_exec(tg_dl_db, sql, nullptr, nullptr, &err);
switch_mutex_unlock(tg_dl_db_mutex);
if (err) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,
"Telegram: DB delete error: %s\n", err);
switch_core_db_free(err);
}
}
/* Callback for SELECT during startup recovery — populates in-memory map only. */
static int tg_db_load_row(void *unused, int argc, char **argv, char **col_names)
{
if (argc < 15 || !argv[0] || !argv[0][0]) return 0;
tg_pending_download pd = {};
#define SCOL(dst, idx) if (argv[idx]) strncpy(dst, argv[idx], sizeof(dst) - 1)
#define ICOL(dst, idx) if (argv[idx]) dst = (decltype(dst))atoll(argv[idx])
SCOL(pd.profile_name, 1);
ICOL(pd.chat_id, 2);
ICOL(pd.from_user_id, 3);
ICOL(pd.msg_id, 4);
ICOL(pd.file_id, 5);
SCOL(pd.file_type, 6);
SCOL(pd.file_name, 7);
SCOL(pd.caption, 8);
SCOL(pd.mime_type, 9);
SCOL(pd.audio_title, 10);
SCOL(pd.audio_performer,11);
ICOL(pd.duration, 12);
ICOL(pd.width, 13);
ICOL(pd.height, 14);
#undef SCOL
#undef ICOL
switch_mutex_lock(tg_pending_downloads_mutex);
tg_pending_downloads[argv[0]] = pd;
switch_mutex_unlock(tg_pending_downloads_mutex);
return 0;
}
/* Load persisted rows into map and re-issue downloadFile for each profile's entries. */
static void tg_db_recover_downloads(void)
{
if (!tg_dl_db) return;
/* Phase 1: populate in-memory map from DB. */
char *err = nullptr;
switch_mutex_lock(tg_dl_db_mutex);
switch_core_db_exec(tg_dl_db,
"SELECT map_key,profile_name,chat_id,from_user_id,msg_id,file_id,"
"file_type,file_name,caption,mime_type,audio_title,audio_performer,"
"duration,width,height FROM tg_pending_downloads;",
tg_db_load_row, nullptr, &err);
switch_mutex_unlock(tg_dl_db_mutex);
if (err) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR,
"Telegram: DB load error: %s\n", err);
switch_core_db_free(err);
return;
}
/* Phase 2: re-issue downloadFile for each entry whose profile is up. */
switch_mutex_lock(tg_pending_downloads_mutex);
for (auto &kv : tg_pending_downloads) {
tg_pending_download &pd = kv.second;
switch_mutex_lock(globals.profiles_mutex);
tg_profile_t *profile = (tg_profile_t *)switch_core_hash_find(
globals.profiles, pd.profile_name);
switch_mutex_unlock(globals.profiles_mutex);
if (!profile || !profile->tg_client_id) continue;
auto req = td::td_api::make_object<td::td_api::downloadFile>();
req->file_id_ = pd.file_id;
req->priority_ = 1;
req->offset_ = 0;
req->limit_ = 0;
req->synchronous_ = false;
telegram_client_manager->send(profile->tg_client_id, tg_new_request_id(), std::move(req));
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE,
"Telegram [%s]: recovery re-issued downloadFile for file_id=%d type=%s\n",
pd.profile_name, pd.file_id, pd.file_type);
}
switch_mutex_unlock(tg_pending_downloads_mutex);
}
/* ── TDLib auth state machine ───────────────────────────────────────────────── */
static void tg_profile_send_parameters(tg_profile_t *profile)
{
auto params = td::td_api::make_object<td::td_api::setTdlibParameters>();
params->use_test_dc_ = (strcmp(profile->tg_profile_server, DC_SERVER_PROD) != 0);
params->database_directory_ = profile->tg_profile_database_dir;
params->files_directory_ = profile->tg_profile_files_dir;
params->use_file_database_ = true;
params->use_chat_info_database_ = true;
params->use_message_database_ = true;
params->use_secret_chats_ = false;
params->api_id_ = atoi(profile->tg_profile_api_id);
params->api_hash_ = profile->tg_profile_api_hash;
params->system_language_code_ = "en";
params->device_model_ = "FreeSWITCH";
params->application_version_ = "1.0";
telegram_client_manager->send(profile->tg_client_id, tg_new_request_id(), std::move(params));
}
static void tg_handle_auth_state(tg_profile_t *profile, td::td_api::AuthorizationState &state)
{
switch (state.get_id()) {
case td::td_api::authorizationStateWaitTdlibParameters::ID:
profile->tg_profile_status = TG_PROFILE_STATUS_CONNECTING;
tg_profile_send_parameters(profile);
break;
case td::td_api::authorizationStateWaitPhoneNumber::ID:
if (!zstr(profile->tg_profile_login)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE,
"Telegram [%s]: auto-submitting phone number from profile config\n",
profile->tg_profile_name);
telegram_client_manager->send(profile->tg_client_id, tg_new_request_id(),
td::td_api::make_object<td::td_api::setAuthenticationPhoneNumber>(
profile->tg_profile_login, nullptr));
} else {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE,
"Telegram [%s]: waiting for phone number — "
"run: telegram_login %s <phone>\n",
profile->tg_profile_name, profile->tg_profile_name);
}
break;
case td::td_api::authorizationStateWaitCode::ID:
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE,
"Telegram [%s]: waiting for auth code — "
"run: telegram_code %s <code>\n",
profile->tg_profile_name, profile->tg_profile_name);
break;
case td::td_api::authorizationStateWaitPassword::ID:
if (!zstr(profile->tg_profile_password)) {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE,
"Telegram [%s]: auto-submitting 2FA password from profile config\n",
profile->tg_profile_name);
telegram_client_manager->send(profile->tg_client_id, tg_new_request_id(),
td::td_api::make_object<td::td_api::checkAuthenticationPassword>(
profile->tg_profile_password));
} else {
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE,
"Telegram [%s]: waiting for 2FA password — "
"run: telegram_password %s <password>\n",
profile->tg_profile_name, profile->tg_profile_name);
}
break;
case td::td_api::authorizationStateReady::ID:
profile->tg_profile_status = TG_PROFILE_STATUS_UP;
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE,
"Telegram [%s]: connected and ready\n", profile->tg_profile_name);
break;
case td::td_api::authorizationStateLoggingOut::ID:
profile->tg_profile_status = TG_PROFILE_STATUS_CONNECTING;
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE,
"Telegram [%s]: logging out\n", profile->tg_profile_name);
break;
case td::td_api::authorizationStateClosing::ID:
profile->tg_profile_status = TG_PROFILE_STATUS_DOWN;
break;
case td::td_api::authorizationStateClosed::ID:
profile->tg_profile_status = TG_PROFILE_STATUS_DOWN;
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_NOTICE,
"Telegram [%s]: closed\n", profile->tg_profile_name);
break;
default:
break;
}
}
/* ── Call media types ───────────────────────────────────────────────────────── */
struct tg_call_entry {
char session_uuid[SWITCH_UUID_FORMATTED_LENGTH + 1];
};
/* Receives decoded Telegram audio and writes it into a ring buffer. */
class TelegramRenderer : public tgcalls::FakeAudioDeviceModule::Renderer {
public:
switch_buffer_t *playout_buf = nullptr;
std::mutex playout_mtx;
bool Render(const tgcalls::AudioFrame &frame) override {
std::lock_guard<std::mutex> lk(playout_mtx);
if (!playout_buf) return true;
{
static std::atomic<uint32_t> render_count{0};
uint32_t cnt = ++render_count;
if (cnt % 500 == 1) {
int16_t maxval = 0;
size_t total = frame.num_samples * frame.num_channels;
for (size_t i = 0; i < total; i++) {
int16_t v = frame.audio_samples[i];
if (v < 0) v = -v;
if (v > maxval) maxval = v;
}
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG,
"tgcalls Render: call#%u ch=%zu samples=%zu max_sample=%d\n",
cnt, frame.num_channels, frame.num_samples, (int)maxval);
}
}
if (frame.num_channels == 1) {
switch_buffer_write(playout_buf, frame.audio_samples,
frame.num_samples * sizeof(int16_t));
} else {
/* Downmix to mono */
std::vector<int16_t> mono(frame.num_samples);
for (size_t i = 0; i < frame.num_samples; i++) {
int32_t sum = 0;
for (size_t c = 0; c < frame.num_channels; c++)
sum += frame.audio_samples[i * frame.num_channels + c];
mono[i] = (int16_t)(sum / (int32_t)frame.num_channels);
}
switch_buffer_write(playout_buf, mono.data(),
frame.num_samples * sizeof(int16_t));
}
return true;
}
};
/* Provides ADM audio for WebRTC-based instances (e.g. InstanceV2ReferenceImpl).
* capture_buf is fed by channel_write_frame; Record() drains it 10ms at a time.
* InstanceImpl-based instances ignore the ADM and use addExternalAudioSamples instead. */
class TelegramRecorder : public tgcalls::FakeAudioDeviceModule::Recorder {
public:
switch_buffer_t *capture_buf = nullptr;
std::mutex capture_mtx;
int16_t pcm_buf[TG_ADM_SAMPLES] = {};
tgcalls::AudioFrame Record() override {
std::lock_guard<std::mutex> lk(capture_mtx);
if (capture_buf && switch_buffer_inuse(capture_buf) >= TG_ADM_BYTES) {
switch_buffer_read(capture_buf, pcm_buf, TG_ADM_BYTES);
} else {
memset(pcm_buf, 0, TG_ADM_BYTES);
}
return {pcm_buf, TG_ADM_SAMPLES, sizeof(int16_t), 1, TG_AUDIO_RATE, 0, 0};
}
};
struct TelegramCallMedia {
std::unique_ptr<tgcalls::Instance> instance;
std::shared_ptr<TelegramRenderer> renderer;
std::shared_ptr<TelegramRecorder> recorder;
switch_buffer_t *playout_buf = nullptr;
switch_buffer_t *capture_buf = nullptr;
std::atomic<bool> stopping{false};
};
/* ── Private channel object ─────────────────────────────────────────────────── */
struct private_object {
unsigned int flags;
switch_codec_t read_codec;
switch_codec_t write_codec;
switch_frame_t read_frame;
unsigned char databuf[SWITCH_RECOMMENDED_BUFFER_SIZE];
switch_core_session_t *session;
switch_caller_profile_t *caller_profile;
switch_mutex_t *mutex;
switch_mutex_t *flag_mutex;
char *chat_id;
int32_t tg_call_id;
TelegramCallMedia *call_media;
char tg_profile_name[64];
};
typedef struct private_object private_t;
SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_dialplan, globals.dialplan);
SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_context, globals.context);
SWITCH_DECLARE_GLOBAL_STRING_FUNC(set_global_server, globals.server);
/* ── Forward declarations ───────────────────────────────────────────────────── */
static td::td_api::object_ptr<td::td_api::callProtocol> tg_make_protocol();
static switch_status_t channel_on_init(switch_core_session_t *session);
static switch_status_t channel_on_hangup(switch_core_session_t *session);
static switch_status_t channel_on_destroy(switch_core_session_t *session);
static switch_status_t channel_on_routing(switch_core_session_t *session);
static switch_status_t channel_on_execute(switch_core_session_t *session);
static switch_status_t channel_on_exchange_media(switch_core_session_t *session);
static switch_status_t channel_on_soft_execute(switch_core_session_t *session);
static switch_call_cause_t channel_outgoing_channel(switch_core_session_t *session,
switch_event_t *var_event,
switch_caller_profile_t *outbound_profile,
switch_core_session_t **new_session,
switch_memory_pool_t **pool,
switch_originate_flag_t flags,
switch_call_cause_t *cancel_cause);
static switch_status_t channel_read_frame(switch_core_session_t *session, switch_frame_t **frame,
switch_io_flag_t flags, int stream_id);
static switch_status_t channel_write_frame(switch_core_session_t *session, switch_frame_t *frame,
switch_io_flag_t flags, int stream_id);
static switch_status_t channel_kill_channel(switch_core_session_t *session, int sig);
static void tech_init(private_t *tech_pvt, switch_core_session_t *session)
{
switch_memory_pool_t *pool = switch_core_session_get_pool(session);
tech_pvt->read_frame.data = tech_pvt->databuf;
tech_pvt->read_frame.buflen = sizeof(tech_pvt->databuf);
switch_mutex_init(&tech_pvt->mutex, SWITCH_MUTEX_NESTED, pool);
switch_mutex_init(&tech_pvt->flag_mutex, SWITCH_MUTEX_NESTED, pool);
switch_core_session_set_private(session, tech_pvt);
tech_pvt->session = session;
if (switch_core_codec_init(&tech_pvt->read_codec, "L16", NULL, NULL,
TG_AUDIO_RATE, TG_FRAME_MS, 1,
SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE,
NULL, pool) == SWITCH_STATUS_SUCCESS) {
switch_core_session_set_read_codec(session, &tech_pvt->read_codec);
}
if (switch_core_codec_init(&tech_pvt->write_codec, "L16", NULL, NULL,
TG_AUDIO_RATE, TG_FRAME_MS, 1,
SWITCH_CODEC_FLAG_ENCODE | SWITCH_CODEC_FLAG_DECODE,
NULL, pool) == SWITCH_STATUS_SUCCESS) {
switch_core_session_set_write_codec(session, &tech_pvt->write_codec);
}
tech_pvt->read_frame.rate = TG_AUDIO_RATE;
tech_pvt->read_frame.codec = &tech_pvt->read_codec;
}
/* ── Channel state handlers ─────────────────────────────────────────────────── */
static switch_status_t channel_on_init(switch_core_session_t *session)
{
switch_channel_t *channel = switch_core_session_get_channel(session);
private_t *tech_pvt = static_cast<private_t *>(switch_core_session_get_private(session));
switch_assert(channel != NULL);
switch_assert(tech_pvt != NULL);
switch_set_flag_locked(tech_pvt, TFLAG_IO);
switch_mutex_lock(globals.mutex);
globals.calls++;
switch_mutex_unlock(globals.mutex);
return SWITCH_STATUS_SUCCESS;
}
static switch_status_t channel_on_routing(switch_core_session_t *session)
{
switch_channel_t *channel = switch_core_session_get_channel(session);
private_t *tech_pvt = static_cast<private_t *>(switch_core_session_get_private(session));
switch_assert(channel != NULL);
switch_assert(tech_pvt != NULL);
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG,
"%s CHANNEL ROUTING\n", switch_channel_get_name(channel));
/* For outbound channels, block here until the Telegram call is answered
* (tg_start_media calls switch_channel_mark_answered when callStateReady fires).
* Without this wait, CS_EXECUTE starts immediately and the dialplan's media
* apps run before the call is established. */
if (switch_channel_direction(channel) == SWITCH_CALL_DIRECTION_OUTBOUND) {
while (switch_channel_up_nosig(channel) &&
!switch_channel_test_flag(channel, CF_ANSWERED) &&
!switch_channel_test_flag(channel, CF_EARLY_MEDIA)) {
switch_yield(100000);
}
}
return SWITCH_STATUS_SUCCESS;
}
static switch_status_t channel_on_execute(switch_core_session_t *session)
{
switch_channel_t *channel = switch_core_session_get_channel(session);
private_t *tech_pvt = static_cast<private_t *>(switch_core_session_get_private(session));
switch_assert(channel != NULL);
switch_assert(tech_pvt != NULL);
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG,
"%s CHANNEL EXECUTE\n", switch_channel_get_name(channel));
return SWITCH_STATUS_SUCCESS;
}
static switch_status_t channel_on_destroy(switch_core_session_t *session)
{
private_t *tech_pvt = static_cast<private_t *>(switch_core_session_get_private(session));
switch_assert(switch_core_session_get_channel(session) != NULL);
if (tech_pvt) {
if (switch_core_codec_ready(&tech_pvt->read_codec))
switch_core_codec_destroy(&tech_pvt->read_codec);
if (switch_core_codec_ready(&tech_pvt->write_codec))
switch_core_codec_destroy(&tech_pvt->write_codec);
}
return SWITCH_STATUS_SUCCESS;
}
static switch_status_t channel_on_hangup(switch_core_session_t *session)
{
switch_channel_t *channel = switch_core_session_get_channel(session);
private_t *tech_pvt = static_cast<private_t *>(switch_core_session_get_private(session));
switch_assert(channel != NULL);
switch_assert(tech_pvt != NULL);
switch_clear_flag_locked(tech_pvt, TFLAG_IO);
switch_clear_flag_locked(tech_pvt, TFLAG_VOICE);
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG,
"%s CHANNEL HANGUP\n", switch_channel_get_name(channel));
if (tech_pvt->tg_call_id && tech_pvt->tg_profile_name[0]) {
tg_profile_t *profile = tg_find_profile(tech_pvt->tg_profile_name);
if (profile) {
/* Remove from profile's calls hash */
char id_str[24];
snprintf(id_str, sizeof(id_str), "%d", tech_pvt->tg_call_id);
switch_mutex_lock(profile->calls_mutex);
tg_call_entry *entry = (tg_call_entry*)switch_core_hash_delete(
profile->calls, id_str);
switch_mutex_unlock(profile->calls_mutex);
free(entry);
/* Tell TDLib to drop the call */
if (profile->tg_client_id) {
auto discard = td::td_api::make_object<td::td_api::discardCall>();
discard->call_id_ = tech_pvt->tg_call_id;
discard->is_disconnected_ = false;
discard->invite_link_ = "";
discard->duration_ = 0;
discard->is_video_ = false;
discard->connection_id_ = 0;
telegram_client_manager->send(profile->tg_client_id,
tg_new_request_id(), std::move(discard));
}
}
}
/* Stop tgcalls media asynchronously */
if (tech_pvt->call_media) {
TelegramCallMedia *cm = tech_pvt->call_media;
tech_pvt->call_media = nullptr;
{
std::lock_guard<std::mutex> lk(cm->renderer->playout_mtx);
cm->renderer->playout_buf = nullptr;
}
{
std::lock_guard<std::mutex> lk(cm->recorder->capture_mtx);
cm->recorder->capture_buf = nullptr;
}
if (!cm->stopping.exchange(true)) {
tgcalls::Instance *raw = cm->instance.release();
raw->stop([raw, cm](tgcalls::FinalState) {
if (cm->playout_buf) switch_buffer_destroy(&cm->playout_buf);
if (cm->capture_buf) switch_buffer_destroy(&cm->capture_buf);
delete raw;
delete cm;
});
}
}
switch_mutex_lock(globals.mutex);
globals.calls--;
if (globals.calls < 0) globals.calls = 0;
switch_mutex_unlock(globals.mutex);
return SWITCH_STATUS_SUCCESS;
}
static switch_status_t channel_kill_channel(switch_core_session_t *session, int sig)
{
switch_channel_t *channel = switch_core_session_get_channel(session);
private_t *tech_pvt = static_cast<private_t *>(switch_core_session_get_private(session));
switch_assert(channel != NULL);
switch_assert(tech_pvt != NULL);
switch (sig) {
case SWITCH_SIG_KILL:
switch_clear_flag_locked(tech_pvt, TFLAG_IO);
switch_clear_flag_locked(tech_pvt, TFLAG_VOICE);
switch_channel_hangup(channel, SWITCH_CAUSE_NORMAL_CLEARING);
break;
case SWITCH_SIG_BREAK:
switch_set_flag_locked(tech_pvt, TFLAG_BREAK);
break;
default:
break;
}
return SWITCH_STATUS_SUCCESS;
}
static switch_status_t channel_on_exchange_media(switch_core_session_t *session)
{
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "CHANNEL LOOPBACK\n");
return SWITCH_STATUS_SUCCESS;
}
static switch_status_t channel_on_soft_execute(switch_core_session_t *session)
{
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "CHANNEL TRANSMIT\n");
return SWITCH_STATUS_SUCCESS;
}
static switch_status_t channel_send_dtmf(switch_core_session_t *session, const switch_dtmf_t *dtmf)
{
private_t *tech_pvt = static_cast<private_t *>(switch_core_session_get_private(session));
switch_assert(tech_pvt != NULL);
return SWITCH_STATUS_SUCCESS;
}
static switch_status_t channel_read_frame(switch_core_session_t *session, switch_frame_t **frame,
switch_io_flag_t flags, int stream_id)
{
switch_channel_t *channel = switch_core_session_get_channel(session);
private_t *tech_pvt = static_cast<private_t *>(switch_core_session_get_private(session));
switch_byte_t *data;
switch_assert(channel != NULL);
switch_assert(tech_pvt != NULL);
tech_pvt->read_frame.flags = SFF_NONE;
*frame = NULL;
/* Wait up to 30ms for a full frame from the tgcalls playout buffer */
for (int i = 0; i < 30 && switch_test_flag(tech_pvt, TFLAG_IO); i++) {
if (switch_test_flag(tech_pvt, TFLAG_BREAK)) {
switch_clear_flag(tech_pvt, TFLAG_BREAK);
goto cng;
}
if (tech_pvt->call_media) {
TelegramCallMedia *cm = tech_pvt->call_media;
std::lock_guard<std::mutex> lk(cm->renderer->playout_mtx);
if (cm->playout_buf && switch_buffer_inuse(cm->playout_buf) >= TG_FRAME_BYTES) {
switch_buffer_read(cm->playout_buf, tech_pvt->read_frame.data, TG_FRAME_BYTES);
tech_pvt->read_frame.datalen = TG_FRAME_BYTES;
tech_pvt->read_frame.samples = TG_FRAME_SAMPLES;
*frame = &tech_pvt->read_frame;
return SWITCH_STATUS_SUCCESS;
}
}
switch_yield(1000);
}
if (!switch_test_flag(tech_pvt, TFLAG_IO))
return SWITCH_STATUS_FALSE;
cng:
{
static std::atomic<uint32_t> cng_count{0};
uint32_t c = ++cng_count;
if (c % 50 == 1)
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG,
"channel_read_frame: returning CNG #%u (playout_buf empty)\n", c);
}
data = static_cast<switch_byte_t *>(tech_pvt->read_frame.data);
data[0] = 65;
data[1] = 0;
tech_pvt->read_frame.datalen = 2;
tech_pvt->read_frame.flags = SFF_CNG;
*frame = &tech_pvt->read_frame;
return SWITCH_STATUS_SUCCESS;
}
static switch_status_t channel_write_frame(switch_core_session_t *session, switch_frame_t *frame,
switch_io_flag_t flags, int stream_id)
{
switch_channel_t *channel = switch_core_session_get_channel(session);
private_t *tech_pvt = static_cast<private_t *>(switch_core_session_get_private(session));
switch_assert(channel != NULL);
switch_assert(tech_pvt != NULL);
if (!switch_test_flag(tech_pvt, TFLAG_IO))
return SWITCH_STATUS_FALSE;
if (frame->flags & SFF_CNG)
return SWITCH_STATUS_SUCCESS;
static std::atomic<uint32_t> wf_total{0}, wf_sent{0}, wf_dropped{0};
++wf_total;
if (tech_pvt->call_media && tech_pvt->call_media->instance
&& !tech_pvt->call_media->stopping && frame->datalen > 0) {
++wf_sent;
const uint8_t *p = static_cast<const uint8_t*>(frame->data);
/* Feed ADM recorder for WebRTC-based instances (e.g. InstanceV2ReferenceImpl).
* InstanceImpl ignores the ADM and uses addExternalAudioSamples below. */
{
auto &rec = tech_pvt->call_media->recorder;
std::lock_guard<std::mutex> lk(rec->capture_mtx);
if (rec->capture_buf)