acter/api/settings/
space.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
pub use acter_core::events::settings::{
    ActerAppSettingsContent, EventsSettings, NewsSettings, PinsSettings, SimpleOnOffSetting,
    SimpleOnOffSettingBuilder, SimpleSettingWithTurnOff, SimpleSettingWithTurnOffBuilder,
    StoriesSettings, TasksSettings,
};
use acter_core::events::{
    attachments::AttachmentEventContent,
    calendar::CalendarEventEventContent,
    comments::CommentEventContent,
    news::NewsEntryEventContent,
    pins::PinEventContent,
    rsvp::RsvpEventContent,
    settings::ActerAppSettingsContentBuilder,
    stories::StoryEventContent,
    tasks::{TaskEventContent, TaskListEventContent},
};
use anyhow::{bail, Context, Result};
use matrix_sdk_base::{
    deserialized_responses::SyncOrStrippedState,
    ruma::{
        events::{
            room::power_levels::{
                RoomPowerLevels as RumaRoomPowerLevels, RoomPowerLevelsEventContent,
            },
            StateEventType, StaticEventContent, SyncStateEvent, TimelineEventType,
        },
        Int,
    },
};
use std::{collections::btree_map, ops::Deref};

use crate::{Room, RUNTIME};

#[derive(Clone)]
pub struct ActerAppSettingsBuilder {
    inner: ActerAppSettingsContentBuilder,
}

impl From<ActerAppSettingsContentBuilder> for ActerAppSettingsBuilder {
    fn from(inner: ActerAppSettingsContentBuilder) -> Self {
        ActerAppSettingsBuilder { inner }
    }
}
impl ActerAppSettingsBuilder {
    pub fn news(&mut self, value: Option<Box<SimpleSettingWithTurnOff>>) {
        self.inner.news(value.map(|i| *i));
    }
    pub fn stories(&mut self, value: Option<Box<StoriesSettings>>) {
        self.inner.stories(value.map(|i| *i));
    }
    pub fn pins(&mut self, value: Option<Box<SimpleSettingWithTurnOff>>) {
        self.inner.pins(value.map(|i| *i));
    }
    pub fn events(&mut self, value: Option<Box<SimpleSettingWithTurnOff>>) {
        self.inner.events(value.map(|i| *i));
    }
    pub fn tasks(&mut self, value: Option<Box<TasksSettings>>) {
        self.inner.tasks(value.map(|i| *i));
    }
}

pub struct RoomPowerLevels {
    inner: RumaRoomPowerLevels,
}

impl RoomPowerLevels {
    fn get_for_key(&self, key: TimelineEventType) -> Option<i64> {
        self.inner.events.get(&key).map(|i| (*i).into())
    }
    pub fn news(&self) -> Option<i64> {
        self.get_for_key(<NewsEntryEventContent as StaticEventContent>::TYPE.into())
    }
    pub fn news_key(&self) -> String {
        <NewsEntryEventContent as StaticEventContent>::TYPE.into()
    }
    pub fn stories(&self) -> Option<i64> {
        self.get_for_key(<StoryEventContent as StaticEventContent>::TYPE.into())
    }
    pub fn stories_key(&self) -> String {
        <StoryEventContent as StaticEventContent>::TYPE.into()
    }
    pub fn events(&self) -> Option<i64> {
        self.get_for_key(<CalendarEventEventContent as StaticEventContent>::TYPE.into())
    }
    pub fn events_key(&self) -> String {
        <CalendarEventEventContent as StaticEventContent>::TYPE.into()
    }
    pub fn task_lists(&self) -> Option<i64> {
        self.get_for_key(<TaskListEventContent as StaticEventContent>::TYPE.into())
    }
    pub fn task_lists_key(&self) -> String {
        <TaskListEventContent as StaticEventContent>::TYPE.into()
    }
    pub fn tasks(&self) -> Option<i64> {
        self.get_for_key(<TaskEventContent as StaticEventContent>::TYPE.into())
    }
    pub fn tasks_key(&self) -> String {
        <TaskEventContent as StaticEventContent>::TYPE.into()
    }
    pub fn pins(&self) -> Option<i64> {
        self.get_for_key(<PinEventContent as StaticEventContent>::TYPE.into())
    }
    pub fn pins_key(&self) -> String {
        <PinEventContent as StaticEventContent>::TYPE.into()
    }
    pub fn comments(&self) -> Option<i64> {
        self.get_for_key(<CommentEventContent as StaticEventContent>::TYPE.into())
    }
    pub fn comments_key(&self) -> String {
        <CommentEventContent as StaticEventContent>::TYPE.into()
    }
    pub fn attachments(&self) -> Option<i64> {
        self.get_for_key(<AttachmentEventContent as StaticEventContent>::TYPE.into())
    }
    pub fn attachments_key(&self) -> String {
        <AttachmentEventContent as StaticEventContent>::TYPE.into()
    }
    pub fn rsvp(&self) -> Option<i64> {
        self.get_for_key(<RsvpEventContent as StaticEventContent>::TYPE.into())
    }
    pub fn rsvp_key(&self) -> String {
        <RsvpEventContent as StaticEventContent>::TYPE.into()
    }
    pub fn events_default(&self) -> i64 {
        self.inner.events_default.into()
    }
    pub fn users_default(&self) -> i64 {
        self.inner.users_default.into()
    }
    pub fn max_power_level(&self) -> i64 {
        self.inner.max().into()
    }
    pub fn kick(&self) -> i64 {
        self.inner.kick.into()
    }
    pub fn ban(&self) -> i64 {
        self.inner.ban.into()
    }
    pub fn invite(&self) -> i64 {
        self.inner.invite.into()
    }
    pub fn redact(&self) -> i64 {
        self.inner.redact.into()
    }
}

#[derive(Clone)]
pub struct ActerAppSettings {
    inner: ActerAppSettingsContent,
}

impl Deref for ActerAppSettings {
    type Target = ActerAppSettingsContent;
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl ActerAppSettings {
    pub fn update_builder(&self) -> ActerAppSettingsBuilder {
        ActerAppSettingsBuilder {
            inner: self.inner.updater(),
        }
    }
}

impl Room {
    pub async fn app_settings(&self) -> Result<ActerAppSettings> {
        Ok(ActerAppSettings {
            inner: self.app_settings_content().await?,
        })
    }

    pub async fn power_levels(&self) -> Result<RoomPowerLevels> {
        Ok(RoomPowerLevels {
            inner: self.power_levels_content().await?,
        })
    }

    pub(crate) async fn power_levels_content(&self) -> Result<RumaRoomPowerLevels> {
        let room = self.room.clone();
        RUNTIME
            .spawn(async move {
                let content = room
                    .get_state_event_static::<RoomPowerLevelsEventContent>()
                    .await?
                    .context("Power levels not set up")?
                    .deserialize()?;
                Ok(content.power_levels())
            })
            .await?
    }

    pub async fn update_regular_power_levels(
        &self,
        name: String,
        power_level: i32,
    ) -> Result<bool> {
        if !self.is_joined() {
            bail!("Unable to update a space you aren’t part of");
        }
        let mut current_power_levels = self.power_levels_content().await?;

        match name.to_lowercase().as_str() {
            "events_default" => {
                current_power_levels.events_default = Int::from(power_level);
            }
            "ban" => {
                current_power_levels.ban = Int::from(power_level);
            }
            "kick" => {
                current_power_levels.kick = Int::from(power_level);
            }
            "redact" => {
                current_power_levels.redact = Int::from(power_level);
            }
            "invite" => {
                current_power_levels.invite = Int::from(power_level);
            }
            "state_default" => {
                current_power_levels.state_default = Int::from(power_level);
            }
            _ => {
                bail!("Power level {name} unknown");
            }
        }
        self.update_power_levels(current_power_levels).await
    }

    pub async fn update_feature_power_levels(
        &self,
        name: String,
        power_level: Option<i32>,
    ) -> Result<bool> {
        if !self.is_joined() {
            bail!("Unable to update a space you aren’t part of");
        }
        let mut current_power_levels = self.power_levels_content().await?;
        let mut updated = false;
        match current_power_levels.events.entry(name.into()) {
            btree_map::Entry::Vacant(e) => {
                if let Some(p) = power_level {
                    e.insert(Int::from(p));
                    updated = true;
                }
            }
            btree_map::Entry::Occupied(mut e) => {
                if let Some(p) = power_level {
                    e.insert(Int::from(p));
                    updated = true;
                } else {
                    e.remove_entry();
                    updated = true;
                }
            }
        }

        if !updated {
            return Ok(false);
        }
        self.update_power_levels(current_power_levels).await
    }

    async fn update_power_levels(&self, current_power_levels: RumaRoomPowerLevels) -> Result<bool> {
        if !self
            .get_my_membership()
            .await?
            .can(crate::MemberPermission::CanUpdatePowerLevels)
        {
            bail!("No permissions to change the power levels");
        }

        let room = self.room.clone();
        let my_id = self.user_id()?;

        RUNTIME
            .spawn(async move {
                let permitted = room
                    .can_user_send_state(&my_id, StateEventType::RoomPowerLevels)
                    .await?;
                if !permitted {
                    bail!("No permissions to change power levels in this room");
                }
                let response = room
                    .send_state_event(RoomPowerLevelsEventContent::from(current_power_levels))
                    .await?;
                Ok(true)
            })
            .await?
    }

    pub(crate) async fn app_settings_content(&self) -> Result<ActerAppSettingsContent> {
        let room = self.room.clone();
        RUNTIME
            .spawn(async move {
                if let Some(a) = room
                    .get_state_event_static::<ActerAppSettingsContent>()
                    .await?
                {
                    if let Ok(SyncOrStrippedState::Sync(SyncStateEvent::Original(inner))) =
                        a.deserialize()
                    {
                        return Ok(inner.content);
                    }
                }
                Ok(ActerAppSettingsContent::default()) // all other cases we fall back to default
            })
            .await?
    }

    pub async fn update_app_settings(
        &self,
        new_settings: Box<ActerAppSettingsBuilder>,
    ) -> Result<String> {
        let actual_settings = new_settings.inner.build()?;

        if !self
            .get_my_membership()
            .await?
            .can(crate::MemberPermission::CanChangeAppSettings)
        {
            bail!("No permissions to change the app settings");
        }

        if !self.is_joined() {
            bail!("Unable to update a space you aren’t part of");
        }
        let room = self.room.clone();

        RUNTIME
            .spawn(async move {
                let response = room.send_state_event(actual_settings).await?;
                Ok(response.event_id.to_string())
            })
            .await?
    }
}