-
-
Notifications
You must be signed in to change notification settings - Fork 85
/
telega-core.el
2166 lines (1888 loc) · 84.9 KB
/
telega-core.el
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
;;; telega-core.el --- Core functionality for telega -*- lexical-binding:t -*-
;; Copyright (C) 2018-2019 by Zajcev Evgeny.
;; Author: Zajcev Evgeny <[email protected]>
;; Created: Mon Apr 23 18:09:01 2018
;; Keywords:
;; telega is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; telega is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with telega. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; Variables, macroses, defsubst and runtime goodies for telega
;;; Code:
(require 'cl-lib)
(require 'subr-x)
(require 'ring)
(require 'color)
(require 'cursor-sensor)
(require 'telega-customize)
(declare-function telega-chat--info "telega-chat" (chat))
(declare-function telega-window-recenter "telega-util" (win &optional nlines from-point))
(declare-function telega-emoji-create-svg "telega-util" (emoji &optional c-height))
(declare-function telega-chars-xheight "telega-util" (n))
(declare-function telega-chars-xwidth "telega-util" (n))
(declare-function telega-em-width-ratio "telega-util")
(declare-function telega-em-height-ratio "telega-util")
(declare-function telega-chats-compare "telega-sort" (criteria chat1 chat2))
(defvar telega--lib-directory nil
"The directory from where this library was first loaded.")
(defun telega-etc-file (filename)
"Return absolute path to FILENAME from etc/ directory in telega.
Use FILENAME as is if resulting file does not exist."
(let ((abspath (expand-file-name (concat "etc/" filename)
telega--lib-directory)))
(if (file-exists-p abspath)
abspath
filename)))
(defconst telega-spoiler-translation-table
(let ((table (make-char-table 'translation-table)))
(set-char-table-range table t ?\█)
(aset table ?\s ?\s)
(aset table ?\n ?\n)
table)
"Translation table to hide for spoiler text.")
(defconst telega-chat-types
'(private secret basicgroup supergroup bot channel)
"All types of chats supported by telega.")
(defconst telega-msg-id-step 1048576 ; 2^20
"Message id difference between two consequent messages.")
(defconst telega-mute-for-ever 500000000)
(defconst telega-mute-for-intervals
;; 1h 4h 1d 7d forever
`(3600 14400 86400 604800 ,telega-mute-for-ever))
(defconst telega--slow-mode-delays '(0 10 30 60 300 900 3600)
"List of allowed slow mode delays.")
(defconst telega-chat--chat-media-permissions
'((:can_send_audios . "lng_rights_chat_music")
(:can_send_documents . "lng_rights_chat_files")
(:can_send_photos . "lng_rights_chat_photos")
(:can_send_videos . "lng_rights_chat_videos")
(:can_send_video_notes . "lng_rights_chat_video_messages")
(:can_send_voice_notes . "lng_rights_chat_voice_messages")))
(defconst telega-chat--chat-permissions
`((:can_send_basic_messages . "lng_rights_chat_send_text")
;; Media, "lng_rights_chat_send_media"
,@telega-chat--chat-media-permissions
(:can_send_polls . "lng_rights_chat_send_polls")
(:can_send_other_messages . "lng_rights_chat_send_stickers")
(:can_add_link_previews . "lng_rights_chat_send_links")
(:can_change_info . "lng_rights_group_info")
(:can_invite_users . "lng_rights_chat_add_members")
(:can_pin_messages . "lng_rights_group_pin")
(:can_create_topics . "lng_rights_group_add_topics")))
(defconst telega-chat--admin-permissions
'((:can_be_edited . "lng_rights_edit_admin")
(:can_manage_chat . nil) ;TODO
(:can_change_info . "lng_rights_group_info")
(:can_post_messages . "lng_rights_channel_post")
(:can_edit_messages . "lng_rights_channel_edit")
(:can_delete_messages . "lng_rights_group_delete")
(:can_invite_users . "lng_rights_group_invite_link")
(:can_restrict_members . "telega_rights_restrict_members")
(:can_pin_messages . "lng_rights_group_pin")
(:can_manage_topics . "lng_rights_group_topics")
(:can_promote_members . "telega_rights_promote_members")
(:can_manage_video_chats . "lng_rights_group_manage_calls")
(:can_post_stories . "lng_rights_channel_post_stories")
(:can_edit_stories . "lng_rights_channel_edit_stories")
(:can_delete_stories . "lng_rights_channel_delete_stories")
(:is_anonymous . "lng_rights_group_anonymous")))
(defconst telega-chat--admin-permissions-for-channels
'(:can_post_messages :can_edit_messages :can_post_stories :can_edit_stories
:can_delete_stories))
(defconst telega-notification-scope-types
'((private . "notificationSettingsScopePrivateChats")
(group . "notificationSettingsScopeGroupChats")
(channel . "notificationSettingsScopeChannelChats"))
"Map of lisp name of the scope to TDLib scope type name.")
(defconst telega-currency-symbols-alist
'(("EUR" . "€")
("USD" . "$")
("RUB" . "₽"))
"Alist of currency symbols.")
(defvar telega--column-offset 0
"Additional offset for the `telega-currency-column'.")
(defconst telega-symbol-nbsp "\u00a0"
"Non-breakable space.")
(defconst telega-emoji-animated-fullscreen-list
'("🎆" "🎉" "🎈" "👍" "💩" "❤" "👻" "👎" "🤮" "😂" "💸" "🎃" "🍆")
"List of animated emojis with fullscreen support.")
(defvar telega-emoji-reaction-list nil
"List of supported reactions, updated on `updateActiveEmojiReactions' event.")
(defvar telega-default-reaction-type nil
"Default reaction for the messages.
Updated on `updateDefaultReactionType' event.")
(defconst telega-translate-languages-alist
'(("Afrikaans" . "af") ("Albanian" . "sq") ("Amharic" . "am")
("Arabic" . "ar") ("Armenian" . "hy") ("Azerbaijani" . "az")
("Basque" . "eu") ("Belarusian" . "be") ("Bengali" . "bn")
("Bosnian" . "bs") ("Bulgarian" . "bg") ("Catalan" . "ca")
("Cebuano" . "ceb") ("Chinese" . "zh")
("Chinese Simplified" . "zh-CN") ("Chinese Traditional" . "zh-TW")
("Chichewa" . "ny")
("Corsican" . "co") ("Croatian" . "hr") ("Czech" . "cs")
("Danish" . "da") ("Dutch" . "nl") ("English" . "en")
("Esperanto" . "eo") ("Estonian" . "et") ("Filipino" . "tl")
("Finnish" . "fi") ("French" . "fr") ("Frisian" . "fy")
("Galician" . "gl") ("Georgian" . "ka") ("German" . "de")
("Greek" . "el") ("Gujarati" . "gu") ("Haitian Creole" . "ht")
("Hausa" . "ha") ("Hawaiian" . "haw") ("Hebrew" . "iw")
("Hindi" . "hi") ("Hmong" . "hmn") ("Hungarian" . "hu")
("Icelandic" . "is") ("Igbo" . "ig") ("Indonesian" . "id")
("Irish" . "ga") ("Italian" . "it") ("Japanese" . "ja")
("Kannada" . "kn") ("Kazakh" . "kk") ("Khmer" . "km")
("Korean" . "ko") ("Kurdish (Kurmanji)" . "ku") ("Kyrgyz" . "ky")
("Lao" . "lo") ("Latin" . "la") ("Latvian" . "lv")
("Lithuanian" . "lt") ("Luxembourgish" . "lb") ("Macedonian" . "mk")
("Malagasy" . "mg") ("Malay" . "ms") ("Malayalam" . "ml")
("Maltese" . "mt") ("Maori" . "mi") ("Marathi" . "mr")
("Mongolian" . "mn") ("Myanmar (Burmese)" . "my") ("Nepali" . "ne")
("Norwegian" . "no") ("Pashto" . "ps") ("Persian" . "fa")
("Polish" . "pl") ("Portuguese" . "pt") ("Punjabi" . "pa")
("Romanian" . "ro") ("Russian" . "ru") ("Samoan" . "sm")
("Scots Gaelic" . "gd") ("Serbian" . "sr") ("Sesotho" . "st")
("Shona" . "sn") ("Sindhi" . "sd") ("Sinhala" . "si")
("Slovak" . "sk") ("Slovenian" . "sl") ("Somali" . "so")
("Spanish" . "es") ("Sundanese" . "su") ("Swahili" . "sw")
("Swedish" . "sv") ("Tajik" . "tg") ("Tamil" . "ta")
("Telugu" . "te") ("Thai" . "th") ("Turkish" . "tr")
("Ukrainian" . "uk") ("Urdu" . "ur") ("Uzbek" . "uz")
("Vietnamese" . "vi") ("Welsh" . "cy") ("Xhosa" . "xh")
("Yiddish" . "yi") ("Yoruba" . "yo") ("Zulu" . "zu"))
"Language codes used for translations.")
;;; Runtime variables
(defvar telega-msg--current nil
"Bound to currenty inserting message.")
(defvar telega--chat nil
"Telega chat for the current buffer.
Used in some buffers to refer chat.")
(make-variable-buffer-local 'telega--chat)
(defvar telega--help-win-param nil
"Parameter for the `telega--help-win-redisplay-func'.
Used in help buffers to store some additional data.")
(make-variable-buffer-local 'telega--help-win-param)
(defvar telega--help-win-inserter nil
"Inserter function for the help win.
This function accepts exactly one argument - `telega--help-win-param'.")
(make-variable-buffer-local 'telega--help-win-inserter)
(defvar telega--help-win-dirty-p nil
"Non-nil if help win need redisplay.
Used for optimisations.")
(make-variable-buffer-local 'telega--help-win-dirty-p)
(defvar telega--help-win-tdlib-callbacks nil
"List of pending callbacks in the help window.")
(make-variable-buffer-local 'telega--help-win-tdlib-callbacks)
(defvar telega--me-id nil "User id of myself.")
(defvar telega--replies-id nil "Id of the \"Replies\" chat.")
(defvar telega--options nil "Options updated from telega-server.")
(defvar telega--auth-state nil
"Current Authorization state.")
(defvar telega--conn-state nil
"Current connection state.")
(defvar telega--status "Not Started" "Status of the connection to telegram.")
(defvar telega--status-aux
"Aux status used for long requests, such as fetching chats/searching/etc")
(defvar telega--chats nil "Hash table (id -> chat) for all chats.")
(defvar telega--chat-topics nil "Hash table (id -> topics list) for forums chats.")
(defvar telega--story-list-chat-count nil
"Plist with number of chats having active stories.
Props are `main' and `archive'.")
(defvar telega--story-stealth-mode nil)
(defvar telega--chat-active-stories nil
"Hash table (chat-id -> chatActiveStories) for chat's stories.")
(defvar telega--cached-messages nil
"Hash table ((chat-id . msg-id) -> msg) of cached messages.
Such as pinned, replies, etc.")
(defvar telega--cached-stories nil
"Hash table ((chat-id . story-id) -> story) of cached stories.")
(defvar telega--actions nil
"Hash table ((chat-id . msg-thread-id) -> alist-of-user-actions).")
(defun telega-chat--actions (chat &optional msg-thread-id)
"Return actions for the CHAT and optional MSG-THREAD-ID."
(gethash (cons (plist-get chat :id) (or msg-thread-id 0)) telega--actions))
(defvar telega--ordered-chats nil "Ordered list of all chats.")
(defvar telega--filtered-chats nil
"Chats filtered by currently active filters.
Used to calculate numbers displayed in custom filter buttons.")
(defvar telega-deleted-chats nil
"List of recently deleted chats.
Used for \"Recently Deleted Chats\" rootview.")
(defvar telega--blocked-user-ids-alist '((blockListMain . (0))
(blockListStories . (0)))
"Alist of blocked users.
car of the element is block list, one of `blockListMain' or
`blockListStories', cdr is a list of user ids in that block list.
Used to avoid fetching user's full-info to find out that user is blocked.
CAR of the user ids list is current offset for
`telega--getBlockedMessageSenders'.")
(defvar telega--dirty-chats nil
"List of chats that need to be updated with `telega-chat--update'.
Dirtiness types are stored in the `:telega-dirtiness' chat's property.")
(defvar telega--filters nil "List of active filters.")
(defvar telega--undo-filters nil "List of undo entries.")
(defvar telega--sort-criteria nil "Active sorting criteria list.")
(defvar telega--sort-inverted nil "Non-nil if sorting is inverted.")
(defvar telega--sort-reorder-dirtiness nil
"List of event types affecting chat order for Active sorting criteria.")
(defvar telega--info nil "Alist of (TYPE . INFO-TABLE).")
(defvar telega--full-info nil "Alist of (TYPE . FULL-INFO-TABLE).")
(defvar telega-full-info-offline-p t
"Non-nil to not request telega-server in case full info is not available.
Bind to nil to ensure full info is actualized.")
(defvar telega--top-chats nil
"Alist of (CATEGORY LAST-UPDATE-TIME ..)
CATEGORY is one of `Users', `Bots', `Groups', `Channels',
`InlineBots', `Calls'")
(defvar telega--last-buffer nil
"Used to track buffers switching.
So we can run the code when switching from chat buffer.")
(defvar telega--stickersets nil
"Alist of seen sticker sets.
ID -> sticker set.
Take into account that ID is the string.")
(defvar telega--stickersets-installed-ids nil
"List of ids for installed sticker sets.
Used by `telega-stickerset-installed-p'.")
(defvar telega--stickersets-installed nil
"List of `stickerSetInfo' for installed sticker sets.")
(defvar telega--stickersets-trending nil
"List of trending sticker sets info.")
(defvar telega--stickersets-trending-premium nil
"List of trending Premium sticker sets info.")
(defvar telega--stickersets-system nil
"List of system sticker sets, such as animated dices, animated emojis.")
(defvar telega--stickersets-custom-emojis nil
"List of custom emojis sticker sets info.")
(defvar telega--stickers-favorite nil
"List of favorite stickers.")
(defvar telega--stickers-recent nil
"List of recently used stickers.")
(defvar telega--stickers-recent-attached nil
"List of recently attached stickers.")
(defvar telega--animated-emojis nil
"List of all supported animated emojis.")
(defvar telega--animated-emojis-stickerset-id nil
"Id for sticker set with animated emojis.")
(defvar telega--custom-emoji-stickers nil
"Hash of custom_emoji_id -> sticker for the custom emojis.")
(defvar telega--animations-saved nil
"List of saved animations.")
(defvar telega--chat-themes nil
"List of chat themes.")
(defvar telega--dice-emojis nil
"List of supported emojis for random dice messages.")
(defvar telega--suggested-actions nil
"List of suggested actions to be taken.")
(defvar telega--group-calls nil "Hash table (id -> group-call).")
(defvar telega--favorite-messages-storage-message 'not-yet-fetched
"Message where favorite messages are stored.
Document message with the #telega_favorite_messages hashtag.")
(defvar telega--favorite-messages nil
"List of favorite messages.
Favorite message is a plist with at least `:chat_id', `:id' properties.
`:timestamp' and `:comment' properties are also supported.")
(defvar telega--live-location-messages nil
"List of messages with active live locations.")
(defvar telega--speech-recognition-trial nil
"The parameters of speech recognition without Telegram Premium.")
(defvar telega--close-birthday-users nil
"List of contact users with close birthdays.")
(defvar telega--owned-stars 0
"Number of owned Telegram Stars.")
;; Searching
(defvar telega-search-history nil
"List of recent search queries.")
(defvar telega--search-chats nil
"Result of last `telega--searchChats' or `telega--searchChatsOnServer'.")
(defvar telega--unread-message-count nil
"Plist with counts for unread/unmuted messages.
Props are `:unread_count' and `:unread_unmuted_count'")
(defvar telega--unread-chat-count nil
"Plist with counts for unread/unmuted chats.
Props are `:unread_count', `:unread_unmuted_count', `:marked_as_unread_count'
and `:marked_as_unread_unmuted_count'")
(defvar telega--chat-buffers-alist nil
"Alist of chats and corresponding chatbuf.")
(defun telega-chat-buffers ()
"Return list of all chatbufs."
(mapcar #'cdr telega--chat-buffers-alist))
(defun telega-chat-buffers-manage (&optional for-new-chatbuf)
"Keep number of chat buffers within `telega-chat-buffers-limit'.
If FOR-NEW-CHATBUF is specified, then do not kill this chatbuf
whatever conditions are."
;; NOTE: never kill newly created FOR-NEW-CHATBUF chat buffer
(let* ((chat-buffers (delq for-new-chatbuf (telega-chat-buffers)))
(nbuffers-to-kill (- (length chat-buffers) telega-chat-buffers-limit)))
(when (> nbuffers-to-kill 0)
(let* ((all-buffers (buffer-list))
(buffers (sort chat-buffers
(lambda (buf1 buf2)
(< (length (memq buf1 all-buffers))
(length (memq buf2 all-buffers)))))))
(while (and buffers (> nbuffers-to-kill 0))
;; NOTE: kill only invisible (not having a window) chat
;; buffers
(unless (get-buffer-window (car buffers) t)
(telega-debug "Killing least recent %S" (car buffers))
(cl-decf nbuffers-to-kill)
(kill-buffer (car buffers)))
(setq buffers (cdr buffers)))
))))
(defvar telega--files nil
"Files hash FILE-ID -> (list FILE UPDATE-CALBACKS..).")
(defvar telega--files-updates nil
"Hash of FILE-ID -> (list-of (UPDATE-CB CB-ARGS))
UPDATE-CB is callback to call when file updates.
UPDATE-CB is called with FILE and CB-ARGS as arguments.
UPDATE-CB should return non-nil to be removed after its being called.")
(defvar telega--proxy-pings nil
"Alist for the proxy pings.
In form (PROXY-ID . TIMESTAMP SECONDS)")
(defvar telega-voip--alist nil
"Alist of all calls currently in processing.
In form (ID . CALL)")
(defvar telega-voip--active-call nil
"Currently active call.
Active call is either outgoing call or accepted incoming call.
Only one call can be currently active.")
(defvar telega--scope-notification-alist (cons nil nil)
"Default notification settings for chats.
alist where key is one of:
\"notificationSettingsScopePrivateChats\",
\"notificationSettingsScopeGroupChats\",
\"notificationSettingsScopeChannelChats\".")
(defvar telega-tdlib--chat-folders nil
"List of chat folders received from TDLib.")
(defvar telega-tdlib--chat-folder-tags-p nil
"Non-nil if chat folder tags are enabled.
Updated with `updateChatFolders' event.")
(defvar telega-chat-folders nil
"This variable is bound to list of chat folders when formatting.")
(defvar telega-tdlib--chat-list nil
"Active tdlib chat list used for ordering.")
(defvar telega-tdlib--unix-time nil
"Plist holding remote/local unix times.
Used for adjustments for timing info received from Telegram.")
;; Minibuffer stuff used by chatbuf and stickers
(defvar telega-minibuffer--choices nil
"Bind to list of choices.
Each element in form: (NAME SSET-ID)")
(defvar telega-minibuffer--chat nil
"Bind to chat currently active.")
(defvar telega-minibuffer--string nil
"Bind to Saved string entered to minibuffer.")
(defvar telega--ignored-messages-ring (make-ring 0)
"Ring of ignored messages.
Use \\[execute-extended-command] telega-ignored-messages RET to
display the list.")
(defvar telega-docker--container-id nil
"Docker image id currently running.")
;; See https://github.com/tdlib/td/issues/1645
(defvar telega--relogin-with-phone-number nil
"This var is used to relogin with phone number when skipping QR auth")
(defvar telega--recent-inline-bots nil
"List of usernames for recently used inline bots.")
(defvar telega--notification-messages-ring (make-ring 1)
"Ring of messages triggered notification.
Use \\[execute-extended-command] telega-notifications-history RET to
display the list.")
(defvar telega-topic--default-icons nil
"Cached list of topic icons which can be used by all users.")
(defvar telega--default-face 'default
"Bind this to alter size calculation for the images.")
(defvar telega--accent-colors-alist nil
"Alist id -> accent-color received by `updateAccentColors' event.")
(defvar telega--accent-colors-available-ids nil
"Accent colors received by `updateAccentColors' event.")
(defvar telega-palette-context nil
"Bind this to the context where palette is used.
Available contexts are: `title', `msg-header', `link-preview', `quote',
`precode', `codeblock', `blockquote', `edit', `reply', `iv-chat-link',
`sponsored', `story', `avatar'")
(defun telega-palette-by-color-id (color-id &optional background-mode)
"Return palette with accent colors by COLOR-ID.
Pallete is a plist with the following keys: `:outline', `:foreground',
`:background' and `:colors'"
(unless background-mode
(setq background-mode (frame-parameter nil 'background-mode)))
(cl-assert (memq background-mode '(light dark)))
(if (and color-id (< color-id 7))
(let ((palette (alist-get background-mode telega-builtin-palettes-alist)))
(cl-assert (= (length palette) 7))
(nth color-id palette))
(when-let* ((tl-color (alist-get color-id telega--accent-colors-alist))
(colors (mapcar (lambda (color-value)
(format "#%06x" color-value))
(plist-get tl-color
(if (eq background-mode 'light)
:light_theme_colors
:dark_theme_colors))))
(fg-color (car colors))
(bg-color (telega-color-name-set-saturation-light
fg-color 0.1 (cl-ecase background-mode
(light 0.8)
(dark 0.2))))
(ol-color (cl-ecase background-mode
(light (color-darken-name fg-color 20))
(dark (color-lighten-name fg-color 20)))))
`((:outline ,ol-color) (:foreground ,fg-color)
(:background ,bg-color) (:colors ,colors)))))
(defmacro telega-palette-attr (palette attribute)
"From PALETTE return ATTRIBUTE value.
ATTRIBUTE is one of `:foreground', `:background' or `:outline'."
(let ((attrsym (gensym "attr-spec")))
`(let ((,attrsym ,attribute))
(plist-get (assq ,attrsym ,palette) ,attrsym))))
(defun telega-palette-attr-replace (palette src-attr dst-attr)
"For PALETTE, makes DST-ATTR to have value of SRC-ATTR.
Return new palette.
Example: `(telega-palette-attr-replace palette :outline :foreground)'
to make `:outline' be a `:foreground'."
(let ((new-palette (copy-sequence palette)))
(setcdr (assq dst-attr new-palette)
(cdr (assq src-attr new-palette)))))
(defun telega-palette-attr-delete (palette &rest attributes)
"Return new palette with ATTRIBUTES being deleted from PALETTE."
(let ((new-palette (copy-sequence palette)))
(dolist (attr attributes)
(setq new-palette (assq-delete-all attr new-palette)))
new-palette))
(defun telega-face-with-palette (face palette &rest attributes)
"Merge PALETTE ATTRIBUTES into FACE, resulting in a new face."
(declare (indent 2))
(let ((new-face (cond ((facep face)
(face-spec-choose (face-default-spec face)))
(t
(cl-assert (listp face))
face)))
(need-copy-p t))
(dolist (attr attributes)
(when-let ((value (telega-palette-attr palette attr)))
(when need-copy-p
;; Attribute changes, need a copy
(setq new-face (copy-sequence new-face)
need-copy-p nil))
(plist-put new-face attr value)))
new-face))
(defvar telega--saved-messages-tags nil
"Hash table saved_message_topic_id -> tags.")
;;; Shared chat buffer local variables
(defvar telega-chatbuf--chat nil
"Telega chat for the current chat buffer.")
(make-variable-buffer-local 'telega-chatbuf--chat)
(defun telega-chatbuf--chat (buffer)
"Return chat corresponding chat BUFFER."
(buffer-local-value 'telega-chatbuf--chat buffer))
(defvar telega-chatbuf--marked-messages nil
"List of marked messages.")
(make-variable-buffer-local 'telega-chatbuf--marked-messages)
(defvar telega-chatbuf--marked-messages-1 nil
"List of previously marked messages.")
(make-variable-buffer-local 'telega-chatbuf--marked-messages-1)
(defvar telega-chatbuf--inline-query nil
"Non-nil if some inline bot has been requested.
Actual value is `:@extra` value of the call to inline bot.")
(make-variable-buffer-local 'telega-chatbuf--inline-query)
(defvar telega-chatbuf--input-marker nil)
(make-variable-buffer-local 'telega-chatbuf--input-marker)
(defvar telega-chatbuf--administrators nil
"List of administrators in chatbuf chat.
Asynchronously loaded when chatbuf is created.")
(make-variable-buffer-local 'telega-chatbuf--administrators)
(defvar telega-chatbuf--hidden-headers
(list :active-stories nil :pinned-stories nil :video-chat nil
:active-stories-show-more nil :pinned-stories-show-more nil)
"Plist to check whether some header is hidden by pressing [x] button.")
(make-variable-buffer-local 'telega-chatbuf--hidden-headers)
(defvar telega-chatbuf--group-call-users nil
"List of group call participants.")
(make-variable-buffer-local 'telega-chatbuf--group-call-users)
(defvar telega-chatbuf--fetch-alist nil
"Alist of async requests (fetches) to the telega-server.
Could be used for fetching `admins', `pinned-messages', `reply-markup', etc.")
(make-variable-buffer-local 'telega-chatbuf--fetch-alist)
(defvar telega-chatbuf--bot-start-parameter nil
"Parameter to pass to `telega--sendBotStartMessage' when START is pressed.")
(make-variable-buffer-local 'telega-chatbuf--bot-start-parameter)
(defvar telega-chatbuf-language-code nil
"A two-letter ISO 639-1 language code for the chat's language.")
(make-variable-buffer-local 'telega-chatbuf-language-code)
(defvar telega-chatbuf--focus-status nil
"Last focus status, retrieved with `(telega-focus-state)'.")
(make-variable-buffer-local 'telega-chatbuf--focus-status)
(defvar telega-chatbuf--focus-debounce-timer nil
"Timer for debouncing focus status.")
(make-variable-buffer-local 'telega-chatbuf--focus-debounce-timer)
(defvar telega-chatbuf--history-state-plist nil
"Plist containing different state of history loading.
Could contain `:loading', `:older-loaded', `:newer-freezed' or
`:newer-loaded' elements.")
(make-variable-buffer-local 'telega-chatbuf--history-state-plist)
(defvar telega-chatbuf--thread nil
"Thread currently active in the chatbuf.
Thread is either TL `forumTopic' or `message' starting a thread.")
(make-variable-buffer-local 'telega-chatbuf--thread)
(defun telega-chatbuf--thread-msg ()
"Return chatbuf's thread as thread's root message."
(when (telega-msg-p telega-chatbuf--thread)
telega-chatbuf--thread))
(defun telega-chatbuf--thread-info ()
(plist-get (telega-chatbuf--thread-msg) :telega-thread-info))
(defun telega-chatbuf--thread-topic ()
"Return chatbuf's thread as topic."
(unless (telega-chatbuf--thread-msg)
;; Must be topic or nil at this point
telega-chatbuf--thread))
(defun telega-chatbuf--message-thread-id (&optional only-if-topic-p
for-msg-send-p)
"Return message thread id for the chatbuf.
To be used in various TDLib methods as `:message_thread_id` argument.
If ONLY-IF-TOPIC-P is specified, then return thread id only if topic
is enabled.
If FOR-MSG-SEND-P is specified, then return message thread id for use
with `sendMessage' and `sendMessageAlbum' functions. It differs,
because for General topic 0 message thread id must be used (according
to note from TDLib dev)."
(or (when-let ((topic (telega-chatbuf--thread-topic)))
(if (and for-msg-send-p (telega-topic-match-p topic 'is-general))
0
(telega-topic-msg-thread-id topic)))
(unless only-if-topic-p
(when-let ((thread (telega-chatbuf--thread-msg)))
(plist-get telega-chatbuf--thread :message_thread_id)))
0))
(defvar telega-chatbuf--aux-plist nil
"Supplimentary plist for aux prompt.")
(make-variable-buffer-local 'telega-chatbuf--aux-plist)
(defun telega--init-vars ()
"Initialize runtime variables.
Done when telega server is ready to receive queries."
(setq telega--auth-state nil)
(setq telega--conn-state nil)
(setq telega--status "Disconnected")
(setq telega--status-aux "")
(setq telega--me-id -1)
(setq telega--replies-id nil)
(setq telega--options
;; default limits
(list :message_caption_length_max 1024
:message_text_length_max 4096))
(setq telega--chats (make-hash-table :test #'eq))
(setq telega--chat-topics (make-hash-table :test #'eq))
(setq telega--chat-active-stories (make-hash-table :test #'eq))
(setq telega--cached-messages (make-hash-table :test #'equal))
(setq telega--cached-stories (make-hash-table :test #'equal))
(setq telega--top-chats nil)
(setq telega--search-chats nil)
(setq telega-deleted-chats nil)
(setq telega--blocked-user-ids-alist
(list (cons 'blockListMain (list 0))
(cons 'blockListStories (list 0))))
(setq telega--ordered-chats nil)
(setq telega--filtered-chats nil)
(setq telega--dirty-chats nil)
(setq telega--actions (make-hash-table :test 'equal))
(setq telega--filters nil)
(setq telega--undo-filters nil)
(setq telega--sort-criteria nil)
(setq telega--sort-inverted nil)
(setq telega--sort-reorder-dirtiness nil)
(setq telega--info
(list (cons 'user (make-hash-table :test 'eq))
(cons 'secretChat (make-hash-table :test 'eq))
(cons 'basicGroup (make-hash-table :test 'eq))
(cons 'supergroup (make-hash-table :test 'eq))))
(setq telega--full-info
(list (cons 'user (make-hash-table :test 'eq))
(cons 'basicGroup (make-hash-table :test 'eq))
(cons 'supergroup (make-hash-table :test 'eq))))
(setq telega--ignored-messages-ring
(make-ring telega-ignored-messages-ring-size))
(setq telega--unread-message-count nil)
(setq telega--unread-chat-count nil)
(setq telega--story-list-chat-count nil)
(setq telega--story-stealth-mode nil)
(setq telega--files (make-hash-table :test 'eq))
(setq telega--files-updates (make-hash-table :test 'eq))
(setq telega-voip--alist nil)
(setq telega-voip--active-call nil)
(setq telega--proxy-pings nil)
(setq telega--scope-notification-alist nil)
(setq telega--stickersets nil)
(setq telega--stickersets-installed-ids nil)
(setq telega--stickersets-installed nil)
(setq telega--stickersets-trending nil)
(setq telega--stickersets-trending-premium nil)
(setq telega--stickersets-system nil)
(setq telega--stickersets-custom-emojis nil)
(setq telega--stickers-favorite nil)
(setq telega--stickers-recent nil)
(setq telega--stickers-recent-attached nil)
(setq telega--animated-emojis nil)
(setq telega--animated-emojis-stickerset-id nil)
(setq telega--custom-emoji-stickers
(make-hash-table :size 200 :test 'equal))
(setq telega--animations-saved nil)
(setq telega--chat-themes nil)
(setq telega--dice-emojis nil)
(setq telega-tdlib--chat-folders nil)
(setq telega-tdlib--chat-folder-tags-p nil)
(setq telega-tdlib--chat-list nil)
(setq telega-tdlib--unix-time nil)
(setq telega--group-calls (make-hash-table :test 'eq))
(setq telega-docker--container-id nil)
(setq telega--recent-inline-bots nil)
(setq telega--favorite-messages-storage-message 'not-yet-fetched)
(setq telega--favorite-messages nil)
(setq telega--notification-messages-ring
(make-ring telega-notifications-history-ring-size))
(setq telega--accent-colors-alist nil
telega--accent-colors-available-ids nil)
(setq telega--saved-messages-tags (make-hash-table :test #'eq))
(setq telega--close-birthday-users nil)
(setq telega--owned-stars 0)
)
(defun telega-test-env (&optional quiet-p)
"Test Emacs environment.
If QUIET-P is non-nil, then show success message in echo area.
Return non-nil if all tests are passed."
(interactive "P")
;; 62bits for numbers is required
;; i.e. ./configure --with-wide-int
(cl-assert (= most-positive-fixnum 2305843009213693951) nil
"Emacs with wide ints (--with-wide-int) is required")
(cl-assert (= (string-to-number "542353335") 542353335) nil
(concat "Emacs with `(string-to-number \"542353335\") ==> 542353335'"
" is required"))
;; at least 25.1 emacs is required
;; see https://t.me/emacs_telega/1592
(cl-assert (fboundp 'cursor-intangible-mode) nil
"Emacs with `cursor-intangible-mode' is required")
;; For now stick with at least 27.1 Emacs
(cl-assert (string-version-lessp "27.0" emacs-version) nil
(format "At least Emacs 27.0 is required, but you have %s"
emacs-version))
;; imagemagick for images NOT required, we have now fallback in case
;; native image transforms available (newer Emacs)
(cl-assert (or (image-type-available-p 'imagemagick)
(if (telega-x-frame)
(and (fboundp 'image-transforms-p)
(funcall 'image-transforms-p))
;; For TTY-only emacs, images are not required
t))
nil
(concat "Emacs with `imagemagick' support is required."
" (libmagickcore, libmagickwand, --with-imagemagick)"))
;; SVG is no longer required if avatars are disabled (in TTY for example)
(cl-assert (or (image-type-available-p 'svg)
(and (not telega-root-show-avatars)
(not telega-user-show-avatars)
(not telega-chat-show-avatars)))
nil
(concat "Emacs with `svg' support is needed to show avatars. "
"Disable `telega-XXX-show-avatars' or recompile Emacs with svg support"))
(unless quiet-p
(message "Your Emacs is suitable to run telega.el"))
t)
(defmacro telega-save-window-start (start end &rest body)
"Execute BODY saving window start and point.
Window start is saved only if window start is inbetween START and
END."
(declare (indent 2))
(let ((buf-win-sym (gensym))
(win-start (gensym "winstart"))
(win-start-line (gensym)))
`(let* ((,buf-win-sym (get-buffer-window))
(,win-start (when ,buf-win-sym
(window-start ,buf-win-sym)))
(,win-start-line (when (and ,buf-win-sym
(>= ,win-start ,start)
(<= ,win-start ,end))
(1+ (count-lines 1 ,win-start)))))
(unwind-protect
(progn ,@body)
(when (and ,buf-win-sym ,win-start-line)
(save-excursion
(goto-char (point-min))
(forward-line (1- ,win-start-line))
(set-window-start ,buf-win-sym (point) 'noforce)))))))
(defmacro telega-save-excursion (&rest body)
"Execute BODY saving current point as moving marker."
(declare (indent 0))
(let ((pnt-sym (gensym)))
`(let* ((,pnt-sym (copy-marker (point) t)))
(unwind-protect
(progn ,@body)
(goto-char ,pnt-sym)))))
(defmacro telega-save-cursor (&rest body)
"Execute BODY saving cursor's line and column position."
(declare (indent 0))
(let ((line-sym (gensym "line"))
(col-sym (gensym "col")))
`(let ((,line-sym (+ (if (bolp) 1 0) (count-lines 1 (point))))
(,col-sym (current-column)))
(unwind-protect
(progn ,@body)
(goto-char (point-min))
(cl-assert (> ,line-sym 0))
(forward-line (1- ,line-sym))
(move-to-column ,col-sym)))))
(defmacro lambda-with-current-buffer (args &rest body)
"Same as `lambda' but keep current buffer inside lambda."
(declare (indent 1))
(let ((buf-sym (gensym "buffer")))
`(let ((,buf-sym (current-buffer)))
(lambda ,args
(when (buffer-live-p ,buf-sym)
(with-current-buffer ,buf-sym
,@body))))))
(defmacro with-telega-debug-buffer (&rest body)
"Execute BODY only if `telega-debug' is non-nil, making debug buffer current."
`(when telega-debug
(with-current-buffer (get-buffer-create "*telega-debug*")
(telega-save-excursion
,@body))))
(defmacro with-telega-buffer-modify (&rest body)
"Run BODY inhibiting `buffer-read-only' variable."
`(with-silent-modifications
,@body))
(defmacro with-telega-root-buffer (&rest body)
"Execute BODY setting current buffer to root buffer.
Inhibits read-only flag."
(declare (indent 0))
(let ((bufsym (gensym "rootbuf")))
`(let ((,bufsym (telega-root--buffer)))
(when (buffer-live-p ,bufsym)
(with-current-buffer ,bufsym
(with-telega-buffer-modify
,@body))))))
(defmacro with-telega-chatbuf (chat &rest body)
"Execute BODY setting current buffer to chat buffer of CHAT.
Executes BODY only if chat buffer already exists.
If there is no corresponding buffer, then do nothing.
Inhibits read-only flag."
(declare (indent 1))
(let ((bufsym (cl-gensym "buf"))
(chatsym (cl-gensym "chat")))
`(let* ((,chatsym ,chat)
(,bufsym (if (and telega-chatbuf--chat
(eq telega-chatbuf--chat ,chatsym))
(current-buffer)
(cdr (assq ,chatsym telega--chat-buffers-alist)))))
(when (buffer-live-p ,bufsym)
(with-current-buffer ,bufsym
(with-telega-buffer-modify
,@body))))))
(defun telega-buffer-substring-filter (beg end delete)
"Function to be used as `filter-buffer-substring-function' in chatbufs.
Strips `line-prefix' and `wrap-prefix' text properties from copied text."
(let ((bstr (buffer-substring beg end)))
(when delete
(save-excursion
(goto-char beg)
(delete-region beg end)))
(remove-text-properties 0 (length bstr)
'(line-prefix nil wrap-prefix nil)
bstr)
bstr))
(defmacro with-telega-help-win (buffer-or-name &rest body)
"Execute BODY in help BUFFER-OR-NAME.
Return a buffer."
(declare (indent 1))
`(progn
;; (with-help-window ,buffer-or-name)
;; (redisplay)
(with-help-window ,buffer-or-name
(set-buffer standard-output)
(setq-local nobreak-char-display nil)
;; Special function to filter out `line-prefix', `wrap-prefix' (and
;; probably other) text properties when copying text from chatbuf
(setq-local filter-buffer-substring-function
#'telega-buffer-substring-filter)
(cursor-intangible-mode 1)
(cursor-sensor-mode 1)
(visual-line-mode 1)
;; (setq-local fill-column -1)
;; (visual-fill-column-mode 1)
,@body
,buffer-or-name)))
(defun telega-help-win--add-tdlib-callback (extra)
(setq telega--help-win-tdlib-callbacks
(cons extra telega--help-win-tdlib-callbacks))
extra)
(defun telega-help-win--rm-tdlib-callback (extra)
(setq telega--help-win-tdlib-callbacks
(delq extra telega--help-win-tdlib-callbacks)))
(defun telega-help-win--maybe-redisplay (buffer-or-name for-param)
"Possible redisplay help win with BUFFER-OR-NAME.
If BUFFER-OR-NAME exists and visible then redisplay it."
(when-let ((help-buf (get-buffer buffer-or-name)))
(with-current-buffer help-buf
(when (and (eq for-param telega--help-win-param)
telega--help-win-inserter)
(if (get-buffer-window help-buf)
;; Buffer is visible in some HELP-WIN
(telega-save-window-start (point-min) (point-max)
(telega-save-cursor
(let ((inhibit-read-only t))
;; Cancel any pending tdlib callbacks
(seq-doseq (extra telega--help-win-tdlib-callbacks)
(telega-server--callback-put extra #'ignore))
(setq telega--help-win-tdlib-callbacks nil)
(setq telega--help-win-dirty-p nil)
(erase-buffer)
(funcall telega--help-win-inserter
telega--help-win-param))))
;; Buffer is not visible, mark it as dirty, so it will be
;; redisplayed when switched in
(setq telega--help-win-dirty-p t))))))
(defmacro telega-help-message (help-name fmt &rest fmt-args)
"Show once help message formatted with FMT and FMT-ARGS.
Show message only if `telega-help-messages' is non-nil."
(declare (indent 2))
`(when (and telega-help-messages
(not (get 'telega-help-messages ,help-name)))
(put 'telega-help-messages ,help-name t)
(message (concat "Telega: " ,fmt) ,@fmt-args)))
(defsubst telega-debug (fmt &rest args)
"Insert formatted string into debug buffer.
FMT and ARGS are passed directly to `format'."
(with-telega-debug-buffer
(goto-char (point-max))
(insert (apply 'format (cons (concat "%d: " fmt "\n")
(cons (telega-time-seconds) args))))))
(defmacro telega--tl-type (tl-obj)