/* This file is part of jellything (https://codeberg.org/metamuffin/jellything) which is licensed under the GNU Affero General Public License (version 3); see /COPYING. Copyright (C) 2023 metamuffin */ 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, sessions: RwLock>>, } 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::>(); 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> { 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) } } }