atagen

macltok

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