Medlar/crates/core/src/manager/mod.rs
2026-11-25 13:55:19 -06:00

327 lines
12 KiB
Rust

//! All downloads and what can be done with them: the one way in for the window, the command line and the local port.
//!
//! One thread owns the list. Commands are sent to it and never wait; `snapshot` is read without a lock.
mod actor;
mod bin;
mod files;
mod pick;
pub use bin::Bin;
use crate::adopt::Found;
use crate::error::Failure;
use crate::events::Event;
use crate::http::{Options, Shared};
use crate::limit::Limiter;
use crate::model::{Task, TaskId};
use crate::net_state::Network;
use crate::recover::Recovery;
use crate::recover::sleep::Sleep;
use crate::relink::{Checked, NewLink};
use crate::settings::Limits;
use crate::site::Sites;
use crate::metalink;
use crate::snapshot::Snapshot;
use crate::verify::Checksum;
use crate::{store, tr};
use arc_swap::ArcSwap;
use std::fmt;
use std::future::Future;
use std::io;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::{Arc, Mutex, mpsc};
use std::task::{Context, Poll, ready};
use std::thread::JoinHandle;
use std::time::Duration;
use tokio::sync::{broadcast, oneshot};
#[derive(Debug)]
pub enum Error {
Store(store::Error),
/// Not a name a file can have.
Name,
/// Not a full path.
Folder,
File(io::Error),
Bin(io::Error),
/// The link leads to another file.
Different,
/// Nothing can be taken over; `Checked::text` says why.
Partial(String),
/// The link could not be checked.
Link(Box<Failure>),
/// Medlar is closing.
Closed,
}
pub type Result<T> = std::result::Result<T, Error>;
impl From<store::Error> for Error {
fn from(e: store::Error) -> Error {
Error::Store(e)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&match self {
Error::Store(e) => return e.fmt(f),
Error::Name => tr!("manager.name"),
Error::Folder => tr!("manager.folder"),
Error::File(e) => tr!("manager.file", why = e),
Error::Bin(e) => tr!("manager.bin", why = e),
Error::Different => tr!("manager.different"),
Error::Partial(why) => tr!("manager.partial", why = why),
Error::Link(failure) => failure.text.clone(),
Error::Closed => tr!("manager.closed"),
})
}
}
impl std::error::Error for Error {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Files {
Keep,
/// Finished or not, to the desktop's bin.
Bin,
}
/// Each is fine in any state: what makes no sense there changes nothing, and twice is the same as once.
pub enum Command {
/// Appends it to its queue. `state` may be queued (runs when there is room), waiting or paused; the manager fills in the
/// id, the position (unless given) and all that is learned from the server.
Add(Box<Task>),
/// Runs it now, before all others. The one that has to give way for it waits in its place.
Start(TaskId),
/// Keeps everything it has.
Pause(TaskId),
/// Back in line, also after a failure.
Resume(TaskId),
/// What goes on until it is stopped, like a live stream, ends here: what there is becomes the file.
Finish(TaskId),
/// Pauses it and puts it last.
Stop(TaskId),
/// Can be undone for `Config::undo`, and until the program ends.
Remove { id: TaskId, files: Files },
/// Undoes the removal, binned files included.
Restore(TaskId),
/// From the start, as a new file. A finished one stays where it is.
Redownload(TaskId),
/// Leaves it as it is and adds the same download again, as a new file. Answers with the new one.
KeepBoth(TaskId),
/// Moves the file too. A taken name gets a number.
Move { id: TaskId, folder: PathBuf },
/// Renames the file too. A taken name gets a number.
Rename { id: TaskId, name: String },
/// Compares a finished file with its checksum, or its pieces. Nothing without them.
Verify(TaskId),
/// From the start, as a new file, from the next mirror. The link it has becomes the last mirror.
OtherMirror(TaskId),
/// Changes what the user decides: link, mirrors, queue, position, priority, limits, headers, notes and the like.
/// Changes of other fields are dropped.
Edit { id: TaskId, edit: Box<dyn FnOnce(&mut Task) + Send> },
/// Waits for a link from the source page; `relink::find` puts it first. Pause and Resume end the wait.
AwaitLink(TaskId),
/// Goes on from a link that `Manager::check` looked at, with that link's headers and login instead of the old ones. Refused
/// when it is another file. If the server can't continue, a new download starts over and answers; the old one keeps what it
/// has and is binned when the new one is whole.
Continue { id: TaskId, checked: Box<Checked> },
/// Adds a download that goes on from a file `Manager::check_partial` looked at. The link and what the server said come from
/// there, the rest from the task.
Adopt { task: Box<Task>, found: Box<Found> },
}
impl Command {
fn id(&self) -> Option<TaskId> {
use Command::*;
match self {
Add(_) | Adopt { .. } => None,
Start(id) | Pause(id) | Resume(id) | Stop(id) | Finish(id) | Restore(id) | Redownload(id) | Verify(id) | OtherMirror(id) | KeepBoth(id) | AwaitLink(id) => Some(*id),
Remove { id, .. } | Move { id, .. } | Rename { id, .. } | Edit { id, .. } | Continue { id, .. } => Some(*id),
}
}
}
/// The answer to a command, when the snapshot shows what it did. Needn't be looked at.
#[derive(Debug)]
#[must_use = "errors come only this way; drop it to ignore them"]
pub struct Reply<T = TaskId>(oneshot::Receiver<Result<T>>);
impl<T> Reply<T> {
/// None while there is no answer. Never waits; ask no more after the answer.
pub fn try_get(&mut self) -> Option<Result<T>> {
match self.0.try_recv() {
Ok(result) => Some(result),
Err(oneshot::error::TryRecvError::Empty) => None,
Err(oneshot::error::TryRecvError::Closed) => Some(Err(Error::Closed)),
}
}
/// Not for the thread of the window, nor inside async code.
pub fn wait(self) -> Result<T> {
self.0.blocking_recv().unwrap_or(Err(Error::Closed))
}
}
impl<T> Future for Reply<T> {
type Output = Result<T>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
Poll::Ready(ready!(Pin::new(&mut self.0).poll(cx)).unwrap_or(Err(Error::Closed)))
}
}
pub struct Config {
pub shared: Shared,
/// Logins, proxies and rules per site. None: plain requests only (tests).
pub sites: Option<Arc<Sites>>,
pub options: Options,
pub limits: Limits,
pub limiter: Arc<Limiter>,
pub bin: Bin,
pub recovery: Recovery,
/// How long a removal can be undone.
pub undo: Duration,
/// How often the snapshot follows running downloads.
pub tick: Duration,
}
impl Config {
pub fn new(shared: Shared, limits: Limits) -> Config {
Config {
shared,
sites: None,
options: Options::default(),
limits,
limiter: Limiter::new(),
bin: Bin::default(),
recovery: Recovery::default(),
undo: Duration::from_secs(60),
tick: Duration::from_millis(100),
}
}
}
type Answer = oneshot::Sender<Result<TaskId>>;
enum Msg {
Command(Command, Option<Answer>),
Check(TaskId, NewLink, oneshot::Sender<Result<Checked>>),
FindChecksum(TaskId, oneshot::Sender<Result<Option<Checksum>>>),
ReadMetalink(NewLink, oneshot::Sender<Result<Vec<metalink::File>>>),
CheckPartial(PathBuf, NewLink, oneshot::Sender<Result<Found>>),
Limits(Limits),
OnChange(Box<dyn Fn() + Send>),
/// A download ended.
Ended(TaskId, std::result::Result<PathBuf, actor::Why>),
/// File work ended.
Worked(TaskId, Result<actor::Worked>),
/// A folder was looked at.
Looked(TaskId, bool),
Network(Network),
Sleep(Sleep),
Recovery { tries: u32, auto_resume: bool },
Close,
}
/// Share it in an `Arc`. Dropping it closes it.
pub struct Manager {
to: mpsc::Sender<Msg>,
shot: Arc<ArcSwap<Snapshot>>,
events: broadcast::Sender<Event>,
thread: Mutex<Option<JoinHandle<()>>>,
}
impl Manager {
/// Takes up what was running when the program ended. Reads the whole list: not for the thread of the window.
pub fn open(config: Config) -> Result<Manager> {
let (to, inbox) = mpsc::channel();
let (events, _) = broadcast::channel(4096);
let shot = Arc::new(ArcSwap::from_pointee(Snapshot::default()));
let actor = actor::Actor::new(config, to.clone(), shot.clone(), events.clone())?;
let thread = std::thread::Builder::new().name("manager".into()).spawn(move || actor.run(inbox)).map_err(Error::File)?;
Ok(Manager { to, shot, events, thread: Mutex::new(Some(thread)) })
}
/// Never waits.
pub fn send(&self, command: Command) -> Reply {
let (answer, reply) = oneshot::channel();
// When the thread is gone the answer is dropped, which says so.
let _ = self.to.send(Msg::Command(command, Some(answer)));
Reply(reply)
}
/// Compares what a download has with what a new link leads to; nothing changes. Dropping the reply ends it.
pub fn check(&self, id: TaskId, link: NewLink) -> Reply<Checked> {
let (answer, reply) = oneshot::channel();
let _ = self.to.send(Msg::Check(id, link, answer));
Reply(reply)
}
/// Looks for a checksum beside the file on its server; nothing changes. `Command::Edit` takes it.
pub fn find_checksum(&self, id: TaskId) -> Reply<Option<Checksum>> {
let (answer, reply) = oneshot::channel();
let _ = self.to.send(Msg::FindChecksum(id, answer));
Reply(reply)
}
/// The files in a metalink; `metalink::File::task` makes downloads of them.
pub fn read_metalink(&self, link: NewLink) -> Reply<Vec<metalink::File>> {
let (answer, reply) = oneshot::channel();
let _ = self.to.send(Msg::ReadMetalink(link, answer));
Reply(reply)
}
/// The same for an unfinished file of another program.
pub fn check_partial(&self, path: PathBuf, link: NewLink) -> Reply<Found> {
let (answer, reply) = oneshot::channel();
let _ = self.to.send(Msg::CheckPartial(path, link, answer));
Reply(reply)
}
/// Takes effect at once, also on running downloads. 0 is no limit. Connections that may stay go on as they are.
pub fn set_limits(&self, limits: Limits) {
let _ = self.to.send(Msg::Limits(limits));
}
/// From the settings; takes effect at the next failure.
pub fn set_recovery(&self, tries: u32, auto_resume: bool) {
let _ = self.to.send(Msg::Recovery { tries, auto_resume });
}
/// The list of this moment. Never waits.
pub fn snapshot(&self) -> Arc<Snapshot> {
self.shot.load_full()
}
/// Called from the manager's thread after each new snapshot: at most every tick, and after commands. Must be quick.
pub fn on_change(&self, call: impl Fn() + Send + 'static) {
let _ = self.to.send(Msg::OnChange(Box::new(call)));
}
pub fn subscribe(&self) -> broadcast::Receiver<Event> {
self.events.subscribe()
}
/// Stops everything, saves it and takes no more commands. Doesn't wait; `close` does. What ran goes on at the next start.
pub fn begin_close(&self) {
let _ = self.to.send(Msg::Close);
}
/// Closes and waits for the end, at most two seconds.
pub fn close(&self) {
self.begin_close();
if let Some(thread) = self.thread.lock().unwrap_or_else(|e| e.into_inner()).take() {
let _ = thread.join();
}
}
}
impl Drop for Manager {
fn drop(&mut self) {
self.close();
}
}