Skip to content

Open-source download manager & offline media toolbox for YouTube, music, social media, learning platforms & 1,800+ sites. Built with Tauri 2.0, Rust & Svelte.

feat(pets): implement download and install functionality for pets

Tonhob7f02dda1ce7
diff --git a/src-tauri/src/pets/download.rs b/src-tauri/src/pets/download.rs
new file mode 100644
index 00000000..48ae62bb
--- /dev/null
+++ b/src-tauri/src/pets/download.rs
@@ -0,0 +1,201 @@
+use std::time::Duration;
+
+use serde::{Deserialize, Serialize};
+
+const MANIFEST_URL: &str = "https://petdex.crafter.run/api/manifest";
+const FALLBACK_BUNDLE_URL: &str =
+ "https://pub-94495283df974cfea5e98d6a9e3fa462.r2.dev/packs/petdex-approved.zip";
+const USER_AGENT: &str = "omniget-pets/1.0";
+
+const MIN_SPRITE_BYTES: usize = 10 * 1024;
+const MAX_SPRITE_BYTES: usize = 5 * 1024 * 1024;
+const MAX_PET_JSON_BYTES: usize = 64 * 1024;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct RemoteManifest {
+ #[serde(rename = "generatedAt")]
+ pub generated_at: Option<String>,
+ pub total: u32,
+ #[serde(default)]
+ pub featured: u32,
+ #[serde(rename = "allPetsPackPath")]
+ pub all_pets_pack_path: Option<String>,
+ pub pets: Vec<RemotePet>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct RemotePet {
+ pub slug: String,
+ #[serde(rename = "displayName")]
+ pub display_name: String,
+ #[serde(default)]
+ pub description: Option<String>,
+ #[serde(default)]
+ pub kind: Option<String>,
+ #[serde(default)]
+ pub vibes: Vec<String>,
+ #[serde(default)]
+ pub tags: Vec<String>,
+ #[serde(default)]
+ pub featured: bool,
+ #[serde(default, rename = "spritesheetUrl")]
+ pub spritesheet_url: Option<String>,
+ #[serde(default, rename = "petJsonUrl")]
+ pub pet_json_url: Option<String>,
+ #[serde(default, rename = "zipUrl")]
+ pub zip_url: Option<String>,
+ #[serde(default, rename = "submittedBy")]
+ pub submitted_by: Option<String>,
+}
+
+fn build_client(timeout_secs: u64) -> reqwest::Result<reqwest::Client> {
+ reqwest::Client::builder()
+ .user_agent(USER_AGENT)
+ .timeout(Duration::from_secs(timeout_secs))
+ .connect_timeout(Duration::from_secs(30))
+ .build()
+}
+
+fn is_retryable(status: Option<u16>) -> bool {
+ match status {
+ Some(s) => s >= 500 || s == 408 || s == 429,
+ None => true,
+ }
+}
+
+async fn with_retry<F, Fut, T>(label: &str, mut op: F) -> anyhow::Result<T>
+where
+ F: FnMut() -> Fut,
+ Fut: std::future::Future<Output = Result<T, RetryError>>,
+{
+ let mut backoff_ms: u64 = 1000;
+ for attempt in 0..3 {
+ match op().await {
+ Ok(v) => return Ok(v),
+ Err(err) => {
+ let last = attempt == 2;
+ if last || !err.retryable {
+ return Err(anyhow::anyhow!("{}: {}", label, err.message));
+ }
+ tokio::time::sleep(Duration::from_millis(backoff_ms)).await;
+ backoff_ms *= 2;
+ }
+ }
+ }
+ anyhow::bail!("{}: retry exhausted", label)
+}
+
+pub struct RetryError {
+ pub message: String,
+ pub retryable: bool,
+}
+
+pub async fn fetch_manifest() -> anyhow::Result<RemoteManifest> {
+ with_retry("fetch_manifest", || async {
+ let client = build_client(60).map_err(|e| RetryError {
+ message: e.to_string(),
+ retryable: true,
+ })?;
+ let res = client.get(MANIFEST_URL).send().await.map_err(|e| RetryError {
+ message: e.to_string(),
+ retryable: true,
+ })?;
+ let status = res.status();
+ if !status.is_success() {
+ let retryable = is_retryable(Some(status.as_u16()));
+ return Err(RetryError {
+ message: format!("status {}", status),
+ retryable,
+ });
+ }
+ let text = res.text().await.map_err(|e| RetryError {
+ message: e.to_string(),
+ retryable: true,
+ })?;
+ let parsed: RemoteManifest = serde_json::from_str(&text).map_err(|e| RetryError {
+ message: format!("parse: {}", e),
+ retryable: false,
+ })?;
+ Ok(parsed)
+ })
+ .await
+}
+
+pub fn fallback_bundle_url() -> &'static str {
+ FALLBACK_BUNDLE_URL
+}
+
+pub async fn fetch_bytes(url: &str, max_bytes: usize, timeout_secs: u64) -> anyhow::Result<Vec<u8>> {
+ let label = format!("GET {}", url);
+ with_retry(&label, || async {
+ let client = build_client(timeout_secs).map_err(|e| RetryError {
+ message: e.to_string(),
+ retryable: true,
+ })?;
+ let res = client.get(url).send().await.map_err(|e| RetryError {
+ message: e.to_string(),
+ retryable: true,
+ })?;
+ let status = res.status();
+ if !status.is_success() {
+ let retryable = is_retryable(Some(status.as_u16()));
+ return Err(RetryError {
+ message: format!("status {}", status),
+ retryable,
+ });
+ }
+ let bytes = res.bytes().await.map_err(|e| RetryError {
+ message: e.to_string(),
+ retryable: true,
+ })?;
+ if bytes.len() > max_bytes {
+ return Err(RetryError {
+ message: format!("payload {} > limit {}", bytes.len(), max_bytes),
+ retryable: false,
+ });
+ }
+ Ok(bytes.to_vec())
+ })
+ .await
+}
+
+pub async fn fetch_pet_json(url: &str) -> anyhow::Result<Vec<u8>> {
+ fetch_bytes(url, MAX_PET_JSON_BYTES, 60).await
+}
+
+pub async fn fetch_spritesheet(url: &str) -> anyhow::Result<Vec<u8>> {
+ let bytes = fetch_bytes(url, MAX_SPRITE_BYTES, 60).await?;
+ if bytes.len() < MIN_SPRITE_BYTES {
+ anyhow::bail!("spritesheet too small ({} bytes)", bytes.len());
+ }
+ if !is_webp_or_png(&bytes) {
+ anyhow::bail!("spritesheet is not webp or png");
+ }
+ Ok(bytes)
+}
+
+fn is_webp_or_png(b: &[u8]) -> bool {
+ if b.len() < 12 {
+ return false;
+ }
+ if &b[0..4] == b"RIFF" && &b[8..12] == b"WEBP" {
+ return true;
+ }
+ if b.starts_with(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]) {
+ return true;
+ }
+ false
+}
+
+pub async fn fetch_bundle_zip(url: &str) -> anyhow::Result<Vec<u8>> {
+ fetch_bytes(url, 200 * 1024 * 1024, 600).await
+}
+
+pub fn extract_ext_from_url(url: &str) -> &'static str {
+ let lower = url.to_ascii_lowercase();
+ if lower.ends_with(".png") {
+ "png"
+ } else {
+ "webp"
+ }
+}
diff --git a/src-tauri/src/pets/install.rs b/src-tauri/src/pets/install.rs
new file mode 100644
index 00000000..8eaf63d5
--- /dev/null
+++ b/src-tauri/src/pets/install.rs
@@ -0,0 +1,634 @@
+use std::collections::BTreeMap;
+use std::io::{Cursor, Read, Write};
+use std::path::Path;
+use std::sync::Arc;
+
+use futures::stream::{FuturesUnordered, StreamExt};
+use serde::Serialize;
+use tauri::{AppHandle, Emitter};
+use tokio::sync::Mutex;
+
+use super::download::{
+ extract_ext_from_url, fallback_bundle_url, fetch_bundle_zip, fetch_pet_json,
+ fetch_spritesheet, RemoteManifest, RemotePet,
+};
+use super::manifest::{
+ discover_local_pets, ensure_root, load, manifest_path, now_iso, pet_dir, save_atomic,
+ LocalManifest, LocalPetEntry,
+};
+
+#[derive(Debug, Serialize, Clone)]
+pub struct DiffReport {
+ pub new_remote: Vec<String>,
+ pub in_both: Vec<String>,
+ pub only_local: Vec<String>,
+ pub total_remote: u32,
+ pub total_local: u32,
+}
+
+#[derive(Debug, Serialize, Clone)]
+pub struct InstallReport {
+ pub added: Vec<String>,
+ pub skipped: Vec<String>,
+ pub failed: Vec<FailedInstall>,
+ pub total_bytes: u64,
+ pub duration_ms: u64,
+}
+
+#[derive(Debug, Serialize, Clone)]
+pub struct FailedInstall {
+ pub slug: String,
+ pub reason: String,
+}
+
+#[derive(Debug, Serialize, Clone)]
+pub struct LocalIndex {
+ pub pets: Vec<LocalPetEntry>,
+ pub last_synced_at: Option<String>,
+ pub total: usize,
+}
+
+#[derive(Debug, Serialize, Clone)]
+pub struct ProgressEvent<'a> {
+ pub slug: &'a str,
+ pub current: u32,
+ pub total: u32,
+ pub bytes_downloaded: u64,
+ pub bytes_total: u64,
+}
+
+#[derive(Debug, Serialize, Clone)]
+pub struct StartedEvent {
+ pub kind: String,
+ pub expected: u32,
+}
+
+pub fn refresh_index(app_data_dir: &Path) -> std::io::Result<LocalIndex> {
+ let _ = ensure_root(app_data_dir)?;
+ let mut manifest = load(app_data_dir);
+ discover_local_pets(app_data_dir, &mut manifest)?;
+ save_atomic(app_data_dir, &manifest)?;
+ let mut pets: Vec<LocalPetEntry> = manifest.pets.values().cloned().collect();
+ pets.sort_by(|a, b| a.display_name.to_lowercase().cmp(&b.display_name.to_lowercase()));
+ let total = pets.len();
+ Ok(LocalIndex {
+ pets,
+ last_synced_at: manifest.last_synced_at.clone(),
+ total,
+ })
+}
+
+pub fn diff(local: &LocalIndex, remote: &RemoteManifest) -> DiffReport {
+ let local_set: std::collections::HashSet<String> =
+ local.pets.iter().map(|p| p.slug.clone()).collect();
+ let remote_set: std::collections::HashSet<String> =
+ remote.pets.iter().map(|p| p.slug.clone()).collect();
+ let mut new_remote: Vec<String> = remote
+ .pets
+ .iter()
+ .filter(|p| !local_set.contains(&p.slug))
+ .map(|p| p.slug.clone())
+ .collect();
+ let mut in_both: Vec<String> = remote
+ .pets
+ .iter()
+ .filter(|p| local_set.contains(&p.slug))
+ .map(|p| p.slug.clone())
+ .collect();
+ let mut only_local: Vec<String> = local
+ .pets
+ .iter()
+ .filter(|p| !remote_set.contains(&p.slug))
+ .map(|p| p.slug.clone())
+ .collect();
+ new_remote.sort();
+ in_both.sort();
+ only_local.sort();
+ DiffReport {
+ new_remote,
+ in_both,
+ only_local,
+ total_remote: remote.total,
+ total_local: local.pets.len() as u32,
+ }
+}
+
+async fn install_one(
+ app_data_dir: Arc<std::path::PathBuf>,
+ pet: RemotePet,
+ overwrite: bool,
+) -> Result<(String, u64, LocalPetEntry), FailedInstall> {
+ let slug = pet.slug.clone();
+ let dir = pet_dir(app_data_dir.as_path(), &slug);
+ if dir.exists() && !overwrite {
+ return Err(FailedInstall {
+ slug,
+ reason: "already installed".to_string(),
+ });
+ }
+ let sprite_url = match pet.spritesheet_url.as_ref() {
+ Some(u) => u.clone(),
+ None => {
+ return Err(FailedInstall {
+ slug,
+ reason: "missing spritesheet url".to_string(),
+ });
+ }
+ };
+ let pet_json_url = match pet.pet_json_url.as_ref() {
+ Some(u) => u.clone(),
+ None => {
+ return Err(FailedInstall {
+ slug,
+ reason: "missing pet.json url".to_string(),
+ });
+ }
+ };
+
+ let pet_json_bytes = match fetch_pet_json(&pet_json_url).await {
+ Ok(b) => b,
+ Err(e) => {
+ return Err(FailedInstall {
+ slug,
+ reason: format!("pet.json: {}", e),
+ });
+ }
+ };
+ if serde_json::from_slice::<serde_json::Value>(&pet_json_bytes).is_err() {
+ return Err(FailedInstall {
+ slug,
+ reason: "pet.json invalid".to_string(),
+ });
+ }
+
+ let sprite_bytes = match fetch_spritesheet(&sprite_url).await {
+ Ok(b) => b,
+ Err(e) => {
+ return Err(FailedInstall {
+ slug,
+ reason: format!("sprite: {}", e),
+ });
+ }
+ };
+
+ if let Err(e) = std::fs::create_dir_all(&dir) {
+ return Err(FailedInstall {
+ slug,
+ reason: format!("mkdir: {}", e),
+ });
+ }
+ let sprite_ext = extract_ext_from_url(&sprite_url);
+ let sprite_path = dir.join(format!("spritesheet.{}", sprite_ext));
+ let pet_json_path = dir.join("pet.json");
+ let metadata_path = dir.join("metadata.json");
+ if let Err(e) = atomic_write(&sprite_path, &sprite_bytes) {
+ return Err(FailedInstall {
+ slug,
+ reason: format!("sprite write: {}", e),
+ });
+ }
+ if let Err(e) = atomic_write(&pet_json_path, &pet_json_bytes) {
+ return Err(FailedInstall {
+ slug,
+ reason: format!("pet.json write: {}", e),
+ });
+ }
+ let metadata = serde_json::json!({
+ "id": &slug,
+ "slug": &slug,
+ "displayName": &pet.display_name,
+ "description": pet.description.clone().unwrap_or_default(),
+ "spritesheetPath": format!("/pets/{}/spritesheet.{}", slug, sprite_ext),
+ "petJsonPath": format!("/pets/{}/pet.json", slug),
+ "kind": pet.kind.clone().unwrap_or_default(),
+ "vibes": pet.vibes.clone(),
+ "tags": pet.tags.clone(),
+ "featured": pet.featured,
+ "submittedBy": pet.submitted_by.clone(),
+ "importedAt": now_iso(),
+ });
+ let metadata_bytes = serde_json::to_vec_pretty(&metadata).unwrap_or_default();
+ let _ = atomic_write(&metadata_path, &metadata_bytes);
+
+ let bytes_total = sprite_bytes.len() as u64 + pet_json_bytes.len() as u64;
+ let mut sizes: BTreeMap<String, u64> = BTreeMap::new();
+ sizes.insert("spritesheet".into(), sprite_bytes.len() as u64);
+ sizes.insert("pet.json".into(), pet_json_bytes.len() as u64);
+ let entry = LocalPetEntry {
+ slug: slug.clone(),
+ display_name: pet.display_name.clone(),
+ source: "manifest".to_string(),
+ installed_at: now_iso(),
+ vibes: pet.vibes.clone(),
+ tags: pet.tags.clone(),
+ kind: pet.kind.clone(),
+ sprite_ext: sprite_ext.to_string(),
+ file_sizes: sizes,
+ remote_checked_at: Some(now_iso()),
+ };
+ Ok((slug, bytes_total, entry))
+}
+
+fn atomic_write(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+ let tmp = path.with_extension(format!(
+ "{}.tmp",
+ path.extension().and_then(|s| s.to_str()).unwrap_or("dat")
+ ));
+ {
+ let mut f = std::fs::File::create(&tmp)?;
+ f.write_all(bytes)?;
+ f.sync_all()?;
+ }
+ if path.exists() {
+ std::fs::remove_file(path)?;
+ }
+ std::fs::rename(&tmp, path)?;
+ Ok(())
+}
+
+pub async fn install_missing(
+ app: AppHandle,
+ app_data_dir: std::path::PathBuf,
+ remote: RemoteManifest,
+ requested: Option<Vec<String>>,
+) -> InstallReport {
+ let started = std::time::Instant::now();
+ let _ = ensure_root(&app_data_dir);
+ let manifest_arc: Arc<Mutex<LocalManifest>> = Arc::new(Mutex::new(load(&app_data_dir)));
+ let app_data_arc = Arc::new(app_data_dir.clone());
+
+ let local_known: std::collections::HashSet<String> = {
+ let g = manifest_arc.lock().await;
+ g.pets.keys().cloned().collect()
+ };
+
+ let target_pets: Vec<RemotePet> = remote
+ .pets
+ .into_iter()
+ .filter(|p| {
+ if local_known.contains(&p.slug) {
+ return false;
+ }
+ match &requested {
+ Some(list) => list.iter().any(|s| s == &p.slug),
+ None => true,
+ }
+ })
+ .collect();
+
+ let total = target_pets.len() as u32;
+ let _ = app.emit(
+ "pets:sync:started",
+ StartedEvent {
+ kind: "incremental".to_string(),
+ expected: total,
+ },
+ );
+
+ let mut added: Vec<String> = Vec::new();
+ let mut skipped: Vec<String> = Vec::new();
+ let mut failed: Vec<FailedInstall> = Vec::new();
+ let mut total_bytes: u64 = 0;
+
+ let mut futures = FuturesUnordered::new();
+ let max_parallel = 4;
+
+ let mut iter = target_pets.into_iter();
+ for _ in 0..max_parallel {
+ if let Some(pet) = iter.next() {
+ let app_data_arc = app_data_arc.clone();
+ futures.push(install_one(app_data_arc, pet, false));
+ }
+ }
+
+ let mut current: u32 = 0;
+ while let Some(result) = futures.next().await {
+ current += 1;
+ match result {
+ Ok((slug, bytes, entry)) => {
+ total_bytes += bytes;
+ let mut g = manifest_arc.lock().await;
+ g.pets.insert(slug.clone(), entry);
+ g.last_synced_at = Some(now_iso());
+ let _ = save_atomic(&app_data_dir, &g);
+ drop(g);
+ let _ = app.emit(
+ "pets:sync:progress",
+ ProgressEvent {
+ slug: &slug,
+ current,
+ total,
+ bytes_downloaded: total_bytes,
+ bytes_total: 0,
+ },
+ );
+ added.push(slug);
+ }
+ Err(err) => {
+ if err.reason == "already installed" {
+ skipped.push(err.slug);
+ } else {
+ let _ = app.emit(
+ "pets:sync:error",
+ serde_json::json!({
+ "slug": err.slug,
+ "message": err.reason,
+ "retryable": false,
+ }),
+ );
+ failed.push(err);
+ }
+ }
+ }
+ if let Some(pet) = iter.next() {
+ let app_data_arc = app_data_arc.clone();
+ futures.push(install_one(app_data_arc, pet, false));
+ }
+ }
+
+ {
+ let mut g = manifest_arc.lock().await;
+ g.last_synced_at = Some(now_iso());
+ g.last_remote_manifest_at = remote.generated_at.clone();
+ let _ = save_atomic(&app_data_dir, &g);
+ }
+
+ let report = InstallReport {
+ added,
+ skipped,
+ failed,
+ total_bytes,
+ duration_ms: started.elapsed().as_millis() as u64,
+ };
+ let _ = app.emit("pets:sync:finished", &report);
+ report
+}
+
+pub async fn install_bundle(
+ app: AppHandle,
+ app_data_dir: std::path::PathBuf,
+ remote: RemoteManifest,
+) -> InstallReport {
+ let started = std::time::Instant::now();
+ let _ = ensure_root(&app_data_dir);
+ let bundle_url = remote
+ .all_pets_pack_path
+ .clone()
+ .unwrap_or_else(|| fallback_bundle_url().to_string());
+ let _ = app.emit(
+ "pets:sync:started",
+ StartedEvent {
+ kind: "bundle".to_string(),
+ expected: remote.total,
+ },
+ );
+
+ let zip_bytes = match fetch_bundle_zip(&bundle_url).await {
+ Ok(b) => b,
+ Err(e) => {
+ let report = InstallReport {
+ added: vec![],
+ skipped: vec![],
+ failed: vec![FailedInstall {
+ slug: "bundle".to_string(),
+ reason: format!("bundle download: {}", e),
+ }],
+ total_bytes: 0,
+ duration_ms: started.elapsed().as_millis() as u64,
+ };
+ let _ = app.emit("pets:sync:finished", &report);
+ return report;
+ }
+ };
+
+ let mut manifest = load(&app_data_dir);
+ let local_known: std::collections::HashSet<String> = manifest.pets.keys().cloned().collect();
+ let mut added: Vec<String> = Vec::new();
+ let mut skipped: Vec<String> = Vec::new();
+ let mut failed: Vec<FailedInstall> = Vec::new();
+ let mut total_bytes: u64 = 0;
+
+ let result = (|| -> anyhow::Result<()> {
+ let cursor = Cursor::new(zip_bytes);
+ let mut archive = zip::ZipArchive::new(cursor)?;
+ let mut by_slug: std::collections::BTreeMap<String, Vec<(String, Vec<u8>)>> =
+ std::collections::BTreeMap::new();
+ for i in 0..archive.len() {
+ let mut entry = archive.by_index(i)?;
+ if !entry.is_file() {
+ continue;
+ }
+ let raw_name = match entry.enclosed_name() {
+ Some(n) => n.to_path_buf(),
+ None => continue,
+ };
+ let parts: Vec<String> = raw_name
+ .components()
+ .filter_map(|c| c.as_os_str().to_str().map(|s| s.to_string()))
+ .collect();
+ if parts.len() < 2 {
+ continue;
+ }
+ let slug = parts[parts.len() - 2].clone();
+ let file_name = parts[parts.len() - 1].clone();
+ let mut bytes: Vec<u8> = Vec::new();
+ entry.read_to_end(&mut bytes)?;
+ by_slug.entry(slug).or_default().push((file_name, bytes));
+ }
+
+ for (slug, files) in by_slug {
+ if local_known.contains(&slug) {
+ skipped.push(slug);
+ continue;
+ }
+ let dir = pet_dir(&app_data_dir, &slug);
+ if let Err(e) = std::fs::create_dir_all(&dir) {
+ failed.push(FailedInstall {
+ slug: slug.clone(),
+ reason: format!("mkdir: {}", e),
+ });
+ continue;
+ }
+ let mut sprite_ext = "webp".to_string();
+ let mut sizes: BTreeMap<String, u64> = BTreeMap::new();
+ let mut display_name = slug.clone();
+ let mut vibes: Vec<String> = Vec::new();
+ let mut tags: Vec<String> = Vec::new();
+ let mut kind: Option<String> = None;
+ let mut wrote_sprite = false;
+ for (name, bytes) in files {
+ let lower = name.to_lowercase();
+ let dest = dir.join(&name);
+ if lower == "spritesheet.webp" || lower == "spritesheet.png" {
+ sprite_ext = if lower.ends_with(".png") { "png".into() } else { "webp".into() };
+ if atomic_write(&dest, &bytes).is_ok() {
+ sizes.insert("spritesheet".into(), bytes.len() as u64);
+ wrote_sprite = true;
+ }
+ } else if lower == "pet.json" {
+ if atomic_write(&dest, &bytes).is_ok() {
+ sizes.insert("pet.json".into(), bytes.len() as u64);
+ if let Ok(v) = serde_json::from_slice::<serde_json::Value>(&bytes) {
+ if let Some(name) = v.get("displayName").and_then(|s| s.as_str()) {
+ display_name = name.to_string();
+ }
+ }
+ }
+ } else if lower == "metadata.json" {
+ if atomic_write(&dest, &bytes).is_ok() {
+ if let Ok(v) = serde_json::from_slice::<serde_json::Value>(&bytes) {
+ if let Some(name) = v.get("displayName").and_then(|s| s.as_str()) {
+ display_name = name.to_string();
+ }
+ if let Some(arr) = v.get("vibes").and_then(|s| s.as_array()) {
+ vibes = arr
+ .iter()
+ .filter_map(|x| x.as_str().map(|s| s.to_string()))
+ .collect();
+ }
+ if let Some(arr) = v.get("tags").and_then(|s| s.as_array()) {
+ tags = arr
+ .iter()
+ .filter_map(|x| x.as_str().map(|s| s.to_string()))
+ .collect();
+ }
+ if let Some(k) = v.get("kind").and_then(|s| s.as_str()) {
+ kind = Some(k.to_string());
+ }
+ }
+ }
+ } else {
+ let _ = atomic_write(&dest, &bytes);
+ }
+ total_bytes += bytes.len() as u64;
+ }
+ if !wrote_sprite {
+ failed.push(FailedInstall {
+ slug: slug.clone(),
+ reason: "no spritesheet in bundle entry".to_string(),
+ });
+ continue;
+ }
+ let entry = LocalPetEntry {
+ slug: slug.clone(),
+ display_name,
+ source: "bundle".to_string(),
+ installed_at: now_iso(),
+ vibes,
+ tags,
+ kind,
+ sprite_ext,
+ file_sizes: sizes,
+ remote_checked_at: Some(now_iso()),
+ };
+ manifest.pets.insert(slug.clone(), entry);
+ let _ = app.emit(
+ "pets:sync:progress",
+ ProgressEvent {
+ slug: &slug,
+ current: added.len() as u32 + 1,
+ total: remote.total,
+ bytes_downloaded: total_bytes,
+ bytes_total: 0,
+ },
+ );
+ added.push(slug);
+ let _ = save_atomic(&app_data_dir, &manifest);
+ }
+ Ok(())
+ })();
+
+ if let Err(e) = result {
+ failed.push(FailedInstall {
+ slug: "bundle".to_string(),
+ reason: format!("zip: {}", e),
+ });
+ }
+
+ manifest.last_synced_at = Some(now_iso());
+ manifest.last_remote_manifest_at = remote.generated_at.clone();
+ let _ = save_atomic(&app_data_dir, &manifest);
+
+ let report = InstallReport {
+ added,
+ skipped,
+ failed,
+ total_bytes,
+ duration_ms: started.elapsed().as_millis() as u64,
+ };
+ let _ = app.emit("pets:sync:finished", &report);
+ report
+}
+
+pub async fn force_refresh(
+ app: AppHandle,
+ app_data_dir: std::path::PathBuf,
+ remote: RemoteManifest,
+ slug: String,
+) -> InstallReport {
+ let started = std::time::Instant::now();
+ let pet = remote.pets.into_iter().find(|p| p.slug == slug);
+ let Some(pet) = pet else {
+ let _ = app.emit(
+ "pets:sync:error",
+ serde_json::json!({
+ "slug": slug,
+ "message": "slug not in remote manifest",
+ "retryable": false,
+ }),
+ );
+ return InstallReport {
+ added: vec![],
+ skipped: vec![],
+ failed: vec![FailedInstall {
+ slug,
+ reason: "not in remote manifest".to_string(),
+ }],
+ total_bytes: 0,
+ duration_ms: started.elapsed().as_millis() as u64,
+ };
+ };
+ let app_data_arc = Arc::new(app_data_dir.clone());
+ let result = install_one(app_data_arc, pet, true).await;
+ let mut manifest = load(&app_data_dir);
+ let mut added = vec![];
+ let mut failed = vec![];
+ let mut total_bytes = 0u64;
+ match result {
+ Ok((s, bytes, entry)) => {
+ total_bytes = bytes;
+ manifest.pets.insert(s.clone(), entry);
+ manifest.last_synced_at = Some(now_iso());
+ let _ = save_atomic(&app_data_dir, &manifest);
+ added.push(s);
+ }
+ Err(e) => failed.push(e),
+ }
+ let report = InstallReport {
+ added,
+ skipped: vec![],
+ failed,
+ total_bytes,
+ duration_ms: started.elapsed().as_millis() as u64,
+ };
+ let _ = app.emit("pets:sync:finished", &report);
+ report
+}
+
+pub fn uninstall(app_data_dir: &Path, slug: &str) -> std::io::Result<()> {
+ let dir = pet_dir(app_data_dir, slug);
+ if dir.exists() {
+ std::fs::remove_dir_all(&dir)?;
+ }
+ let mut manifest = load(app_data_dir);
+ manifest.pets.remove(slug);
+ save_atomic(app_data_dir, &manifest)?;
+ Ok(())
+}
+
+pub fn manifest_file(app_data_dir: &Path) -> std::path::PathBuf {
+ manifest_path(app_data_dir)
+}
diff --git a/src-tauri/src/pets/manifest.rs b/src-tauri/src/pets/manifest.rs
new file mode 100644
index 00000000..ca14ddcd
--- /dev/null
+++ b/src-tauri/src/pets/manifest.rs
@@ -0,0 +1,160 @@
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+
+use serde::{Deserialize, Serialize};
+
+pub const MANIFEST_VERSION: u32 = 1;
+const MANIFEST_NAME: &str = "manifest.local.json";
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct LocalManifest {
+ pub version: u32,
+ pub last_synced_at: Option<String>,
+ pub last_remote_manifest_at: Option<String>,
+ pub pets: BTreeMap<String, LocalPetEntry>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct LocalPetEntry {
+ pub slug: String,
+ pub display_name: String,
+ pub source: String,
+ pub installed_at: String,
+ #[serde(default)]
+ pub vibes: Vec<String>,
+ #[serde(default)]
+ pub tags: Vec<String>,
+ #[serde(default)]
+ pub kind: Option<String>,
+ pub sprite_ext: String,
+ #[serde(default)]
+ pub file_sizes: BTreeMap<String, u64>,
+ #[serde(default)]
+ pub remote_checked_at: Option<String>,
+}
+
+impl Default for LocalManifest {
+ fn default() -> Self {
+ Self {
+ version: MANIFEST_VERSION,
+ last_synced_at: None,
+ last_remote_manifest_at: None,
+ pets: BTreeMap::new(),
+ }
+ }
+}
+
+pub fn pets_root(app_data_dir: &Path) -> PathBuf {
+ app_data_dir.join("pets")
+}
+
+pub fn manifest_path(app_data_dir: &Path) -> PathBuf {
+ pets_root(app_data_dir).join(MANIFEST_NAME)
+}
+
+pub fn pet_dir(app_data_dir: &Path, slug: &str) -> PathBuf {
+ pets_root(app_data_dir).join(slug)
+}
+
+pub fn ensure_root(app_data_dir: &Path) -> std::io::Result<PathBuf> {
+ let root = pets_root(app_data_dir);
+ std::fs::create_dir_all(&root)?;
+ Ok(root)
+}
+
+pub fn load(app_data_dir: &Path) -> LocalManifest {
+ let path = manifest_path(app_data_dir);
+ let raw = std::fs::read_to_string(&path).unwrap_or_default();
+ if raw.is_empty() {
+ return LocalManifest::default();
+ }
+ serde_json::from_str(&raw).unwrap_or_default()
+}
+
+pub fn save_atomic(app_data_dir: &Path, manifest: &LocalManifest) -> std::io::Result<()> {
+ let _ = ensure_root(app_data_dir)?;
+ let final_path = manifest_path(app_data_dir);
+ let tmp_path = final_path.with_extension("json.tmp");
+ let bytes = serde_json::to_vec_pretty(manifest)
+ .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
+ std::fs::write(&tmp_path, bytes)?;
+ if final_path.exists() {
+ std::fs::remove_file(&final_path)?;
+ }
+ std::fs::rename(&tmp_path, &final_path)?;
+ Ok(())
+}
+
+pub fn now_iso() -> String {
+ chrono::Utc::now().to_rfc3339()
+}
+
+pub fn discover_local_pets(
+ app_data_dir: &Path,
+ manifest: &mut LocalManifest,
+) -> std::io::Result<()> {
+ let root = pets_root(app_data_dir);
+ let mut existing_slugs: Vec<String> = manifest.pets.keys().cloned().collect();
+ if !root.exists() {
+ return Ok(());
+ }
+ let entries = match std::fs::read_dir(&root) {
+ Ok(it) => it,
+ Err(_) => return Ok(()),
+ };
+ let mut seen_on_disk: Vec<String> = Vec::new();
+ for entry in entries.flatten() {
+ if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
+ continue;
+ }
+ let slug = match entry.file_name().to_str().map(|s| s.to_string()) {
+ Some(s) => s,
+ None => continue,
+ };
+ let dir = entry.path();
+ let webp = dir.join("spritesheet.webp");
+ let png = dir.join("spritesheet.png");
+ let ext = if webp.is_file() {
+ Some("webp")
+ } else if png.is_file() {
+ Some("png")
+ } else {
+ None
+ };
+ let Some(ext) = ext else { continue };
+ seen_on_disk.push(slug.clone());
+ if manifest.pets.contains_key(&slug) {
+ continue;
+ }
+ let pet_json = dir.join("pet.json");
+ let display_name = std::fs::read_to_string(&pet_json)
+ .ok()
+ .and_then(|raw| serde_json::from_str::<serde_json::Value>(&raw).ok())
+ .and_then(|v| {
+ v.get("displayName")
+ .or_else(|| v.get("display_name"))
+ .and_then(|s| s.as_str().map(|s| s.to_string()))
+ })
+ .unwrap_or_else(|| slug.clone());
+ manifest.pets.insert(
+ slug.clone(),
+ LocalPetEntry {
+ slug: slug.clone(),
+ display_name,
+ source: "manual".to_string(),
+ installed_at: now_iso(),
+ vibes: Vec::new(),
+ tags: Vec::new(),
+ kind: None,
+ sprite_ext: ext.to_string(),
+ file_sizes: BTreeMap::new(),
+ remote_checked_at: None,
+ },
+ );
+ }
+ existing_slugs.retain(|slug| !seen_on_disk.contains(slug));
+ for orphan in existing_slugs {
+ manifest.pets.remove(&orphan);
+ }
+ Ok(())
+}
diff --git a/src-tauri/src/pets/mod.rs b/src-tauri/src/pets/mod.rs
new file mode 100644
index 00000000..c6465213
--- /dev/null
+++ b/src-tauri/src/pets/mod.rs
@@ -0,0 +1,288 @@
+pub mod download;
+pub mod install;
+pub mod manifest;
+
+use std::path::PathBuf;
+
+use serde::{Deserialize, Serialize};
+use tauri::{AppHandle, Emitter, Manager};
+use tokio::sync::Mutex;
+
+use download::{fetch_manifest, RemoteManifest};
+use install::{
+ diff as compute_diff, force_refresh as install_force_refresh,
+ install_bundle as install_bundle_impl, install_missing as install_missing_impl,
+ refresh_index, uninstall as uninstall_impl, DiffReport, InstallReport, LocalIndex,
+};
+use manifest::{ensure_root, load, now_iso, pets_root, save_atomic};
+
+#[derive(Default)]
+pub struct PetsState {
+ pub active_slug: Mutex<Option<String>>,
+ pub remote_cache: Mutex<Option<RemoteManifest>>,
+ pub display_prefs_cache: Mutex<Option<DisplayPrefs>>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct DisplayPrefs {
+ pub enabled: bool,
+ pub motion_enabled: bool,
+ pub default_state: String,
+ pub event_overrides: serde_json::Map<String, serde_json::Value>,
+}
+
+impl Default for DisplayPrefs {
+ fn default() -> Self {
+ Self {
+ enabled: true,
+ motion_enabled: true,
+ default_state: "idle".to_string(),
+ event_overrides: serde_json::Map::new(),
+ }
+ }
+}
+
+fn prefs_file(app: &AppHandle) -> Result<PathBuf, String> {
+ let dir = app_data_path(app)?;
+ Ok(pets_root(&dir).join("display_prefs.json"))
+}
+
+fn read_prefs(app: &AppHandle) -> DisplayPrefs {
+ let Ok(path) = prefs_file(app) else {
+ return DisplayPrefs::default();
+ };
+ let raw = match std::fs::read_to_string(&path) {
+ Ok(s) => s,
+ Err(_) => return DisplayPrefs::default(),
+ };
+ serde_json::from_str(&raw).unwrap_or_default()
+}
+
+fn write_prefs(app: &AppHandle, prefs: &DisplayPrefs) -> Result<(), String> {
+ let dir = app_data_path(app)?;
+ ensure_root(&dir).map_err(|e| e.to_string())?;
+ let path = prefs_file(app)?;
+ let body = serde_json::to_vec_pretty(prefs).map_err(|e| e.to_string())?;
+ std::fs::write(&path, body).map_err(|e| e.to_string())
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ActivePref {
+ pub slug: String,
+}
+
+fn app_data_path(app: &AppHandle) -> Result<PathBuf, String> {
+ app.path()
+ .app_data_dir()
+ .map_err(|e| format!("app_data_dir: {}", e))
+}
+
+fn pref_file(app: &AppHandle) -> Result<PathBuf, String> {
+ let dir = app_data_path(app)?;
+ Ok(pets_root(&dir).join("active.json"))
+}
+
+fn read_active(app: &AppHandle) -> Option<String> {
+ let path = pref_file(app).ok()?;
+ let raw = std::fs::read_to_string(&path).ok()?;
+ let v: serde_json::Value = serde_json::from_str(&raw).ok()?;
+ v.get("slug").and_then(|s| s.as_str()).map(|s| s.to_string())
+}
+
+fn write_active(app: &AppHandle, slug: &str) -> Result<(), String> {
+ let dir = app_data_path(app)?;
+ ensure_root(&dir).map_err(|e| e.to_string())?;
+ let path = pref_file(app)?;
+ let body = serde_json::json!({ "slug": slug });
+ std::fs::write(&path, serde_json::to_vec_pretty(&body).unwrap_or_default())
+ .map_err(|e| e.to_string())
+}
+
+#[tauri::command]
+pub async fn pets_get_local_index(app: AppHandle) -> Result<LocalIndex, String> {
+ let dir = app_data_path(&app)?;
+ refresh_index(&dir).map_err(|e| e.to_string())
+}
+
+#[tauri::command]
+pub async fn pets_fetch_remote_manifest(
+ app: AppHandle,
+ state: tauri::State<'_, PetsState>,
+) -> Result<RemoteManifest, String> {
+ let manifest = fetch_manifest().await.map_err(|e| e.to_string())?;
+ *state.remote_cache.lock().await = Some(manifest.clone());
+ let _ = app;
+ Ok(manifest)
+}
+
+#[tauri::command]
+pub async fn pets_diff(
+ app: AppHandle,
+ state: tauri::State<'_, PetsState>,
+) -> Result<DiffReport, String> {
+ let dir = app_data_path(&app)?;
+ let local = refresh_index(&dir).map_err(|e| e.to_string())?;
+ let remote = fetch_manifest().await.map_err(|e| e.to_string())?;
+ *state.remote_cache.lock().await = Some(remote.clone());
+ let mut local_manifest = load(&dir);
+ local_manifest.last_remote_manifest_at = remote.generated_at.clone();
+ let _ = save_atomic(&dir, &local_manifest);
+ Ok(compute_diff(&local, &remote))
+}
+
+#[tauri::command]
+pub async fn pets_install_bundle(
+ app: AppHandle,
+ state: tauri::State<'_, PetsState>,
+) -> Result<InstallReport, String> {
+ let dir = app_data_path(&app)?;
+ let remote = match state.remote_cache.lock().await.clone() {
+ Some(m) => m,
+ None => fetch_manifest().await.map_err(|e| e.to_string())?,
+ };
+ Ok(install_bundle_impl(app, dir, remote).await)
+}
+
+#[tauri::command]
+pub async fn pets_install_missing(
+ app: AppHandle,
+ state: tauri::State<'_, PetsState>,
+ slugs: Option<Vec<String>>,
+) -> Result<InstallReport, String> {
+ let dir = app_data_path(&app)?;
+ let remote = match state.remote_cache.lock().await.clone() {
+ Some(m) => m,
+ None => fetch_manifest().await.map_err(|e| e.to_string())?,
+ };
+ Ok(install_missing_impl(app, dir, remote, slugs).await)
+}
+
+#[tauri::command]
+pub async fn pets_force_refresh(
+ app: AppHandle,
+ state: tauri::State<'_, PetsState>,
+ slug: String,
+) -> Result<InstallReport, String> {
+ let dir = app_data_path(&app)?;
+ let remote = match state.remote_cache.lock().await.clone() {
+ Some(m) => m,
+ None => fetch_manifest().await.map_err(|e| e.to_string())?,
+ };
+ Ok(install_force_refresh(app, dir, remote, slug).await)
+}
+
+#[tauri::command]
+pub async fn pets_uninstall(app: AppHandle, slug: String) -> Result<(), String> {
+ let dir = app_data_path(&app)?;
+ uninstall_impl(&dir, &slug).map_err(|e| e.to_string())
+}
+
+#[tauri::command]
+pub async fn pets_open_folder(app: AppHandle) -> Result<(), String> {
+ let dir = app_data_path(&app)?;
+ let root = pets_root(&dir);
+ ensure_root(&dir).map_err(|e| e.to_string())?;
+ open_native_folder(&root)
+}
+
+fn open_native_folder(path: &std::path::Path) -> Result<(), String> {
+ #[cfg(target_os = "windows")]
+ {
+ std::process::Command::new("explorer")
+ .arg(path)
+ .spawn()
+ .map(|_| ())
+ .map_err(|e| e.to_string())
+ }
+ #[cfg(target_os = "macos")]
+ {
+ std::process::Command::new("open")
+ .arg(path)
+ .spawn()
+ .map(|_| ())
+ .map_err(|e| e.to_string())
+ }
+ #[cfg(target_os = "linux")]
+ {
+ std::process::Command::new("xdg-open")
+ .arg(path)
+ .spawn()
+ .map(|_| ())
+ .map_err(|e| e.to_string())
+ }
+}
+
+#[tauri::command]
+pub async fn pets_set_active(
+ app: AppHandle,
+ state: tauri::State<'_, PetsState>,
+ slug: String,
+) -> Result<(), String> {
+ write_active(&app, &slug)?;
+ *state.active_slug.lock().await = Some(slug);
+ Ok(())
+}
+
+#[tauri::command]
+pub async fn pets_get_active(
+ app: AppHandle,
+ state: tauri::State<'_, PetsState>,
+) -> Result<Option<String>, String> {
+ {
+ let g = state.active_slug.lock().await;
+ if let Some(s) = g.clone() {
+ return Ok(Some(s));
+ }
+ }
+ let stored = read_active(&app);
+ *state.active_slug.lock().await = stored.clone();
+ Ok(stored)
+}
+
+#[tauri::command]
+pub async fn pets_get_display_prefs(
+ app: AppHandle,
+ state: tauri::State<'_, PetsState>,
+) -> Result<DisplayPrefs, String> {
+ {
+ let g = state.display_prefs_cache.lock().await;
+ if let Some(p) = g.clone() {
+ return Ok(p);
+ }
+ }
+ let prefs = read_prefs(&app);
+ *state.display_prefs_cache.lock().await = Some(prefs.clone());
+ Ok(prefs)
+}
+
+#[tauri::command]
+pub async fn pets_set_display_prefs(
+ app: AppHandle,
+ state: tauri::State<'_, PetsState>,
+ prefs: DisplayPrefs,
+) -> Result<DisplayPrefs, String> {
+ write_prefs(&app, &prefs)?;
+ *state.display_prefs_cache.lock().await = Some(prefs.clone());
+ let _ = app.emit("pets:prefs:changed", &prefs);
+ Ok(prefs)
+}
+
+#[tauri::command]
+pub async fn pets_resolve_path(app: AppHandle, slug: String) -> Result<String, String> {
+ let dir = app_data_path(&app)?;
+ let pet_dir = pets_root(&dir).join(&slug);
+ let webp = pet_dir.join("spritesheet.webp");
+ let png = pet_dir.join("spritesheet.png");
+ let path = if webp.is_file() {
+ webp
+ } else if png.is_file() {
+ png
+ } else {
+ return Err(format!("no spritesheet for slug '{}'", slug));
+ };
+ Ok(path.to_string_lossy().into_owned())
+}
+
+pub fn _now_iso_export() -> String {
+ now_iso()
+}
diff --git a/src-tauri/src/platforms/mod.rs b/src-tauri/src/platforms/mod.rs
index 1a289b5e..9682624a 100644
--- a/src-tauri/src/platforms/mod.rs
+++ b/src-tauri/src/platforms/mod.rs
@@ -1,6 +1,7 @@
pub use omniget_core::platforms::traits;
pub use omniget_core::platforms::Platform;
+pub mod noop;
pub mod bluesky;
pub mod pinterest;
pub mod tiktok;
diff --git a/src-tauri/src/platforms/noop.rs b/src-tauri/src/platforms/noop.rs
new file mode 100644
index 00000000..181b262b
--- /dev/null
+++ b/src-tauri/src/platforms/noop.rs
@@ -0,0 +1,46 @@
+use async_trait::async_trait;
+
+use crate::platforms::traits::PlatformDownloader;
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo};
+
+pub struct NoopDownloader;
+
+impl NoopDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+impl Default for NoopDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for NoopDownloader {
+ fn name(&self) -> &str {
+ "external"
+ }
+
+ fn can_handle(&self, _url: &str) -> bool {
+ false
+ }
+
+ async fn get_media_info(&self, _url: &str) -> anyhow::Result<MediaInfo> {
+ Err(anyhow::anyhow!(
+ "NoopDownloader cannot fetch media info; this item is driven by an external plugin"
+ ))
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: tokio::sync::mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow::anyhow!(
+ "NoopDownloader cannot drive download; this item is driven by an external plugin"
+ ))
+ }
+}