Coverage for slidge/core/attachment_upload.py: 85%

306 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-12-01 19:36 +0000

1"""Upload attachments to an HTTP upload service (:xep:`0363`).""" 

2 

3from __future__ import annotations 

4 

5import contextlib 

6import datetime 

7import functools 

8import hashlib 

9import io 

10import logging 

11import os 

12import shutil 

13import stat 

14import tempfile 

15import warnings 

16from base64 import b64encode 

17from collections.abc import AsyncGenerator, AsyncIterator, Iterator 

18from mimetypes import guess_type 

19from pathlib import Path 

20from typing import IO, TYPE_CHECKING, Literal, cast 

21from urllib.parse import quote as urlquote 

22from urllib.parse import urlsplit 

23from uuid import uuid4 

24 

25import aiohttp 

26from PIL.Image import Image 

27from slixmpp import JID, Iq 

28 

29from ..db.models import Attachment 

30from ..util.types import AnyGateway, AvatarMetadata, LegacyAttachment 

31from ..util.util import fix_namespaces, fix_suffix 

32from . import config 

33 

34if TYPE_CHECKING: 

35 from ..db.avatar import AvatarType 

36 from ..util.types import AnySession 

37 

38 

39class AttachmentUploader: 

40 """Turns a :class:`.LegacyAttachment` into a URL that XMPP clients can fetch.""" 

41 

42 xmpp: AnyGateway 

43 session: AnySession | None 

44 """ 

45 The session uplaoding attachments, or :const:`None` for the gateway component, 

46 which is not bound to a :term:`User`. 

47 """ 

48 

49 def __init__(self, xmpp: AnyGateway, session: AnySession | None) -> None: 

50 self.xmpp = xmpp 

51 self._session = session 

52 

53 @contextlib.asynccontextmanager 

54 async def dedup_lock( 

55 self, 

56 attachment: LegacyAttachment | Path | str, 

57 ) -> AsyncGenerator[None]: 

58 """Take a lock on an attachment with a given name. 

59 

60 Prevents races which download the same attachment several times.""" 

61 session = self._session 

62 if ( 

63 session is None 

64 or not isinstance(attachment, LegacyAttachment) 

65 or attachment.legacy_file_id is None 

66 ): 

67 yield 

68 else: 

69 async with session.lock(("attachment", attachment.legacy_file_id)): 

70 yield 

71 

72 async def get_stored(self, attachment: LegacyAttachment) -> Attachment: 

73 """ 

74 Fetch the :class:`.Attachment` already uploaded for this user, if any, 

75 or a new (transient) one. 

76 """ 

77 session = self._session 

78 if attachment.legacy_file_id is not None and session is not None: 

79 with self.xmpp.store.session() as orm: 

80 stored = ( 

81 orm.query(Attachment) 

82 .filter_by( 

83 legacy_file_id=str(attachment.legacy_file_id), 

84 user_account_id=session.user_pk, 

85 ) 

86 .one_or_none() 

87 ) 

88 if stored is not None: 

89 if not await self.__valid_url(session, stored.url): 

90 stored.url = None # type:ignore[assignment] 

91 return stored 

92 return Attachment( 

93 user_account_id=None if session is None else session.user_pk, 

94 legacy_file_id=None 

95 if attachment.legacy_file_id is None 

96 else str(attachment.legacy_file_id), 

97 url=attachment.url if config.USE_ATTACHMENT_ORIGINAL_URLS else None, 

98 ) 

99 

100 def record(self, stored: Attachment) -> None: 

101 """Remember an uploaded attachment, so that it is not uploaded twice. 

102 

103 No-op without a session, since attachments are stored per user. 

104 """ 

105 # TODO: we need a separate mechanism to record gateway component attachments. 

106 if self._session is None: 

107 return 

108 with self.xmpp.store.session(expire_on_commit=False) as orm: 

109 orm.add(stored) 

110 orm.commit() 

111 

112 @staticmethod 

113 async def __valid_url(session: AnySession, url: str) -> bool: 

114 async with session.http.head(url) as r: 

115 return r.status < 400 

116 

117 async def get_url(self, att: LegacyAttachment, stored: Attachment) -> str: 

118 att = _ensure_name(att) 

119 

120 if len(att.name) > config.ATTACHMENT_MAXIMUM_FILE_NAME_LENGTH: 

121 log.debug("Trimming long filename: %s", att.name) 

122 base, ext = os.path.splitext(att.name) 

123 att.name = ( 

124 base[: config.ATTACHMENT_MAXIMUM_FILE_NAME_LENGTH - len(ext)] + ext 

125 ) 

126 

127 if config.FIX_FILENAME_SUFFIX_MIME_TYPE and isinstance(att.path, Path): 

128 att.name, att.content_type = fix_suffix( 

129 att.path, att.content_type, att.name 

130 ) 

131 

132 att.legacy_file_id = stored.legacy_file_id 

133 

134 if att.date is None and att.path is not None: 

135 assert isinstance(att.path, Path) 

136 att.date = datetime.datetime.fromtimestamp( 

137 att.path.stat().st_mtime, tz=datetime.UTC 

138 ) 

139 

140 hasher = hashlib.sha256() if att.sha256 is None else None 

141 if config.NO_UPLOAD_PATH: 

142 att.path, new_url = await self.__no_upload( 

143 att, stored.legacy_file_id, hasher 

144 ) 

145 new_url = ( 

146 (config.NO_UPLOAD_URL_PREFIX or "") + "/message/" + urlquote(new_url) 

147 ) 

148 else: 

149 new_url = await self.__upload(att, hasher=hasher) 

150 if hasher is not None: 

151 att.sha256 = b64encode(hasher.digest()).decode() 

152 

153 if stored.legacy_file_id: 

154 stored.url = new_url 

155 

156 return new_url 

157 

158 async def __upload( 

159 self, 

160 att: _AttachmentWithName, 

161 purpose: Literal["message", "profile"] = "message", 

162 hasher: hashlib._Hash | None = None, 

163 ) -> str: 

164 assert config.UPLOAD_SERVICE 

165 att = await _ensure_metadata(att, self.xmpp.http) 

166 iq_slot = await self.__request_upload_slot( 

167 config.UPLOAD_SERVICE, 

168 att.name, 

169 att.size, 

170 att.content_type, 

171 purpose=purpose, 

172 ) 

173 if iq_slot["type"] == "error": 

174 # COMPAT: In theory, __request_upload_slot() raises IqError, but 

175 # there is a bug in prosody's mod_privilege where the outer 

176 # IQ type is (illegally) not set to error when the inner IQ 

177 # has type='error'. 

178 raise RuntimeError(f"Error while requesting upload slot: {iq_slot}") 

179 slot = iq_slot.get_plugin("http_upload_slot", check=True) 

180 if slot is None: 

181 raise RuntimeError(f"No upload slot in this IQ: {iq_slot}") 

182 put = slot["put"]["url"] 

183 assert isinstance(put, str) 

184 if not put: 

185 raise RuntimeError(f"Cannot find a PUT URL in: {slot}") 

186 get = slot["get"]["url"] 

187 assert isinstance(get, str) 

188 if not get: 

189 raise RuntimeError(f"Cannot find a GET URL in: {slot}") 

190 headers = { 

191 "Content-Length": str(att.size), 

192 "Content-Type": att.content_type, 

193 **{header["name"]: header["value"] for header in slot["put"]["headers"]}, 

194 } 

195 

196 async with ( 

197 _get_data(att, self.xmpp.http, hasher) as data, 

198 self.xmpp.http.put(slot["put"]["url"], data=data, headers=headers) as resp, 

199 ): 

200 resp.raise_for_status() 

201 

202 return get 

203 

204 async def __request_upload_slot( 

205 self, 

206 upload_service: JID | str, 

207 filename: str, 

208 size: int, 

209 content_type: str, 

210 *, 

211 purpose: Literal["message", "profile"] = "message", 

212 ) -> Iq: 

213 iq_request = self.xmpp.make_iq_get(ito=upload_service) 

214 request = iq_request["http_upload_request"] 

215 request["filename"] = filename 

216 request["size"] = str(size) 

217 request["content-type"] = content_type 

218 if purpose != "message": 

219 request.enable(purpose) 

220 session = self._session 

221 if session is not None: 

222 iq_request.set_from(session.user_jid) 

223 try: 

224 return await self.xmpp.plugin["xep_0356"].send_privileged_iq(iq_request) 

225 except Exception as e: # noqa: BLE001 

226 warnings.warn( 

227 "Could not request upload slot on behalf of " 

228 f"{session.user_jid}: {e}." 

229 "Falling back to not using privileges." 

230 ) 

231 fix_namespaces(iq_request.xml, "jabber:client", "jabber:component:accept") 

232 iq_request.set_from(config.UPLOAD_REQUESTER or self.xmpp.boundjid) 

233 return await iq_request.send() # type:ignore[no-any-return] 

234 

235 async def __no_upload( 

236 self, 

237 att: _AttachmentWithName, 

238 legacy_file_id: str | None, 

239 hasher: hashlib._Hash | None = None, 

240 ) -> tuple[Path, str]: 

241 if legacy_file_id is None: 

242 file_id = uuid4().hex 

243 else: 

244 file_id = hashlib.sha256(legacy_file_id.encode()).hexdigest() 

245 assert config.NO_UPLOAD_PATH is not None 

246 assert config.NO_UPLOAD_URL_PREFIX is not None 

247 destination_dir = Path(config.NO_UPLOAD_PATH) / "message" / file_id 

248 

249 if destination_dir.exists(): 

250 log.debug("Dest dir exists: %s", destination_dir) 

251 files = [f for f in destination_dir.glob("**/*") if f.is_file()] 

252 if len(files) == 1: 

253 log.debug( 

254 "Found the legacy attachment '%s' at '%s'", 

255 legacy_file_id, 

256 files[0], 

257 ) 

258 name = files[0].name 

259 uu = files[0].parent.name # anti-obvious url trick, see below 

260 return files[0], f"{file_id}/{uu}/{name}" 

261 else: 

262 log.warning( 

263 ( 

264 "There are several or zero files in %s, " 

265 "slidge doesn't know which one to pick among %s. " 

266 "Removing the dir." 

267 ), 

268 destination_dir, 

269 files, 

270 ) 

271 shutil.rmtree(destination_dir) 

272 

273 log.debug("Did not find a file in: %s", destination_dir) 

274 # let's use a UUID to avoid URLs being too obvious 

275 uu = str(uuid4()) 

276 destination_dir = destination_dir / uu 

277 destination_dir.mkdir(parents=True) 

278 

279 assert att.name 

280 destination = destination_dir / att.name 

281 if att.path: 

282 assert isinstance(att.path, Path) 

283 if hasher is not None: 

284 with att.path.open("rb") as fp: 

285 for chunk in _iter_io(fp): 

286 hasher.update(chunk) 

287 try: 

288 destination.hardlink_to(att.path) 

289 except OSError as e: 

290 if is_temp_path(att.path): 

291 shutil.copy2(att.path, destination) 

292 else: 

293 log.debug("Could not hardlink: %s, attempting symlink", e) 

294 try: 

295 destination.symlink_to(att.path) 

296 except OSError as e: 

297 log.debug("Could not symlink: %s, copying data", e) 

298 shutil.copy2(att.path, destination) 

299 elif att.data: 

300 destination.write_bytes(att.data) 

301 if hasher is not None: 

302 hasher.update(att.data) 

303 else: 

304 with destination.open("wb") as f: 

305 async with _get_data(att, self.xmpp.http, hasher) as data: 

306 if isinstance(data, AsyncIterator): 

307 async for chunk in data: 

308 f.write(chunk) 

309 elif isinstance(data, bytes): 

310 f.write(data) 

311 else: 

312 for chunk in _iter_io(data): 

313 f.write(chunk) 

314 

315 if att.size is None: 

316 att.size = destination.stat().st_size 

317 

318 if config.NO_UPLOAD_FILE_READ_OTHERS: 

319 log.debug("Changing perms of %s", destination) 

320 destination.chmod(destination.stat().st_mode | stat.S_IROTH) 

321 

322 url = f"{file_id}/{uu}/{att.name}" 

323 return destination, url 

324 

325 async def upload_avatar( 

326 self, avatar: AvatarType, img: Image, hash_: str 

327 ) -> AvatarMetadata | None: 

328 if config.NO_UPLOAD_PATH: 

329 return await self.__no_upload_avatar(avatar, img, hash_) 

330 else: 

331 return await self.__upload_avatar(avatar, img, hash_) 

332 

333 async def __no_upload_avatar( 

334 self, avatar: AvatarType, img: Image, hash_: str 

335 ) -> AvatarMetadata | None: 

336 assert config.NO_UPLOAD_PATH 

337 assert img.format 

338 format = img.format.lower() 

339 dest = (Path(config.NO_UPLOAD_PATH) / "profile" / hash_ / "avatar").with_suffix( 

340 "." + format 

341 ) 

342 url = f"{config.NO_UPLOAD_URL_PREFIX}/profile/{hash_}/{dest.name}" 

343 if not dest.exists(): 

344 dest.parent.mkdir(exist_ok=True, parents=True) 

345 if avatar.path: 

346 shutil.copy2(avatar.path, dest) 

347 elif avatar.data: 

348 dest.write_bytes(avatar.data) 

349 else: 

350 img.save(dest) 

351 return AvatarMetadata( 

352 url=url, 

353 width=img.width, 

354 height=img.height, 

355 bytes=dest.stat().st_size, 

356 id=hashlib.sha1(dest.read_bytes()).hexdigest(), 

357 type=format, 

358 ) 

359 

360 async def __upload_avatar( 

361 self, avatar: AvatarType, img: Image, hash_: str 

362 ) -> AvatarMetadata | None: 

363 assert config.UPLOAD_SERVICE is not None 

364 if not await self.xmpp._has_feature( 

365 JID(config.UPLOAD_SERVICE), 

366 self.xmpp.plugin["xep_0363"].stanza.ProfilePurpose.namespace + "#profile", 

367 ): 

368 warnings.warn( 

369 f"The upload service {config.UPLOAD_SERVICE} does not support " 

370 "the 'profile' purpose, avatar data can only be served in-band.", 

371 UserWarning, 

372 ) 

373 return None 

374 

375 att = await _ensure_metadata( 

376 _AttachmentWithName( 

377 data=avatar.data, 

378 url=avatar.url, 

379 path=avatar.path, 

380 name=avatar.path.name if avatar.path else "avatar", 

381 ), 

382 self.xmpp.http, 

383 ) 

384 hasher = hashlib.sha1() 

385 try: 

386 url = await self.__upload(att, purpose="profile", hasher=hasher) 

387 except Exception: 

388 log.exception("Could not upload avatar") 

389 return None 

390 return AvatarMetadata( 

391 url=url, 

392 width=img.width, 

393 height=img.height, 

394 bytes=att.size, 

395 id=hasher.hexdigest(), 

396 type=att.content_type.removeprefix("image/"), 

397 ) 

398 

399 

400class _AttachmentWithName(LegacyAttachment): 

401 name: str 

402 path: Path | None 

403 

404 

405class _AttachmentWithMetadata(_AttachmentWithName): 

406 size: int 

407 content_type: str 

408 

409 

410def _ensure_name(att: LegacyAttachment) -> _AttachmentWithName: 

411 if not att.name: 

412 if att.path: 

413 att.name = Path(att.path).name 

414 elif att.url: 

415 att.name = att.url.split("/")[-1] 

416 else: 

417 att.name = "unnamed-file" 

418 return cast(_AttachmentWithName, att) 

419 

420 

421async def _ensure_metadata( 

422 att: _AttachmentWithName, http: aiohttp.ClientSession 

423) -> _AttachmentWithMetadata: 

424 if att.size is None: 

425 if att.data: 

426 att.size = len(att.data) 

427 elif att.stream: 

428 att.stream.seek(0, io.SEEK_END) 

429 att.size = att.stream.tell() 

430 att.stream.seek(0) 

431 elif att.path: 

432 assert isinstance(att.path, Path) 

433 att.size = att.path.stat().st_size 

434 elif att.url: 

435 async with http.head(att.url) as resp: 

436 att.size = resp.content_length 

437 if att.size is None: 

438 warnings.warn( 

439 f"{urlsplit(att.url).netloc} does not use the content-length header, " 

440 "temporary files need to be written to disk" 

441 ) 

442 async with http.get(att.url) as resp: 

443 await _tmp_write(att, resp.content.iter_any()) 

444 elif att.aio_stream: 

445 warnings.warn("A size should be passed with async iterators") 

446 await _tmp_write(att, att.aio_stream) 

447 

448 if not att.content_type: 

449 att.content_type, _encoding = guess_type(att.name) 

450 if not att.content_type: 

451 att.content_type = "application/octet-stream" 

452 

453 return cast(_AttachmentWithMetadata, att) 

454 

455 

456async def _tmp_write(att: LegacyAttachment, aio_it: AsyncIterator[bytes]) -> None: 

457 assert att.name is not None 

458 tmp_dir = Path(tempfile.mkdtemp(prefix=_TEMP_PREFIX)) 

459 with (tmp_dir / att.name).open("wb") as fp: 

460 async for chunk in aio_it: 

461 fp.write(chunk) 

462 att.path = Path(fp.name) 

463 att.size = att.path.stat().st_size 

464 

465 

466@contextlib.asynccontextmanager 

467async def _get_data( 

468 att: LegacyAttachment, 

469 http: aiohttp.ClientSession, 

470 hasher: hashlib._Hash | None = None, 

471) -> AsyncIterator[bytes | IO[bytes] | AsyncIterator[bytes]]: 

472 

473 if att.data is not None: 

474 if hasher is not None: 

475 hasher.update(att.data) 

476 yield att.data 

477 elif att.stream is not None: 

478 _hash(att.stream, hasher) 

479 yield att.stream 

480 elif att.path is not None: 

481 assert isinstance(att.path, Path) 

482 with att.path.open("rb") as fp: 

483 _hash(fp, hasher) 

484 yield fp 

485 elif att.aio_stream is not None: 

486 # The aiostream may already have been consumed if a size wasn't passed. 

487 # But in this case the `path` attribute is not None, cf above. 

488 yield _hash_and_yield_async(att.aio_stream, hasher) 

489 elif att.url is not None: 

490 async with http.get(att.url) as resp_get: 

491 resp_get.raise_for_status() 

492 yield _hash_and_yield_async(resp_get.content.iter_any(), hasher) 

493 else: 

494 raise RuntimeError("NEVER") 

495 

496 

497def _hash(fp: IO[bytes], hasher: hashlib._Hash | None = None) -> None: 

498 if hasher is not None: 

499 fp.seek(0) 

500 for chunk in _iter_io(fp): 

501 hasher.update(chunk) 

502 fp.seek(0) 

503 

504 

505async def _hash_and_yield_async( 

506 source: AsyncIterator[bytes], hasher: hashlib._Hash | None = None 

507) -> AsyncIterator[bytes]: 

508 async for chunk in source: 

509 if hasher is not None: 

510 hasher.update(chunk) 

511 yield chunk 

512 

513 

514def is_temp_path(path: Path, async_iterator_download_only: bool = False) -> bool: 

515 try: 

516 rel = path.relative_to(_TEMP_ROOT) 

517 except ValueError: 

518 return False 

519 if async_iterator_download_only: 

520 return rel.parts[0].startswith(_TEMP_PREFIX) 

521 else: 

522 return True 

523 

524 

525def _iter_io(fp: IO[bytes], chunk_size: int = 2**18) -> Iterator[bytes]: 

526 return iter(functools.partial(fp.read, chunk_size), b"") 

527 

528 

529_TEMP_ROOT = Path(tempfile.gettempdir()) 

530_TEMP_PREFIX = "slidge-async-iterator-download" 

531 

532log = logging.getLogger(__name__)