atagen

macltok

public
Star0
Watch0
fa51490b6ae98fdf5eeddb0799f4e3a160bf53cb
3
ssh://brewery@pls.lobotomise.me:33/atagen/macltok.git
src/engine/media.rsRust807 lines26.8 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
pub(crate) async fn download_file(
357
    client: &Client,
358
    source: MediaSource,
359
    mimetype: Option<String>,
360
    max_bytes: usize,
361
) -> Result<Media, Error> {
362
    let request = MediaRequestParameters {
363
        source,
364
        format: MediaFormat::File,
365
    };
366
    fetch(client.clone(), request, mimetype, max_bytes).await
367
}
368
369
async fn fetch(
370
    client: Client,
371
    request: MediaRequestParameters,
372
    mimetype: Option<String>,
373
    max_bytes: usize,
374
) -> Result<Media, Error> {
375
    if let Some(cached) = cached_media(&client, &request).await? {
376
        if cached.len() > max_bytes {
377
            if let Ok(store) = client.media_store().lock().await {
378
                let _ = store.remove_media_content(&request).await;
379
            }
380
            return Err(too_large("cached media exceeds the configured byte limit"));
381
        }
382
        // plain and encrypted share a cache key, so a plain fetch of an encrypted file's uri
383
        // leaves ciphertext here. its hash gives it away
384
        if is_ciphertext(&cached, &request.source) {
385
            let bytes = maybe_decrypt(cached, &request, max_bytes)?;
386
            cache(&client, &request, &bytes).await;
387
            return Ok(media(bytes, mimetype));
388
        }
389
        return Ok(media(cached, mimetype));
390
    }
391
    let (bytes, served_mimetype) = download_bounded(&client, &request, max_bytes).await?;
392
    // the sdk caches plaintext under the encrypted key, so we do too or nobody can read anything
393
    let bytes = maybe_decrypt(bytes, &request, max_bytes)?;
394
    cache(&client, &request, &bytes).await;
395
    Ok(media(bytes, mimetype.or(served_mimetype)))
396
}
397
398
async fn cache(client: &Client, request: &MediaRequestParameters, bytes: &[u8]) {
399
    if let Ok(store) = client.media_store().lock().await {
400
        let _ = store
401
            .add_media_content(
402
                request,
403
                bytes.to_vec(),
404
                matrix_sdk::media::store::IgnoreMediaRetentionPolicy::No,
405
            )
406
            .await;
407
    }
408
}
409
410
fn is_ciphertext(bytes: &[u8], source: &MediaSource) -> bool {
411
    use sha2::{Digest, Sha256};
412
    let MediaSource::Encrypted(file) = source else {
413
        return false;
414
    };
415
    file.hashes
416
        .get(&ruma::events::room::EncryptedFileHashAlgorithm::Sha256)
417
        .is_some_and(|hash| hash.as_bytes() == Sha256::digest(bytes).as_slice())
418
}
419
420
fn media(bytes: Vec<u8>, mimetype: Option<String>) -> Media {
421
    let mimetype = mimetype
422
        .or_else(|| sniff_image(&bytes).map(str::to_owned))
423
        .unwrap_or_else(|| "application/octet-stream".to_owned());
424
    Media {
425
        bytes: Arc::from(bytes),
426
        mimetype,
427
    }
428
}
429
430
/// the cache forgets content types, and avatars never declare one. images are the common case
431
fn sniff_image(bytes: &[u8]) -> Option<&'static str> {
432
    match bytes {
433
        [0x89, b'P', b'N', b'G', ..] => Some("image/png"),
434
        [0xff, 0xd8, 0xff, ..] => Some("image/jpeg"),
435
        [b'G', b'I', b'F', b'8', ..] => Some("image/gif"),
436
        [
437
            b'R',
438
            b'I',
439
            b'F',
440
            b'F',
441
            _,
442
            _,
443
            _,
444
            _,
445
            b'W',
446
            b'E',
447
            b'B',
448
            b'P',
449
            ..,
450
        ] => Some("image/webp"),
451
        _ => None,
452
    }
453
}
454
455
async fn cached_media(
456
    client: &Client,
457
    request: &MediaRequestParameters,
458
) -> Result<Option<Vec<u8>>, Error> {
459
    fn cache_failed(
460
        source: impl std::error::Error + SendOutsideWasm + SyncOutsideWasm + 'static,
461
    ) -> Error {
462
        Error::with_source(ErrorKind::Store, "reading media cache failed", source)
463
    }
464
    client
465
        .media_store()
466
        .lock()
467
        .await
468
        .map_err(cache_failed)?
469
        .get_media_content(request)
470
        .await
471
        .map_err(cache_failed)
472
}
473
474
fn maybe_decrypt(
475
    bytes: Vec<u8>,
476
    request: &MediaRequestParameters,
477
    max_bytes: usize,
478
) -> Result<Vec<u8>, Error> {
479
    let MediaSource::Encrypted(file) = &request.source else {
480
        return Ok(bytes);
481
    };
482
    fn decrypt_failed(
483
        source: impl std::error::Error + SendOutsideWasm + SyncOutsideWasm + 'static,
484
    ) -> Error {
485
        Error::with_source(
486
            ErrorKind::MediaUnavailable,
487
            "media decryption failed",
488
            source,
489
        )
490
    }
491
    let info: MediaEncryptionInfo = (**file).clone().into();
492
    let mut cursor = std::io::Cursor::new(bytes);
493
    let mut decryptor = AttachmentDecryptor::new(&mut cursor, info).map_err(decrypt_failed)?;
494
    let mut decrypted = Vec::new();
495
    let mut chunk = [0_u8; 8192];
496
    loop {
497
        let read = decryptor.read(&mut chunk).map_err(decrypt_failed)?;
498
        if read == 0 {
499
            return Ok(decrypted);
500
        }
501
        if read > max_bytes.saturating_sub(decrypted.len()) {
502
            return Err(too_large(
503
                "decrypted media exceeds the configured byte limit",
504
            ));
505
        }
506
        decrypted.extend_from_slice(&chunk[..read]);
507
    }
508
}
509
510
/// the sdk's own download has no size cap, so we do it by hand
511
async fn download_bounded(
512
    client: &Client,
513
    request: &MediaRequestParameters,
514
    max_bytes: usize,
515
) -> Result<(Vec<u8>, Option<String>), Error> {
516
    if is_local(&request.source) {
517
        return Err(Error::new(
518
            ErrorKind::MediaUnavailable,
519
            "local media is not in the media cache",
520
        ));
521
    }
522
    let network_failed =
523
        |source| Error::with_source(ErrorKind::Network, "media download failed", source);
524
    let mut refreshed = false;
525
    let response = loop {
526
        let http_request = media_http_request(client, request).await?;
527
        let (parts, _) = http_request.into_parts();
528
        let mut builder = client
529
            .http_client()
530
            .get(parts.uri.to_string())
531
            .timeout(DOWNLOAD_TOTAL);
532
        for (name, value) in &parts.headers {
533
            builder = builder.header(name.as_str(), value.as_bytes());
534
        }
535
        let response = builder.send().await.map_err(network_failed)?;
536
        if response.status() != matrix_sdk::reqwest::StatusCode::UNAUTHORIZED {
537
            break response;
538
        }
539
        if refreshed
540
            || client
541
                .session_tokens()
542
                .is_none_or(|tokens| tokens.refresh_token.is_none())
543
        {
544
            return Err(Error::new(
545
                ErrorKind::Unauthenticated,
546
                "media download was not authorized",
547
            ));
548
        }
549
        client.refresh_access_token().await.map_err(|source| {
550
            Error::from_refresh_token("refreshing media access token failed", source)
551
        })?;
552
        refreshed = true;
553
    };
554
    let status = response.status();
555
    if !status.is_success() {
556
        return Err(Error::new(
557
            ErrorKind::MediaUnavailable,
558
            format!("media download failed with status {status}"),
559
        ));
560
    }
561
    if response
562
        .content_length()
563
        .is_some_and(|length| length > max_bytes as u64)
564
    {
565
        return Err(too_large("media exceeds the configured byte limit"));
566
    }
567
    let mimetype = response
568
        .headers()
569
        .get(http::header::CONTENT_TYPE)
570
        .and_then(|value| value.to_str().ok())
571
        .map(str::to_owned);
572
    let mut stream = response.bytes_stream();
573
    let mut bytes = Vec::new();
574
    loop {
575
        let chunk = matrix_sdk::timeout::timeout(stream.next(), DOWNLOAD_IDLE)
576
            .await
577
            .map_err(|_| Error::new(ErrorKind::Network, "media download stalled"))?;
578
        let Some(chunk) = chunk else { break };
579
        let chunk = chunk.map_err(network_failed)?;
580
        if chunk.len() > max_bytes.saturating_sub(bytes.len()) {
581
            return Err(too_large(
582
                "downloaded media exceeds the configured byte limit",
583
            ));
584
        }
585
        bytes.extend_from_slice(&chunk);
586
    }
587
    Ok((bytes, mimetype))
588
}
589
590
async fn media_http_request(
591
    client: &Client,
592
    request: &MediaRequestParameters,
593
) -> Result<http::Request<Vec<u8>>, Error> {
594
    let versions = client.supported_versions().await.map_err(|source| {
595
        Error::with_source(
596
            ErrorKind::Network,
597
            "reading supported server versions failed",
598
            source,
599
        )
600
    })?;
601
    let authenticated =
602
        authenticated_media::get_content::v1::Request::PATH_BUILDER.is_supported(&versions);
603
    let base = client.homeserver().to_string();
604
    let token = client.access_token();
605
    let invalid_uri =
606
        |source| Error::with_source(ErrorKind::Invalid, "media URI is invalid", source);
607
    let (uri, thumbnail) = match (&request.source, &request.format) {
608
        (MediaSource::Encrypted(file), _) => (&file.url, None),
609
        (MediaSource::Plain(uri), MediaFormat::File) => (uri, None),
610
        (MediaSource::Plain(uri), MediaFormat::Thumbnail(settings)) => (uri, Some(settings)),
611
    };
612
    // each endpoint has its own auth input type, so no generic helper can take them all
613
    macro_rules! into_http {
614
        ($endpoint:expr, $token:expr) => {
615
            $endpoint
616
                .try_into_http_request::<Vec<u8>>(&base, $token, Cow::Borrowed(&versions))
617
                .map_err(|source| {
618
                    Error::with_source(ErrorKind::Other, "media request is invalid", source)
619
                })?
620
        };
621
    }
622
    let authed = SendAccessToken::IfRequired(token.as_deref().unwrap_or(""));
623
    #[allow(deprecated)]
624
    let mut http_request = match (thumbnail, authenticated) {
625
        (None, true) => into_http!(
626
            authenticated_media::get_content::v1::Request::from_uri(uri).map_err(invalid_uri)?,
627
            authed
628
        ),
629
        (None, false) => into_http!(
630
            media::get_content::v3::Request::from_url(uri).map_err(invalid_uri)?,
631
            SendAccessToken::None
632
        ),
633
        (Some(settings), true) => {
634
            let mut endpoint = authenticated_media::get_content_thumbnail::v1::Request::from_uri(
635
                uri,
636
                settings.width,
637
                settings.height,
638
            )
639
            .map_err(invalid_uri)?;
640
            endpoint.method = Some(settings.method.clone());
641
            endpoint.animated = Some(settings.animated);
642
            into_http!(endpoint, authed)
643
        }
644
        (Some(settings), false) => {
645
            let mut endpoint = media::get_content_thumbnail::v3::Request::from_url(
646
                uri,
647
                settings.width,
648
                settings.height,
649
            )
650
            .map_err(invalid_uri)?;
651
            endpoint.method = Some(settings.method.clone());
652
            endpoint.animated = Some(settings.animated);
653
            into_http!(endpoint, SendAccessToken::None)
654
        }
655
    };
656
    // legacy endpoints don't ask for a token but plenty of servers want one anyway
657
    if let Some(token) = token.as_deref() {
658
        let value = format!("Bearer {token}").parse().map_err(|_| {
659
            Error::new(ErrorKind::Unauthenticated, "stored access token is invalid")
660
        })?;
661
        http_request
662
            .headers_mut()
663
            .insert(http::header::AUTHORIZATION, value);
664
    }
665
    Ok(http_request)
666
}
667
668
pub(crate) async fn queue_upload(
669
    room: Room,
670
    upload: AttachmentUpload,
671
    max_bytes: usize,
672
) -> Result<(), Error> {
673
    let (mut upload, mime, mut config) = prepare_upload(upload, max_bytes)?;
674
    let thread_root = upload.timeline_id.thread_root().cloned();
675
    config.reply = match (upload.reply_to.take(), thread_root) {
676
        (Some(event_id), thread_root) => {
677
            let reply = || SdkReply {
678
                event_id: event_id.clone(),
679
                enforce_thread: if thread_root.is_some() {
680
                    EnforceThread::Threaded(ReplyWithinThread::Yes)
681
                } else {
682
                    EnforceThread::MaybeThreaded
683
                },
684
                add_mentions: if upload.notify_replied_to {
685
                    AddMentions::Yes
686
                } else {
687
                    AddMentions::No
688
                },
689
            };
690
            if let Some(thread_root) = &thread_root {
691
                check_reply_thread(&room, reply(), thread_root).await?;
692
            }
693
            Some(reply())
694
        }
695
        (None, Some(root_event_id)) => Some(SdkReply {
696
            event_id: root_event_id,
697
            enforce_thread: EnforceThread::Threaded(ReplyWithinThread::No),
698
            add_mentions: AddMentions::No,
699
        }),
700
        (None, None) => None,
701
    };
702
    room.send_queue()
703
        .send_attachment(upload.filename, mime, upload.bytes, config)
704
        .await
705
        .map(drop)
706
        .map_err(|source| {
707
            use matrix_sdk::send_queue::RoomSendQueueError;
708
            let kind = match &source {
709
                RoomSendQueueError::RoomNotJoined | RoomSendQueueError::RoomDisappeared => {
710
                    ErrorKind::RoomUnknown
711
                }
712
                RoomSendQueueError::StorageError(_) => ErrorKind::Store,
713
                _ => ErrorKind::MediaUnavailable,
714
            };
715
            Error::with_source(kind, "media upload could not be queued", source)
716
        })
717
}
718
719
/// the send queue builds the relation itself, so a reply that would land in another thread has to be caught before it is queued
720
async fn check_reply_thread(
721
    room: &Room,
722
    reply: SdkReply,
723
    thread_root: &OwnedEventId,
724
) -> Result<(), Error> {
725
    let content = room
726
        .make_reply_event(
727
            RoomMessageEventContentWithoutRelation::text_plain(""),
728
            reply,
729
        )
730
        .await
731
        .map_err(|source| {
732
            Error::with_source(ErrorKind::Timeline, "reply operation failed", source)
733
        })?;
734
    if matches!(
735
        content.relates_to.as_ref(),
736
        Some(Relation::Thread(thread)) if &thread.event_id == thread_root
737
    ) {
738
        Ok(())
739
    } else {
740
        Err(Error::new(
741
            ErrorKind::Invalid,
742
            "reply target does not belong to the selected thread",
743
        ))
744
    }
745
}
746
747
/// least recently seen goes first. stale order slots are skipped by stamp rather than hunted down
748
struct MediaRegistry {
749
    entries: HashMap<MediaId, (MediaRegistration, u64)>,
750
    order: VecDeque<(MediaId, u64)>,
751
    next_stamp: u64,
752
    limit: usize,
753
}
754
755
impl MediaRegistry {
756
    fn new(limit: usize) -> Self {
757
        Self {
758
            entries: HashMap::new(),
759
            order: VecDeque::new(),
760
            next_stamp: 0,
761
            limit,
762
        }
763
    }
764
765
    fn get(&self, id: &MediaId) -> Option<&MediaRegistration> {
766
        self.entries.get(id).map(|(media, _)| media)
767
    }
768
769
    fn insert_all(&mut self, media: Vec<MediaRegistration>) {
770
        for media in media {
771
            let stamp = self.next_stamp;
772
            self.next_stamp += 1;
773
            self.order.push_back((media.id.clone(), stamp));
774
            self.entries.insert(media.id.clone(), (media, stamp));
775
        }
776
        while self.entries.len() > self.limit {
777
            let Some((id, stamp)) = self.order.pop_front() else {
778
                break;
779
            };
780
            if self.is_current(&id, stamp) {
781
                self.entries.remove(&id);
782
            }
783
        }
784
        if self.order.len() > self.limit.saturating_mul(4) {
785
            let entries = &self.entries;
786
            self.order
787
                .retain(|(id, stamp)| entries.get(id).is_some_and(|(_, current)| current == stamp));
788
        }
789
    }
790
791
    fn is_current(&self, id: &MediaId, stamp: u64) -> bool {
792
        self.entries
793
            .get(id)
794
            .is_some_and(|(_, current)| *current == stamp)
795
    }
796
797
    fn release(&mut self, scope: &MediaScope) {
798
        self.entries.retain(|id, _| !scope.owns(id));
799
        let entries = &self.entries;
800
        self.order.retain(|(id, _)| entries.contains_key(id));
801
    }
802
803
    fn clear(&mut self) {
804
        self.entries.clear();
805
        self.order.clear();
806
    }
807
}