slidge 0.1.0rc1__py3-none-any.whl → 0.1.1__py3-none-any.whl
Sign up to get free protection for your applications and to get access to all the features.
- slidge/__init__.py +54 -31
- slidge/__main__.py +51 -5
- slidge/command/__init__.py +28 -0
- slidge/command/adhoc.py +258 -0
- slidge/command/admin.py +193 -0
- slidge/command/base.py +441 -0
- slidge/command/categories.py +3 -0
- slidge/command/chat_command.py +288 -0
- slidge/command/register.py +179 -0
- slidge/command/user.py +250 -0
- slidge/contact/__init__.py +8 -0
- slidge/contact/contact.py +452 -0
- slidge/contact/roster.py +192 -0
- slidge/core/__init__.py +2 -0
- slidge/core/cache.py +121 -39
- slidge/core/config.py +116 -11
- slidge/core/gateway/__init__.py +3 -0
- slidge/core/gateway/base.py +895 -0
- slidge/core/gateway/caps.py +63 -0
- slidge/core/gateway/delivery_receipt.py +52 -0
- slidge/core/gateway/disco.py +80 -0
- slidge/core/gateway/mam.py +75 -0
- slidge/core/gateway/muc_admin.py +35 -0
- slidge/core/gateway/ping.py +66 -0
- slidge/core/gateway/presence.py +95 -0
- slidge/core/gateway/registration.py +53 -0
- slidge/core/gateway/search.py +102 -0
- slidge/core/gateway/session_dispatcher.py +789 -0
- slidge/core/gateway/vcard_temp.py +130 -0
- slidge/core/mixins/__init__.py +9 -1
- slidge/core/mixins/attachment.py +506 -0
- slidge/core/mixins/avatar.py +167 -0
- slidge/core/mixins/base.py +6 -19
- slidge/core/mixins/disco.py +66 -15
- slidge/core/mixins/lock.py +31 -0
- slidge/core/mixins/message.py +254 -252
- slidge/core/mixins/message_maker.py +154 -0
- slidge/core/mixins/presence.py +128 -31
- slidge/core/mixins/recipient.py +43 -0
- slidge/core/pubsub.py +275 -116
- slidge/core/session.py +586 -518
- slidge/group/__init__.py +10 -0
- slidge/group/archive.py +125 -0
- slidge/group/bookmarks.py +163 -0
- slidge/group/participant.py +458 -0
- slidge/group/room.py +1103 -0
- slidge/migration.py +18 -0
- slidge/slixfix/__init__.py +68 -0
- slidge/{util/xep_0050 → slixfix/link_preview}/__init__.py +4 -5
- slidge/slixfix/link_preview/link_preview.py +17 -0
- slidge/slixfix/link_preview/stanza.py +99 -0
- slidge/slixfix/roster.py +60 -0
- slidge/{util → slixfix}/xep_0077/register.py +1 -2
- slidge/slixfix/xep_0077/stanza.py +104 -0
- slidge/{util → slixfix}/xep_0100/gateway.py +17 -12
- slidge/slixfix/xep_0153/__init__.py +10 -0
- slidge/slixfix/xep_0153/stanza.py +25 -0
- slidge/slixfix/xep_0153/vcard_avatar.py +23 -0
- slidge/slixfix/xep_0264/__init__.py +5 -0
- slidge/slixfix/xep_0264/stanza.py +36 -0
- slidge/slixfix/xep_0264/thumbnail.py +23 -0
- slidge/slixfix/xep_0292/__init__.py +5 -0
- slidge/slixfix/xep_0292/vcard4.py +100 -0
- slidge/slixfix/xep_0313/__init__.py +12 -0
- slidge/slixfix/xep_0313/mam.py +262 -0
- slidge/slixfix/xep_0313/stanza.py +359 -0
- slidge/slixfix/xep_0317/__init__.py +5 -0
- slidge/slixfix/xep_0317/hats.py +17 -0
- slidge/slixfix/xep_0317/stanza.py +28 -0
- slidge/{util → slixfix}/xep_0356_old/privilege.py +9 -7
- slidge/slixfix/xep_0424/__init__.py +9 -0
- slidge/slixfix/xep_0424/retraction.py +77 -0
- slidge/slixfix/xep_0424/stanza.py +28 -0
- slidge/slixfix/xep_0490/__init__.py +8 -0
- slidge/slixfix/xep_0490/mds.py +47 -0
- slidge/slixfix/xep_0490/stanza.py +17 -0
- slidge/util/__init__.py +4 -6
- slidge/util/archive_msg.py +61 -0
- slidge/util/conf.py +25 -4
- slidge/util/db.py +23 -69
- slidge/util/schema.sql +126 -0
- slidge/util/sql.py +508 -0
- slidge/util/test.py +136 -86
- slidge/util/types.py +155 -14
- slidge/util/util.py +225 -51
- slidge-0.1.1.dist-info/METADATA +110 -0
- slidge-0.1.1.dist-info/RECORD +96 -0
- {slidge-0.1.0rc1.dist-info → slidge-0.1.1.dist-info}/WHEEL +1 -1
- slidge/core/adhoc.py +0 -492
- slidge/core/chat_command.py +0 -197
- slidge/core/contact.py +0 -441
- slidge/core/disco.py +0 -59
- slidge/core/gateway.py +0 -899
- slidge/core/muc/__init__.py +0 -3
- slidge/core/muc/bookmarks.py +0 -74
- slidge/core/muc/participant.py +0 -152
- slidge/core/muc/room.py +0 -348
- slidge/plugins/discord/__init__.py +0 -121
- slidge/plugins/discord/client.py +0 -121
- slidge/plugins/discord/session.py +0 -172
- slidge/plugins/dummy.py +0 -334
- slidge/plugins/facebook.py +0 -591
- slidge/plugins/hackernews.py +0 -209
- slidge/plugins/mattermost/__init__.py +0 -1
- slidge/plugins/mattermost/api.py +0 -288
- slidge/plugins/mattermost/gateway.py +0 -417
- slidge/plugins/mattermost/websocket.py +0 -248
- slidge/plugins/signal/__init__.py +0 -4
- slidge/plugins/signal/config.py +0 -4
- slidge/plugins/signal/contact.py +0 -104
- slidge/plugins/signal/gateway.py +0 -379
- slidge/plugins/signal/group.py +0 -76
- slidge/plugins/signal/session.py +0 -515
- slidge/plugins/signal/txt.py +0 -13
- slidge/plugins/signal/util.py +0 -32
- slidge/plugins/skype.py +0 -310
- slidge/plugins/steam.py +0 -400
- slidge/plugins/telegram/__init__.py +0 -6
- slidge/plugins/telegram/client.py +0 -325
- slidge/plugins/telegram/config.py +0 -21
- slidge/plugins/telegram/contact.py +0 -154
- slidge/plugins/telegram/gateway.py +0 -182
- slidge/plugins/telegram/group.py +0 -184
- slidge/plugins/telegram/session.py +0 -275
- slidge/plugins/telegram/util.py +0 -153
- slidge/plugins/whatsapp/__init__.py +0 -6
- slidge/plugins/whatsapp/config.py +0 -17
- slidge/plugins/whatsapp/contact.py +0 -33
- slidge/plugins/whatsapp/event.go +0 -455
- slidge/plugins/whatsapp/gateway.go +0 -156
- slidge/plugins/whatsapp/gateway.py +0 -69
- slidge/plugins/whatsapp/go.mod +0 -17
- slidge/plugins/whatsapp/go.sum +0 -22
- slidge/plugins/whatsapp/session.go +0 -371
- slidge/plugins/whatsapp/session.py +0 -370
- slidge/util/xep_0030/__init__.py +0 -13
- slidge/util/xep_0030/disco.py +0 -811
- slidge/util/xep_0030/stanza/__init__.py +0 -7
- slidge/util/xep_0030/stanza/info.py +0 -270
- slidge/util/xep_0030/stanza/items.py +0 -147
- slidge/util/xep_0030/static.py +0 -467
- slidge/util/xep_0050/adhoc.py +0 -631
- slidge/util/xep_0050/stanza.py +0 -180
- slidge/util/xep_0077/stanza.py +0 -71
- slidge/util/xep_0292/__init__.py +0 -1
- slidge/util/xep_0292/stanza.py +0 -167
- slidge/util/xep_0292/vcard4.py +0 -74
- slidge/util/xep_0356/__init__.py +0 -7
- slidge/util/xep_0356/permissions.py +0 -35
- slidge/util/xep_0356/privilege.py +0 -160
- slidge/util/xep_0356/stanza.py +0 -44
- slidge/util/xep_0461/__init__.py +0 -6
- slidge/util/xep_0461/reply.py +0 -48
- slidge/util/xep_0461/stanza.py +0 -80
- slidge-0.1.0rc1.dist-info/METADATA +0 -171
- slidge-0.1.0rc1.dist-info/RECORD +0 -99
- /slidge/{plugins/__init__.py → py.typed} +0 -0
- /slidge/{util → slixfix}/xep_0077/__init__.py +0 -0
- /slidge/{util → slixfix}/xep_0100/__init__.py +0 -0
- /slidge/{util → slixfix}/xep_0100/stanza.py +0 -0
- /slidge/{util → slixfix}/xep_0356_old/__init__.py +0 -0
- /slidge/{util → slixfix}/xep_0356_old/stanza.py +0 -0
- {slidge-0.1.0rc1.dist-info → slidge-0.1.1.dist-info}/LICENSE +0 -0
- {slidge-0.1.0rc1.dist-info → slidge-0.1.1.dist-info}/entry_points.txt +0 -0
@@ -1,417 +0,0 @@
|
|
1
|
-
import asyncio
|
2
|
-
import io
|
3
|
-
import pprint
|
4
|
-
import re
|
5
|
-
from datetime import datetime
|
6
|
-
from typing import Any, Optional
|
7
|
-
|
8
|
-
import emoji
|
9
|
-
from mattermost_api_reference_client.models import Status
|
10
|
-
from mattermost_api_reference_client.types import Unset
|
11
|
-
from slixmpp import JID
|
12
|
-
from slixmpp.exceptions import XMPPError
|
13
|
-
|
14
|
-
from slidge import *
|
15
|
-
|
16
|
-
from .api import ContactNotFound, MattermostClient
|
17
|
-
from .websocket import EventType, MattermostEvent, Websocket
|
18
|
-
|
19
|
-
|
20
|
-
class Gateway(BaseGateway):
|
21
|
-
REGISTRATION_INSTRUCTIONS = (
|
22
|
-
"Enter mattermost credentials. "
|
23
|
-
"Get your MMAUTH_TOKEN on the web interface, using the dev tools of your browser (it's a cookie)."
|
24
|
-
)
|
25
|
-
REGISTRATION_FIELDS = [
|
26
|
-
FormField(var="url", label="Mattermost server URL", required=True),
|
27
|
-
FormField(var="token", label="MMAUTH_TOKEN", required=True),
|
28
|
-
FormField(var="basepath", label="Base path", value="/api/v4", required=True),
|
29
|
-
FormField(
|
30
|
-
var="basepath_ws",
|
31
|
-
label="Websocket base path",
|
32
|
-
value="/websocket",
|
33
|
-
required=True,
|
34
|
-
),
|
35
|
-
FormField(
|
36
|
-
var="strict_ssl",
|
37
|
-
label="Strict SSL verification",
|
38
|
-
value="1",
|
39
|
-
required=False,
|
40
|
-
type="boolean",
|
41
|
-
),
|
42
|
-
]
|
43
|
-
|
44
|
-
ROSTER_GROUP = "Mattermost"
|
45
|
-
|
46
|
-
COMPONENT_NAME = "Mattermost (slidge)"
|
47
|
-
COMPONENT_TYPE = "mattermost"
|
48
|
-
|
49
|
-
COMPONENT_AVATAR = "https://play-lh.googleusercontent.com/aX7JaAPkmnkeThK4kgb_HHlBnswXF0sPyNI8I8LNmEMMo1vDvMx32tCzgPMsyEXXzZRc"
|
50
|
-
|
51
|
-
async def validate(
|
52
|
-
self, user_jid: JID, registration_form: dict[str, Optional[str]]
|
53
|
-
):
|
54
|
-
mm_client = get_client_from_registration_form(registration_form)
|
55
|
-
try:
|
56
|
-
await mm_client.login()
|
57
|
-
except Exception as e:
|
58
|
-
raise ValueError("Could not authenticate: %s - %s", e, e.args)
|
59
|
-
if mm_client.me is None:
|
60
|
-
raise ValueError("Could not authenticate")
|
61
|
-
|
62
|
-
|
63
|
-
class Contact(LegacyContact["Session", str]):
|
64
|
-
legacy_id: str
|
65
|
-
|
66
|
-
MARKS = False
|
67
|
-
|
68
|
-
def __init__(self, *a, **kw):
|
69
|
-
super().__init__(*a, **kw)
|
70
|
-
self._direct_channel_id: Optional[str] = None
|
71
|
-
self._mm_id: Optional[str] = None
|
72
|
-
|
73
|
-
def update_status(self, status: Optional[str]):
|
74
|
-
if status is None: # custom status
|
75
|
-
self.session.log.debug("Status is None: %s", status)
|
76
|
-
self.online()
|
77
|
-
elif status == "online":
|
78
|
-
self.online()
|
79
|
-
elif status == "offline":
|
80
|
-
self.offline()
|
81
|
-
elif status == "away":
|
82
|
-
self.away()
|
83
|
-
elif status == "dnd":
|
84
|
-
self.busy()
|
85
|
-
else:
|
86
|
-
self.session.log.warning(
|
87
|
-
"Unknown status for '%s':",
|
88
|
-
status,
|
89
|
-
)
|
90
|
-
|
91
|
-
async def direct_channel_id(self):
|
92
|
-
if self._direct_channel_id is None:
|
93
|
-
self._direct_channel_id = (
|
94
|
-
await self.session.mm_client.get_direct_channel(await self.mm_id())
|
95
|
-
).id
|
96
|
-
self.session.contacts.direct_channel_id_to_username[
|
97
|
-
self._direct_channel_id
|
98
|
-
] = self.legacy_id
|
99
|
-
return self._direct_channel_id
|
100
|
-
|
101
|
-
async def mm_id(self):
|
102
|
-
if self._mm_id is None:
|
103
|
-
self._mm_id = (
|
104
|
-
await self.session.mm_client.get_user_by_username(self.legacy_id)
|
105
|
-
).id
|
106
|
-
self.session.contacts.user_id_to_username[self._mm_id] = self.legacy_id
|
107
|
-
return self._mm_id
|
108
|
-
|
109
|
-
async def update_reactions(self, legacy_msg_id):
|
110
|
-
self.react(
|
111
|
-
legacy_msg_id,
|
112
|
-
[
|
113
|
-
# TODO: find a better when than these non standard emoji aliases replace
|
114
|
-
emoji.emojize(f":{x.replace('_3_', '_three_')}:", language="alias")
|
115
|
-
for x in await self.session.get_mm_reactions(
|
116
|
-
legacy_msg_id, await self.mm_id()
|
117
|
-
)
|
118
|
-
],
|
119
|
-
)
|
120
|
-
|
121
|
-
|
122
|
-
class Roster(LegacyRoster["Session", Contact, str]):
|
123
|
-
user_id_to_username: dict[str, str]
|
124
|
-
direct_channel_id_to_username: dict[str, str]
|
125
|
-
|
126
|
-
def __init__(self, *a, **kw):
|
127
|
-
super().__init__(*a, **kw)
|
128
|
-
self.user_id_to_username = {}
|
129
|
-
self.direct_channel_id_to_username = {}
|
130
|
-
|
131
|
-
async def by_mm_user_id(self, user_id: str):
|
132
|
-
try:
|
133
|
-
legacy_id = self.user_id_to_username[user_id]
|
134
|
-
except KeyError:
|
135
|
-
user = await self.session.mm_client.get_user(user_id)
|
136
|
-
if isinstance(user.username, Unset):
|
137
|
-
raise RuntimeError
|
138
|
-
legacy_id = self.user_id_to_username[user_id] = user.username
|
139
|
-
return await self.by_legacy_id(legacy_id)
|
140
|
-
|
141
|
-
async def by_direct_channel_id(self, channel_id: str):
|
142
|
-
if (username := self.direct_channel_id_to_username.get(channel_id)) is None:
|
143
|
-
for c in self:
|
144
|
-
if (await c.direct_channel_id()) == channel_id:
|
145
|
-
return c
|
146
|
-
else:
|
147
|
-
return await self.by_legacy_id(username)
|
148
|
-
|
149
|
-
|
150
|
-
class Session(
|
151
|
-
BaseSession[
|
152
|
-
Gateway, str, Roster, Contact, LegacyBookmarks, LegacyMUC, LegacyParticipant
|
153
|
-
]
|
154
|
-
):
|
155
|
-
def __init__(self, user):
|
156
|
-
super().__init__(user)
|
157
|
-
self.messages_waiting_for_echo = set[str]()
|
158
|
-
self.send_lock = asyncio.Lock()
|
159
|
-
f = self.user.registration_form
|
160
|
-
self.mm_client = get_client_from_registration_form(f)
|
161
|
-
self.ws = Websocket(
|
162
|
-
re.sub("^http", "ws", f["url"] or "")
|
163
|
-
+ (f["basepath"] or "")
|
164
|
-
+ (f["basepath_ws"] or ""),
|
165
|
-
f["token"],
|
166
|
-
)
|
167
|
-
self.view_futures = dict[str, asyncio.Future[None]]()
|
168
|
-
|
169
|
-
async def login(self):
|
170
|
-
await self.mm_client.login()
|
171
|
-
await self.add_contacts()
|
172
|
-
self.xmpp.loop.create_task(self.ws.connect(self.on_mm_event))
|
173
|
-
return f"Connected as '{(await self.mm_client.me).username}'"
|
174
|
-
|
175
|
-
async def add_contacts(self):
|
176
|
-
user_ids = await self.mm_client.get_contacts()
|
177
|
-
contact_mm_users = await self.mm_client.get_users_by_ids(user_ids)
|
178
|
-
contact_mm_statuses = await self.mm_client.get_users_statuses_by_ids(user_ids)
|
179
|
-
|
180
|
-
statuses = {s.user_id: s for s in contact_mm_statuses}
|
181
|
-
|
182
|
-
for user in contact_mm_users:
|
183
|
-
status: Status = statuses[user.id]
|
184
|
-
contact = await self.contacts.by_legacy_id(user.username)
|
185
|
-
self.contacts.user_id_to_username[user.id] = user.username
|
186
|
-
if user.nickname:
|
187
|
-
contact.name = user.nickname
|
188
|
-
elif user.first_name and user.last_name:
|
189
|
-
contact.name = user.first_name + " " + user.last_name
|
190
|
-
elif user.first_name:
|
191
|
-
contact.name = user.first_name
|
192
|
-
elif user.last_name:
|
193
|
-
contact.name = user.last_name
|
194
|
-
|
195
|
-
contact.avatar = await self.mm_client.get_profile_image(user.id)
|
196
|
-
|
197
|
-
await contact.add_to_roster()
|
198
|
-
contact.update_status(str(status.status))
|
199
|
-
|
200
|
-
async def on_mm_event(self, event: MattermostEvent):
|
201
|
-
self.log.debug("Event: %s", event)
|
202
|
-
if event.type == EventType.Hello:
|
203
|
-
self.log.debug("Received hello event: %s", event.data)
|
204
|
-
elif event.type == EventType.Posted:
|
205
|
-
post = event.data["post"]
|
206
|
-
self.log.debug("Post: %s", pprint.pformat(post))
|
207
|
-
|
208
|
-
text = post["message"]
|
209
|
-
|
210
|
-
channel_id = post["channel_id"]
|
211
|
-
post_id = post["id"]
|
212
|
-
user_id = post["user_id"]
|
213
|
-
|
214
|
-
if event.data["channel_type"] == "D": # Direct messages?
|
215
|
-
if user_id == await self.mm_client.mm_id:
|
216
|
-
try:
|
217
|
-
async with self.send_lock:
|
218
|
-
self.messages_waiting_for_echo.remove(post_id)
|
219
|
-
except KeyError:
|
220
|
-
members = await self.mm_client.get_channel_members(channel_id)
|
221
|
-
if len(members) > 2:
|
222
|
-
raise RuntimeError("Not a direct message after all")
|
223
|
-
for m in members:
|
224
|
-
if m.user_id != await self.mm_client.mm_id:
|
225
|
-
contact = await self.contacts.by_mm_user_id(m.user_id)
|
226
|
-
break
|
227
|
-
else:
|
228
|
-
raise RuntimeError("What?")
|
229
|
-
|
230
|
-
contact.send_text(
|
231
|
-
text,
|
232
|
-
legacy_msg_id=post_id,
|
233
|
-
when=datetime.fromtimestamp(post["update_at"] / 1000),
|
234
|
-
carbon=True,
|
235
|
-
)
|
236
|
-
else:
|
237
|
-
contact = await self.contacts.by_mm_user_id(user_id)
|
238
|
-
if event.data.get("set_online"):
|
239
|
-
contact.online()
|
240
|
-
file_metas = post.get("metadata", {}).get("files", [])
|
241
|
-
|
242
|
-
if not file_metas:
|
243
|
-
contact.send_text(text, legacy_msg_id=post_id)
|
244
|
-
return
|
245
|
-
|
246
|
-
last_file_i = len(file_metas) - 1
|
247
|
-
|
248
|
-
for i, file_meta in enumerate(file_metas):
|
249
|
-
last = i == last_file_i
|
250
|
-
await contact.send_file(
|
251
|
-
filename=file_meta["name"],
|
252
|
-
input_file=io.BytesIO(
|
253
|
-
await self.mm_client.get_file(file_meta["id"])
|
254
|
-
),
|
255
|
-
legacy_msg_id=post_id if last else None,
|
256
|
-
caption=text if last else None,
|
257
|
-
)
|
258
|
-
elif event.data["channel_type"] == "P":
|
259
|
-
# private channel
|
260
|
-
pass
|
261
|
-
elif event.type == EventType.ChannelViewed:
|
262
|
-
channel_id = event.data["channel_id"]
|
263
|
-
try:
|
264
|
-
f = self.view_futures.pop(channel_id)
|
265
|
-
except KeyError:
|
266
|
-
pass
|
267
|
-
else:
|
268
|
-
f.set_result(None)
|
269
|
-
return
|
270
|
-
posts = await self.mm_client.get_posts_for_channel(channel_id)
|
271
|
-
try:
|
272
|
-
last_msg_id = posts.posts.additional_keys[-1]
|
273
|
-
except IndexError:
|
274
|
-
self.log.debug("ChannelViewed event for a channel with no messages")
|
275
|
-
return
|
276
|
-
if (c := await self.contacts.by_direct_channel_id(channel_id)) is None:
|
277
|
-
self.log.debug("Ignoring unknown channel")
|
278
|
-
else:
|
279
|
-
c.displayed(last_msg_id, carbon=True)
|
280
|
-
elif event.type == EventType.StatusChange:
|
281
|
-
user_id = event.data["user_id"]
|
282
|
-
if user_id == await self.mm_client.mm_id:
|
283
|
-
self.log.debug("Own status change")
|
284
|
-
else:
|
285
|
-
|
286
|
-
contact = await self.contacts.by_mm_user_id(user_id)
|
287
|
-
contact.update_status(event.data["status"])
|
288
|
-
elif event.type == EventType.Typing:
|
289
|
-
contact = await self.contacts.by_mm_user_id(event.data["user_id"])
|
290
|
-
contact.composing()
|
291
|
-
elif event.type == EventType.PostEdited:
|
292
|
-
post = event.data["post"]
|
293
|
-
if post["user_id"] == await self.mm_client.mm_id:
|
294
|
-
if (
|
295
|
-
c := await self.contacts.by_direct_channel_id(post["channel_id"])
|
296
|
-
) is None:
|
297
|
-
self.log.debug("Ignoring edit in unknown channel")
|
298
|
-
else:
|
299
|
-
c.correct(post["id"], post["message"], carbon=True)
|
300
|
-
else:
|
301
|
-
contact = await self.contacts.by_mm_user_id(post["user_id"])
|
302
|
-
if post["channel_id"] == await contact.direct_channel_id():
|
303
|
-
contact.correct(post["id"], post["message"])
|
304
|
-
elif event.type == EventType.PostDeleted:
|
305
|
-
post = event.data["post"]
|
306
|
-
if post["user_id"] == await self.mm_client.mm_id:
|
307
|
-
if (
|
308
|
-
c := await self.contacts.by_direct_channel_id(post["channel_id"])
|
309
|
-
) is None:
|
310
|
-
self.log.debug("Ignoring edit in unknown channel")
|
311
|
-
else:
|
312
|
-
c.retract(post["id"], carbon=True)
|
313
|
-
else:
|
314
|
-
contact = await self.contacts.by_mm_user_id(post["user_id"])
|
315
|
-
if post["channel_id"] == await contact.direct_channel_id():
|
316
|
-
contact.retract(post["id"])
|
317
|
-
elif event.type in (EventType.ReactionAdded, EventType.ReactionRemoved):
|
318
|
-
reaction = event.data["reaction"]
|
319
|
-
legacy_msg_id = reaction["post_id"]
|
320
|
-
if (who := reaction["user_id"]) == await self.mm_client.mm_id:
|
321
|
-
user_reactions_name = {
|
322
|
-
f":{x}:" for x in await self.get_mm_reactions(legacy_msg_id, who)
|
323
|
-
}
|
324
|
-
user_reactions_char = {
|
325
|
-
# TODO: find a better when than these non standard emoji aliases replace
|
326
|
-
emoji.emojize(x.replace("_3_", "_three_"), language="alias")
|
327
|
-
for x in user_reactions_name
|
328
|
-
}
|
329
|
-
self.log.debug(
|
330
|
-
"carbon: %s vs %s", user_reactions_name, user_reactions_char
|
331
|
-
)
|
332
|
-
contact = await self.contacts.by_direct_channel_id(
|
333
|
-
event.broadcast["channel_id"]
|
334
|
-
)
|
335
|
-
contact.react(legacy_msg_id, user_reactions_char, carbon=True)
|
336
|
-
else:
|
337
|
-
await (await self.contacts.by_mm_user_id(who)).update_reactions(
|
338
|
-
reaction["post_id"]
|
339
|
-
)
|
340
|
-
|
341
|
-
async def logout(self):
|
342
|
-
pass
|
343
|
-
|
344
|
-
async def send_text(self, text: str, chat: Contact, **k):
|
345
|
-
async with self.send_lock:
|
346
|
-
try:
|
347
|
-
msg_id = await self.mm_client.send_message_to_user(chat.legacy_id, text)
|
348
|
-
except ContactNotFound:
|
349
|
-
raise XMPPError(
|
350
|
-
"recipient-unavailable", text="Cannot find this mattermost user"
|
351
|
-
)
|
352
|
-
|
353
|
-
self.messages_waiting_for_echo.add(msg_id)
|
354
|
-
return msg_id
|
355
|
-
|
356
|
-
async def send_file(self, url: str, chat: Contact, **k):
|
357
|
-
channel_id = await chat.direct_channel_id()
|
358
|
-
file_id = await self.mm_client.upload_file(channel_id, url)
|
359
|
-
return await self.mm_client.send_message_with_file(channel_id, file_id)
|
360
|
-
|
361
|
-
async def active(self, c: Contact):
|
362
|
-
pass
|
363
|
-
|
364
|
-
async def inactive(self, c: Contact):
|
365
|
-
pass
|
366
|
-
|
367
|
-
async def composing(self, c: Contact):
|
368
|
-
await self.ws.user_typing(await c.direct_channel_id())
|
369
|
-
|
370
|
-
async def paused(self, c: Contact):
|
371
|
-
# no equivalent in MM, seems to have an automatic timeout in clients
|
372
|
-
pass
|
373
|
-
|
374
|
-
async def displayed(self, legacy_msg_id: Any, c: Contact):
|
375
|
-
channel = await c.direct_channel_id()
|
376
|
-
f = self.view_futures[channel] = self.xmpp.loop.create_future()
|
377
|
-
await self.mm_client.view_channel(channel)
|
378
|
-
await f
|
379
|
-
|
380
|
-
async def correct(self, text: str, legacy_msg_id: Any, c: Contact):
|
381
|
-
await self.mm_client.update_post(legacy_msg_id, text)
|
382
|
-
|
383
|
-
async def search(self, form_values: dict[str, str]):
|
384
|
-
pass
|
385
|
-
|
386
|
-
async def retract(self, legacy_msg_id: Any, c: Contact):
|
387
|
-
await self.mm_client.delete_post(legacy_msg_id)
|
388
|
-
|
389
|
-
async def react(self, legacy_msg_id: Any, emojis: list[str], c: Contact):
|
390
|
-
mm_reactions = await self.get_mm_reactions(
|
391
|
-
legacy_msg_id, await self.mm_client.mm_id
|
392
|
-
)
|
393
|
-
xmpp_reactions = {
|
394
|
-
emoji.demojize(x, language="alias", delimiters=("", "")) for x in emojis
|
395
|
-
}
|
396
|
-
self.log.debug("%s vs %s", mm_reactions, xmpp_reactions)
|
397
|
-
for e in xmpp_reactions - mm_reactions:
|
398
|
-
await self.mm_client.react(legacy_msg_id, e)
|
399
|
-
for e in mm_reactions - xmpp_reactions:
|
400
|
-
await self.mm_client.delete_reaction(legacy_msg_id, e)
|
401
|
-
|
402
|
-
async def get_mm_reactions(self, legacy_msg_id: str, user_id: Optional[str]):
|
403
|
-
return {
|
404
|
-
x.emoji_name
|
405
|
-
for x in await self.mm_client.get_reactions(legacy_msg_id)
|
406
|
-
if x.user_id == user_id
|
407
|
-
}
|
408
|
-
|
409
|
-
|
410
|
-
def get_client_from_registration_form(f: dict[str, Optional[str]]):
|
411
|
-
url = (f.get("url") or "") + (f.get("basepath") or "")
|
412
|
-
return MattermostClient(
|
413
|
-
url,
|
414
|
-
verify_ssl=f["strict_ssl"],
|
415
|
-
timeout=5,
|
416
|
-
token=f["token"],
|
417
|
-
)
|
@@ -1,248 +0,0 @@
|
|
1
|
-
import asyncio
|
2
|
-
import json
|
3
|
-
import logging
|
4
|
-
import pprint
|
5
|
-
import ssl
|
6
|
-
import time
|
7
|
-
from dataclasses import dataclass
|
8
|
-
from enum import Enum
|
9
|
-
|
10
|
-
import aiohttp
|
11
|
-
|
12
|
-
|
13
|
-
class EventType(str, Enum):
|
14
|
-
AddedToTeam = "added_to_team"
|
15
|
-
AuthenticationChallenge = "authentication_challenge"
|
16
|
-
ChannelConverted = "channel_converted"
|
17
|
-
ChannelCreated = "channel_created"
|
18
|
-
ChannelDeleted = "channel_deleted"
|
19
|
-
ChannelMemberUpdated = "channel_member_updated"
|
20
|
-
ChannelUpdated = "channel_updated"
|
21
|
-
ChannelViewed = "channel_viewed"
|
22
|
-
ConfigChanged = "config_changed"
|
23
|
-
DeleteTeam = "delete_team"
|
24
|
-
DirectAdded = "direct_added"
|
25
|
-
EmojiAdded = "emoji_added"
|
26
|
-
EphemeralMessage = "ephemeral_message"
|
27
|
-
GroupAdded = "group_added"
|
28
|
-
Hello = "hello"
|
29
|
-
LeaveTeam = "leave_team"
|
30
|
-
LicenseChanged = "license_changed"
|
31
|
-
MemberroleUpdated = "memberrole_updated"
|
32
|
-
NewUser = "new_user"
|
33
|
-
PluginDisabled = "plugin_disabled"
|
34
|
-
PluginEnabled = "plugin_enabled"
|
35
|
-
PluginStatusesChanged = "plugin_statuses_changed"
|
36
|
-
PostDeleted = "post_deleted"
|
37
|
-
PostEdited = "post_edited"
|
38
|
-
PostUnread = "post_unread"
|
39
|
-
Posted = "posted"
|
40
|
-
PreferenceChanged = "preference_changed"
|
41
|
-
PreferencesChanged = "preferences_changed"
|
42
|
-
PreferencesDeleted = "preferences_deleted"
|
43
|
-
ReactionAdded = "reaction_added"
|
44
|
-
ReactionRemoved = "reaction_removed"
|
45
|
-
Response = "response"
|
46
|
-
RoleUpdated = "role_updated"
|
47
|
-
StatusChange = "status_change"
|
48
|
-
Typing = "typing"
|
49
|
-
UpdateTeam = "update_team"
|
50
|
-
UserAdded = "user_added"
|
51
|
-
UserRemoved = "user_removed"
|
52
|
-
UserRoleUpdated = "user_role_updated"
|
53
|
-
UserUpdated = "user_updated"
|
54
|
-
DialogOpened = "dialog_opened"
|
55
|
-
ThreadUpdated = "thread_updated"
|
56
|
-
ThreadFollowChanged = "thread_follow_changed"
|
57
|
-
ThreadReadChanged = "thread_read_changed"
|
58
|
-
|
59
|
-
# not in the https://api.mattermost.com
|
60
|
-
SidebarCategoryUpdated = "sidebar_category_updated"
|
61
|
-
|
62
|
-
Unknown = "__unknown__"
|
63
|
-
|
64
|
-
|
65
|
-
@dataclass
|
66
|
-
class MattermostEvent:
|
67
|
-
type: EventType
|
68
|
-
data: dict
|
69
|
-
broadcast: dict
|
70
|
-
left: dict
|
71
|
-
|
72
|
-
def __str__(self):
|
73
|
-
return (
|
74
|
-
f"<{self.type}:"
|
75
|
-
f" \ndata: {pprint.pformat(self.data)}"
|
76
|
-
f" \nbroadcast: {pprint.pformat(self.broadcast)}"
|
77
|
-
f" \nleft: {pprint.pformat(self.left)}"
|
78
|
-
f">"
|
79
|
-
)
|
80
|
-
|
81
|
-
|
82
|
-
class Websocket:
|
83
|
-
def __init__(self, url, token):
|
84
|
-
self.token = token
|
85
|
-
self.url = url
|
86
|
-
|
87
|
-
self._alive = False
|
88
|
-
self._last_msg = 0.0
|
89
|
-
|
90
|
-
self.ssl_verify = True
|
91
|
-
self.keep_alive = True
|
92
|
-
self.keep_alive_delay = 30
|
93
|
-
self.websocket: asyncio.Future[
|
94
|
-
aiohttp.ClientWebSocketResponse
|
95
|
-
] = asyncio.get_event_loop().create_future()
|
96
|
-
self._futures: dict[int, asyncio.Future[dict]] = {}
|
97
|
-
self._seq_cursor = 0
|
98
|
-
|
99
|
-
async def connect(self, event_handler):
|
100
|
-
"""
|
101
|
-
Connect to the websocket and authenticate it.
|
102
|
-
When the authentication has finished, start the loop listening for messages,
|
103
|
-
sending a ping to the server to keep the connection alive.
|
104
|
-
:param event_handler: Every websocket event will be passed there. Takes one argument.
|
105
|
-
:type event_handler: Function(message)
|
106
|
-
:return:
|
107
|
-
"""
|
108
|
-
context = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
|
109
|
-
if not self.ssl_verify:
|
110
|
-
context.verify_mode = ssl.CERT_NONE
|
111
|
-
|
112
|
-
url = self.url
|
113
|
-
self._alive = True
|
114
|
-
|
115
|
-
while True:
|
116
|
-
try:
|
117
|
-
async with aiohttp.ClientSession() as session:
|
118
|
-
async with session.ws_connect(url, ssl=context) as websocket:
|
119
|
-
self.websocket.set_result(websocket)
|
120
|
-
await self._authenticate_websocket(websocket)
|
121
|
-
while self._alive:
|
122
|
-
try:
|
123
|
-
await self._start_loop(websocket, event_handler)
|
124
|
-
except aiohttp.ClientError:
|
125
|
-
break
|
126
|
-
if (not self.keep_alive) or (not self._alive):
|
127
|
-
break
|
128
|
-
except Exception as e:
|
129
|
-
log.error("Failed to establish websocket connection")
|
130
|
-
log.exception(e)
|
131
|
-
self.websocket = asyncio.get_event_loop().create_future()
|
132
|
-
await asyncio.sleep(self.keep_alive_delay)
|
133
|
-
|
134
|
-
async def _start_loop(self, websocket, event_handler):
|
135
|
-
"""
|
136
|
-
We will listen for websockets events, sending a heartbeats on a timer.
|
137
|
-
If we don't the webserver would close the idle connection,
|
138
|
-
forcing us to reconnect.
|
139
|
-
"""
|
140
|
-
log.debug("Starting websocket loop")
|
141
|
-
keep_alive = asyncio.create_task(self._do_heartbeats(websocket))
|
142
|
-
log.debug("Waiting for messages on websocket")
|
143
|
-
while self._alive:
|
144
|
-
message = await websocket.receive_str()
|
145
|
-
d = json.loads(message)
|
146
|
-
self._last_msg = time.time()
|
147
|
-
if (seq := d.get("seq_reply")) is None:
|
148
|
-
await handle_event(d, event_handler)
|
149
|
-
else:
|
150
|
-
try:
|
151
|
-
self._futures.pop(seq).set_result(d)
|
152
|
-
except KeyError:
|
153
|
-
if d["seq_reply"] != 1 and d["status"] != "OK":
|
154
|
-
log.warning("Ignoring %s", d)
|
155
|
-
log.debug("cancelling heartbeat task")
|
156
|
-
keep_alive.cancel()
|
157
|
-
try:
|
158
|
-
await keep_alive
|
159
|
-
except asyncio.CancelledError:
|
160
|
-
pass
|
161
|
-
|
162
|
-
async def _do_heartbeats(self, websocket):
|
163
|
-
"""
|
164
|
-
This is a little complicated, but we only need to pong the websocket if
|
165
|
-
we haven't received a message inside the timeout window.
|
166
|
-
Since messages can be received, while we are waiting we need to check
|
167
|
-
after sleep.
|
168
|
-
"""
|
169
|
-
timeout = 30
|
170
|
-
while True:
|
171
|
-
since_last_msg = time.time() - self._last_msg
|
172
|
-
next_timeout = (
|
173
|
-
timeout - since_last_msg if since_last_msg <= timeout else timeout
|
174
|
-
)
|
175
|
-
await asyncio.sleep(next_timeout)
|
176
|
-
if time.time() - self._last_msg >= timeout:
|
177
|
-
log.debug("sending heartbeat...")
|
178
|
-
await websocket.pong()
|
179
|
-
self._last_msg = time.time()
|
180
|
-
|
181
|
-
def disconnect(self):
|
182
|
-
"""Sets `self._alive` to False so the loop in `self._start_loop` will finish."""
|
183
|
-
log.info("Disconnecting websocket")
|
184
|
-
self._alive = False
|
185
|
-
|
186
|
-
async def _authenticate_websocket(self, websocket):
|
187
|
-
"""
|
188
|
-
Sends an authentication challenge over a websocket.
|
189
|
-
This is not needed when we just send the cookie we got on login
|
190
|
-
when connecting to the websocket.
|
191
|
-
"""
|
192
|
-
log.debug("Authenticating websocket")
|
193
|
-
json_data = json.dumps(
|
194
|
-
{
|
195
|
-
"seq": 1,
|
196
|
-
"action": "authentication_challenge",
|
197
|
-
"data": {"token": self.token},
|
198
|
-
}
|
199
|
-
)
|
200
|
-
await websocket.send_str(json_data)
|
201
|
-
while True:
|
202
|
-
message = await websocket.receive_str()
|
203
|
-
status = json.loads(message)
|
204
|
-
log.debug(status)
|
205
|
-
if ("event" in status and status["event"] == "hello") and (
|
206
|
-
"seq" in status and status["seq"] == 0
|
207
|
-
):
|
208
|
-
log.info("Websocket authentication OK")
|
209
|
-
return True
|
210
|
-
log.error("Websocket authentication failed")
|
211
|
-
|
212
|
-
async def user_typing(self, channel_id):
|
213
|
-
seq = self._seq_cursor
|
214
|
-
self._seq_cursor += 1
|
215
|
-
f = self._futures[seq] = asyncio.get_event_loop().create_future()
|
216
|
-
payload = json.dumps(
|
217
|
-
{
|
218
|
-
"seq": seq,
|
219
|
-
"action": "user_typing",
|
220
|
-
"data": {"channel_id": channel_id},
|
221
|
-
}
|
222
|
-
)
|
223
|
-
log.debug("Sending %s", payload)
|
224
|
-
await (await self.websocket).send_str(payload)
|
225
|
-
r = await f
|
226
|
-
log.debug("Confirmation %s", r)
|
227
|
-
|
228
|
-
|
229
|
-
async def handle_event(d, event_handler):
|
230
|
-
if "event" in d:
|
231
|
-
raw_data = d.pop("data")
|
232
|
-
data = {}
|
233
|
-
|
234
|
-
for k, v in raw_data.items():
|
235
|
-
try:
|
236
|
-
data[k] = json.loads(v)
|
237
|
-
except (json.JSONDecodeError, TypeError):
|
238
|
-
data[k] = v
|
239
|
-
|
240
|
-
try:
|
241
|
-
event = EventType(d.pop("event"))
|
242
|
-
except ValueError:
|
243
|
-
event = EventType.Unknown
|
244
|
-
bro = d.pop("broadcast")
|
245
|
-
await event_handler(MattermostEvent(event, data, bro, d))
|
246
|
-
|
247
|
-
|
248
|
-
log = logging.getLogger(__name__)
|
slidge/plugins/signal/config.py
DELETED