-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathmatrix_commander.py
executable file
·10298 lines (9698 loc) · 399 KB
/
matrix_commander.py
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
#!/usr/bin/env python3
r"""matrix_commander.py.
For help and documentation, please read the README.md file.
Online available at:
https://github.com/8go/matrix-commander/blob/master/README.md
"""
# 234567890123456789012345678901234567890123456789012345678901234567890123456789
# 000000001111111111222222222233333333334444444444555555555566666666667777777777
# automatically sorted by isort,
# then formatted by black --line-length 79
import argparse
import ast
import asyncio
import datetime
import errno
import getpass
import json
import logging
import os
import re # regular expression
import select
import shutil
import ssl
import subprocess
import sys
import tempfile
import textwrap
import time
import traceback
import urllib.request
import uuid
from importlib import metadata
from os import R_OK, access
from os.path import isfile
from ssl import SSLContext
from typing import Literal, Optional, Union
from urllib.parse import quote, urlparse
from uuid import uuid4
import aiofiles
import aiofiles.os
import emoji
import magic
from aiohttp import ClientConnectorError, ClientSession, TCPConnector, web
from markdown import markdown
from nio import (AsyncClient, AsyncClientConfig, BaseRoomKeyRequest,
ContentRepositoryConfigError, DeleteDevicesAuthResponse,
DeleteDevicesError, DevicesError, DiscoveryInfoError,
DownloadError, DummyEvent, EnableEncryptionBuilder,
EncryptedToDeviceEvent, EncryptionError, ErrorResponse, Event,
ForwardedRoomKeyEvent, InviteMemberEvent, JoinedMembersError,
JoinedRoomsError, JoinError, KeyVerificationAccept,
KeyVerificationCancel, KeyVerificationEvent,
KeyVerificationKey, KeyVerificationMac, KeyVerificationStart,
LocalProtocolError, LoginInfoError, LoginResponse,
LogoutError, MatrixRoom, MessageDirection, OlmEvent,
PresenceGetError, PresenceSetError, ProfileGetAvatarResponse,
ProfileGetDisplayNameError, ProfileGetError,
ProfileSetAvatarResponse, ProfileSetDisplayNameError,
RedactedEvent, RedactionEvent, RoomAliasEvent, RoomBanError,
RoomCreateError, RoomDeleteAliasResponse, RoomEncryptedAudio,
RoomEncryptedFile, RoomEncryptedImage, RoomEncryptedMedia,
RoomEncryptedVideo, RoomEncryptionEvent, RoomForgetError,
RoomGetStateResponse, RoomGetVisibilityResponse,
RoomInviteError, RoomKeyEvent, RoomKeyRequest,
RoomKeyRequestCancellation, RoomKickError, RoomLeaveError,
RoomMemberEvent, RoomMessage, RoomMessageAudio,
RoomMessageEmote, RoomMessageFile, RoomMessageFormatted,
RoomMessageImage, RoomMessageMedia, RoomMessageNotice,
RoomMessagesError, RoomMessageText, RoomMessageUnknown,
RoomMessageVideo, RoomNameEvent, RoomPreset,
RoomPutAliasResponse, RoomReadMarkersError, RoomRedactError,
RoomResolveAliasError, RoomResolveAliasResponse,
RoomSendError, RoomUnbanError, RoomVisibility, SyncError,
SyncResponse, ToDeviceError, ToDeviceEvent, ToDeviceMessage,
UnknownEvent, UnknownToDeviceEvent, UpdateDeviceError,
UploadError, UploadResponse, crypto, responses)
from PIL import Image
from xdg import BaseDirectory
try:
import notify2
HAVE_NOTIFY = True
except ImportError:
HAVE_NOTIFY = False
try:
from nio import GetOpenIDTokenError
HAVE_OPENID = True
except ImportError:
HAVE_OPENID = False
# version number
VERSION = "2024-11-21"
VERSIONNR = "8.0.4"
# matrix-commander; for backwards compitability replace _ with -
PROG_WITHOUT_EXT = os.path.splitext(os.path.basename(__file__))[0].replace(
"_", "-"
)
# matrix-commander.py; for backwards compitability replace _ with -
PROG_WITH_EXT = os.path.basename(__file__).replace("_", "-")
# file to store credentials in case you want to run program multiple times
CREDENTIALS_FILE_DEFAULT = "credentials.json" # login credentials JSON file
# e.g. ~/.config/matrix-commander/
CREDENTIALS_DIR_LASTRESORT = os.path.expanduser(
BaseDirectory.xdg_config_home + "/" # "~/.config/"
) + os.path.splitext(os.path.basename(__file__))[0].replace("_", "-")
# directory to be used by end-to-end encrypted protocol for persistent storage
STORE_DIR_DEFAULT = "./store/"
# e.g. ~/.local/share/matrix-commander/
# the STORE_PATH_LASTRESORT will be concatenated with a directory name
# like store to result in a final path of
# e.g. ~/.local/share/matrix-commander/store/ as actual persistent store dir
STORE_PATH_LASTRESORT = os.path.normpath(
(
os.path.expanduser(
BaseDirectory.xdg_data_home + "/"
) # ~/.local/share/
+ os.path.splitext(os.path.basename(__file__))[0].replace("_", "-")
)
)
# e.g. ~/.local/share/matrix-commander/store/
STORE_DIR_LASTRESORT = os.path.normpath(
(os.path.expanduser(STORE_PATH_LASTRESORT + "/" + STORE_DIR_DEFAULT))
)
# directory to be used for downloading media files
MEDIA_DIR_DEFAULT = "./media/"
# usually there are no permissions for using: /run/matrix-commander.pid
# so instead local files like ~/.run/matrix-commander.some-uuid-here.pid will
# be used for storing the PID(s) for sending signals.
# There might be more than 1 process running in parallel, so there might be
# more than 1 PID at a given point in time.
PID_DIR_DEFAULT = os.path.normpath(os.path.expanduser("~/.run/"))
PID_FILE_DEFAULT = os.path.normpath(
PID_DIR_DEFAULT + "/" + PROG_WITHOUT_EXT + "." + str(uuid.uuid4()) + ".pid"
)
DEFAULT_LOG_LEVEL_LOWER_MODULE = logging.WARNING
# verification type, wait for incoming verification request
VERIFY_EMOJI = "emoji"
# verification type, send an outgoing verification request
VERIFY_EMOJI_REQ = "emojireq"
VERIFY_MANUAL = "manual" # verification type
VERIFY_DEFAULT = VERIFY_EMOJI
PRINT = "print" # version type
CHECK = "check" # version type
ONCE = "once" # listening type
NEVER = "never" # listening type
FOREVER = "forever" # listening type
ALL = "all" # listening type
TAIL = "tail" # listening type
DEFAULT_SEPARATOR = " " # used for sperating columns in print outputs
SEP = DEFAULT_SEPARATOR
LISTEN_DEFAULT = NEVER
TAIL_UNUSED_DEFAULT = 0 # get 0 if --tail is not specified
TAIL_USED_DEFAULT = 10 # get the last 10 msgs by default with --tail
VERIFY_UNUSED_DEFAULT = None # use None if --verify is not specified
VERIFY_USED_DEFAULT = VERIFY_DEFAULT # use 'emoji' by default with --verify
VERSION_UNUSED_DEFAULT = None # use None if --version is not specified
VERSION_USED_DEFAULT = PRINT # use 'print' by default with --version
SET_DEVICE_NAME_UNUSED_DEFAULT = None # use None if option is not specified
SET_DISPLAY_NAME_UNUSED_DEFAULT = None # use None option not used
NO_SSL_UNUSED_DEFAULT = None # use None if --no-ssl is not given
SSL_CERTIFICATE_DEFAULT = None # use None if --ssl-certificate is not given
MXC_ID_PLACEHOLDER = "__mxc_id__"
HOMESERVER_PLACEHOLDER = "__homeserver__" # like https://matrix.example.org
HOSTNAME_PLACEHOLDER = "__hostname__" # like matrix.example.org
ACCESS_TOKEN_PLACEHOLDER = "__access_token__"
USER_ID_PLACEHOLDER = "__user_id__" # like @ mc: matrix.example.com
DEVICE_ID_PLACEHOLDER = "__device_id__"
ROOM_ID_PLACEHOLDER = "__room_id__"
SYNC_FULL = "full" # sync with full_state=True for send actions
# SYNC_PARTIAL = "full" # sync with full_state=False for send actions
SYNC_OFF = "off" # no sync is done for send actions
SYNC_DEFAULT = SYNC_FULL
# text, intended for human consumption
OUTPUT_TEXT = "text"
# json, as close to as what NIO API provides, a few convenient fields added
# transport_response removed
OUTPUT_JSON = "json"
# json-max, json format, like "json" but with transport_response object added
OUTPUT_JSON_MAX = "json-max"
# json-spec, json format, if and only if output adheres 100% to Matrix
# Specification will the data be printed. Currently, only --listen (--tail)
# adhere to Spec and hence print a JSON object. All other print nothing.
OUTPUT_JSON_SPEC = "json-spec"
OUTPUT_DEFAULT = OUTPUT_TEXT
# source, use media file name as provided by sender
MEDIA_NAME_SOURCE = "source"
# clean up source name. Use source name but with unusual chars replaced with _
MEDIA_NAME_CLEAN = "clean"
# ignore source provided name, use event-id as media file name
# Looks like this $rsad57dafs57asfag45gsFjdTXW1dsfroBiO2IsidKk'
MEDIA_NAME_EVENTID = "eventid"
# ignore source provided name, use current time at receiver as media file name
# Looks like this '20231012_152234_266600', date_time_microseconds
MEDIA_NAME_TIME = "time"
# defaults to "clean"
MEDIA_NAME_DEFAULT = MEDIA_NAME_CLEAN
# chars allowed in a clean name: alphanumerical and these
MEDIA_NAME_CLEAN_CHARS = "._- ~$"
# location of README.md file if it is not found on local harddisk
# used for --manual
README_FILE_RAW_URL = (
"https://raw.githubusercontent.com/8go/matrix-commander/master/README.md"
)
INVITES_LIST = "list"
INVITES_JOIN = "join"
INVITES_LIST_JOIN = "list+join"
INVITES_UNUSED_DEFAULT = None # use None if --room-invites is not specified
INVITES_USED_DEFAULT = (
INVITES_LIST # use 'list' by default with --room-invites
)
# increment this number and use new incremented number for next warning
# last unique Wxxx warning number used: W114:
# increment this number and use new incremented number for next error
# last unique Exxx error number used: E258:
class LooseVersion:
"""Version numbering and comparison.
See https://github.com/effigies/looseversion/blob/main/looseversion.py.
Argument 'other' must be of type LooseVersion.
"""
component_re = re.compile(r"(\d+ | [a-z]+ | \.)", re.VERBOSE)
def __init__(self, vstring=None):
if vstring:
self.parse(vstring)
def __eq__(self, other):
return self._cmp(other) == 0
def __lt__(self, other):
return self._cmp(other) < 0
def __le__(self, other):
return self._cmp(other) <= 0
def __gt__(self, other):
return self._cmp(other) > 0
def __ge__(self, other):
return self._cmp(other) >= 0
def parse(self, vstring):
self.vstring = vstring
components = [
x for x in self.component_re.split(vstring) if x and x != "."
]
for i, obj in enumerate(components):
try:
components[i] = int(obj)
except ValueError:
pass
self.version = components
def __str__(self):
return self.vstring
def __repr__(self):
return "LooseVersion ('%s')" % str(self)
def _cmp(self, other):
if self.version == other.version:
return 0
if self.version < other.version:
return -1
if self.version > other.version:
return 1
class MatrixCommanderError(Exception):
pass
class MatrixCommanderWarning(Warning):
pass
class GlobalState:
"""Keep global variables.
Trivial class to help keep some global state.
"""
def __init__(self):
"""Store global state."""
self.log: logging.Logger = None # logger object
self.pa: argparse.Namespace = None # parsed arguments
# to which logic (message, image, audio, file, event) is
# stdin pipe assigned?
self.stdin_use: str = "none"
# 1) ssl None means default SSL context will be used.
# 2) ssl False means SSL certificate validation will be skipped
# 3) ssl a valid SSLContext means that the specified context will be
# used. This is useful to using local SSL certificate.
self.ssl: Union[None, SSLContext, bool] = None
self.client: Union[None, AsyncClient] = None
self.credentials: Union[None, dict] = None
self.send_action = False # argv contains send action
self.listen_action = False # argv contains listen action
self.room_action = False # argv contains room action
self.set_action = False # argv contains set action
self.get_action = False # argv contains get action
self.setget_action = False # argv contains set or get action
self.err_count = 0 # how many errors have occurred so far
self.warn_count = 0 # how many warnings have occurred so far
# Convert None to "", useful when reporting values to stdout
# Should only be called with a) None or b) a string.
# We want to avoid situation where we would print: name = None
def zn(str):
return str or ""
def get_qualifiedclassname(obj):
klass = obj.__class__
module = klass.__module__
if module == "builtins":
return klass.__qualname__ # avoid outputs like 'builtins.str'
return module + "." + klass.__qualname__
def privacy_filter(dirty: str) -> str:
"""Remove private info from string"""
# homeserver = urlparse(gs.credentials["homeserver"])
# server_name = homeserver.netloc
# clean = dirty.replace(server_name, "your.homeserver.org")
return dirty.replace(gs.credentials["access_token"], "***")
def print_output(
option: Literal["text", "json", "json-max", "json-spec"],
*,
text: str,
json_: dict = None,
json_max: dict = None,
json_spec: dict = None,
) -> None:
"""Print output according to which option is specified with --output"""
# json_ has the underscore to avoid a name clash with the module json
results = {
OUTPUT_TEXT: text,
OUTPUT_JSON: json_,
OUTPUT_JSON_MAX: json_max,
OUTPUT_JSON_SPEC: json_spec,
}
if results[option] is None:
if option == OUTPUT_JSON_SPEC:
gs.log.debug(
"Are you sure you wanted to use --output json-spec? "
"Most outputs will be empty."
)
return
if option == OUTPUT_TEXT:
print(results[option], flush=True)
elif option == OUTPUT_JSON_SPEC:
print(json.dumps(results[option]), flush=True)
else: # OUTPUT_JSON or OUTPUT_JSON_MAX
print(json.dumps(results[option], default=obj_to_dict), flush=True)
def obj_to_dict(obj):
"""Return dict of object
Useful for json.dump() dict-to-json conversion.
"""
if gs.pa.verbose > 1: # 2+
gs.log.debug(f"obj_to_dict: {obj.__class__}")
gs.log.debug(f"obj_to_dict: {obj.__class__.__name__}")
gs.log.debug(f"obj_to_dict: {get_qualifiedclassname(obj)}")
# summary: shortcut: just these 2: RequestInfo and ClientResponse
# if get_qualifiedclassname(obj) == "aiohttp.client_reqrep.RequestInfo":
# return {obj.__class__.__name__: str(obj)}
# if get_qualifiedclassname(obj) == "aiohttp.client_reqrep.ClientResponse":
# return {obj.__class__.__name__: str(obj)}
# details, one by one:
# if get_qualifiedclassname(obj) == "collections.deque":
# return {obj.__class__.__name__: str(obj)}
# if get_qualifiedclassname(obj) == "aiohttp.helpers.TimerContext":
# return {obj.__class__.__name__: str(obj)}
# if get_qualifiedclassname(obj) == "asyncio.events.TimerHandle":
# return {obj.__class__.__name__: str(obj)}
# if get_qualifiedclassname(obj) =="multidict._multidict.CIMultiDictProxy":
# return {obj.__class__.__name__: str(obj)}
# if get_qualifiedclassname(obj) == "aiosignal.Signal":
# return {obj.__class__.__name__: str(obj)}
# this one is crucial, it make the serialization circular reference.
if get_qualifiedclassname(obj) == "aiohttp.streams.StreamReader":
return {obj.__class__.__name__: str(obj)}
# these four are crucial, they make the serialization circular reference.
if (
get_qualifiedclassname(obj)
== "asyncio.unix_events._UnixSelectorEventLoop"
):
return {obj.__class__.__name__: str(obj)}
if get_qualifiedclassname(obj) == "aiohttp.tracing.Trace":
return {obj.__class__.__name__: str(obj)}
if get_qualifiedclassname(obj) == "aiohttp.tracing.TraceConfig":
return {obj.__class__.__name__: str(obj)}
# avoid "keys must be str, int, float, bool or None" errors
if get_qualifiedclassname(obj) == "aiohttp.connector.TCPConnector":
return {obj.__class__.__name__: str(obj)}
if hasattr(obj, "__dict__"):
if (
"inbound_group_store" in obj.__dict__
and "session_store" in obj.__dict__
and "outbound_group_sessions" in obj.__dict__
):
# "olm" is hige, 1MB+, 20K lines of JSON
# grab only some items
# "olm": {
# "user_id": "@xxx:xxx.xxx.xxx",
# "device_id": "xxx",
# "uploaded_key_count": 50,
# "users_for_key_query": {
# "set": "..."
# },
# "device_store": {
# ... want
# },
# "session_store": {
# ... dont want, too long
# },
# "inbound_group_store": {
# ... dont want, 20K lines, too long
# },
# "outbound_group_sessions": {},
# "tracked_users": {
# "set": "set()"
# },
dictcopy = {}
for key in [
"user_id",
"device_id",
"uploaded_key_count",
"users_for_key_query",
"device_store",
"outbound_group_sessions",
"tracked_users",
"outgoing_key_requests",
"received_key_requests",
"key_requests_waiting_for_session",
"key_request_devices_no_session",
"key_request_from_untrusted",
"wedged_devices",
"key_re_requests_events",
"key_verifications",
"outgoing_to_device_messages",
"message_index_store",
"store",
]:
dictcopy.update({key: obj.__dict__[key]})
if gs.pa.verbose > 1: # 2+
gs.log.debug(
f"{obj} is not serializable, simplifying to {dictcopy}."
)
return dictcopy
if gs.pa.verbose > 1: # 2+
gs.log.debug(
f"{obj} is not serializable, using its available dictionary "
f"{obj.__dict__}."
)
return obj.__dict__
else:
# gs.log.debug(
# f"Object {obj} ({type(obj)}) has no class dictionary. "
# "Cannot be converted to JSON object. "
# "Will be converted to JSON string."
# )
# simple types like yarl.URL do not have a __dict__
# get the class name as string, create a dict with classname and value
if gs.pa.verbose > 1: # 2+
gs.log.debug(
f"{obj} is not serializable, simplifying to key value pair "
f"key '{obj.__class__.__name__}' and value '{str(obj)}'."
)
return {obj.__class__.__name__: str(obj)}
def choose_available_filename(filename):
"""Return next available filename.
If filename (includes path) does not exist,
then it returns filename. If file already
exists it adds a counter at end, before
extension, and increases counter until it
finds a filename that does not yet exist.
This avoids overwritting files when sources
have same name.
"""
if os.path.exists(filename):
try:
start, ext = filename.rsplit(".", 1)
except ValueError:
start, ext = (filename, "")
i = 0
while os.path.exists(f"{start}_{i}.{ext}"):
i += 1
return f"{start}_{i}.{ext}"
else:
return filename
def derive_media_filename_with_path(event):
"""Derive file name under which to store a given media file.
Depending on --download-media-name derive the corresponding file
name under which to store the downloaded media file. Note that
the file name giveb be the source, i.e. the sender, cannot be trusted.
The source can specify and provide any string, even invalid file
names or names containing backslash or slash and similar.
Adds path as given in --download-media to file name.
As last step function adds a sequential number, iff necessary, to assure
that the file does not yet exist and that no file is overwritten
(if multiple media files have the same name).
"""
method = gs.pa.download_media_name
if method == MEDIA_NAME_SOURCE:
newfn = event.body
elif method == MEDIA_NAME_EVENTID:
newfn = event.event_id
elif method == MEDIA_NAME_TIME:
# e.g. '20231012_152234_266600' (YYYYMMDD_HHMMSS_MICROSECONDS)
newfn = "{date:%Y%m%d_%H%M%S_%f}".format(date=datetime.datetime.now())
else:
# event.body is not trustworthy
# and can contain garbage characters
# such as / or \ which will cause file open
# to fail. Replace those.
newfn = "".join(
[
x if (x.isalnum() or x in MEDIA_NAME_CLEAN_CHARS) else "_"
for x in event.body
]
)
gs.log.debug(f"Media file name method is: {method}")
gs.log.debug(f"New file name for media is: {newfn}")
filename_with_path = choose_available_filename(
os.path.join(gs.pa.download_media, newfn)
)
gs.log.debug(
f"Unique file name for media with path is: {filename_with_path}"
)
return filename_with_path
async def synchronize(client: AsyncClient) -> SyncResponse:
"""Synchronize with server, e.g. in order to get rooms.
Arguments:
---------
client : Client
Returns: None
Raises exception on error.
"""
try:
resp = await client.sync(timeout=10000, full_state=True)
except ClientConnectorError as e:
err = (
"E100: "
"sync() failed. Do you have connectivity to internet? "
f"ClientConnectorError {e}"
)
raise MatrixCommanderError(err) from e
except Exception as e:
err = "E101: " f"sync() failed. Exception {e}"
raise MatrixCommanderError(err) from e
if isinstance(resp, SyncError):
err = "E102: " f"sync failed with resp = {privacy_filter(str(resp))}"
raise MatrixCommanderError(err) from None
return resp
async def download_mxc(
client: AsyncClient, mxc: str, filename: Optional[str] = None
):
"""Download MXC resource.
Arguments:
---------
client : Client
mxc : str
string representing URL like mxc://matrix.org/someRandomKey
filename : str
optional name of file for storing download
"""
nio_version = metadata.version("matrix-nio")
# version incompatibility between matrix-nio 0.19.0 and 0.20+
# https://matrix.example.com/Abc123
# server_name = "matrix.example.com"
# media_id = "Abc123"
# matrix-nio v0.19.0 has: download(server_name: str, media_id: str, ..)
# convert mxc to server_name and media_id
# v0.20+ : resp = await client.download(mxc=mxc, filename=filename)
# v0.19- : resp = await client.download(
# server_name=server_name, media_id=media_id,
# filename=filename)
gs.log.debug(f"download_mxc input mxc is {mxc}.")
if nio_version.startswith("0.1"): # like 0.19
gs.log.info(
f"You are running matrix-nio version {nio_version}. "
"You should be running version 0.20+. Update if necessary. "
)
url = urlparse(mxc)
gs.log.debug(f"download_mxc input url is {url}.")
response = await client.download(
server_name=url.netloc,
media_id=url.path.strip("/"),
filename=filename,
)
else:
gs.log.debug(
f"You are running matrix-nio version {nio_version}. Great!"
)
response = await client.download(mxc=mxc, filename=filename)
gs.log.debug(f"download_mxc response is {response}.")
return response
class Callbacks(object):
"""Class to pass client to callback methods."""
def __init__(self, client):
"""Store AsyncClient."""
self.client = client
async def invite_callback(self, room, event):
"""Handle an incoming invite event.
If an invite is received, then list or join the room specified
in the invite.
"""
try:
gs.log.debug(
f"invite_callback(): for room {room} received this "
f"event: type: {type(event)}, "
f"event: {event}"
)
# There are MULTIPLE events received!
# event 1:
# InviteMemberEvent(source={'type': 'm.room.member',
# 'state_key': '@jane:matrix.example.com',
# 'sender': '@jane:matrix.example.com'},
# sender='@jane:matrix.example.com',
# state_key='@jane:matrix.example.com',
# membership='join',
# prev_membership=None,
# content={'membership': 'join', 'displayname': 'M',
# 'avatar_url': '...'}, prev_content=None)
# event 2:
# InviteMemberEvent(source={'type': 'm.room.member',
# 'sender': '@jane:matrix.example.com',
# 'state_key': '@john:matrix.example.com',
# 'origin_server_ts': 1681986390778,
# 'unsigned': {'replaces_state': '$xxx',
# 'prev_content': {'membership': 'leave'},
# 'prev_sender': '@john:matrix.example.com', 'age': 13037},
# 'event_id': 'xxx'},
# sender='@jane:matrix.example.com',
# state_key='@john:matrix.example.com',
# membership='invite',
# prev_membership='leave',
# content={'membership': 'invite', 'displayname': 'bot',
# 'avatar_url': 'xxx'}, prev_content={'membership': 'leave'})
gs.log.debug(
f"Got invite event for room {room.room_id} from "
f"{event.sender}. "
f"Event shows membership as '{event.membership}'."
)
if event.membership == "invite":
gs.log.debug(
"Event will be processed because it shows "
f"membership as '{event.membership}'."
)
# list
if (
gs.pa.room_invites == INVITES_LIST
or gs.pa.room_invites == INVITES_LIST_JOIN
):
# output format controlled via --output flag
text = (
f"{room.room_id}{SEP}m.room.member"
f"{SEP}{event.membership}"
)
# we use the dictionary.
json_max = {"room_id": room.room_id}
json_max.update({"event": "m.room.member"})
json_max.update({"membership": event.membership})
json_ = json_max.copy()
json_spec = None
print_output(
gs.pa.output,
text=text,
json_=json_,
json_max=json_max,
json_spec=json_spec,
)
# join
if (
gs.pa.room_invites == INVITES_JOIN
or gs.pa.room_invites == INVITES_LIST_JOIN
):
result = await self.client.join(room.room_id)
if isinstance(result, JoinError):
gs.log.error(
f"E249: Error joining room {room.room_id}: "
f"{result.message}",
)
gs.err_count += 1
else:
# Successfully joined room
gs.log.info(
f"Joined room {room.room_id} successfully."
)
else:
gs.log.debug(
"Event will be skipped because it shows "
f"membership as '{event.membership}'."
)
except BaseException:
gs.log.debug("Here is the traceback.\n" + traceback.format_exc())
# according to pylama: function too complex: C901 # noqa: C901
async def message_callback(self, room: MatrixRoom, event): # noqa: C901
"""Handle all events of type RoomMessage.
Includes events like RoomMessageText, RoomMessageImage, etc.
"""
try:
gs.log.debug(
f"message_callback(): for room {room} received this "
f"event: type: {type(event)}, event_id: {event.event_id}, "
f"event: {event}"
)
if not gs.pa.listen_self:
if event.sender == self.client.user:
try:
gs.log.debug(
f"Skipping message sent by myself: {event.body}"
)
except AttributeError: # does not have .body
gs.log.debug(
f"Skipping message sent by myself: {event}"
)
return
# millisec since 1970
gs.log.debug(f"event.server_timestamp = {event.server_timestamp}")
timestamp = datetime.datetime.fromtimestamp(
int(event.server_timestamp / 1000)
) # sec since 1970
event_datetime = timestamp.strftime("%Y-%m-%d %H:%M:%S")
# e.g. 2020-08-06 17:30:18
gs.log.debug(f"event_datetime = {event_datetime}")
if isinstance(event, RoomMessageMedia): # for all media events
mxc = event.url # media mxc
url = await self.client.mxc_to_http(mxc) # media url
gs.log.debug(f"HTTP URL of media is : {url}")
msg_url = " [" + url + "]"
if gs.pa.download_media != "":
# download unencrypted/plain media file
resp = await download_mxc(self.client, mxc)
if isinstance(resp, DownloadError):
gs.log.error(
"E105: "
f"download of URI '{mxc}' to local file "
f"failed with response {privacy_filter(str(resp))}"
)
gs.err_count += 1
msg_url += " [Download of media file failed]"
else:
media_data = resp.body
filename = derive_media_filename_with_path(event)
async with aiofiles.open(filename, "wb") as f:
await f.write(media_data)
# Set atime and mtime of file to event timestamp
os.utime(
filename,
ns=((event.server_timestamp * 1000000,) * 2),
)
msg_url += f" [Downloaded media file to {filename}]"
if isinstance(event, RoomEncryptedMedia): # for all e2e media
mxc = event.url # media mxc
url = await self.client.mxc_to_http(mxc) # media url
gs.log.debug(f"HTTP URL of media is : {url}")
msg_url = " [" + url + "]"
if gs.pa.download_media != "":
# download encrypted media file
resp = await download_mxc(self.client, mxc)
if isinstance(resp, DownloadError):
gs.log.error(
"E106: "
f"download of URI '{mxc}' to local file "
f"failed with response {privacy_filter(str(resp))}"
)
gs.err_count += 1
msg_url += " [Download of media file failed]"
else:
media_data = resp.body
filename = derive_media_filename_with_path(event)
async with aiofiles.open(filename, "wb") as f:
await f.write(
crypto.attachments.decrypt_attachment(
media_data,
event.source["content"]["file"]["key"][
"k"
],
event.source["content"]["file"]["hashes"][
"sha256"
],
event.source["content"]["file"]["iv"],
)
)
# Set atime and mtime of file to event timestamp
os.utime(
filename,
ns=((event.server_timestamp * 1000000,) * 2),
)
msg_url += (
" [Downloaded and decrypted media "
f"file to {filename}]"
)
if isinstance(event, RoomMessageAudio):
msg = "Received audio: " + event.body + msg_url
elif isinstance(event, RoomMessageEmote):
msg = "Received emote: " + event.body
elif isinstance(event, RoomMessageFile):
msg = "Received file: " + event.body + msg_url
elif isinstance(event, RoomMessageFormatted):
msg = event.body
elif isinstance(event, RoomMessageImage):
# Usually body is something like "image.svg"
msg = "Received image: " + event.body + msg_url
elif isinstance(event, RoomMessageNotice):
msg = event.body # Extract the message text
elif isinstance(event, RoomMessageText):
msg = event.body # Extract the message text
elif isinstance(event, RoomMessageUnknown):
msg = "Received room message of unknown type: " + event.msgtype
elif isinstance(event, RoomMessageVideo):
msg = "Received video: " + event.body + msg_url
elif isinstance(event, RoomEncryptedAudio):
msg = "Received encrypted audio: " + event.body + msg_url
elif isinstance(event, RoomEncryptedFile):
msg = "Received encrypted file: " + event.body + msg_url
elif isinstance(event, RoomEncryptedImage):
# Usually body is something like "image.svg"
msg = "Received encrypted image: " + event.body + msg_url
elif isinstance(event, RoomEncryptedVideo):
msg = "Received encrypted video: " + event.body + msg_url
elif isinstance(event, RoomMessageMedia):
# this should never be reached, this is a base class
# it should be a audio, image, video, etc.
# Put here at the end as defensive programming
msg = "Received media: " + event.body + msg_url
elif isinstance(event, RoomEncryptedMedia):
# this should never be reached, this is a base class
# it should be a audio, image, video, etc.
# Put here at the end as defensive programming
msg = "Received encrypted media: " + event.body + msg_url
elif isinstance(event, RoomMemberEvent):
msg = (
"Received room-member event: "
f"sender: {event.sender}, operation: {event.membership}"
)
elif isinstance(event, RoomEncryptionEvent):
msg = (
"Received room-encryption event: "
f"sender: {event.sender}"
)
elif isinstance(event, RoomAliasEvent):
msg = (
"Received room-alias event: sender: "
f"{event.sender}, alias: {event.canonical_alias}"
)
elif isinstance(event, RoomNameEvent):
msg = (
"Received room-name event: sender: "
f"{event.sender}, room name: {event.name}"
)
elif isinstance(event, RedactedEvent):
msg = (
"Received redacted event: "
f"sender: {event.sender}, "
f"type: {event.type}, redacter: {event.redacter}"
)
elif isinstance(event, RedactionEvent):
msg = (
"Received redaction event: "
f"sender: {event.sender}, "
f"redacts: {event.redacts}"
)
elif isinstance(event, UnknownEvent):
if event.type == "m.reaction":
msg = (
"Received a reaction, an emoji: "
f"{event.source['content']['m.relates_to']['key']}"
)
else:
msg = f"Received unknown event: {event}"
else:
msg = f"Received unknown event: {event}"
# if event['type'] == "m.room.message":
# if event['content']['msgtype'] == "m.text":
# content = event['content']['body']
# else:
# download_url = api.get_download_url(
# event['content']['url'])
# content = download_url
# else:
# content = "\n{{ " + event['type'] + " event }}\n"
gs.log.debug(f"type(msg) = {type(msg)}. msg is a string")
sender_nick = room.user_name(event.sender)
if not sender_nick: # convert @foo:mat.io into foo
sender_nick = user_id_to_short_user_name(event.sender)
room_nick = room.display_name
if room_nick in (None, "", "Empty Room"):
room_nick = "Undetermined"
if gs.pa.print_event_id:
event_id_detail = f" | {event.event_id}"
else:
event_id_detail = ""
# Prevent faking messages by prefixing each line of a multiline
# message with space.
fixed_msg = re.sub("\n", "\n ", msg)
complete_msg = (
"Message received for room "
f"{room_nick} [{room.room_id}] | "
f"sender {sender_nick} "
f"[{event.sender}] | {event_datetime}"
f"{event_id_detail} | {fixed_msg}"
)
gs.log.debug(complete_msg)
# output format controlled via --output flag
text = complete_msg # print the received message
json_ = {"source": event.source}
json_.update({"room": room})
json_.update({"room_display_name": room.display_name})
json_.update({"sender_nick": sender_nick})
json_.update({"event_datetime": event_datetime})
json_max = event.__dict__
json_max.update({"room": room})
json_max.update({"room_display_name": room.display_name})
json_max.update({"sender_nick": sender_nick})
json_max.update({"event_datetime": event_datetime})
json_spec = event.source
print_output(
gs.pa.output,
text=text,
json_=json_,
json_max=json_max,
json_spec=json_spec,
)
if gs.pa.os_notify:
avatar_url = await get_avatar_url(self.client, event.sender)
notify(
f"From {room.user_name(event.sender)}",
msg[:160],
avatar_url,
)
except BaseException:
gs.log.debug("Here is the traceback.\n" + traceback.format_exc())
# according to linter: function is too complex, C901
async def to_device_callback(self, event): # noqa: C901
"""Handle events sent to device."""
gs.log.debug(f"to_device_callback(): {event}")
# Added Aug 2024, see
# https://matrix-nio.readthedocs.io/en/latest/nio.html#nio.Client.get_active_key_requests