365 lines
18 KiB
Rust
365 lines
18 KiB
Rust
//! The app folders of this machine, shared with the storebound CLI: `~/.storebound/projects.json`
|
|
//! (STOREBOUND_REGISTRY), the same file as `storebound apps folders` / `apps add` / `storebound desktop` / `ws`
|
|
//! (cli/lib/registry.ts). The list of folders is the registry's; the app keeps its per-folder extras (mapped accounts)
|
|
//! in state.json under the same id. `sync` runs at start, when the list is shown and before a deep link is handled;
|
|
//! adding, removing and locating a folder in the app write the registry too. The first start with a registry missing
|
|
//! writes the app's own list into it.
|
|
//! { "version": 1, "projects": [{ "id": "<16 hex>", "path": "/abs/folder", "name": "Star Dash", "added": "<iso>" }],
|
|
//! "storeApps": [{ "id": "<16 hex>", "store": "apple", "appId": "6400000000", "account": "<profile>", "name": "…" }] }
|
|
//! `storeApps` (written by `storebound apps add --store … --app-id …`) are apps live on a store with no project on this
|
|
//! machine: they join the app list of the account with that credential profile (`store_apps_cached`), so the
|
|
//! portfolio shows them read-only ("store only"). Writing the folder list keeps them.
|
|
use std::fs;
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use serde::{Deserialize, Serialize};
|
|
use serde_json::Value;
|
|
use sha2::{Digest, Sha256};
|
|
|
|
use crate::store::{Project, State};
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct Entry {
|
|
pub id: String,
|
|
pub path: String,
|
|
pub name: String,
|
|
#[serde(default)]
|
|
pub added: String,
|
|
}
|
|
|
|
pub fn default_file(home: Option<&Path>) -> PathBuf {
|
|
if let Some(f) = std::env::var_os("STOREBOUND_REGISTRY").filter(|f| !f.is_empty()) {
|
|
return PathBuf::from(f);
|
|
}
|
|
home.map(Path::to_path_buf).unwrap_or_default().join(".storebound").join("projects.json")
|
|
}
|
|
|
|
/// The CLI's id for a folder it adds: sha256("project:<path>"), 16 hex (cli/lib/registry.ts folderId).
|
|
pub fn folder_id(path: &str) -> String {
|
|
Sha256::digest(format!("project:{path}").as_bytes()).iter().take(8).map(|b| format!("{b:02x}")).collect()
|
|
}
|
|
|
|
fn hex16(s: &str) -> bool {
|
|
s.len() == 16 && s.chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
|
|
}
|
|
|
|
/// Parses the file (pure): entries without an absolute path or with a repeated path are dropped.
|
|
pub fn parse(text: &str) -> Vec<Entry> {
|
|
let Ok(v) = serde_json::from_str::<Value>(text) else { return vec![] };
|
|
let mut out: Vec<Entry> = vec![];
|
|
for p in v.get("projects").and_then(Value::as_array).into_iter().flatten() {
|
|
let Some(path) = p.get("path").and_then(Value::as_str) else { continue };
|
|
if !Path::new(path).is_absolute() || out.iter().any(|e| e.path == path) {
|
|
continue;
|
|
}
|
|
let id = p.get("id").and_then(Value::as_str).filter(|i| hex16(i) && !out.iter().any(|e| e.id == *i)).map(str::to_string).unwrap_or_else(|| folder_id(path));
|
|
let name = p.get("name").and_then(Value::as_str).filter(|n| !n.trim().is_empty()).map(str::to_string)
|
|
.unwrap_or_else(|| Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "App".into()));
|
|
out.push(Entry { id, path: path.to_string(), name, added: p.get("added").and_then(Value::as_str).unwrap_or_default().to_string() });
|
|
}
|
|
out
|
|
}
|
|
|
|
/// None = the file does not exist (first start); Some(list) otherwise (an unreadable file reads as empty).
|
|
pub fn read(file: &Path) -> Option<Vec<Entry>> {
|
|
match fs::read_to_string(file) {
|
|
Ok(t) => Some(parse(&t)),
|
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
|
|
Err(_) => Some(vec![]),
|
|
}
|
|
}
|
|
|
|
pub fn write(file: &Path, entries: &[Entry]) -> Result<(), String> {
|
|
if let Some(d) = file.parent() {
|
|
fs::create_dir_all(d).map_err(|e| e.to_string())?;
|
|
}
|
|
// the store-only entries the CLI wrote stay as they are
|
|
let keep = fs::read_to_string(file).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()).and_then(|v| v.get("storeApps").cloned()).filter(|s| s.as_array().is_some_and(|a| !a.is_empty()));
|
|
let mut doc = serde_json::json!({ "version": 1, "projects": entries });
|
|
// the folders' `ignored` flags (written by the CLI or by push_ignored) stay with their folder
|
|
let old = fs::read_to_string(file).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok());
|
|
if let (Some(old), Some(list)) = (old.as_ref().and_then(|o| o.get("projects")).and_then(Value::as_array), doc.get_mut("projects").and_then(Value::as_array_mut)) {
|
|
for e in list {
|
|
let ig = e.get("path").and_then(Value::as_str).and_then(|path| old.iter().find(|o| o.get("path").and_then(Value::as_str) == Some(path))).and_then(|o| o.get("ignored")).cloned();
|
|
if let (Some(ig), Some(o)) = (ig, e.as_object_mut()) {
|
|
o.insert("ignored".into(), ig);
|
|
}
|
|
}
|
|
}
|
|
if let Some(s) = keep {
|
|
doc["storeApps"] = s;
|
|
}
|
|
let text = serde_json::to_string_pretty(&doc).map_err(|e| e.to_string())? + "\n";
|
|
let tmp = file.with_extension(format!("tmp-{}", std::process::id()));
|
|
fs::write(&tmp, text).map_err(|e| e.to_string())?;
|
|
fs::rename(&tmp, file).map_err(|e| e.to_string())
|
|
}
|
|
|
|
/// An app that is live on a store with no project on this machine (cli/lib/registry.ts StoreOnlyApp).
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub struct StoreOnly {
|
|
pub id: String,
|
|
/// "apple" | "play"
|
|
pub store: String,
|
|
/// Apple: the numeric app id; Play: the package name.
|
|
pub app_id: String,
|
|
/// The credential profile that reads it; None = the account of that store when there is only one.
|
|
pub account: Option<String>,
|
|
pub name: String,
|
|
pub bundle_id: Option<String>,
|
|
}
|
|
|
|
/// The store-only entries of the file's text (pure): malformed ones are dropped.
|
|
pub fn parse_store_apps(text: &str) -> Vec<StoreOnly> {
|
|
let Ok(v) = serde_json::from_str::<Value>(text) else { return vec![] };
|
|
let mut out: Vec<StoreOnly> = vec![];
|
|
for x in v.get("storeApps").and_then(Value::as_array).into_iter().flatten() {
|
|
let s = |k: &str| x.get(k).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_string);
|
|
let (Some(store), Some(app_id)) = (s("store"), s("appId")) else { continue };
|
|
let ok = match store.as_str() {
|
|
"apple" => app_id.len() >= 6 && app_id.len() <= 12 && app_id.chars().all(|c| c.is_ascii_digit()),
|
|
"play" => app_id.contains('.') && app_id.chars().all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_'),
|
|
_ => false,
|
|
};
|
|
if !ok || out.iter().any(|o| o.store == store && o.app_id == app_id) {
|
|
continue;
|
|
}
|
|
let id: String = Sha256::digest(format!("store:{store}:{app_id}").as_bytes()).iter().take(8).map(|b| format!("{b:02x}")).collect();
|
|
let bundle_id = s("bundleId").or_else(|| (store == "play").then(|| app_id.clone()));
|
|
out.push(StoreOnly { id, name: s("name").unwrap_or_else(|| app_id.clone()), account: s("account"), bundle_id, store, app_id });
|
|
}
|
|
out
|
|
}
|
|
|
|
pub fn read_store_apps(file: &Path) -> Vec<StoreOnly> {
|
|
fs::read_to_string(file).map(|t| parse_store_apps(&t)).unwrap_or_default()
|
|
}
|
|
|
|
/// One account's app list (`apps.list` JSON, or None when never read) with the store-only entries of its profile
|
|
/// added (pure). `store` is "apple" | "play"; `only` = this is the only account of that store (entries that name no
|
|
/// profile go to it). The entries already in the list (same id) are left as the store reported them.
|
|
pub fn with_store_only(list: Option<Value>, store: &str, profile: Option<&str>, only: bool, apps: &[StoreOnly], at: &str) -> Option<Value> {
|
|
let mine: Vec<&StoreOnly> = apps.iter().filter(|a| a.store == store && (a.account.as_deref().is_some_and(|p| Some(p) == profile) || (a.account.is_none() && only))).collect();
|
|
if mine.is_empty() {
|
|
return list;
|
|
}
|
|
let ios = store == "apple";
|
|
let mut v = list.unwrap_or_else(|| serde_json::json!({ "store": if ios { "ios" } else { "android" }, "apps": [], "warnings": [], "at": at }));
|
|
if !v.get("apps").is_some_and(Value::is_array) {
|
|
v["apps"] = serde_json::json!([]);
|
|
}
|
|
let have: Vec<String> = v["apps"].as_array().map(|a| a.iter().filter_map(|x| x.get("id").and_then(Value::as_str).map(str::to_string)).collect()).unwrap_or_default();
|
|
for a in mine {
|
|
if have.contains(&a.app_id) {
|
|
continue;
|
|
}
|
|
let app = serde_json::json!({
|
|
"store": if ios { "ios" } else { "android" }, "id": a.app_id, "bundleId": a.bundle_id.clone().unwrap_or_default(), "name": a.name,
|
|
"platforms": [if ios { "IOS" } else { "ANDROID" }], "sku": null, "primaryLocale": null, "latest": null, "icon": null, "registered": true,
|
|
});
|
|
if let Some(list) = v["apps"].as_array_mut() {
|
|
list.push(app);
|
|
}
|
|
}
|
|
Some(v)
|
|
}
|
|
|
|
fn entry_of(p: &Project) -> Entry {
|
|
Entry { id: p.id.clone(), path: p.path.clone(), name: p.name.clone(), added: p.added.clone() }
|
|
}
|
|
|
|
/// Makes the app's folder list the registry's (pure on the values). A registry folder the app has (by path) keeps the
|
|
/// app's id, name and accounts; a new one comes in with the registry's id; a folder that left the registry leaves the
|
|
/// app (with its links, ignore entries and studio moves). Returns (changed state, the registry to write back if it
|
|
/// needs the app's ids or names).
|
|
pub fn merge(state: &mut State, reg: Option<Vec<Entry>>) -> (bool, Option<Vec<Entry>>) {
|
|
let Some(reg) = reg else {
|
|
// first start with a shared list: the app's folders become it
|
|
return (false, Some(state.projects.iter().map(entry_of).collect()));
|
|
};
|
|
let mut projects = Vec::with_capacity(reg.len());
|
|
let mut write_back = false;
|
|
for e in ® {
|
|
match state.projects.iter().find(|p| p.path == e.path) {
|
|
Some(p) => {
|
|
if p.id != e.id || p.name != e.name {
|
|
write_back = true;
|
|
}
|
|
projects.push(p.clone());
|
|
}
|
|
None => {
|
|
// an id the app already uses for another folder gets the CLI's id instead
|
|
let id = if state.projects.iter().any(|p| p.id == e.id) { folder_id(&e.path) } else { e.id.clone() };
|
|
write_back |= id != e.id;
|
|
projects.push(Project { id, path: e.path.clone(), name: e.name.clone(), play_account: None, apple_account: None, added: e.added.clone() });
|
|
}
|
|
}
|
|
}
|
|
let gone: Vec<String> = state.projects.iter().filter(|p| !projects.iter().any(|x| x.id == p.id)).map(|p| p.id.clone()).collect();
|
|
let changed = projects != state.projects;
|
|
for id in &gone {
|
|
let key = format!("project:{id}");
|
|
state.overrides.links.retain(|l| &l.project != id);
|
|
state.overrides.ignored.retain(|i| i != &key);
|
|
state.overrides.app_studio.retain(|a| a.key != key);
|
|
}
|
|
state.projects = projects;
|
|
(changed, if write_back { Some(state.projects.iter().map(entry_of).collect()) } else { None })
|
|
}
|
|
|
|
/// Reads the registry, merges, writes it back when needed. Returns whether the state changed.
|
|
pub fn sync(state: &mut State, file: &Path) -> Result<bool, String> {
|
|
let (changed, back) = merge(state, read(file));
|
|
if let Some(list) = back {
|
|
write(file, &list)?;
|
|
}
|
|
Ok(changed)
|
|
}
|
|
|
|
/// After the app changed its list (add, remove, locate): the registry gets the app's list, keeping folders another
|
|
/// tool added since the last sync.
|
|
pub fn publish(state: &State, file: &Path, removed: &[String]) -> Result<(), String> {
|
|
let mut list: Vec<Entry> = state.projects.iter().map(entry_of).collect();
|
|
for e in read(file).unwrap_or_default() {
|
|
if !list.iter().any(|x| x.path == e.path || x.id == e.id) && !removed.contains(&e.path) {
|
|
list.push(e);
|
|
}
|
|
}
|
|
write(file, &list)
|
|
}
|
|
|
|
// ---- ignored apps: the registry's `ignored` flags (cli/lib/registry.ts) <-> the app's ignore keys ----
|
|
// projects: "ignored": ["apple", "play"] (both = the whole app) <-> "project:<id>" (both) / "project:<id>:ios" / "project:<id>:android"
|
|
// storeApps: "ignored": ["apple"] <-> "app:ios:<account id>:<app id>" (android for play)
|
|
// The registry is the truth for the apps it lists: `pull_ignored` (start, list shown) replaces the app's keys for those
|
|
// apps with the registry's flags, `push_ignored` (the owner ignores or restores in the app) writes them back. Apps
|
|
// that are not in the registry (listed by a store account only) keep their keys in the app's state alone.
|
|
const SIDES: [&str; 2] = ["apple", "play"];
|
|
|
|
fn word_of(side: &str) -> &'static str {
|
|
if side == "apple" { "ios" } else { "android" }
|
|
}
|
|
|
|
fn sides_in(v: &Value) -> Vec<String> {
|
|
let have: Vec<&str> = v.get("ignored").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
|
|
SIDES.iter().filter(|s| have.contains(s)).map(|s| s.to_string()).collect()
|
|
}
|
|
|
|
fn is_project_key_of(k: &str, id: &str) -> bool {
|
|
k == format!("project:{id}") || k.starts_with(&format!("project:{id}:"))
|
|
}
|
|
|
|
/// The ignore keys of one folder for its ignored store sides (pure).
|
|
pub fn project_keys(id: &str, sides: &[String]) -> Vec<String> {
|
|
if SIDES.iter().all(|s| sides.iter().any(|x| x == s)) {
|
|
return vec![format!("project:{id}")];
|
|
}
|
|
sides.iter().filter(|s| SIDES.contains(&s.as_str())).map(|s| format!("project:{id}:{}", word_of(s))).collect()
|
|
}
|
|
|
|
/// The ignored store sides of a folder, from the app's ignore keys (pure).
|
|
pub fn project_sides(keys: &[String], id: &str) -> Vec<String> {
|
|
let mut on = [false, false];
|
|
for k in keys {
|
|
if *k == format!("project:{id}") {
|
|
on = [true, true];
|
|
} else if *k == format!("project:{id}:ios") {
|
|
on[0] = true;
|
|
} else if *k == format!("project:{id}:android") {
|
|
on[1] = true;
|
|
}
|
|
}
|
|
SIDES.iter().enumerate().filter(|(i, _)| on[*i]).map(|(_, s)| s.to_string()).collect()
|
|
}
|
|
|
|
/// Whether an ignore key "app:<ios|android>:<account>:<app id>" is this store app (pure).
|
|
pub fn app_key_matches(k: &str, store: &str, app_id: &str) -> bool {
|
|
let Some(rest) = k.strip_prefix("app:") else { return false };
|
|
rest.split(':').next() == Some(word_of(store)) && rest.rsplit(':').next() == Some(app_id)
|
|
}
|
|
|
|
/// The account (id) that reads a store-only entry: the one with its credential profile, else the only account of that store.
|
|
pub fn account_for(accounts: &[crate::accounts::Account], store: &str, profile: Option<&str>) -> Option<String> {
|
|
use crate::accounts::AccountKind;
|
|
let kind = if store == "apple" { AccountKind::Apple } else { AccountKind::Play };
|
|
let of_kind: Vec<_> = accounts.iter().filter(|a| a.kind == kind).collect();
|
|
match profile {
|
|
Some(p) => of_kind.iter().find(|a| a.profile.as_deref() == Some(p)).map(|a| a.id.clone()),
|
|
None => (of_kind.len() == 1).then(|| of_kind[0].id.clone()),
|
|
}
|
|
}
|
|
|
|
fn parse_doc(file: &Path) -> Option<Value> {
|
|
serde_json::from_str::<Value>(&fs::read_to_string(file).ok()?).ok()
|
|
}
|
|
|
|
/// Registry flags -> the app's ignore keys. True when the keys changed.
|
|
pub fn pull_ignored(state: &mut State, file: &Path) -> bool {
|
|
let Some(doc) = parse_doc(file) else { return false };
|
|
let before = state.overrides.ignored.clone();
|
|
let mut keys = before.clone();
|
|
for p in doc.get("projects").and_then(Value::as_array).into_iter().flatten() {
|
|
let Some(path) = p.get("path").and_then(Value::as_str) else { continue };
|
|
let Some(id) = state.projects.iter().find(|x| x.path == path).map(|x| x.id.clone()) else { continue };
|
|
keys.retain(|k| !is_project_key_of(k, &id));
|
|
keys.extend(project_keys(&id, &sides_in(p)));
|
|
}
|
|
for a in doc.get("storeApps").and_then(Value::as_array).into_iter().flatten() {
|
|
let (Some(store), Some(app_id)) = (a.get("store").and_then(Value::as_str), a.get("appId").and_then(Value::as_str)) else { continue };
|
|
let Some(acct) = account_for(&state.accounts, store, a.get("account").and_then(Value::as_str)) else { continue };
|
|
keys.retain(|k| !app_key_matches(k, store, app_id));
|
|
if sides_in(a).iter().any(|s| s == store) {
|
|
keys.push(format!("app:{}:{acct}:{app_id}", word_of(store)));
|
|
}
|
|
}
|
|
let mut seen = std::collections::HashSet::new();
|
|
keys.retain(|k| seen.insert(k.clone()));
|
|
if keys == before {
|
|
return false;
|
|
}
|
|
state.overrides.ignored = keys;
|
|
true
|
|
}
|
|
|
|
/// The app's ignore keys -> registry flags (only the apps the registry lists). Writes when something changed.
|
|
pub fn push_ignored(state: &State, file: &Path) -> Result<bool, String> {
|
|
let Some(mut doc) = parse_doc(file) else { return Ok(false) };
|
|
let keys = &state.overrides.ignored;
|
|
let mut changed = false;
|
|
let mut set = |entry: &mut Value, sides: Vec<String>| {
|
|
if sides_in(entry) == sides {
|
|
return;
|
|
}
|
|
changed = true;
|
|
if let Some(o) = entry.as_object_mut() {
|
|
if sides.is_empty() {
|
|
o.remove("ignored");
|
|
} else {
|
|
o.insert("ignored".into(), serde_json::json!(sides));
|
|
}
|
|
}
|
|
};
|
|
if let Some(list) = doc.get_mut("projects").and_then(Value::as_array_mut) {
|
|
for p in list {
|
|
let Some(id) = p.get("path").and_then(Value::as_str).and_then(|path| state.projects.iter().find(|x| x.path == path)).map(|x| x.id.clone()) else { continue };
|
|
set(p, project_sides(keys, &id));
|
|
}
|
|
}
|
|
if let Some(list) = doc.get_mut("storeApps").and_then(Value::as_array_mut) {
|
|
for a in list {
|
|
let (Some(store), Some(app_id)) = (a.get("store").and_then(Value::as_str).map(str::to_string), a.get("appId").and_then(Value::as_str).map(str::to_string)) else { continue };
|
|
if account_for(&state.accounts, &store, a.get("account").and_then(Value::as_str)).is_none() {
|
|
continue;
|
|
}
|
|
let on = keys.iter().any(|k| app_key_matches(k, &store, &app_id));
|
|
set(a, if on { vec![store] } else { vec![] });
|
|
}
|
|
}
|
|
if changed {
|
|
let text = serde_json::to_string_pretty(&doc).map_err(|e| e.to_string())? + "\n";
|
|
let tmp = file.with_extension(format!("tmp-{}", std::process::id()));
|
|
fs::write(&tmp, text).map_err(|e| e.to_string())?;
|
|
fs::rename(&tmp, file).map_err(|e| e.to_string())?;
|
|
}
|
|
Ok(changed)
|
|
}
|