Mercurial > libervia-backend
annotate libervia/backend/plugins/plugin_comp_email_gateway/__init__.py @ 4337:95792a1f26c7
component email gateway: attachments handling:
attachments are now stored, and metadata are created in database.
rel 453
author | Goffi <goffi@goffi.org> |
---|---|
date | Tue, 03 Dec 2024 00:13:23 +0100 |
parents | 055930cc81f9 |
children | 7c0b7ecb816f |
rev | line source |
---|---|
4303 | 1 #!/usr/bin/env python3 |
2 | |
3 # Libervia Email Gateway Component | |
4 # Copyright (C) 2009-2024 Jérôme Poisson (goffi@goffi.org) | |
5 | |
6 # This program is free software: you can redistribute it and/or modify | |
7 # it under the terms of the GNU Affero General Public License as published by | |
8 # the Free Software Foundation, either version 3 of the License, or | |
9 # (at your option) any later version. | |
10 | |
11 # This program is distributed in the hope that it will be useful, | |
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
14 # GNU Affero General Public License for more details. | |
15 | |
16 # You should have received a copy of the GNU Affero General Public License | |
17 # along with this program. If not, see <http://www.gnu.org/licenses/>. | |
18 | |
19 from email.header import decode_header | |
20 from email.message import EmailMessage | |
21 from email.mime.text import MIMEText | |
4309
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
22 from email.utils import formataddr, getaddresses, parseaddr |
4303 | 23 from functools import partial |
4337
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
24 import hashlib |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
25 from pathlib import Path |
4303 | 26 import re |
4337
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
27 import shutil |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
28 import tempfile |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
29 from typing import TYPE_CHECKING, NamedTuple, cast |
4303 | 30 |
4309
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
31 from pydantic import BaseModel |
4303 | 32 from twisted.internet import defer, reactor |
4337
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
33 from twisted.internet.threads import deferToThread |
4303 | 34 from twisted.mail import smtp |
35 from twisted.words.protocols.jabber import jid | |
4309
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
36 from twisted.words.protocols.jabber import error as jabber_error |
4303 | 37 from twisted.words.protocols.jabber.error import StanzaError |
38 from twisted.words.protocols.jabber.xmlstream import XMPPHandler | |
39 from twisted.words.xish import domish | |
40 from wokkel import data_form, disco, iwokkel | |
41 from zope.interface import implementer | |
42 | |
43 from libervia.backend.core import exceptions | |
44 from libervia.backend.core.constants import Const as C | |
4337
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
45 from libervia.backend.core.core_types import SatXMPPComponent, SatXMPPEntity |
4303 | 46 from libervia.backend.core.i18n import D_, _ |
47 from libervia.backend.core.log import getLogger | |
48 from libervia.backend.memory.persistent import LazyPersistentBinaryDict | |
49 from libervia.backend.memory.sqla import select | |
50 from libervia.backend.memory.sqla_mapping import PrivateIndBin | |
51 from libervia.backend.models.core import MessageData | |
4309
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
52 from libervia.backend.plugins.plugin_xep_0033 import ( |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
53 AddressType, |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
54 AddressesData, |
4337
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
55 RECIPIENT_FIELDS, |
4309
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
56 ) |
4303 | 57 from libervia.backend.plugins.plugin_xep_0077 import XEP_0077 |
58 from libervia.backend.plugins.plugin_xep_0106 import XEP_0106 | |
4337
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
59 from libervia.backend.plugins.plugin_xep_0131 import HeadersData, Urgency, XEP_0131 |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
60 from libervia.backend.plugins.plugin_xep_0498 import XEP_0498 |
4303 | 61 from libervia.backend.tools.utils import aio |
62 | |
4337
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
63 from .imap import IMAPClientFactory |
4303 | 64 from .models import Credentials, UserData |
4337
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
65 |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
66 if TYPE_CHECKING: |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
67 from libervia.backend.core.main import LiberviaBackend |
4303 | 68 |
69 | |
70 log = getLogger(__name__) | |
71 | |
72 IMPORT_NAME = "email-gateway" | |
73 NAME = "Libervia Email Gateway" | |
74 | |
75 PLUGIN_INFO = { | |
76 C.PI_NAME: "Email Gateway Component", | |
77 C.PI_IMPORT_NAME: IMPORT_NAME, | |
78 C.PI_MODES: [C.PLUG_MODE_COMPONENT], | |
79 C.PI_TYPE: C.PLUG_TYPE_ENTRY_POINT, | |
80 C.PI_PROTOCOLS: [], | |
4337
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
81 C.PI_DEPENDENCIES: ["XEP-0033", "XEP-0077", "XEP-0106", "XEP-0498"], |
4303 | 82 C.PI_RECOMMENDATIONS: [], |
83 C.PI_MAIN: "EmailGatewayComponent", | |
84 C.PI_HANDLER: C.BOOL_TRUE, | |
85 C.PI_DESCRIPTION: D_( | |
86 "Gateway to handle email. Usual emails are handled as message, while mailing " | |
87 "lists are converted to pubsub blogs." | |
88 ), | |
89 } | |
90 | |
91 CONF_SECTION = f"component {IMPORT_NAME}" | |
92 PREFIX_KEY_CREDENTIALS = "CREDENTIALS_" | |
93 KEY_CREDENTIALS = f"{PREFIX_KEY_CREDENTIALS}{{from_jid}}" | |
94 | |
95 email_pattern = re.compile(r"[^@]+@[^@]+\.[^@]+") | |
96 | |
97 | |
4337
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
98 class FileMetadata(NamedTuple): |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
99 path: Path |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
100 hash: str |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
101 size: int |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
102 |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
103 |
4309
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
104 class SendMailExtra(BaseModel): |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
105 addresses: AddressesData | None = None |
4317
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
106 headers: HeadersData | None = None |
4309
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
107 |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
108 |
4303 | 109 class EmailGatewayComponent: |
110 IMPORT_NAME = IMPORT_NAME | |
111 verbose = 0 | |
112 | |
4337
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
113 def __init__(self, host: "LiberviaBackend") -> None: |
4303 | 114 self.host = host |
4337
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
115 self.client: SatXMPPComponent | None = None |
4303 | 116 self.initalized = False |
117 self.storage: LazyPersistentBinaryDict | None = None | |
118 self._iq_register = cast(XEP_0077, host.plugins["XEP-0077"]) | |
119 self._iq_register.register_handler( | |
120 self._on_registration_form, self._on_registration_submit | |
121 ) | |
122 self._e = cast(XEP_0106, host.plugins["XEP-0106"]) | |
4317
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
123 self._shim = cast(XEP_0131, host.plugins["XEP-0131"]) |
4337
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
124 self._pfs = cast(XEP_0498, host.plugins["XEP-0498"]) |
4303 | 125 # TODO: For the moment, all credentials are kept in cache; we should only keep the |
126 # X latest. | |
127 self.users_data: dict[jid.JID, UserData] = {} | |
4337
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
128 self.files_path = self.host.get_local_path(None, C.FILES_DIR) |
4303 | 129 host.trigger.add_with_check( |
130 "message_received", self, self._message_received_trigger, priority=-1000 | |
131 ) | |
132 | |
133 async def _init(self) -> None: | |
134 """Initialisation done after profile is connected""" | |
135 assert self.client is not None | |
136 self.client.identities.append(disco.DiscoIdentity("gateway", "smtp", NAME)) | |
137 self.storage = LazyPersistentBinaryDict(IMPORT_NAME, self.client.profile) | |
138 await self.connect_registered_users() | |
139 | |
140 @aio | |
141 async def get_registered_users(self) -> dict[jid.JID, Credentials]: | |
142 """Retrieve credentials for all registered users | |
143 | |
144 @return: a mapping from user JID to credentials data. | |
145 """ | |
146 assert self.client is not None | |
147 profile_id = self.host.memory.storage.profiles[self.client.profile] | |
148 async with self.host.memory.storage.session() as session: | |
149 query = select(PrivateIndBin).where( | |
150 PrivateIndBin.profile_id == profile_id, | |
151 PrivateIndBin.namespace == IMPORT_NAME, | |
152 PrivateIndBin.key.startswith(PREFIX_KEY_CREDENTIALS), | |
153 ) | |
154 result = await session.execute(query) | |
155 return { | |
156 jid.JID(p.key[len(PREFIX_KEY_CREDENTIALS) :]): p.value | |
157 for p in result.scalars() | |
158 } | |
159 | |
160 async def connect_registered_users(self) -> None: | |
161 """Connected users already registered to the gateway.""" | |
162 registered_data = await self.get_registered_users() | |
163 for user_jid, credentials in registered_data.items(): | |
164 user_data = self.users_data[user_jid] = UserData(credentials=credentials) | |
165 if not credentials["imap_success"]: | |
166 log.warning( | |
167 f"Ignoring unsuccessful IMAP credentials of {user_jid}. This user " | |
168 "won't receive message from this gateway." | |
169 ) | |
170 else: | |
171 try: | |
172 await self.connect_imap(user_jid, user_data) | |
173 except Exception as e: | |
174 log.warning(f"Can't connect {user_jid} to IMAP: {e}.") | |
175 else: | |
176 log.debug(f"Connection to IMAP server successful for {user_jid}.") | |
177 | |
178 def get_handler(self, __) -> XMPPHandler: | |
179 return EmailGatewayHandler() | |
180 | |
181 async def profile_connecting(self, client: SatXMPPEntity) -> None: | |
4337
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
182 assert isinstance(client, SatXMPPComponent) |
4303 | 183 self.client = client |
184 if not self.initalized: | |
185 await self._init() | |
186 self.initalized = True | |
187 | |
188 def _message_received_trigger( | |
189 self, | |
190 client: SatXMPPEntity, | |
191 message_elt: domish.Element, | |
192 post_treat: defer.Deferred, | |
193 ) -> bool: | |
194 """add the gateway workflow on post treatment""" | |
195 if client != self.client: | |
196 return True | |
197 post_treat.addCallback( | |
198 lambda mess_data: defer.ensureDeferred( | |
199 self.on_message(client, mess_data, message_elt) | |
200 ) | |
201 ) | |
202 return True | |
203 | |
204 async def on_message( | |
205 self, client: SatXMPPEntity, mess_data: MessageData, message_elt: domish.Element | |
206 ) -> dict: | |
207 """Called once message has been parsed | |
208 | |
209 @param client: Client session. | |
210 @param mess_data: Message data. | |
211 @return: Message data. | |
212 """ | |
213 if client != self.client: | |
214 return mess_data | |
215 from_jid = mess_data["from"].userhostJID() | |
4317
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
216 extra_kw = {} |
4303 | 217 if mess_data["type"] not in ("chat", "normal"): |
218 log.warning(f"ignoring message with unexpected type: {mess_data}") | |
219 return mess_data | |
220 if not client.is_local(from_jid): | |
221 log.warning(f"ignoring non local message: {mess_data}") | |
222 return mess_data | |
223 if not mess_data["to"].user: | |
4309
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
224 addresses = mess_data["extra"].get("addresses") |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
225 if not addresses: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
226 log.warning(f"ignoring message addressed to gateway itself: {mess_data}") |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
227 return mess_data |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
228 else: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
229 to_email = None |
4317
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
230 extra_kw["addresses"] = addresses |
4309
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
231 else: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
232 try: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
233 to_email = self._e.unescape(mess_data["to"].user) |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
234 except ValueError: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
235 raise exceptions.DataError( |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
236 f'Invalid "to" JID, can\'t send message: {message_elt.toXml()}.' |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
237 ) |
4303 | 238 |
4317
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
239 self._shim.move_keywords_to_headers(mess_data["extra"]) |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
240 headers = mess_data["extra"].get("headers") |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
241 if headers: |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
242 extra_kw["headers"] = headers |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
243 |
4303 | 244 try: |
245 body_lang, body = next(iter(mess_data["message"].items())) | |
246 except (KeyError, StopIteration): | |
247 log.warning(f"No body found: {mess_data}") | |
248 body_lang, body = "", "" | |
249 try: | |
250 subject_lang, subject = next(iter(mess_data["subject"].items())) | |
251 except (KeyError, StopIteration): | |
252 subject_lang, subject = "", None | |
253 | |
254 if not body and not subject: | |
255 log.warning(f"Ignoring empty message: {mess_data}") | |
256 return mess_data | |
257 | |
258 try: | |
259 await self.send_email( | |
260 from_jid=from_jid, | |
261 to_email=to_email, | |
262 body=body, | |
263 subject=subject, | |
4317
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
264 extra=SendMailExtra(**extra_kw) if extra_kw else None, |
4303 | 265 ) |
266 except exceptions.UnknownEntityError: | |
267 log.warning(f"Can't send message, user {from_jid} is not registered.") | |
268 message_error_elt = StanzaError( | |
269 "subscription-required", | |
270 text="User need to register to the gateway before sending emails.", | |
271 ).toResponse(message_elt) | |
272 await client.a_send(message_error_elt) | |
273 raise exceptions.CancelError("User not registered.") | |
4309
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
274 except StanzaError as e: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
275 log.warning("Can't send message: {e}") |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
276 message_error_elt = e.toResponse(message_elt) |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
277 await client.a_send(message_error_elt) |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
278 raise exceptions.CancelError("Can't send message: {e}") |
4303 | 279 |
280 return mess_data | |
281 | |
4309
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
282 def jid_to_email( |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
283 self, client: SatXMPPEntity, address_jid: jid.JID, credentials: dict[str, str] |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
284 ) -> str: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
285 """Convert a JID to an email address. |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
286 |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
287 If JID is from the gateway, email address will be extracted. Otherwise, the |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
288 gateway email will be used, with XMPP address specified in name part. |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
289 |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
290 @param address_jid: JID of the recipient. |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
291 @param credentials: Sender credentials. |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
292 @return: Email address. |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
293 """ |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
294 if address_jid and address_jid.host.endswith(str(client.jid)): |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
295 return self._e.unescape(address_jid.user) |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
296 else: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
297 email_address = credentials["user_email"] |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
298 if address_jid: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
299 email_address = formataddr((f"xmpp:{address_jid}", email_address)) |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
300 return email_address |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
301 |
4303 | 302 async def send_email( |
303 self, | |
304 from_jid: jid.JID, | |
4309
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
305 to_email: str | None, |
4303 | 306 body: str, |
307 subject: str | None, | |
4309
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
308 extra: SendMailExtra | None = None, |
4303 | 309 ) -> None: |
310 """Send an email using sender credentials. | |
311 | |
312 Credentials will be retrieve from cache, or database. | |
313 | |
314 @param from_jid: Bare JID of the sender. | |
315 @param to_email: Email address of the destinee. | |
316 @param body: Body of the email. | |
317 @param subject: Subject of the email. | |
4309
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
318 @param extra: Extra data. |
4303 | 319 |
320 @raise exceptions.UnknownEntityError: Credentials for "from_jid" can't be found. | |
321 """ | |
4309
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
322 assert self.client is not None |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
323 if extra is None: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
324 extra = SendMailExtra() |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
325 if to_email is None and (extra.addresses is None or not extra.addresses.to): |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
326 raise exceptions.InternalError( |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
327 '"to_email" can\'t be None if there is no "to" address!' |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
328 ) |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
329 |
4303 | 330 # We need a bare jid. |
331 assert self.storage is not None | |
332 assert not from_jid.resource | |
333 try: | |
334 user_data = self.users_data[from_jid] | |
335 except KeyError: | |
336 key = KEY_CREDENTIALS.format(from_jid=from_jid) | |
337 credentials = await self.storage.get(key) | |
338 if credentials is None: | |
339 raise exceptions.UnknownEntityError( | |
340 f"No credentials found for {from_jid}." | |
341 ) | |
342 self.users_data[from_jid] = UserData(credentials) | |
343 else: | |
344 credentials = user_data.credentials | |
345 | |
346 msg = MIMEText(body, "plain", "UTF-8") | |
347 if subject is not None: | |
348 msg["Subject"] = subject | |
349 msg["From"] = formataddr( | |
350 (credentials["user_name"] or None, credentials["user_email"]) | |
351 ) | |
4309
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
352 if extra.addresses: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
353 assert extra.addresses.to |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
354 main_to_address = extra.addresses.to[0] |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
355 assert main_to_address.jid |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
356 to_email = self.jid_to_email(self.client, main_to_address.jid, credentials) |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
357 for field in RECIPIENT_FIELDS: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
358 addresses = getattr(extra.addresses, field) |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
359 if not addresses: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
360 continue |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
361 for address in addresses: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
362 if not address.delivered and ( |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
363 address.jid is None or address.jid.host != str(self.client.jid) |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
364 ): |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
365 log.warning( |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
366 "Received undelivered message to external JID, this is not " |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
367 "allowed! Cancelling the message sending." |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
368 ) |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
369 stanza_err = jabber_error.StanzaError( |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
370 "forbidden", |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
371 text="Multicasting (XEP-0033 addresses) can only be used " |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
372 "with JID from this gateway, not external ones. " |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
373 f" {address.jid} can't be delivered by this gateway and " |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
374 "should be delivered by server instead.", |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
375 ) |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
376 raise stanza_err |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
377 email_addresses = [ |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
378 self.jid_to_email(self.client, address.jid, credentials) |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
379 for address in addresses |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
380 if address.jid |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
381 ] |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
382 if email_addresses: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
383 msg[field.upper()] = ", ".join(email_addresses) |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
384 else: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
385 assert to_email is not None |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
386 msg["To"] = to_email |
4303 | 387 |
388 sender_domain = credentials["user_email"].split("@", 1)[-1] | |
389 | |
4317
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
390 if extra.headers: |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
391 if extra.headers.keywords: |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
392 msg["Keywords"] = extra.headers.keywords |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
393 if extra.headers.urgency: |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
394 urgency = extra.headers.urgency |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
395 if urgency == Urgency.medium: |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
396 importance = "normal" |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
397 else: |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
398 importance = urgency |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
399 msg["Importance"] = importance |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
400 |
4303 | 401 await smtp.sendmail( |
402 credentials["smtp_host"].encode(), | |
403 credentials["user_email"].encode(), | |
404 [to_email.encode()], | |
405 msg.as_bytes(), | |
406 senderDomainName=sender_domain, | |
407 port=int(credentials["smtp_port"]), | |
408 username=credentials["smtp_username"].encode(), | |
409 password=credentials["smtp_password"].encode(), | |
410 requireAuthentication=True, | |
411 # TODO: only STARTTLS is supported right now, implicit TLS should be supported | |
412 # too. | |
413 requireTransportSecurity=True, | |
414 ) | |
415 | |
416 async def _on_registration_form( | |
417 self, client: SatXMPPEntity, iq_elt: domish.Element | |
418 ) -> tuple[bool, data_form.Form] | None: | |
419 if client != self.client: | |
420 return | |
421 assert self.storage is not None | |
422 from_jid = jid.JID(iq_elt["from"]) | |
423 key = KEY_CREDENTIALS.format(from_jid=from_jid.userhost()) | |
424 credentials = await self.storage.get(key) or {} | |
425 | |
426 form = data_form.Form(formType="form", title="IMAP/SMTP Credentials") | |
427 | |
428 # Add instructions | |
429 form.instructions = [ | |
430 D_( | |
431 "Please provide your IMAP and SMTP credentials to configure the " | |
432 "connection." | |
433 ) | |
434 ] | |
435 | |
436 # Add identity fields | |
437 form.addField( | |
438 data_form.Field( | |
439 fieldType="text-single", | |
440 var="user_name", | |
441 label="User Name", | |
442 desc=D_('The display name to use in the "From" field of sent emails.'), | |
443 value=credentials.get("user_name"), | |
444 required=True, | |
445 ) | |
446 ) | |
447 | |
448 form.addField( | |
449 data_form.Field( | |
450 fieldType="text-single", | |
451 var="user_email", | |
452 label="User Email", | |
453 desc=D_('The email address to use in the "From" field of sent emails.'), | |
454 value=credentials.get("user_email"), | |
455 required=True, | |
456 ) | |
457 ) | |
458 | |
459 # Add fields for IMAP credentials | |
460 form.addField( | |
461 data_form.Field( | |
462 fieldType="text-single", | |
463 var="imap_host", | |
464 label="IMAP Host", | |
465 desc=D_("IMAP server hostname or IP address"), | |
466 value=credentials.get("imap_host"), | |
467 required=True, | |
468 ) | |
469 ) | |
470 form.addField( | |
471 data_form.Field( | |
472 fieldType="text-single", | |
473 var="imap_port", | |
474 label="IMAP Port", | |
475 desc=D_("IMAP server port (default: 993)"), | |
476 value=credentials.get("imap_port", "993"), | |
477 ) | |
478 ) | |
479 form.addField( | |
480 data_form.Field( | |
481 fieldType="text-single", | |
482 var="imap_username", | |
483 label="IMAP Username", | |
484 desc=D_("Username for IMAP authentication"), | |
485 value=credentials.get("imap_username"), | |
486 required=True, | |
487 ) | |
488 ) | |
489 form.addField( | |
490 data_form.Field( | |
491 fieldType="text-private", | |
492 var="imap_password", | |
493 label="IMAP Password", | |
494 desc=D_("Password for IMAP authentication"), | |
495 value=credentials.get("imap_password"), | |
496 required=True, | |
497 ) | |
498 ) | |
499 | |
500 # Add fields for SMTP credentials | |
501 form.addField( | |
502 data_form.Field( | |
503 fieldType="text-single", | |
504 var="smtp_host", | |
505 label="SMTP Host", | |
506 desc=D_("SMTP server hostname or IP address"), | |
507 value=credentials.get("smtp_host"), | |
508 required=True, | |
509 ) | |
510 ) | |
511 form.addField( | |
512 data_form.Field( | |
513 fieldType="text-single", | |
514 var="smtp_port", | |
515 label="SMTP Port", | |
516 desc=D_("SMTP server port (default: 587)"), | |
517 value=credentials.get("smtp_port", "587"), | |
518 ) | |
519 ) | |
520 form.addField( | |
521 data_form.Field( | |
522 fieldType="text-single", | |
523 var="smtp_username", | |
524 label="SMTP Username", | |
525 desc=D_("Username for SMTP authentication"), | |
526 value=credentials.get("smtp_username"), | |
527 required=True, | |
528 ) | |
529 ) | |
530 form.addField( | |
531 data_form.Field( | |
532 fieldType="text-private", | |
533 var="smtp_password", | |
534 label="SMTP Password", | |
535 desc=D_("Password for SMTP authentication"), | |
536 value=credentials.get("smtp_password"), | |
537 required=True, | |
538 ) | |
539 ) | |
540 | |
541 return bool(credentials), form | |
542 | |
543 def validate_field( | |
544 self, | |
545 form: data_form.Form, | |
546 key: str, | |
547 field_type: str, | |
548 min_value: int | None = None, | |
549 max_value: int | None = None, | |
550 default: str | int | None = None, | |
551 ) -> None: | |
552 """Validate a single field. | |
553 | |
554 @param form: The form containing the fields. | |
555 @param key: The key of the field to validate. | |
556 @param field_type: The expected type of the field value. | |
557 @param min_value: Optional minimum value for integer fields. | |
558 @param max_value: Optional maximum value for integer fields. | |
559 @param default: Default value to use if the field is missing. | |
560 @raise StanzaError: If the field value is invalid or missing. | |
561 """ | |
562 field = form.fields.get(key) | |
563 if field is None: | |
564 if default is None: | |
565 raise StanzaError("bad-request", text=f"{key} is required") | |
566 field = data_form.Field(var=key, value=str(default)) | |
567 form.addField(field) | |
568 | |
569 value = field.value | |
570 if field_type == "int": | |
571 try: | |
572 value = int(value) | |
573 if (min_value is not None and value < min_value) or ( | |
574 max_value is not None and value > max_value | |
575 ): | |
576 raise ValueError | |
577 except (ValueError, TypeError): | |
578 raise StanzaError("bad-request", text=f"Invalid value for {key}: {value}") | |
579 elif field_type == "str": | |
580 if not isinstance(value, str): | |
581 raise StanzaError("bad-request", text=f"Invalid value for {key}: {value}") | |
582 | |
583 # Basic email validation for user_email field | |
584 if key == "user_email": | |
585 # XXX: This is a minimal check. A complete email validation is notoriously | |
586 # difficult. | |
587 if not email_pattern.match(value): | |
588 raise StanzaError( | |
589 "bad-request", text=f"Invalid email address: {value}" | |
590 ) | |
591 | |
592 def validate_imap_smtp_form(self, submit_form: data_form.Form) -> None: | |
593 """Validate the submitted IMAP/SMTP credentials form. | |
594 | |
595 @param submit_form: The submitted form containing IMAP/SMTP credentials. | |
596 @raise StanzaError: If any of the values are invalid. | |
597 """ | |
598 # Validate identity fields | |
599 self.validate_field(submit_form, "user_name", "str") | |
600 self.validate_field(submit_form, "user_email", "str") | |
601 | |
602 # Validate IMAP fields | |
603 self.validate_field(submit_form, "imap_host", "str") | |
604 self.validate_field( | |
605 submit_form, "imap_port", "int", min_value=1, max_value=65535, default=993 | |
606 ) | |
607 self.validate_field(submit_form, "imap_username", "str") | |
608 self.validate_field(submit_form, "imap_password", "str") | |
609 | |
610 # Validate SMTP fields | |
611 self.validate_field(submit_form, "smtp_host", "str") | |
612 self.validate_field( | |
613 submit_form, "smtp_port", "int", min_value=1, max_value=65535, default=587 | |
614 ) | |
615 self.validate_field(submit_form, "smtp_username", "str") | |
616 self.validate_field(submit_form, "smtp_password", "str") | |
617 | |
4309
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
618 def email_to_jid( |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
619 self, |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
620 client: SatXMPPEntity, |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
621 user_email: str, |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
622 user_jid: jid.JID, |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
623 email_name: str, |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
624 email_addr: str, |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
625 ) -> tuple[jid.JID, str | None]: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
626 """Convert an email address to a JID and extract the name if present. |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
627 |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
628 @param client: Client session. |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
629 @param user_email: Email address of the gateway user. |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
630 @param user_jid: JID of the gateway user. |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
631 @param email_name: Email associated name. |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
632 @param email_addr: Email address. |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
633 @return: Tuple of JID and name (if present). |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
634 """ |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
635 email_name = email_name.strip() |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
636 if email_name.startswith("xmpp:"): |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
637 return jid.JID(email_name[5:]), None |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
638 elif email_addr == user_email: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
639 return (user_jid, None) |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
640 else: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
641 return ( |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
642 jid.JID(None, (self._e.escape(email_addr), client.jid.host, None)), |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
643 email_name or None, |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
644 ) |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
645 |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
646 async def on_new_email( |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
647 self, user_data: UserData, user_jid: jid.JID, email: EmailMessage |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
648 ) -> None: |
4303 | 649 """Called when a new message has been received. |
650 | |
4309
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
651 @param user_data: user data, used to map registered user email to corresponding |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
652 jid. |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
653 @param user_jid: JID of the recipient. |
4303 | 654 @param email: Parsed email. |
655 """ | |
656 assert self.client is not None | |
4309
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
657 user_email = user_data.credentials["user_email"] |
4303 | 658 name, email_addr = parseaddr(email["from"]) |
659 email_addr = email_addr.lower() | |
660 from_jid = jid.JID(None, (self._e.escape(email_addr), self.client.jid.host, None)) | |
661 | |
662 # Get the email body | |
663 body_mime = email.get_body(("plain",)) | |
664 if body_mime is not None: | |
665 charset = body_mime.get_content_charset() or "utf-8" | |
666 body = body_mime.get_payload(decode=True).decode(charset, errors="replace") | |
667 else: | |
668 log.warning(f"No body found in email:\n{email}") | |
669 body = "" | |
670 | |
671 # Decode the subject | |
672 subject = email.get("subject") | |
673 if subject: | |
674 decoded_subject = decode_header(subject) | |
675 subject = "".join( | |
676 [ | |
677 part.decode(encoding or "utf-8") if isinstance(part, bytes) else part | |
678 for part, encoding in decoded_subject | |
679 ] | |
680 ).strip() | |
681 else: | |
682 subject = None | |
683 | |
4309
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
684 # Parse recipient fields |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
685 kwargs = {} |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
686 for field in RECIPIENT_FIELDS: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
687 email_addresses = email.get_all(field) |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
688 if email_addresses: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
689 jids_and_names = [ |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
690 self.email_to_jid(self.client, user_email, user_jid, name, addr) |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
691 for name, addr in getaddresses(email_addresses) |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
692 ] |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
693 kwargs[field] = [ |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
694 AddressType(jid=jid, desc=name) for jid, name in jids_and_names |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
695 ] |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
696 |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
697 # At least "to" header should be set, so kwargs should never be empty |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
698 assert kwargs |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
699 addresses_data = AddressesData(**kwargs) |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
700 |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
701 # Parse reply-to field |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
702 reply_to_addresses = email.get_all("reply-to") |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
703 if reply_to_addresses: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
704 jids_with_names = [ |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
705 self.email_to_jid(self.client, user_email, user_jid, name, addr) |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
706 for name, addr in getaddresses(reply_to_addresses) |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
707 ] |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
708 addresses_data.replyto = [ |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
709 AddressType(jid=jid, desc=name) for jid, name in jids_with_names |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
710 ] |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
711 |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
712 # Set noreply flag |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
713 # The is no flag to indicate a no-reply message, so we check common user parts in |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
714 # from and reply-to headers. |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
715 from_addresses = [email_addr] |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
716 if reply_to_addresses: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
717 from_addresses.extend( |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
718 addr for a in reply_to_addresses if (addr := parseaddr(a)[1]) |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
719 ) |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
720 for from_address in from_addresses: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
721 from_user_part = from_address.split("@", 1)[0].lower() |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
722 if from_user_part in ( |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
723 "no-reply", |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
724 "noreply", |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
725 "do-not-reply", |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
726 "donotreply", |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
727 "notification", |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
728 "notifications", |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
729 ): |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
730 addresses_data.noreply = True |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
731 break |
4317
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
732 extra = {} |
4309
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
733 |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
734 if ( |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
735 not addresses_data.replyto |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
736 and not addresses_data.noreply |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
737 and not addresses_data.cc |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
738 and not addresses_data.bcc |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
739 and addresses_data.to == [AddressType(jid=user_jid)] |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
740 ): |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
741 # The main recipient is the only one, and there is no other metadata: there is |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
742 # no need to add addresses metadata. |
4317
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
743 pass |
4309
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
744 else: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
745 for address in addresses_data.addresses: |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
746 if address.jid and ( |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
747 address.jid == user_jid or address.jid.host == str(self.client.jid) |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
748 ): |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
749 # Those are email address, and have been delivered by the sender, |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
750 # other JID addresses will have to be delivered by us. |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
751 address.delivered = True |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
752 |
4317
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
753 extra["addresses"] = addresses_data.model_dump(mode="json", exclude_none=True) |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
754 |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
755 # We look for interesting headers |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
756 headers = {} |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
757 keywords_headers = email.get_all("keywords") |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
758 if keywords_headers: |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
759 keywords = ",".join(keywords_headers) |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
760 headers["keywords"] = keywords |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
761 |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
762 importance = email["importance"] |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
763 if importance: |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
764 # We convert to urgency |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
765 if importance in ("low", "high"): |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
766 headers["urgency"] = importance |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
767 elif importance == "normal": |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
768 headers["urgency"] = "medium" |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
769 else: |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
770 log.warning("Ignoring invalid importance header: {importance!r}") |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
771 |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
772 if headers: |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
773 extra["headers"] = HeadersData(**headers).model_dump( |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
774 mode="json", exclude_none=True |
055930cc81f9
component email gateway: Add support for XEP-0131 headers:
Goffi <goffi@goffi.org>
parents:
4309
diff
changeset
|
775 ) |
4309
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
776 |
4337
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
777 # Handle attachments |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
778 for part in email.iter_attachments(): |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
779 await self.handle_attachment(part, user_jid) |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
780 |
4303 | 781 client = self.client.get_virtual_client(from_jid) |
4337
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
782 |
4309
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
783 await client.sendMessage( |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
784 user_jid, |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
785 {"": body}, |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
786 {"": subject} if subject else None, |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
787 extra=extra, |
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
788 ) |
4303 | 789 |
4337
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
790 async def handle_attachment(self, part: EmailMessage, recipient_jid: jid.JID) -> None: |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
791 """Handle an attachment from an email. |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
792 |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
793 @param part: The object representing the attachment. |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
794 @param recipient_jid: JID of the recipient to whom the attachment is being sent. |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
795 """ |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
796 assert self.client is not None |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
797 content_type = part.get_content_type() |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
798 filename = part.get_filename() or "attachment" |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
799 log.debug(f"Handling attachment: {filename} ({content_type})") |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
800 file_metadata = await deferToThread(self._save_attachment, part) |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
801 if file_metadata is not None: |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
802 log.debug(f"Attachment {filename!r} saved to {file_metadata.path}") |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
803 try: |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
804 await self.host.memory.set_file( |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
805 self.client, |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
806 filename, |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
807 file_hash=file_metadata.hash, |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
808 hash_algo="sha-256", |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
809 size=file_metadata.size, |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
810 namespace=PLUGIN_INFO[C.PI_IMPORT_NAME], |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
811 mime_type=content_type, |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
812 owner=recipient_jid, |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
813 ) |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
814 except Exception: |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
815 log.exception(f"Failed to register file {filename!r}") |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
816 |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
817 def _save_attachment(self, part: EmailMessage) -> FileMetadata | None: |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
818 """Save the attachment to files path. |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
819 |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
820 This method must be executed in a thread with deferToThread to avoid blocking the |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
821 reactor with IO operations if the attachment is large. |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
822 |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
823 @param part: The object representing the attachment. |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
824 @return: Attachment data, or None if an error occurs. |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
825 @raises IOError: Can't save the attachment. |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
826 """ |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
827 temp_file = None |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
828 try: |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
829 with tempfile.NamedTemporaryFile(delete=False) as temp_file: |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
830 payload = part.get_payload(decode=True) |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
831 if isinstance(payload, bytes): |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
832 temp_file.write(payload) |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
833 file_hash = hashlib.sha256(payload).hexdigest() |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
834 file_path = self.files_path / file_hash |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
835 shutil.move(temp_file.name, file_path) |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
836 file_size = len(payload) |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
837 return FileMetadata(path=file_path, hash=file_hash, size=file_size) |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
838 else: |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
839 log.warning(f"Can't write payload of type {type(payload)}.") |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
840 return None |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
841 except Exception as e: |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
842 raise IOError(f"Failed to save attachment: {e}") |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
843 finally: |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
844 if temp_file is not None and Path(temp_file.name).exists(): |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
845 Path(temp_file.name).unlink() |
95792a1f26c7
component email gateway: attachments handling:
Goffi <goffi@goffi.org>
parents:
4317
diff
changeset
|
846 |
4303 | 847 async def connect_imap(self, from_jid: jid.JID, user_data: UserData) -> None: |
848 """Connect to IMAP service. | |
849 | |
850 [self.on_new_email] will be used as callback on new messages. | |
851 | |
852 @param from_jid: JID of the user associated with given credentials. | |
853 @param credentials: Email credentials. | |
854 """ | |
855 credentials = user_data.credentials | |
856 | |
857 connected = defer.Deferred() | |
858 factory = IMAPClientFactory( | |
859 user_data, | |
4309
b56b1eae7994
component email gateway: add multicasting:
Goffi <goffi@goffi.org>
parents:
4303
diff
changeset
|
860 partial(self.on_new_email, user_data, from_jid.userhostJID()), |
4303 | 861 connected, |
862 ) | |
863 reactor.connectTCP( | |
864 credentials["imap_host"], int(credentials["imap_port"]), factory | |
865 ) | |
866 await connected | |
867 | |
868 async def _on_registration_submit( | |
869 self, | |
870 client: SatXMPPEntity, | |
871 iq_elt: domish.Element, | |
872 submit_form: data_form.Form | None, | |
873 ) -> bool | None: | |
874 """Handle registration submit request. | |
875 | |
876 Submit form is validated, and credentials are stored. | |
877 @param client: client session. | |
878 iq_elt: IQ stanza of the submission request. | |
879 submit_form: submit form. | |
880 @return: True if successful. | |
881 None if the callback is not relevant for this request. | |
882 """ | |
883 if client != self.client: | |
884 return | |
885 assert self.storage is not None | |
886 from_jid = jid.JID(iq_elt["from"]).userhostJID() | |
887 | |
888 if submit_form is None: | |
889 # This is an unregistration request. | |
890 try: | |
891 user_data = self.users_data[from_jid] | |
892 except KeyError: | |
893 pass | |
894 else: | |
895 if user_data.imap_client is not None: | |
896 try: | |
897 await user_data.imap_client.logout() | |
898 except Exception: | |
899 log.exception(f"Can't log out {from_jid} from IMAP server.") | |
900 key = KEY_CREDENTIALS.format(from_jid=from_jid) | |
901 await self.storage.adel(key) | |
902 log.info(f"{from_jid} unregistered from this gateway.") | |
903 return True | |
904 | |
905 self.validate_imap_smtp_form(submit_form) | |
906 credentials = {key: field.value for key, field in submit_form.fields.items()} | |
907 user_data = self.users_data.get(from_jid) | |
908 if user_data is None: | |
909 # The user is not in cache, we cache current credentials. | |
910 user_data = self.users_data[from_jid] = UserData(credentials=credentials) | |
911 else: | |
912 # The user is known, we update credentials. | |
913 user_data.credentials = credentials | |
914 key = KEY_CREDENTIALS.format(from_jid=from_jid) | |
915 try: | |
916 await self.connect_imap(from_jid, user_data) | |
917 except Exception as e: | |
918 log.warning(f"Can't connect to IMAP server for {from_jid}") | |
919 credentials["imap_success"] = False | |
920 await self.storage.aset(key, credentials) | |
921 raise e | |
922 else: | |
923 log.debug(f"Connection successful to IMAP server for {from_jid}") | |
924 credentials["imap_success"] = True | |
925 await self.storage.aset(key, credentials) | |
926 return True | |
927 | |
928 | |
929 @implementer(iwokkel.IDisco) | |
930 class EmailGatewayHandler(XMPPHandler): | |
931 | |
932 def getDiscoInfo(self, requestor, target, nodeIdentifier=""): | |
933 return [] | |
934 | |
935 def getDiscoItems(self, requestor, target, nodeIdentifier=""): | |
936 return [] |