pleroma groups!!!!!! try it -> https://piggo.space/hob
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
group-actor/src/store/mod.rs

231 lines
7.3 KiB

use std::path::{Path, PathBuf};
use std::sync::Arc;
use elefren::{scopes, FediClient, Registration, Scopes};
use futures::StreamExt;
use tokio::sync::RwLock;
use data::{GroupConfig};
use crate::error::GroupError;
use crate::group_handler::GroupHandle;
use std::time::Duration;
use crate::store::data::CommonConfig;
pub(crate) mod data;
#[derive(Debug, Default)]
pub struct ConfigStore {
store_path: PathBuf,
config: Arc<CommonConfig>,
}
#[derive(Debug)]
pub struct NewGroupOptions {
pub server: String,
pub acct: String,
}
#[derive(Debug)]
pub struct StoreOptions {
pub store_dir: String,
}
impl ConfigStore {
/// Create a new instance of the store.
/// If a path is given, it will try to load the content from a file.
pub async fn load_from_fs(options: StoreOptions) -> Result<Arc<Self>, GroupError> {
let given_path: &Path = options.store_dir.as_ref();
let mut common_file : Option<PathBuf> = None;
let base_dir : PathBuf;
if given_path.is_file() {
if given_path.extension().unwrap_or_default().to_string_lossy() == "json" {
// this is a groups.json file
common_file = Some(given_path.to_owned());
base_dir = given_path.parent().ok_or_else(|| GroupError::BadConfig("no parent dir".into()))?.to_owned();
} else {
return Err(GroupError::BadConfig("bad config file, should be JSON".into()));
}
} else if given_path.is_dir() {
let cf = given_path.join("groups.json");
if cf.is_file() {
common_file = Some(cf);
}
base_dir = given_path.to_owned();
} else {
return Err(GroupError::BadConfig("bad config file/dir".into()));
}
if !base_dir.is_dir() {
return Err(GroupError::BadConfig("base dir does not exist".into()));
}
let config : CommonConfig = if let Some(cf) = &common_file {
let f = tokio::fs::read(&cf).await?;
serde_json::from_slice(&f)?
} else {
CommonConfig::default()
};
Ok(Arc::new(Self {
store_path: base_dir.to_owned(),
config: Arc::new(config),
}))
}
/// Spawn a new group
pub async fn auth_new_group(self: &Arc<Self>, opts: NewGroupOptions) -> Result<GroupHandle, GroupError> {
let registration = Registration::new(&opts.server)
.client_name("group-actor")
.force_login(true)
.scopes(make_scopes())
.build()
.await?;
println!("--- Authenticating NEW bot user @{} ---", opts.acct);
let client = elefren::helpers::cli::authenticate(registration).await?;
let appdata = client.data.clone();
let group_dir = self.store_path.join(&opts.acct);
let data = GroupConfig::from_appdata(opts.acct.clone(), appdata, group_dir).await?;
// save & persist
let group_account = match client.verify_credentials().await {
Ok(account) => {
info!(
"Group account verified: @{}, \"{}\"",
account.acct, account.display_name
);
account
}
Err(e) => {
error!("Group @{} auth error: {}", opts.acct, e);
return Err(e.into());
}
};
Ok(GroupHandle {
group_account,
client,
config: data,
common_config: self.config.clone(),
})
}
/// Re-auth an existing group
pub async fn reauth_group(self: &Arc<Self>, acct: &str) -> Result<GroupHandle, GroupError> {
let group_dir = self.store_path.join(&acct);
let mut config = GroupConfig::from_dir(group_dir).await?;
println!("--- Re-authenticating bot user @{} ---", acct);
let registration = Registration::new(config.get_appdata().base.to_string())
.client_name("group-actor")
.force_login(true)
.scopes(make_scopes())
.build()
.await?;
let client = elefren::helpers::cli::authenticate(registration).await?;
println!("Auth complete");
let appdata = client.data.clone();
config.set_appdata(appdata);
config.save_if_needed(true).await?;
let group_account = match client.verify_credentials().await {
Ok(account) => {
info!(
"Group account verified: @{}, \"{}\"",
account.acct, account.display_name
);
account
}
Err(e) => {
error!("Group @{} auth error: {}", acct, e);
return Err(e.into());
}
};
Ok(GroupHandle {
group_account,
client,
config,
common_config: self.config.clone(),
})
}
/// Spawn existing group using saved creds
pub async fn spawn_groups(self: Arc<Self>) -> Result<Vec<GroupHandle>, GroupError> {
let dirs = std::fs::read_dir(&self.store_path.join("groups.d"))?;
// Connect in parallel
Ok(futures::stream::iter(dirs)
.map(|entry_maybe : Result<std::fs::DirEntry, std::io::Error>| async {
match entry_maybe {
Ok(entry) => {
let mut gc = GroupConfig::from_dir(entry.path())
.await.ok()?;
if !gc.is_enabled() {
debug!("Group @{} is DISABLED", gc.get_acct());
return None;
}
debug!("Connecting to @{}", gc.get_acct());
let client = FediClient::from(gc.get_appdata().clone());
let my_account = match client.verify_credentials().await {
Ok(account) => {
info!(
"Group account verified: @{}, \"{}\"",
account.acct, account.display_name
);
account
}
Err(e) => {
error!("Group @{} auth error: {}", gc.get_acct(), e);
return None;
}
};
Some(GroupHandle {
group_account: my_account,
client,
config: gc,
common_config: self.config.clone(),
})
}
Err(e) => {
error!("{}", e);
None
}
}
})
.buffer_unordered(8)
.collect::<Vec<_>>()
.await
.into_iter()
.flatten()
.collect())
}
pub async fn group_exists(&self, acct : &str) -> bool {
self.store_path.join(acct)
.join("config.json")
.is_file()
}
}
fn make_scopes() -> Scopes {
Scopes::read_all()
| Scopes::write(scopes::Write::Statuses)
| Scopes::write(scopes::Write::Media)
| Scopes::write(scopes::Write::Follows)
}