acter/api/
account.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
use acter_core::events::settings::{ActerUserAppSettingsContent, APP_USER_SETTINGS};
use anyhow::{bail, Context, Result};
use futures::stream::StreamExt;
use matrix_sdk::Account as SdkAccount;
use matrix_sdk_base::{
    media::MediaRequestParameters,
    ruma::{
        api::client::uiaa::{AuthData, Password},
        assign,
        events::{ignored_user_list::IgnoredUserListEventContent, room::MediaSource},
        OwnedMxcUri, OwnedUserId, UserId,
    },
    StateStoreDataKey, StateStoreDataValue,
};
use std::{ops::Deref, path::PathBuf};
use tokio::sync::broadcast::Receiver;
use tokio_stream::{wrappers::BroadcastStream, Stream};

use super::{
    common::{clearify_error, OptionBuffer, OptionString, ThumbnailSize},
    RUNTIME,
};
use crate::{ActerUserAppSettings, Client};

mod three_pid;

pub use three_pid::{ExternalId, ThreePidEmailTokenResponse};

#[derive(Clone, Debug)]
pub struct Account {
    pub(crate) account: SdkAccount,
    client: Client,
    user_id: OwnedUserId,
}

impl Deref for Account {
    type Target = SdkAccount;
    fn deref(&self) -> &SdkAccount {
        &self.account
    }
}

impl Account {
    pub fn new(account: SdkAccount, user_id: OwnedUserId, client: Client) -> Self {
        Account {
            account,
            client,
            user_id,
        }
    }

    pub fn user_id(&self) -> OwnedUserId {
        self.user_id.clone()
    }

    pub async fn display_name(&self) -> Result<OptionString> {
        let account = self.account.clone();
        RUNTIME
            .spawn(async move {
                let name = account.get_display_name().await?;
                Ok(OptionString::new(name))
            })
            .await?
    }

    pub async fn set_display_name(&self, new_name: String) -> Result<bool> {
        let client = self.client.deref().clone();
        let account = self.account.clone();
        RUNTIME
            .spawn(async move {
                let capabilities = client.get_capabilities().await?;
                if !capabilities.set_displayname.enabled {
                    bail!("Server doesn’t support change of display name");
                }
                let name = if new_name.is_empty() {
                    None
                } else {
                    Some(new_name.as_str())
                };
                account.set_display_name(name).await?;
                Ok(true)
            })
            .await?
    }

    pub async fn avatar(&self, thumb_size: Option<Box<ThumbnailSize>>) -> Result<OptionBuffer> {
        let account = self.account.clone();
        let client = self.client.deref().clone();
        RUNTIME
            .spawn(async move {
                let source = match account.get_cached_avatar_url().await? {
                    Some(url) => MediaSource::Plain(url),
                    None => match account.get_avatar_url().await? {
                        Some(e) => MediaSource::Plain(e),
                        None => return Ok(OptionBuffer::new(None)),
                    },
                };
                let format = ThumbnailSize::parse_into_media_format(thumb_size);
                let request = MediaRequestParameters { source, format };
                Ok(OptionBuffer::new(Some(
                    client.media().get_media_content(&request, true).await?,
                )))
            })
            .await?
    }

    pub async fn upload_avatar(&self, uri: String) -> Result<OwnedMxcUri> {
        let client = self.client.deref().clone();
        let account = self.account.clone();
        let path = PathBuf::from(uri);
        let user_id = self.user_id();
        RUNTIME
            .spawn(async move {
                let capabilities = client.get_capabilities().await?;
                if !capabilities.set_avatar_url.enabled {
                    bail!("Server doesn’t support change of avatar url");
                }
                let guess = mime_guess::from_path(path.clone());
                let content_type = guess.first().context("don’t know mime type")?;
                let data = std::fs::read(path)?;
                let new_url = account.upload_avatar(&content_type, data).await?;

                // set the internal cached key so the next fetch properly updates this
                client
                    .store()
                    .set_kv_data(
                        StateStoreDataKey::UserAvatarUrl(&user_id),
                        StateStoreDataValue::UserAvatarUrl(new_url.clone()),
                    )
                    .await;
                Ok(new_url)
            })
            .await?
    }

    pub async fn ignore_user(&self, user_id: String) -> Result<bool> {
        let user_id = UserId::parse(user_id)?;
        let account = self.account.clone();

        RUNTIME
            .spawn(async move {
                account.ignore_user(&user_id).await?;
                Ok(true)
            })
            .await?
    }

    pub async fn unignore_user(&self, user_id: String) -> Result<bool> {
        let user_id = UserId::parse(user_id)?;
        let account = self.account.clone();

        RUNTIME
            .spawn(async move {
                account.unignore_user(&user_id).await?;
                Ok(true)
            })
            .await?
    }

    pub async fn ignored_users(&self) -> Result<Vec<OwnedUserId>> {
        let account = self.account.clone();

        RUNTIME
            .spawn(async move {
                let content = account
                    .account_data::<IgnoredUserListEventContent>()
                    .await?
                    .context("Ignored users not found")?
                    .deserialize()?;
                Ok(content.ignored_users.keys().cloned().collect())
            })
            .await?
    }

    pub async fn change_password(&self, old_val: String, new_val: String) -> Result<bool> {
        let client = self.client.deref().clone();
        let account = self.account.clone();
        let user_id = self.user_id.clone();

        RUNTIME
            .spawn(async move {
                let capabilities = client.get_capabilities().await?;
                if !capabilities.change_password.enabled {
                    bail!("Server doesn’t support password change");
                }
                if let Err(e) = account.change_password(&new_val, None).await {
                    let Some(inf) = e.as_uiaa_response() else {
                        return Err(clearify_error(e));
                    };
                    let pswd = assign!(Password::new(user_id.into(), old_val), {
                        session: inf.session.clone(),
                    });
                    let auth_data = AuthData::Password(pswd);
                    account
                        .change_password(&new_val, Some(auth_data))
                        .await
                        .map_err(clearify_error)?;
                }
                Ok(true)
            })
            .await?
    }

    pub async fn deactivate(&self, password: String) -> Result<bool> {
        let account = self.account.clone();
        let user_id = self.user_id.clone();

        RUNTIME
            .spawn(async move {
                if let Err(e) = account.deactivate(None, None, false).await {
                    let Some(inf) = e.as_uiaa_response() else {
                        return Err(clearify_error(e));
                    };
                    let pswd = assign!(Password::new(user_id.into(), password), {
                        session: inf.session.clone(),
                    });
                    let auth_data = AuthData::Password(pswd);
                    account.deactivate(None, Some(auth_data), false).await?;
                    // FIXME: remove local data, too!
                }
                Ok(true)
            })
            .await?
    }

    pub async fn acter_app_settings(&self) -> Result<ActerUserAppSettings> {
        let account = self.account.clone();

        RUNTIME
            .spawn(async move {
                let inner = if let Some(raw) = account
                    .account_data::<ActerUserAppSettingsContent>()
                    .await?
                {
                    raw.deserialize()?
                } else {
                    ActerUserAppSettingsContent::default()
                };

                Ok(ActerUserAppSettings::new(account, inner))
            })
            .await?
    }

    pub fn subscribe_app_settings_stream(&self) -> impl Stream<Item = bool> {
        BroadcastStream::new(self.subscribe()).map(|_| true)
    }

    pub fn subscribe(&self) -> Receiver<()> {
        self.client.subscribe(APP_USER_SETTINGS.clone())
    }
}