wip translation system

This commit is contained in:
2021-10-06 01:09:20 +02:00
parent 881411ebd3
commit bd47a004bf
9 changed files with 221 additions and 97 deletions
+6
View File
@@ -1,3 +1,6 @@
use std::collections::HashMap;
use crate::tr::TranslationTable;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct CommonConfig {
@@ -21,6 +24,8 @@ pub struct CommonConfig {
/// Time after which a socket is always closed, even if seemingly alive.
/// This is a work-around for servers that stop sending notifs after a while.
pub socket_retire_time_s: f64,
#[serde(skip)]
pub tr : HashMap<String, TranslationTable>,
}
impl Default for CommonConfig {
@@ -34,6 +39,7 @@ impl Default for CommonConfig {
delay_reopen_error_s: 5.0,
socket_alive_timeout_s: 30.0,
socket_retire_time_s: 120.0,
tr: Default::default(),
}
}
}
+7
View File
@@ -13,6 +13,8 @@ struct FixedConfig {
acct: String,
/// elefren data
appdata: AppData,
/// configured locale to use
locale: String,
/// Server's character limit
character_limit: usize,
#[serde(skip)]
@@ -73,6 +75,7 @@ impl Default for FixedConfig {
Self {
enabled: true,
acct: "".to_string(),
locale: "en".to_string(),
appdata: AppData {
base: Default::default(),
client_id: Default::default(),
@@ -365,6 +368,10 @@ impl GroupConfig {
&self.config.appdata
}
pub(crate) fn get_locale(&self) -> &str {
&self.config.locale
}
pub(crate) fn set_appdata(&mut self, appdata: AppData) {
if self.config.appdata != appdata {
self.config.mark_dirty();
+60 -26
View File
@@ -11,12 +11,14 @@ pub mod common_config;
pub mod group_config;
pub use common_config::CommonConfig;
pub use group_config::GroupConfig;
use crate::tr::TranslationTable;
#[derive(Debug, Default)]
pub struct ConfigStore {
store_path: PathBuf,
groups_path: PathBuf,
config: Arc<CommonConfig>,
locales_path: PathBuf,
config: CommonConfig,
}
#[derive(Debug)]
@@ -33,7 +35,7 @@ pub struct StoreOptions {
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> {
pub async fn load_from_fs(options: StoreOptions) -> Result<Self, GroupError> {
let given_path: &Path = options.store_dir.as_ref();
let mut common_file: Option<PathBuf> = None;
@@ -74,21 +76,24 @@ impl ConfigStore {
debug!("Using common config:\n{:#?}", config);
let groups_path = base_dir.join("groups.d");
let groups_path = base_dir.join("groups");
if !groups_path.exists() {
debug!("Creating groups directory");
tokio::fs::create_dir_all(&groups_path).await?;
}
Ok(Arc::new(Self {
let locales_path = base_dir.join("locales");
Ok(Self {
store_path: base_dir.to_owned(),
groups_path,
config: Arc::new(config),
}))
locales_path,
config,
})
}
/// Spawn a new group
pub async fn auth_new_group(self: &Arc<Self>, opts: NewGroupOptions) -> Result<GroupHandle, GroupError> {
pub async fn auth_new_group(&self, opts: NewGroupOptions) -> Result<(), GroupError> {
let registration = Registration::new(&opts.server)
.client_name("group-actor")
.force_login(true)
@@ -106,13 +111,12 @@ impl ConfigStore {
// save & persist
let group_account = match client.verify_credentials().await {
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);
@@ -120,17 +124,11 @@ impl ConfigStore {
}
};
Ok(GroupHandle {
group_account,
client,
config: data,
cc: self.config.clone(),
internal: GroupInternal::default(),
})
Ok(())
}
/// Re-auth an existing group
pub async fn reauth_group(self: &Arc<Self>, acct: &str) -> Result<GroupHandle, GroupError> {
pub async fn reauth_group(&self, acct: &str) -> Result<(), GroupError> {
let group_dir = self.groups_path.join(&acct);
let mut config = GroupConfig::from_dir(group_dir).await?;
@@ -165,20 +163,56 @@ impl ConfigStore {
}
};
Ok(GroupHandle {
group_account,
client,
config,
cc: self.config.clone(),
internal: GroupInternal::default(),
})
Ok(())
}
pub async fn find_locales(&mut self) {
if !self.locales_path.is_dir() {
debug!("No locales path set!");
return;
}
let entries = match std::fs::read_dir(&self.locales_path) {
Ok(ee) => ee,
Err(e) => {
warn!("Error listing locales");
return;
}
};
for e in entries {
if let Ok(e) = e {
let path = e.path();
if path.is_file() && path.extension().unwrap_or_default().to_string_lossy() == "json" {
let filename = path.file_name().unwrap_or_default().to_string_lossy();
debug!("Loading locale {}", filename);
match tokio::fs::read(&path).await {
Ok(f) => {
if let Ok(tr) = serde_json::from_slice::<TranslationTable>(&f) {
let locale_name = path.file_stem().unwrap_or_default().to_string_lossy().to_string();
debug!("Loaded locale: {}", locale_name);
self.config.tr.insert(locale_name, tr);
} else {
error!("Failed to parse locale file {}", path.display());
}
},
Err(e) => {
error!("Failed to read locale file {}: {}", path.display(), e);
}
}
}
}
}
}
/// Spawn existing group using saved creds
pub async fn spawn_groups(self: Arc<Self>) -> Result<Vec<GroupHandle>, GroupError> {
pub async fn spawn_groups(self) -> Result<Vec<GroupHandle>, GroupError> {
info!("Starting group services for groups in {}", self.groups_path.display());
let dirs = std::fs::read_dir(&self.groups_path)?;
let config = Arc::new(self.config);
// Connect in parallel
Ok(futures::stream::iter(dirs)
.map(|entry_maybe: Result<std::fs::DirEntry, std::io::Error>| async {
@@ -213,7 +247,7 @@ impl ConfigStore {
group_account: my_account,
client,
config: gc,
cc: self.config.clone(),
cc: config.clone(),
internal: GroupInternal::default(),
})
}