use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use paperpaw_sdk::builtin::params;
use paperpaw_sdk::event::Event;
use paperpaw_sdk::replies::HttpReply;
use paperpaw_sdk::{Arg, Command, Commands, Env, HttpRequest, Params, install};
use crate::catalog::{self, Device};
use crate::{CATALOG, INSTALLER, PLUGIN, failed, trust};
pub(crate) const FETCHED: Event<HttpReply> = Event::new("store.queued");
const TURN: &str = "> ";
const QUIET: &str = "~";
const REQUESTED: &str = "&";
fn path() -> String {
format!("{}/queue.txt", Env::plugin_dir(PLUGIN.as_str()))
}
fn lines(env: &Env<'_>) -> Vec<String> {
paperpaw_sdk::read_file(env.storage(), &path(), 16 * 1024)
.ok()
.and_then(|bytes| String::from_utf8(bytes).ok())
.map(|text| text.lines().map(ToString::to_string).collect())
.unwrap_or_default()
}
fn keep(env: &Env<'_>, lines: &[String]) {
if lines.is_empty() {
let _ = env.storage().remove(&path());
return;
}
let mut text = lines.join("\n");
text.push('\n');
let _ = env.storage().create_dir(&Env::plugin_dir(PLUGIN.as_str()));
let _ = env.storage().write(&path(), text.as_bytes());
}
fn entry(line: &str) -> (&str, bool) {
let line = line.strip_prefix(TURN).unwrap_or(line);
match line
.strip_prefix(QUIET)
.or_else(|| line.strip_prefix(REQUESTED))
{
Some(id) => (id, true),
None => (line, false),
}
}
pub(crate) fn requested(env: &Env<'_>) -> bool {
lines(env).first().is_some_and(|line| {
line.strip_prefix(TURN)
.is_some_and(|rest| rest.starts_with(REQUESTED))
})
}
pub(crate) fn requested_waiting(env: &Env<'_>) -> bool {
lines(env).iter().any(|line| {
line.strip_prefix(TURN)
.unwrap_or(line)
.starts_with(REQUESTED)
})
}
pub(crate) fn waiting(env: &Env<'_>) -> Vec<String> {
lines(env)
.iter()
.map(|line| entry(line).0.to_string())
.collect()
}
pub(crate) fn quiet(env: &Env<'_>) -> bool {
lines(env)
.first()
.is_some_and(|line| line.starts_with(TURN) && entry(line).1)
}
pub(crate) fn has_quiet(env: &Env<'_>) -> bool {
lines(env).iter().any(|line| entry(line).1)
}
fn quiet_path() -> String {
format!("{}/queue-quiet.txt", Env::plugin_dir(PLUGIN.as_str()))
}
pub(crate) fn note(env: &Env<'_>, name: &str, done: bool) {
let _ = env.storage().create_dir(&Env::plugin_dir(PLUGIN.as_str()));
let line = format!(
"{}{}\n",
if done { '+' } else { '-' },
name.replace('\n', " ")
);
let _ = env.storage().append(&quiet_path(), line.as_bytes());
}
fn name_of(env: &Env<'_>, id: &str) -> String {
env.i18n()
.get(&format!("store.offer.{id}"))
.map_or_else(|| id.to_string(), ToString::to_string)
}
fn said(env: &Env<'_>, out: &mut Commands) {
if has_quiet(env) {
return;
}
let Some(text) = paperpaw_sdk::read_file(env.storage(), &quiet_path(), 16 * 1024)
.ok()
.and_then(|bytes| String::from_utf8(bytes).ok())
else {
return;
};
let _ = env.storage().remove(&quiet_path());
let names = |mark: char| {
text.lines()
.filter_map(|line| line.strip_prefix(mark))
.collect::<Vec<_>>()
.join(", ")
};
let (done, mut not) = (names('+'), names('-'));
let styles = name_of(env, crate::styles::PACK);
if let Some(rest) = crate::styles::without(¬, &styles) {
not = rest;
if crate::styles::hint_due(env) {
out.push(Command::Notify(
env.i18n()
.format("store.styles.later", &[("name", Arg::Str(&styles))]),
));
}
}
if !done.is_empty() {
out.push(Command::Notify(
env.i18n()
.format("store.offer.done", &[("names", Arg::Str(&done))]),
));
}
if !not.is_empty() {
out.push(Command::Notify(
env.i18n()
.format("store.offer.not-done", &[("names", Arg::Str(¬))]),
));
}
}
pub(crate) fn add(env: &Env<'_>, ids: &[String], out: &mut Commands) {
put(env, ids, "", out);
}
pub(crate) fn add_requested(env: &Env<'_>, ids: &[String], out: &mut Commands) {
put(env, ids, REQUESTED, out);
}
pub(crate) fn add_quietly(env: &Env<'_>, ids: &[String], out: &mut Commands) {
put(env, ids, QUIET, out);
}
fn put(env: &Env<'_>, ids: &[String], mark: &str, out: &mut Commands) {
let mut all = lines(env);
let known = waiting(env);
for id in ids {
if !known.contains(id) {
all.push(format!("{mark}{id}"));
}
}
keep(env, &all);
next(env, out);
}
pub(crate) fn interrupted(env: &Env<'_>) {
let mut all = lines(env);
if let Some(first) = all.first_mut()
&& let Some(id) = first.strip_prefix(TURN)
{
*first = id.to_string();
keep(env, &all);
}
}
fn page_url(env: &Env<'_>, device: &Device<'_>, id: &str) -> String {
let list = env.settings().read(&CATALOG);
let community = crate::community(env);
catalog::plugin_url(
list.trim(),
device.name,
env.i18n().language(),
id,
community,
device.fingerprint,
)
}
pub(crate) fn next(env: &Env<'_>, out: &mut Commands) {
if INSTALLER.progress(env.storage()).is_some() {
return;
}
let Some(device) = Device::of(env).filter(|_| env.caps().network) else {
return;
};
let mut all = lines(env);
if all.first().is_some_and(|first| first.starts_with(TURN)) {
all.remove(0);
}
all.retain(|line| install::is_plugin_name(entry(line).0));
let Some(first) = all.first().cloned() else {
keep(env, &[]);
crate::request::finished(env, out);
return said(env, out);
};
let id = entry(&first).0.to_string();
all[0] = format!("{TURN}{first}");
keep(env, &all);
said(env, out);
let url = page_url(env, &device, &id);
let mut request = HttpRequest::new("GET", &url, FETCHED);
request = request
.save_to(catalog::plugin_part(&id))
.max_file(catalog::MAX_PAGE_FILE);
request = request.with(Params::new().with(params::ID, id));
out.push(Command::http(request));
}
pub(crate) fn fetched(env: &Env<'_>, reply: &HttpReply, out: &mut Commands) {
let Some(id) = reply.context.get(params::ID).map(ToString::to_string) else {
return;
};
crate::styles::answered(env, &id, reply.status);
let fetched = catalog::plugin_part(&id);
let plugin = Device::of(env)
.filter(|_| (200..300).contains(&reply.status))
.and_then(|device| {
let address = reply
.final_url
.clone()
.unwrap_or_else(|| page_url(env, &device, &id));
catalog::plugin(env.storage(), &fetched, &address, &device)
})
.filter(|plugin| {
plugin.entry.id == id
&& !plugin.entry.switched_off(env)
&& !plugin.entry.unbuilt()
&& (plugin.entry.installed(env).is_none() || plugin.entry.newer(env))
});
let _ = env.storage().remove(&fetched);
match plugin {
Some(plugin) => {
trust::expect(env.storage(), &plugin.entry.id, plugin.named().as_ref());
if !INSTALLER.start(env, &plugin.package, out) {
if requested(env) {
crate::request::outcome(env, &id, false);
} else if quiet(env) {
note(env, &plugin.entry.name, false);
} else {
out.push(failed(env, &plugin.entry.name));
}
next(env, out);
}
}
None => {
if requested(env) {
crate::request::outcome(env, &id, env.plugins().get(&id).is_some());
} else if quiet(env) {
note(env, &name_of(env, &id), false);
}
next(env, out);
}
}
}