garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /programs/src/bin/updates.rs

raw

//! The updates service: in the background, with no window, it looks at the
//! package sources now and then for new versions of the installed apps, as
//! Settings → Updates chose (`pinnacle_ui::updates::Choice`). Told, it
//! names them in a notification, once a version; installing, it brings an
//! app to the new version itself when the app is not running and the new
//! version asks for no more than the installed one may do, and says so
//! after. What asks for more is only told: the Store shows its rights
//! before the tap.
//!
//! The system too (`pinnacle_pkg::system`): a newer one for this board is
//! told of, or, installing, fetched into the slot that does not run and set
//! to be tried at the next start, which the person chooses (Settings →
//! Updates → Restart); nothing restarts the device by itself. After a start
//! from a slot it puts the files that system came with in their places, and
//! tells of a try that did not start.
//!
//! A look a minute after the start, then every six hours, and when Settings
//! asks (`system-updates`, `LOOK`); none while the choice is off, and none
//! while there is no network, which is looked at again in five minutes.

#![no_std]
#![no_main]

extern crate alloc;

use alloc::string::String;
use alloc::vec::Vec;

use pinnacle_rt::abi::net::ONLINE;
use pinnacle_rt::{Channel, Received, fs, println};
use pinnacle_ui::store::{self, Offer};
use pinnacle_ui::updates::{self, Choice};

/// The first look, after the start.
const FIRST_MS: u64 = 60_000;
/// Between looks.
const EVERY_MS: u64 = 6 * 3600 * 1000;
/// Again, when the network was not there, or an app to update was running.
const SOON_MS: u64 = 5 * 60_000;

/// The versions already told, `name version` a line: a notification comes
/// once a version, not at every look.
const TOLD: &str = "system:/settings/updates-told";
/// The same for the system: the last thing told of it (`offered 413`,
/// `ready 413`, `failed 414`).
const TOLD_SYSTEM: &str = "system:/settings/updates-told-system";

/// Notifies `title`/`text` (a tap opens Settings) unless `what` was the
/// last thing told of the system.
fn tell_system(display: Option<&Channel>, what: &str, title: &str, text: &str) {
    if fs::read_string(TOLD_SYSTEM).as_deref().map(str::trim) == Some(what) {
        return;
    }
    if let Some(display) = display {
        pinnacle_ui::notify(display, "settings", title, text);
    }
    fs::write(TOLD_SYSTEM, what.as_bytes());
}

/// Looks for a newer system, and as `choice` says tells of it or fetches it
/// to be tried at the next start. A line for Settings when there is news.
fn look_system(display: Option<&Channel>, choice: Choice) -> Option<String> {
    let running = updates::Running::now();
    let Some(offer) = updates::system_offer(&running) else {
        updates::set_offered(None);
        return None;
    };
    let version = &offer.version;
    if updates::failed_version().is_some_and(|v| v == *version) {
        updates::set_offered(None);
        return Some(alloc::format!("system {version} did not start: not tried again"));
    }
    if updates::waiting().is_some_and(|(_, v)| v == *version) {
        updates::set_offered(None);
        return Some(alloc::format!("system {version} ready: restart to finish"));
    }
    updates::set_offered(Some(version));
    if choice != Choice::Install {
        tell_system(
            display,
            &alloc::format!("offered {version}"),
            "System update",
            &alloc::format!("Version {version} can be installed in Settings → Updates"),
        );
        return Some(alloc::format!("system {version} to install"));
    }
    println!("updates: fetching system {version}, {}", store::size(offer.size));
    match updates::fetch_system(&offer, &mut |_, _| {}) {
        Ok(slot) => {
            updates::set_offered(None);
            println!("updates: system {version} ready in slot {}", slot.name());
            tell_system(
                display,
                &alloc::format!("ready {version}"),
                "System update ready",
                &alloc::format!("Version {version} starts when the device restarts"),
            );
            Some(alloc::format!("system {version} ready: restart to finish"))
        }
        Err(why) => {
            println!("updates: system {version} not fetched: {why}");
            Some(alloc::format!("system {version} failed: {why}"))
        }
    }
}

/// A try of a new system that did not start, told of once.
fn tell_failure(display: Option<&Channel>) {
    let record = updates::record();
    if let Some(failed) = record.failed {
        let version = updates::slot_version(failed).unwrap_or_default();
        let running = updates::Running::now().version;
        println!("updates: system {version} did not start; {running} runs");
        tell_system(
            display,
            &alloc::format!("failed {version}"),
            "System update did not start",
            &alloc::format!("Version {version} did not start: version {running} runs again"),
        );
    }
}

fn clock_text() -> String {
    pinnacle_rt::locale::time_text()
}

/// "Paint", "Paint and Notes", "Paint, Notes and Clock".
fn names(list: &[String]) -> String {
    match list {
        [] => String::new(),
        [one] => one.clone(),
        [rest @ .., last] => alloc::format!("{} and {last}", rest.join(", ")),
    }
}

/// What one look found.
#[derive(Default)]
struct Look {
    /// Title and version.
    updated: Vec<(String, String)>,
    /// Waiting for the person: told, or to tell.
    to_tell: Vec<(String, String)>,
    /// Running now: tried again soon.
    running: Vec<String>,
    failed: Vec<String>,
}

/// Looks once: the catalogs against what is installed, and, when `choice`
/// installs, brings in by itself each update that asks for no more than
/// its installed version may do, while its app is not running. None when
/// no source answered.
fn look(display: Option<&Channel>, choice: Choice) -> Option<Look> {
    let offers = store::catalog()?;
    let mut found = Look::default();
    let newer = offers
        .iter()
        .filter(|o| store::installed(&o.name).is_some_and(|v| v != o.version));
    for offer in newer {
        if choice == Choice::Install && no_more_rights(offer) {
            // Its files are not changed under it; without the display
            // server to ask, it is taken to run.
            if display.is_none_or(|d| pinnacle_ui::running(d, &offer.name)) {
                println!("updates: {} is running: later", offer.name);
                found.running.push(offer.title.clone());
                continue;
            }
            match store::install(offer, &mut |_, _| {}) {
                Ok(()) => {
                    println!("updates: {} updated to {}", offer.name, offer.version);
                    found.updated.push((offer.title.clone(), offer.version.clone()));
                    continue;
                }
                // Told too: the Store may do it, or say why not.
                Err(why) => {
                    println!("updates: {} not updated: {why}", offer.name);
                    found.failed.push(offer.title.clone());
                }
            }
        } else if choice == Choice::Install {
            println!("updates: {} asks for more than it may do now: told", offer.name);
        }
        found.to_tell.push((offer.name.clone(), offer.version.clone()));
    }
    Some(found)
}

/// Whether `offer` asks for no more than its installed version may do.
fn no_more_rights(offer: &Offer) -> bool {
    store::installed_rights(&offer.name).is_some_and(|r| offer.rights.within(r))
}

/// Tells the person what `found` holds that was not told before, and keeps
/// it as told. The line Settings shows of it.
fn tell(display: Option<&Channel>, found: &Look) -> String {
    let told_text = fs::read_string(TOLD).unwrap_or_default();
    let told: Vec<&str> = told_text.lines().collect();
    let titles = |list: &[(String, String)]| -> Vec<String> {
        list.iter()
            .map(|(name, _)| {
                let manifest = fs::read_string(&alloc::format!("system:/apps/{name}/manifest"));
                manifest
                    .as_deref()
                    .and_then(|m| fs::field(m, "title"))
                    .map_or_else(|| name.clone(), |t| String::from(t.trim()))
            })
            .collect()
    };
    let new: Vec<(String, String)> = found
        .to_tell
        .iter()
        .filter(|(name, version)| !told.contains(&alloc::format!("{name} {version}").as_str()))
        .cloned()
        .collect();
    // "Calculator updated to version 2", or "Calculator and Paint updated".
    let updated = match found.updated.as_slice() {
        [] => String::new(),
        [(title, version)] => alloc::format!("{title} updated to version {version}"),
        many => {
            let titles: Vec<String> = many.iter().map(|(t, _)| t.clone()).collect();
            alloc::format!("{} updated", names(&titles))
        }
    };
    if let Some(display) = display {
        if !updated.is_empty() {
            pinnacle_ui::notify(display, "store", "Apps updated", &updated);
        }
        if !new.is_empty() {
            let text = alloc::format!("{}: update in the Store", names(&titles(&new)));
            pinnacle_ui::notify(display, "store", "Updates", &text);
        }
    }
    // Kept: what waits now, so a version told stays told while it waits.
    let mut keep = String::new();
    for (name, version) in &found.to_tell {
        keep += &alloc::format!("{name} {version}\n");
    }
    fs::write(TOLD, keep.as_bytes());
    let mut parts: Vec<String> = Vec::new();
    if !updated.is_empty() {
        parts.push(updated);
    }
    if !found.to_tell.is_empty() {
        parts.push(alloc::format!("{} in the Store", names(&titles(&found.to_tell))));
    }
    if !found.running.is_empty() {
        parts.push(alloc::format!("{} once closed", names(&found.running)));
    }
    if !found.failed.is_empty() {
        parts.push(alloc::format!("{} failed", names(&found.failed)));
    }
    if parts.is_empty() {
        "Every app is up to date".into()
    } else {
        parts.join("; ")
    }
}

#[unsafe(no_mangle)]
fn main(_argument: u64) -> u64 {
    let service = pinnacle_rt::register(updates::SERVICE).expect("could not register the updates service");
    let mut display: Option<Channel> = None;
    let mut clients: Vec<Channel> = Vec::new();
    // Who asked for the look under way, to answer when it ends.
    let mut asking: Vec<usize> = Vec::new();
    let mut buffer = alloc::vec![0u8; pinnacle_rt::abi::MAX_MESSAGE];
    let mut next = Some(pinnacle_rt::time() + FIRST_MS);
    println!("updates: {:?}", Choice::read());
    if let Some(put) = updates::apply_files() {
        println!("updates: the system's files in their places ({put} changed)");
    }
    // Told at the first look, once the display server has its home screen.
    let mut failure_told = false;
    loop {
        let choice = Choice::read();
        let due = if choice == Choice::Off { None } else { next };
        let mut channels: Vec<&Channel> = alloc::vec![&service];
        channels.extend(clients.iter());
        let received = pinnacle_rt::receive(&channels, &mut buffer, due);
        drop(channels);
        let now = pinnacle_rt::time();
        let looking = match received {
            Received::Timeout => true,
            Received::Message {
                index: 0,
                mut handles,
                ..
            } if !handles.is_empty() => {
                clients.push(Channel(handles.remove(0)));
                false
            }
            Received::Message { index, len, .. } if index >= 1 && len > 0 => match buffer[0] {
                updates::LOOK => {
                    asking.push(index - 1);
                    true
                }
                updates::CHANGED => {
                    println!("updates: now {:?}", Choice::read());
                    next = Some(now + FIRST_MS);
                    false
                }
                _ => false,
            },
            Received::Closed { index } if index >= 1 => {
                clients.remove(index - 1);
                asking.retain(|&a| a != index - 1);
                for a in &mut asking {
                    if *a > index - 1 {
                        *a -= 1;
                    }
                }
                false
            }
            _ => false,
        };
        if !looking {
            continue;
        }
        // Asked by Settings, it looks even when off: the person asked.
        let choice = Choice::read();
        // Connected only now, as the other services do: a client before the
        // launcher's would be taken for the home screen.
        if display.is_none() {
            display = pinnacle_rt::connect("display");
        }
        if !failure_told {
            tell_failure(display.as_ref());
            failure_told = true;
        }
        let what = if pinnacle_rt::net::state() != ONLINE {
            next = Some(now + SOON_MS);
            String::from("No network")
        } else {
            match look(display.as_ref(), choice) {
                None => {
                    next = Some(now + SOON_MS);
                    String::from("No package source answered")
                }
                Some(found) => {
                    next = Some(
                        now + if found.running.is_empty() {
                            EVERY_MS
                        } else {
                            SOON_MS
                        },
                    );
                    let apps = tell(display.as_ref(), &found);
                    match look_system(display.as_ref(), choice) {
                        Some(system) => alloc::format!("{apps}; {system}"),
                        None => apps,
                    }
                }
            }
        };
        println!("updates: looked: {what}");
        updates::set_last(&clock_text(), &what);
        for &a in &asking {
            if let Some(c) = clients.get(a) {
                c.send(&[updates::LOOKED], Vec::new());
            }
        }
        asking.clear();
    }
}