atagen

macltok

public
Star0
Watch0
121a56ce119d97a65954edd1253f68cb6093d2a7
3
ssh://brewery@pls.lobotomise.me:33/atagen/macltok.git
src/engine/media.rsRust791 lines26.4 KB
1
use std::{
2
    borrow::Cow,
3
    collections::{HashMap, VecDeque},
4
    io::Read as _,
5
    panic::AssertUnwindSafe,
6
    sync::Arc,
7
    time::Duration,
8
};
9
10
use futures_util::{
11
    FutureExt, StreamExt,
12
    future::{Shared, WeakShared},
13
};
14
use matrix_sdk::{
15
    Client, Room, SendOutsideWasm, SyncOutsideWasm,
16
    media::{MediaFormat, MediaRequestParameters, MediaThumbnailSettings},
17
    room::reply::{EnforceThread, Reply as SdkReply},
18
    ruma::{
19
        api::{
20
            Metadata, OutgoingRequest,
21
            auth_scheme::SendAccessToken,
22
            client::{authenticated_media, media},
23
        },
24
        events::room::{
25
            EncryptedFileHash, EncryptedFileHashAlgorithm, EncryptedFileInfo, MediaSource,
26
            message::{
27
                AddMentions, Relation, ReplyWithinThread, RoomMessageEventContentWithoutRelation,
28
            },
29
        },
30
    },
31
};
32
use matrix_sdk_crypto::{AttachmentDecryptor, MediaEncryptionInfo};
33
use ruma::{MxcUri, OwnedEventId};
34
use tokio::sync::Mutex;
35
36
use super::{executor::EngineBoxFuture, url_preview::UrlPreviews};
37
use crate::{
38
    AttachmentEncryption, AttachmentUpload, Error, ErrorKind, LinkPreview, Media, MediaFile,
39
    MediaId, MediaKind, MediaLocation, MediaSize,
40
    normalise::{MediaRegistration, MediaScope, MediaSourceInfo},
41
    upload::prepare_upload,
42
};
43
44
/// a stalled download gives up after this long without a byte
45
const DOWNLOAD_IDLE: Duration = Duration::from_secs(60);
46
/// the sdk client gives up on any request after thirty seconds, far too soon for a video
47
const DOWNLOAD_TOTAL: Duration = Duration::from_secs(60 * 60);
48
49
type FlightFuture = EngineBoxFuture<'static, Result<Media, Error>>;
50
type Flight = Shared<FlightFuture>;
51
52
/// owns everything needed to turn a media id or an mxc uri into bytes, so the
53
/// handle can answer media queries without a trip through the engine
54
pub(crate) struct MediaService {
55
    client: Client,
56
    registry: Mutex<MediaRegistry>,
57
    flights: Mutex<HashMap<String, WeakShared<FlightFuture>>>,
58
    max_bytes: usize,
59
    url_previews: UrlPreviews,
60
}
61
62
impl MediaService {
63
    pub(crate) fn new(client: Client, max_bytes: usize, max_sources: usize) -> Self {
64
        Self {
65
            url_previews: UrlPreviews::new(client.clone()),
66
            client,
67
            registry: Mutex::new(MediaRegistry::new(max_sources)),
68
            flights: Mutex::new(HashMap::new()),
69
            max_bytes,
70
        }
71
    }
72
73
    pub(crate) async fn url_preview(&self, url: &str) -> Result<Option<LinkPreview>, Error> {
74
        self.url_previews.preview(url).await
75
    }
76
77
    pub(crate) async fn register(&self, media: Vec<MediaRegistration>) {
78
        if !media.is_empty() {
79
            self.registry.lock().await.insert_all(media);
80
        }
81
    }
82
83
    pub(crate) async fn release(&self, scope: &MediaScope) {
84
        self.registry.lock().await.release(scope);
85
    }
86
87
    pub(crate) async fn clear(&self) {
88
        self.registry.lock().await.clear();
89
    }
90
91
    pub(crate) async fn timeline_media(
92
        &self,
93
        media_id: &MediaId,
94
        size: MediaSize,
95
    ) -> Result<Media, Error> {
96
        let chosen = choose_source(self.registered(media_id).await?, size)?;
97
        if chosen
98
            .declared_size
99
            .is_some_and(|size| size > self.max_bytes as u64)
100
        {
101
            return Err(too_large("media exceeds the configured byte limit"));
102
        }
103
        self.fetch_or_file(chosen.request, chosen.mimetype).await
104
    }
105
106
    pub(crate) async fn media_location(
107
        &self,
108
        media_id: &MediaId,
109
        size: MediaSize,
110
    ) -> Result<MediaLocation, Error> {
111
        let media = self.registered(media_id).await?;
112
        let chosen = choose_source(media.clone(), size)?;
113
        if is_local(&chosen.request.source) {
114
            return Ok(MediaLocation::Local);
115
        }
116
        if !matches!(chosen.request.format, MediaFormat::Thumbnail(_)) {
117
            return Ok(MediaLocation::File(
118
                media_file(
119
                    &self.client,
120
                    chosen.request,
121
                    chosen.mimetype,
122
                    chosen.declared_size,
123
                )
124
                .await?,
125
            ));
126
        }
127
        let url = media_http_request(&self.client, &chosen.request)
128
            .await?
129
            .uri()
130
            .to_string();
131
        let fallback = MediaRequestParameters {
132
            source: media.full.source,
133
            format: MediaFormat::File,
134
        };
135
        Ok(MediaLocation::ServerThumbnail {
136
            url,
137
            fallback: media_file(
138
                &self.client,
139
                fallback,
140
                media.full.mimetype,
141
                media.full.declared_size,
142
            )
143
            .await?,
144
        })
145
    }
146
147
    async fn registered(&self, media_id: &MediaId) -> Result<MediaRegistration, Error> {
148
        if let Some(uri) = media_id.as_plain() {
149
            return plain_registration(media_id, uri);
150
        }
151
        self.registry
152
            .lock()
153
            .await
154
            .get(media_id)
155
            .cloned()
156
            .ok_or_else(|| {
157
                Error::new(
158
                    ErrorKind::MediaUnknown,
159
                    "media is not registered in a retained timeline",
160
                )
161
            })
162
    }
163
164
    /// plenty of servers won't thumbnail everything, and the file itself is the next best
165
    /// thing. the byte cap still holds either way
166
    async fn fetch_or_file(
167
        &self,
168
        request: MediaRequestParameters,
169
        mimetype: Option<String>,
170
    ) -> Result<Media, Error> {
171
        if !matches!(request.format, MediaFormat::Thumbnail(_)) {
172
            return self.fetch(request, mimetype).await;
173
        }
174
        match self.fetch(request.clone(), mimetype.clone()).await {
175
            Err(error) if error.kind == ErrorKind::MediaUnavailable => {
176
                let file = MediaRequestParameters {
177
                    source: request.source,
178
                    format: MediaFormat::File,
179
                };
180
                self.fetch(file, mimetype).await
181
            }
182
            result => result,
183
        }
184
    }
185
186
    async fn fetch(
187
        &self,
188
        request: MediaRequestParameters,
189
        mimetype: Option<String>,
190
    ) -> Result<Media, Error> {
191
        let key = flight_key(&request);
192
        let flight = {
193
            let mut flights = self.flights.lock().await;
194
            flights.retain(|_, flight| flight.upgrade().is_some());
195
            match flights.get(&key).and_then(WeakShared::upgrade) {
196
                Some(flight) => flight,
197
                None => {
198
                    let prepared = AssertUnwindSafe(fetch(
199
                        self.client.clone(),
200
                        request,
201
                        mimetype,
202
                        self.max_bytes,
203
                    ))
204
                    .catch_unwind()
205
                    .map(|result| {
206
                        result.unwrap_or_else(|_| {
207
                            Err(Error::new(ErrorKind::Other, "media fetch panicked"))
208
                        })
209
                    });
210
                    let boxed: FlightFuture = Box::pin(prepared);
211
                    let flight: Flight = boxed.shared();
212
                    if let Some(weak) = flight.downgrade() {
213
                        flights.insert(key, weak);
214
                    }
215
                    flight
216
                }
217
            }
218
        };
219
        flight.await
220
    }
221
}
222
223
struct ChosenSource {
224
    request: MediaRequestParameters,
225
    mimetype: Option<String>,
226
    declared_size: Option<u64>,
227
}
228
229
fn plain_registration(media_id: &MediaId, uri: &MxcUri) -> Result<MediaRegistration, Error> {
230
    if !uri.is_valid() {
231
        return Err(Error::new(ErrorKind::Invalid, "mxc uri is malformed"));
232
    }
233
    Ok(MediaRegistration {
234
        id: media_id.clone(),
235
        kind: MediaKind::Image,
236
        full: MediaSourceInfo {
237
            source: MediaSource::Plain(uri.to_owned()),
238
            mimetype: None,
239
            declared_size: None,
240
        },
241
        thumbnail: None,
242
    })
243
}
244
245
fn choose_source(media: MediaRegistration, size: MediaSize) -> Result<ChosenSource, Error> {
246
    let (source, format, mimetype, declared_size) = match size {
247
        MediaSize::Full => (
248
            media.full.source,
249
            MediaFormat::File,
250
            media.full.mimetype,
251
            media.full.declared_size,
252
        ),
253
        MediaSize::Thumbnail { width, height } => match media.thumbnail {
254
            Some(thumbnail) => (
255
                thumbnail.source,
256
                MediaFormat::File,
257
                thumbnail.mimetype,
258
                thumbnail.declared_size,
259
            ),
260
            // the server can only resize what it can read
261
            None if matches!(media.kind, MediaKind::Image | MediaKind::Video)
262
                && matches!(media.full.source, MediaSource::Plain(_)) =>
263
            {
264
                // the server picks the thumbnail's type, so the original's would be a lie
265
                let format = if is_local(&media.full.source) {
266
                    MediaFormat::File
267
                } else {
268
                    thumbnail_format(width, height)
269
                };
270
                (media.full.source, format, None, None)
271
            }
272
            None => {
273
                return Err(Error::new(
274
                    ErrorKind::MediaUnavailable,
275
                    "the requested media size is unavailable",
276
                ));
277
            }
278
        },
279
    };
280
    Ok(ChosenSource {
281
        request: MediaRequestParameters { source, format },
282
        mimetype,
283
        declared_size,
284
    })
285
}
286
287
async fn media_file(
288
    client: &Client,
289
    request: MediaRequestParameters,
290
    mimetype: Option<String>,
291
    declared_size: Option<u64>,
292
) -> Result<MediaFile, Error> {
293
    let url = media_http_request(client, &request)
294
        .await?
295
        .uri()
296
        .to_string();
297
    let encryption = match &request.source {
298
        MediaSource::Plain(_) => None,
299
        MediaSource::Encrypted(file) => {
300
            let (EncryptedFileInfo::V2(info), Some(EncryptedFileHash::Sha256(sha256))) = (
301
                &file.info,
302
                file.hashes.get(&EncryptedFileHashAlgorithm::Sha256),
303
            ) else {
304
                return Err(Error::new(
305
                    ErrorKind::MediaUnavailable,
306
                    "encrypted media is not v2 with a sha256 hash",
307
                ));
308
            };
309
            Some(AttachmentEncryption {
310
                key: info.k.encode(),
311
                iv: info.iv.encode(),
312
                sha256: sha256.encode(),
313
            })
314
        }
315
    };
316
    Ok(MediaFile {
317
        url,
318
        mimetype,
319
        declared_size,
320
        encryption,
321
    })
322
}
323
324
fn thumbnail_format(width: u32, height: u32) -> MediaFormat {
325
    MediaFormat::Thumbnail(MediaThumbnailSettings::new(width.into(), height.into()))
326
}
327
328
fn is_local(source: &MediaSource) -> bool {
329
    let uri = match source {
330
        MediaSource::Plain(uri) => uri,
331
        MediaSource::Encrypted(file) => &file.url,
332
    };
333
    uri.server_name()
334
        .is_ok_and(|server| server.as_str() == "send-queue.localhost")
335
}
336
337
/// plain and encrypted sources share a cache key in the sdk, but must never share a flight
338
fn flight_key(request: &MediaRequestParameters) -> String {
339
    let uri = match &request.source {
340
        MediaSource::Plain(uri) => format!("plain|{uri}"),
341
        MediaSource::Encrypted(file) => format!("encrypted|{}", file.url),
342
    };
343
    match &request.format {
344
        MediaFormat::File => uri.to_owned(),
345
        MediaFormat::Thumbnail(settings) => format!(
346
            "{uri}|{}|{}x{}|{}",
347
            settings.method, settings.width, settings.height, settings.animated
348
        ),
349
    }
350
}
351
352
fn too_large(message: &'static str) -> Error {
353
    Error::new(ErrorKind::MediaTooLarge, message)
354
}
355
356
async fn fetch(
357
    client: Client,
358
    request: MediaRequestParameters,
359
    mimetype: Option<String>,
360
    max_bytes: usize,
361
) -> Result<Media, Error> {
362
    if let Some(cached) = cached_media(&client, &request).await? {
363
        if cached.len() > max_bytes {
364
            if let Ok(store) = client.media_store().lock().await {
365
                let _ = store.remove_media_content(&request).await;
366
            }
367
            return Err(too_large("cached media exceeds the configured byte limit"));
368
        }
369
        // plain and encrypted share a cache key, so a plain fetch of an encrypted file's uri
370
        // leaves ciphertext here. its hash gives it away
371
        if is_ciphertext(&cached, &request.source) {
372
            let bytes = maybe_decrypt(cached, &request, max_bytes)?;
373
            cache(&client, &request, &bytes).await;
374
            return Ok(media(bytes, mimetype));
375
        }
376
        return Ok(media(cached, mimetype));
377
    }
378
    let (bytes, served_mimetype) = download_bounded(&client, &request, max_bytes).await?;
379
    // the sdk caches plaintext under the encrypted key, so we do too or nobody can read anything
380
    let bytes = maybe_decrypt(bytes, &request, max_bytes)?;
381
    cache(&client, &request, &bytes).await;
382
    Ok(media(bytes, mimetype.or(served_mimetype)))
383
}
384
385
async fn cache(client: &Client, request: &MediaRequestParameters, bytes: &[u8]) {
386
    if let Ok(store) = client.media_store().lock().await {
387
        let _ = store
388
            .add_media_content(
389
                request,
390
                bytes.to_vec(),
391
                matrix_sdk::media::store::IgnoreMediaRetentionPolicy::No,
392
            )
393
            .await;
394
    }
395
}
396
397
fn is_ciphertext(bytes: &[u8], source: &MediaSource) -> bool {
398
    use sha2::{Digest, Sha256};
399
    let MediaSource::Encrypted(file) = source else {
400
        return false;
401
    };
402
    file.hashes
403
        .get(&ruma::events::room::EncryptedFileHashAlgorithm::Sha256)
404
        .is_some_and(|hash| hash.as_bytes() == Sha256::digest(bytes).as_slice())
405
}
406
407
fn media(bytes: Vec<u8>, mimetype: Option<String>) -> Media {
408
    let mimetype = mimetype
409
        .or_else(|| sniff_image(&bytes).map(str::to_owned))
410
        .unwrap_or_else(|| "application/octet-stream".to_owned());
411
    Media {
412
        bytes: Arc::from(bytes),
413
        mimetype,
414
    }
415
}
416
417
/// the cache forgets content types, and avatars never declare one. images are the common case
418
fn sniff_image(bytes: &[u8]) -> Option<&'static str> {
419
    match bytes {
420
        [0x89, b'P', b'N', b'G', ..] => Some("image/png"),
421
        [0xff, 0xd8, 0xff, ..] => Some("image/jpeg"),
422
        [b'G', b'I', b'F', b'8', ..] => Some("image/gif"),
423
        [
424
            b'R',
425
            b'I',
426
            b'F',
427
            b'F',
428
            _,
429
            _,
430
            _,
431
            _,
432
            b'W',
433
            b'E',
434
            b'B',
435
            b'P',
436
            ..,
437
        ] => Some("image/webp"),
438
        _ => None,
439
    }
440
}
441
442
async fn cached_media(
443
    client: &Client,
444
    request: &MediaRequestParameters,
445
) -> Result<Option<Vec<u8>>, Error> {
446
    fn cache_failed(
447
        source: impl std::error::Error + SendOutsideWasm + SyncOutsideWasm + 'static,
448
    ) -> Error {
449
        Error::with_source(ErrorKind::Store, "reading media cache failed", source)
450
    }
451
    client
452
        .media_store()
453
        .lock()
454
        .await
455
        .map_err(cache_failed)?
456
        .get_media_content(request)
457
        .await
458
        .map_err(cache_failed)
459
}
460
461
fn maybe_decrypt(
462
    bytes: Vec<u8>,
463
    request: &MediaRequestParameters,
464
    max_bytes: usize,
465
) -> Result<Vec<u8>, Error> {
466
    let MediaSource::Encrypted(file) = &request.source else {
467
        return Ok(bytes);
468
    };
469
    fn decrypt_failed(
470
        source: impl std::error::Error + SendOutsideWasm + SyncOutsideWasm + 'static,
471
    ) -> Error {
472
        Error::with_source(
473
            ErrorKind::MediaUnavailable,
474
            "media decryption failed",
475
            source,
476
        )
477
    }
478
    let info: MediaEncryptionInfo = (**file).clone().into();
479
    let mut cursor = std::io::Cursor::new(bytes);
480
    let mut decryptor = AttachmentDecryptor::new(&mut cursor, info).map_err(decrypt_failed)?;
481
    let mut decrypted = Vec::new();
482
    let mut chunk = [0_u8; 8192];
483
    loop {
484
        let read = decryptor.read(&mut chunk).map_err(decrypt_failed)?;
485
        if read == 0 {
486
            return Ok(decrypted);
487
        }
488
        if read > max_bytes.saturating_sub(decrypted.len()) {
489
            return Err(too_large(
490
                "decrypted media exceeds the configured byte limit",
491
            ));
492
        }
493
        decrypted.extend_from_slice(&chunk[..read]);
494
    }
495
}
496
497
/// the sdk's own download has no size cap, so we do it by hand
498
async fn download_bounded(
499
    client: &Client,
500
    request: &MediaRequestParameters,
501
    max_bytes: usize,
502
) -> Result<(Vec<u8>, Option<String>), Error> {
503
    if is_local(&request.source) {
504
        return Err(Error::new(
505
            ErrorKind::MediaUnavailable,
506
            "local media is not in the media cache",
507
        ));
508
    }
509
    let network_failed =
510
        |source| Error::with_source(ErrorKind::Network, "media download failed", source);
511
    let mut refreshed = false;
512
    let response = loop {
513
        let http_request = media_http_request(client, request).await?;
514
        let (parts, _) = http_request.into_parts();
515
        let mut builder = client
516
            .http_client()
517
            .get(parts.uri.to_string())
518
            .timeout(DOWNLOAD_TOTAL);
519
        for (name, value) in &parts.headers {
520
            builder = builder.header(name.as_str(), value.as_bytes());
521
        }
522
        let response = builder.send().await.map_err(network_failed)?;
523
        if response.status() != matrix_sdk::reqwest::StatusCode::UNAUTHORIZED {
524
            break response;
525
        }
526
        if refreshed
527
            || client
528
                .session_tokens()
529
                .is_none_or(|tokens| tokens.refresh_token.is_none())
530
        {
531
            return Err(Error::new(
532
                ErrorKind::Unauthenticated,
533
                "media download was not authorized",
534
            ));
535
        }
536
        client.refresh_access_token().await.map_err(|source| {
537
            Error::from_refresh_token("refreshing media access token failed", source)
538
        })?;
539
        refreshed = true;
540
    };
541
    let status = response.status();
542
    if !status.is_success() {
543
        return Err(Error::new(
544
            ErrorKind::MediaUnavailable,
545
            format!("media download failed with status {status}"),
546
        ));
547
    }
548
    if response
549
        .content_length()
550
        .is_some_and(|length| length > max_bytes as u64)
551
    {
552
        return Err(too_large("media exceeds the configured byte limit"));
553
    }
554
    let mimetype = response
555
        .headers()
556
        .get(http::header::CONTENT_TYPE)
557
        .and_then(|value| value.to_str().ok())
558
        .map(str::to_owned);
559
    let mut stream = response.bytes_stream();
560
    let mut bytes = Vec::new();
561
    loop {
562
        let chunk = matrix_sdk::timeout::timeout(stream.next(), DOWNLOAD_IDLE)
563
            .await
564
            .map_err(|_| Error::new(ErrorKind::Network, "media download stalled"))?;
565
        let Some(chunk) = chunk else { break };
566
        let chunk = chunk.map_err(network_failed)?;
567
        if chunk.len() > max_bytes.saturating_sub(bytes.len()) {
568
            return Err(too_large(
569
                "downloaded media exceeds the configured byte limit",
570
            ));
571
        }
572
        bytes.extend_from_slice(&chunk);
573
    }
574
    Ok((bytes, mimetype))
575
}
576
577
async fn media_http_request(
578
    client: &Client,
579
    request: &MediaRequestParameters,
580
) -> Result<http::Request<Vec<u8>>, Error> {
581
    let versions = client.supported_versions().await.map_err(|source| {
582
        Error::with_source(
583
            ErrorKind::Network,
584
            "reading supported server versions failed",
585
            source,
586
        )
587
    })?;
588
    let authenticated =
589
        authenticated_media::get_content::v1::Request::PATH_BUILDER.is_supported(&versions);
590
    let base = client.homeserver().to_string();
591
    let token = client.access_token();
592
    let invalid_uri =
593
        |source| Error::with_source(ErrorKind::Invalid, "media URI is invalid", source);
594
    let (uri, thumbnail) = match (&request.source, &request.format) {
595
        (MediaSource::Encrypted(file), _) => (&file.url, None),
596
        (MediaSource::Plain(uri), MediaFormat::File) => (uri, None),
597
        (MediaSource::Plain(uri), MediaFormat::Thumbnail(settings)) => (uri, Some(settings)),
598
    };
599
    // each endpoint has its own auth input type, so no generic helper can take them all
600
    macro_rules! into_http {
601
        ($endpoint:expr, $token:expr) => {
602
            $endpoint
603
                .try_into_http_request::<Vec<u8>>(&base, $token, Cow::Borrowed(&versions))
604
                .map_err(|source| {
605
                    Error::with_source(ErrorKind::Other, "media request is invalid", source)
606
                })?
607
        };
608
    }
609
    let authed = SendAccessToken::IfRequired(token.as_deref().unwrap_or(""));
610
    #[allow(deprecated)]
611
    let mut http_request = match (thumbnail, authenticated) {
612
        (None, true) => into_http!(
613
            authenticated_media::get_content::v1::Request::from_uri(uri).map_err(invalid_uri)?,
614
            authed
615
        ),
616
        (None, false) => into_http!(
617
            media::get_content::v3::Request::from_url(uri).map_err(invalid_uri)?,
618
            SendAccessToken::None
619
        ),
620
        (Some(settings), true) => {
621
            let mut endpoint = authenticated_media::get_content_thumbnail::v1::Request::from_uri(
622
                uri,
623
                settings.width,
624
                settings.height,
625
            )
626
            .map_err(invalid_uri)?;
627
            endpoint.method = Some(settings.method.clone());
628
            endpoint.animated = Some(settings.animated);
629
            into_http!(endpoint, authed)
630
        }
631
        (Some(settings), false) => {
632
            let mut endpoint = media::get_content_thumbnail::v3::Request::from_url(
633
                uri,
634
                settings.width,
635
                settings.height,
636
            )
637
            .map_err(invalid_uri)?;
638
            endpoint.method = Some(settings.method.clone());
639
            endpoint.animated = Some(settings.animated);
640
            into_http!(endpoint, SendAccessToken::None)
641
        }
642
    };
643
    // legacy endpoints don't ask for a token but plenty of servers want one anyway
644
    if let Some(token) = token.as_deref() {
645
        let value = format!("Bearer {token}").parse().map_err(|_| {
646
            Error::new(ErrorKind::Unauthenticated, "stored access token is invalid")
647
        })?;
648
        http_request
649
            .headers_mut()
650
            .insert(http::header::AUTHORIZATION, value);
651
    }
652
    Ok(http_request)
653
}
654
655
pub(crate) async fn queue_upload(
656
    room: Room,
657
    upload: AttachmentUpload,
658
    max_bytes: usize,
659
) -> Result<(), Error> {
660
    let (mut upload, mime, mut config) = prepare_upload(upload, max_bytes)?;
661
    let thread_root = upload.timeline_id.thread_root().cloned();
662
    config.reply = match (upload.reply_to.take(), thread_root) {
663
        (Some(event_id), thread_root) => {
664
            let reply = || SdkReply {
665
                event_id: event_id.clone(),
666
                enforce_thread: if thread_root.is_some() {
667
                    EnforceThread::Threaded(ReplyWithinThread::Yes)
668
                } else {
669
                    EnforceThread::MaybeThreaded
670
                },
671
                add_mentions: if upload.notify_replied_to {
672
                    AddMentions::Yes
673
                } else {
674
                    AddMentions::No
675
                },
676
            };
677
            if let Some(thread_root) = &thread_root {
678
                check_reply_thread(&room, reply(), thread_root).await?;
679
            }
680
            Some(reply())
681
        }
682
        (None, Some(root_event_id)) => Some(SdkReply {
683
            event_id: root_event_id,
684
            enforce_thread: EnforceThread::Threaded(ReplyWithinThread::No),
685
            add_mentions: AddMentions::No,
686
        }),
687
        (None, None) => None,
688
    };
689
    room.send_queue()
690
        .send_attachment(upload.filename, mime, upload.bytes, config)
691
        .await
692
        .map(drop)
693
        .map_err(|source| {
694
            use matrix_sdk::send_queue::RoomSendQueueError;
695
            let kind = match &source {
696
                RoomSendQueueError::RoomNotJoined | RoomSendQueueError::RoomDisappeared => {
697
                    ErrorKind::RoomUnknown
698
                }
699
                RoomSendQueueError::StorageError(_) => ErrorKind::Store,
700
                _ => ErrorKind::MediaUnavailable,
701
            };
702
            Error::with_source(kind, "media upload could not be queued", source)
703
        })
704
}
705
706
/// the send queue builds the relation itself, so a reply that would land in another thread has to be caught before it is queued
707
async fn check_reply_thread(
708
    room: &Room,
709
    reply: SdkReply,
710
    thread_root: &OwnedEventId,
711
) -> Result<(), Error> {
712
    let content = room
713
        .make_reply_event(RoomMessageEventContentWithoutRelation::text_plain(""), reply)
714
        .await
715
        .map_err(|source| {
716
            Error::with_source(ErrorKind::Timeline, "reply operation failed", source)
717
        })?;
718
    if matches!(
719
        content.relates_to.as_ref(),
720
        Some(Relation::Thread(thread)) if &thread.event_id == thread_root
721
    ) {
722
        Ok(())
723
    } else {
724
        Err(Error::new(
725
            ErrorKind::Invalid,
726
            "reply target does not belong to the selected thread",
727
        ))
728
    }
729
}
730
731
/// least recently seen goes first. stale order slots are skipped by stamp rather than hunted down
732
struct MediaRegistry {
733
    entries: HashMap<MediaId, (MediaRegistration, u64)>,
734
    order: VecDeque<(MediaId, u64)>,
735
    next_stamp: u64,
736
    limit: usize,
737
}
738
739
impl MediaRegistry {
740
    fn new(limit: usize) -> Self {
741
        Self {
742
            entries: HashMap::new(),
743
            order: VecDeque::new(),
744
            next_stamp: 0,
745
            limit,
746
        }
747
    }
748
749
    fn get(&self, id: &MediaId) -> Option<&MediaRegistration> {
750
        self.entries.get(id).map(|(media, _)| media)
751
    }
752
753
    fn insert_all(&mut self, media: Vec<MediaRegistration>) {
754
        for media in media {
755
            let stamp = self.next_stamp;
756
            self.next_stamp += 1;
757
            self.order.push_back((media.id.clone(), stamp));
758
            self.entries.insert(media.id.clone(), (media, stamp));
759
        }
760
        while self.entries.len() > self.limit {
761
            let Some((id, stamp)) = self.order.pop_front() else {
762
                break;
763
            };
764
            if self.is_current(&id, stamp) {
765
                self.entries.remove(&id);
766
            }
767
        }
768
        if self.order.len() > self.limit.saturating_mul(4) {
769
            let entries = &self.entries;
770
            self.order
771
                .retain(|(id, stamp)| entries.get(id).is_some_and(|(_, current)| current == stamp));
772
        }
773
    }
774
775
    fn is_current(&self, id: &MediaId, stamp: u64) -> bool {
776
        self.entries
777
            .get(id)
778
            .is_some_and(|(_, current)| *current == stamp)
779
    }
780
781
    fn release(&mut self, scope: &MediaScope) {
782
        self.entries.retain(|id, _| !scope.owns(id));
783
        let entries = &self.entries;
784
        self.order.retain(|(id, _)| entries.contains_key(id));
785
    }
786
787
    fn clear(&mut self) {
788
        self.entries.clear();
789
        self.order.clear();
790
    }
791
}