aboutsummaryrefslogtreecommitdiff
path: root/server/src/federation.rs
blob: 578261be5470f6f497ac6d74bf993a8bd78b718a (plain)
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
use crate::CONF;
use anyhow::anyhow;
use jellyclient::{Instance, Session};
use std::{collections::HashMap, sync::Arc, time::Duration};
use tokio::sync::RwLock;

pub struct Federation {
    instances: HashMap<String, Instance>,
    sessions: RwLock<HashMap<String, Arc<Session>>>,
}

impl Federation {
    pub fn initialize() -> Self {
        let instances = CONF
            .remote_credentials
            .iter()
            .map(|(k, (_, _, tls))| (k.to_owned(), Instance::new(k.to_owned(), *tls)))
            .collect::<HashMap<_, _>>();

        Self {
            instances,
            sessions: Default::default(),
        }
    }

    pub fn get_instance(&self, host: &String) -> anyhow::Result<&Instance> {
        Ok(self
            .instances
            .get(host)
            .ok_or(anyhow!("unknown instance"))?)
    }
    pub async fn get_session(&self, host: &String) -> anyhow::Result<Arc<Session>> {
        let mut w = self.sessions.write().await;
        if let Some(s) = w.get(host) {
            Ok(s.to_owned())
        } else {
            let (username, password, _) = CONF
                .remote_credentials
                .get(host)
                .ok_or(anyhow!("no credentials of the remote server"))?;
            let s = Arc::new(
                self.get_instance(host)?
                    .to_owned()
                    .login(
                        username.to_owned(),
                        password.to_owned(),
                        Duration::from_secs(60 * 60 * 24 * 356),
                    )
                    .await?,
            );
            w.insert(host.to_owned(), s.clone());
            Ok(s)
        }
    }
}