~boringcactus/gemifedi

ref: 360f9f18c0b0b13a20fb29b73161993f85e26490 gemifedi/src/mastodon_util.rs -rw-r--r-- 2.0 KiB
360f9f18 — Melody Horn add posting 1 year, 2 months ago
                                                                                
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
use std::{
    fs::{self, create_dir_all},
    path::PathBuf,
};

use elefren::{
    prelude::*,
    registration::Registered,
    scopes,
};
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
struct AppInstall {
    parts: (String, String, String, String, Scopes, bool),
}

pub fn scopes_needed() -> Scopes {
    Scopes::read(scopes::Read::Statuses)
        | Scopes::read(scopes::Read::Notifications)
        | Scopes::write(scopes::Write::Statuses)
        | Scopes::write(scopes::Write::Notifications)
        | Scopes::write(scopes::Write::Favourites)
}

pub fn get_app_install(domain: &str) -> Registered<elefren::http_send::HttpSender> {
    let mut data_path = PathBuf::from("data");
    data_path.push("domains");
    create_dir_all(&data_path).unwrap();
    data_path.push(format!("{}.toml", domain));

    let scopes_needed = scopes_needed();

    if data_path.exists() {
        let file_data = fs::read(&data_path).unwrap();
        let install: AppInstall = toml::from_slice(file_data.as_slice()).unwrap();
        let (base, client_id, client_secret, redirect, scopes, force_login) = install.parts;
        dbg!(&scopes, &scopes_needed);
        if scopes != scopes_needed {
            // we don't have the scopes we need, so re-register on this domain
            let _ = fs::remove_file(data_path);
            return get_app_install(domain);
        }
        Registered::from_parts(&base, &client_id, &client_secret, &redirect, scopes, force_login)
    } else {
        let registered = Registration::new(format!("https://{}", domain))
            .client_name(concat!("gemifedi v", env!("CARGO_PKG_VERSION")))
            .website("https://git.sr.ht/~boringcactus/gemifedi")
            .scopes(scopes_needed)
            .build()
            .unwrap();
        let parts = registered.clone().into_parts();
        let install = AppInstall { parts };
        let file_data = toml::to_string(&install).unwrap();
        fs::write(data_path, file_data).unwrap();
        registered
    }
}