use std::borrow::Borrow;
use std::collections::{BTreeMap, HashMap};
use std::future::Future;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;
use futures_util::future::{AbortHandle, Either, abortable, select};
use tokio::sync::{Notify, broadcast};
use super::details::Names;
use super::text;
use crate::client::AuthorizedUrl;
use crate::error::{Error, Result};
use crate::library::MediaItem;
use crate::mirror::runtime::{Task, spawn, timeout};
use crate::mirror::{
BoxFuture, ConnectionState, ItemIds, ItemImage, LibrarySyncState, Mirror, MirrorEvent, Related,
Runtime, SyncKind,
};
use crate::server::ServerApi;
use crate::types::ItemWithRelations;
use crate::types::book::Book;
use crate::types::episode::Episode;
use crate::types::library::{LibraryType, ServerLibraryForRead};
use crate::types::media::{MediaFileQuery, MediaQuery, RsSort, SqlOrder};
use crate::types::movie::Movie;
use crate::types::person::Person;
use crate::types::serie::Serie;
use crate::types::tag::Tag;
pub const BURST: Duration = Duration::from_millis(250);
pub const FIRST_WAIT: Duration = Duration::from_secs(10);
pub const BIG_SYNC: u64 = 500;
const BASE_WAIT: Duration = Duration::from_secs(10);
pub const MAX_IDS: usize = 1000;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Ids {
Listed(ItemIds),
Many,
}
impl Ids {
fn merge(&mut self, later: ItemIds) {
if let Ids::Listed(ids) = self {
ids.merge(later);
if ids.len() > MAX_IDS {
*self = Ids::Many;
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Change {
Server,
Library {
library: String,
items: BTreeMap<SyncKind, Ids>,
},
All,
}
impl Change {
pub fn library(&self) -> Option<&str> {
match self {
Change::Library { library, .. } => Some(library),
_ => None,
}
}
pub fn ids(&self, kind: SyncKind) -> Option<Ids> {
match self {
Change::Library { items, .. } => items.get(&kind).cloned(),
Change::All => Some(Ids::Many),
Change::Server => None,
}
}
pub fn touches(&self, kind: SyncKind) -> bool {
match self {
Change::Library { items, .. } => items.contains_key(&kind),
Change::All => true,
Change::Server => false,
}
}
}
#[cfg(not(target_arch = "wasm32"))]
pub trait OnChange: Fn(&Change) + Send + Sync + 'static {}
#[cfg(not(target_arch = "wasm32"))]
impl<T: Fn(&Change) + Send + Sync + 'static> OnChange for T {}
#[cfg(target_arch = "wasm32")]
pub trait OnChange: Fn(&Change) + 'static {}
#[cfg(target_arch = "wasm32")]
impl<T: Fn(&Change) + 'static> OnChange for T {}
#[cfg(not(target_arch = "wasm32"))]
type Listener = Arc<dyn Fn(&Change) + Send + Sync>;
#[cfg(target_arch = "wasm32")]
type Listener = Arc<dyn Fn(&Change)>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Reach {
Disconnected,
Connecting,
Connected,
Offline { reason: String, retry: bool },
}
#[derive(Debug, Clone)]
pub struct LibraryView {
pub library: ServerLibraryForRead,
pub count: u64,
pub revision: u64,
pub syncing: bool,
pub copying: bool,
pub sync_detail: String,
pub sync_percent: Option<f64>,
}
pub fn grid_query() -> MediaQuery {
MediaQuery {
sort: RsSort::Created,
order: SqlOrder::DESC,
..Default::default()
}
}
const TYPE_ORDER: [LibraryType; 6] = [
LibraryType::Photos,
LibraryType::Movies,
LibraryType::Shows,
LibraryType::Books,
LibraryType::Iptv,
LibraryType::Other,
];
pub fn sort_libraries<L: Borrow<ServerLibraryForRead>>(libraries: &mut [L]) {
let rank = |kind: &LibraryType| TYPE_ORDER.iter().position(|k| k == kind);
libraries.sort_by_cached_key(|l| {
let l = l.borrow();
(rank(&l.kind), l.name.to_lowercase())
});
}
fn escaped(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for byte in text.bytes() {
match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
out.push(byte as char)
}
_ => out.push_str(&format!("%{byte:02X}")),
}
}
out
}
pub fn thumb_url(base: &str, library: &str, media: &str, version: u64) -> String {
format!(
"{base}/libraries/{}/medias/{}/image?size=thumb&v={version}",
escaped(library),
escaped(media),
)
}
pub fn media_file_url(base: &str, library: &str, media: &str, query: &MediaFileQuery) -> String {
let mut params: Vec<String> = (query.unsupported_mime.iter())
.map(|mime| format!("unsupportedMime={}", escaped(mime)))
.collect();
if let Some(page) = query.page {
params.push(format!("page={page}"));
}
if query.raw {
params.push("raw=true".to_owned());
}
let query = if params.is_empty() {
String::new()
} else {
format!("?{}", params.join("&"))
};
format!(
"{base}/libraries/{}/medias/{}{query}",
escaped(library),
escaped(media)
)
}
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
#[derive(Debug, Clone)]
enum Link {
Idle,
Connecting,
Connected,
Failed(String),
}
#[derive(Debug, Clone, Copy)]
struct Held {
revision: u64,
count: u64,
syncing: bool,
big: bool,
marks: u64,
}
impl Held {
fn mark(&mut self) {
self.syncing = true;
self.marks += 1;
}
}
#[derive(Default)]
struct NamesCache {
generation: u64,
libraries: HashMap<String, Arc<Names>>,
}
impl NamesCache {
fn forget(&mut self, library: Option<&str>) {
self.generation += 1;
match library {
Some(library) => {
self.libraries.remove(library);
}
None => self.libraries.clear(),
}
}
fn keep(&mut self, library: &str, generation: u64, names: &Arc<Names>) {
if self.generation == generation {
self.libraries.insert(library.to_owned(), Arc::clone(names));
}
}
}
#[derive(Clone)]
pub struct ServerCopy {
shared: Arc<Shared>,
}
struct Shared {
follow: Task,
mirror: Mirror,
runtime: Arc<dyn Runtime>,
listener: Listener,
link: Mutex<Link>,
attempt: AtomicU64,
api: Mutex<Option<(u64, ServerApi)>>,
connecting: Mutex<Option<AbortHandle>>,
base: Mutex<Option<AuthorizedUrl>>,
woken: Arc<Notify>,
revision: Mutex<u64>,
held: Arc<Mutex<HashMap<String, Held>>>,
names: Arc<Mutex<NamesCache>>,
}
impl std::fmt::Debug for ServerCopy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ServerCopy")
.field("link", &*lock(&self.shared.link))
.finish_non_exhaustive()
}
}
impl Drop for Shared {
fn drop(&mut self) {
self.follow.abort();
if let Some(connecting) = lock(&self.connecting).take() {
connecting.abort();
}
}
}
impl ServerCopy {
#[cfg(all(feature = "sqlite", not(target_arch = "wasm32")))]
pub async fn open(
options: crate::mirror::MirrorOptions,
listener: impl OnChange,
) -> Result<ServerCopy> {
if let Some(folder) = options.path.parent() {
tokio::fs::create_dir_all(folder)
.await
.map_err(|error| Error::Storage {
message: format!("cannot create the copy's folder: {error}"),
})?;
}
let runtime = Arc::new(tokio::runtime::Handle::current());
let mirror = Mirror::open(options).await?;
Ok(ServerCopy::with_mirror(mirror, runtime, listener))
}
pub fn with_mirror(
mirror: Mirror,
runtime: Arc<dyn Runtime>,
listener: impl OnChange,
) -> ServerCopy {
let listener: Listener = Arc::new(listener);
let woken = Arc::new(Notify::new());
let names = Arc::new(Mutex::new(NamesCache::default()));
let held = Arc::new(Mutex::new(HashMap::new()));
let follow = spawn(
runtime.as_ref(),
Box::pin(follow(
mirror.subscribe(),
Arc::clone(&runtime),
Arc::clone(&listener),
Arc::clone(&woken),
Arc::clone(&held),
Arc::clone(&names),
)),
);
ServerCopy {
shared: Arc::new(Shared {
follow,
mirror,
runtime,
listener,
link: Mutex::new(Link::Idle),
attempt: AtomicU64::new(0),
api: Mutex::default(),
connecting: Mutex::default(),
base: Mutex::default(),
woken,
revision: Mutex::new(0),
held,
names,
}),
}
}
pub fn mirror(&self) -> &Mirror {
&self.shared.mirror
}
#[cfg(not(target_arch = "wasm32"))]
pub fn connect<E: std::fmt::Display + 'static>(
&self,
connecting: impl Future<Output = std::result::Result<ServerApi, E>> + Send + 'static,
) {
self.start_connect(Box::pin(async move {
connecting.await.map_err(|error| error.to_string())
}));
}
#[cfg(target_arch = "wasm32")]
pub fn connect<E: std::fmt::Display + 'static>(
&self,
connecting: impl Future<Output = std::result::Result<ServerApi, E>> + 'static,
) {
self.start_connect(Box::pin(async move {
connecting.await.map_err(|error| error.to_string())
}));
}
fn start_connect(&self, connecting: BoxFuture<std::result::Result<ServerApi, String>>) {
let (connecting, handle) = abortable(connecting);
let attempt = {
let mut link = lock(&self.shared.link);
*link = Link::Connecting;
if let Some(previous) = lock(&self.shared.connecting).replace(handle) {
previous.abort();
}
self.shared.attempt.fetch_add(1, Ordering::SeqCst) + 1
};
let copy = Arc::downgrade(&self.shared);
let listener = Arc::clone(&self.shared.listener);
self.shared.runtime.spawn(Box::pin(async move {
listener(&Change::Server);
let Ok(result) = connecting.await else {
return;
};
let Some(shared) = copy.upgrade() else {
return;
};
let copy = ServerCopy { shared };
let connected = {
let mut link = lock(©.shared.link);
if copy.shared.attempt.load(Ordering::SeqCst) != attempt {
return;
}
match result {
Ok(api) => {
copy.shared.mirror.connect(api.clone());
*lock(©.shared.api) = Some((attempt, api));
*link = Link::Connected;
true
}
Err(reason) => {
*link = Link::Failed(reason);
lock(©.shared.api).take();
lock(©.shared.base).take();
copy.shared.mirror.disconnect();
false
}
}
};
if connected {
copy.refresh_base().await;
}
copy.shared.woken.notify_waiters();
(copy.shared.listener)(&Change::Server);
}));
}
pub fn disconnect(&self) {
{
let mut link = lock(&self.shared.link);
self.shared.attempt.fetch_add(1, Ordering::SeqCst);
if let Some(connecting) = lock(&self.shared.connecting).take() {
connecting.abort();
}
*link = Link::Idle;
lock(&self.shared.api).take();
lock(&self.shared.base).take();
self.shared.mirror.disconnect();
}
self.shared.woken.notify_waiters();
let listener = Arc::clone(&self.shared.listener);
self.shared
.runtime
.spawn(Box::pin(async move { listener(&Change::Server) }));
}
pub fn api(&self) -> Option<ServerApi> {
lock(&self.shared.api).clone().map(|(_, api)| api)
}
pub fn reach(&self) -> Reach {
match &*lock(&self.shared.link) {
Link::Idle => Reach::Disconnected,
Link::Connecting => Reach::Connecting,
Link::Failed(reason) => Reach::Offline {
reason: reason.clone(),
retry: true,
},
Link::Connected => match self.shared.mirror.status().connection {
ConnectionState::Connected => Reach::Connected,
ConnectionState::Offline(reason) => Reach::Offline {
reason,
retry: false,
},
ConnectionState::Connecting | ConnectionState::Disconnected => Reach::Connecting,
},
}
}
fn unreachable(&self) -> bool {
matches!(self.reach(), Reach::Disconnected | Reach::Offline { .. })
}
pub async fn ready(&self, library: Option<&str>) {
let known = async || match library {
Some(library) => {
matches!(self.shared.mirror.library(library).await, Ok(Some(_)))
|| self.shared.mirror.status().connection == ConnectionState::Connected
}
None => {
!self
.shared
.mirror
.libraries()
.await
.unwrap_or_default()
.is_empty()
|| self.shared.mirror.status().connection == ConnectionState::Connected
}
};
let wait = async {
loop {
let woken = self.shared.woken.notified();
if known().await || self.unreachable() {
return;
}
woken.await;
}
};
timeout(self.shared.runtime.as_ref(), FIRST_WAIT, wait).await;
}
pub async fn libraries(&self) -> Result<Vec<ServerLibraryForRead>> {
let mut libraries = self.shared.mirror.libraries().await?;
sort_libraries(&mut libraries);
Ok(libraries)
}
pub fn syncing(&self, library: &str) -> bool {
matches!(
self.shared.mirror.status().libraries.get(library),
Some(LibrarySyncState::Queued | LibrarySyncState::Syncing(_))
)
}
pub fn sync_summary(&self, library: Option<&str>) -> Option<String> {
text::sync_summary(&self.shared.mirror.status(), library)
}
pub fn focus(&self, library: Option<&str>) {
if self.shared.mirror.priority().as_deref() != library {
self.shared.mirror.set_priority(library);
}
}
pub async fn library(&self, library: &str) -> Result<LibraryView> {
self.ready(Some(library)).await;
let found = self
.shared
.mirror
.library(library)
.await?
.ok_or_else(|| Error::NotFound {
message: format!("No library {library} on this server."),
path: None,
})?;
let state = self.shared.mirror.status().libraries.get(library).cloned();
let syncing = matches!(
state,
Some(LibrarySyncState::Queued | LibrarySyncState::Syncing(_))
);
let held = lock(&self.shared.held).get(library).copied();
let marks = held.map_or(0, |held| held.marks);
let shown = match held {
Some(held) if syncing => held,
_ => {
let count = self.count(library, &grid_query()).await?;
let revision = match held {
Some(held) if !held.syncing && held.count == count => held.revision,
_ => {
let mut revision = lock(&self.shared.revision);
*revision += 1;
*revision
}
};
Held {
revision,
count,
syncing: false,
big: false,
marks,
}
}
};
let big = syncing
&& (shown.big
|| matches!(&state, Some(LibrarySyncState::Syncing(p))
if p.kind == SyncKind::Medias && p.total.unwrap_or(0) > BIG_SYNC)
|| !self.shared.mirror.synced_once(library).await?);
{
let mut held = lock(&self.shared.held);
let current = held.get(library).map_or(marks, |held| held.marks);
held.insert(
library.into(),
Held {
big,
syncing: syncing || current != marks,
marks: current,
..shown
},
);
}
let (detail, percent) = text::sync_progress(state.as_ref());
Ok(LibraryView {
library: found,
count: shown.count,
revision: shown.revision,
syncing,
copying: big,
sync_detail: if big { detail } else { String::new() },
sync_percent: percent.filter(|_| big),
})
}
pub async fn count(&self, library: &str, query: &MediaQuery) -> Result<u64> {
self.shared.mirror.count_medias(library, query).await
}
pub async fn media(&self, library: &str, id: &str) -> Result<Option<MediaItem>> {
self.shared.mirror.media(library, id).await
}
pub async fn medias(
&self,
library: &str,
query: &MediaQuery,
offset: usize,
limit: usize,
) -> Result<Vec<MediaItem>> {
self.shared
.mirror
.medias_at(library, query, offset, limit)
.await
}
pub async fn related(&self, library: &str, media: &MediaItem) -> Result<Related> {
self.shared.mirror.related(library, media).await
}
pub async fn people(&self, library: &str) -> Result<Vec<Person>> {
self.shared.mirror.people(library).await
}
pub async fn person(&self, library: &str, id: &str) -> Result<Option<Person>> {
self.shared.mirror.person(library, id).await
}
pub async fn item_image(&self, library: &str, item: ItemImage<'_>) -> Result<Option<Vec<u8>>> {
self.shared.mirror.item_image(library, item).await
}
pub async fn tags(&self, library: &str) -> Result<Vec<Tag>> {
self.shared.mirror.tags(library).await
}
pub async fn tag(&self, library: &str, id: &str) -> Result<Option<Tag>> {
self.shared.mirror.tag(library, id).await
}
pub async fn series(&self, library: &str) -> Result<Vec<ItemWithRelations<Serie>>> {
self.shared.mirror.series(library).await
}
pub async fn serie(&self, library: &str, id: &str) -> Result<Option<ItemWithRelations<Serie>>> {
self.shared.mirror.serie(library, id).await
}
pub async fn episodes(&self, library: &str, serie: Option<&str>) -> Result<Vec<Episode>> {
self.shared.mirror.episodes(library, serie).await
}
pub async fn episode(&self, library: &str, id: &str) -> Result<Option<Episode>> {
self.shared.mirror.episode(library, id).await
}
pub async fn movies(&self, library: &str) -> Result<Vec<ItemWithRelations<Movie>>> {
self.shared.mirror.movies(library).await
}
pub async fn movie(&self, library: &str, id: &str) -> Result<Option<ItemWithRelations<Movie>>> {
self.shared.mirror.movie(library, id).await
}
pub async fn books(&self, library: &str) -> Result<Vec<ItemWithRelations<Book>>> {
self.shared.mirror.books(library).await
}
pub async fn book(&self, library: &str, id: &str) -> Result<Option<ItemWithRelations<Book>>> {
self.shared.mirror.book(library, id).await
}
pub async fn names(&self, library: &str) -> Result<Arc<Names>> {
let generation = {
let cache = lock(&self.shared.names);
if let Some(names) = cache.libraries.get(library) {
return Ok(Arc::clone(names));
}
cache.generation
};
let people = self.shared.mirror.people(library).await?;
let tags = self.shared.mirror.tags(library).await?;
let names = Arc::new(Names::new(people, tags));
lock(&self.shared.names).keep(library, generation, &names);
Ok(names)
}
pub fn base(&self) -> Option<AuthorizedUrl> {
lock(&self.shared.base).clone()
}
pub fn set_base(&self, base: AuthorizedUrl) {
*lock(&self.shared.base) = Some(base);
}
pub async fn refresh_base(&self) {
let Some((attempt, api)) = lock(&self.shared.api).clone() else {
return;
};
let read = timeout(
self.shared.runtime.as_ref(),
BASE_WAIT,
api.client().authorized_url("", &[]),
);
if let Some(Ok(mut base)) = read.await
&& self.shared.attempt.load(Ordering::SeqCst) == attempt
{
base.url = base.url.trim_end_matches('/').to_owned();
let changed = lock(&self.shared.base).replace(base.clone()) != Some(base);
if changed {
let listener = Arc::clone(&self.shared.listener);
self.shared
.runtime
.spawn(Box::pin(async move { listener(&Change::Server) }));
}
}
}
pub async fn renew_base(&self) {
if let Some(api) = self.api() {
let renew = api.client().renew_token();
let _ = timeout(self.shared.runtime.as_ref(), BASE_WAIT, renew).await;
}
self.refresh_base().await;
}
pub async fn locate(
&self,
library: &str,
media: &str,
query: &MediaFileQuery,
fresh: bool,
) -> Option<AuthorizedUrl> {
if fresh {
self.renew_base().await;
}
if let Some(api) = self.shared.mirror.library_api(library)
&& let Some(Ok(url)) = timeout(
self.shared.runtime.as_ref(),
BASE_WAIT,
api.media_url(media, query),
)
.await
{
return Some(url);
}
let base = self.base()?;
Some(AuthorizedUrl {
url: media_file_url(&base.url, library, media, query),
..base
})
}
}
async fn follow(
mut received: broadcast::Receiver<MirrorEvent>,
runtime: Arc<dyn Runtime>,
listener: Listener,
woken: Arc<Notify>,
held: Arc<Mutex<HashMap<String, Held>>>,
names: Arc<Mutex<NamesCache>>,
) {
let (mut server, mut all) = (false, false);
let mut libraries = BTreeMap::<String, BTreeMap<SyncKind, Ids>>::new();
let mut timer: Option<BoxFuture<()>> = None;
loop {
let event = match timer.take() {
Some(running) => match select(Box::pin(received.recv()), running).await {
Either::Left((event, running)) => {
timer = Some(running);
event
}
Either::Right(((), _)) => {
if all {
listener(&Change::All);
} else {
if server {
listener(&Change::Server);
}
for (library, mut items) in std::mem::take(&mut libraries) {
items.retain(
|_, ids| !matches!(ids, Ids::Listed(ids) if ids.is_empty()),
);
listener(&Change::Library { library, items });
}
}
(server, all) = (false, false);
libraries.clear();
continue;
}
},
None => received.recv().await,
};
match event {
Ok(MirrorEvent::Changed { library, changes }) => {
if changes.contains_key(&SyncKind::People) || changes.contains_key(&SyncKind::Tags)
{
lock(&names).forget(Some(&library));
}
let items = libraries.entry(library).or_default();
for (kind, ids) in changes {
(items.entry(kind))
.or_insert_with(|| Ids::Listed(ItemIds::default()))
.merge(ids);
}
}
Ok(MirrorEvent::Sync { library, state }) => {
if matches!(
state,
LibrarySyncState::Queued | LibrarySyncState::Syncing(_)
) && let Some(shown) = lock(&held).get_mut(&library)
{
shown.mark();
}
libraries.entry(library).or_default();
}
Ok(MirrorEvent::Libraries | MirrorEvent::Connection(_)) => server = true,
Err(broadcast::error::RecvError::Lagged(_)) => {
lock(&names).forget(None);
lock(&held).values_mut().for_each(Held::mark);
all = true;
}
Err(broadcast::error::RecvError::Closed) => break,
}
if timer.is_none() {
timer = Some(runtime.sleep(BURST));
}
woken.notify_waiters();
}
}
#[cfg(all(test, feature = "sqlite"))]
mod tests;