-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMSLib.py
More file actions
4646 lines (3903 loc) · 185 KB
/
MSLib.py
File metadata and controls
4646 lines (3903 loc) · 185 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 ast
import copy
import json
import zlib
import html
import inspect
import logging
import os
import os.path
import time
import threading
import traceback
import re
import base64
from dataclasses import dataclass
from enum import Enum
from html.parser import HTMLParser
from struct import unpack
from typing import List, Callable, Optional, Any, Union, Dict, Tuple, get_origin, get_args
from urllib.parse import urlencode, parse_qs, urlparse
from ui.bulletin import BulletinHelper as _BulletinHelper # type: ignore
from ui.settings import Header, Switch, Input, Text, Divider # type: ignore
from ui.alert import AlertDialogBuilder # type: ignore
from base_plugin import BasePlugin, HookResult, MethodHook, HookStrategy # type: ignore
from android_utils import log as _log, run_on_ui_thread # type: ignore
from client_utils import get_messages_controller, get_last_fragment, send_request, send_message, get_file_loader, run_on_queue # type: ignore
from java import dynamic_proxy, jclass # type: ignore
from java.util import Locale, ArrayList # type: ignore
from java.lang import Long, Integer, Boolean # type: ignore
from org.telegram.tgnet import TLRPC, TLObject # type: ignore
from org.telegram.ui import ChatActivity # type: ignore
from org.telegram.messenger import R, Utilities, AndroidUtilities, ApplicationLoader, MessageObject, AccountInstance, FileLoader # type: ignore
from com.exteragram.messenger.plugins import PluginsController # type: ignore
from android.view import View # type: ignore
from hook_utils import get_private_field, set_private_field # type: ignore
from android.view import MotionEvent # type: ignore
__name__ = "MSLib"
__id__ = "MSLib"
__description__ = "MSLib is a powerful plugin development library"
__icon__ = "MSMainPack/3"
__author__ = "@MiracleStudios"
__version__ = "1.1"
__min_version__ = "12.0.0"
# ==================== Constants ====================
CACHE_DIRECTORY = None
PLUGINS_DIRECTORY = None
COMPANION_PATH = None
LOCALE = "en"
ALLOWED_ARG_TYPES = (str, int, float, bool, Any)
ALLOWED_ORIGIN = (Union, Optional)
NOT_PREMIUM = 0
TELEGRAM_PREMIUM = 1
MSLIB_GLOBAL_PREMIUM = 2
DEFAULT_AUTOUPDATE_TIMEOUT = "600"
DEFAULT_DISABLE_TIMESTAMP_CHECK = False
DEFAULT_DEBUG_MODE = False
MSLIB_AUTOUPDATE_CHANNEL_ID = -1003314084396
MSLIB_AUTOUPDATE_MSG_ID = 3
autoupdater = None
def _init_constants():
global CACHE_DIRECTORY, PLUGINS_DIRECTORY, COMPANION_PATH, LOCALE
if CACHE_DIRECTORY is None:
CACHE_DIRECTORY = os.path.join(AndroidUtilities.getCacheDir().getAbsolutePath(), "mslib_cache")
if PLUGINS_DIRECTORY is None:
PLUGINS_DIRECTORY = os.path.dirname(os.path.dirname(__file__))
if COMPANION_PATH is None:
COMPANION_PATH = os.path.join(PLUGINS_DIRECTORY, "mslib_companion.py")
try:
LOCALE = Locale.getDefault().getLanguage()
except Exception:
LOCALE = "en"
# ==================== Utilities ====================
def pluralization_string(count: int, forms: List[str]) -> str:
if len(forms) == 2:
return f"{count} {forms[1] if count != 1 else forms[0]}"
elif len(forms) == 3:
if count % 10 == 1 and count % 100 != 11:
return f"{count} {forms[0]}"
elif 2 <= count % 10 <= 4 and (count % 100 < 10 or count % 100 >= 20):
return f"{count} {forms[1]}"
else:
return f"{count} {forms[2]}"
else:
return f"{count} {forms[0]}"
def get_locale() -> str:
return LOCALE
# ==================== Logging utilities ====================
class CustomLogger(logging.Logger):
def _log(self, level: int, msg: Any, args: Tuple[Any, ...], exc_info=None, extra=None, stack_info=False, stacklevel=1):
caller_frame = inspect.stack()[2]
func_name = caller_frame.function
level_name = logging.getLevelName(level).upper()
prefix_items = [level_name, self.name, func_name]
prefix_items = filter(lambda i: i, prefix_items)
prefix_items = [f"[{i}]" for i in prefix_items]
prefix = " ".join(prefix_items)
try:
formatted_msg = str(msg) % args if args else str(msg)
except (TypeError, ValueError):
formatted_msg = f"{msg} {args}"
_log(f"{prefix} {formatted_msg}")
logging.setLoggerClass(CustomLogger)
def build_log(tag: str, level=logging.INFO) -> logging.Logger:
logger = logging.getLogger(tag)
logger.setLevel(level)
return logger
logger = build_log(__name__)
def format_exc() -> str:
return traceback.format_exc().strip()
def format_exc_from(e: Exception) -> str:
return "".join(traceback.format_exception(type(e), e, e.__traceback__)).strip()
def format_exc_only(e: Exception) -> str:
return ''.join(traceback.format_exception_only(type(e), e)).strip()
# ==================== Markdown & HTML parsers ====================
def add_surrogates(text: str) -> str:
return re.compile(r"[\U00010000-\U0010FFFF]").sub(
lambda match: "".join(chr(i) for i in unpack("<HH", match.group().encode("utf-16le"))),
text
)
def remove_surrogates(text: str) -> str:
return text.encode("utf-16", "surrogatepass").decode("utf-16")
class TLEntityType(Enum):
CODE = 'code'
PRE = 'pre'
STRIKETHROUGH = 'strikethrough'
TEXT_LINK = 'text_link'
BOLD = 'bold'
ITALIC = 'italic'
UNDERLINE = 'underline'
SPOILER = 'spoiler'
CUSTOM_EMOJI = 'custom_emoji'
BLOCKQUOTE = 'blockquote'
@dataclass
class RawEntity:
type: TLEntityType
offset: int
length: int
extra: Optional[str] = None
def to_tlrpc_object(self) -> 'TLRPC.MessageEntity':
if self.type == TLEntityType.BOLD:
entity = TLRPC.TL_messageEntityBold()
elif self.type == TLEntityType.ITALIC:
entity = TLRPC.TL_messageEntityItalic()
elif self.type == TLEntityType.UNDERLINE:
entity = TLRPC.TL_messageEntityUnderline()
elif self.type == TLEntityType.STRIKETHROUGH:
entity = TLRPC.TL_messageEntityStrike()
elif self.type == TLEntityType.CODE:
entity = TLRPC.TL_messageEntityCode()
elif self.type == TLEntityType.PRE:
entity = TLRPC.TL_messageEntityPre()
if self.extra:
entity.language = self.extra
elif self.type == TLEntityType.TEXT_LINK:
entity = TLRPC.TL_messageEntityTextUrl()
entity.url = self.extra or ""
elif self.type == TLEntityType.CUSTOM_EMOJI:
entity = TLRPC.TL_messageEntityCustomEmoji()
try:
entity.document_id = int(self.extra) if self.extra else 0
except (ValueError, TypeError):
entity.document_id = 0
elif self.type == TLEntityType.SPOILER:
entity = TLRPC.TL_messageEntitySpoiler()
elif self.type == TLEntityType.BLOCKQUOTE:
entity = TLRPC.TL_messageEntityBlockquote()
else:
entity = TLRPC.TL_messageEntityUnknown()
entity.offset = self.offset
entity.length = self.length
return entity
@dataclass
class ParsedMessage:
text: str
entities: List[RawEntity]
class HTMLParser_(HTMLParser):
def __init__(self):
super().__init__()
self.text = ""
self.entities = []
self.tag_stack = []
def handle_starttag(self, tag, attrs):
self.tag_stack.append((tag, dict(attrs), len(self.text)))
def handle_data(self, data):
self.text += data
def handle_endtag(self, tag):
if not self.tag_stack or self.tag_stack[-1][0] != tag:
return
tag_name, attrs, start_pos = self.tag_stack.pop()
length = len(self.text) - start_pos
if length <= 0:
return
entity_type = None
extra = None
if tag_name == 'b' or tag_name == 'strong':
entity_type = TLEntityType.BOLD
elif tag_name == 'i' or tag_name == 'em':
entity_type = TLEntityType.ITALIC
elif tag_name == 'u':
entity_type = TLEntityType.UNDERLINE
elif tag_name == 's' or tag_name == 'del' or tag_name == 'strike':
entity_type = TLEntityType.STRIKETHROUGH
elif tag_name == 'code':
entity_type = TLEntityType.CODE
elif tag_name == 'pre':
entity_type = TLEntityType.PRE
elif tag_name == 'a':
entity_type = TLEntityType.TEXT_LINK
extra = attrs.get('href', '')
elif tag_name == 'emoji':
entity_type = TLEntityType.CUSTOM_EMOJI
extra = attrs.get('id', '')
elif tag_name == 'blockquote':
entity_type = TLEntityType.BLOCKQUOTE
elif tag_name == 'spoiler':
entity_type = TLEntityType.SPOILER
if entity_type:
self.entities.append(RawEntity(entity_type, start_pos, length, extra))
class HTML:
@staticmethod
def parse(text: str) -> ParsedMessage:
"""Parses HTML text and returns ParsedMessage with plain text and entities"""
parser = HTMLParser_()
parser.feed(text)
return ParsedMessage(text=add_surrogates(parser.text), entities=parser.entities)
@staticmethod
def unparse(text: str, entities: List[RawEntity]) -> str:
if not entities:
return text
result = []
last_offset = 0
for entity in sorted(entities, key=lambda e: e.offset):
result.append(text[last_offset:entity.offset])
content = text[entity.offset:entity.offset + entity.length]
if entity.type == TLEntityType.BOLD:
result.append(f"<b>{content}</b>")
elif entity.type == TLEntityType.ITALIC:
result.append(f"<i>{content}</i>")
elif entity.type == TLEntityType.UNDERLINE:
result.append(f"<u>{content}</u>")
elif entity.type == TLEntityType.STRIKETHROUGH:
result.append(f"<s>{content}</s>")
elif entity.type == TLEntityType.CODE:
result.append(f"<code>{content}</code>")
elif entity.type == TLEntityType.PRE:
result.append(f"<pre>{content}</pre>")
elif entity.type == TLEntityType.TEXT_LINK:
result.append(f'<a href="{entity.extra}">{content}</a>')
elif entity.type == TLEntityType.CUSTOM_EMOJI:
result.append(f'<emoji id="{entity.extra}">{content}</emoji>')
elif entity.type == TLEntityType.BLOCKQUOTE:
result.append(f"<blockquote>{content}</blockquote>")
elif entity.type == TLEntityType.SPOILER:
result.append(f"<spoiler>{content}</spoiler>")
last_offset = entity.offset + entity.length
result.append(text[last_offset:])
return ''.join(result)
class Markdown:
BOLD_DELIM = "**"
ITALIC_DELIM = "_"
UNDERLINE_DELIM = "__"
STRIKE_DELIM = "~~"
SPOILER_DELIM = "||"
CODE_DELIM = "`"
PRE_DELIM = "```"
BLOCKQUOTE_DELIM = ">"
@staticmethod
def parse(text: str, strict: bool = False) -> ParsedMessage:
"""Parse Markdown text and return ParsedMessage with plain text and entities"""
entities = []
markers_to_remove = []
# Bold (**text**)
for match in re.finditer(r'\*\*(.+?)\*\*', text):
content = match.group(1)
start = match.start()
markers_to_remove.append((start, match.end(), content))
# Strikethrough (~~text~~)
for match in re.finditer(r'~~(.+?)~~', text):
content = match.group(1)
start = match.start()
# Check if not part of bold
if not any(m[0] <= start < m[1] for m in markers_to_remove):
markers_to_remove.append((start, match.end(), content))
# Code (`text`)
for match in re.finditer(r'`([^`]+)`', text):
content = match.group(1)
start = match.start()
markers_to_remove.append((start, match.end(), content))
# Spoiler (||text||)
for match in re.finditer(r'\|\|(.+?)\|\|', text):
content = match.group(1)
start = match.start()
markers_to_remove.append((start, match.end(), content))
# Italic (*text* but not **) - process after bold
for match in re.finditer(r'(?<!\*)\*([^*]+)\*(?!\*)', text):
content = match.group(1)
start = match.start()
# Check if not part of other formatting
if not any(m[0] <= start < m[1] for m in markers_to_remove):
markers_to_remove.append((start, match.end(), content))
markers_to_remove.sort(key=lambda x: x[0], reverse=True)
clean_text = text
offset_map = {}
for start, end, content in markers_to_remove:
marker_len = end - start
content_len = len(content)
shift = marker_len - content_len
offset_map[start] = (start, shift)
clean_text = clean_text[:start] + content + clean_text[end:]
for match in re.finditer(r'\*\*(.+?)\*\*', text):
original_start = match.start()
content_len = len(match.group(1))
new_offset = original_start
for pos, (orig_pos, shift) in offset_map.items():
if orig_pos < original_start:
new_offset -= shift
entities.append(RawEntity(
TLEntityType.BOLD,
new_offset,
content_len
))
for match in re.finditer(r'~~(.+?)~~', text):
original_start = match.start()
content_len = len(match.group(1))
new_offset = original_start
for pos, (orig_pos, shift) in offset_map.items():
if orig_pos < original_start:
new_offset -= shift
entities.append(RawEntity(
TLEntityType.STRIKETHROUGH,
new_offset,
content_len
))
for match in re.finditer(r'`([^`]+)`', text):
original_start = match.start()
content_len = len(match.group(1))
new_offset = original_start
for pos, (orig_pos, shift) in offset_map.items():
if orig_pos < original_start:
new_offset -= shift
entities.append(RawEntity(
TLEntityType.CODE,
new_offset,
content_len
))
for match in re.finditer(r'\|\|(.+?)\|\|', text):
original_start = match.start()
content_len = len(match.group(1))
new_offset = original_start
for pos, (orig_pos, shift) in offset_map.items():
if orig_pos < original_start:
new_offset -= shift
entities.append(RawEntity(
TLEntityType.SPOILER,
new_offset,
content_len
))
for match in re.finditer(r'(?<!\*)\*([^*]+)\*(?!\*)', text):
original_start = match.start()
content_len = len(match.group(1))
new_offset = original_start
for pos, (orig_pos, shift) in offset_map.items():
if orig_pos < original_start:
new_offset -= shift
entities.append(RawEntity(
TLEntityType.ITALIC,
new_offset,
content_len
))
entities.sort(key=lambda e: e.offset)
return ParsedMessage(text=add_surrogates(clean_text), entities=entities)
@staticmethod
def unparse(text: str, entities: List[RawEntity]) -> str:
if not entities:
return text
result = []
last_offset = 0
for entity in sorted(entities, key=lambda e: e.offset):
result.append(text[last_offset:entity.offset])
content = text[entity.offset:entity.offset + entity.length]
if entity.type == TLEntityType.BOLD:
result.append(f"**{content}**")
elif entity.type == TLEntityType.ITALIC:
result.append(f"*{content}*")
elif entity.type == TLEntityType.UNDERLINE:
result.append(f"__{content}__")
elif entity.type == TLEntityType.STRIKETHROUGH:
result.append(f"~~{content}~~")
elif entity.type == TLEntityType.CODE:
result.append(f"`{content}`")
elif entity.type == TLEntityType.PRE:
result.append(f"```{content}```")
elif entity.type == TLEntityType.TEXT_LINK:
result.append(f"[{content}]({entity.extra})")
elif entity.type == TLEntityType.SPOILER:
result.append(f"||{content}||")
else:
result.append(content)
last_offset = entity.offset + entity.length
result.append(text[last_offset:])
return ''.join(result)
def link(text: str, url: str) -> str:
return f'<a href="{url}">{text}</a>'
# ==================== Working with Java collections ====================
def arraylist_to_list(jarray: Optional[ArrayList]) -> Optional[List[Any]]:
return [jarray.get(i) for i in range(jarray.size())] if jarray else None
def list_to_arraylist(python_list: Optional[List[Any]], int_auto_convert: bool = True) -> Optional[ArrayList]:
if not python_list:
return None
arraylist = ArrayList()
for item in python_list:
if int_auto_convert and isinstance(item, int):
arraylist.add(Integer(item))
else:
arraylist.add(item)
return arraylist
# ==================== Compression & Encoding ====================
def compress_and_encode(data: Union[bytes, str], level: int = 9) -> str:
"""Сжимает и кодирует данные в base64"""
try:
if isinstance(data, str):
data = data.encode('utf-8')
compressed = zlib.compress(data, level=level)
return base64.b64encode(compressed).decode('utf-8')
except Exception as e:
logger.error(f"Failed to compress and encode: {format_exc_only(e)}")
return ""
def decode_and_decompress(encoded_data: Union[bytes, str]) -> bytes:
"""Декодирует из base64 и разжимает данные"""
try:
if isinstance(encoded_data, str):
encoded_data = encoded_data.encode('utf-8')
compressed = base64.b64decode(encoded_data)
return zlib.decompress(compressed)
except Exception as e:
logger.error(f"Failed to decode and decompress: {format_exc_only(e)}")
return b""
# ==================== Decorators for plugin development ====================
def command(
cmd: Optional[str] = None, *,
aliases: Optional[List[str]] = None,
doc: Optional[str] = None,
enabled: Optional[Union[str, bool]] = None
):
"""
Decorator for commands
Args:
cmd (str): The command name (uses function name if not specified)
aliases (List[str]): A list of aliases for the command
doc (str): String-key in `strings` for command description
enabled (str/bool): Setting-key or boolean for enabling the command
"""
def decorator(func):
func.__is_command__ = True
func.__aliases__ = aliases or []
func.__cdoc__ = doc
func.__enabled__ = enabled
func.__cmd__ = cmd or func.__name__
return func
return decorator
def uri(uri: str):
"""
Decorator for URIs
Args:
uri (str): The URI
"""
def decorator(func):
func.__is_uri_handler__ = True
func.__uri__ = uri
return func
return decorator
def message_uri(uri: str, support_long_click: bool = False):
"""
Decorator for URIs in messages
Args:
uri (str): The URI
support_long_click (bool): if true, func will be called on long click too
"""
def decorator(func):
func.__is_uri_message_handler__ = True
func.__uri__ = uri
func.__support_long__ = support_long_click
return func
return decorator
# ==================== PluginsData helper (как в CactusLib) ====================
class PluginsData:
"""Класс для парсинга метаданных плагинов"""
_current_instance = None
plugins = {}
@classmethod
def parse(cls, plugin_path: str, plugin_id=None):
"""Парсит плагин и извлекает strings, commands, description"""
strings, commands, description = cls.get_plugin_strings_and_commands(plugin_path)
if not strings:
return
cls.plugins[plugin_id or strings.get("__id__", os.path.basename(plugin_path))] = {
"strings": strings,
"commands": commands,
"description": description
}
@classmethod
def description(cls, plugin_id: str) -> str:
"""Возвращает описание плагина"""
if plugin_id not in cls.plugins:
return "<unknown-plugin>"
return cls.locale(plugin_id).get("__doc__", cls.plugins[plugin_id].get("description", ""))
@classmethod
def locale(cls, plugin_id: str) -> Dict[str, str]:
"""Возвращает локализованные строки для плагина"""
locale_dict: Dict[str, Union[str, Dict[str, str]]] = cls.plugins[plugin_id]["strings"].get(
LOCALE,
cls.plugins[plugin_id]["strings"]
)
if "en" in locale_dict:
locale_dict = locale_dict["en"]
return locale_dict
@classmethod
def commands(cls, plugin_id: str) -> Dict[str, str]:
"""Возвращает команды плагина"""
if plugin_id not in cls.plugins:
return {}
return cls.plugins[plugin_id].get("commands", {})
@staticmethod
def get_plugin_strings_and_commands(
filepath: Optional[str] = None,
file_content: Optional[str] = None
) -> Tuple[Dict[str, Dict[str, str]], Dict[str, str], Optional[str]]:
"""Извлекает strings, commands и description из файла плагина"""
if file_content:
tree = ast.parse(file_content, filename=filepath or "<unknown>")
else:
if not os.path.exists(filepath):
return {}, {}, None
with open(filepath, "r", encoding="utf-8") as f:
tree = ast.parse(f.read(), filename=filepath)
description, strings, commands, _id = "", {}, {}, None
# Извлекаем __description__ и __id__
for node in ast.iter_child_nodes(tree):
if isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name) and target.id == "__description__":
if isinstance(node.value, ast.Constant):
description = node.value.value
if _id:
break
if isinstance(target, ast.Name) and target.id == "__id__":
if isinstance(node.value, ast.Constant):
_id = node.value.value
if description:
break
# Ищем класс наследующийся от MSLib.Plugin/CactusModule и т.д.
for node in ast.walk(tree):
if isinstance(node, ast.ClassDef):
inherits_from_plugin = False
for base in node.bases:
if (isinstance(base, ast.Attribute) and
isinstance(base.value, ast.Name) and
base.value.id in ["MSLib", "CactusUtils"] and
base.attr in ["Plugin", "CactusPlugin", "CactusModule", "MSLib"]):
inherits_from_plugin = True
break
elif isinstance(base, ast.Name) and base.id in ["MSLib", "BasePlugin"]:
inherits_from_plugin = True
break
if inherits_from_plugin:
# Извлекаем strings
for item in node.body:
if isinstance(item, ast.Assign):
for target in item.targets:
if isinstance(target, ast.Name) and target.id == "strings":
try:
strings = ast.literal_eval(item.value) # type: ignore
except Exception:
pass
break
# Извлекаем commands из декораторов
elif isinstance(item, ast.FunctionDef):
for decorator in item.decorator_list:
is_command_decorator = False
decorator_args = {}
if isinstance(decorator, ast.Call):
if (isinstance(decorator.func, ast.Name) and decorator.func.id == "command") or \
(isinstance(decorator.func, ast.Attribute) and decorator.func.attr == "command"):
is_command_decorator = True
for keyword in decorator.keywords:
if keyword.arg == "command":
try:
decorator_args['cmd'] = ast.literal_eval(keyword.value) # type: ignore
except Exception:
pass
elif keyword.arg == "doc":
try:
decorator_args['doc'] = ast.literal_eval(keyword.value) # type: ignore
except Exception:
pass
if decorator.args and len(decorator.args) > 0 and 'cmd' not in decorator_args:
try:
decorator_args['cmd'] = ast.literal_eval(decorator.args[0]) # type: ignore
except Exception:
pass
elif isinstance(decorator, ast.Name) and decorator.id == "command":
is_command_decorator = True
decorator_args['cmd'] = item.name
decorator_args['doc'] = None
if is_command_decorator:
cmd_value = decorator_args.get('cmd', item.name)
doc_value = decorator_args.get('doc')
commands[cmd_value] = doc_value
break
if strings is not None:
strings["__id__"] = _id
return strings, commands, description
strings["__id__"] = _id
return strings, commands, description
@staticmethod
def is_mslib_plugin(filepath: str) -> bool:
"""Проверяет является ли файл MSLib плагином"""
try:
with open(filepath, "r", encoding="utf-8") as f:
tree = ast.parse(f.read(), filename=filepath)
for node in ast.walk(tree):
if isinstance(node, ast.ClassDef):
for base in node.bases:
if (isinstance(base, ast.Attribute) and
isinstance(base.value, ast.Name) and
base.value.id in ["MSLib", "CactusUtils"] and
base.attr in ["Plugin", "CactusPlugin", "CactusModule"]):
return True
elif isinstance(base, ast.Name) and base.id in ["MSLib", "BasePlugin"]:
return True
return False
except Exception:
return False
# ==================== PluginInfo helper ====================
class PluginInfo:
"""Класс для работы с информацией о плагине"""
def __init__(self, lib_instance, plugin_instance, is_compatible: bool = True):
self.lib = lib_instance
self.plugin = plugin_instance
self.is_compatible = is_compatible
def export(self, with_data: bool = True) -> Dict[str, Any]:
"""Экспортирует плагин в словарь"""
try:
plugin_id = getattr(self.plugin, 'id', 'unknown')
plugin_name = getattr(self.plugin, 'name', plugin_id)
plugin_version = getattr(self.plugin, 'version', '1.0')
plugin_enabled = getattr(self.plugin, 'enabled', False)
data = {
"plugin_meta": {
"id": plugin_id,
"name": plugin_name,
"version": plugin_version,
"enabled": plugin_enabled
},
"file_content": "", # Должно заполняться при чтении файла
}
if with_data and hasattr(self.plugin, '_export_data'):
try:
exported = self.plugin._export_data()
if exported:
data["data"] = exported
except Exception as e:
logger.error(f"Failed to export data from {plugin_id}: {format_exc_only(e)}")
# Экспорт настроек
if with_data:
try:
settings = {}
# Здесь можно добавить логику экспорта настроек
if settings:
data["settings"] = settings
except Exception as e:
logger.error(f"Failed to export settings from {plugin_id}: {format_exc_only(e)}")
return data
except Exception as e:
logger.error(f"Failed to export plugin: {format_exc()}")
return {}
# ==================== Command system ====================
class CannotCastError(Exception):
pass
class WrongArgumentAmountError(Exception):
pass
class MissingRequiredArguments(Exception):
pass
class InvalidTypeError(Exception):
pass
class ArgSpec:
def __init__(self, name, annotation, kind, default=None, is_optional=False):
self.name = name
self.annotation = annotation
self.kind = kind
self.default = default if default is not None else inspect.Parameter.empty
self.is_optional = is_optional
@classmethod
def from_parameter(cls, param):
is_optional = False
annotation = param.annotation
if hasattr(annotation, '__origin__'):
if annotation.__origin__ is Union:
if type(None) in annotation.__args__:
is_optional = True
non_none_args = [arg for arg in annotation.__args__ if arg is not type(None)]
if len(non_none_args) == 1:
annotation = non_none_args[0]
return cls(
name=param.name,
annotation=annotation if annotation != inspect.Parameter.empty else Any,
kind=param.kind,
default=param.default,
is_optional=is_optional
)
@dataclass
class UriCallback:
"""Callback для URI обработчиков (как в CactusLib)"""
cell: Any # ChatMessageCell
message: MessageObject
method: str
raw_url: str
long_press: bool = False
def edit_message(self, text: str, **kwargs):
"""Редактирует сообщение"""
fragment = kwargs.pop("fragment", get_last_fragment())
# Будем использовать edit_message когда он определён ниже
from MSLib import edit_message as _edit_msg
_edit_msg(self.message, text, fragment=fragment, **kwargs)
if kwargs.get("markup", None) is None and self.message.messageOwner.reply_markup:
self.edit_markup()
edit = edit_message
def edit_markup(self, markup=None):
"""Редактирует Inline-клавиатуру"""
# Будем использовать edit_message_markup когда он определён ниже
from MSLib import edit_message_markup as _edit_markup
_edit_markup(self.cell, markup)
def delete_message(self):
"""Удаляет сообщение"""
dialog_id = self.message.getDialogId()
chat = get_messages_controller().getChat(-dialog_id)
if self.message.canDeleteMessage(
self.message.getChatMode() == 1,
chat
):
topic_id = self.message.getTopicId()
# Используем Requests когда он определён
Requests.delete_messages(
[self.message.getRealId()],
dialog_id,
lambda r, e: None
)
delete = delete_message
@dataclass
class Uri:
"""Класс для создания URI ссылок (tg://cactus/...)"""
plugin_id: str
command: str
kwargs: Dict[str, str]
@classmethod
def create(cls, plugin, cmd: str, **kwargs):
"""Создаёт Uri из plugin объекта"""
return cls(
plugin_id=plugin.id if hasattr(plugin, 'id') else str(plugin),
command=cmd,
kwargs=kwargs
)
def string(self) -> str:
"""Возвращает строку URI"""
base = f"tg://mslib/{self.plugin_id}/{self.command}"
if self.kwargs:
params = urlencode(self.kwargs)
return f"{base}?{params}"
return base
def __str__(self):
return self.string()
@dataclass
class MessageUri(Uri):
"""Класс для URI внутри сообщений (tg://mslibX/...)"""
def string(self) -> str:
"""Возвращает строку URI для сообщений"""
base = f"tg://mslibX/{self.plugin_id}/{self.command}"
if self.kwargs:
params = urlencode(self.kwargs)
return f"{base}?{params}"
return base
class Command:
def __init__(self, func, name, args=None, subcommands=None, error_handler=None, aliases=None, doc=None, enabled=None):
self.func = func
self.name = name
self.args = args if args is not None else []
self.subcommands = subcommands if subcommands is not None else {}
self.error_handler = error_handler
# Новые атрибуты из CactusLib
self.aliases = aliases if aliases is not None else []
self.doc = doc # Ключ в strings для описания команды
self.enabled = enabled # Ключ настройки или булево значение
def subcommand(self, name: str):
def decorator(func: Callable):
cmd = create_command(func, name)
self.subcommands[name] = cmd
return func
return decorator
def register_error_handler(self, func: Callable[[Any, int, Exception], HookResult]):
self.error_handler = func
return func
def add_alias(self, alias: str):
"""Добавляет алиас к команде"""
if alias not in self.aliases:
self.aliases.append(alias)
def remove_alias(self, alias: str):
"""Удаляет алиас из команды"""
if alias in self.aliases:
self.aliases.remove(alias)
def is_enabled(self, plugin_instance=None) -> bool:
"""Проверяет включена ли команда"""
if self.enabled is None:
return True
if isinstance(self.enabled, bool):
return self.enabled
if isinstance(self.enabled, str) and plugin_instance:
# Пытаемся получить настройку из плагина
try:
return plugin_instance.get_setting(self.enabled, True)
except Exception:
return True
return True
def get_subcommand(self, name: str) -> Optional['Command']:
"""Получает подкоманду по имени"""
return self.subcommands.get(name)
def has_subcommands(self) -> bool:
"""Проверяет есть ли подкоманды"""
return len(self.subcommands) > 0
def list_subcommands(self) -> List[str]:
"""Возвращает список имён подкоманд"""
return list(self.subcommands.keys())
def is_allowed_type(arg_type) -> bool:
if arg_type in ALLOWED_ARG_TYPES:
return True
if arg_type is type(None):
return True
origin = get_origin(arg_type)
if origin in ALLOWED_ORIGIN:
return all(is_allowed_type(t) for t in get_args(arg_type))
return False
def create_command(func: Callable, name: str) -> Command:
signature = inspect.signature(func)
parameters = list(signature.parameters.values())
return_type = signature.return_annotation
if len(parameters) < 2:
raise MissingRequiredArguments("Command must have 'param' variable as first argument and 'account' variable as second argument")