Medlar/crates/core/src/model.rs
2026-11-24 23:29:30 -06:00

284 lines
8.1 KiB
Rust

//! What Medlar remembers: tasks, parts, queues, tags and hosts.
//!
//! Secrets (cookies, logins, tokens) never appear here. `secret` fields hold the name of a keyring item.
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
pub type TaskId = i64;
pub type QueueId = i64;
pub type TagId = i64;
/// Milliseconds since 1970.
pub type Time = i64;
/// The queue that always exists.
pub const MAIN_QUEUE: QueueId = 1;
/// An enum stored by name.
macro_rules! named_enum {
($(#[$meta:meta])* $name:ident { $($(#[$vmeta:meta])* $variant:ident = $text:literal),* $(,)? }) => {
$(#[$meta])*
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum $name { $($(#[$vmeta])* #[serde(rename = $text)] $variant),* }
impl $name {
pub const ALL: &'static [$name] = &[$($name::$variant),*];
pub fn name(self) -> &'static str {
match self { $($name::$variant => $text),* }
}
pub fn from_name(name: &str) -> Option<$name> {
$name::ALL.iter().copied().find(|v| v.name() == name)
}
}
};
}
named_enum!(
/// What a task is doing. The catalogue holds its label under `state.<name>`.
State {
/// Ready, until its queue has room.
Queued = "queued",
/// Held back by a time, another task, a retry or the network.
Waiting = "waiting",
Running = "running",
Paused = "paused",
/// Comparing the checksum.
Checking = "checking",
/// Naming, unpacking or converting the finished file.
Finishing = "finishing",
Done = "done",
Failed = "failed",
/// Was done, but the file is no longer there.
Gone = "gone",
}
);
impl State {
/// The states this one may move to.
pub fn moves(self) -> &'static [State] {
use State::*;
match self {
Queued => &[Running, Waiting, Paused, Failed],
Waiting => &[Queued, Running, Paused, Failed],
// Queued again: the app was killed, or the task gave up its place.
Running => &[Queued, Waiting, Paused, Checking, Finishing, Failed],
Paused => &[Queued, Waiting, Failed],
Checking => &[Queued, Paused, Finishing, Failed],
Finishing => &[Queued, Done, Failed],
// Queued: download again. Checking: check the file again.
Done => &[Queued, Checking, Gone],
Failed => &[Queued, Waiting, Paused],
Gone => &[Queued, Done],
}
}
pub fn can_become(self, to: State) -> bool {
self.moves().contains(&to)
}
}
named_enum!(
/// Share of bandwidth and connections.
Priority {
Lowest = "lowest",
Low = "low",
Normal = "normal",
High = "high",
Highest = "highest",
/// Everything else waits.
Only = "only",
}
);
named_enum!(
/// Why a task failed. Filled by S007; each kind has a label under `error.<name>`.
ErrorKind {}
);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TaskError {
/// None for a kind this version doesn't know.
pub kind: Option<ErrorKind>,
/// Plain words, already free of secrets.
pub detail: String,
}
/// A file to download. `id` is 0 until the store adds it.
#[derive(Debug, Clone, PartialEq)]
pub struct Task {
pub id: TaskId,
pub url: String,
pub mirrors: Vec<String>,
/// The page the link came from, opened to get a new link.
pub source_page: Option<String>,
pub name: String,
pub folder: PathBuf,
/// Changed through `Store::set_state` only.
pub state: State,
/// Changed through `Store::set_state` only.
pub error: Option<TaskError>,
pub queue: QueueId,
/// Order inside the queue.
pub position: f64,
pub priority: Priority,
pub size: Option<u64>,
pub downloaded: u64,
pub mime: Option<String>,
pub etag: Option<String>,
pub last_modified: Option<String>,
/// `sha256:…`.
pub checksum: Option<String>,
pub max_parts: Option<u32>,
/// Bytes per second.
pub speed_limit: Option<u64>,
/// Cookies and authorization are refused here; they go to the keyring.
pub headers: Vec<(String, String)>,
pub proxy: Option<String>,
/// Keyring item with the cookies and login.
pub secret: Option<String>,
pub after: Option<TaskId>,
pub start_at: Option<Time>,
pub added_at: Time,
pub finished_at: Option<Time>,
/// Set while the removal can still be undone.
pub removed_at: Option<Time>,
pub tags: Vec<TagId>,
pub notes: String,
}
impl Default for Task {
fn default() -> Task {
Task {
id: 0,
url: String::new(),
mirrors: vec![],
source_page: None,
name: String::new(),
folder: PathBuf::new(),
state: State::Queued,
error: None,
queue: MAIN_QUEUE,
position: 0.0,
priority: Priority::Normal,
size: None,
downloaded: 0,
mime: None,
etag: None,
last_modified: None,
checksum: None,
max_parts: None,
speed_limit: None,
headers: vec![],
proxy: None,
secret: None,
after: None,
start_at: None,
added_at: now(),
finished_at: None,
removed_at: None,
tags: vec![],
notes: String::new(),
}
}
}
/// A range of the file: bytes `start..end`, of which the first `done` are on disk.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Part {
pub start: u64,
/// None when the length is unknown.
pub end: Option<u64>,
pub done: u64,
}
/// Weekdays and times a queue may run.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Schedule {
/// Bit 0 is Monday.
pub days: u8,
/// Minutes after midnight.
pub from: u16,
/// Smaller than `from` when it ends the next day.
pub to: u16,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Queue {
pub id: QueueId,
/// Empty for the main queue, which the catalogue names (`queue.main`).
pub name: String,
pub folder: Option<PathBuf>,
pub speed_limit: Option<u64>,
pub max_active: Option<u32>,
pub position: f64,
pub paused: bool,
pub schedule: Vec<Schedule>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Tag {
pub id: TagId,
pub name: String,
/// `#rrggbb`.
pub color: Option<String>,
}
/// What Medlar learned, or was told, about a host.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct HostProfile {
pub host: String,
/// Connections the host tolerated.
pub good_connections: Option<u32>,
/// Cap set by the user.
pub max_connections: Option<u32>,
pub ranges: Option<bool>,
pub speed_limit: Option<u64>,
pub user_agent: Option<String>,
pub proxy: Option<String>,
/// Keyring item with the login.
pub secret: Option<String>,
pub seen_at: Time,
}
pub fn now() -> Time {
chrono::Utc::now().timestamp_millis()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn illegal_moves_are_refused() {
use State::*;
for (from, to) in [(Queued, Done), (Paused, Done), (Running, Done), (Done, Running), (Gone, Running), (Failed, Done), (Done, Paused)] {
assert!(!from.can_become(to), "{from:?} to {to:?}");
}
for &s in State::ALL {
assert!(!s.can_become(s), "{s:?} to itself");
}
}
#[test]
fn every_state_can_reach_done() {
for &start in State::ALL {
let mut seen = vec![start];
let mut i = 0;
while i < seen.len() {
seen.extend(seen[i].moves().iter().filter(|s| !seen.contains(s)).copied().collect::<Vec<_>>());
i += 1;
}
assert!(seen.contains(&State::Done), "{start:?}");
}
}
#[test]
fn names_round_trip() {
for &s in State::ALL {
assert_eq!(State::from_name(s.name()), Some(s));
}
assert_eq!(Priority::from_name("nope"), None);
}
}