//! A folder of the owner's songs, or an album ZIP, into their object, by the phone's own rules//! (`cotton_mac::music`).//!//! pnpm music:import <folder|album.zip> --zone <IANA zone> --base <url> --device-id <id> --token-file <path> [--key-file <path>] [--data-dir <dir>] [--dry-run]//!//! <folder> a folder of song files (mp3, m4a, flac, ogg, opus, wav, aiff),//! walked to the bottom; hidden files are skipped. A song is named//! by its path under the folder and the one above it, so//! `Artist/Album (Year)/01 Title.flac` reads whether the artist's//! folder, one album's or a whole library was given. An album ZIP//! (a Bandcamp download), given or met in the folder, is one//! album: its songs streamed out, its shop page (a Bandcamp URL//! in its note), its file date as the day bought and its PDF//! booklet kept on the album (`cotton_mac::music::album_zip`).//! --zone the owner's zone, Asia/Kolkata: a song's and an album's day//! added is today there. Named, never read off this Mac (a zone is//! the workspace's and is passed in: cotton-store's//! no_ambient_timezone)//! --base the object's address: https://cottondb.com (the token names the//! object), <the dev Worker's address (config/dev-server.json)>, or//! http://127.0.0.1:8787/b/<slug> under `wrangler dev`//! --device-id the id `seal-device` signed this Mac in under: the run is this//! Mac as a device that holds the person's data key, so every//! song, cover and booklet leaves it sealed and a row of a sealed//! table (an artist) goes sealed (e2e rulings R2, R6)//! --token-file the device credential `seal-device` kept; never printed. An//! assistant's `ctn_` token holds no key and is refused//! --key-file the vault key's file, where the tool was not given the login//! Keychain (`seal-device --key-file`)//! --data-dir where the importer's copy is kept between runs (a scratch//! folder when not named)//! --dry-run read the folder and decide every song against an empty object://! nothing is sent, and --base and --token-file are not needed//!//! Each file is said on stderr as it is answered (added, here, better, worse,//! refused); stdout is the run's summary as JSON. Run again, it sends nothing//! the object holds: every song already in is `here`.//!//! Tests: `cargo test -p cotton-mac --test music_import`.use std::path::{Path, PathBuf};use std::process::ExitCode;use cotton_mac::music::album_zip::{import_path, PathReport};use cotton_mac::music::import::{Memory, Outcome};use cotton_mac::device::DeviceArgs;use serde_json::json;const USAGE: &str = "pnpm music:import <folder|album.zip> --zone <IANA zone> --base <url> --device-id <id> --token-file <path> [--key-file <path>] [--data-dir <dir>] [--dry-run]";structArgs { folder: PathBuf, zone: String, device: DeviceArgs, dry_run: bool,}/// A path as the person typed it, from where they typed it: pnpm runs a root/// verb from the root and says where it was asked in INIT_CWD.fn path_from(typed: &str) -> PathBuf {ifletSome(rest) = typed.strip_prefix("~/") {ifletSome(home) = std::env::var_os("HOME") {returnPath::new(&home).join(rest); } }let path = PathBuf::from(typed);if path.is_absolute() {return path; }let cwd = std::env::var_os("INIT_CWD").map(PathBuf::from).or_else(|| std::env::current_dir().ok()).unwrap_or_default(); cwd.join(path)}fn parse(argv: &[String]) -> Result<Args, String> {letmut folder = None;letmut zone = None;letmut device = DeviceArgs::default();letmut dry_run = false;letmut at = 0;while at < argv.len() {let arg = &argv[at];match arg.as_str() {"--dry-run" => dry_run = true,"--zone" | "--base" | "--token-file" | "--device-id" | "--key-file" | "--data-dir" => {let value = argv.get(at + 1).filter(|value| !value.starts_with("--")).ok_or_else(|| format!("{arg} needs a value"))?;if arg == "--zone" { zone = Some(value.to_string()); } elseif arg == "--token-file" || arg == "--key-file" || arg == "--data-dir" { device.take(arg, &path_from(value).to_string_lossy()); } else { device.take(arg, value); } at += 1; } flag if flag.starts_with("--") => returnErr(format!("no option {flag}: {USAGE}")), _ if folder.is_some() => returnErr(format!("name one folder or ZIP: {USAGE}")), typed => folder = Some(path_from(typed)), } at += 1; }let folder = folder.ok_or_else(|| format!("name the folder or ZIP: {USAGE}"))?;let zone = zone.ok_or_else(|| format!("name the owner's zone with --zone: {USAGE}"))?; today(&zone)?;if !dry_run && (device.base.is_none() || device.token_file.is_none() || device.device_id.is_none()) {returnErr(format!("--base, --device-id and --token-file are needed unless --dry-run: {USAGE}")); }Ok(Args { folder, zone, device, dry_run })}/// Today in the owner's zone: a song's and an album's day added.fn today(zone: &str) -> Result<String, String> {let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_err(|error| error.to_string())?;let day = cotton_core::transforms::zoned_clock::zoned_parts(now.as_millis() as i64, zone) .map_err(|_| format!("--zone {zone} is not a zone (an IANA name, Asia/Kolkata)"))?;Ok(format!("{:04}-{:02}-{:02}", day.year, day.month, day.day))}fn summary(run: &PathReport, dry_run: bool) -> serde_json::Value {let report = &run.report; json!({"dryRun": dry_run,"added": report.count("added"),"here": report.count("here"),"better": report.count("better"),"worse": report.count("worse"),"refused": report.count("refused"),"albumsMade": report.albums_made,"artistsMade": report.artists_made,"coversSent": report.covers_sent,"bytesSent": report.bytes_sent,"said": report.said,// Each playlist file found: its list, made or grown, and the entries no song was found for."lists": report.lists,// A better file took these files' places: the object still holds them, and they can go (`pnpm media:remove`)."replaced": report.songs.iter().filter_map(|song| song.replaced.clone()).collect::<Vec<_>>(),// Each file's outcome and its song's id: `pnpm fetch:run` links the songs a download landed."songs": report.songs.iter().map(|song| json!({"source_path": song.source_path, "outcome": song.outcome, "id": song.id})).collect::<Vec<_>>(),// Each album ZIP: the album it came in as and where it was bought, or why it was refused."zips": run.zips, })}fn run() -> Result<(), String> {let argv: Vec<String> = std::env::args().skip(1).collect();let args = parse(&argv)?;letmut done = 0usize;letmut each = |outcome: &Outcome| { done += 1; eprintln!("{done:>5} {:<7} {} ({})", outcome.outcome, outcome.source_path, outcome.line); };let report = if args.dry_run { import_path(&Memory::new("dry-run"), &args.folder, &today(&args.zone)?, &args.zone, &mut each) } else {// This Mac as a device holding the person's data key: rows to sealed tables and every file go sealed.let device = args.device.open()?; import_path(&device.object, &args.folder, &today(&args.zone)?, &args.zone, &mut each) } .map_err(|error| error.to_string())?; println!("{}", serde_json::to_string_pretty(&summary(&report, args.dry_run)).expect("a summary serialises"));Ok(())}fn main() -> ExitCode {match run() {Ok(()) => ExitCode::SUCCESS,Err(error) => { eprintln!("music:import: {error}");ExitCode::FAILURE } }}