use std::collections::HashMap;
use std::sync::{Mutex, PoisonError};
use serde::de::DeserializeOwned;
use super::store::{Changes, FileLinks, SyncKind};
use super::sync::{PAGE_OVERLAP, fetch_page};
use super::{Inner, Mirror, PAGE_SIZE, not_connected};
use crate::client::now_ms;
use crate::error::{Error, Result};
use crate::library::LibraryApi;
use crate::types::ItemWithRelations;
use crate::types::episode::Episode;
use crate::types::library::LibraryType;
use crate::types::movie::Movie;
const MAX_PAGES: usize = 1000;
const MAX_PAGE_READS: usize = 3;
#[derive(Default)]
pub(super) struct ViewingWrites {
counts: Mutex<(usize, u64)>,
write: tokio::sync::Mutex<()>,
}
impl ViewingWrites {
fn counts(&self) -> std::sync::MutexGuard<'_, (usize, u64)> {
self.counts.lock().unwrap_or_else(PoisonError::into_inner)
}
fn seen(&self) -> (usize, u64) {
*self.counts()
}
pub(super) fn started(&self) -> u64 {
self.seen().1
}
fn quiet_since(&self, started: u64) -> bool {
self.seen() == (0, started)
}
fn begin(&self) -> Pending<'_> {
let mut counts = self.counts();
counts.0 += 1;
counts.1 += 1;
Pending { writes: self }
}
}
struct Pending<'a> {
writes: &'a ViewingWrites,
}
impl Drop for Pending<'_> {
fn drop(&mut self) {
let mut counts = self.writes.counts();
counts.0 = counts.0.saturating_sub(1);
}
}
impl Inner {
pub(super) async fn write_fetched(
&self,
library: &str,
generation: i64,
mut changes: Changes,
started: u64,
) -> Result<()> {
let _write = self.viewing.write.lock().await;
if !self.viewing.quiet_since(started) {
self.keep_viewing(library, &mut changes).await?;
}
self.write(library, generation, changes).await
}
async fn keep_viewing(&self, library: &str, changes: &mut Changes) -> Result<()> {
if !changes.movies.is_empty() {
let ids = changes.movies.iter().map(|m| m.item.id.clone()).collect();
let stored: HashMap<String, Movie> = (self
.stored::<ItemWithRelations<Movie>>(library, SyncKind::Movies, ids)
.await?
.into_iter())
.map(|movie| (movie.item.id.clone(), movie.item))
.collect();
for movie in &mut changes.movies {
if let Some(stored) = stored.get(&movie.item.id) {
movie.item.watched = stored.watched;
movie.item.progress = stored.progress;
movie.item.progress_modified = stored.progress_modified;
}
}
}
if !changes.episodes.is_empty() {
let ids = changes.episodes.iter().map(Episode::id).collect();
let stored: HashMap<String, Episode> = (self
.stored::<Episode>(library, SyncKind::Episodes, ids)
.await?
.into_iter())
.map(|episode| (episode.id(), episode))
.collect();
for episode in &mut changes.episodes {
if let Some(stored) = stored.get(&episode.id()) {
episode.watched = stored.watched;
episode.progress = stored.progress;
episode.progress_modified = stored.progress_modified;
}
}
}
Ok(())
}
async fn stored<T: DeserializeOwned>(
&self,
library: &str,
kind: SyncKind,
ids: Vec<String>,
) -> Result<Vec<T>> {
let values = self.store.items_by_id(library, kind, ids).await?;
(values.into_iter())
.map(|value| {
serde_json::from_value(value).map_err(|e| {
Error::storage(format!("local copy: unreadable {}: {e}", kind.name()))
})
})
.collect()
}
}
impl Mirror {
pub async fn file_links(&self, library: &str) -> Result<FileLinks> {
self.inner.store.file_links(library).await
}
pub async fn refresh_viewing(&self, library: &str) -> Result<()> {
let kind = match self.inner.library(library).map(|l| l.kind) {
Some(LibraryType::Movies) => SyncKind::Movies,
Some(LibraryType::Shows) => SyncKind::Episodes,
_ => return Ok(()),
};
let api = self.inner.api(library).ok_or_else(not_connected)?;
let generation = self.generation(library).await?;
let mut offset: u32 = 0;
let mut first: Option<String> = None;
let viewing = &self.inner.viewing;
for _ in 0..MAX_PAGES {
let mut reads = 0;
let (page, written) = loop {
let started = viewing.started();
let page = fetch_page(&api, kind, None, offset).await?;
let write = viewing.write.lock().await;
reads += 1;
if viewing.quiet_since(started) {
break (page, Some(write));
}
if reads >= MAX_PAGE_READS {
break (page, None);
}
};
if offset > 0 && page.ids.first() == first.as_ref() {
break;
}
first = first.or_else(|| page.ids.first().cloned());
let len = page.len;
if written.is_some() {
self.inner.write(library, generation, page.changes).await?;
}
drop(written);
if len < PAGE_SIZE as usize {
break;
}
offset += len as u32 - PAGE_OVERLAP;
}
Ok(())
}
pub async fn set_movie_watched(&self, library: &str, movie: &str, watched: bool) -> Result<()> {
let _pending = self.inner.viewing.begin();
let date = watched.then(now_ms);
self.connected(library)?
.set_movie_watched(movie, date.unwrap_or(0))
.await?;
self.patch_movie(library, movie, |movie| movie.watched = date)
.await
}
pub async fn set_movie_progress(
&self,
library: &str,
movie: &str,
progress: u64,
) -> Result<()> {
let _pending = self.inner.viewing.begin();
self.connected(library)?
.set_movie_progress(movie, progress)
.await?;
self.patch_movie(library, movie, |movie| {
movie.progress = Some(progress);
movie.progress_modified = Some(now_ms().max(0) as u64);
})
.await
}
pub async fn set_episode_watched(
&self,
library: &str,
episode: &Episode,
watched: bool,
) -> Result<()> {
let _pending = self.inner.viewing.begin();
let date = watched.then(now_ms);
let Episode {
serie,
season,
number,
..
} = episode;
self.connected(library)?
.set_episode_watched(serie, *season, *number, date.unwrap_or(0))
.await?;
self.patch_episode(library, &episode.id(), |episode| episode.watched = date)
.await
}
pub async fn set_episode_progress(
&self,
library: &str,
episode: &Episode,
progress: u64,
) -> Result<()> {
let _pending = self.inner.viewing.begin();
let Episode {
serie,
season,
number,
..
} = episode;
self.connected(library)?
.set_episode_progress(serie, *season, *number, progress)
.await?;
self.patch_episode(library, &episode.id(), |episode| {
episode.progress = Some(progress);
episode.progress_modified = Some(now_ms().max(0) as u64);
})
.await
}
fn connected(&self, library: &str) -> Result<LibraryApi> {
self.inner.api(library).ok_or_else(not_connected)
}
async fn generation(&self, library: &str) -> Result<i64> {
let state = self.inner.store.sync_state(library).await?;
Ok(state.map_or(0, |state| state.generation))
}
async fn patch_movie(
&self,
library: &str,
movie: &str,
patch: impl FnOnce(&mut Movie),
) -> Result<()> {
let _write = self.inner.viewing.write.lock().await;
if let Some(mut stored) = self.movie(library, movie).await? {
patch(&mut stored.item);
let generation = self.generation(library).await?;
(self.inner)
.write(library, generation, Changes::movie(stored))
.await?;
}
Ok(())
}
async fn patch_episode(
&self,
library: &str,
id: &str,
patch: impl FnOnce(&mut Episode),
) -> Result<()> {
let _write = self.inner.viewing.write.lock().await;
if let Some(mut stored) = self.episode(library, id).await? {
patch(&mut stored);
let generation = self.generation(library).await?;
(self.inner)
.write(library, generation, Changes::episode(stored))
.await?;
}
Ok(())
}
}