Matridge 0.2.0a0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
matridge/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ # import everything for automatic subclasses discovery by slidge core
2
+
3
+ from . import command, contact, gateway, group, session
4
+
5
+ __all__ = "session", "gateway", "contact", "group", "command"
matridge/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from slidge import entrypoint
2
+
3
+ if __name__ == "__main__":
4
+ entrypoint("matridge")
matridge/command.py ADDED
@@ -0,0 +1,176 @@
1
+ from typing import Union
2
+
3
+ import nio
4
+ from nio.crypto import OlmDevice, TrustState
5
+ from slidge.command import Command, CommandAccess, Form, FormField, TableResult
6
+ from slidge.command.base import FormValues
7
+ from slixmpp.exceptions import XMPPError
8
+
9
+ from .group import MUC
10
+ from .session import Session
11
+
12
+
13
+ class ListSpaces(Command):
14
+ NAME = "Matrix spaces"
15
+ CHAT_COMMAND = NODE = "spaces"
16
+ HELP = "List the matrix spaces you're part of"
17
+ ACCESS = CommandAccess.USER_LOGGED
18
+
19
+ async def run(self, session: Session, _ifrom, *args: str) -> Form: # type:ignore
20
+ spaces = list[nio.MatrixRoom]()
21
+ for room in session.matrix.rooms.values():
22
+ if room.children:
23
+ spaces.append(room)
24
+ spaces = sorted(spaces, key=lambda r: r.name)
25
+ return Form(
26
+ title=self.NAME,
27
+ instructions="Choose a space to list its children rooms. "
28
+ "NB: as of now, you can also see rooms that you are a member of.",
29
+ handler=self.finish, # type:ignore
30
+ handler_args=(spaces,),
31
+ fields=[
32
+ FormField(
33
+ "space",
34
+ label="Matrix space",
35
+ type="list-single",
36
+ options=[
37
+ {"label": room.display_name, "value": str(i)}
38
+ for i, room in enumerate(spaces)
39
+ ],
40
+ )
41
+ ],
42
+ )
43
+
44
+ @staticmethod
45
+ async def finish(
46
+ form_values: FormValues,
47
+ session: Session,
48
+ _ifrom,
49
+ rooms: list[nio.MatrixRoom],
50
+ ):
51
+ space = rooms[int(form_values["space"])] # type:ignore
52
+ mucs = list[MUC]()
53
+ for room_id in space.children:
54
+ try:
55
+ mucs.append(await session.bookmarks.by_legacy_id(room_id))
56
+ except XMPPError:
57
+ continue
58
+
59
+ mucs = sorted(mucs, key=lambda muc: muc.name)
60
+ return TableResult(
61
+ fields=[FormField("name"), FormField("jid", type="jid-single")],
62
+ description=f"Rooms of '{space.display_name}'",
63
+ jids_are_mucs=True,
64
+ items=[{"name": muc.name, "jid": str(muc.jid)} for muc in mucs],
65
+ )
66
+
67
+
68
+ class ManageTrust(Command):
69
+ NAME = "Manage trust"
70
+ CHAT_COMMAND = NODE = "verify"
71
+ HELP = "Manage which OLM keys you trust or not."
72
+ ACCESS = CommandAccess.USER_LOGGED
73
+
74
+ HUMAN_STATES = {0: "unset", 1: "verified", 2: "blacklisted", 3: "ignored"}
75
+
76
+ def __human_device(self, d: OlmDevice, state=True):
77
+ r = f"{d.ed25519} of {d.user_id}"
78
+ if state:
79
+ return r + f" ({self.HUMAN_STATES[d.trust_state.value]})"
80
+ return r
81
+
82
+ async def run(
83
+ self,
84
+ session: Session, # type:ignore
85
+ _ifrom,
86
+ *args: str,
87
+ ) -> Union[Form, str]:
88
+ devices = list[OlmDevice](session.matrix.olm.device_store)
89
+ device_dict = {d.id: d for d in devices}
90
+
91
+ # this part if for chat commands only
92
+ if args:
93
+ if args[0] == "all":
94
+ return await self.step2(
95
+ {
96
+ "device": list(device_dict.keys()), # type:ignore
97
+ "new_state": "verified",
98
+ },
99
+ session,
100
+ None,
101
+ device_dict,
102
+ )
103
+
104
+ else:
105
+ return await self.step2(
106
+ {"device": args[0].upper(), "new_state": "verified"},
107
+ session,
108
+ None,
109
+ device_dict,
110
+ )
111
+
112
+ return Form(
113
+ title=self.NAME,
114
+ instructions="Choose the session(s) which trust state you want to change",
115
+ handler=self.step2, # type:ignore
116
+ handler_args=(device_dict,),
117
+ fields=[
118
+ FormField(
119
+ "device",
120
+ label="Device(s)",
121
+ type="list-multi",
122
+ options=[
123
+ {"label": self.__human_device(d), "value": d.id}
124
+ for d in devices
125
+ ],
126
+ ),
127
+ FormField(
128
+ "new_state",
129
+ label="What new status do you want to give the selected devices?",
130
+ type="list-single",
131
+ options=[
132
+ {"label": v, "value": v} for v in self.HUMAN_STATES.values()
133
+ ],
134
+ ),
135
+ ],
136
+ )
137
+
138
+ async def step2(
139
+ self,
140
+ form_values: FormValues,
141
+ session: Session,
142
+ _ifrom,
143
+ devices: dict[str, OlmDevice],
144
+ ):
145
+ new_state = form_values["new_state"]
146
+ matrix = session.matrix
147
+ result = ""
148
+ for device_name in form_values["device"]: # type:ignore
149
+ device = devices[device_name]
150
+ change = False
151
+ if new_state == "unset":
152
+ if device.trust_state == TrustState.verified:
153
+ change = matrix.unverify_device(device)
154
+ elif device.trust_state == TrustState.ignored:
155
+ change = matrix.unignore_device(device)
156
+ elif device.trust_state == TrustState.blacklisted:
157
+ change = matrix.unblacklist_device(device)
158
+ elif new_state == "verified":
159
+ change = session.matrix.verify_device(device)
160
+ elif new_state == "blacklisted":
161
+ change = session.matrix.blacklist_device(device)
162
+ elif new_state == "ignored":
163
+ change = session.matrix.ignore_device(device)
164
+
165
+ if change:
166
+ result += (
167
+ f"\nThe status of {self.__human_device(device, False)} "
168
+ f"is now {new_state}."
169
+ )
170
+ else:
171
+ result += (
172
+ f"\nThe status of {self.__human_device(device, False)} "
173
+ f"has not changed."
174
+ )
175
+
176
+ return result or "Nothing was changed."
matridge/config.py ADDED
@@ -0,0 +1,35 @@
1
+ MAX_HISTORY_FETCH = 100
2
+ MAX_HISTORY_FETCH__DOC = (
3
+ "Number of events to fetch to back-fill MUC history before slidge starts up."
4
+ )
5
+
6
+ MAX_PARTICIPANTS_FETCH = 10
7
+ MAX_PARTICIPANTS_FETCH__DOC = (
8
+ "Number of participants to fetch when joining a group. "
9
+ "Higher values will make joining slower, and participants will appear when "
10
+ "they speak or if they spoke in the back-filled events. "
11
+ "Participants with power levels > 50 (ie, admins) will be fetched."
12
+ )
13
+
14
+ NIO_SILENT = True
15
+ NIO_SILENT__DOC = (
16
+ "Set this to False to respect the global log level from the matrix lib. "
17
+ "It's REALLY verbose, so the default is to use WARNING."
18
+ )
19
+
20
+ PARSE_MESSAGE_STYLING = True
21
+ PARSE_MESSAGE_STYLING__DOC = """
22
+ Convert Message Styling (XEP-0393) message bodies to Matrix custom HTML.
23
+ Supported markup:
24
+ _underline_
25
+ *bold*
26
+ ~strikethrough~
27
+ `code span`
28
+ ```code block```
29
+ >quote
30
+ ||spoiler
31
+ \\_escape style_
32
+ """
33
+
34
+ TRUST_EVERYTHING = False
35
+ TRUST_EVERYTHING__DOC = "Always trust new encryption keys. This is unsafe if you need perfect bridge to end encryption."
matridge/contact.py ADDED
@@ -0,0 +1,59 @@
1
+ from datetime import datetime, timedelta
2
+ from typing import TYPE_CHECKING
3
+
4
+ import nio
5
+ from slidge import LegacyContact, LegacyRoster
6
+ from slixmpp.exceptions import XMPPError
7
+
8
+ if TYPE_CHECKING:
9
+ from .session import Session
10
+
11
+
12
+ class Contact(LegacyContact[str]):
13
+ """
14
+ We don't implement direct messages but the what's parsed here will propagate
15
+ to MUC participants.
16
+ """
17
+
18
+ session: "Session"
19
+
20
+ async def update_info(self):
21
+ resp = await self.session.matrix.get_profile(self.legacy_id)
22
+ if not isinstance(resp, nio.ProfileGetResponse):
23
+ if resp.status_code == "M_FORBIDDEN":
24
+ self.log.warning("Could not get profile: %s", resp)
25
+ return
26
+ raise XMPPError("internal-server-error", str(resp))
27
+
28
+ self.name = resp.displayname
29
+
30
+ if resp.other_info:
31
+ self.set_vcard(note=str(resp.other_info))
32
+
33
+ if mxc := resp.avatar_url:
34
+ self.avatar = await self.session.matrix.mxc_to_http(mxc)
35
+ else:
36
+ self.avatar = None
37
+
38
+ def update_presence(self, p: nio.PresenceEvent):
39
+ kw = dict(status=p.status_msg)
40
+ if last := p.last_active_ago is not None:
41
+ kw["last_seen"] = datetime.now() - timedelta(seconds=last)
42
+ if p.currently_active:
43
+ self.online(**kw)
44
+ else:
45
+ self.away(**kw)
46
+
47
+
48
+ class Roster(LegacyRoster[str, Contact]):
49
+ session: "Session"
50
+
51
+ async def jid_username_to_legacy_id(self, jid_username: str):
52
+ u = await super().jid_username_to_legacy_id(jid_username)
53
+ if not u.startswith("@"):
54
+ raise XMPPError(
55
+ "bad-request",
56
+ f"'{jid_username}' is not a valid matrix username. "
57
+ "Matrix usernames starts with @",
58
+ )
59
+ return u
matridge/gateway.py ADDED
@@ -0,0 +1,79 @@
1
+ import logging
2
+ from typing import Optional
3
+
4
+ from nio.responses import LoginError
5
+ from slidge import BaseGateway, FormField, global_config
6
+ from slixmpp import JID
7
+
8
+ from . import config
9
+ from .matrix import AuthenticationClient
10
+ from .util import Credentials
11
+
12
+
13
+ class Gateway(BaseGateway):
14
+ REGISTRATION_FIELDS = [
15
+ FormField(var="homeserver", label="Home Server", required=True),
16
+ FormField(var="username", label="User name", required=True),
17
+ FormField(var="password", label="Password", required=True, private=True),
18
+ FormField(
19
+ var="device",
20
+ label="Device name",
21
+ value=f"matridge on {getattr(global_config, 'JID', 'dev')}",
22
+ required=True,
23
+ ),
24
+ ]
25
+ REGISTRATION_INSTRUCTIONS: str = "Enter your credentials"
26
+
27
+ COMPONENT_NAME = "matridge"
28
+ """Name of the component, as seen in service discovery by XMPP clients"""
29
+ COMPONENT_TYPE = "matrix"
30
+
31
+ COMPONENT_AVATAR = "https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/Matrix_icon.svg/209px-Matrix_icon.svg.png"
32
+
33
+ ROSTER_GROUP: str = "matrix"
34
+
35
+ MARK_ALL_MESSAGES = False
36
+
37
+ PROPER_RECEIPTS = True
38
+
39
+ GROUPS = True
40
+
41
+ def __init__(self):
42
+ super().__init__()
43
+ if config.NIO_SILENT:
44
+ logging.getLogger("peewee").setLevel(logging.WARNING)
45
+ logging.getLogger("nio.responses").setLevel(logging.WARNING)
46
+ logging.getLogger("nio.rooms").setLevel(logging.WARNING)
47
+
48
+ async def validate(
49
+ self, user_jid: JID, registration_form: dict[str, Optional[str]]
50
+ ) -> Credentials:
51
+ client = AuthenticationClient(
52
+ registration_form["homeserver"], # type:ignore
53
+ registration_form["username"], # type:ignore
54
+ user_jid,
55
+ )
56
+ await client.fix_homeserver()
57
+ resp = await client.login(
58
+ registration_form["password"], # type:ignore
59
+ registration_form["device"], # type:ignore
60
+ )
61
+ if isinstance(resp, LoginError):
62
+ log.debug("Failed login: %r", resp)
63
+ raise PermissionError(resp)
64
+ return client.get_credentials(resp)
65
+
66
+ async def unregister(self, user):
67
+ """
68
+ Optionally override this if you need to clean additional
69
+ stuff after a user has been removed from the persistent user store.
70
+
71
+ By default, this just calls :meth:`BaseSession.logout`.
72
+
73
+ :param user:
74
+ """
75
+ session = self.get_session_from_user(user)
76
+ await session.matrix.logout() # type:ignore
77
+
78
+
79
+ log = logging.getLogger(__name__)
matridge/group.py ADDED
@@ -0,0 +1,144 @@
1
+ import typing
2
+
3
+ import nio
4
+ from slidge.group import LegacyBookmarks, LegacyMUC, LegacyParticipant, MucType
5
+ from slidge.util.types import HoleBound
6
+ from slixmpp.exceptions import XMPPError
7
+
8
+ from . import config
9
+ from .util import MatrixMixin, server_timestamp_to_datetime
10
+
11
+ if typing.TYPE_CHECKING:
12
+ from .session import Session
13
+
14
+
15
+ class Participant(MatrixMixin, LegacyParticipant):
16
+ session: "Session"
17
+ muc: "MUC"
18
+
19
+
20
+ class Bookmarks(LegacyBookmarks):
21
+ session: "Session"
22
+
23
+ async def fill(self):
24
+ self.log.debug("Filling rooms")
25
+ for room in self.session.matrix.rooms:
26
+ try:
27
+ await self.by_legacy_id(room)
28
+ except XMPPError as e:
29
+ self.log.debug(
30
+ "%s is not a group chat or trouble getting it: %r", room, e
31
+ )
32
+
33
+
34
+ class MUC(LegacyMUC[str, str, Participant, str]):
35
+ session: "Session"
36
+ type = MucType.CHANNEL_NON_ANONYMOUS
37
+
38
+ async def get_room(self):
39
+ try:
40
+ return self.session.matrix.rooms[self.legacy_id]
41
+ except KeyError:
42
+ raise XMPPError("item-not-found", f"No room named {self.legacy_id}")
43
+
44
+ async def get_message(self, msg_id: str) -> typing.Optional[nio.Event]:
45
+ return await self.session.matrix.get_event(self.legacy_id, msg_id)
46
+
47
+ async def update_info(self):
48
+ room = await self.get_room()
49
+
50
+ if new := room.replacement_room:
51
+ raise XMPPError("redirect", f"{new}")
52
+ self.log.debug("Children: %s", room.children)
53
+ if room.children:
54
+ raise XMPPError("bad-request", "This is not a real room but a 'space'")
55
+
56
+ self.user_nick = room.user_name(self.session.matrix.user_id)
57
+
58
+ self.log.debug("User nick: %s", self.user_nick)
59
+ self.name = room.display_name
60
+ self.log.debug("Avatar: %s", room.room_avatar_url)
61
+ self.n_participants = room.member_count
62
+ self.subject = room.topic
63
+
64
+ if room.room_avatar_url:
65
+ self.avatar = await self.session.matrix.mxc_to_http(room.room_avatar_url)
66
+
67
+ elif room.member_count == 2:
68
+ # if 1:1 set room avatar to other users's avatar
69
+ for user_id, user in list(room.users.items()):
70
+ if user_id == self.session.matrix.user_id:
71
+ continue
72
+ if user.avatar_url is None:
73
+ break
74
+ self.avatar = await self.session.matrix.mxc_to_http(user.avatar_url)
75
+ break
76
+
77
+ async def fill_participants(self):
78
+ room = await self.get_room()
79
+ if not room.members_synced:
80
+ resp = await self.session.matrix.joined_members(self.legacy_id)
81
+ if isinstance(resp, nio.JoinedMembersResponse):
82
+ self.log.debug(
83
+ "Joined members response: %s participants", len(resp.members)
84
+ )
85
+ else:
86
+ self.log.debug("Joined members error: %s", resp)
87
+
88
+ power_levels = room.power_levels.users
89
+ i = 0
90
+ if len(room.users.items()) > config.MAX_PARTICIPANTS_FETCH:
91
+ # matrix groups are huge
92
+ self.KEEP_BACKFILLED_PARTICIPANTS = True
93
+
94
+ for user_id, user in list(room.users.items()):
95
+ power_level = power_levels.get(user_id, 0)
96
+ if user_id == self.session.matrix.user_id:
97
+ continue
98
+ else:
99
+ if power_level < 50 and i > config.MAX_PARTICIPANTS_FETCH:
100
+ continue
101
+ try:
102
+ p = await self.get_participant_by_legacy_id(user.user_id)
103
+ except XMPPError:
104
+ continue
105
+ if power_level == 100:
106
+ p.affiliation = "owner"
107
+ p.role = "moderator"
108
+ elif power_level >= 50:
109
+ p.affiliation = "admin"
110
+ p.role = "moderator"
111
+ else:
112
+ i += 1
113
+ yield p
114
+
115
+ async def backfill(
116
+ self,
117
+ after: HoleBound | None = None,
118
+ before: HoleBound | None = None,
119
+ ):
120
+ after_date = None if after is None else after.timestamp
121
+ before_date = None if before is None else before.timestamp
122
+ async for event in self.session.matrix.fetch_history(
123
+ self.legacy_id,
124
+ config.MAX_HISTORY_FETCH,
125
+ ):
126
+ if not isinstance(event, nio.RoomMessage):
127
+ self.log.debug("Not back-filling with %s", type(event))
128
+ when = server_timestamp_to_datetime(event)
129
+ if after_date is not None and when <= after_date:
130
+ continue
131
+ if before_date is not None and when >= before_date:
132
+ continue
133
+ participant = await self.session.matrix.get_participant(
134
+ await self.get_room(), event
135
+ )
136
+ await participant.send_matrix_message(event, archive_only=True)
137
+
138
+ # FIXME: this breaks everything, probably because of parallel calls
139
+ # to sync()
140
+ # if isinstance(event, nio.UnknownEvent) and event.type == "m.reaction":
141
+ # await self.session.matrix.on_reaction(
142
+ # await self.get_room(), event, when=when, archive_only=True
143
+ # )
144
+ # continue