Skip to main content

matrix_sdk_ui/
image_packs.rs

1// Copyright 2026 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! [Image packs], which hold the custom emoticons and stickers that can be
16//! used in a room.
17//!
18//! [Image packs]: https://spec.matrix.org/v1.19/client-server-api/#image-packs
19
20use std::collections::BTreeMap;
21
22use itertools::Itertools;
23use matrix_sdk::{
24    Client, Result, Room, RoomState,
25    deserialized_responses::{RawSyncOrStrippedState, SyncOrStrippedState},
26};
27use ruma::{
28    OwnedRoomId,
29    events::{
30        SyncStateEvent,
31        image_pack::rooms::{ImagePackRoomsEventContent, RoomImagePackMeta},
32        room::image_pack::{PackUsage, RoomImagePackEventContent},
33    },
34};
35use tracing::warn;
36
37use crate::spaces::SpaceService;
38
39/// An image pack, defined by an `m.room.image_pack` state event.
40#[derive(Clone, Debug)]
41pub struct ImagePack {
42    /// The room the pack is defined in.
43    pub room_id: OwnedRoomId,
44    /// The state key of the pack's state event, identifying it within its
45    /// room.
46    pub state_key: String,
47    /// The pack's images and metadata.
48    ///
49    /// If the pack doesn't have a display name or an avatar, those of its room
50    /// are used, as the spec recommends.
51    pub content: RoomImagePackEventContent,
52    /// Whether the user enabled the pack globally, through their
53    /// `m.image_pack.rooms` account data.
54    pub is_enabled_globally: bool,
55}
56
57impl ImagePack {
58    /// Whether the pack's images can be used as inline emoticons.
59    pub fn is_emoticon_pack(&self) -> bool {
60        self.is_usable_as(PackUsage::Emoticon)
61    }
62
63    /// Whether the pack's images can be sent as stickers.
64    pub fn is_sticker_pack(&self) -> bool {
65        self.is_usable_as(PackUsage::Sticker)
66    }
67
68    /// Packs without a usage can be used for everything.
69    fn is_usable_as(&self, usage: PackUsage) -> bool {
70        let usages = &self.content.pack.usage;
71        usages.is_empty() || usages.contains(&usage)
72    }
73}
74
75/// Get the image packs that can be used in a room.
76///
77/// They are returned in the order in which the spec recommends presenting
78/// them:
79///
80/// 1. The packs that the user enabled globally through their
81///    `m.image_pack.rooms` account data. The ones of rooms the user isn't in
82///    are skipped, as their images can't be accessed.
83/// 2. The packs defined in the room's state.
84/// 3. The packs defined in the state of the joined spaces the room belongs to,
85///    closest spaces first.
86///
87/// The packs of the same room are sorted by state key. A pack that would appear
88/// more than once is only returned the first time.
89/// Packs without images are skipped.
90///
91/// All the packs are read from the local state of their rooms, which the
92/// [`RoomListService`](crate::RoomListService) requests.
93pub async fn image_packs(room: &Room, space_service: &SpaceService) -> Result<Vec<ImagePack>> {
94    let client = room.client();
95    let enabled_packs = enabled_packs(&client).await?;
96    let mut packs = Vec::new();
97
98    for (room_id, state_keys) in &enabled_packs {
99        let Some(pack_room) =
100            client.get_room(room_id).filter(|room| room.state() == RoomState::Joined)
101        else {
102            continue;
103        };
104
105        let events = pack_room.get_state_events_for_keys_static(state_keys.keys()).await?;
106        packs.extend(image_packs_from(&pack_room, events, &enabled_packs));
107    }
108
109    packs.extend(image_packs_from(room, room.get_state_events_static().await?, &enabled_packs));
110
111    for space_id in space_service.joined_ancestors_of(room.room_id()).await {
112        if let Some(space) = client.get_room(&space_id) {
113            let events = space.get_state_events_static().await?;
114            packs.extend(image_packs_from(&space, events, &enabled_packs));
115        }
116    }
117
118    // Keep only the first occurrence of each pack, identified by its room and
119    // state key.
120    Ok(packs.into_iter().unique_by(|pack| (pack.room_id.clone(), pack.state_key.clone())).collect())
121}
122
123/// Get the packs that the user enabled globally through their
124/// `m.image_pack.rooms` account data, by room and state key.
125async fn enabled_packs(
126    client: &Client,
127) -> Result<BTreeMap<OwnedRoomId, BTreeMap<String, RoomImagePackMeta>>> {
128    let Some(raw) = client.account().account_data::<ImagePackRoomsEventContent>().await? else {
129        return Ok(BTreeMap::new());
130    };
131
132    // Any client can write this account data, so a malformed one is ignored
133    // rather than hiding the packs of the room and its spaces too.
134    Ok(raw.deserialize().map(|content| content.rooms).unwrap_or_else(|error| {
135        warn!("Ignoring malformed m.image_pack.rooms account data: {error}");
136        Default::default()
137    }))
138}
139
140/// Turn a room's `m.room.image_pack` state events into image packs.
141fn image_packs_from(
142    room: &Room,
143    events: Vec<RawSyncOrStrippedState<RoomImagePackEventContent>>,
144    enabled_packs: &BTreeMap<OwnedRoomId, BTreeMap<String, RoomImagePackMeta>>,
145) -> impl Iterator<Item = ImagePack> {
146    let enabled_state_keys = enabled_packs.get(room.room_id());
147
148    events
149        .into_iter()
150        .filter_map(move |raw| match raw.deserialize() {
151            // Packs without images have nothing to offer.
152            Ok(SyncOrStrippedState::Sync(SyncStateEvent::Original(mut event)))
153                if !event.content.images.is_empty() =>
154            {
155                let is_enabled_globally = enabled_state_keys
156                    .is_some_and(|state_keys| state_keys.contains_key(&event.state_key));
157
158                // Use the room's name and avatar for the pack's missing ones.
159                let meta = &mut event.content.pack;
160                meta.display_name = meta.display_name.take().or_else(|| room.name());
161                meta.avatar_url = meta.avatar_url.take().or_else(|| room.avatar_url());
162
163                Some(ImagePack {
164                    room_id: room.room_id().to_owned(),
165                    state_key: event.state_key,
166                    content: event.content,
167                    is_enabled_globally,
168                })
169            }
170            _ => None,
171        })
172        // The store returns state events in no particular order.
173        .sorted_by(|a, b| a.state_key.cmp(&b.state_key))
174}
175
176#[cfg(test)]
177mod tests {
178    use std::collections::{BTreeMap, BTreeSet};
179
180    use ruma::{events::room::image_pack::PackUsage, owned_room_id};
181
182    use super::{ImagePack, RoomImagePackEventContent};
183
184    fn pack(usage: &[PackUsage]) -> ImagePack {
185        let mut content = RoomImagePackEventContent::new(BTreeMap::new());
186        content.pack.usage = BTreeSet::from_iter(usage.iter().cloned());
187        ImagePack {
188            room_id: owned_room_id!("!room:localhost"),
189            state_key: String::new(),
190            content,
191            is_enabled_globally: false,
192        }
193    }
194
195    #[test]
196    fn test_usage() {
197        // A pack without a usage can be used for everything.
198        let pack_without_usage = pack(&[]);
199        assert!(pack_without_usage.is_emoticon_pack());
200        assert!(pack_without_usage.is_sticker_pack());
201
202        // Otherwise, it can only be used as it says.
203        let sticker_pack = pack(&[PackUsage::Sticker]);
204        assert!(!sticker_pack.is_emoticon_pack());
205        assert!(sticker_pack.is_sticker_pack());
206    }
207}