atagen

macltok

public
Star0
Watch0
5a52012c9b1d7ec241e293fb63039a10884d6fdc
3
ssh://brewery@pls.lobotomise.me:33/atagen/macltok.git

Blame: src/engine/media.rs

31ce2453c82fatagen2026-09-24 13:07 UTC1
use std::{
31ce2453c82fatagen2026-09-24 13:07 UTC2
    borrow::Cow,
31ce2453c82fatagen2026-09-24 13:07 UTC3
    collections::{HashMap, VecDeque},
31ce2453c82fatagen2026-09-24 13:07 UTC4
    io::Read as _,
31ce2453c82fatagen2026-09-24 13:07 UTC5
    panic::AssertUnwindSafe,
31ce2453c82fatagen2026-09-24 13:07 UTC6
    sync::Arc,
5a52012c9b1datagen2026-09-24 23:45 UTC7
    time::Duration,
31ce2453c82fatagen2026-09-24 13:07 UTC8
};
31ce2453c82fatagen2026-09-24 13:07 UTC9
31ce2453c82fatagen2026-09-24 13:07 UTC10
use futures_util::{
31ce2453c82fatagen2026-09-24 13:07 UTC11
    FutureExt, StreamExt,
31ce2453c82fatagen2026-09-24 13:07 UTC12
    future::{BoxFuture, Shared, WeakShared},
31ce2453c82fatagen2026-09-24 13:07 UTC13
};
31ce2453c82fatagen2026-09-24 13:07 UTC14
use matrix_sdk::{
31ce2453c82fatagen2026-09-24 13:07 UTC15
    Client, Room,
31ce2453c82fatagen2026-09-24 13:07 UTC16
    media::{MediaFormat, MediaRequestParameters, MediaThumbnailSettings},
31ce2453c82fatagen2026-09-24 13:07 UTC17
    room::reply::{EnforceThread, Reply as SdkReply},
31ce2453c82fatagen2026-09-24 13:07 UTC18
    ruma::{
31ce2453c82fatagen2026-09-24 13:07 UTC19
        api::{
31ce2453c82fatagen2026-09-24 13:07 UTC20
            Metadata, OutgoingRequest,
31ce2453c82fatagen2026-09-24 13:07 UTC21
            auth_scheme::SendAccessToken,
31ce2453c82fatagen2026-09-24 13:07 UTC22
            client::{authenticated_media, media},
31ce2453c82fatagen2026-09-24 13:07 UTC23
        },
31ce2453c82fatagen2026-09-24 13:07 UTC24
        events::room::{
31ce2453c82fatagen2026-09-24 13:07 UTC25
            MediaSource,
31ce2453c82fatagen2026-09-24 13:07 UTC26
            message::{AddMentions, ReplyWithinThread},
31ce2453c82fatagen2026-09-24 13:07 UTC27
        },
31ce2453c82fatagen2026-09-24 13:07 UTC28
    },
31ce2453c82fatagen2026-09-24 13:07 UTC29
};
31ce2453c82fatagen2026-09-24 13:07 UTC30
use matrix_sdk_crypto::{AttachmentDecryptor, MediaEncryptionInfo};
31ce2453c82fatagen2026-09-24 13:07 UTC31
use ruma::MxcUri;
31ce2453c82fatagen2026-09-24 13:07 UTC32
use tokio::sync::Mutex;
31ce2453c82fatagen2026-09-24 13:07 UTC33
31ce2453c82fatagen2026-09-24 13:07 UTC34
use crate::{
31ce2453c82fatagen2026-09-24 13:07 UTC35
    AttachmentUpload, Error, ErrorKind, Media, MediaId, MediaKind, MediaSize, TimelineId,
31ce2453c82fatagen2026-09-24 13:07 UTC36
    normalise::{MediaRegistration, MediaScope},
31ce2453c82fatagen2026-09-24 13:07 UTC37
    upload::prepare_upload,
31ce2453c82fatagen2026-09-24 13:07 UTC38
};
31ce2453c82fatagen2026-09-24 13:07 UTC39
5a52012c9b1datagen2026-09-24 23:45 UTC40
/// a stalled download gives up after this long without a byte
5a52012c9b1datagen2026-09-24 23:45 UTC41
const DOWNLOAD_IDLE: Duration = Duration::from_secs(60);
5a52012c9b1datagen2026-09-24 23:45 UTC42
/// the sdk client gives up on any request after thirty seconds, far too soon for a video
5a52012c9b1datagen2026-09-24 23:45 UTC43
const DOWNLOAD_TOTAL: Duration = Duration::from_secs(60 * 60);
31ce2453c82fatagen2026-09-24 13:07 UTC44
31ce2453c82fatagen2026-09-24 13:07 UTC45
type FlightFuture = BoxFuture<'static, Result<Media, Error>>;
31ce2453c82fatagen2026-09-24 13:07 UTC46
type Flight = Shared<FlightFuture>;
31ce2453c82fatagen2026-09-24 13:07 UTC47
31ce2453c82fatagen2026-09-24 13:07 UTC48
/// owns everything needed to turn a media id or an mxc uri into bytes, so the
31ce2453c82fatagen2026-09-24 13:07 UTC49
/// handle can answer media queries without a trip through the engine
31ce2453c82fatagen2026-09-24 13:07 UTC50
pub(crate) struct MediaService {
31ce2453c82fatagen2026-09-24 13:07 UTC51
    client: Client,
31ce2453c82fatagen2026-09-24 13:07 UTC52
    registry: Mutex<MediaRegistry>,
31ce2453c82fatagen2026-09-24 13:07 UTC53
    flights: Mutex<HashMap<String, WeakShared<FlightFuture>>>,
31ce2453c82fatagen2026-09-24 13:07 UTC54
    max_bytes: usize,
31ce2453c82fatagen2026-09-24 13:07 UTC55
}
31ce2453c82fatagen2026-09-24 13:07 UTC56
31ce2453c82fatagen2026-09-24 13:07 UTC57
impl MediaService {
31ce2453c82fatagen2026-09-24 13:07 UTC58
    pub(crate) fn new(client: Client, max_bytes: usize, max_sources: usize) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC59
        Self {
31ce2453c82fatagen2026-09-24 13:07 UTC60
            client,
31ce2453c82fatagen2026-09-24 13:07 UTC61
            registry: Mutex::new(MediaRegistry::new(max_sources)),
31ce2453c82fatagen2026-09-24 13:07 UTC62
            flights: Mutex::new(HashMap::new()),
31ce2453c82fatagen2026-09-24 13:07 UTC63
            max_bytes,
31ce2453c82fatagen2026-09-24 13:07 UTC64
        }
31ce2453c82fatagen2026-09-24 13:07 UTC65
    }
31ce2453c82fatagen2026-09-24 13:07 UTC66
31ce2453c82fatagen2026-09-24 13:07 UTC67
    pub(crate) async fn register(&self, media: Vec<MediaRegistration>) {
31ce2453c82fatagen2026-09-24 13:07 UTC68
        if !media.is_empty() {
31ce2453c82fatagen2026-09-24 13:07 UTC69
            self.registry.lock().await.insert_all(media);
31ce2453c82fatagen2026-09-24 13:07 UTC70
        }
31ce2453c82fatagen2026-09-24 13:07 UTC71
    }
31ce2453c82fatagen2026-09-24 13:07 UTC72
31ce2453c82fatagen2026-09-24 13:07 UTC73
    pub(crate) async fn release(&self, scope: &MediaScope) {
31ce2453c82fatagen2026-09-24 13:07 UTC74
        self.registry.lock().await.release(scope);
31ce2453c82fatagen2026-09-24 13:07 UTC75
    }
31ce2453c82fatagen2026-09-24 13:07 UTC76
31ce2453c82fatagen2026-09-24 13:07 UTC77
    pub(crate) async fn clear(&self) {
31ce2453c82fatagen2026-09-24 13:07 UTC78
        self.registry.lock().await.clear();
31ce2453c82fatagen2026-09-24 13:07 UTC79
    }
31ce2453c82fatagen2026-09-24 13:07 UTC80
31ce2453c82fatagen2026-09-24 13:07 UTC81
    pub(crate) async fn timeline_media(
31ce2453c82fatagen2026-09-24 13:07 UTC82
        &self,
31ce2453c82fatagen2026-09-24 13:07 UTC83
        media_id: &MediaId,
31ce2453c82fatagen2026-09-24 13:07 UTC84
        size: MediaSize,
31ce2453c82fatagen2026-09-24 13:07 UTC85
    ) -> Result<Media, Error> {
31ce2453c82fatagen2026-09-24 13:07 UTC86
        let media = self
31ce2453c82fatagen2026-09-24 13:07 UTC87
            .registry
31ce2453c82fatagen2026-09-24 13:07 UTC88
            .lock()
31ce2453c82fatagen2026-09-24 13:07 UTC89
            .await
31ce2453c82fatagen2026-09-24 13:07 UTC90
            .get(media_id)
31ce2453c82fatagen2026-09-24 13:07 UTC91
            .cloned()
31ce2453c82fatagen2026-09-24 13:07 UTC92
            .ok_or_else(|| {
31ce2453c82fatagen2026-09-24 13:07 UTC93
                Error::new(
31ce2453c82fatagen2026-09-24 13:07 UTC94
                    ErrorKind::MediaUnknown,
31ce2453c82fatagen2026-09-24 13:07 UTC95
                    "media is not registered in a retained timeline",
31ce2453c82fatagen2026-09-24 13:07 UTC96
                )
31ce2453c82fatagen2026-09-24 13:07 UTC97
            })?;
31ce2453c82fatagen2026-09-24 13:07 UTC98
        let (source, format, mimetype, declared_size) = match size {
31ce2453c82fatagen2026-09-24 13:07 UTC99
            MediaSize::Full => (
31ce2453c82fatagen2026-09-24 13:07 UTC100
                media.full.source,
31ce2453c82fatagen2026-09-24 13:07 UTC101
                MediaFormat::File,
31ce2453c82fatagen2026-09-24 13:07 UTC102
                media.full.mimetype,
31ce2453c82fatagen2026-09-24 13:07 UTC103
                media.full.declared_size,
31ce2453c82fatagen2026-09-24 13:07 UTC104
            ),
5a52012c9b1datagen2026-09-24 23:45 UTC105
            MediaSize::Thumbnail { width, height } => match media.thumbnail {
31ce2453c82fatagen2026-09-24 13:07 UTC106
                Some(thumbnail) => (
31ce2453c82fatagen2026-09-24 13:07 UTC107
                    thumbnail.source,
31ce2453c82fatagen2026-09-24 13:07 UTC108
                    MediaFormat::File,
31ce2453c82fatagen2026-09-24 13:07 UTC109
                    thumbnail.mimetype,
31ce2453c82fatagen2026-09-24 13:07 UTC110
                    thumbnail.declared_size,
31ce2453c82fatagen2026-09-24 13:07 UTC111
                ),
31ce2453c82fatagen2026-09-24 13:07 UTC112
                // the server can only resize what it can read
31ce2453c82fatagen2026-09-24 13:07 UTC113
                None if matches!(media.kind, MediaKind::Image | MediaKind::Video)
31ce2453c82fatagen2026-09-24 13:07 UTC114
                    && matches!(media.full.source, MediaSource::Plain(_)) =>
31ce2453c82fatagen2026-09-24 13:07 UTC115
                {
5a52012c9b1datagen2026-09-24 23:45 UTC116
                    // the server picks the thumbnail's type, so the original's would be a lie
5a52012c9b1datagen2026-09-24 23:45 UTC117
                    let format = if is_local(&media.full.source) {
5a52012c9b1datagen2026-09-24 23:45 UTC118
                        MediaFormat::File
5a52012c9b1datagen2026-09-24 23:45 UTC119
                    } else {
5a52012c9b1datagen2026-09-24 23:45 UTC120
                        thumbnail_format(width, height)
5a52012c9b1datagen2026-09-24 23:45 UTC121
                    };
5a52012c9b1datagen2026-09-24 23:45 UTC122
                    (media.full.source, format, None, None)
31ce2453c82fatagen2026-09-24 13:07 UTC123
                }
31ce2453c82fatagen2026-09-24 13:07 UTC124
                None => {
31ce2453c82fatagen2026-09-24 13:07 UTC125
                    return Err(Error::new(
31ce2453c82fatagen2026-09-24 13:07 UTC126
                        ErrorKind::MediaUnavailable,
31ce2453c82fatagen2026-09-24 13:07 UTC127
                        "the requested media size is unavailable",
31ce2453c82fatagen2026-09-24 13:07 UTC128
                    ));
31ce2453c82fatagen2026-09-24 13:07 UTC129
                }
31ce2453c82fatagen2026-09-24 13:07 UTC130
            },
31ce2453c82fatagen2026-09-24 13:07 UTC131
        };
31ce2453c82fatagen2026-09-24 13:07 UTC132
        if declared_size.is_some_and(|size| size > self.max_bytes as u64) {
31ce2453c82fatagen2026-09-24 13:07 UTC133
            return Err(too_large("media exceeds the configured byte limit"));
31ce2453c82fatagen2026-09-24 13:07 UTC134
        }
5a52012c9b1datagen2026-09-24 23:45 UTC135
        self.fetch_or_file(MediaRequestParameters { source, format }, mimetype)
31ce2453c82fatagen2026-09-24 13:07 UTC136
            .await
31ce2453c82fatagen2026-09-24 13:07 UTC137
    }
31ce2453c82fatagen2026-09-24 13:07 UTC138
31ce2453c82fatagen2026-09-24 13:07 UTC139
    pub(crate) async fn mxc_media(&self, uri: &MxcUri, size: MediaSize) -> Result<Media, Error> {
31ce2453c82fatagen2026-09-24 13:07 UTC140
        if !uri.is_valid() {
31ce2453c82fatagen2026-09-24 13:07 UTC141
            return Err(Error::new(ErrorKind::Invalid, "mxc uri is malformed"));
31ce2453c82fatagen2026-09-24 13:07 UTC142
        }
31ce2453c82fatagen2026-09-24 13:07 UTC143
        let format = match size {
31ce2453c82fatagen2026-09-24 13:07 UTC144
            MediaSize::Full => MediaFormat::File,
31ce2453c82fatagen2026-09-24 13:07 UTC145
            MediaSize::Thumbnail { width, height } => thumbnail_format(width, height),
31ce2453c82fatagen2026-09-24 13:07 UTC146
        };
5a52012c9b1datagen2026-09-24 23:45 UTC147
        self.fetch_or_file(
31ce2453c82fatagen2026-09-24 13:07 UTC148
            MediaRequestParameters {
31ce2453c82fatagen2026-09-24 13:07 UTC149
                source: MediaSource::Plain(uri.to_owned()),
31ce2453c82fatagen2026-09-24 13:07 UTC150
                format,
31ce2453c82fatagen2026-09-24 13:07 UTC151
            },
31ce2453c82fatagen2026-09-24 13:07 UTC152
            None,
31ce2453c82fatagen2026-09-24 13:07 UTC153
        )
31ce2453c82fatagen2026-09-24 13:07 UTC154
        .await
31ce2453c82fatagen2026-09-24 13:07 UTC155
    }
31ce2453c82fatagen2026-09-24 13:07 UTC156
5a52012c9b1datagen2026-09-24 23:45 UTC157
    /// plenty of servers won't thumbnail everything, and the file itself is the next best
5a52012c9b1datagen2026-09-24 23:45 UTC158
    /// thing. the byte cap still holds either way
5a52012c9b1datagen2026-09-24 23:45 UTC159
    async fn fetch_or_file(
5a52012c9b1datagen2026-09-24 23:45 UTC160
        &self,
5a52012c9b1datagen2026-09-24 23:45 UTC161
        request: MediaRequestParameters,
5a52012c9b1datagen2026-09-24 23:45 UTC162
        mimetype: Option<String>,
5a52012c9b1datagen2026-09-24 23:45 UTC163
    ) -> Result<Media, Error> {
5a52012c9b1datagen2026-09-24 23:45 UTC164
        if !matches!(request.format, MediaFormat::Thumbnail(_)) {
5a52012c9b1datagen2026-09-24 23:45 UTC165
            return self.fetch(request, mimetype).await;
5a52012c9b1datagen2026-09-24 23:45 UTC166
        }
5a52012c9b1datagen2026-09-24 23:45 UTC167
        match self.fetch(request.clone(), mimetype.clone()).await {
5a52012c9b1datagen2026-09-24 23:45 UTC168
            Err(error) if error.kind == ErrorKind::MediaUnavailable => {
5a52012c9b1datagen2026-09-24 23:45 UTC169
                let file = MediaRequestParameters {
5a52012c9b1datagen2026-09-24 23:45 UTC170
                    source: request.source,
5a52012c9b1datagen2026-09-24 23:45 UTC171
                    format: MediaFormat::File,
5a52012c9b1datagen2026-09-24 23:45 UTC172
                };
5a52012c9b1datagen2026-09-24 23:45 UTC173
                self.fetch(file, mimetype).await
5a52012c9b1datagen2026-09-24 23:45 UTC174
            }
5a52012c9b1datagen2026-09-24 23:45 UTC175
            result => result,
5a52012c9b1datagen2026-09-24 23:45 UTC176
        }
5a52012c9b1datagen2026-09-24 23:45 UTC177
    }
5a52012c9b1datagen2026-09-24 23:45 UTC178
31ce2453c82fatagen2026-09-24 13:07 UTC179
    async fn fetch(
31ce2453c82fatagen2026-09-24 13:07 UTC180
        &self,
31ce2453c82fatagen2026-09-24 13:07 UTC181
        request: MediaRequestParameters,
31ce2453c82fatagen2026-09-24 13:07 UTC182
        mimetype: Option<String>,
31ce2453c82fatagen2026-09-24 13:07 UTC183
    ) -> Result<Media, Error> {
31ce2453c82fatagen2026-09-24 13:07 UTC184
        let key = flight_key(&request);
31ce2453c82fatagen2026-09-24 13:07 UTC185
        let flight = {
31ce2453c82fatagen2026-09-24 13:07 UTC186
            let mut flights = self.flights.lock().await;
31ce2453c82fatagen2026-09-24 13:07 UTC187
            flights.retain(|_, flight| flight.upgrade().is_some());
31ce2453c82fatagen2026-09-24 13:07 UTC188
            match flights.get(&key).and_then(WeakShared::upgrade) {
31ce2453c82fatagen2026-09-24 13:07 UTC189
                Some(flight) => flight,
31ce2453c82fatagen2026-09-24 13:07 UTC190
                None => {
31ce2453c82fatagen2026-09-24 13:07 UTC191
                    let flight: Flight = AssertUnwindSafe(fetch(
31ce2453c82fatagen2026-09-24 13:07 UTC192
                        self.client.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC193
                        request,
31ce2453c82fatagen2026-09-24 13:07 UTC194
                        mimetype,
31ce2453c82fatagen2026-09-24 13:07 UTC195
                        self.max_bytes,
31ce2453c82fatagen2026-09-24 13:07 UTC196
                    ))
31ce2453c82fatagen2026-09-24 13:07 UTC197
                    .catch_unwind()
31ce2453c82fatagen2026-09-24 13:07 UTC198
                    .map(|result| {
31ce2453c82fatagen2026-09-24 13:07 UTC199
                        result.unwrap_or_else(|_| {
31ce2453c82fatagen2026-09-24 13:07 UTC200
                            Err(Error::new(ErrorKind::Other, "media fetch panicked"))
31ce2453c82fatagen2026-09-24 13:07 UTC201
                        })
31ce2453c82fatagen2026-09-24 13:07 UTC202
                    })
31ce2453c82fatagen2026-09-24 13:07 UTC203
                    .boxed()
31ce2453c82fatagen2026-09-24 13:07 UTC204
                    .shared();
31ce2453c82fatagen2026-09-24 13:07 UTC205
                    if let Some(weak) = flight.downgrade() {
31ce2453c82fatagen2026-09-24 13:07 UTC206
                        flights.insert(key, weak);
31ce2453c82fatagen2026-09-24 13:07 UTC207
                    }
31ce2453c82fatagen2026-09-24 13:07 UTC208
                    flight
31ce2453c82fatagen2026-09-24 13:07 UTC209
                }
31ce2453c82fatagen2026-09-24 13:07 UTC210
            }
31ce2453c82fatagen2026-09-24 13:07 UTC211
        };
31ce2453c82fatagen2026-09-24 13:07 UTC212
        flight.await
31ce2453c82fatagen2026-09-24 13:07 UTC213
    }
31ce2453c82fatagen2026-09-24 13:07 UTC214
}
31ce2453c82fatagen2026-09-24 13:07 UTC215
31ce2453c82fatagen2026-09-24 13:07 UTC216
fn thumbnail_format(width: u32, height: u32) -> MediaFormat {
31ce2453c82fatagen2026-09-24 13:07 UTC217
    MediaFormat::Thumbnail(MediaThumbnailSettings::new(width.into(), height.into()))
31ce2453c82fatagen2026-09-24 13:07 UTC218
}
31ce2453c82fatagen2026-09-24 13:07 UTC219
5a52012c9b1datagen2026-09-24 23:45 UTC220
fn is_local(source: &MediaSource) -> bool {
5a52012c9b1datagen2026-09-24 23:45 UTC221
    let uri = match source {
5a52012c9b1datagen2026-09-24 23:45 UTC222
        MediaSource::Plain(uri) => uri,
5a52012c9b1datagen2026-09-24 23:45 UTC223
        MediaSource::Encrypted(file) => &file.url,
5a52012c9b1datagen2026-09-24 23:45 UTC224
    };
5a52012c9b1datagen2026-09-24 23:45 UTC225
    uri.server_name()
5a52012c9b1datagen2026-09-24 23:45 UTC226
        .is_ok_and(|server| server.as_str() == "send-queue.localhost")
5a52012c9b1datagen2026-09-24 23:45 UTC227
}
5a52012c9b1datagen2026-09-24 23:45 UTC228
5a52012c9b1datagen2026-09-24 23:45 UTC229
/// plain and encrypted sources share a cache key in the sdk, but must never share a flight
31ce2453c82fatagen2026-09-24 13:07 UTC230
fn flight_key(request: &MediaRequestParameters) -> String {
31ce2453c82fatagen2026-09-24 13:07 UTC231
    let uri = match &request.source {
5a52012c9b1datagen2026-09-24 23:45 UTC232
        MediaSource::Plain(uri) => format!("plain|{uri}"),
5a52012c9b1datagen2026-09-24 23:45 UTC233
        MediaSource::Encrypted(file) => format!("encrypted|{}", file.url),
31ce2453c82fatagen2026-09-24 13:07 UTC234
    };
31ce2453c82fatagen2026-09-24 13:07 UTC235
    match &request.format {
31ce2453c82fatagen2026-09-24 13:07 UTC236
        MediaFormat::File => uri.to_owned(),
31ce2453c82fatagen2026-09-24 13:07 UTC237
        MediaFormat::Thumbnail(settings) => format!(
31ce2453c82fatagen2026-09-24 13:07 UTC238
            "{uri}|{}|{}x{}|{}",
31ce2453c82fatagen2026-09-24 13:07 UTC239
            settings.method, settings.width, settings.height, settings.animated
31ce2453c82fatagen2026-09-24 13:07 UTC240
        ),
31ce2453c82fatagen2026-09-24 13:07 UTC241
    }
31ce2453c82fatagen2026-09-24 13:07 UTC242
}
31ce2453c82fatagen2026-09-24 13:07 UTC243
31ce2453c82fatagen2026-09-24 13:07 UTC244
fn too_large(message: &'static str) -> Error {
31ce2453c82fatagen2026-09-24 13:07 UTC245
    Error::new(ErrorKind::MediaTooLarge, message)
31ce2453c82fatagen2026-09-24 13:07 UTC246
}
31ce2453c82fatagen2026-09-24 13:07 UTC247
31ce2453c82fatagen2026-09-24 13:07 UTC248
async fn fetch(
31ce2453c82fatagen2026-09-24 13:07 UTC249
    client: Client,
31ce2453c82fatagen2026-09-24 13:07 UTC250
    request: MediaRequestParameters,
31ce2453c82fatagen2026-09-24 13:07 UTC251
    mimetype: Option<String>,
31ce2453c82fatagen2026-09-24 13:07 UTC252
    max_bytes: usize,
31ce2453c82fatagen2026-09-24 13:07 UTC253
) -> Result<Media, Error> {
31ce2453c82fatagen2026-09-24 13:07 UTC254
    if let Some(cached) = cached_media(&client, &request).await? {
31ce2453c82fatagen2026-09-24 13:07 UTC255
        if cached.len() > max_bytes {
31ce2453c82fatagen2026-09-24 13:07 UTC256
            if let Ok(store) = client.media_store().lock().await {
31ce2453c82fatagen2026-09-24 13:07 UTC257
                let _ = store.remove_media_content(&request).await;
31ce2453c82fatagen2026-09-24 13:07 UTC258
            }
31ce2453c82fatagen2026-09-24 13:07 UTC259
            return Err(too_large("cached media exceeds the configured byte limit"));
31ce2453c82fatagen2026-09-24 13:07 UTC260
        }
5a52012c9b1datagen2026-09-24 23:45 UTC261
        // plain and encrypted share a cache key, so a plain fetch of an encrypted file's uri
5a52012c9b1datagen2026-09-24 23:45 UTC262
        // leaves ciphertext here. its hash gives it away
5a52012c9b1datagen2026-09-24 23:45 UTC263
        if is_ciphertext(&cached, &request.source) {
5a52012c9b1datagen2026-09-24 23:45 UTC264
            let bytes = maybe_decrypt(cached, &request, max_bytes)?;
5a52012c9b1datagen2026-09-24 23:45 UTC265
            cache(&client, &request, &bytes).await;
5a52012c9b1datagen2026-09-24 23:45 UTC266
            return Ok(media(bytes, mimetype));
5a52012c9b1datagen2026-09-24 23:45 UTC267
        }
31ce2453c82fatagen2026-09-24 13:07 UTC268
        return Ok(media(cached, mimetype));
31ce2453c82fatagen2026-09-24 13:07 UTC269
    }
31ce2453c82fatagen2026-09-24 13:07 UTC270
    let (bytes, served_mimetype) = download_bounded(&client, &request, max_bytes).await?;
31ce2453c82fatagen2026-09-24 13:07 UTC271
    // the sdk caches plaintext under the encrypted key, so we do too or nobody can read anything
31ce2453c82fatagen2026-09-24 13:07 UTC272
    let bytes = maybe_decrypt(bytes, &request, max_bytes)?;
5a52012c9b1datagen2026-09-24 23:45 UTC273
    cache(&client, &request, &bytes).await;
5a52012c9b1datagen2026-09-24 23:45 UTC274
    Ok(media(bytes, mimetype.or(served_mimetype)))
5a52012c9b1datagen2026-09-24 23:45 UTC275
}
5a52012c9b1datagen2026-09-24 23:45 UTC276
5a52012c9b1datagen2026-09-24 23:45 UTC277
async fn cache(client: &Client, request: &MediaRequestParameters, bytes: &[u8]) {
31ce2453c82fatagen2026-09-24 13:07 UTC278
    if let Ok(store) = client.media_store().lock().await {
31ce2453c82fatagen2026-09-24 13:07 UTC279
        let _ = store
31ce2453c82fatagen2026-09-24 13:07 UTC280
            .add_media_content(
5a52012c9b1datagen2026-09-24 23:45 UTC281
                request,
5a52012c9b1datagen2026-09-24 23:45 UTC282
                bytes.to_vec(),
31ce2453c82fatagen2026-09-24 13:07 UTC283
                matrix_sdk::media::store::IgnoreMediaRetentionPolicy::No,
31ce2453c82fatagen2026-09-24 13:07 UTC284
            )
31ce2453c82fatagen2026-09-24 13:07 UTC285
            .await;
31ce2453c82fatagen2026-09-24 13:07 UTC286
    }
5a52012c9b1datagen2026-09-24 23:45 UTC287
}
5a52012c9b1datagen2026-09-24 23:45 UTC288
5a52012c9b1datagen2026-09-24 23:45 UTC289
fn is_ciphertext(bytes: &[u8], source: &MediaSource) -> bool {
5a52012c9b1datagen2026-09-24 23:45 UTC290
    use sha2::{Digest, Sha256};
5a52012c9b1datagen2026-09-24 23:45 UTC291
    let MediaSource::Encrypted(file) = source else {
5a52012c9b1datagen2026-09-24 23:45 UTC292
        return false;
5a52012c9b1datagen2026-09-24 23:45 UTC293
    };
5a52012c9b1datagen2026-09-24 23:45 UTC294
    file.hashes
5a52012c9b1datagen2026-09-24 23:45 UTC295
        .get(&ruma::events::room::EncryptedFileHashAlgorithm::Sha256)
5a52012c9b1datagen2026-09-24 23:45 UTC296
        .is_some_and(|hash| hash.as_bytes() == Sha256::digest(bytes).as_slice())
31ce2453c82fatagen2026-09-24 13:07 UTC297
}
31ce2453c82fatagen2026-09-24 13:07 UTC298
31ce2453c82fatagen2026-09-24 13:07 UTC299
fn media(bytes: Vec<u8>, mimetype: Option<String>) -> Media {
31ce2453c82fatagen2026-09-24 13:07 UTC300
    let mimetype = mimetype
31ce2453c82fatagen2026-09-24 13:07 UTC301
        .or_else(|| sniff_image(&bytes).map(str::to_owned))
31ce2453c82fatagen2026-09-24 13:07 UTC302
        .unwrap_or_else(|| "application/octet-stream".to_owned());
31ce2453c82fatagen2026-09-24 13:07 UTC303
    Media {
31ce2453c82fatagen2026-09-24 13:07 UTC304
        bytes: Arc::from(bytes),
31ce2453c82fatagen2026-09-24 13:07 UTC305
        mimetype,
31ce2453c82fatagen2026-09-24 13:07 UTC306
    }
31ce2453c82fatagen2026-09-24 13:07 UTC307
}
31ce2453c82fatagen2026-09-24 13:07 UTC308
31ce2453c82fatagen2026-09-24 13:07 UTC309
/// the cache forgets content types, and avatars never declare one. images are the common case
31ce2453c82fatagen2026-09-24 13:07 UTC310
fn sniff_image(bytes: &[u8]) -> Option<&'static str> {
31ce2453c82fatagen2026-09-24 13:07 UTC311
    match bytes {
31ce2453c82fatagen2026-09-24 13:07 UTC312
        [0x89, b'P', b'N', b'G', ..] => Some("image/png"),
31ce2453c82fatagen2026-09-24 13:07 UTC313
        [0xff, 0xd8, 0xff, ..] => Some("image/jpeg"),
31ce2453c82fatagen2026-09-24 13:07 UTC314
        [b'G', b'I', b'F', b'8', ..] => Some("image/gif"),
31ce2453c82fatagen2026-09-24 13:07 UTC315
        [
31ce2453c82fatagen2026-09-24 13:07 UTC316
            b'R',
31ce2453c82fatagen2026-09-24 13:07 UTC317
            b'I',
31ce2453c82fatagen2026-09-24 13:07 UTC318
            b'F',
31ce2453c82fatagen2026-09-24 13:07 UTC319
            b'F',
31ce2453c82fatagen2026-09-24 13:07 UTC320
            _,
31ce2453c82fatagen2026-09-24 13:07 UTC321
            _,
31ce2453c82fatagen2026-09-24 13:07 UTC322
            _,
31ce2453c82fatagen2026-09-24 13:07 UTC323
            _,
31ce2453c82fatagen2026-09-24 13:07 UTC324
            b'W',
31ce2453c82fatagen2026-09-24 13:07 UTC325
            b'E',
31ce2453c82fatagen2026-09-24 13:07 UTC326
            b'B',
31ce2453c82fatagen2026-09-24 13:07 UTC327
            b'P',
31ce2453c82fatagen2026-09-24 13:07 UTC328
            ..,
31ce2453c82fatagen2026-09-24 13:07 UTC329
        ] => Some("image/webp"),
31ce2453c82fatagen2026-09-24 13:07 UTC330
        _ => None,
31ce2453c82fatagen2026-09-24 13:07 UTC331
    }
31ce2453c82fatagen2026-09-24 13:07 UTC332
}
31ce2453c82fatagen2026-09-24 13:07 UTC333
31ce2453c82fatagen2026-09-24 13:07 UTC334
async fn cached_media(
31ce2453c82fatagen2026-09-24 13:07 UTC335
    client: &Client,
31ce2453c82fatagen2026-09-24 13:07 UTC336
    request: &MediaRequestParameters,
31ce2453c82fatagen2026-09-24 13:07 UTC337
) -> Result<Option<Vec<u8>>, Error> {
31ce2453c82fatagen2026-09-24 13:07 UTC338
    fn cache_failed(source: impl std::error::Error + Send + Sync + 'static) -> Error {
31ce2453c82fatagen2026-09-24 13:07 UTC339
        Error::with_source(ErrorKind::Store, "reading media cache failed", source)
31ce2453c82fatagen2026-09-24 13:07 UTC340
    }
31ce2453c82fatagen2026-09-24 13:07 UTC341
    client
31ce2453c82fatagen2026-09-24 13:07 UTC342
        .media_store()
31ce2453c82fatagen2026-09-24 13:07 UTC343
        .lock()
31ce2453c82fatagen2026-09-24 13:07 UTC344
        .await
31ce2453c82fatagen2026-09-24 13:07 UTC345
        .map_err(cache_failed)?
31ce2453c82fatagen2026-09-24 13:07 UTC346
        .get_media_content(request)
31ce2453c82fatagen2026-09-24 13:07 UTC347
        .await
31ce2453c82fatagen2026-09-24 13:07 UTC348
        .map_err(cache_failed)
31ce2453c82fatagen2026-09-24 13:07 UTC349
}
31ce2453c82fatagen2026-09-24 13:07 UTC350
31ce2453c82fatagen2026-09-24 13:07 UTC351
fn maybe_decrypt(
31ce2453c82fatagen2026-09-24 13:07 UTC352
    bytes: Vec<u8>,
31ce2453c82fatagen2026-09-24 13:07 UTC353
    request: &MediaRequestParameters,
31ce2453c82fatagen2026-09-24 13:07 UTC354
    max_bytes: usize,
31ce2453c82fatagen2026-09-24 13:07 UTC355
) -> Result<Vec<u8>, Error> {
31ce2453c82fatagen2026-09-24 13:07 UTC356
    let MediaSource::Encrypted(file) = &request.source else {
31ce2453c82fatagen2026-09-24 13:07 UTC357
        return Ok(bytes);
31ce2453c82fatagen2026-09-24 13:07 UTC358
    };
31ce2453c82fatagen2026-09-24 13:07 UTC359
    fn decrypt_failed(source: impl std::error::Error + Send + Sync + 'static) -> Error {
31ce2453c82fatagen2026-09-24 13:07 UTC360
        Error::with_source(
31ce2453c82fatagen2026-09-24 13:07 UTC361
            ErrorKind::MediaUnavailable,
31ce2453c82fatagen2026-09-24 13:07 UTC362
            "media decryption failed",
31ce2453c82fatagen2026-09-24 13:07 UTC363
            source,
31ce2453c82fatagen2026-09-24 13:07 UTC364
        )
31ce2453c82fatagen2026-09-24 13:07 UTC365
    }
31ce2453c82fatagen2026-09-24 13:07 UTC366
    let info: MediaEncryptionInfo = (**file).clone().into();
31ce2453c82fatagen2026-09-24 13:07 UTC367
    let mut cursor = std::io::Cursor::new(bytes);
31ce2453c82fatagen2026-09-24 13:07 UTC368
    let mut decryptor = AttachmentDecryptor::new(&mut cursor, info).map_err(decrypt_failed)?;
31ce2453c82fatagen2026-09-24 13:07 UTC369
    let mut decrypted = Vec::new();
31ce2453c82fatagen2026-09-24 13:07 UTC370
    let mut chunk = [0_u8; 8192];
31ce2453c82fatagen2026-09-24 13:07 UTC371
    loop {
31ce2453c82fatagen2026-09-24 13:07 UTC372
        let read = decryptor.read(&mut chunk).map_err(decrypt_failed)?;
31ce2453c82fatagen2026-09-24 13:07 UTC373
        if read == 0 {
31ce2453c82fatagen2026-09-24 13:07 UTC374
            return Ok(decrypted);
31ce2453c82fatagen2026-09-24 13:07 UTC375
        }
31ce2453c82fatagen2026-09-24 13:07 UTC376
        if read > max_bytes.saturating_sub(decrypted.len()) {
31ce2453c82fatagen2026-09-24 13:07 UTC377
            return Err(too_large(
31ce2453c82fatagen2026-09-24 13:07 UTC378
                "decrypted media exceeds the configured byte limit",
31ce2453c82fatagen2026-09-24 13:07 UTC379
            ));
31ce2453c82fatagen2026-09-24 13:07 UTC380
        }
31ce2453c82fatagen2026-09-24 13:07 UTC381
        decrypted.extend_from_slice(&chunk[..read]);
31ce2453c82fatagen2026-09-24 13:07 UTC382
    }
31ce2453c82fatagen2026-09-24 13:07 UTC383
}
31ce2453c82fatagen2026-09-24 13:07 UTC384
5a52012c9b1datagen2026-09-24 23:45 UTC385
/// the sdk's own download has no size cap, so we do it by hand
31ce2453c82fatagen2026-09-24 13:07 UTC386
async fn download_bounded(
31ce2453c82fatagen2026-09-24 13:07 UTC387
    client: &Client,
31ce2453c82fatagen2026-09-24 13:07 UTC388
    request: &MediaRequestParameters,
31ce2453c82fatagen2026-09-24 13:07 UTC389
    max_bytes: usize,
31ce2453c82fatagen2026-09-24 13:07 UTC390
) -> Result<(Vec<u8>, Option<String>), Error> {
5a52012c9b1datagen2026-09-24 23:45 UTC391
    if is_local(&request.source) {
31ce2453c82fatagen2026-09-24 13:07 UTC392
        return Err(Error::new(
31ce2453c82fatagen2026-09-24 13:07 UTC393
            ErrorKind::MediaUnavailable,
31ce2453c82fatagen2026-09-24 13:07 UTC394
            "local media is not in the media cache",
31ce2453c82fatagen2026-09-24 13:07 UTC395
        ));
31ce2453c82fatagen2026-09-24 13:07 UTC396
    }
31ce2453c82fatagen2026-09-24 13:07 UTC397
    let network_failed =
31ce2453c82fatagen2026-09-24 13:07 UTC398
        |source| Error::with_source(ErrorKind::Network, "media download failed", source);
31ce2453c82fatagen2026-09-24 13:07 UTC399
    let mut refreshed = false;
31ce2453c82fatagen2026-09-24 13:07 UTC400
    let response = loop {
31ce2453c82fatagen2026-09-24 13:07 UTC401
        let http_request = media_http_request(client, request).await?;
31ce2453c82fatagen2026-09-24 13:07 UTC402
        let (parts, _) = http_request.into_parts();
5a52012c9b1datagen2026-09-24 23:45 UTC403
        let mut builder = client
5a52012c9b1datagen2026-09-24 23:45 UTC404
            .http_client()
5a52012c9b1datagen2026-09-24 23:45 UTC405
            .get(parts.uri.to_string())
5a52012c9b1datagen2026-09-24 23:45 UTC406
            .timeout(DOWNLOAD_TOTAL);
31ce2453c82fatagen2026-09-24 13:07 UTC407
        for (name, value) in &parts.headers {
31ce2453c82fatagen2026-09-24 13:07 UTC408
            builder = builder.header(name.as_str(), value.as_bytes());
31ce2453c82fatagen2026-09-24 13:07 UTC409
        }
31ce2453c82fatagen2026-09-24 13:07 UTC410
        let response = builder.send().await.map_err(network_failed)?;
31ce2453c82fatagen2026-09-24 13:07 UTC411
        if response.status() != matrix_sdk::reqwest::StatusCode::UNAUTHORIZED {
31ce2453c82fatagen2026-09-24 13:07 UTC412
            break response;
31ce2453c82fatagen2026-09-24 13:07 UTC413
        }
31ce2453c82fatagen2026-09-24 13:07 UTC414
        if refreshed
31ce2453c82fatagen2026-09-24 13:07 UTC415
            || client
31ce2453c82fatagen2026-09-24 13:07 UTC416
                .session_tokens()
31ce2453c82fatagen2026-09-24 13:07 UTC417
                .is_none_or(|tokens| tokens.refresh_token.is_none())
31ce2453c82fatagen2026-09-24 13:07 UTC418
        {
31ce2453c82fatagen2026-09-24 13:07 UTC419
            return Err(Error::new(
31ce2453c82fatagen2026-09-24 13:07 UTC420
                ErrorKind::Unauthenticated,
31ce2453c82fatagen2026-09-24 13:07 UTC421
                "media download was not authorized",
31ce2453c82fatagen2026-09-24 13:07 UTC422
            ));
31ce2453c82fatagen2026-09-24 13:07 UTC423
        }
31ce2453c82fatagen2026-09-24 13:07 UTC424
        client.refresh_access_token().await.map_err(|source| {
31ce2453c82fatagen2026-09-24 13:07 UTC425
            Error::from_refresh_token("refreshing media access token failed", source)
31ce2453c82fatagen2026-09-24 13:07 UTC426
        })?;
31ce2453c82fatagen2026-09-24 13:07 UTC427
        refreshed = true;
31ce2453c82fatagen2026-09-24 13:07 UTC428
    };
31ce2453c82fatagen2026-09-24 13:07 UTC429
    let status = response.status();
31ce2453c82fatagen2026-09-24 13:07 UTC430
    if !status.is_success() {
31ce2453c82fatagen2026-09-24 13:07 UTC431
        return Err(Error::new(
31ce2453c82fatagen2026-09-24 13:07 UTC432
            ErrorKind::MediaUnavailable,
31ce2453c82fatagen2026-09-24 13:07 UTC433
            format!("media download failed with status {status}"),
31ce2453c82fatagen2026-09-24 13:07 UTC434
        ));
31ce2453c82fatagen2026-09-24 13:07 UTC435
    }
31ce2453c82fatagen2026-09-24 13:07 UTC436
    if response
31ce2453c82fatagen2026-09-24 13:07 UTC437
        .content_length()
31ce2453c82fatagen2026-09-24 13:07 UTC438
        .is_some_and(|length| length > max_bytes as u64)
31ce2453c82fatagen2026-09-24 13:07 UTC439
    {
31ce2453c82fatagen2026-09-24 13:07 UTC440
        return Err(too_large("media exceeds the configured byte limit"));
31ce2453c82fatagen2026-09-24 13:07 UTC441
    }
31ce2453c82fatagen2026-09-24 13:07 UTC442
    let mimetype = response
31ce2453c82fatagen2026-09-24 13:07 UTC443
        .headers()
31ce2453c82fatagen2026-09-24 13:07 UTC444
        .get(http::header::CONTENT_TYPE)
31ce2453c82fatagen2026-09-24 13:07 UTC445
        .and_then(|value| value.to_str().ok())
31ce2453c82fatagen2026-09-24 13:07 UTC446
        .map(str::to_owned);
31ce2453c82fatagen2026-09-24 13:07 UTC447
    let mut stream = response.bytes_stream();
31ce2453c82fatagen2026-09-24 13:07 UTC448
    let mut bytes = Vec::new();
5a52012c9b1datagen2026-09-24 23:45 UTC449
    loop {
5a52012c9b1datagen2026-09-24 23:45 UTC450
        let chunk = tokio::time::timeout(DOWNLOAD_IDLE, stream.next())
5a52012c9b1datagen2026-09-24 23:45 UTC451
            .await
5a52012c9b1datagen2026-09-24 23:45 UTC452
            .map_err(|_| Error::new(ErrorKind::Network, "media download stalled"))?;
5a52012c9b1datagen2026-09-24 23:45 UTC453
        let Some(chunk) = chunk else { break };
31ce2453c82fatagen2026-09-24 13:07 UTC454
        let chunk = chunk.map_err(network_failed)?;
31ce2453c82fatagen2026-09-24 13:07 UTC455
        if chunk.len() > max_bytes.saturating_sub(bytes.len()) {
31ce2453c82fatagen2026-09-24 13:07 UTC456
            return Err(too_large(
31ce2453c82fatagen2026-09-24 13:07 UTC457
                "downloaded media exceeds the configured byte limit",
31ce2453c82fatagen2026-09-24 13:07 UTC458
            ));
31ce2453c82fatagen2026-09-24 13:07 UTC459
        }
31ce2453c82fatagen2026-09-24 13:07 UTC460
        bytes.extend_from_slice(&chunk);
31ce2453c82fatagen2026-09-24 13:07 UTC461
    }
31ce2453c82fatagen2026-09-24 13:07 UTC462
    Ok((bytes, mimetype))
31ce2453c82fatagen2026-09-24 13:07 UTC463
}
31ce2453c82fatagen2026-09-24 13:07 UTC464
31ce2453c82fatagen2026-09-24 13:07 UTC465
async fn media_http_request(
31ce2453c82fatagen2026-09-24 13:07 UTC466
    client: &Client,
31ce2453c82fatagen2026-09-24 13:07 UTC467
    request: &MediaRequestParameters,
31ce2453c82fatagen2026-09-24 13:07 UTC468
) -> Result<http::Request<Vec<u8>>, Error> {
31ce2453c82fatagen2026-09-24 13:07 UTC469
    let versions = client.supported_versions().await.map_err(|source| {
31ce2453c82fatagen2026-09-24 13:07 UTC470
        Error::with_source(
31ce2453c82fatagen2026-09-24 13:07 UTC471
            ErrorKind::Network,
31ce2453c82fatagen2026-09-24 13:07 UTC472
            "reading supported server versions failed",
31ce2453c82fatagen2026-09-24 13:07 UTC473
            source,
31ce2453c82fatagen2026-09-24 13:07 UTC474
        )
31ce2453c82fatagen2026-09-24 13:07 UTC475
    })?;
31ce2453c82fatagen2026-09-24 13:07 UTC476
    let authenticated =
31ce2453c82fatagen2026-09-24 13:07 UTC477
        authenticated_media::get_content::v1::Request::PATH_BUILDER.is_supported(&versions);
31ce2453c82fatagen2026-09-24 13:07 UTC478
    let base = client.homeserver().to_string();
31ce2453c82fatagen2026-09-24 13:07 UTC479
    let token = client.access_token();
31ce2453c82fatagen2026-09-24 13:07 UTC480
    let invalid_uri =
31ce2453c82fatagen2026-09-24 13:07 UTC481
        |source| Error::with_source(ErrorKind::Invalid, "media URI is invalid", source);
31ce2453c82fatagen2026-09-24 13:07 UTC482
    let (uri, thumbnail) = match (&request.source, &request.format) {
31ce2453c82fatagen2026-09-24 13:07 UTC483
        (MediaSource::Encrypted(file), _) => (&file.url, None),
31ce2453c82fatagen2026-09-24 13:07 UTC484
        (MediaSource::Plain(uri), MediaFormat::File) => (uri, None),
31ce2453c82fatagen2026-09-24 13:07 UTC485
        (MediaSource::Plain(uri), MediaFormat::Thumbnail(settings)) => (uri, Some(settings)),
31ce2453c82fatagen2026-09-24 13:07 UTC486
    };
31ce2453c82fatagen2026-09-24 13:07 UTC487
    // each endpoint has its own auth input type, so no generic helper can take them all
31ce2453c82fatagen2026-09-24 13:07 UTC488
    macro_rules! into_http {
31ce2453c82fatagen2026-09-24 13:07 UTC489
        ($endpoint:expr, $token:expr) => {
31ce2453c82fatagen2026-09-24 13:07 UTC490
            $endpoint
31ce2453c82fatagen2026-09-24 13:07 UTC491
                .try_into_http_request::<Vec<u8>>(&base, $token, Cow::Borrowed(&versions))
31ce2453c82fatagen2026-09-24 13:07 UTC492
                .map_err(|source| {
31ce2453c82fatagen2026-09-24 13:07 UTC493
                    Error::with_source(ErrorKind::Other, "media request is invalid", source)
31ce2453c82fatagen2026-09-24 13:07 UTC494
                })?
31ce2453c82fatagen2026-09-24 13:07 UTC495
        };
31ce2453c82fatagen2026-09-24 13:07 UTC496
    }
31ce2453c82fatagen2026-09-24 13:07 UTC497
    let authed = SendAccessToken::IfRequired(token.as_deref().unwrap_or(""));
31ce2453c82fatagen2026-09-24 13:07 UTC498
    #[allow(deprecated)]
31ce2453c82fatagen2026-09-24 13:07 UTC499
    let mut http_request = match (thumbnail, authenticated) {
31ce2453c82fatagen2026-09-24 13:07 UTC500
        (None, true) => into_http!(
31ce2453c82fatagen2026-09-24 13:07 UTC501
            authenticated_media::get_content::v1::Request::from_uri(uri).map_err(invalid_uri)?,
31ce2453c82fatagen2026-09-24 13:07 UTC502
            authed
31ce2453c82fatagen2026-09-24 13:07 UTC503
        ),
31ce2453c82fatagen2026-09-24 13:07 UTC504
        (None, false) => into_http!(
31ce2453c82fatagen2026-09-24 13:07 UTC505
            media::get_content::v3::Request::from_url(uri).map_err(invalid_uri)?,
31ce2453c82fatagen2026-09-24 13:07 UTC506
            SendAccessToken::None
31ce2453c82fatagen2026-09-24 13:07 UTC507
        ),
31ce2453c82fatagen2026-09-24 13:07 UTC508
        (Some(settings), true) => {
31ce2453c82fatagen2026-09-24 13:07 UTC509
            let mut endpoint = authenticated_media::get_content_thumbnail::v1::Request::from_uri(
31ce2453c82fatagen2026-09-24 13:07 UTC510
                uri,
31ce2453c82fatagen2026-09-24 13:07 UTC511
                settings.width,
31ce2453c82fatagen2026-09-24 13:07 UTC512
                settings.height,
31ce2453c82fatagen2026-09-24 13:07 UTC513
            )
31ce2453c82fatagen2026-09-24 13:07 UTC514
            .map_err(invalid_uri)?;
31ce2453c82fatagen2026-09-24 13:07 UTC515
            endpoint.method = Some(settings.method.clone());
31ce2453c82fatagen2026-09-24 13:07 UTC516
            endpoint.animated = Some(settings.animated);
31ce2453c82fatagen2026-09-24 13:07 UTC517
            into_http!(endpoint, authed)
31ce2453c82fatagen2026-09-24 13:07 UTC518
        }
31ce2453c82fatagen2026-09-24 13:07 UTC519
        (Some(settings), false) => {
31ce2453c82fatagen2026-09-24 13:07 UTC520
            let mut endpoint = media::get_content_thumbnail::v3::Request::from_url(
31ce2453c82fatagen2026-09-24 13:07 UTC521
                uri,
31ce2453c82fatagen2026-09-24 13:07 UTC522
                settings.width,
31ce2453c82fatagen2026-09-24 13:07 UTC523
                settings.height,
31ce2453c82fatagen2026-09-24 13:07 UTC524
            )
31ce2453c82fatagen2026-09-24 13:07 UTC525
            .map_err(invalid_uri)?;
31ce2453c82fatagen2026-09-24 13:07 UTC526
            endpoint.method = Some(settings.method.clone());
31ce2453c82fatagen2026-09-24 13:07 UTC527
            endpoint.animated = Some(settings.animated);
31ce2453c82fatagen2026-09-24 13:07 UTC528
            into_http!(endpoint, SendAccessToken::None)
31ce2453c82fatagen2026-09-24 13:07 UTC529
        }
31ce2453c82fatagen2026-09-24 13:07 UTC530
    };
31ce2453c82fatagen2026-09-24 13:07 UTC531
    // legacy endpoints don't ask for a token but plenty of servers want one anyway
31ce2453c82fatagen2026-09-24 13:07 UTC532
    if let Some(token) = token.as_deref() {
31ce2453c82fatagen2026-09-24 13:07 UTC533
        let value = format!("Bearer {token}").parse().map_err(|_| {
31ce2453c82fatagen2026-09-24 13:07 UTC534
            Error::new(ErrorKind::Unauthenticated, "stored access token is invalid")
31ce2453c82fatagen2026-09-24 13:07 UTC535
        })?;
31ce2453c82fatagen2026-09-24 13:07 UTC536
        http_request
31ce2453c82fatagen2026-09-24 13:07 UTC537
            .headers_mut()
31ce2453c82fatagen2026-09-24 13:07 UTC538
            .insert(http::header::AUTHORIZATION, value);
31ce2453c82fatagen2026-09-24 13:07 UTC539
    }
31ce2453c82fatagen2026-09-24 13:07 UTC540
    Ok(http_request)
31ce2453c82fatagen2026-09-24 13:07 UTC541
}
31ce2453c82fatagen2026-09-24 13:07 UTC542
31ce2453c82fatagen2026-09-24 13:07 UTC543
pub(crate) async fn queue_upload(
31ce2453c82fatagen2026-09-24 13:07 UTC544
    room: Room,
31ce2453c82fatagen2026-09-24 13:07 UTC545
    upload: AttachmentUpload,
31ce2453c82fatagen2026-09-24 13:07 UTC546
    max_bytes: usize,
31ce2453c82fatagen2026-09-24 13:07 UTC547
) -> Result<(), Error> {
31ce2453c82fatagen2026-09-24 13:07 UTC548
    let (upload, mime, mut config) = prepare_upload(upload, max_bytes)?;
31ce2453c82fatagen2026-09-24 13:07 UTC549
    if let TimelineId::Thread { root_event_id, .. } = &upload.timeline_id {
31ce2453c82fatagen2026-09-24 13:07 UTC550
        config.reply = Some(SdkReply {
31ce2453c82fatagen2026-09-24 13:07 UTC551
            event_id: root_event_id.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC552
            enforce_thread: EnforceThread::Threaded(ReplyWithinThread::No),
31ce2453c82fatagen2026-09-24 13:07 UTC553
            add_mentions: AddMentions::No,
31ce2453c82fatagen2026-09-24 13:07 UTC554
        });
31ce2453c82fatagen2026-09-24 13:07 UTC555
    }
31ce2453c82fatagen2026-09-24 13:07 UTC556
    room.send_queue()
31ce2453c82fatagen2026-09-24 13:07 UTC557
        .send_attachment(upload.filename, mime, upload.bytes, config)
31ce2453c82fatagen2026-09-24 13:07 UTC558
        .await
31ce2453c82fatagen2026-09-24 13:07 UTC559
        .map(drop)
31ce2453c82fatagen2026-09-24 13:07 UTC560
        .map_err(|source| {
5a52012c9b1datagen2026-09-24 23:45 UTC561
            use matrix_sdk::send_queue::RoomSendQueueError;
5a52012c9b1datagen2026-09-24 23:45 UTC562
            let kind = match &source {
5a52012c9b1datagen2026-09-24 23:45 UTC563
                RoomSendQueueError::RoomNotJoined | RoomSendQueueError::RoomDisappeared => {
5a52012c9b1datagen2026-09-24 23:45 UTC564
                    ErrorKind::RoomUnknown
5a52012c9b1datagen2026-09-24 23:45 UTC565
                }
5a52012c9b1datagen2026-09-24 23:45 UTC566
                RoomSendQueueError::StorageError(_) => ErrorKind::Store,
5a52012c9b1datagen2026-09-24 23:45 UTC567
                _ => ErrorKind::MediaUnavailable,
5a52012c9b1datagen2026-09-24 23:45 UTC568
            };
5a52012c9b1datagen2026-09-24 23:45 UTC569
            Error::with_source(kind, "media upload could not be queued", source)
31ce2453c82fatagen2026-09-24 13:07 UTC570
        })
31ce2453c82fatagen2026-09-24 13:07 UTC571
}
31ce2453c82fatagen2026-09-24 13:07 UTC572
31ce2453c82fatagen2026-09-24 13:07 UTC573
/// least recently seen goes first. stale order slots are skipped by stamp rather than hunted down
31ce2453c82fatagen2026-09-24 13:07 UTC574
struct MediaRegistry {
31ce2453c82fatagen2026-09-24 13:07 UTC575
    entries: HashMap<MediaId, (MediaRegistration, u64)>,
31ce2453c82fatagen2026-09-24 13:07 UTC576
    order: VecDeque<(MediaId, u64)>,
31ce2453c82fatagen2026-09-24 13:07 UTC577
    next_stamp: u64,
31ce2453c82fatagen2026-09-24 13:07 UTC578
    limit: usize,
31ce2453c82fatagen2026-09-24 13:07 UTC579
}
31ce2453c82fatagen2026-09-24 13:07 UTC580
31ce2453c82fatagen2026-09-24 13:07 UTC581
impl MediaRegistry {
31ce2453c82fatagen2026-09-24 13:07 UTC582
    fn new(limit: usize) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC583
        Self {
31ce2453c82fatagen2026-09-24 13:07 UTC584
            entries: HashMap::new(),
31ce2453c82fatagen2026-09-24 13:07 UTC585
            order: VecDeque::new(),
31ce2453c82fatagen2026-09-24 13:07 UTC586
            next_stamp: 0,
31ce2453c82fatagen2026-09-24 13:07 UTC587
            limit,
31ce2453c82fatagen2026-09-24 13:07 UTC588
        }
31ce2453c82fatagen2026-09-24 13:07 UTC589
    }
31ce2453c82fatagen2026-09-24 13:07 UTC590
31ce2453c82fatagen2026-09-24 13:07 UTC591
    fn get(&self, id: &MediaId) -> Option<&MediaRegistration> {
31ce2453c82fatagen2026-09-24 13:07 UTC592
        self.entries.get(id).map(|(media, _)| media)
31ce2453c82fatagen2026-09-24 13:07 UTC593
    }
31ce2453c82fatagen2026-09-24 13:07 UTC594
31ce2453c82fatagen2026-09-24 13:07 UTC595
    fn insert_all(&mut self, media: Vec<MediaRegistration>) {
31ce2453c82fatagen2026-09-24 13:07 UTC596
        for media in media {
31ce2453c82fatagen2026-09-24 13:07 UTC597
            let stamp = self.next_stamp;
31ce2453c82fatagen2026-09-24 13:07 UTC598
            self.next_stamp += 1;
31ce2453c82fatagen2026-09-24 13:07 UTC599
            self.order.push_back((media.id.clone(), stamp));
31ce2453c82fatagen2026-09-24 13:07 UTC600
            self.entries.insert(media.id.clone(), (media, stamp));
31ce2453c82fatagen2026-09-24 13:07 UTC601
        }
31ce2453c82fatagen2026-09-24 13:07 UTC602
        while self.entries.len() > self.limit {
31ce2453c82fatagen2026-09-24 13:07 UTC603
            let Some((id, stamp)) = self.order.pop_front() else {
31ce2453c82fatagen2026-09-24 13:07 UTC604
                break;
31ce2453c82fatagen2026-09-24 13:07 UTC605
            };
31ce2453c82fatagen2026-09-24 13:07 UTC606
            if self.is_current(&id, stamp) {
31ce2453c82fatagen2026-09-24 13:07 UTC607
                self.entries.remove(&id);
31ce2453c82fatagen2026-09-24 13:07 UTC608
            }
31ce2453c82fatagen2026-09-24 13:07 UTC609
        }
31ce2453c82fatagen2026-09-24 13:07 UTC610
        if self.order.len() > self.limit.saturating_mul(4) {
31ce2453c82fatagen2026-09-24 13:07 UTC611
            let entries = &self.entries;
31ce2453c82fatagen2026-09-24 13:07 UTC612
            self.order
31ce2453c82fatagen2026-09-24 13:07 UTC613
                .retain(|(id, stamp)| entries.get(id).is_some_and(|(_, current)| current == stamp));
31ce2453c82fatagen2026-09-24 13:07 UTC614
        }
31ce2453c82fatagen2026-09-24 13:07 UTC615
    }
31ce2453c82fatagen2026-09-24 13:07 UTC616
31ce2453c82fatagen2026-09-24 13:07 UTC617
    fn is_current(&self, id: &MediaId, stamp: u64) -> bool {
31ce2453c82fatagen2026-09-24 13:07 UTC618
        self.entries
31ce2453c82fatagen2026-09-24 13:07 UTC619
            .get(id)
31ce2453c82fatagen2026-09-24 13:07 UTC620
            .is_some_and(|(_, current)| *current == stamp)
31ce2453c82fatagen2026-09-24 13:07 UTC621
    }
31ce2453c82fatagen2026-09-24 13:07 UTC622
31ce2453c82fatagen2026-09-24 13:07 UTC623
    fn release(&mut self, scope: &MediaScope) {
31ce2453c82fatagen2026-09-24 13:07 UTC624
        self.entries.retain(|id, _| !scope.owns(id));
31ce2453c82fatagen2026-09-24 13:07 UTC625
        let entries = &self.entries;
31ce2453c82fatagen2026-09-24 13:07 UTC626
        self.order.retain(|(id, _)| entries.contains_key(id));
31ce2453c82fatagen2026-09-24 13:07 UTC627
    }
31ce2453c82fatagen2026-09-24 13:07 UTC628
31ce2453c82fatagen2026-09-24 13:07 UTC629
    fn clear(&mut self) {
31ce2453c82fatagen2026-09-24 13:07 UTC630
        self.entries.clear();
31ce2453c82fatagen2026-09-24 13:07 UTC631
        self.order.clear();
31ce2453c82fatagen2026-09-24 13:07 UTC632
    }
31ce2453c82fatagen2026-09-24 13:07 UTC633
}