atagen

macltok

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

Blame: src/engine/mutations.rs

5a52012c9b1datagen2026-09-24 23:45 UTC1
use std::{
5a52012c9b1datagen2026-09-24 23:45 UTC2
    collections::{HashMap, HashSet, VecDeque},
5a52012c9b1datagen2026-09-24 23:45 UTC3
    sync::Arc,
5a52012c9b1datagen2026-09-24 23:45 UTC4
};
31ce2453c82fatagen2026-09-24 13:07 UTC5
31ce2453c82fatagen2026-09-24 13:07 UTC6
use matrix_sdk::{
31ce2453c82fatagen2026-09-24 13:07 UTC7
    Client, Room,
31ce2453c82fatagen2026-09-24 13:07 UTC8
    ruma::{
31ce2453c82fatagen2026-09-24 13:07 UTC9
        Int,
9bd34e25bb86atagen2026-10-24 07:23 UTC10
        api::client::{
9bd34e25bb86atagen2026-10-24 07:23 UTC11
            profile::{AvatarUrl, DisplayName},
9bd34e25bb86atagen2026-10-24 07:23 UTC12
            room::{
9bd34e25bb86atagen2026-10-24 07:23 UTC13
                Visibility as SdkVisibility,
9bd34e25bb86atagen2026-10-24 07:23 UTC14
                create_room::v3::{Request as CreateRoomRequest, RoomPreset as SdkPreset},
9bd34e25bb86atagen2026-10-24 07:23 UTC15
            },
9bd34e25bb86atagen2026-10-24 07:23 UTC16
            state::get_state_event_for_key,
31ce2453c82fatagen2026-09-24 13:07 UTC17
        },
31ce2453c82fatagen2026-09-24 13:07 UTC18
        events::{
31ce2453c82fatagen2026-09-24 13:07 UTC19
            AnyGlobalAccountDataEventContent, GlobalAccountDataEventType, MessageLikeEventType,
9bd34e25bb86atagen2026-10-24 07:23 UTC20
            StateEventType,
9bd34e25bb86atagen2026-10-24 07:23 UTC21
            ignored_user_list::{IgnoredUser, IgnoredUserListEventContent},
9bd34e25bb86atagen2026-10-24 07:23 UTC22
            room::power_levels::RoomPowerLevelsEventContent,
31ce2453c82fatagen2026-09-24 13:07 UTC23
        },
9bd34e25bb86atagen2026-10-24 07:23 UTC24
        serde::{JsonObject, Raw},
31ce2453c82fatagen2026-09-24 13:07 UTC25
    },
31ce2453c82fatagen2026-09-24 13:07 UTC26
};
31ce2453c82fatagen2026-09-24 13:07 UTC27
use ruma::{OwnedRoomId, OwnedUserId};
9bd34e25bb86atagen2026-10-24 07:23 UTC28
use serde_json::Value as JsonValue;
1fe480c16a3catagen2026-09-26 08:44 UTC29
use tokio::sync::mpsc;
31ce2453c82fatagen2026-09-24 13:07 UTC30
31ce2453c82fatagen2026-09-24 13:07 UTC31
use super::commands::{Job, guarded};
1fe480c16a3catagen2026-09-26 08:44 UTC32
use super::executor::TaskSet;
fa51490b6ae9atagen2026-10-24 08:41 UTC33
use super::packs::{self, PackEdit};
31ce2453c82fatagen2026-09-24 13:07 UTC34
use crate::{
fa51490b6ae9atagen2026-10-24 08:41 UTC35
    CommandOutput, CreateRoomOptions, Error, ErrorKind, ImagePackSource, PowerLevelChanges,
fa51490b6ae9atagen2026-10-24 08:41 UTC36
    RoomCommand, RoomPreset, RoomVisibility,
fa51490b6ae9atagen2026-10-24 08:41 UTC37
    normalise::{ENABLED_ROOMS, USER_PACK, stored_space_order},
fa51490b6ae9atagen2026-10-24 08:41 UTC38
    space_order,
31ce2453c82fatagen2026-09-24 13:07 UTC39
};
31ce2453c82fatagen2026-09-24 13:07 UTC40
31ce2453c82fatagen2026-09-24 13:07 UTC41
/// state changes that must not race each other. same room, same alias, same dm
31ce2453c82fatagen2026-09-24 13:07 UTC42
/// partner or same account data type run in order, everything else runs at once
31ce2453c82fatagen2026-09-24 13:07 UTC43
pub(super) enum Mutation {
31ce2453c82fatagen2026-09-24 13:07 UTC44
    Room(RoomCommand),
31ce2453c82fatagen2026-09-24 13:07 UTC45
    GlobalAccountData {
31ce2453c82fatagen2026-09-24 13:07 UTC46
        event_type: GlobalAccountDataEventType,
31ce2453c82fatagen2026-09-24 13:07 UTC47
        content: Raw<AnyGlobalAccountDataEventContent>,
31ce2453c82fatagen2026-09-24 13:07 UTC48
    },
9bd34e25bb86atagen2026-10-24 07:23 UTC49
    Ignore {
9bd34e25bb86atagen2026-10-24 07:23 UTC50
        user_id: OwnedUserId,
9bd34e25bb86atagen2026-10-24 07:23 UTC51
        ignored: bool,
9bd34e25bb86atagen2026-10-24 07:23 UTC52
    },
9bd34e25bb86atagen2026-10-24 07:23 UTC53
    ReorderSpaces(Vec<OwnedRoomId>),
fa51490b6ae9atagen2026-10-24 08:41 UTC54
    Pack {
fa51490b6ae9atagen2026-10-24 08:41 UTC55
        pack: ImagePackSource,
fa51490b6ae9atagen2026-10-24 08:41 UTC56
        edit: PackEdit,
fa51490b6ae9atagen2026-10-24 08:41 UTC57
    },
fa51490b6ae9atagen2026-10-24 08:41 UTC58
    PackEnabledEverywhere {
fa51490b6ae9atagen2026-10-24 08:41 UTC59
        room_id: OwnedRoomId,
fa51490b6ae9atagen2026-10-24 08:41 UTC60
        state_key: String,
fa51490b6ae9atagen2026-10-24 08:41 UTC61
        enabled: bool,
fa51490b6ae9atagen2026-10-24 08:41 UTC62
    },
31ce2453c82fatagen2026-09-24 13:07 UTC63
}
31ce2453c82fatagen2026-09-24 13:07 UTC64
31ce2453c82fatagen2026-09-24 13:07 UTC65
pub(super) type MutationJob = Job<Mutation>;
31ce2453c82fatagen2026-09-24 13:07 UTC66
31ce2453c82fatagen2026-09-24 13:07 UTC67
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
31ce2453c82fatagen2026-09-24 13:07 UTC68
enum Key {
31ce2453c82fatagen2026-09-24 13:07 UTC69
    Room(OwnedRoomId),
31ce2453c82fatagen2026-09-24 13:07 UTC70
    Alias(String),
31ce2453c82fatagen2026-09-24 13:07 UTC71
    Direct(OwnedUserId),
31ce2453c82fatagen2026-09-24 13:07 UTC72
    AccountData(String),
31ce2453c82fatagen2026-09-24 13:07 UTC73
    Independent(u64),
31ce2453c82fatagen2026-09-24 13:07 UTC74
}
31ce2453c82fatagen2026-09-24 13:07 UTC75
31ce2453c82fatagen2026-09-24 13:07 UTC76
pub(super) async fn run_scheduler(
31ce2453c82fatagen2026-09-24 13:07 UTC77
    client: Client,
31ce2453c82fatagen2026-09-24 13:07 UTC78
    mut jobs: mpsc::Receiver<MutationJob>,
31ce2453c82fatagen2026-09-24 13:07 UTC79
    queue_limit: usize,
31ce2453c82fatagen2026-09-24 13:07 UTC80
) {
9bd34e25bb86atagen2026-10-24 07:23 UTC81
    let fresh = Fresh::default();
31ce2453c82fatagen2026-09-24 13:07 UTC82
    let mut waiting = HashMap::<Key, VecDeque<MutationJob>>::new();
31ce2453c82fatagen2026-09-24 13:07 UTC83
    let mut running = HashSet::<Key>::new();
1fe480c16a3catagen2026-09-26 08:44 UTC84
    let mut tasks = TaskSet::<Key>::new();
31ce2453c82fatagen2026-09-24 13:07 UTC85
    let mut queued = 0_usize;
31ce2453c82fatagen2026-09-24 13:07 UTC86
    let mut independent = 0_u64;
31ce2453c82fatagen2026-09-24 13:07 UTC87
    let mut receiving = true;
31ce2453c82fatagen2026-09-24 13:07 UTC88
    while receiving || !tasks.is_empty() {
31ce2453c82fatagen2026-09-24 13:07 UTC89
        tokio::select! {
31ce2453c82fatagen2026-09-24 13:07 UTC90
            biased;
31ce2453c82fatagen2026-09-24 13:07 UTC91
            Some(finished) = tasks.join_next(), if !tasks.is_empty() => {
31ce2453c82fatagen2026-09-24 13:07 UTC92
                // a job's own panic is caught inside it, so this is only ever a key
31ce2453c82fatagen2026-09-24 13:07 UTC93
                let Ok(key) = finished else { continue };
31ce2453c82fatagen2026-09-24 13:07 UTC94
                let next = waiting.get_mut(&key).and_then(VecDeque::pop_front);
31ce2453c82fatagen2026-09-24 13:07 UTC95
                if waiting.get(&key).is_some_and(VecDeque::is_empty) {
31ce2453c82fatagen2026-09-24 13:07 UTC96
                    waiting.remove(&key);
31ce2453c82fatagen2026-09-24 13:07 UTC97
                }
31ce2453c82fatagen2026-09-24 13:07 UTC98
                match next {
31ce2453c82fatagen2026-09-24 13:07 UTC99
                    Some(job) => {
31ce2453c82fatagen2026-09-24 13:07 UTC100
                        queued -= 1;
9bd34e25bb86atagen2026-10-24 07:23 UTC101
                        spawn(&mut tasks, &client, &fresh, key, job);
31ce2453c82fatagen2026-09-24 13:07 UTC102
                    }
31ce2453c82fatagen2026-09-24 13:07 UTC103
                    None => {
31ce2453c82fatagen2026-09-24 13:07 UTC104
                        running.remove(&key);
31ce2453c82fatagen2026-09-24 13:07 UTC105
                    }
31ce2453c82fatagen2026-09-24 13:07 UTC106
                }
31ce2453c82fatagen2026-09-24 13:07 UTC107
            }
31ce2453c82fatagen2026-09-24 13:07 UTC108
            job = jobs.recv(), if receiving => {
31ce2453c82fatagen2026-09-24 13:07 UTC109
                let Some(job) = job else {
31ce2453c82fatagen2026-09-24 13:07 UTC110
                    receiving = false;
31ce2453c82fatagen2026-09-24 13:07 UTC111
                    continue;
31ce2453c82fatagen2026-09-24 13:07 UTC112
                };
5a52012c9b1datagen2026-09-24 23:45 UTC113
                let key = key(&job.command, client.user_id().map(ruma::UserId::server_name)).unwrap_or_else(|| {
31ce2453c82fatagen2026-09-24 13:07 UTC114
                    independent += 1;
31ce2453c82fatagen2026-09-24 13:07 UTC115
                    Key::Independent(independent)
31ce2453c82fatagen2026-09-24 13:07 UTC116
                });
31ce2453c82fatagen2026-09-24 13:07 UTC117
                if running.insert(key.clone()) {
9bd34e25bb86atagen2026-10-24 07:23 UTC118
                    spawn(&mut tasks, &client, &fresh, key, job);
31ce2453c82fatagen2026-09-24 13:07 UTC119
                } else if queued < queue_limit {
31ce2453c82fatagen2026-09-24 13:07 UTC120
                    waiting.entry(key).or_default().push_back(job);
31ce2453c82fatagen2026-09-24 13:07 UTC121
                    queued += 1;
31ce2453c82fatagen2026-09-24 13:07 UTC122
                } else {
31ce2453c82fatagen2026-09-24 13:07 UTC123
                    job.reply.done(Err(Error::new(
31ce2453c82fatagen2026-09-24 13:07 UTC124
                        ErrorKind::QueueFull,
31ce2453c82fatagen2026-09-24 13:07 UTC125
                        "room command queue is full",
31ce2453c82fatagen2026-09-24 13:07 UTC126
                    )));
31ce2453c82fatagen2026-09-24 13:07 UTC127
                }
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
5a52012c9b1datagen2026-09-24 23:45 UTC133
/// `server` is ours, since a new alias lives there
5a52012c9b1datagen2026-09-24 23:45 UTC134
fn key(mutation: &Mutation, server: Option<&ruma::ServerName>) -> Option<Key> {
31ce2453c82fatagen2026-09-24 13:07 UTC135
    let room_id = match mutation {
31ce2453c82fatagen2026-09-24 13:07 UTC136
        Mutation::GlobalAccountData { event_type, .. } => {
31ce2453c82fatagen2026-09-24 13:07 UTC137
            return Some(Key::AccountData(event_type.to_string()));
31ce2453c82fatagen2026-09-24 13:07 UTC138
        }
9bd34e25bb86atagen2026-10-24 07:23 UTC139
        Mutation::Ignore { .. } => {
9bd34e25bb86atagen2026-10-24 07:23 UTC140
            return Some(Key::AccountData(
9bd34e25bb86atagen2026-10-24 07:23 UTC141
                GlobalAccountDataEventType::IgnoredUserList.to_string(),
9bd34e25bb86atagen2026-10-24 07:23 UTC142
            ));
9bd34e25bb86atagen2026-10-24 07:23 UTC143
        }
9bd34e25bb86atagen2026-10-24 07:23 UTC144
        Mutation::ReorderSpaces(_) => {
9bd34e25bb86atagen2026-10-24 07:23 UTC145
            return Some(Key::AccountData(space_order::EVENT_TYPE.to_owned()));
9bd34e25bb86atagen2026-10-24 07:23 UTC146
        }
fa51490b6ae9atagen2026-10-24 08:41 UTC147
        Mutation::Pack {
fa51490b6ae9atagen2026-10-24 08:41 UTC148
            pack: ImagePackSource::User,
fa51490b6ae9atagen2026-10-24 08:41 UTC149
            ..
fa51490b6ae9atagen2026-10-24 08:41 UTC150
        } => return Some(Key::AccountData(USER_PACK.to_owned())),
fa51490b6ae9atagen2026-10-24 08:41 UTC151
        Mutation::Pack {
fa51490b6ae9atagen2026-10-24 08:41 UTC152
            pack: ImagePackSource::Room { room_id, .. },
fa51490b6ae9atagen2026-10-24 08:41 UTC153
            ..
fa51490b6ae9atagen2026-10-24 08:41 UTC154
        } => room_id,
fa51490b6ae9atagen2026-10-24 08:41 UTC155
        Mutation::PackEnabledEverywhere { .. } => {
fa51490b6ae9atagen2026-10-24 08:41 UTC156
            return Some(Key::AccountData(ENABLED_ROOMS.to_owned()));
fa51490b6ae9atagen2026-10-24 08:41 UTC157
        }
31ce2453c82fatagen2026-09-24 13:07 UTC158
        Mutation::Room(RoomCommand::Join { room, .. }) => {
31ce2453c82fatagen2026-09-24 13:07 UTC159
            return Some(match OwnedRoomId::try_from(room.clone()) {
31ce2453c82fatagen2026-09-24 13:07 UTC160
                Ok(room_id) => Key::Room(room_id),
31ce2453c82fatagen2026-09-24 13:07 UTC161
                Err(alias) => Key::Alias(alias.to_string()),
31ce2453c82fatagen2026-09-24 13:07 UTC162
            });
31ce2453c82fatagen2026-09-24 13:07 UTC163
        }
31ce2453c82fatagen2026-09-24 13:07 UTC164
        Mutation::Room(RoomCommand::CreateDirect(user_id)) => {
31ce2453c82fatagen2026-09-24 13:07 UTC165
            return Some(Key::Direct(user_id.clone()));
31ce2453c82fatagen2026-09-24 13:07 UTC166
        }
5a52012c9b1datagen2026-09-24 23:45 UTC167
        Mutation::Room(RoomCommand::Create(options)) => {
5a52012c9b1datagen2026-09-24 23:45 UTC168
            return match (&options.alias_localpart, options.invite.as_slice()) {
5a52012c9b1datagen2026-09-24 23:45 UTC169
                (Some(localpart), _) => Some(Key::Alias(format!("#{localpart}:{}", server?))),
5a52012c9b1datagen2026-09-24 23:45 UTC170
                (None, [user_id]) if options.direct => Some(Key::Direct(user_id.clone())),
5a52012c9b1datagen2026-09-24 23:45 UTC171
                _ => None,
5a52012c9b1datagen2026-09-24 23:45 UTC172
            };
5a52012c9b1datagen2026-09-24 23:45 UTC173
        }
31ce2453c82fatagen2026-09-24 13:07 UTC174
        Mutation::Room(
31ce2453c82fatagen2026-09-24 13:07 UTC175
            RoomCommand::Leave(room_id)
31ce2453c82fatagen2026-09-24 13:07 UTC176
            | RoomCommand::Forget(room_id)
31ce2453c82fatagen2026-09-24 13:07 UTC177
            | RoomCommand::AcceptInvite(room_id)
31ce2453c82fatagen2026-09-24 13:07 UTC178
            | RoomCommand::RejectInvite(room_id)
31ce2453c82fatagen2026-09-24 13:07 UTC179
            | RoomCommand::InviteUser { room_id, .. }
31ce2453c82fatagen2026-09-24 13:07 UTC180
            | RoomCommand::KickUser { room_id, .. }
31ce2453c82fatagen2026-09-24 13:07 UTC181
            | RoomCommand::BanUser { room_id, .. }
31ce2453c82fatagen2026-09-24 13:07 UTC182
            | RoomCommand::UnbanUser { room_id, .. }
31ce2453c82fatagen2026-09-24 13:07 UTC183
            | RoomCommand::SetPowerLevels { room_id, .. }
31ce2453c82fatagen2026-09-24 13:07 UTC184
            | RoomCommand::SetUserPowerLevel { room_id, .. }
9bd34e25bb86atagen2026-10-24 07:23 UTC185
            | RoomCommand::MuteUser { room_id, .. }
9bd34e25bb86atagen2026-10-24 07:23 UTC186
            | RoomCommand::SetFavourite { room_id, .. }
9bd34e25bb86atagen2026-10-24 07:23 UTC187
            | RoomCommand::SetOwnDisplayName { room_id, .. }
9bd34e25bb86atagen2026-10-24 07:23 UTC188
            | RoomCommand::SetOwnAvatar { room_id, .. }
31ce2453c82fatagen2026-09-24 13:07 UTC189
            | RoomCommand::SetAccountData { room_id, .. },
31ce2453c82fatagen2026-09-24 13:07 UTC190
        ) => room_id,
31ce2453c82fatagen2026-09-24 13:07 UTC191
        Mutation::Room(_) => return None,
31ce2453c82fatagen2026-09-24 13:07 UTC192
    };
31ce2453c82fatagen2026-09-24 13:07 UTC193
    Some(Key::Room(room_id.clone()))
31ce2453c82fatagen2026-09-24 13:07 UTC194
}
31ce2453c82fatagen2026-09-24 13:07 UTC195
5a52012c9b1datagen2026-09-24 23:45 UTC196
/// dms made here that the next sync hasn't told the sdk about yet, since `get_dm_room`
5a52012c9b1datagen2026-09-24 23:45 UTC197
/// only knows `m.direct` once it comes back round
5a52012c9b1datagen2026-09-24 23:45 UTC198
type FreshDms = Arc<std::sync::Mutex<HashMap<OwnedUserId, OwnedRoomId>>>;
5a52012c9b1datagen2026-09-24 23:45 UTC199
9bd34e25bb86atagen2026-10-24 07:23 UTC200
/// space orders written here that sync hasn't echoed into the store yet
9bd34e25bb86atagen2026-10-24 07:23 UTC201
type FreshOrders = Arc<std::sync::Mutex<HashMap<OwnedRoomId, String>>>;
9bd34e25bb86atagen2026-10-24 07:23 UTC202
9bd34e25bb86atagen2026-10-24 07:23 UTC203
#[derive(Clone, Default)]
9bd34e25bb86atagen2026-10-24 07:23 UTC204
struct Fresh {
9bd34e25bb86atagen2026-10-24 07:23 UTC205
    dms: FreshDms,
9bd34e25bb86atagen2026-10-24 07:23 UTC206
    orders: FreshOrders,
9bd34e25bb86atagen2026-10-24 07:23 UTC207
}
9bd34e25bb86atagen2026-10-24 07:23 UTC208
9bd34e25bb86atagen2026-10-24 07:23 UTC209
fn spawn(tasks: &mut TaskSet<Key>, client: &Client, fresh: &Fresh, key: Key, job: MutationJob) {
31ce2453c82fatagen2026-09-24 13:07 UTC210
    let client = client.clone();
9bd34e25bb86atagen2026-10-24 07:23 UTC211
    let fresh = fresh.clone();
31ce2453c82fatagen2026-09-24 13:07 UTC212
    tasks.spawn(async move {
31ce2453c82fatagen2026-09-24 13:07 UTC213
        let Job { command, reply } = job;
9bd34e25bb86atagen2026-10-24 07:23 UTC214
        reply.send(guarded("room command", execute(&client, &fresh, command)).await);
31ce2453c82fatagen2026-09-24 13:07 UTC215
        key
31ce2453c82fatagen2026-09-24 13:07 UTC216
    });
31ce2453c82fatagen2026-09-24 13:07 UTC217
}
31ce2453c82fatagen2026-09-24 13:07 UTC218
5a52012c9b1datagen2026-09-24 23:45 UTC219
async fn execute(
5a52012c9b1datagen2026-09-24 23:45 UTC220
    client: &Client,
9bd34e25bb86atagen2026-10-24 07:23 UTC221
    fresh: &Fresh,
5a52012c9b1datagen2026-09-24 23:45 UTC222
    mutation: Mutation,
5a52012c9b1datagen2026-09-24 23:45 UTC223
) -> Result<CommandOutput, Error> {
31ce2453c82fatagen2026-09-24 13:07 UTC224
    let command = match mutation {
31ce2453c82fatagen2026-09-24 13:07 UTC225
        Mutation::GlobalAccountData {
31ce2453c82fatagen2026-09-24 13:07 UTC226
            event_type,
31ce2453c82fatagen2026-09-24 13:07 UTC227
            content,
31ce2453c82fatagen2026-09-24 13:07 UTC228
        } => {
31ce2453c82fatagen2026-09-24 13:07 UTC229
            client
31ce2453c82fatagen2026-09-24 13:07 UTC230
                .account()
31ce2453c82fatagen2026-09-24 13:07 UTC231
                .set_account_data_raw(event_type, content)
31ce2453c82fatagen2026-09-24 13:07 UTC232
                .await
31ce2453c82fatagen2026-09-24 13:07 UTC233
                .map_err(|source| Error::from_sdk("writing account data failed", source))?;
31ce2453c82fatagen2026-09-24 13:07 UTC234
            return Ok(CommandOutput::Done);
31ce2453c82fatagen2026-09-24 13:07 UTC235
        }
9bd34e25bb86atagen2026-10-24 07:23 UTC236
        Mutation::Ignore { user_id, ignored } => {
9bd34e25bb86atagen2026-10-24 07:23 UTC237
            return set_ignored(client, user_id, ignored).await.map(done);
9bd34e25bb86atagen2026-10-24 07:23 UTC238
        }
9bd34e25bb86atagen2026-10-24 07:23 UTC239
        Mutation::ReorderSpaces(order) => {
9bd34e25bb86atagen2026-10-24 07:23 UTC240
            return reorder_spaces(client, &fresh.orders, order).await.map(done);
9bd34e25bb86atagen2026-10-24 07:23 UTC241
        }
fa51490b6ae9atagen2026-10-24 08:41 UTC242
        Mutation::Pack { pack, edit } => return packs::edit_pack(client, &pack, edit).await,
fa51490b6ae9atagen2026-10-24 08:41 UTC243
        Mutation::PackEnabledEverywhere {
fa51490b6ae9atagen2026-10-24 08:41 UTC244
            room_id,
fa51490b6ae9atagen2026-10-24 08:41 UTC245
            state_key,
fa51490b6ae9atagen2026-10-24 08:41 UTC246
            enabled,
fa51490b6ae9atagen2026-10-24 08:41 UTC247
        } => {
fa51490b6ae9atagen2026-10-24 08:41 UTC248
            return packs::set_enabled_everywhere(client, room_id, state_key, enabled)
fa51490b6ae9atagen2026-10-24 08:41 UTC249
                .await
fa51490b6ae9atagen2026-10-24 08:41 UTC250
                .map(done);
fa51490b6ae9atagen2026-10-24 08:41 UTC251
        }
31ce2453c82fatagen2026-09-24 13:07 UTC252
        Mutation::Room(command) => command,
31ce2453c82fatagen2026-09-24 13:07 UTC253
    };
9bd34e25bb86atagen2026-10-24 07:23 UTC254
    let fresh_dms = &fresh.dms;
31ce2453c82fatagen2026-09-24 13:07 UTC255
    let room = |room_id: &OwnedRoomId| client.get_room(room_id).ok_or_else(Error::room_unknown);
31ce2453c82fatagen2026-09-24 13:07 UTC256
    let joined = |room: Room| CommandOutput::Room(room.room_id().to_owned());
31ce2453c82fatagen2026-09-24 13:07 UTC257
    let sdk = |message: &'static str| move |source| Error::from_sdk(message, source);
31ce2453c82fatagen2026-09-24 13:07 UTC258
    match command {
31ce2453c82fatagen2026-09-24 13:07 UTC259
        RoomCommand::Join { room, via } => client
31ce2453c82fatagen2026-09-24 13:07 UTC260
            .join_room_by_id_or_alias(&room, &via)
31ce2453c82fatagen2026-09-24 13:07 UTC261
            .await
31ce2453c82fatagen2026-09-24 13:07 UTC262
            .map(joined)
31ce2453c82fatagen2026-09-24 13:07 UTC263
            .map_err(sdk("joining room failed")),
31ce2453c82fatagen2026-09-24 13:07 UTC264
        RoomCommand::Leave(room_id) => room(&room_id)?
31ce2453c82fatagen2026-09-24 13:07 UTC265
            .leave()
31ce2453c82fatagen2026-09-24 13:07 UTC266
            .await
31ce2453c82fatagen2026-09-24 13:07 UTC267
            .map(done)
31ce2453c82fatagen2026-09-24 13:07 UTC268
            .map_err(sdk("leaving room failed")),
31ce2453c82fatagen2026-09-24 13:07 UTC269
        RoomCommand::Forget(room_id) => room(&room_id)?
31ce2453c82fatagen2026-09-24 13:07 UTC270
            .forget()
31ce2453c82fatagen2026-09-24 13:07 UTC271
            .await
31ce2453c82fatagen2026-09-24 13:07 UTC272
            .map(done)
31ce2453c82fatagen2026-09-24 13:07 UTC273
            .map_err(sdk("forgetting room failed")),
31ce2453c82fatagen2026-09-24 13:07 UTC274
        RoomCommand::AcceptInvite(room_id) => room(&room_id)?
31ce2453c82fatagen2026-09-24 13:07 UTC275
            .join()
31ce2453c82fatagen2026-09-24 13:07 UTC276
            .await
31ce2453c82fatagen2026-09-24 13:07 UTC277
            .map(done)
31ce2453c82fatagen2026-09-24 13:07 UTC278
            .map_err(sdk("accepting invite failed")),
31ce2453c82fatagen2026-09-24 13:07 UTC279
        RoomCommand::RejectInvite(room_id) => room(&room_id)?
31ce2453c82fatagen2026-09-24 13:07 UTC280
            .leave()
31ce2453c82fatagen2026-09-24 13:07 UTC281
            .await
31ce2453c82fatagen2026-09-24 13:07 UTC282
            .map(done)
31ce2453c82fatagen2026-09-24 13:07 UTC283
            .map_err(sdk("rejecting invite failed")),
31ce2453c82fatagen2026-09-24 13:07 UTC284
        RoomCommand::InviteUser { room_id, user_id } => room(&room_id)?
31ce2453c82fatagen2026-09-24 13:07 UTC285
            .invite_user_by_id(&user_id)
31ce2453c82fatagen2026-09-24 13:07 UTC286
            .await
31ce2453c82fatagen2026-09-24 13:07 UTC287
            .map(done)
31ce2453c82fatagen2026-09-24 13:07 UTC288
            .map_err(sdk("inviting user failed")),
31ce2453c82fatagen2026-09-24 13:07 UTC289
        RoomCommand::KickUser {
31ce2453c82fatagen2026-09-24 13:07 UTC290
            room_id,
31ce2453c82fatagen2026-09-24 13:07 UTC291
            user_id,
31ce2453c82fatagen2026-09-24 13:07 UTC292
            reason,
31ce2453c82fatagen2026-09-24 13:07 UTC293
        } => room(&room_id)?
31ce2453c82fatagen2026-09-24 13:07 UTC294
            .kick_user(&user_id, reason.as_deref())
31ce2453c82fatagen2026-09-24 13:07 UTC295
            .await
31ce2453c82fatagen2026-09-24 13:07 UTC296
            .map(done)
31ce2453c82fatagen2026-09-24 13:07 UTC297
            .map_err(sdk("kicking user failed")),
31ce2453c82fatagen2026-09-24 13:07 UTC298
        RoomCommand::BanUser {
31ce2453c82fatagen2026-09-24 13:07 UTC299
            room_id,
31ce2453c82fatagen2026-09-24 13:07 UTC300
            user_id,
31ce2453c82fatagen2026-09-24 13:07 UTC301
            reason,
31ce2453c82fatagen2026-09-24 13:07 UTC302
        } => room(&room_id)?
31ce2453c82fatagen2026-09-24 13:07 UTC303
            .ban_user(&user_id, reason.as_deref())
31ce2453c82fatagen2026-09-24 13:07 UTC304
            .await
31ce2453c82fatagen2026-09-24 13:07 UTC305
            .map(done)
31ce2453c82fatagen2026-09-24 13:07 UTC306
            .map_err(sdk("banning user failed")),
31ce2453c82fatagen2026-09-24 13:07 UTC307
        RoomCommand::UnbanUser {
31ce2453c82fatagen2026-09-24 13:07 UTC308
            room_id,
31ce2453c82fatagen2026-09-24 13:07 UTC309
            user_id,
31ce2453c82fatagen2026-09-24 13:07 UTC310
            reason,
31ce2453c82fatagen2026-09-24 13:07 UTC311
        } => room(&room_id)?
31ce2453c82fatagen2026-09-24 13:07 UTC312
            .unban_user(&user_id, reason.as_deref())
31ce2453c82fatagen2026-09-24 13:07 UTC313
            .await
31ce2453c82fatagen2026-09-24 13:07 UTC314
            .map(done)
31ce2453c82fatagen2026-09-24 13:07 UTC315
            .map_err(sdk("unbanning user failed")),
31ce2453c82fatagen2026-09-24 13:07 UTC316
        RoomCommand::SetPowerLevels { room_id, changes } => {
31ce2453c82fatagen2026-09-24 13:07 UTC317
            apply_power_level_changes(&room(&room_id)?, changes)
31ce2453c82fatagen2026-09-24 13:07 UTC318
                .await
31ce2453c82fatagen2026-09-24 13:07 UTC319
                .map(done)
31ce2453c82fatagen2026-09-24 13:07 UTC320
        }
31ce2453c82fatagen2026-09-24 13:07 UTC321
        RoomCommand::SetUserPowerLevel {
31ce2453c82fatagen2026-09-24 13:07 UTC322
            room_id,
31ce2453c82fatagen2026-09-24 13:07 UTC323
            user_id,
31ce2453c82fatagen2026-09-24 13:07 UTC324
            level,
31ce2453c82fatagen2026-09-24 13:07 UTC325
        } => room(&room_id)?
31ce2453c82fatagen2026-09-24 13:07 UTC326
            .update_power_levels(vec![(&user_id, power_level(level)?)])
31ce2453c82fatagen2026-09-24 13:07 UTC327
            .await
31ce2453c82fatagen2026-09-24 13:07 UTC328
            .map(done)
31ce2453c82fatagen2026-09-24 13:07 UTC329
            .map_err(sdk("updating user power level failed")),
9bd34e25bb86atagen2026-10-24 07:23 UTC330
        RoomCommand::MuteUser {
9bd34e25bb86atagen2026-10-24 07:23 UTC331
            room_id,
9bd34e25bb86atagen2026-10-24 07:23 UTC332
            user_id,
9bd34e25bb86atagen2026-10-24 07:23 UTC333
            muted,
9bd34e25bb86atagen2026-10-24 07:23 UTC334
        } => mute_user(client, &room(&room_id)?, &user_id, muted)
9bd34e25bb86atagen2026-10-24 07:23 UTC335
            .await
9bd34e25bb86atagen2026-10-24 07:23 UTC336
            .map(done),
9bd34e25bb86atagen2026-10-24 07:23 UTC337
        RoomCommand::SetFavourite { room_id, favourite } => room(&room_id)?
9bd34e25bb86atagen2026-10-24 07:23 UTC338
            .set_is_favourite(favourite, None)
9bd34e25bb86atagen2026-10-24 07:23 UTC339
            .await
9bd34e25bb86atagen2026-10-24 07:23 UTC340
            .map(done)
9bd34e25bb86atagen2026-10-24 07:23 UTC341
            .map_err(sdk("setting favourite failed")),
9bd34e25bb86atagen2026-10-24 07:23 UTC342
        RoomCommand::SetOwnDisplayName { room_id, name } => {
9bd34e25bb86atagen2026-10-24 07:23 UTC343
            set_own_member_field(client, &room(&room_id)?, ProfileField::DisplayName, name)
9bd34e25bb86atagen2026-10-24 07:23 UTC344
                .await
9bd34e25bb86atagen2026-10-24 07:23 UTC345
                .map(done)
9bd34e25bb86atagen2026-10-24 07:23 UTC346
        }
9bd34e25bb86atagen2026-10-24 07:23 UTC347
        RoomCommand::SetOwnAvatar { room_id, avatar } => set_own_member_field(
9bd34e25bb86atagen2026-10-24 07:23 UTC348
            client,
9bd34e25bb86atagen2026-10-24 07:23 UTC349
            &room(&room_id)?,
9bd34e25bb86atagen2026-10-24 07:23 UTC350
            ProfileField::Avatar,
9bd34e25bb86atagen2026-10-24 07:23 UTC351
            avatar.map(String::from),
9bd34e25bb86atagen2026-10-24 07:23 UTC352
        )
9bd34e25bb86atagen2026-10-24 07:23 UTC353
        .await
9bd34e25bb86atagen2026-10-24 07:23 UTC354
        .map(done),
31ce2453c82fatagen2026-09-24 13:07 UTC355
        RoomCommand::SetAccountData {
31ce2453c82fatagen2026-09-24 13:07 UTC356
            room_id,
31ce2453c82fatagen2026-09-24 13:07 UTC357
            event_type,
31ce2453c82fatagen2026-09-24 13:07 UTC358
            content,
31ce2453c82fatagen2026-09-24 13:07 UTC359
        } => room(&room_id)?
31ce2453c82fatagen2026-09-24 13:07 UTC360
            .set_account_data_raw(event_type, content)
31ce2453c82fatagen2026-09-24 13:07 UTC361
            .await
31ce2453c82fatagen2026-09-24 13:07 UTC362
            .map(done)
31ce2453c82fatagen2026-09-24 13:07 UTC363
            .map_err(sdk("writing room account data failed")),
31ce2453c82fatagen2026-09-24 13:07 UTC364
        RoomCommand::Create(options) => client
31ce2453c82fatagen2026-09-24 13:07 UTC365
            .create_room(create_room_request(options))
31ce2453c82fatagen2026-09-24 13:07 UTC366
            .await
31ce2453c82fatagen2026-09-24 13:07 UTC367
            .map(joined)
31ce2453c82fatagen2026-09-24 13:07 UTC368
            .map_err(sdk("creating room failed")),
5a52012c9b1datagen2026-09-24 23:45 UTC369
        RoomCommand::CreateDirect(user_id) => {
5a52012c9b1datagen2026-09-24 23:45 UTC370
            if let Some(existing) = client.get_dm_room(&user_id) {
5a52012c9b1datagen2026-09-24 23:45 UTC371
                return Ok(joined(existing));
5a52012c9b1datagen2026-09-24 23:45 UTC372
            }
5a52012c9b1datagen2026-09-24 23:45 UTC373
            let fresh = fresh_dms
5a52012c9b1datagen2026-09-24 23:45 UTC374
                .lock()
5a52012c9b1datagen2026-09-24 23:45 UTC375
                .expect("nothing panics holding this")
5a52012c9b1datagen2026-09-24 23:45 UTC376
                .get(&user_id)
5a52012c9b1datagen2026-09-24 23:45 UTC377
                .cloned();
5a52012c9b1datagen2026-09-24 23:45 UTC378
            if let Some(room_id) = fresh.filter(|room_id| client.get_room(room_id).is_some()) {
5a52012c9b1datagen2026-09-24 23:45 UTC379
                return Ok(CommandOutput::Room(room_id));
5a52012c9b1datagen2026-09-24 23:45 UTC380
            }
5a52012c9b1datagen2026-09-24 23:45 UTC381
            let room = client
31ce2453c82fatagen2026-09-24 13:07 UTC382
                .create_dm(&user_id)
31ce2453c82fatagen2026-09-24 13:07 UTC383
                .await
5a52012c9b1datagen2026-09-24 23:45 UTC384
                .map_err(sdk("creating direct room failed"))?;
5a52012c9b1datagen2026-09-24 23:45 UTC385
            fresh_dms
5a52012c9b1datagen2026-09-24 23:45 UTC386
                .lock()
5a52012c9b1datagen2026-09-24 23:45 UTC387
                .expect("nothing panics holding this")
5a52012c9b1datagen2026-09-24 23:45 UTC388
                .insert(user_id, room.room_id().to_owned());
5a52012c9b1datagen2026-09-24 23:45 UTC389
            Ok(joined(room))
5a52012c9b1datagen2026-09-24 23:45 UTC390
        }
31ce2453c82fatagen2026-09-24 13:07 UTC391
        _ => Err(Error::new(ErrorKind::Other, "room command was misrouted")),
31ce2453c82fatagen2026-09-24 13:07 UTC392
    }
31ce2453c82fatagen2026-09-24 13:07 UTC393
}
31ce2453c82fatagen2026-09-24 13:07 UTC394
31ce2453c82fatagen2026-09-24 13:07 UTC395
/// one state event carrying every requested change, since the sdk's own patcher is private
31ce2453c82fatagen2026-09-24 13:07 UTC396
async fn apply_power_level_changes(room: &Room, changes: PowerLevelChanges) -> Result<(), Error> {
31ce2453c82fatagen2026-09-24 13:07 UTC397
    let mut levels = room
31ce2453c82fatagen2026-09-24 13:07 UTC398
        .power_levels()
31ce2453c82fatagen2026-09-24 13:07 UTC399
        .await
31ce2453c82fatagen2026-09-24 13:07 UTC400
        .map_err(|source| Error::from_sdk("reading power levels failed", source.into()))?;
31ce2453c82fatagen2026-09-24 13:07 UTC401
    for (target, value) in [
31ce2453c82fatagen2026-09-24 13:07 UTC402
        (&mut levels.ban, changes.ban),
31ce2453c82fatagen2026-09-24 13:07 UTC403
        (&mut levels.invite, changes.invite),
31ce2453c82fatagen2026-09-24 13:07 UTC404
        (&mut levels.kick, changes.kick),
31ce2453c82fatagen2026-09-24 13:07 UTC405
        (&mut levels.redact, changes.redact),
31ce2453c82fatagen2026-09-24 13:07 UTC406
        (&mut levels.events_default, changes.events_default),
31ce2453c82fatagen2026-09-24 13:07 UTC407
        (&mut levels.state_default, changes.state_default),
31ce2453c82fatagen2026-09-24 13:07 UTC408
        (&mut levels.users_default, changes.users_default),
31ce2453c82fatagen2026-09-24 13:07 UTC409
        (&mut levels.notifications.room, changes.room_notification),
31ce2453c82fatagen2026-09-24 13:07 UTC410
    ] {
31ce2453c82fatagen2026-09-24 13:07 UTC411
        if let Some(value) = value {
31ce2453c82fatagen2026-09-24 13:07 UTC412
            *target = power_level(value)?;
31ce2453c82fatagen2026-09-24 13:07 UTC413
        }
31ce2453c82fatagen2026-09-24 13:07 UTC414
    }
31ce2453c82fatagen2026-09-24 13:07 UTC415
    for (event_type, value) in [
31ce2453c82fatagen2026-09-24 13:07 UTC416
        (StateEventType::RoomName.into(), changes.room_name),
31ce2453c82fatagen2026-09-24 13:07 UTC417
        (StateEventType::RoomAvatar.into(), changes.room_avatar),
31ce2453c82fatagen2026-09-24 13:07 UTC418
        (StateEventType::RoomTopic.into(), changes.room_topic),
31ce2453c82fatagen2026-09-24 13:07 UTC419
        (StateEventType::SpaceChild.into(), changes.space_child),
31ce2453c82fatagen2026-09-24 13:07 UTC420
        (MessageLikeEventType::Beacon.into(), changes.beacon),
31ce2453c82fatagen2026-09-24 13:07 UTC421
        (StateEventType::BeaconInfo.into(), changes.beacon_info),
31ce2453c82fatagen2026-09-24 13:07 UTC422
    ] {
31ce2453c82fatagen2026-09-24 13:07 UTC423
        if let Some(value) = value {
31ce2453c82fatagen2026-09-24 13:07 UTC424
            levels.events.insert(event_type, power_level(value)?);
31ce2453c82fatagen2026-09-24 13:07 UTC425
        }
31ce2453c82fatagen2026-09-24 13:07 UTC426
    }
31ce2453c82fatagen2026-09-24 13:07 UTC427
    let content = RoomPowerLevelsEventContent::try_from(levels).map_err(|source| {
31ce2453c82fatagen2026-09-24 13:07 UTC428
        Error::with_source(
31ce2453c82fatagen2026-09-24 13:07 UTC429
            ErrorKind::Invalid,
31ce2453c82fatagen2026-09-24 13:07 UTC430
            "normalising power levels failed",
31ce2453c82fatagen2026-09-24 13:07 UTC431
            source,
31ce2453c82fatagen2026-09-24 13:07 UTC432
        )
31ce2453c82fatagen2026-09-24 13:07 UTC433
    })?;
31ce2453c82fatagen2026-09-24 13:07 UTC434
    room.send_state_event(content)
31ce2453c82fatagen2026-09-24 13:07 UTC435
        .await
31ce2453c82fatagen2026-09-24 13:07 UTC436
        .map(drop)
31ce2453c82fatagen2026-09-24 13:07 UTC437
        .map_err(|source| Error::from_sdk("updating power levels failed", source))
31ce2453c82fatagen2026-09-24 13:07 UTC438
}
31ce2453c82fatagen2026-09-24 13:07 UTC439
9bd34e25bb86atagen2026-10-24 07:23 UTC440
/// reads the list from the server, since the store only catches up on the next sync
9bd34e25bb86atagen2026-10-24 07:23 UTC441
async fn set_ignored(client: &Client, user_id: OwnedUserId, ignored: bool) -> Result<(), Error> {
9bd34e25bb86atagen2026-10-24 07:23 UTC442
    if ignored && client.user_id() == Some(&*user_id) {
9bd34e25bb86atagen2026-10-24 07:23 UTC443
        return Err(Error::new(ErrorKind::Invalid, "you can't ignore yourself"));
9bd34e25bb86atagen2026-10-24 07:23 UTC444
    }
9bd34e25bb86atagen2026-10-24 07:23 UTC445
    let account = client.account();
9bd34e25bb86atagen2026-10-24 07:23 UTC446
    let mut list = account
9bd34e25bb86atagen2026-10-24 07:23 UTC447
        .fetch_account_data_static::<IgnoredUserListEventContent>()
9bd34e25bb86atagen2026-10-24 07:23 UTC448
        .await
9bd34e25bb86atagen2026-10-24 07:23 UTC449
        .map_err(|source| Error::from_sdk("reading the ignore list failed", source))?
9bd34e25bb86atagen2026-10-24 07:23 UTC450
        .map(|raw| raw.deserialize())
9bd34e25bb86atagen2026-10-24 07:23 UTC451
        .transpose()
9bd34e25bb86atagen2026-10-24 07:23 UTC452
        .map_err(|source| {
9bd34e25bb86atagen2026-10-24 07:23 UTC453
            Error::with_source(ErrorKind::Invalid, "the ignore list is malformed", source)
9bd34e25bb86atagen2026-10-24 07:23 UTC454
        })?
9bd34e25bb86atagen2026-10-24 07:23 UTC455
        .unwrap_or_default();
9bd34e25bb86atagen2026-10-24 07:23 UTC456
    let changed = if ignored {
9bd34e25bb86atagen2026-10-24 07:23 UTC457
        list.ignored_users
9bd34e25bb86atagen2026-10-24 07:23 UTC458
            .insert(user_id, IgnoredUser::new())
9bd34e25bb86atagen2026-10-24 07:23 UTC459
            .is_none()
9bd34e25bb86atagen2026-10-24 07:23 UTC460
    } else {
9bd34e25bb86atagen2026-10-24 07:23 UTC461
        list.ignored_users.remove(&user_id).is_some()
9bd34e25bb86atagen2026-10-24 07:23 UTC462
    };
9bd34e25bb86atagen2026-10-24 07:23 UTC463
    if !changed {
9bd34e25bb86atagen2026-10-24 07:23 UTC464
        return Ok(());
9bd34e25bb86atagen2026-10-24 07:23 UTC465
    }
9bd34e25bb86atagen2026-10-24 07:23 UTC466
    account
9bd34e25bb86atagen2026-10-24 07:23 UTC467
        .set_account_data(list)
9bd34e25bb86atagen2026-10-24 07:23 UTC468
        .await
9bd34e25bb86atagen2026-10-24 07:23 UTC469
        .map(drop)
9bd34e25bb86atagen2026-10-24 07:23 UTC470
        .map_err(|source| Error::from_sdk("writing the ignore list failed", source))
9bd34e25bb86atagen2026-10-24 07:23 UTC471
}
9bd34e25bb86atagen2026-10-24 07:23 UTC472
9bd34e25bb86atagen2026-10-24 07:23 UTC473
async fn reorder_spaces(
9bd34e25bb86atagen2026-10-24 07:23 UTC474
    client: &Client,
9bd34e25bb86atagen2026-10-24 07:23 UTC475
    fresh: &FreshOrders,
9bd34e25bb86atagen2026-10-24 07:23 UTC476
    order: Vec<OwnedRoomId>,
9bd34e25bb86atagen2026-10-24 07:23 UTC477
) -> Result<(), Error> {
9bd34e25bb86atagen2026-10-24 07:23 UTC478
    if order.iter().collect::<HashSet<_>>().len() != order.len() {
9bd34e25bb86atagen2026-10-24 07:23 UTC479
        return Err(Error::new(ErrorKind::Invalid, "a space is listed twice"));
9bd34e25bb86atagen2026-10-24 07:23 UTC480
    }
9bd34e25bb86atagen2026-10-24 07:23 UTC481
    let mut rooms = HashMap::new();
9bd34e25bb86atagen2026-10-24 07:23 UTC482
    let mut spaces = Vec::with_capacity(order.len());
9bd34e25bb86atagen2026-10-24 07:23 UTC483
    for room_id in order {
9bd34e25bb86atagen2026-10-24 07:23 UTC484
        let room = client.get_room(&room_id).ok_or_else(Error::room_unknown)?;
9bd34e25bb86atagen2026-10-24 07:23 UTC485
        let stored = stored_space_order(&room).await;
9bd34e25bb86atagen2026-10-24 07:23 UTC486
        let current = {
9bd34e25bb86atagen2026-10-24 07:23 UTC487
            let mut fresh = fresh.lock().expect("nothing panics holding this");
9bd34e25bb86atagen2026-10-24 07:23 UTC488
            match fresh.get(&room_id) {
9bd34e25bb86atagen2026-10-24 07:23 UTC489
                Some(written) if stored.as_ref() != Some(written) => Some(written.clone()),
9bd34e25bb86atagen2026-10-24 07:23 UTC490
                Some(_) => fresh.remove(&room_id),
9bd34e25bb86atagen2026-10-24 07:23 UTC491
                None => stored,
9bd34e25bb86atagen2026-10-24 07:23 UTC492
            }
9bd34e25bb86atagen2026-10-24 07:23 UTC493
        };
9bd34e25bb86atagen2026-10-24 07:23 UTC494
        rooms.insert(room_id.clone(), room);
9bd34e25bb86atagen2026-10-24 07:23 UTC495
        spaces.push((room_id, current));
9bd34e25bb86atagen2026-10-24 07:23 UTC496
    }
9bd34e25bb86atagen2026-10-24 07:23 UTC497
    for (room_id, order) in space_order::plan(&spaces) {
9bd34e25bb86atagen2026-10-24 07:23 UTC498
        let content = Raw::new(&serde_json::json!({ "order": order }))
9bd34e25bb86atagen2026-10-24 07:23 UTC499
            .expect("a string map always serialises")
9bd34e25bb86atagen2026-10-24 07:23 UTC500
            .cast_unchecked();
9bd34e25bb86atagen2026-10-24 07:23 UTC501
        rooms[&room_id]
9bd34e25bb86atagen2026-10-24 07:23 UTC502
            .set_account_data_raw(space_order::EVENT_TYPE.into(), content)
9bd34e25bb86atagen2026-10-24 07:23 UTC503
            .await
9bd34e25bb86atagen2026-10-24 07:23 UTC504
            .map_err(|source| Error::from_sdk("writing a space order failed", source))?;
9bd34e25bb86atagen2026-10-24 07:23 UTC505
        fresh
9bd34e25bb86atagen2026-10-24 07:23 UTC506
            .lock()
9bd34e25bb86atagen2026-10-24 07:23 UTC507
            .expect("nothing panics holding this")
9bd34e25bb86atagen2026-10-24 07:23 UTC508
            .insert(room_id, order);
9bd34e25bb86atagen2026-10-24 07:23 UTC509
    }
9bd34e25bb86atagen2026-10-24 07:23 UTC510
    Ok(())
9bd34e25bb86atagen2026-10-24 07:23 UTC511
}
9bd34e25bb86atagen2026-10-24 07:23 UTC512
9bd34e25bb86atagen2026-10-24 07:23 UTC513
/// below the cheapest of the levels a message could need, so neither plain nor encrypted
9bd34e25bb86atagen2026-10-24 07:23 UTC514
/// sends get through
9bd34e25bb86atagen2026-10-24 07:23 UTC515
async fn mute_user(
9bd34e25bb86atagen2026-10-24 07:23 UTC516
    client: &Client,
9bd34e25bb86atagen2026-10-24 07:23 UTC517
    room: &Room,
9bd34e25bb86atagen2026-10-24 07:23 UTC518
    user_id: &OwnedUserId,
9bd34e25bb86atagen2026-10-24 07:23 UTC519
    muted: bool,
9bd34e25bb86atagen2026-10-24 07:23 UTC520
) -> Result<(), Error> {
9bd34e25bb86atagen2026-10-24 07:23 UTC521
    let own_user_id = client
9bd34e25bb86atagen2026-10-24 07:23 UTC522
        .user_id()
9bd34e25bb86atagen2026-10-24 07:23 UTC523
        .ok_or_else(|| Error::new(ErrorKind::Unauthenticated, "the client is not logged in"))?;
9bd34e25bb86atagen2026-10-24 07:23 UTC524
    let mut levels = room
9bd34e25bb86atagen2026-10-24 07:23 UTC525
        .power_levels()
9bd34e25bb86atagen2026-10-24 07:23 UTC526
        .await
9bd34e25bb86atagen2026-10-24 07:23 UTC527
        .map_err(|source| Error::from_sdk("reading power levels failed", source.into()))?;
9bd34e25bb86atagen2026-10-24 07:23 UTC528
    if !levels.user_can_change_user_power_level(own_user_id, user_id) {
9bd34e25bb86atagen2026-10-24 07:23 UTC529
        return Err(Error::new(
9bd34e25bb86atagen2026-10-24 07:23 UTC530
            ErrorKind::Forbidden,
9bd34e25bb86atagen2026-10-24 07:23 UTC531
            "you can't change this user's power level",
9bd34e25bb86atagen2026-10-24 07:23 UTC532
        ));
9bd34e25bb86atagen2026-10-24 07:23 UTC533
    }
9bd34e25bb86atagen2026-10-24 07:23 UTC534
    let speaking = [
9bd34e25bb86atagen2026-10-24 07:23 UTC535
        levels.events_default,
9bd34e25bb86atagen2026-10-24 07:23 UTC536
        levels.for_message(MessageLikeEventType::RoomMessage),
9bd34e25bb86atagen2026-10-24 07:23 UTC537
        levels.for_message(MessageLikeEventType::RoomEncrypted),
9bd34e25bb86atagen2026-10-24 07:23 UTC538
    ]
9bd34e25bb86atagen2026-10-24 07:23 UTC539
    .into_iter()
9bd34e25bb86atagen2026-10-24 07:23 UTC540
    .min()
9bd34e25bb86atagen2026-10-24 07:23 UTC541
    .expect("the list isn't empty");
9bd34e25bb86atagen2026-10-24 07:23 UTC542
    let current = levels
9bd34e25bb86atagen2026-10-24 07:23 UTC543
        .users
9bd34e25bb86atagen2026-10-24 07:23 UTC544
        .get(user_id)
9bd34e25bb86atagen2026-10-24 07:23 UTC545
        .copied()
9bd34e25bb86atagen2026-10-24 07:23 UTC546
        .unwrap_or(levels.users_default);
9bd34e25bb86atagen2026-10-24 07:23 UTC547
    match (muted, current < speaking) {
9bd34e25bb86atagen2026-10-24 07:23 UTC548
        (true, true) | (false, false) => return Ok(()),
9bd34e25bb86atagen2026-10-24 07:23 UTC549
        (true, false) => {
9bd34e25bb86atagen2026-10-24 07:23 UTC550
            let level = speaking.checked_sub(Int::from(1)).ok_or_else(|| {
9bd34e25bb86atagen2026-10-24 07:23 UTC551
                Error::new(
9bd34e25bb86atagen2026-10-24 07:23 UTC552
                    ErrorKind::Invalid,
9bd34e25bb86atagen2026-10-24 07:23 UTC553
                    "there's no power level below this room's lowest",
9bd34e25bb86atagen2026-10-24 07:23 UTC554
                )
9bd34e25bb86atagen2026-10-24 07:23 UTC555
            })?;
9bd34e25bb86atagen2026-10-24 07:23 UTC556
            levels.users.insert(user_id.clone(), level);
9bd34e25bb86atagen2026-10-24 07:23 UTC557
        }
9bd34e25bb86atagen2026-10-24 07:23 UTC558
        (false, true) => {
9bd34e25bb86atagen2026-10-24 07:23 UTC559
            levels.users.remove(user_id);
9bd34e25bb86atagen2026-10-24 07:23 UTC560
        }
9bd34e25bb86atagen2026-10-24 07:23 UTC561
    }
9bd34e25bb86atagen2026-10-24 07:23 UTC562
    let content = RoomPowerLevelsEventContent::try_from(levels).map_err(|source| {
9bd34e25bb86atagen2026-10-24 07:23 UTC563
        Error::with_source(
9bd34e25bb86atagen2026-10-24 07:23 UTC564
            ErrorKind::Invalid,
9bd34e25bb86atagen2026-10-24 07:23 UTC565
            "normalising power levels failed",
9bd34e25bb86atagen2026-10-24 07:23 UTC566
            source,
9bd34e25bb86atagen2026-10-24 07:23 UTC567
        )
9bd34e25bb86atagen2026-10-24 07:23 UTC568
    })?;
9bd34e25bb86atagen2026-10-24 07:23 UTC569
    room.send_state_event(content)
9bd34e25bb86atagen2026-10-24 07:23 UTC570
        .await
9bd34e25bb86atagen2026-10-24 07:23 UTC571
        .map(drop)
9bd34e25bb86atagen2026-10-24 07:23 UTC572
        .map_err(|source| Error::from_sdk("updating power levels failed", source))
9bd34e25bb86atagen2026-10-24 07:23 UTC573
}
9bd34e25bb86atagen2026-10-24 07:23 UTC574
9bd34e25bb86atagen2026-10-24 07:23 UTC575
#[derive(Clone, Copy)]
9bd34e25bb86atagen2026-10-24 07:23 UTC576
enum ProfileField {
9bd34e25bb86atagen2026-10-24 07:23 UTC577
    DisplayName,
9bd34e25bb86atagen2026-10-24 07:23 UTC578
    Avatar,
9bd34e25bb86atagen2026-10-24 07:23 UTC579
}
9bd34e25bb86atagen2026-10-24 07:23 UTC580
9bd34e25bb86atagen2026-10-24 07:23 UTC581
/// rewrites your member event from the server's copy so membership and unknown keys survive,
9bd34e25bb86atagen2026-10-24 07:23 UTC582
/// and an earlier change this sync hasn't delivered yet isn't lost
9bd34e25bb86atagen2026-10-24 07:23 UTC583
async fn set_own_member_field(
9bd34e25bb86atagen2026-10-24 07:23 UTC584
    client: &Client,
9bd34e25bb86atagen2026-10-24 07:23 UTC585
    room: &Room,
9bd34e25bb86atagen2026-10-24 07:23 UTC586
    field: ProfileField,
9bd34e25bb86atagen2026-10-24 07:23 UTC587
    value: Option<String>,
9bd34e25bb86atagen2026-10-24 07:23 UTC588
) -> Result<(), Error> {
9bd34e25bb86atagen2026-10-24 07:23 UTC589
    let own_user_id = client
9bd34e25bb86atagen2026-10-24 07:23 UTC590
        .user_id()
9bd34e25bb86atagen2026-10-24 07:23 UTC591
        .ok_or_else(|| Error::new(ErrorKind::Unauthenticated, "the client is not logged in"))?
9bd34e25bb86atagen2026-10-24 07:23 UTC592
        .to_owned();
9bd34e25bb86atagen2026-10-24 07:23 UTC593
    let key = match field {
9bd34e25bb86atagen2026-10-24 07:23 UTC594
        ProfileField::DisplayName => "displayname",
9bd34e25bb86atagen2026-10-24 07:23 UTC595
        ProfileField::Avatar => "avatar_url",
9bd34e25bb86atagen2026-10-24 07:23 UTC596
    };
9bd34e25bb86atagen2026-10-24 07:23 UTC597
    let value = match value {
9bd34e25bb86atagen2026-10-24 07:23 UTC598
        Some(value) => Some(value),
9bd34e25bb86atagen2026-10-24 07:23 UTC599
        None => {
9bd34e25bb86atagen2026-10-24 07:23 UTC600
            let profile = client
9bd34e25bb86atagen2026-10-24 07:23 UTC601
                .account()
9bd34e25bb86atagen2026-10-24 07:23 UTC602
                .fetch_user_profile()
9bd34e25bb86atagen2026-10-24 07:23 UTC603
                .await
9bd34e25bb86atagen2026-10-24 07:23 UTC604
                .map_err(|source| Error::from_sdk("fetching the profile failed", source))?;
9bd34e25bb86atagen2026-10-24 07:23 UTC605
            let global = match field {
9bd34e25bb86atagen2026-10-24 07:23 UTC606
                ProfileField::DisplayName => profile.get_static::<DisplayName>(),
9bd34e25bb86atagen2026-10-24 07:23 UTC607
                ProfileField::Avatar => profile
9bd34e25bb86atagen2026-10-24 07:23 UTC608
                    .get_static::<AvatarUrl>()
9bd34e25bb86atagen2026-10-24 07:23 UTC609
                    .map(|avatar| avatar.map(String::from)),
9bd34e25bb86atagen2026-10-24 07:23 UTC610
            };
9bd34e25bb86atagen2026-10-24 07:23 UTC611
            global.map_err(|source| {
9bd34e25bb86atagen2026-10-24 07:23 UTC612
                Error::with_source(
9bd34e25bb86atagen2026-10-24 07:23 UTC613
                    ErrorKind::Server,
9bd34e25bb86atagen2026-10-24 07:23 UTC614
                    "the server sent a malformed profile",
9bd34e25bb86atagen2026-10-24 07:23 UTC615
                    source,
9bd34e25bb86atagen2026-10-24 07:23 UTC616
                )
9bd34e25bb86atagen2026-10-24 07:23 UTC617
            })?
9bd34e25bb86atagen2026-10-24 07:23 UTC618
        }
9bd34e25bb86atagen2026-10-24 07:23 UTC619
    };
9bd34e25bb86atagen2026-10-24 07:23 UTC620
    let request = get_state_event_for_key::v3::Request::new(
9bd34e25bb86atagen2026-10-24 07:23 UTC621
        room.room_id().to_owned(),
9bd34e25bb86atagen2026-10-24 07:23 UTC622
        StateEventType::RoomMember,
9bd34e25bb86atagen2026-10-24 07:23 UTC623
        own_user_id.to_string(),
9bd34e25bb86atagen2026-10-24 07:23 UTC624
    );
9bd34e25bb86atagen2026-10-24 07:23 UTC625
    let response = client
9bd34e25bb86atagen2026-10-24 07:23 UTC626
        .send(request)
9bd34e25bb86atagen2026-10-24 07:23 UTC627
        .await
9bd34e25bb86atagen2026-10-24 07:23 UTC628
        .map_err(|source| Error::from_http("reading your member event failed", source))?;
9bd34e25bb86atagen2026-10-24 07:23 UTC629
    let mut content: JsonObject =
9bd34e25bb86atagen2026-10-24 07:23 UTC630
        serde_json::from_str(response.event_or_content.get()).map_err(|source| {
9bd34e25bb86atagen2026-10-24 07:23 UTC631
            Error::with_source(ErrorKind::Invalid, "your member event is malformed", source)
9bd34e25bb86atagen2026-10-24 07:23 UTC632
        })?;
9bd34e25bb86atagen2026-10-24 07:23 UTC633
    match value {
9bd34e25bb86atagen2026-10-24 07:23 UTC634
        Some(value) => content.insert(key.to_owned(), JsonValue::String(value)),
9bd34e25bb86atagen2026-10-24 07:23 UTC635
        None => content.remove(key),
9bd34e25bb86atagen2026-10-24 07:23 UTC636
    };
9bd34e25bb86atagen2026-10-24 07:23 UTC637
    room.send_state_event_raw(
9bd34e25bb86atagen2026-10-24 07:23 UTC638
        "m.room.member",
9bd34e25bb86atagen2026-10-24 07:23 UTC639
        own_user_id.as_str(),
9bd34e25bb86atagen2026-10-24 07:23 UTC640
        JsonValue::Object(content),
9bd34e25bb86atagen2026-10-24 07:23 UTC641
    )
9bd34e25bb86atagen2026-10-24 07:23 UTC642
    .await
9bd34e25bb86atagen2026-10-24 07:23 UTC643
    .map(drop)
9bd34e25bb86atagen2026-10-24 07:23 UTC644
    .map_err(|source| Error::from_sdk("updating your member event failed", source))
9bd34e25bb86atagen2026-10-24 07:23 UTC645
}
9bd34e25bb86atagen2026-10-24 07:23 UTC646
31ce2453c82fatagen2026-09-24 13:07 UTC647
fn done<T>(_: T) -> CommandOutput {
31ce2453c82fatagen2026-09-24 13:07 UTC648
    CommandOutput::Done
31ce2453c82fatagen2026-09-24 13:07 UTC649
}
31ce2453c82fatagen2026-09-24 13:07 UTC650
31ce2453c82fatagen2026-09-24 13:07 UTC651
fn power_level(value: i64) -> Result<Int, Error> {
31ce2453c82fatagen2026-09-24 13:07 UTC652
    value.try_into().map_err(|source| {
31ce2453c82fatagen2026-09-24 13:07 UTC653
        Error::with_source(
31ce2453c82fatagen2026-09-24 13:07 UTC654
            ErrorKind::Invalid,
31ce2453c82fatagen2026-09-24 13:07 UTC655
            "power level is outside the Matrix integer range",
31ce2453c82fatagen2026-09-24 13:07 UTC656
            source,
31ce2453c82fatagen2026-09-24 13:07 UTC657
        )
31ce2453c82fatagen2026-09-24 13:07 UTC658
    })
31ce2453c82fatagen2026-09-24 13:07 UTC659
}
31ce2453c82fatagen2026-09-24 13:07 UTC660
31ce2453c82fatagen2026-09-24 13:07 UTC661
fn create_room_request(options: CreateRoomOptions) -> CreateRoomRequest {
31ce2453c82fatagen2026-09-24 13:07 UTC662
    let mut request = CreateRoomRequest::new();
31ce2453c82fatagen2026-09-24 13:07 UTC663
    request.name = options.name;
31ce2453c82fatagen2026-09-24 13:07 UTC664
    request.topic = options.topic;
31ce2453c82fatagen2026-09-24 13:07 UTC665
    request.room_alias_name = options.alias_localpart;
31ce2453c82fatagen2026-09-24 13:07 UTC666
    request.invite = options.invite;
31ce2453c82fatagen2026-09-24 13:07 UTC667
    request.is_direct = options.direct;
31ce2453c82fatagen2026-09-24 13:07 UTC668
    request.visibility = match options.visibility {
31ce2453c82fatagen2026-09-24 13:07 UTC669
        RoomVisibility::Private => SdkVisibility::Private,
31ce2453c82fatagen2026-09-24 13:07 UTC670
        RoomVisibility::Public => SdkVisibility::Public,
31ce2453c82fatagen2026-09-24 13:07 UTC671
    };
31ce2453c82fatagen2026-09-24 13:07 UTC672
    request.preset = options.preset.map(|preset| match preset {
31ce2453c82fatagen2026-09-24 13:07 UTC673
        RoomPreset::PrivateChat => SdkPreset::PrivateChat,
31ce2453c82fatagen2026-09-24 13:07 UTC674
        RoomPreset::TrustedPrivateChat => SdkPreset::TrustedPrivateChat,
31ce2453c82fatagen2026-09-24 13:07 UTC675
        RoomPreset::PublicChat => SdkPreset::PublicChat,
31ce2453c82fatagen2026-09-24 13:07 UTC676
    });
31ce2453c82fatagen2026-09-24 13:07 UTC677
    request
31ce2453c82fatagen2026-09-24 13:07 UTC678
}