ipatool-rs 0.1.9

A terminal UI and CLI for searching, purchasing, and downloading iOS App Store IPA files.
use anyhow::{Context, Result};

use ipatool_core::api;
use ipatool_core::client::AppleClient;
use ipatool_core::model::storefront::country_code_from_store_front;
use ipatool_core::model::{Account, Platform};

use super::{
    app_not_found_error, is_empty_song_list_error, reauth_or_fail, version_not_found_error,
};
use crate::output::{self, OutputFormat};

const MAX_VERSION_ATTEMPTS: u32 = 3;

pub async fn list(
    client: &AppleClient,
    app_id: Option<i64>,
    bundle_identifier: Option<&str>,
    account: &Account,
    format: OutputFormat,
) -> Result<()> {
    let resolved_app_id = resolve_app_id(client, app_id, bundle_identifier, account).await?;
    let mut account = account.clone();
    let mut result = None;
    let mut last_error = None;

    for attempt in 0..MAX_VERSION_ATTEMPTS {
        match api::versions::list_versions(client, resolved_app_id, &account).await {
            Ok(versions) => {
                result = Some(versions);
                break;
            }
            Err(e) if e.is_license_not_found() => {
                return Err(license_not_found_error(bundle_identifier));
            }
            Err(e) if e.is_token_expired() && attempt + 1 < MAX_VERSION_ATTEMPTS => {
                last_error = Some(e.to_string());
                eprintln!(
                    "Token expired, re-authenticating (attempt {})...",
                    attempt + 1
                );
                account = reauth_or_fail(client, &account).await?;
            }
            Err(e) => return Err(e).context("failed to list versions"),
        }
    }

    let result = result.with_context(|| {
        last_error.map_or_else(
            || "failed to list versions after retries".to_string(),
            |e| format!("failed to list versions after retries: {e}"),
        )
    })?;

    match format {
        OutputFormat::Text => {
            eprintln!("Versions for app {}:", result.app_id);
            for v in &result.versions {
                let latest = result.latest_external_version_id.as_deref()
                    == Some(v.external_version_id.as_str());
                match (v.version_string.as_deref(), latest) {
                    (Some(ver), true) => {
                        println!("  {} (version: {}, latest)", v.external_version_id, ver)
                    }
                    (Some(ver), false) => {
                        println!("  {} (version: {})", v.external_version_id, ver)
                    }
                    (None, true) => println!("  {} (latest)", v.external_version_id),
                    (None, false) => println!("  {}", v.external_version_id),
                }
            }
            if result.versions.is_empty() {
                eprintln!("  (no versions found)");
            }
        }
        OutputFormat::Json => output::print_json(&result),
    }

    Ok(())
}

pub async fn meta(
    client: &AppleClient,
    app_id: Option<i64>,
    bundle_identifier: Option<&str>,
    version_id: &str,
    account: &Account,
    format: OutputFormat,
) -> Result<()> {
    let resolved_app_id = resolve_app_id(client, app_id, bundle_identifier, account).await?;
    let mut account = account.clone();

    let mut result = None;
    let mut last_error = None;

    for attempt in 0..MAX_VERSION_ATTEMPTS {
        match api::versions::get_version_metadata(client, resolved_app_id, &account, version_id)
            .await
        {
            Ok(metadata) => {
                result = Some(metadata);
                break;
            }
            Err(e) if e.is_license_not_found() => {
                return Err(license_not_found_error(bundle_identifier));
            }
            Err(e) if is_empty_song_list_error(&e) => {
                return Err(version_not_found_error(
                    version_id,
                    resolved_app_id,
                    bundle_identifier,
                ));
            }
            Err(e) if e.is_token_expired() && attempt + 1 < MAX_VERSION_ATTEMPTS => {
                last_error = Some(e.to_string());
                eprintln!(
                    "Token expired, re-authenticating (attempt {})...",
                    attempt + 1
                );
                account = reauth_or_fail(client, &account).await?;
            }
            Err(e) => return Err(e).context("failed to get version metadata"),
        }
    }

    let result = result.with_context(|| {
        last_error.map_or_else(
            || "failed to get version metadata after retries".to_string(),
            |e| format!("failed to get version metadata after retries: {e}"),
        )
    })?;

    match format {
        OutputFormat::Text => {
            if let Some(ref v) = result.bundle_short_version {
                println!("Version:       {v}");
            }
            if let Some(ref v) = result.bundle_version {
                println!("Build:         {v}");
            }
            if let Some(ref v) = result.release_date {
                println!("Release Date:  {v}");
            }
        }
        OutputFormat::Json => output::print_json(&result),
    }

    Ok(())
}

async fn resolve_app_id(
    client: &AppleClient,
    app_id: Option<i64>,
    bundle_identifier: Option<&str>,
    account: &Account,
) -> Result<i64> {
    match app_id {
        Some(id) => Ok(id),
        None => {
            let bid = bundle_identifier.ok_or_else(|| {
                anyhow::anyhow!("either --app-id or --bundle-identifier is required")
            })?;
            let country = country_code_from_store_front(&account.store_front).unwrap_or("US");
            let app = api::lookup::lookup(client, bid, country, Platform::IPhone)
                .await
                .with_context(|| {
                    format!("lookup failed for bundle identifier {bid} in storefront {country}")
                })?
                .ok_or_else(|| app_not_found_error(bid, country))?;
            Ok(app.id)
        }
    }
}

fn license_not_found_error(bundle_identifier: Option<&str>) -> anyhow::Error {
    match bundle_identifier {
        Some(bid) => anyhow::anyhow!(
            "license not found for {bid}; run `ipatool purchase -b {bid}` first, then retry"
        ),
        None => anyhow::anyhow!(
            "license not found; run `ipatool purchase -b <bundle-id>` first, then retry"
        ),
    }
}