219 lines
11 KiB
Rust
219 lines
11 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 });
|
|
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)
|
|
}
|