pub mod clipboard_watcher;
pub mod drop_watcher;
pub mod pull;
pub mod retry;
pub mod upload;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{mpsc, oneshot, watch};
use tokio::time::{Instant, MissedTickBehavior};
use crate::clipboard::{Clipboard, ClipboardError, RgbaImage};
use crate::config::{AfterSend, Config};
use crate::store::{BackendFuture, StoreError};
use self::clipboard_watcher::ClipboardWatcher;
use self::drop_watcher::DropTracker;
use self::pull::{ClipboardWrite, Puller};
use self::upload::{JobOutcome, Uploader};
pub const SENT_DIR: &str = "sent";
const DEFAULT_RESCAN_INTERVAL: Duration = Duration::from_secs(5);
const QUEUE_DEPTH: usize = 64;
pub type StoreOpener = Arc<dyn Fn() -> BackendFuture<'static> + Send + Sync>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Job {
Text(String),
File(PathBuf),
Image(RgbaImage),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ServeOptions {
pub drop_folder: PathBuf,
pub clipboard_poll_interval: Duration,
pub file_stable_wait: Duration,
pub rescan_interval: Duration,
pub after_send: AfterSend,
pub device: String,
pub clipboard_images: bool,
pub pull: bool,
pub pull_interval: Duration,
pub download_dir: PathBuf,
}
impl ServeOptions {
pub fn from_config(config: &Config) -> Self {
Self {
drop_folder: config.serve.drop_folder.clone(),
clipboard_poll_interval: Duration::from_millis(config.serve.clipboard_poll_interval_ms),
file_stable_wait: Duration::from_millis(config.serve.file_stable_wait_ms),
rescan_interval: DEFAULT_RESCAN_INTERVAL,
after_send: config.serve.after_send,
device: config.client.device_name.clone(),
clipboard_images: config.serve.clipboard_images,
pull: config.serve.pull,
pull_interval: Duration::from_millis(config.serve.pull_interval_ms),
download_dir: config.client.download_dir.clone(),
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum ServeError {
#[error("cannot open the store: {0}")]
Store(#[from] StoreError),
#[error("cannot prepare the drop folder {path}: {message}")]
DropFolder {
path: String,
message: String,
},
#[error("cannot watch the drop folder {path}: {message}")]
Watch {
path: String,
message: String,
},
}
pub async fn run(
options: ServeOptions,
clipboard: Option<Box<dyn Clipboard>>,
open_store: StoreOpener,
shutdown: watch::Receiver<bool>,
) -> Result<(), ServeError> {
let (ready, _) = oneshot::channel();
run_with_ready(options, clipboard, open_store, shutdown, ready).await
}
pub async fn run_with_ready(
options: ServeOptions,
clipboard: Option<Box<dyn Clipboard>>,
open_store: StoreOpener,
mut shutdown: watch::Receiver<bool>,
ready: oneshot::Sender<()>,
) -> Result<(), ServeError> {
let store = open_store().await?;
let folder = options.drop_folder.clone();
let shown = folder.display().to_string();
let sent_dir = folder.join(SENT_DIR);
tokio::fs::create_dir_all(&sent_dir)
.await
.map_err(|err| ServeError::DropFolder {
path: shown.clone(),
message: err.to_string(),
})?;
let (changed_tx, changed_rx) = mpsc::channel(1);
let _watcher =
drop_watcher::watch_folder(&folder, changed_tx).map_err(|err| ServeError::Watch {
path: shown.clone(),
message: err.to_string(),
})?;
let (writes_tx, writes_rx) = mpsc::channel(4);
let puller = if options.pull {
let pull_store = open_store().await?;
let puller = Puller::start(
pull_store.as_ref(),
options.device.clone(),
options.download_dir.clone(),
clipboard.is_some().then(|| writes_tx.clone()),
)
.await?;
Some((puller, pull_store))
} else {
None
};
drop(writes_tx);
let (jobs_tx, mut jobs_rx) = mpsc::channel(QUEUE_DEPTH);
let mut tasks = Vec::new();
match clipboard {
Some(clipboard) => tasks.push(tokio::spawn(clipboard_loop(
clipboard,
options.clipboard_poll_interval,
options.clipboard_images,
writes_rx,
jobs_tx.clone(),
shutdown.clone(),
))),
None => tracing::warn!("no clipboard available; only the drop folder is watched"),
}
if let Some((puller, pull_store)) = puller {
tracing::info!(
interval_ms = options.pull_interval.as_millis() as u64,
"pull mode: applying items from other devices"
);
tasks.push(tokio::spawn(pull::pull_loop(
puller,
pull_store,
open_store.clone(),
options.pull_interval,
shutdown.clone(),
)));
}
let (skipped_tx, skipped_rx) = mpsc::unbounded_channel();
tasks.push(tokio::spawn(drop_loop(
folder,
options.file_stable_wait,
options.rescan_interval,
jobs_tx,
changed_rx,
skipped_rx,
shutdown.clone(),
)));
tracing::info!(
path = shown.as_str(),
"serving: watching the clipboard and the drop folder"
);
let _ = ready.send(());
let mut uploader = Uploader::new(
store,
open_store,
options.device,
options.after_send,
sent_dir,
);
loop {
tokio::select! {
() = stopped(&mut shutdown) => break,
job = jobs_rx.recv() => match job {
Some(job) => {
let file = match &job {
Job::File(path) => Some(path.clone()),
Job::Text(_) | Job::Image(_) => None,
};
if uploader.handle(job, &mut shutdown).await == JobOutcome::Skipped
&& let Some(path) = file
{
let _ = skipped_tx.send(path);
}
}
None => break,
},
}
}
for task in tasks {
task.abort();
}
tracing::info!("serve stopped");
Ok(())
}
pub(crate) async fn stopped(shutdown: &mut watch::Receiver<bool>) {
let _ = shutdown.wait_for(|stop| *stop).await;
}
async fn clipboard_loop(
mut clipboard: Box<dyn Clipboard>,
interval: Duration,
images: bool,
mut writes: mpsc::Receiver<ClipboardWrite>,
jobs: mpsc::Sender<Job>,
mut shutdown: watch::Receiver<bool>,
) {
let mut watcher = ClipboardWatcher::new();
let mut ticker = tokio::time::interval(interval);
ticker.set_missed_tick_behavior(MissedTickBehavior::Delay);
let mut last_error: Option<String> = None;
loop {
tokio::select! {
() = stopped(&mut shutdown) => return,
Some(write) = writes.recv() => {
let task = tokio::task::spawn_blocking(move || {
let result = write_clipboard(clipboard.as_mut(), &write);
(clipboard, write, result)
});
match task.await {
Ok((back, write, result)) => {
clipboard = back;
match (result, &write) {
(Ok(()), ClipboardWrite::Text(text)) => watcher.mark_text(text),
(Ok(()), ClipboardWrite::Image(image)) => watcher.mark_image(image),
(Err(err), _) => {
tracing::warn!(error = %err, "cannot put pulled content on the clipboard");
}
}
}
Err(err) => {
tracing::warn!(error = %err, "the clipboard writer stopped");
return;
}
}
continue;
}
_ = ticker.tick() => {}
}
let read = tokio::task::spawn_blocking(move || {
let result = read_clipboard(clipboard.as_mut(), images);
(clipboard, result)
});
let result = match read.await {
Ok((back, result)) => {
clipboard = back;
result
}
Err(err) => {
tracing::warn!(error = %err, "the clipboard reader stopped");
return;
}
};
match result {
Ok((text, image)) => {
last_error = None;
if let Some(text) = watcher.observe(text) {
tracing::debug!(size = text.len() as u64, "new clipboard text");
if jobs.send(Job::Text(text)).await.is_err() {
return;
}
} else if let Some(image) = watcher.observe_image(image) {
tracing::debug!(
width = image.width(),
height = image.height(),
"new clipboard image"
);
if jobs.send(Job::Image(image)).await.is_err() {
return;
}
}
}
Err(err) => {
let message = err.to_string();
if last_error.as_deref() != Some(message.as_str()) {
tracing::warn!(error = message.as_str(), "cannot read the clipboard");
last_error = Some(message);
}
}
}
}
}
fn write_clipboard(
clipboard: &mut dyn Clipboard,
write: &ClipboardWrite,
) -> Result<(), ClipboardError> {
match write {
ClipboardWrite::Text(text) => clipboard.write_text(text),
ClipboardWrite::Image(image) => clipboard.write_image(image),
}
}
fn read_clipboard(
clipboard: &mut dyn Clipboard,
images: bool,
) -> Result<(Option<String>, Option<RgbaImage>), ClipboardError> {
crate::clipboard::read_payload(clipboard, images)
}
async fn drop_loop(
folder: PathBuf,
stable_wait: Duration,
rescan: Duration,
jobs: mpsc::Sender<Job>,
mut changed: mpsc::Receiver<()>,
mut skipped: mpsc::UnboundedReceiver<PathBuf>,
mut shutdown: watch::Receiver<bool>,
) {
let mut tracker = DropTracker::new(stable_wait);
let settle_tick = (stable_wait / 2).clamp(Duration::from_millis(50), Duration::from_secs(1));
let mut watching = true;
loop {
match drop_watcher::scan(&folder).await {
Ok(files) => {
for path in tracker.observe(files, Instant::now()) {
if jobs.send(Job::File(path)).await.is_err() {
return;
}
}
}
Err(err) => {
tracing::warn!(path = %folder.display(), error = %err, "cannot scan the drop folder")
}
}
let wait = if tracker.has_pending() {
settle_tick
} else {
rescan
};
tokio::select! {
() = stopped(&mut shutdown) => return,
event = changed.recv(), if watching => {
if event.is_none() {
watching = false;
}
}
Some(path) = skipped.recv() => tracker.mark_skipped(&path),
() = tokio::time::sleep(wait) => {}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::MapEnv;
#[test]
fn options_come_from_the_config() {
let text = "[client]\ndevice_name = \"lap\"\ndownload_dir = \"/dl\"\n[server]\nkind = \"local\"\n[server.local]\npath = \"/s\"\n[serve]\ndrop_folder = \"/drop\"\nclipboard_poll_interval_ms = 300\nfile_stable_wait_ms = 0\nafter_send = \"delete\"\n";
let config =
crate::config::parse(text, std::path::Path::new("/c.toml"), &MapEnv::new()).unwrap();
assert_eq!(
ServeOptions::from_config(&config),
ServeOptions {
drop_folder: PathBuf::from("/drop"),
clipboard_poll_interval: Duration::from_millis(300),
file_stable_wait: Duration::ZERO,
rescan_interval: Duration::from_secs(5),
after_send: AfterSend::Delete,
device: "lap".into(),
clipboard_images: true,
pull: false,
pull_interval: Duration::from_millis(5000),
download_dir: PathBuf::from("/dl"),
}
);
}
}