Matridge 0.2.0__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,14 @@
1
+ from slidge import entrypoint
2
+ from slidge.util.util import get_version # noqa: F401
3
+
4
+ # import everything for automatic subclasses discovery by slidge core
5
+ from . import command, contact, gateway, group, session
6
+
7
+
8
+ def main():
9
+ entrypoint("matridge")
10
+
11
+
12
+ __all__ = "session", "gateway", "contact", "group", "command", "main"
13
+
14
+ __version__ = "v0.2.0"
matridge/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from matridge import main
2
+
3
+ main()
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_VERBOSE = False
15
+ NIO_VERBOSE__DOC = (
16
+ "Set this to True 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,64 @@
1
+ import asyncio
2
+ from datetime import datetime, timedelta
3
+ from typing import TYPE_CHECKING
4
+
5
+ import nio
6
+ from aiohttp import ClientConnectionError
7
+ from slidge import LegacyContact, LegacyRoster
8
+ from slixmpp.exceptions import XMPPError
9
+
10
+ if TYPE_CHECKING:
11
+ from .session import Session
12
+
13
+
14
+ class Contact(LegacyContact[str]):
15
+ """
16
+ We don't implement direct messages but the what's parsed here will propagate
17
+ to MUC participants.
18
+ """
19
+
20
+ session: "Session"
21
+
22
+ async def update_info(self):
23
+ try:
24
+ resp = await self.session.matrix.get_profile(self.legacy_id)
25
+ except (ClientConnectionError, TimeoutError, asyncio.TimeoutError) as e:
26
+ raise XMPPError("remote-server-timeout", str(e))
27
+ if not isinstance(resp, nio.ProfileGetResponse):
28
+ if resp.status_code == "M_FORBIDDEN":
29
+ self.log.warning("Could not get profile: %s", resp)
30
+ return
31
+ raise XMPPError("internal-server-error", str(resp))
32
+
33
+ self.name = resp.displayname
34
+
35
+ if resp.other_info:
36
+ self.set_vcard(note=str(resp.other_info))
37
+
38
+ if mxc := resp.avatar_url:
39
+ self.avatar = await self.session.matrix.mxc_to_http(mxc)
40
+ else:
41
+ self.avatar = None
42
+
43
+ def update_presence(self, p: nio.PresenceEvent):
44
+ kw = dict(status=p.status_msg)
45
+ if last := p.last_active_ago is not None:
46
+ kw["last_seen"] = datetime.now() - timedelta(seconds=last)
47
+ if p.currently_active:
48
+ self.online(**kw)
49
+ else:
50
+ self.away(**kw)
51
+
52
+
53
+ class Roster(LegacyRoster[str, Contact]):
54
+ session: "Session"
55
+
56
+ async def jid_username_to_legacy_id(self, jid_username: str):
57
+ u = await super().jid_username_to_legacy_id(jid_username)
58
+ if not u.startswith("@"):
59
+ raise XMPPError(
60
+ "bad-request",
61
+ f"'{jid_username}' is not a valid matrix username. "
62
+ "Matrix usernames starts with @",
63
+ )
64
+ return u
matridge/gateway.py ADDED
@@ -0,0 +1,76 @@
1
+ import logging
2
+ from shutil import rmtree
3
+ from typing import TYPE_CHECKING, Optional
4
+
5
+ from nio.responses import LoginError
6
+ from slidge import BaseGateway, FormField, global_config
7
+ from slixmpp import JID
8
+
9
+ from . import config
10
+ from .matrix import AuthenticationClient
11
+ from .util import Credentials
12
+
13
+ if TYPE_CHECKING:
14
+ from .session import Session
15
+
16
+
17
+ class Gateway(BaseGateway):
18
+ REGISTRATION_FIELDS = [
19
+ FormField(var="homeserver", label="Home Server", required=True),
20
+ FormField(var="username", label="User name", required=True),
21
+ FormField(var="password", label="Password", required=True, private=True),
22
+ FormField(
23
+ var="device",
24
+ label="Device name",
25
+ value=f"matridge on {getattr(global_config, 'JID', 'dev')}",
26
+ required=True,
27
+ ),
28
+ ]
29
+ REGISTRATION_INSTRUCTIONS: str = "Enter your credentials"
30
+
31
+ COMPONENT_NAME = "Matrix (slidge)"
32
+ COMPONENT_TYPE = "matrix"
33
+
34
+ COMPONENT_AVATAR = "https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/Matrix_icon.svg/209px-Matrix_icon.svg.png"
35
+
36
+ ROSTER_GROUP: str = "matrix"
37
+
38
+ MARK_ALL_MESSAGES = False
39
+
40
+ PROPER_RECEIPTS = True
41
+
42
+ GROUPS = True
43
+
44
+ def __init__(self):
45
+ super().__init__()
46
+ if not config.NIO_VERBOSE:
47
+ logging.getLogger("peewee").setLevel(logging.WARNING)
48
+ logging.getLogger("nio.responses").setLevel(logging.WARNING)
49
+ logging.getLogger("nio.rooms").setLevel(logging.WARNING)
50
+
51
+ async def validate(
52
+ self, user_jid: JID, registration_form: dict[str, Optional[str]]
53
+ ) -> Credentials:
54
+ client = AuthenticationClient(
55
+ registration_form["homeserver"], # type:ignore
56
+ registration_form["username"], # type:ignore
57
+ user_jid,
58
+ )
59
+ await client.fix_homeserver()
60
+ resp = await client.login(
61
+ registration_form["password"], # type:ignore
62
+ registration_form["device"], # type:ignore
63
+ )
64
+ if isinstance(resp, LoginError):
65
+ log.debug("Failed login: %r", resp)
66
+ raise PermissionError(resp)
67
+ return client.get_credentials(resp)
68
+
69
+ async def unregister(self, user):
70
+ session: "Session" = self.get_session_from_user(user) # type: ignore
71
+ session.matrix.stop_listen()
72
+ await session.matrix.logout()
73
+ rmtree(session.matrix.store_path)
74
+
75
+
76
+ log = logging.getLogger(__name__)
matridge/group.py ADDED
@@ -0,0 +1,154 @@
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
+ try:
134
+ participant = await self.session.matrix.get_participant(
135
+ await self.get_room(), event
136
+ )
137
+ except XMPPError as e:
138
+ # maybe deleted profiles?
139
+ self.log.warning(
140
+ "Something is wrong with participant %s, falling back to using matrix ID as nickname: %s",
141
+ event.sender,
142
+ e,
143
+ )
144
+ participant = await self.get_participant(event.sender)
145
+
146
+ await participant.send_matrix_message(event, archive_only=True)
147
+
148
+ # FIXME: this breaks everything, probably because of parallel calls
149
+ # to sync()
150
+ # if isinstance(event, nio.UnknownEvent) and event.type == "m.reaction":
151
+ # await self.session.matrix.on_reaction(
152
+ # await self.get_room(), event, when=when, archive_only=True
153
+ # )
154
+ # continue