Desktop host: studios, account studio and checks, store app lists per account, store-only app targets, pairing / link / ignore overrides, settings (refresh, cache age, notifications, channel), cache info, data folder, notifications, reset
This commit is contained in:
parent
53f9e6dd75
commit
e058d09683
25 changed files with 1063 additions and 20 deletions
|
|
@ -29,6 +29,20 @@
|
||||||
"allow-open-external",
|
"allow-open-external",
|
||||||
"allow-tools-info",
|
"allow-tools-info",
|
||||||
"allow-tools-install",
|
"allow-tools-install",
|
||||||
"allow-tools-uninstall"
|
"allow-tools-uninstall",
|
||||||
|
"allow-workspace-get",
|
||||||
|
"allow-studio-save",
|
||||||
|
"allow-studio-remove",
|
||||||
|
"allow-studio-logo",
|
||||||
|
"allow-account-update",
|
||||||
|
"allow-account-check",
|
||||||
|
"allow-store-apps-refresh",
|
||||||
|
"allow-store-apps-cached",
|
||||||
|
"allow-overrides-set",
|
||||||
|
"allow-settings-set",
|
||||||
|
"allow-cache-info",
|
||||||
|
"allow-data-reveal",
|
||||||
|
"allow-notify",
|
||||||
|
"allow-app-reset"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-account-check"
|
||||||
|
description = "Enables the account_check command without any pre-configured scope."
|
||||||
|
commands.allow = ["account_check"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-account-check"
|
||||||
|
description = "Denies the account_check command without any pre-configured scope."
|
||||||
|
commands.deny = ["account_check"]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-account-update"
|
||||||
|
description = "Enables the account_update command without any pre-configured scope."
|
||||||
|
commands.allow = ["account_update"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-account-update"
|
||||||
|
description = "Denies the account_update command without any pre-configured scope."
|
||||||
|
commands.deny = ["account_update"]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-app-reset"
|
||||||
|
description = "Enables the app_reset command without any pre-configured scope."
|
||||||
|
commands.allow = ["app_reset"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-app-reset"
|
||||||
|
description = "Denies the app_reset command without any pre-configured scope."
|
||||||
|
commands.deny = ["app_reset"]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-cache-info"
|
||||||
|
description = "Enables the cache_info command without any pre-configured scope."
|
||||||
|
commands.allow = ["cache_info"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-cache-info"
|
||||||
|
description = "Denies the cache_info command without any pre-configured scope."
|
||||||
|
commands.deny = ["cache_info"]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-data-reveal"
|
||||||
|
description = "Enables the data_reveal command without any pre-configured scope."
|
||||||
|
commands.allow = ["data_reveal"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-data-reveal"
|
||||||
|
description = "Denies the data_reveal command without any pre-configured scope."
|
||||||
|
commands.deny = ["data_reveal"]
|
||||||
11
apps/desktop/src-tauri/permissions/autogenerated/notify.toml
Normal file
11
apps/desktop/src-tauri/permissions/autogenerated/notify.toml
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-notify"
|
||||||
|
description = "Enables the notify command without any pre-configured scope."
|
||||||
|
commands.allow = ["notify"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-notify"
|
||||||
|
description = "Denies the notify command without any pre-configured scope."
|
||||||
|
commands.deny = ["notify"]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-overrides-set"
|
||||||
|
description = "Enables the overrides_set command without any pre-configured scope."
|
||||||
|
commands.allow = ["overrides_set"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-overrides-set"
|
||||||
|
description = "Denies the overrides_set command without any pre-configured scope."
|
||||||
|
commands.deny = ["overrides_set"]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-settings-set"
|
||||||
|
description = "Enables the settings_set command without any pre-configured scope."
|
||||||
|
commands.allow = ["settings_set"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-settings-set"
|
||||||
|
description = "Denies the settings_set command without any pre-configured scope."
|
||||||
|
commands.deny = ["settings_set"]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-store-apps-cached"
|
||||||
|
description = "Enables the store_apps_cached command without any pre-configured scope."
|
||||||
|
commands.allow = ["store_apps_cached"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-store-apps-cached"
|
||||||
|
description = "Denies the store_apps_cached command without any pre-configured scope."
|
||||||
|
commands.deny = ["store_apps_cached"]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-store-apps-refresh"
|
||||||
|
description = "Enables the store_apps_refresh command without any pre-configured scope."
|
||||||
|
commands.allow = ["store_apps_refresh"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-store-apps-refresh"
|
||||||
|
description = "Denies the store_apps_refresh command without any pre-configured scope."
|
||||||
|
commands.deny = ["store_apps_refresh"]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-studio-logo"
|
||||||
|
description = "Enables the studio_logo command without any pre-configured scope."
|
||||||
|
commands.allow = ["studio_logo"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-studio-logo"
|
||||||
|
description = "Denies the studio_logo command without any pre-configured scope."
|
||||||
|
commands.deny = ["studio_logo"]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-studio-remove"
|
||||||
|
description = "Enables the studio_remove command without any pre-configured scope."
|
||||||
|
commands.allow = ["studio_remove"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-studio-remove"
|
||||||
|
description = "Denies the studio_remove command without any pre-configured scope."
|
||||||
|
commands.deny = ["studio_remove"]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-studio-save"
|
||||||
|
description = "Enables the studio_save command without any pre-configured scope."
|
||||||
|
commands.allow = ["studio_save"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-studio-save"
|
||||||
|
description = "Denies the studio_save command without any pre-configured scope."
|
||||||
|
commands.deny = ["studio_save"]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
# Automatically generated - DO NOT EDIT!
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "allow-workspace-get"
|
||||||
|
description = "Enables the workspace_get command without any pre-configured scope."
|
||||||
|
commands.allow = ["workspace_get"]
|
||||||
|
|
||||||
|
[[permission]]
|
||||||
|
identifier = "deny-workspace-get"
|
||||||
|
description = "Denies the workspace_get command without any pre-configured scope."
|
||||||
|
commands.deny = ["workspace_get"]
|
||||||
|
|
@ -22,6 +22,9 @@ pub struct Account {
|
||||||
pub label: String,
|
pub label: String,
|
||||||
pub kind: AccountKind,
|
pub kind: AccountKind,
|
||||||
pub created: String,
|
pub created: String,
|
||||||
|
/// The studio this account belongs to (workspace::Studio id), if any.
|
||||||
|
#[serde(default)]
|
||||||
|
pub studio: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The keychain entry of one account (JSON).
|
/// The keychain entry of one account (JSON).
|
||||||
|
|
|
||||||
|
|
@ -94,6 +94,19 @@ impl Cache {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Rows, bytes of the saved values and the oldest read time.
|
||||||
|
pub fn info(&self) -> Result<(u64, u64, Option<String>), String> {
|
||||||
|
let db = self.db.lock().map_err(|_| "cache poisoned")?;
|
||||||
|
db.query_row("SELECT COUNT(*), COALESCE(SUM(LENGTH(value)), 0), MIN(at) FROM reads", [], |r| Ok((r.get::<_, i64>(0)? as u64, r.get::<_, i64>(1)? as u64, r.get(2)?)))
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drops reads older than `cutoff` (RFC 3339, compared as text: every `at` is written in the same UTC format).
|
||||||
|
pub fn prune_before(&self, cutoff: &str) -> Result<usize, String> {
|
||||||
|
let db = self.db.lock().map_err(|_| "cache poisoned")?;
|
||||||
|
db.execute("DELETE FROM reads WHERE at < ?1", params![cutoff]).map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
pub fn clear(&self) -> Result<(), String> {
|
pub fn clear(&self) -> Result<(), String> {
|
||||||
let db = self.db.lock().map_err(|_| "cache poisoned")?;
|
let db = self.db.lock().map_err(|_| "cache poisoned")?;
|
||||||
db.execute("DELETE FROM reads", []).map_err(|e| e.to_string())?;
|
db.execute("DELETE FROM reads", []).map_err(|e| e.to_string())?;
|
||||||
|
|
|
||||||
|
|
@ -17,6 +17,7 @@ use crate::downloads;
|
||||||
use crate::policy::{self, Kind};
|
use crate::policy::{self, Kind};
|
||||||
use crate::sidecar::{valid_job, Fail, Progress, Sidecar};
|
use crate::sidecar::{valid_job, Fail, Progress, Sidecar};
|
||||||
use crate::store::{self, Project, State as Saved};
|
use crate::store::{self, Project, State as Saved};
|
||||||
|
use crate::workspace::{self, Overrides, Settings, StoreTarget, Studio};
|
||||||
|
|
||||||
pub struct AppState {
|
pub struct AppState {
|
||||||
pub sidecar: Sidecar,
|
pub sidecar: Sidecar,
|
||||||
|
|
@ -62,6 +63,40 @@ fn project_params(s: &AppState, project_id: &str) -> Res<(Project, Map<String, V
|
||||||
Ok((p, creds))
|
Ok((p, creds))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Credentials of the accounts a store-only app is read with; each part must use an account of its store.
|
||||||
|
fn target_params(s: &AppState, t: &StoreTarget) -> Res<Map<String, Value>> {
|
||||||
|
let st = saved(s)?;
|
||||||
|
let kind = |id: &str| st.accounts.iter().find(|a| a.id == id).map(|a| a.kind);
|
||||||
|
if let Some((acc, ..)) = &t.ios {
|
||||||
|
if kind(acc) != Some(AccountKind::Apple) {
|
||||||
|
return Err(Fail::host("store app: not an App Store Connect account"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some((acc, _)) = &t.android {
|
||||||
|
if kind(acc) != Some(AccountKind::Play) {
|
||||||
|
return Err(Fail::host("store app: not a Google Play account"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
drop(st);
|
||||||
|
let mut creds = Map::new();
|
||||||
|
for id in t.accounts() {
|
||||||
|
if let Ok(secret) = s.secrets.get(id) {
|
||||||
|
secret.to_credentials(&mut creds);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(creds)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One account's credentials only (account reads).
|
||||||
|
fn account_creds(s: &AppState, id: &str) -> Res<Map<String, Value>> {
|
||||||
|
if !saved(s)?.accounts.iter().any(|a| a.id == id) {
|
||||||
|
return Err(Fail::host("unknown account"));
|
||||||
|
}
|
||||||
|
let mut creds = Map::new();
|
||||||
|
s.secrets.get(id).map_err(Fail::host)?.to_credentials(&mut creds);
|
||||||
|
Ok(creds)
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
pub struct AppInfo {
|
pub struct AppInfo {
|
||||||
version: &'static str,
|
version: &'static str,
|
||||||
|
|
@ -105,6 +140,24 @@ pub async fn sidecar_call(window: WebviewWindow, app: AppHandle, state: State<'_
|
||||||
let mut cache_project = None;
|
let mut cache_project = None;
|
||||||
if matches!(kind, Some(Kind::Read | Kind::Write)) {
|
if matches!(kind, Some(Kind::Read | Kind::Write)) {
|
||||||
let id = project_id.ok_or_else(|| Fail::host(format!("{method} needs a project")))?;
|
let id = project_id.ok_or_else(|| Fail::host(format!("{method} needs a project")))?;
|
||||||
|
if id.starts_with("store:") {
|
||||||
|
// a store-only app: store reads only, through the sidecar's generated config
|
||||||
|
if kind != Some(Kind::Read) {
|
||||||
|
return Err(Fail::host("store-only apps are read-only: link a folder to change anything"));
|
||||||
|
}
|
||||||
|
let target = StoreTarget::parse(&id).map_err(Fail::host)?;
|
||||||
|
let creds = target_params(&state, &target)?;
|
||||||
|
let o = p.as_object_mut().ok_or_else(|| Fail::host("params"))?;
|
||||||
|
o.insert("virtual".into(), target.virtual_project());
|
||||||
|
if !creds.is_empty() {
|
||||||
|
o.insert("credentials".into(), Value::Object(creds));
|
||||||
|
}
|
||||||
|
let res = r.call_job(&method, p, job.as_deref()).await?;
|
||||||
|
if res["ok"] == Value::Bool(true) && !res["data"].is_null() {
|
||||||
|
let _ = state.cache.put(&id, &method, &args, &res, &store::now_iso());
|
||||||
|
}
|
||||||
|
return Ok(res);
|
||||||
|
}
|
||||||
let (proj, creds) = project_params(&state, &id)?;
|
let (proj, creds) = project_params(&state, &id)?;
|
||||||
let o = p.as_object_mut().ok_or_else(|| Fail::host("params"))?;
|
let o = p.as_object_mut().ok_or_else(|| Fail::host("params"))?;
|
||||||
o.insert("project".into(), Value::String(proj.path));
|
o.insert("project".into(), Value::String(proj.path));
|
||||||
|
|
@ -347,6 +400,10 @@ pub fn project_remove(window: WebviewWindow, state: State<'_, AppState>, id: Str
|
||||||
guard(&window)?;
|
guard(&window)?;
|
||||||
let mut st = saved(&state)?;
|
let mut st = saved(&state)?;
|
||||||
st.projects.retain(|p| p.id != id);
|
st.projects.retain(|p| p.id != id);
|
||||||
|
st.overrides.links.retain(|l| l.project != id);
|
||||||
|
let (ig, key) = (format!("project:{id}"), format!("project:{id}"));
|
||||||
|
st.overrides.ignored.retain(|i| i != &ig);
|
||||||
|
st.overrides.app_studio.retain(|a| a.key != key);
|
||||||
let _ = state.cache.forget_project(&id);
|
let _ = state.cache.forget_project(&id);
|
||||||
persist(&state, &st)
|
persist(&state, &st)
|
||||||
}
|
}
|
||||||
|
|
@ -380,9 +437,19 @@ pub fn accounts_list(window: WebviewWindow, state: State<'_, AppState>) -> Res<V
|
||||||
Ok(saved(&state)?.accounts.clone())
|
Ok(saved(&state)?.accounts.clone())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add_account(state: &AppState, label: &str, secret: Secret) -> Res<Account> {
|
fn check_studio(state: &AppState, studio: &Option<String>) -> Res<()> {
|
||||||
|
if let Some(s) = studio {
|
||||||
|
if !saved(state)?.studios.iter().any(|x| &x.id == s) {
|
||||||
|
return Err(Fail::host("unknown studio"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_account(state: &AppState, label: &str, secret: Secret, studio: Option<String>) -> Res<Account> {
|
||||||
let label = accounts::check_label(label).map_err(Fail::host)?;
|
let label = accounts::check_label(label).map_err(Fail::host)?;
|
||||||
let acc = Account { id: store::new_id()?, label, kind: secret.kind(), created: store::now_iso() };
|
check_studio(state, &studio)?;
|
||||||
|
let acc = Account { id: store::new_id()?, label, kind: secret.kind(), created: store::now_iso(), studio };
|
||||||
state.secrets.set(&acc.id, &secret).map_err(Fail::host)?;
|
state.secrets.set(&acc.id, &secret).map_err(Fail::host)?;
|
||||||
let mut st = saved(state)?;
|
let mut st = saved(state)?;
|
||||||
st.accounts.push(acc.clone());
|
st.accounts.push(acc.clone());
|
||||||
|
|
@ -409,24 +476,26 @@ async fn pick_file(window: &WebviewWindow, title: &'static str, filter: (&'stati
|
||||||
|
|
||||||
/// Google Play: pick the service account JSON key in a native dialog; it goes to the keychain only.
|
/// Google Play: pick the service account JSON key in a native dialog; it goes to the keychain only.
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn account_add_play(window: WebviewWindow, state: State<'_, AppState>, label: String) -> Res<Option<Account>> {
|
pub async fn account_add_play(window: WebviewWindow, state: State<'_, AppState>, label: String, studio: Option<String>) -> Res<Option<Account>> {
|
||||||
guard(&window)?;
|
guard(&window)?;
|
||||||
accounts::check_label(&label).map_err(Fail::host)?;
|
accounts::check_label(&label).map_err(Fail::host)?;
|
||||||
|
check_studio(&state, &studio)?;
|
||||||
let Some(text) = pick_file(&window, "Google Play service account key (JSON)", ("JSON key", &["json"])).await? else { return Ok(None) };
|
let Some(text) = pick_file(&window, "Google Play service account key (JSON)", ("JSON key", &["json"])).await? else { return Ok(None) };
|
||||||
let sa = accounts::check_service_account(&text).map_err(Fail::host)?;
|
let sa = accounts::check_service_account(&text).map_err(Fail::host)?;
|
||||||
add_account(&state, &label, Secret::Play { service_account: sa }).map(Some)
|
add_account(&state, &label, Secret::Play { service_account: sa }, studio).map(Some)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// App Store Connect: key id + issuer id typed in the app, the .p8 picked in a native dialog; all to the keychain.
|
/// App Store Connect: key id + issuer id typed in the app, the .p8 picked in a native dialog; all to the keychain.
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn account_add_apple(window: WebviewWindow, state: State<'_, AppState>, label: String, key_id: String, issuer_id: String) -> Res<Option<Account>> {
|
pub async fn account_add_apple(window: WebviewWindow, state: State<'_, AppState>, label: String, key_id: String, issuer_id: String, studio: Option<String>) -> Res<Option<Account>> {
|
||||||
guard(&window)?;
|
guard(&window)?;
|
||||||
accounts::check_label(&label).map_err(Fail::host)?;
|
accounts::check_label(&label).map_err(Fail::host)?;
|
||||||
|
check_studio(&state, &studio)?;
|
||||||
let key_id = accounts::check_key_id(&key_id).map_err(Fail::host)?;
|
let key_id = accounts::check_key_id(&key_id).map_err(Fail::host)?;
|
||||||
let issuer_id = accounts::check_issuer_id(&issuer_id).map_err(Fail::host)?;
|
let issuer_id = accounts::check_issuer_id(&issuer_id).map_err(Fail::host)?;
|
||||||
let Some(text) = pick_file(&window, "App Store Connect API key (.p8)", ("API key", &["p8"])).await? else { return Ok(None) };
|
let Some(text) = pick_file(&window, "App Store Connect API key (.p8)", ("API key", &["p8"])).await? else { return Ok(None) };
|
||||||
let p8 = accounts::check_p8(&text).map_err(Fail::host)?;
|
let p8 = accounts::check_p8(&text).map_err(Fail::host)?;
|
||||||
add_account(&state, &label, Secret::Apple { key_id, issuer_id, p8 }).map(Some)
|
add_account(&state, &label, Secret::Apple { key_id, issuer_id, p8 }, studio).map(Some)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
|
|
@ -435,6 +504,9 @@ pub fn account_remove(window: WebviewWindow, state: State<'_, AppState>, id: Str
|
||||||
state.secrets.delete(&id).map_err(Fail::host)?;
|
state.secrets.delete(&id).map_err(Fail::host)?;
|
||||||
let mut st = saved(&state)?;
|
let mut st = saved(&state)?;
|
||||||
st.accounts.retain(|a| a.id != id);
|
st.accounts.retain(|a| a.id != id);
|
||||||
|
let ignored = format!("account:{id}");
|
||||||
|
st.overrides.ignored.retain(|i| i != &ignored);
|
||||||
|
let _ = state.cache.forget_project(&format!("acct:{id}"));
|
||||||
for p in st.projects.iter_mut() {
|
for p in st.projects.iter_mut() {
|
||||||
if p.play_account.as_deref() == Some(id.as_str()) {
|
if p.play_account.as_deref() == Some(id.as_str()) {
|
||||||
p.play_account = None;
|
p.play_account = None;
|
||||||
|
|
@ -446,18 +518,31 @@ pub fn account_remove(window: WebviewWindow, state: State<'_, AppState>, id: Str
|
||||||
persist(&state, &st)
|
persist(&state, &st)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Store reads run at most this many apps at once (each is two status reads).
|
/// Store-only apps one live portfolio read takes at most.
|
||||||
const LIVE_PARALLEL: usize = 4;
|
const MAX_STORE_TARGETS: usize = 300;
|
||||||
|
|
||||||
/// `portfolio.status` over every project. Offline unless `live`; live reads every app with its own accounts, several
|
/// `portfolio.status` over every project. Offline unless `live`; live reads every app with its own accounts, several
|
||||||
/// at once, and sends one progress line per finished app (job progress n / total). Each live app result is cached;
|
/// at once, and sends one progress line per finished app (job progress n / total). Each live app result is cached;
|
||||||
/// the whole live result too (project "*"), so the portfolio shows the last read when offline.
|
/// the whole live result too (project "*"), so the portfolio shows the last read when offline.
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn portfolio_status(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>, live: Option<bool>, job: Option<String>) -> Res<Value> {
|
pub async fn portfolio_status(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>, live: Option<bool>, stores: Option<Vec<String>>, job: Option<String>) -> Res<Value> {
|
||||||
guard(&window)?;
|
guard(&window)?;
|
||||||
let job = job_of(job)?;
|
let job = job_of(job)?;
|
||||||
let projects = saved(&state)?.projects.clone();
|
let (projects, parallel) = {
|
||||||
if projects.is_empty() {
|
let st = saved(&state)?;
|
||||||
|
let ignored: Vec<&str> = st.overrides.ignored.iter().filter_map(|i| i.strip_prefix("project:")).collect();
|
||||||
|
(st.projects.iter().filter(|p| !ignored.contains(&p.id.as_str())).cloned().collect::<Vec<_>>(), st.settings.refresh.parallel.clamp(1, 8) as usize)
|
||||||
|
};
|
||||||
|
// store-only apps (live reads only): validated targets with their accounts' credentials
|
||||||
|
let mut targets = Vec::new();
|
||||||
|
if live == Some(true) {
|
||||||
|
for key in stores.unwrap_or_default().into_iter().take(MAX_STORE_TARGETS) {
|
||||||
|
let t = StoreTarget::parse(&key).map_err(Fail::host)?;
|
||||||
|
let creds = target_params(&state, &t)?;
|
||||||
|
targets.push((key, t, creds));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if projects.is_empty() && targets.is_empty() {
|
||||||
return Ok(json!({ "apps": [], "at": store::now_iso() }));
|
return Ok(json!({ "apps": [], "at": store::now_iso() }));
|
||||||
}
|
}
|
||||||
let r = state.sidecar.get(&app).await?;
|
let r = state.sidecar.get(&app).await?;
|
||||||
|
|
@ -465,8 +550,8 @@ pub async fn portfolio_status(window: WebviewWindow, app: AppHandle, state: Stat
|
||||||
let paths: Vec<&str> = projects.iter().map(|p| p.path.as_str()).collect();
|
let paths: Vec<&str> = projects.iter().map(|p| p.path.as_str()).collect();
|
||||||
return r.call_job("portfolio.status", json!({ "projects": paths }), job.as_deref()).await;
|
return r.call_job("portfolio.status", json!({ "projects": paths }), job.as_deref()).await;
|
||||||
}
|
}
|
||||||
let total = projects.len();
|
let total = projects.len() + targets.len();
|
||||||
let sem = Arc::new(tokio::sync::Semaphore::new(LIVE_PARALLEL));
|
let sem = Arc::new(tokio::sync::Semaphore::new(parallel));
|
||||||
let done = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
let done = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||||
let mut handles = Vec::new();
|
let mut handles = Vec::new();
|
||||||
for p in &projects {
|
for p in &projects {
|
||||||
|
|
@ -481,6 +566,18 @@ pub async fn portfolio_status(window: WebviewWindow, app: AppHandle, state: Stat
|
||||||
(id, res)
|
(id, res)
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
for (key, t, creds) in targets {
|
||||||
|
let (r, sem, done, app, job, id) = (r.clone(), sem.clone(), done.clone(), app.clone(), job.clone(), key.clone());
|
||||||
|
let entry = json!({ "key": key, "virtual": t.virtual_project() });
|
||||||
|
handles.push(tauri::async_runtime::spawn(async move {
|
||||||
|
let _permit = sem.acquire_owned().await.ok();
|
||||||
|
let sub = job.as_ref().map(|j| format!("{j}:p"));
|
||||||
|
let res = r.call_job("portfolio.status", json!({ "projects": [entry], "live": true, "credentials": creds }), sub.as_deref()).await;
|
||||||
|
let n = done.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
|
||||||
|
let _ = app.emit_to(policy::MAIN, "sidecar-progress", Progress { params: json!({ "requestId": 0, "n": n, "total": total, "project": id }), job: job.clone() });
|
||||||
|
(id, res)
|
||||||
|
}));
|
||||||
|
}
|
||||||
let mut all = Vec::new();
|
let mut all = Vec::new();
|
||||||
let at = store::now_iso();
|
let at = store::now_iso();
|
||||||
for h in handles {
|
for h in handles {
|
||||||
|
|
@ -541,3 +638,250 @@ pub async fn tools_uninstall(window: WebviewWindow, state: State<'_, AppState>,
|
||||||
state.sidecar.shutdown().await;
|
state.sidecar.shutdown().await;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- D3: studios, store accounts' apps, pairing overrides, ignore list, settings ----
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct Workspace {
|
||||||
|
studios: Vec<Studio>,
|
||||||
|
overrides: Overrides,
|
||||||
|
settings: Settings,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Studios, the owner's pairing / link / ignore overrides and the app settings in one read.
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn workspace_get(window: WebviewWindow, state: State<'_, AppState>) -> Res<Workspace> {
|
||||||
|
guard(&window)?;
|
||||||
|
let st = saved(&state)?;
|
||||||
|
Ok(Workspace { studios: st.studios.clone(), overrides: st.overrides.clone(), settings: st.settings.clone() })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates (no id) or renames / recolours a studio.
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn studio_save(window: WebviewWindow, state: State<'_, AppState>, id: Option<String>, name: String, color: String) -> Res<Studio> {
|
||||||
|
guard(&window)?;
|
||||||
|
let name = workspace::check_studio_name(&name).map_err(Fail::host)?;
|
||||||
|
let color = workspace::check_color(&color).map_err(Fail::host)?;
|
||||||
|
let mut st = saved(&state)?;
|
||||||
|
let out = match id {
|
||||||
|
Some(id) => {
|
||||||
|
let s = st.studios.iter_mut().find(|s| s.id == id).ok_or_else(|| Fail::host("unknown studio"))?;
|
||||||
|
s.name = name;
|
||||||
|
s.color = color;
|
||||||
|
s.clone()
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
if st.studios.len() >= 100 {
|
||||||
|
return Err(Fail::host("at most 100 studios"));
|
||||||
|
}
|
||||||
|
let s = Studio { id: store::new_id()?, name, color, logo: None, created: store::now_iso() };
|
||||||
|
st.studios.push(s.clone());
|
||||||
|
s
|
||||||
|
}
|
||||||
|
};
|
||||||
|
persist(&state, &st)?;
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Removes a studio; its accounts and apps stay, without a studio.
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn studio_remove(window: WebviewWindow, state: State<'_, AppState>, id: String) -> Res<()> {
|
||||||
|
guard(&window)?;
|
||||||
|
let mut st = saved(&state)?;
|
||||||
|
st.studios.retain(|s| s.id != id);
|
||||||
|
for a in st.accounts.iter_mut() {
|
||||||
|
if a.studio.as_deref() == Some(id.as_str()) {
|
||||||
|
a.studio = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
st.overrides.app_studio.retain(|a| a.studio != id);
|
||||||
|
persist(&state, &st)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Studio logo: a small PNG / JPEG / WebP picked in a native dialog (kept as a data URL), or `clear`.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn studio_logo(window: WebviewWindow, state: State<'_, AppState>, id: String, clear: bool) -> Res<Option<Studio>> {
|
||||||
|
guard(&window)?;
|
||||||
|
if !saved(&state)?.studios.iter().any(|s| s.id == id) {
|
||||||
|
return Err(Fail::host("unknown studio"));
|
||||||
|
}
|
||||||
|
let logo = if clear {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
let w = window.clone();
|
||||||
|
let picked = tauri::async_runtime::spawn_blocking(move || w.app_handle().dialog().file().set_title("Studio logo (PNG, JPEG or WebP)").add_filter("Image", &["png", "jpg", "jpeg", "webp"]).set_parent(&w).blocking_pick_file())
|
||||||
|
.await
|
||||||
|
.map_err(|e| Fail::host(e.to_string()))?;
|
||||||
|
let Some(p) = picked else { return Ok(None) };
|
||||||
|
let path = p.into_path().map_err(|e| Fail::host(e.to_string()))?;
|
||||||
|
if std::fs::metadata(&path).map_err(|e| Fail::host(e.to_string()))?.len() > workspace::LOGO_MAX as u64 {
|
||||||
|
return Err(Fail::host("logo: at most 256 KB"));
|
||||||
|
}
|
||||||
|
Some(workspace::logo_data_url(&std::fs::read(&path).map_err(|e| Fail::host(e.to_string()))?).map_err(Fail::host)?)
|
||||||
|
};
|
||||||
|
let mut st = saved(&state)?;
|
||||||
|
let s = st.studios.iter_mut().find(|s| s.id == id).ok_or_else(|| Fail::host("unknown studio"))?;
|
||||||
|
s.logo = logo;
|
||||||
|
let out = s.clone();
|
||||||
|
persist(&state, &st)?;
|
||||||
|
Ok(Some(out))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renames an account or moves it to another studio (the key in the keychain stays as it is).
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn account_update(window: WebviewWindow, state: State<'_, AppState>, id: String, label: String, studio: Option<String>) -> Res<Account> {
|
||||||
|
guard(&window)?;
|
||||||
|
let label = accounts::check_label(&label).map_err(Fail::host)?;
|
||||||
|
check_studio(&state, &studio)?;
|
||||||
|
let mut st = saved(&state)?;
|
||||||
|
let a = st.accounts.iter_mut().find(|a| a.id == id).ok_or_else(|| Fail::host("unknown account"))?;
|
||||||
|
a.label = label;
|
||||||
|
a.studio = studio;
|
||||||
|
let out = a.clone();
|
||||||
|
persist(&state, &st)?;
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Does the account's key work, and can it see apps (sidecar `account.check`). Not cached: it is a live answer.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn account_check(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>, id: String, job: Option<String>) -> Res<Value> {
|
||||||
|
guard(&window)?;
|
||||||
|
let job = job_of(job)?;
|
||||||
|
let creds = account_creds(&state, &id)?;
|
||||||
|
let r = state.sidecar.get(&app).await?;
|
||||||
|
r.call_job("account.check", json!({ "credentials": creds }), job.as_deref()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads every app the account can see from its store (sidecar `apps.list`, icons per Settings) and keeps the list
|
||||||
|
/// (cache project "acct:<id>").
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn store_apps_refresh(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>, id: String, job: Option<String>) -> Res<Entry> {
|
||||||
|
guard(&window)?;
|
||||||
|
let job = job_of(job)?;
|
||||||
|
let creds = account_creds(&state, &id)?;
|
||||||
|
let icons = saved(&state)?.settings.refresh.icons;
|
||||||
|
let r = state.sidecar.get(&app).await?;
|
||||||
|
let value = r.call_job("apps.list", json!({ "credentials": creds, "args": { "icons": icons } }), job.as_deref()).await?;
|
||||||
|
let at = store::now_iso();
|
||||||
|
state.cache.put(&format!("acct:{id}"), "apps.list", &json!({}), &value, &at).map_err(Fail::host)?;
|
||||||
|
Ok(Entry { value, at })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct AccountApps {
|
||||||
|
account: String,
|
||||||
|
entry: Option<Entry>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The last app list read of every account (null for an account never read).
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn store_apps_cached(window: WebviewWindow, state: State<'_, AppState>) -> Res<Vec<AccountApps>> {
|
||||||
|
guard(&window)?;
|
||||||
|
let ids: Vec<String> = saved(&state)?.accounts.iter().map(|a| a.id.clone()).collect();
|
||||||
|
ids.into_iter()
|
||||||
|
.map(|account| {
|
||||||
|
let entry = state.cache.get(&format!("acct:{account}"), "apps.list", &json!({})).map_err(Fail::host)?;
|
||||||
|
Ok(AccountApps { account, entry })
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replaces the pairing / link / studio / ignore overrides (every key is checked).
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn overrides_set(window: WebviewWindow, state: State<'_, AppState>, overrides: Overrides) -> Res<Overrides> {
|
||||||
|
guard(&window)?;
|
||||||
|
workspace::check_overrides(&overrides).map_err(Fail::host)?;
|
||||||
|
let mut st = saved(&state)?;
|
||||||
|
st.overrides = overrides.clone();
|
||||||
|
persist(&state, &st)?;
|
||||||
|
Ok(overrides)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Saves the app settings; a shorter "keep saved reads" drops older reads right away.
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn settings_set(window: WebviewWindow, state: State<'_, AppState>, settings: Settings) -> Res<Settings> {
|
||||||
|
guard(&window)?;
|
||||||
|
workspace::check_settings(&settings).map_err(Fail::host)?;
|
||||||
|
let mut st = saved(&state)?;
|
||||||
|
st.settings = settings.clone();
|
||||||
|
persist(&state, &st)?;
|
||||||
|
drop(st);
|
||||||
|
prune_cache(&state, settings.cache.keep_days);
|
||||||
|
Ok(settings)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn prune_cache(state: &AppState, keep_days: u32) {
|
||||||
|
if keep_days == 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
|
||||||
|
let cutoff = store::iso_from_unix(now.saturating_sub(u64::from(keep_days) * 86_400));
|
||||||
|
let _ = state.cache.prune_before(&cutoff);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct CacheInfo {
|
||||||
|
rows: u64,
|
||||||
|
bytes: u64,
|
||||||
|
oldest: Option<String>,
|
||||||
|
/// cache.sqlite (+ its WAL) on disk.
|
||||||
|
file_bytes: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn cache_info(window: WebviewWindow, state: State<'_, AppState>) -> Res<CacheInfo> {
|
||||||
|
guard(&window)?;
|
||||||
|
let (rows, bytes, oldest) = state.cache.info().map_err(Fail::host)?;
|
||||||
|
let file_bytes = ["", "-wal", "-shm"].iter().filter_map(|s| std::fs::metadata(state.data_dir.join(format!("{}{s}", crate::cache::FILE))).ok()).map(|m| m.len()).sum();
|
||||||
|
Ok(CacheInfo { rows, bytes, oldest, file_bytes })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shows the app data folder (state, saved reads, downloaded tools; never keys) in the file manager.
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn data_reveal(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>) -> Res<()> {
|
||||||
|
guard(&window)?;
|
||||||
|
let _ = std::fs::create_dir_all(&state.data_dir);
|
||||||
|
app.opener().reveal_item_in_dir(state.data_dir.join(store::FILE)).or_else(|_| app.opener().open_path(state.data_dir.to_string_lossy(), None::<&str>)).map_err(|e| Fail::host(e.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A desktop notification (review state changed, a new 1-2 star review, a crash rate over the threshold). The window
|
||||||
|
/// decides when, from Settings > Notifications; text is plain and short.
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn notify(window: WebviewWindow, app: AppHandle, title: String, body: String) -> Res<()> {
|
||||||
|
guard(&window)?;
|
||||||
|
use tauri_plugin_notification::NotificationExt;
|
||||||
|
let cut = |s: &str, n: usize| s.chars().filter(|c| !c.is_control()).take(n).collect::<String>();
|
||||||
|
app.notification().builder().title(cut(&title, 80)).body(cut(&body, 240)).show().map_err(|e| Fail::host(e.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Forgets everything after a native confirmation: store keys (keychain), studios, accounts, app folders (the folders
|
||||||
|
/// themselves stay), overrides, settings and saved reads. Downloaded tools stay. True when it was reset.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn app_reset(window: WebviewWindow, state: State<'_, AppState>) -> Res<bool> {
|
||||||
|
guard(&window)?;
|
||||||
|
let w = window.clone();
|
||||||
|
let yes = tauri::async_runtime::spawn_blocking(move || {
|
||||||
|
w.app_handle()
|
||||||
|
.dialog()
|
||||||
|
.message("Removes every store key from the system keychain and forgets studios, accounts, app folders (the folders and their files stay), pairing, the ignore list, settings and saved store reads.\n\nDownloaded tools stay. This cannot be undone.")
|
||||||
|
.title("Reset storebound desktop?")
|
||||||
|
.kind(MessageDialogKind::Warning)
|
||||||
|
.buttons(MessageDialogButtons::OkCancelCustom("Reset".into(), "Cancel".into()))
|
||||||
|
.parent(&w)
|
||||||
|
.blocking_show()
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|e| Fail::host(e.to_string()))?;
|
||||||
|
if !yes {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
let mut st = saved(&state)?;
|
||||||
|
for a in &st.accounts {
|
||||||
|
state.secrets.delete(&a.id).map_err(Fail::host)?;
|
||||||
|
}
|
||||||
|
*st = Saved::default();
|
||||||
|
persist(&state, &st)?;
|
||||||
|
drop(st);
|
||||||
|
state.cache.clear().map_err(Fail::host)?;
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -22,4 +22,18 @@ pub const COMMANDS: &[&str] = &[
|
||||||
"tools_info",
|
"tools_info",
|
||||||
"tools_install",
|
"tools_install",
|
||||||
"tools_uninstall",
|
"tools_uninstall",
|
||||||
|
"workspace_get",
|
||||||
|
"studio_save",
|
||||||
|
"studio_remove",
|
||||||
|
"studio_logo",
|
||||||
|
"account_update",
|
||||||
|
"account_check",
|
||||||
|
"store_apps_refresh",
|
||||||
|
"store_apps_cached",
|
||||||
|
"overrides_set",
|
||||||
|
"settings_set",
|
||||||
|
"cache_info",
|
||||||
|
"data_reveal",
|
||||||
|
"notify",
|
||||||
|
"app_reset",
|
||||||
];
|
];
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@ pub mod downloads;
|
||||||
pub mod policy;
|
pub mod policy;
|
||||||
pub mod sidecar;
|
pub mod sidecar;
|
||||||
pub mod store;
|
pub mod store;
|
||||||
|
pub mod workspace;
|
||||||
|
|
||||||
include!("commands_list.rs");
|
include!("commands_list.rs");
|
||||||
|
|
||||||
|
|
@ -136,14 +137,19 @@ pub fn run() {
|
||||||
let data_dir = app.path().app_data_dir()?;
|
let data_dir = app.path().app_data_dir()?;
|
||||||
dev_seed(&data_dir);
|
dev_seed(&data_dir);
|
||||||
let cache = cache::Cache::open(&data_dir).or_else(|_| cache::Cache::in_memory()).map_err(std::io::Error::other)?;
|
let cache = cache::Cache::open(&data_dir).or_else(|_| cache::Cache::in_memory()).map_err(std::io::Error::other)?;
|
||||||
app.manage(commands::AppState {
|
let saved = store::load(&data_dir);
|
||||||
|
let keep_days = saved.settings.cache.keep_days;
|
||||||
|
let state = commands::AppState {
|
||||||
sidecar: sidecar::Sidecar::default(),
|
sidecar: sidecar::Sidecar::default(),
|
||||||
saved: Mutex::new(store::load(&data_dir)),
|
saved: Mutex::new(saved),
|
||||||
data_dir,
|
data_dir,
|
||||||
secrets: Box::new(accounts::Keychain),
|
secrets: Box::new(accounts::Keychain),
|
||||||
cache,
|
cache,
|
||||||
downloads: downloads::Jobs::default(),
|
downloads: downloads::Jobs::default(),
|
||||||
});
|
};
|
||||||
|
// Settings > Offline cache: drop saved reads older than the chosen number of days
|
||||||
|
commands::prune_cache(&state, keep_days);
|
||||||
|
app.manage(state);
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
app.set_menu(menu(app.handle())?)?;
|
app.set_menu(menu(app.handle())?)?;
|
||||||
#[cfg(not(target_os = "macos"))]
|
#[cfg(not(target_os = "macos"))]
|
||||||
|
|
@ -194,6 +200,20 @@ pub fn run() {
|
||||||
commands::tools_info,
|
commands::tools_info,
|
||||||
commands::tools_install,
|
commands::tools_install,
|
||||||
commands::tools_uninstall,
|
commands::tools_uninstall,
|
||||||
|
commands::workspace_get,
|
||||||
|
commands::studio_save,
|
||||||
|
commands::studio_remove,
|
||||||
|
commands::studio_logo,
|
||||||
|
commands::account_update,
|
||||||
|
commands::account_check,
|
||||||
|
commands::store_apps_refresh,
|
||||||
|
commands::store_apps_cached,
|
||||||
|
commands::overrides_set,
|
||||||
|
commands::settings_set,
|
||||||
|
commands::cache_info,
|
||||||
|
commands::data_reveal,
|
||||||
|
commands::notify,
|
||||||
|
commands::app_reset,
|
||||||
])
|
])
|
||||||
.build(tauri::generate_context!())
|
.build(tauri::generate_context!())
|
||||||
.expect("storebound desktop failed to start");
|
.expect("storebound desktop failed to start");
|
||||||
|
|
|
||||||
|
|
@ -51,6 +51,8 @@ pub enum Kind {
|
||||||
System,
|
System,
|
||||||
Portfolio,
|
Portfolio,
|
||||||
Session,
|
Session,
|
||||||
|
/// Account-scoped store reads (apps.list, account.check): the host runs them with one account's key.
|
||||||
|
Account,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Kind {
|
impl Kind {
|
||||||
|
|
@ -61,6 +63,7 @@ impl Kind {
|
||||||
"system" => Kind::System,
|
"system" => Kind::System,
|
||||||
"portfolio" => Kind::Portfolio,
|
"portfolio" => Kind::Portfolio,
|
||||||
"session" => Kind::Session,
|
"session" => Kind::Session,
|
||||||
|
"account" => Kind::Account,
|
||||||
_ => return None,
|
_ => return None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
@ -78,6 +81,7 @@ pub fn sanitize_js_call(method: &str, kind: Option<Kind>, params: &Value) -> Res
|
||||||
match kind {
|
match kind {
|
||||||
Kind::Session => return Err(format!("{method} is the host's")),
|
Kind::Session => return Err(format!("{method} is the host's")),
|
||||||
Kind::Portfolio => return Err(format!("{method}: use portfolio_status")),
|
Kind::Portfolio => return Err(format!("{method}: use portfolio_status")),
|
||||||
|
Kind::Account => return Err(format!("{method}: use the account commands")),
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
let empty = Map::new();
|
let empty = Map::new();
|
||||||
|
|
@ -131,7 +135,7 @@ pub fn external_allowed(url: &Url) -> bool {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Deep links the app reacts to: `storebound://<screen>` for a known screen, nothing else.
|
/// Deep links the app reacts to: `storebound://<screen>` for a known screen, nothing else.
|
||||||
pub const DEEP_LINK_SCREENS: &[&str] = &["portfolio", "apps", "accounts", "dependencies", "settings"];
|
pub const DEEP_LINK_SCREENS: &[&str] = &["portfolio", "apps", "accounts", "ignored", "dependencies", "settings"];
|
||||||
|
|
||||||
pub fn deep_link_screen(url: &Url) -> Option<&'static str> {
|
pub fn deep_link_screen(url: &Url) -> Option<&'static str> {
|
||||||
if url.scheme() != "storebound" {
|
if url.scheme() != "storebound" {
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,7 @@ use std::path::{Path, PathBuf};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::accounts::Account;
|
use crate::accounts::Account;
|
||||||
|
use crate::workspace::{Overrides, Settings, Studio};
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
|
|
@ -27,6 +28,12 @@ pub struct State {
|
||||||
pub projects: Vec<Project>,
|
pub projects: Vec<Project>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub accounts: Vec<Account>,
|
pub accounts: Vec<Account>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub studios: Vec<Studio>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub overrides: Overrides,
|
||||||
|
#[serde(default)]
|
||||||
|
pub settings: Settings,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub const FILE: &str = "state.json";
|
pub const FILE: &str = "state.json";
|
||||||
|
|
|
||||||
309
apps/desktop/src-tauri/src/workspace.rs
Normal file
309
apps/desktop/src-tauri/src/workspace.rs
Normal file
|
|
@ -0,0 +1,309 @@
|
||||||
|
//! Studios, app pairing overrides, the ignore list, app settings and store-only app targets. Pure data and checks, so
|
||||||
|
//! tests/workspace.rs can pin every rule. Nothing here is a secret: studios are names and colours, overrides are store
|
||||||
|
//! app keys (account id + store app id), settings are numbers and switches.
|
||||||
|
//!
|
||||||
|
//! Store app key: "ios:<account id>:<App Store Connect app id>" or "android:<account id>:<package name>"
|
||||||
|
//! Store target id: "store:ios:<account>:<app id>:<bundle id>;android:<account>:<package>" (either part optional, at least
|
||||||
|
//! one): a store-only app (no app folder) the window reads through the sidecar's generated config.
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
|
||||||
|
/// Colours a studio can carry (CSS classes `studio-<name>` in the window, contrast-checked there).
|
||||||
|
pub const STUDIO_COLORS: &[&str] = &["indigo", "violet", "rose", "amber", "emerald", "teal", "sky", "slate"];
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Studio {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub color: String,
|
||||||
|
/// Small logo as a data: URL (PNG / JPEG / WebP, at most LOGO_MAX bytes before encoding), or none (monogram).
|
||||||
|
#[serde(default)]
|
||||||
|
pub logo: Option<String>,
|
||||||
|
pub created: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const LOGO_MAX: usize = 256 * 1024;
|
||||||
|
|
||||||
|
pub fn check_studio_name(s: &str) -> Result<String, String> {
|
||||||
|
let s = s.trim();
|
||||||
|
if s.is_empty() || s.chars().count() > 48 || s.chars().any(char::is_control) {
|
||||||
|
return Err("studio name: 1 to 48 characters".into());
|
||||||
|
}
|
||||||
|
Ok(s.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn check_color(s: &str) -> Result<String, String> {
|
||||||
|
if STUDIO_COLORS.contains(&s) {
|
||||||
|
Ok(s.to_string())
|
||||||
|
} else {
|
||||||
|
Err(format!("colour: one of {}", STUDIO_COLORS.join(", ")))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Logo bytes -> data URL; only small raster images whose bytes match the type.
|
||||||
|
pub fn logo_data_url(bytes: &[u8]) -> Result<String, String> {
|
||||||
|
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||||
|
if bytes.len() > LOGO_MAX {
|
||||||
|
return Err("logo: at most 256 KB".into());
|
||||||
|
}
|
||||||
|
let mime = if bytes.starts_with(&[0x89, b'P', b'N', b'G']) {
|
||||||
|
"image/png"
|
||||||
|
} else if bytes.starts_with(&[0xff, 0xd8, 0xff]) {
|
||||||
|
"image/jpeg"
|
||||||
|
} else if bytes.len() > 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
|
||||||
|
"image/webp"
|
||||||
|
} else {
|
||||||
|
return Err("logo: a PNG, JPEG or WebP image".into());
|
||||||
|
};
|
||||||
|
Ok(format!("data:{mime};base64,{}", STANDARD.encode(bytes)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Account ids are what store::new_id makes (16 hex).
|
||||||
|
pub fn is_account_id(s: &str) -> bool {
|
||||||
|
s.len() == 16 && s.chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_bundle(s: &str) -> bool {
|
||||||
|
!s.is_empty() && s.len() <= 155 && s.contains('.') && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-') && s.chars().next().is_some_and(|c| c.is_ascii_alphanumeric())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_package(s: &str) -> bool {
|
||||||
|
let parts: Vec<&str> = s.split('.').collect();
|
||||||
|
s.len() <= 155
|
||||||
|
&& parts.len() >= 2
|
||||||
|
&& parts.iter().all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'))
|
||||||
|
&& parts[0].chars().next().is_some_and(|c| c.is_ascii_alphabetic())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_asc_id(s: &str) -> bool {
|
||||||
|
!s.is_empty() && s.len() <= 20 && s.chars().all(|c| c.is_ascii_digit())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One app record on one store account.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum StoreAppKey {
|
||||||
|
Ios { account: String, app_id: String },
|
||||||
|
Android { account: String, package: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StoreAppKey {
|
||||||
|
pub fn parse(s: &str) -> Result<StoreAppKey, String> {
|
||||||
|
let mut it = s.splitn(3, ':');
|
||||||
|
let (store, account, id) = (it.next().unwrap_or_default(), it.next().unwrap_or_default(), it.next().unwrap_or_default());
|
||||||
|
if !is_account_id(account) {
|
||||||
|
return Err(format!("store app key {s}: bad account id"));
|
||||||
|
}
|
||||||
|
match store {
|
||||||
|
"ios" if is_asc_id(id) => Ok(StoreAppKey::Ios { account: account.into(), app_id: id.into() }),
|
||||||
|
"android" if is_package(id) => Ok(StoreAppKey::Android { account: account.into(), package: id.into() }),
|
||||||
|
_ => Err(format!("store app key {s}: ios:<account>:<app id> or android:<account>:<package>")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn account(&self) -> &str {
|
||||||
|
match self {
|
||||||
|
StoreAppKey::Ios { account, .. } | StoreAppKey::Android { account, .. } => account,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A store-only app the window reads: which accounts, which store ids.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||||
|
pub struct StoreTarget {
|
||||||
|
/// (account, App Store Connect app id, bundle id)
|
||||||
|
pub ios: Option<(String, String, String)>,
|
||||||
|
/// (account, package name)
|
||||||
|
pub android: Option<(String, String)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StoreTarget {
|
||||||
|
pub fn parse(s: &str) -> Result<StoreTarget, String> {
|
||||||
|
let rest = s.strip_prefix("store:").ok_or("store target: store:...")?;
|
||||||
|
if rest.len() > 400 {
|
||||||
|
return Err("store target: too long".into());
|
||||||
|
}
|
||||||
|
let mut t = StoreTarget::default();
|
||||||
|
for part in rest.split(';') {
|
||||||
|
let f: Vec<&str> = part.split(':').collect();
|
||||||
|
match f.as_slice() {
|
||||||
|
["ios", acc, id, bundle] if t.ios.is_none() && is_account_id(acc) && is_asc_id(id) && is_bundle(bundle) => {
|
||||||
|
t.ios = Some((acc.to_string(), id.to_string(), bundle.to_string()));
|
||||||
|
}
|
||||||
|
["android", acc, pkg] if t.android.is_none() && is_account_id(acc) && is_package(pkg) => {
|
||||||
|
t.android = Some((acc.to_string(), pkg.to_string()));
|
||||||
|
}
|
||||||
|
_ => return Err(format!("store target: bad part '{part}'")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if t.ios.is_none() && t.android.is_none() {
|
||||||
|
return Err("store target: ios and / or android".into());
|
||||||
|
}
|
||||||
|
Ok(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The sidecar's `virtual` object: store ids only, named after them.
|
||||||
|
pub fn virtual_project(&self) -> Value {
|
||||||
|
let name = self.ios.as_ref().map(|i| i.2.clone()).or_else(|| self.android.as_ref().map(|a| a.1.clone())).unwrap_or_default();
|
||||||
|
let mut v = json!({ "name": name });
|
||||||
|
if let Some((_, id, bundle)) = &self.ios {
|
||||||
|
v["apple"] = json!({ "bundleId": bundle, "appId": id });
|
||||||
|
}
|
||||||
|
if let Some((_, pkg)) = &self.android {
|
||||||
|
v["play"] = json!({ "packageName": pkg });
|
||||||
|
}
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn accounts(&self) -> Vec<&str> {
|
||||||
|
self.ios.iter().map(|i| i.0.as_str()).chain(self.android.iter().map(|a| a.0.as_str())).collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Pair {
|
||||||
|
pub ios: String,
|
||||||
|
pub android: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Link {
|
||||||
|
/// Store app key.
|
||||||
|
pub key: String,
|
||||||
|
/// Project id (app folder).
|
||||||
|
pub project: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct AppStudio {
|
||||||
|
/// Store app key or "project:<id>".
|
||||||
|
pub key: String,
|
||||||
|
pub studio: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The owner's corrections to automatic pairing, links of store apps to folders, studio moves and the ignore list.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct Overrides {
|
||||||
|
#[serde(default)]
|
||||||
|
pub pairs: Vec<Pair>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub unpairs: Vec<Pair>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub links: Vec<Link>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub app_studio: Vec<AppStudio>,
|
||||||
|
/// "app:<store app key>", "project:<id>" or "account:<id>".
|
||||||
|
#[serde(default)]
|
||||||
|
pub ignored: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const MAX_OVERRIDES: usize = 2000;
|
||||||
|
|
||||||
|
/// Checks every key; drops nothing silently (an error names the bad entry).
|
||||||
|
pub fn check_overrides(o: &Overrides) -> Result<(), String> {
|
||||||
|
if o.pairs.len() + o.unpairs.len() + o.links.len() + o.app_studio.len() + o.ignored.len() > MAX_OVERRIDES {
|
||||||
|
return Err("too many overrides".into());
|
||||||
|
}
|
||||||
|
for p in o.pairs.iter().chain(o.unpairs.iter()) {
|
||||||
|
match (StoreAppKey::parse(&p.ios)?, StoreAppKey::parse(&p.android)?) {
|
||||||
|
(StoreAppKey::Ios { .. }, StoreAppKey::Android { .. }) => {}
|
||||||
|
_ => return Err("pair: an iOS key and an Android key".into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for l in &o.links {
|
||||||
|
StoreAppKey::parse(&l.key)?;
|
||||||
|
if l.project.is_empty() || l.project.len() > 64 {
|
||||||
|
return Err("link: project id".into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for a in &o.app_studio {
|
||||||
|
if let Some(p) = a.key.strip_prefix("project:") {
|
||||||
|
if p.is_empty() || p.len() > 64 {
|
||||||
|
return Err("app studio: project id".into());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
StoreAppKey::parse(&a.key)?;
|
||||||
|
}
|
||||||
|
if a.studio.is_empty() || a.studio.len() > 64 {
|
||||||
|
return Err("app studio: studio id".into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i in &o.ignored {
|
||||||
|
let ok = match i.split_once(':') {
|
||||||
|
Some(("app", k)) => StoreAppKey::parse(k).is_ok(),
|
||||||
|
Some(("account", id)) => is_account_id(id),
|
||||||
|
Some(("project", id)) => !id.is_empty() && id.len() <= 64,
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
if !ok {
|
||||||
|
return Err(format!("ignored: bad entry '{i}'"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct RefreshSettings {
|
||||||
|
/// Minutes between automatic store reads; 0 = off.
|
||||||
|
pub auto_minutes: u32,
|
||||||
|
pub on_launch: bool,
|
||||||
|
/// Apps read at the same time (1-8).
|
||||||
|
pub parallel: u8,
|
||||||
|
/// Read app icons from the stores when importing (an extra request per app).
|
||||||
|
pub icons: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct CacheSettings {
|
||||||
|
/// Saved reads older than this many days are dropped; 0 = keep.
|
||||||
|
pub keep_days: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct NotifySettings {
|
||||||
|
pub review_state: bool,
|
||||||
|
pub low_reviews: bool,
|
||||||
|
pub crash: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct Settings {
|
||||||
|
pub refresh: RefreshSettings,
|
||||||
|
pub cache: CacheSettings,
|
||||||
|
pub notify: NotifySettings,
|
||||||
|
/// Update channel (placeholder until the updater ships): stable | beta.
|
||||||
|
pub channel: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Settings {
|
||||||
|
fn default() -> Settings {
|
||||||
|
Settings {
|
||||||
|
refresh: RefreshSettings { auto_minutes: 0, on_launch: false, parallel: 4, icons: true },
|
||||||
|
cache: CacheSettings { keep_days: 30 },
|
||||||
|
notify: NotifySettings { review_state: true, low_reviews: true, crash: true },
|
||||||
|
channel: "stable".into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const AUTO_MINUTES: &[u32] = &[0, 15, 30, 60, 180, 720];
|
||||||
|
pub const KEEP_DAYS: &[u32] = &[0, 7, 30, 90, 365];
|
||||||
|
|
||||||
|
pub fn check_settings(s: &Settings) -> Result<(), String> {
|
||||||
|
if !AUTO_MINUTES.contains(&s.refresh.auto_minutes) {
|
||||||
|
return Err("refresh: 0 (off), 15, 30, 60, 180 or 720 minutes".into());
|
||||||
|
}
|
||||||
|
if !(1..=8).contains(&s.refresh.parallel) {
|
||||||
|
return Err("parallel reads: 1 to 8".into());
|
||||||
|
}
|
||||||
|
if !KEEP_DAYS.contains(&s.cache.keep_days) {
|
||||||
|
return Err("keep saved reads: 0 (always), 7, 30, 90 or 365 days".into());
|
||||||
|
}
|
||||||
|
if !["stable", "beta"].contains(&s.channel.as_str()) {
|
||||||
|
return Err("channel: stable or beta".into());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
@ -9,9 +9,9 @@ const FAKE_PEM: &str = "-----BEGIN PRIVATE KEY-----\nnot-a-real-key\n-----END PR
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn shown_metadata_carries_no_secret() {
|
fn shown_metadata_carries_no_secret() {
|
||||||
let a = Account { id: "abc".into(), label: "Studio Play".into(), kind: AccountKind::Play, created: "2026-10-10T00:00:00Z".into() };
|
let a = Account { id: "abc".into(), label: "Studio Play".into(), kind: AccountKind::Play, created: "2026-10-10T00:00:00Z".into(), studio: Some("s1".into()) };
|
||||||
let v = serde_json::to_value(&a).unwrap();
|
let v = serde_json::to_value(&a).unwrap();
|
||||||
assert_eq!(v.as_object().unwrap().keys().cloned().collect::<Vec<_>>(), vec!["created", "id", "kind", "label"]);
|
assert_eq!(v.as_object().unwrap().keys().cloned().collect::<Vec<_>>(), vec!["created", "id", "kind", "label", "studio"]);
|
||||||
assert_eq!(v["kind"], "play");
|
assert_eq!(v["kind"], "play");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -53,6 +53,7 @@ fn state_file_round_trip_is_atomic_and_tolerant() {
|
||||||
let st = State {
|
let st = State {
|
||||||
projects: vec![Project { id: "1".into(), path: "/games/a".into(), name: "A".into(), play_account: Some("p".into()), apple_account: None, added: "2026-10-10T00:00:00Z".into() }],
|
projects: vec![Project { id: "1".into(), path: "/games/a".into(), name: "A".into(), play_account: Some("p".into()), apple_account: None, added: "2026-10-10T00:00:00Z".into() }],
|
||||||
accounts: vec![],
|
accounts: vec![],
|
||||||
|
..State::default()
|
||||||
};
|
};
|
||||||
store::save(dir.path(), &st).unwrap();
|
store::save(dir.path(), &st).unwrap();
|
||||||
assert_eq!(store::load(dir.path()), st);
|
assert_eq!(store::load(dir.path()), st);
|
||||||
|
|
|
||||||
160
apps/desktop/src-tauri/tests/workspace.rs
Normal file
160
apps/desktop/src-tauri/tests/workspace.rs
Normal file
|
|
@ -0,0 +1,160 @@
|
||||||
|
//! Desktop D3: studios, store app keys and store-only targets, pairing / ignore overrides, settings, old state files.
|
||||||
|
use serde_json::json;
|
||||||
|
use storebound_desktop::cache::Cache;
|
||||||
|
use storebound_desktop::policy::{sanitize_js_call, Kind};
|
||||||
|
use storebound_desktop::store::{self, State};
|
||||||
|
use storebound_desktop::workspace::*;
|
||||||
|
|
||||||
|
const A1: &str = "0123456789abcdef";
|
||||||
|
const A2: &str = "fedcba9876543210";
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn studio_names_colours_and_logos() {
|
||||||
|
assert_eq!(check_studio_name(" Example Games ").unwrap(), "Example Games");
|
||||||
|
assert!(check_studio_name("").is_err());
|
||||||
|
assert!(check_studio_name(&"x".repeat(49)).is_err());
|
||||||
|
assert!(check_studio_name("a\nb").is_err());
|
||||||
|
for c in STUDIO_COLORS {
|
||||||
|
assert!(check_color(c).is_ok());
|
||||||
|
}
|
||||||
|
assert!(check_color("#ff0000").is_err());
|
||||||
|
assert!(check_color("red; background:url(x)").is_err());
|
||||||
|
assert!(logo_data_url(&[0x89, b'P', b'N', b'G', 1, 2]).unwrap().starts_with("data:image/png;base64,"));
|
||||||
|
assert!(logo_data_url(&[0xff, 0xd8, 0xff, 0]).unwrap().starts_with("data:image/jpeg;base64,"));
|
||||||
|
assert!(logo_data_url(b"RIFF\0\0\0\0WEBPVP8 ").unwrap().starts_with("data:image/webp;"));
|
||||||
|
assert!(logo_data_url(b"<svg onload=alert(1)>").is_err(), "no SVG (scripts) as a logo");
|
||||||
|
assert!(logo_data_url(&vec![0x89; LOGO_MAX + 1]).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn store_app_keys() {
|
||||||
|
assert_eq!(StoreAppKey::parse(&format!("ios:{A1}:6400000101")).unwrap(), StoreAppKey::Ios { account: A1.into(), app_id: "6400000101".into() });
|
||||||
|
assert_eq!(StoreAppKey::parse(&format!("android:{A2}:com.example.puzzle")).unwrap().account(), A2);
|
||||||
|
for bad in [
|
||||||
|
format!("ios:{A1}:com.example.puzzle"),
|
||||||
|
format!("android:{A1}:6400000101"),
|
||||||
|
"ios:nothex0123456789:1".to_string(),
|
||||||
|
format!("mac:{A1}:1"),
|
||||||
|
format!("android:{A1}:com.example.puzzle/../x"),
|
||||||
|
format!("android:{A1}:.example"),
|
||||||
|
format!("ios:{}:1", A1.to_uppercase()),
|
||||||
|
] {
|
||||||
|
assert!(StoreAppKey::parse(&bad).is_err(), "{bad}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn store_only_targets_become_virtual_projects_with_store_ids_only() {
|
||||||
|
let t = StoreTarget::parse(&format!("store:ios:{A1}:6400000101:com.example.puzzle;android:{A2}:com.example.puzzle")).unwrap();
|
||||||
|
assert_eq!(t.accounts(), vec![A1, A2]);
|
||||||
|
assert_eq!(
|
||||||
|
t.virtual_project(),
|
||||||
|
json!({ "name": "com.example.puzzle", "apple": { "bundleId": "com.example.puzzle", "appId": "6400000101" }, "play": { "packageName": "com.example.puzzle" } })
|
||||||
|
);
|
||||||
|
let only = StoreTarget::parse(&format!("store:android:{A2}:com.example.runner")).unwrap();
|
||||||
|
assert_eq!(only.virtual_project(), json!({ "name": "com.example.runner", "play": { "packageName": "com.example.runner" } }));
|
||||||
|
for bad in [
|
||||||
|
"store:".to_string(),
|
||||||
|
"ios:x".to_string(),
|
||||||
|
format!("store:ios:{A1}:6400000101"),
|
||||||
|
format!("store:ios:{A1}:6400000101:com.example.a;ios:{A1}:6400000102:com.example.b"),
|
||||||
|
format!("store:android:{A2}:com.example.a;android:{A2}:com.example.b"),
|
||||||
|
format!("store:android:{A2}:com.example.a;path:/etc"),
|
||||||
|
format!("store:ios:{A1}:6400000101:../../etc"),
|
||||||
|
format!("store:android:{A2}:com.example.a;{}", "x".repeat(400)),
|
||||||
|
] {
|
||||||
|
assert!(StoreTarget::parse(&bad).is_err(), "{bad}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn overrides_are_checked_entry_by_entry() {
|
||||||
|
let ok = Overrides {
|
||||||
|
pairs: vec![Pair { ios: format!("ios:{A1}:6400000101"), android: format!("android:{A2}:com.example.puzzle") }],
|
||||||
|
unpairs: vec![Pair { ios: format!("ios:{A1}:6400000102"), android: format!("android:{A2}:com.example.notes") }],
|
||||||
|
links: vec![Link { key: format!("ios:{A1}:6400000103"), project: "p1".into() }],
|
||||||
|
app_studio: vec![AppStudio { key: format!("android:{A2}:com.example.runner"), studio: "s1".into() }, AppStudio { key: "project:p1".into(), studio: "s2".into() }],
|
||||||
|
ignored: vec![format!("app:ios:{A1}:6400000104"), format!("account:{A2}"), "project:p9".into()],
|
||||||
|
};
|
||||||
|
assert!(check_overrides(&ok).is_ok());
|
||||||
|
let mut swapped = ok.clone();
|
||||||
|
swapped.pairs = vec![Pair { ios: format!("android:{A2}:com.example.puzzle"), android: format!("ios:{A1}:6400000101") }];
|
||||||
|
assert!(check_overrides(&swapped).is_err());
|
||||||
|
for bad in ["app:ios:x:1", "account:short", "project:", "everything", "app:"] {
|
||||||
|
let mut o = ok.clone();
|
||||||
|
o.ignored.push(bad.into());
|
||||||
|
assert!(check_overrides(&o).is_err(), "{bad}");
|
||||||
|
}
|
||||||
|
let many = Overrides { ignored: (0..=MAX_OVERRIDES).map(|i| format!("project:p{i}")).collect(), ..Default::default() };
|
||||||
|
assert!(check_overrides(&many).is_err());
|
||||||
|
// camelCase on the wire
|
||||||
|
let v = serde_json::to_value(&ok).unwrap();
|
||||||
|
assert!(v.get("appStudio").is_some());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn settings_have_safe_defaults_and_bounds() {
|
||||||
|
let d = Settings::default();
|
||||||
|
assert!(check_settings(&d).is_ok());
|
||||||
|
assert_eq!((d.refresh.auto_minutes, d.refresh.on_launch, d.refresh.parallel, d.cache.keep_days, d.channel.as_str()), (0, false, 4, 30, "stable"));
|
||||||
|
let mut s = d.clone();
|
||||||
|
s.refresh.parallel = 0;
|
||||||
|
assert!(check_settings(&s).is_err());
|
||||||
|
s = d.clone();
|
||||||
|
s.refresh.parallel = 9;
|
||||||
|
assert!(check_settings(&s).is_err());
|
||||||
|
s = d.clone();
|
||||||
|
s.refresh.auto_minutes = 1;
|
||||||
|
assert!(check_settings(&s).is_err(), "no tight polling of the store APIs");
|
||||||
|
s = d.clone();
|
||||||
|
s.cache.keep_days = 3;
|
||||||
|
assert!(check_settings(&s).is_err());
|
||||||
|
s = d;
|
||||||
|
s.channel = "nightly".into();
|
||||||
|
assert!(check_settings(&s).is_err());
|
||||||
|
let v = serde_json::to_value(Settings::default()).unwrap();
|
||||||
|
assert_eq!(v["refresh"]["autoMinutes"], 0);
|
||||||
|
assert_eq!(v["cache"]["keepDays"], 30);
|
||||||
|
assert_eq!(v["notify"]["lowReviews"], true);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_d2_state_file_still_loads_with_empty_d3_parts() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let d2 = json!({
|
||||||
|
"projects": [{ "id": "p1", "path": "/x", "name": "X", "playAccount": null, "appleAccount": null, "added": "2026-10-01T00:00:00Z" }],
|
||||||
|
"accounts": [{ "id": A1, "label": "Play", "kind": "play", "created": "2026-10-01T00:00:00Z" }]
|
||||||
|
});
|
||||||
|
std::fs::write(dir.path().join(store::FILE), d2.to_string()).unwrap();
|
||||||
|
let st = store::load(dir.path());
|
||||||
|
assert_eq!(st.projects.len(), 1);
|
||||||
|
assert_eq!(st.accounts[0].studio, None);
|
||||||
|
assert!(st.studios.is_empty());
|
||||||
|
assert_eq!(st.overrides, Overrides::default());
|
||||||
|
assert_eq!(st.settings, Settings::default());
|
||||||
|
store::save(dir.path(), &st).unwrap();
|
||||||
|
assert_eq!(store::load(dir.path()), st);
|
||||||
|
assert_eq!(State::default().settings.refresh.parallel, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn account_reads_are_the_hosts() {
|
||||||
|
// the window cannot call apps.list / account.check directly: only the account commands (one key per call)
|
||||||
|
assert!(sanitize_js_call("apps.list", Some(Kind::Account), &json!({ "credentials": {} })).is_err());
|
||||||
|
assert!(sanitize_js_call("account.check", Some(Kind::Account), &json!({})).is_err());
|
||||||
|
assert_eq!(Kind::parse("account"), Some(Kind::Account));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cache_info_and_pruning_by_age() {
|
||||||
|
let c = Cache::in_memory().unwrap();
|
||||||
|
c.put("p", "health", &json!({}), &json!({ "n": 1 }), "2026-01-01T00:00:00Z").unwrap();
|
||||||
|
c.put("p", "reviews.list", &json!({}), &json!({ "n": 2 }), "2026-10-01T00:00:00Z").unwrap();
|
||||||
|
c.put("acct:x", "apps.list", &json!({}), &json!({ "apps": [] }), "2026-10-10T00:00:00Z").unwrap();
|
||||||
|
let (rows, bytes, oldest) = c.info().unwrap();
|
||||||
|
assert_eq!((rows, oldest.as_deref()), (3, Some("2026-01-01T00:00:00Z")));
|
||||||
|
assert!(bytes > 0);
|
||||||
|
assert_eq!(c.prune_before("2026-09-01T00:00:00Z").unwrap(), 1);
|
||||||
|
assert!(c.get("p", "health", &json!({})).unwrap().is_none());
|
||||||
|
assert!(c.get("p", "reviews.list", &json!({})).unwrap().is_some());
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue