use serde_json::json;
use super::*;
use crate::mirror::MirrorOptions;
use crate::mirror::tests::{FakeServer, TempDir, media, sample_library, server_api, until};
fn recorder() -> (impl OnChange, Arc<Mutex<Vec<Change>>>) {
let changes = Arc::new(Mutex::new(Vec::new()));
let kept = Arc::clone(&changes);
let listener = move |change: &Change| {
kept.lock().unwrap().push(change.clone());
};
(listener, changes)
}
async fn open(dir: &TempDir) -> (ServerCopy, Arc<Mutex<Vec<Change>>>) {
let (listener, changes) = recorder();
let path = dir.0.join("server").join("mirror.db");
let copy = ServerCopy::open(MirrorOptions::new(path), listener)
.await
.unwrap();
(copy, changes)
}
fn connect(copy: &ServerCopy, fake: &Arc<FakeServer>) {
let fake = Arc::clone(fake);
copy.connect(async move { Ok::<_, Error>(server_api(fake)) });
}
async fn synced(copy: &ServerCopy, library: &str) -> LibraryView {
until("the library synced", async || {
!copy.library(library).await.unwrap().syncing
})
.await;
copy.library(library).await.unwrap()
}
#[tokio::test]
async fn a_first_sync_shows_its_progress_then_the_medias() {
let dir = TempDir::new();
let fake = FakeServer::new(vec![sample_library("photos")]);
let (copy, changes) = open(&dir).await;
assert_eq!(copy.reach(), Reach::Disconnected);
*fake.gated.lock().unwrap() = Some("photos".into());
let gate = fake.gate.lock().await;
copy.focus(Some("photos"));
connect(©, &fake);
let first = copy.library("photos").await.unwrap();
assert!(first.syncing && first.copying, "{first:?}");
assert_eq!((first.count, first.sync_detail.is_empty()), (0, false));
assert_eq!(copy.mirror().priority().as_deref(), Some("photos"));
copy.focus(None);
copy.library("photos").await.unwrap();
assert_eq!(copy.mirror().priority(), None);
copy.focus(Some("photos"));
drop(gate);
let done = synced(©, "photos").await;
assert_eq!(done.count, 3);
assert!(!done.copying && done.sync_detail.is_empty() && done.sync_percent.is_none());
assert!(done.revision > first.revision, "the grid reads its medias");
assert_eq!(copy.reach(), Reach::Connected);
assert_eq!(
copy.library("photos").await.unwrap().revision,
done.revision
);
let ids: Vec<String> = (copy
.medias("photos", &grid_query(), 0, 10)
.await
.unwrap()
.into_iter())
.map(|m| m.item.id)
.collect();
assert_eq!(ids, ["m3", "m2", "m1"], "newest first");
until("the changes told", async || {
let changes = changes.lock().unwrap();
changes.contains(&Change::Server)
&& (changes.iter())
.any(|c| c.library() == Some("photos") && c.touches(SyncKind::Medias))
})
.await;
}
#[tokio::test]
async fn a_library_holds_still_while_it_syncs_again() {
let dir = TempDir::new();
let fake = FakeServer::new(vec![sample_library("photos")]);
let (copy, _) = open(&dir).await;
connect(©, &fake);
let before = synced(©, "photos").await;
*fake.gated.lock().unwrap() = Some("photos".into());
let gate = fake.gate.lock().await;
fake.edit("photos", |library| {
library.medias.push(media("m4", 400, json!({})));
});
copy.mirror().sync_library("photos");
until("the sync started", async || copy.syncing("photos")).await;
let held = copy.library("photos").await.unwrap();
assert!(held.syncing && !held.copying, "a small sync shows the grid");
assert_eq!((held.count, held.revision), (before.count, before.revision));
drop(gate);
let after = synced(©, "photos").await;
assert_eq!(after.count, 4);
assert!(after.revision > before.revision);
}
#[tokio::test]
async fn a_sync_over_between_two_reads_brings_a_new_revision() {
let dir = TempDir::new();
let fake = FakeServer::new(vec![sample_library("photos")]);
let (copy, _) = open(&dir).await;
connect(©, &fake);
let before = synced(©, "photos").await;
fake.edit("photos", |library| {
library.medias[0] = media("m1", 400, json!({}));
});
copy.mirror().sync_library("photos");
until("the copy has the edit", async || {
copy.medias("photos", &grid_query(), 0, 1).await.unwrap()[0]
.item
.id
== "m1"
})
.await;
until("the sync ended", async || !copy.syncing("photos")).await;
let after = copy.library("photos").await.unwrap();
assert_eq!(after.count, before.count);
assert!(after.revision > before.revision);
}
#[tokio::test]
async fn a_live_change_names_its_items() {
let dir = TempDir::new();
let fake = FakeServer::new(vec![sample_library("photos")]);
let (copy, changes) = open(&dir).await;
connect(©, &fake);
synced(©, "photos").await;
until("the event stream", async || fake.has_event_stream()).await;
until_told(&changes, "photos").await;
changes.lock().unwrap().clear();
fake.send_event(
"medias",
"medias",
json!({"library": "photos", "medias": [
{"action": "updated", "media": media("m2", 500, json!({}))},
{"action": "added", "media": media("m4", 500, json!({}))},
{"action": "deleted", "media": media("m1", 500, json!({}))}
]}),
);
let told = until_told(&changes, "photos").await;
let expected = ItemIds {
added: ["m4".to_owned()].into(),
updated: ["m2".to_owned()].into(),
removed: ["m1".to_owned()].into(),
};
assert_eq!(
told,
BTreeMap::from([(SyncKind::Medias, Ids::Listed(expected))])
);
let change = Change::Library {
library: "photos".into(),
items: told,
};
assert!(change.ids(SyncKind::Medias).is_some() && change.ids(SyncKind::People).is_none());
assert_eq!(Change::All.ids(SyncKind::People), Some(Ids::Many));
assert_eq!(Change::Server.ids(SyncKind::Medias), None);
let m2 = copy.media("photos", "m2").await.unwrap().unwrap();
assert_eq!(m2.item.created, Some(500));
}
async fn until_told(changes: &Mutex<Vec<Change>>, library: &str) -> BTreeMap<SyncKind, Ids> {
let mut told = None;
until("the change told", async || {
told = (changes.lock().unwrap().iter()).find_map(|change| match change {
Change::Library { library: l, items } if l == library && !items.is_empty() => {
Some(items.clone())
}
_ => None,
});
told.is_some()
})
.await;
told.unwrap()
}
#[test]
fn ids_merge_into_their_net_change() {
let ids = |added: &[&str], updated: &[&str], removed: &[&str]| ItemIds {
added: added.iter().map(|s| s.to_string()).collect(),
updated: updated.iter().map(|s| s.to_string()).collect(),
removed: removed.iter().map(|s| s.to_string()).collect(),
};
let mut burst = ids(&["new", "gone"], &["edited"], &["back"]);
burst.merge(ids(&["back"], &["new", "edited"], &["gone", "edited"]));
assert_eq!(burst, ids(&["new"], &["back"], &["edited"]));
let mut odd = ids(&[], &["u"], &["r"]);
odd.merge(ids(&["u"], &["r"], &[]));
assert_eq!(odd, ids(&[], &["r", "u"], &[]));
let mut listed = Ids::Listed(ItemIds::default());
let many: Vec<String> = (0..=MAX_IDS).map(|i| i.to_string()).collect();
listed.merge(ids(
&[],
&many.iter().map(String::as_str).collect::<Vec<_>>(),
&[],
));
assert_eq!(listed, Ids::Many);
}
#[tokio::test]
async fn a_failed_connection_waits_for_a_retry() {
let dir = TempDir::new();
let fake = FakeServer::new(vec![sample_library("photos")]);
let (copy, _) = open(&dir).await;
copy.connect(async { Err::<ServerApi, _>("The server does not answer.") });
until("offline", async || {
matches!(copy.reach(), Reach::Offline { .. })
})
.await;
assert_eq!(
copy.reach(),
Reach::Offline {
reason: "The server does not answer.".into(),
retry: true
}
);
let started = std::time::Instant::now();
copy.ready(None).await;
assert!(started.elapsed() < Duration::from_secs(1));
assert!(copy.libraries().await.unwrap().is_empty());
connect(©, &fake);
until("connected", async || copy.reach() == Reach::Connected).await;
copy.ready(None).await;
assert_eq!(copy.libraries().await.unwrap().len(), 1);
copy.disconnect();
assert_eq!(copy.reach(), Reach::Disconnected);
assert!(copy.api().is_none());
}
fn stalled() -> (
impl Future<Output = Result<ServerApi>> + Send + 'static,
tokio::sync::oneshot::Receiver<()>,
) {
let (kept, dropped) = tokio::sync::oneshot::channel::<()>();
let connecting = async move {
let _kept = kept;
std::future::pending::<Result<ServerApi>>().await
};
(connecting, dropped)
}
#[tokio::test]
async fn a_disconnect_while_connecting_is_told() {
let dir = TempDir::new();
let (copy, changes) = open(&dir).await;
let (connecting, dropped) = stalled();
copy.connect(connecting);
until("the connection started", async || {
!changes.lock().unwrap().is_empty()
})
.await;
assert_eq!(copy.reach(), Reach::Connecting);
changes.lock().unwrap().clear();
copy.disconnect();
assert_eq!(copy.reach(), Reach::Disconnected);
until("the disconnect was told", async || {
changes.lock().unwrap().contains(&Change::Server)
})
.await;
assert!(dropped.await.is_err());
}
#[tokio::test]
async fn a_dropped_copy_stops_its_connection() {
let dir = TempDir::new();
let (copy, _) = open(&dir).await;
let (connecting, dropped) = stalled();
copy.connect(connecting);
drop(copy);
let stopped = tokio::time::timeout(Duration::from_secs(5), dropped).await;
assert!(matches!(stopped, Ok(Err(_))), "the connection still runs");
}
#[tokio::test]
async fn files_are_located_on_the_base_url_without_a_connection() {
let dir = TempDir::new();
let (copy, _) = open(&dir).await;
assert!(
copy.locate("l", "m", &Default::default(), false)
.await
.is_none()
);
copy.set_base(AuthorizedUrl {
url: "http://s".into(),
token: "t".into(),
expires: 0,
});
let query = MediaFileQuery {
unsupported_mime: vec!["all".into()],
..Default::default()
};
let located = copy.locate("l", "m", &query, false).await.unwrap();
assert_eq!(
(located.url.as_str(), located.token.as_str()),
("http://s/libraries/l/medias/m?unsupportedMime=all", "t")
);
copy.disconnect();
assert!(copy.base().is_none());
assert!(copy.locate("l", "m", &query, false).await.is_none());
}
#[tokio::test]
async fn a_library_gone_from_the_server_is_not_waited_for() {
let dir = TempDir::new();
let fake = FakeServer::new(vec![sample_library("photos")]);
let (copy, _) = open(&dir).await;
connect(©, &fake);
synced(©, "photos").await;
let started = std::time::Instant::now();
let gone = copy.library("gone").await;
assert!(matches!(gone, Err(Error::NotFound { .. })), "{gone:?}");
assert!(started.elapsed() < Duration::from_secs(2), "waited for it");
}
#[tokio::test]
async fn an_empty_library_syncing_again_shows_its_grid() {
let dir = TempDir::new();
let mut empty = sample_library("movies");
empty.medias.clear();
let fake = FakeServer::new(vec![empty]);
let (copy, _) = open(&dir).await;
connect(©, &fake);
synced(©, "movies").await;
*fake.gated.lock().unwrap() = Some("movies".into());
let gate = fake.gate.lock().await;
copy.mirror().sync_library("movies");
until("the sync started", async || copy.syncing("movies")).await;
let view = copy.library("movies").await.unwrap();
assert!(view.syncing && !view.copying, "{view:?}");
drop(gate);
}
#[tokio::test]
async fn a_sync_with_nothing_new_tells_no_items() {
let dir = TempDir::new();
let fake = FakeServer::new(vec![sample_library("photos")]);
let (copy, changes) = open(&dir).await;
connect(©, &fake);
synced(©, "photos").await;
until_told(&changes, "photos").await;
tokio::time::sleep(BURST * 2).await;
changes.lock().unwrap().clear();
copy.mirror().sync_library("photos");
synced(©, "photos").await;
tokio::time::sleep(BURST * 2).await;
let told: Vec<Change> = changes.lock().unwrap().clone();
assert!(
told.iter()
.all(|c| !matches!(c, Change::Library { items, .. } if !items.is_empty())),
"{told:?}"
);
}
#[tokio::test]
async fn names_are_read_once_until_the_library_changes() {
let dir = TempDir::new();
let fake = FakeServer::new(vec![sample_library("photos")]);
let (copy, _) = open(&dir).await;
connect(©, &fake);
synced(©, "photos").await;
let names = copy.names("photos").await.unwrap();
assert!(Arc::ptr_eq(&names, ©.names("photos").await.unwrap()));
let medias = copy.medias("photos", &grid_query(), 0, 10).await.unwrap();
let m1 = medias.iter().find(|m| m.item.id == "m1").unwrap();
let rows = super::super::details::details(m1, &names);
assert!(
rows.iter()
.any(|d| d.label == "People" && d.value == "Alice")
);
}
#[test]
fn names_read_before_a_change_are_not_kept() {
let mut cache = NamesCache::default();
let names = Arc::new(Names::default());
let generation = cache.generation;
cache.forget(Some("photos"));
cache.keep("photos", generation, false, &names);
assert!(cache.libraries.is_empty());
cache.keep("photos", cache.generation, false, &names);
assert!(cache.get("photos", false).is_some());
}
#[test]
fn names_read_while_locked_are_read_again_once_unlocked() {
let mut cache = NamesCache::default();
let encrypted = Arc::new(Names::default());
cache.keep("vault", cache.generation, false, &encrypted);
assert!(cache.get("vault", false).is_some());
assert!(cache.get("vault", true).is_none());
let decrypted = Arc::new(Names::default());
cache.keep("vault", cache.generation, true, &decrypted);
let kept = cache.get("vault", true).unwrap();
assert!(Arc::ptr_eq(&kept, &decrypted));
}
#[test]
fn libraries_sort_by_type_then_name() {
let library = |id: &str, name: &str, kind: &str| -> ServerLibraryForRead {
serde_json::from_value(json!({"id": id, "name": name, "type": kind})).unwrap()
};
let mut libraries = vec![
library("1", "Films", "movies"),
library("2", "travel", "photos"),
library("3", "Family", "photos"),
];
sort_libraries(&mut libraries);
let ids: Vec<&str> = libraries.iter().map(|l| l.id.as_str()).collect();
assert_eq!(ids, ["3", "2", "1"]);
let mut refs: Vec<&ServerLibraryForRead> = libraries.iter().rev().collect();
sort_libraries(&mut refs);
assert_eq!(refs[0].id, "3");
}
#[test]
fn file_urls_escape_their_ids_and_carry_no_token() {
assert_eq!(
thumb_url("https://s.example:443", "lib 1", "m/2", 3),
"https://s.example:443/libraries/lib%201/medias/m%2F2/image?size=thumb&v=3"
);
assert_eq!(
media_file_url("http://s", "l", "m", &Default::default()),
"http://s/libraries/l/medias/m"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn reads_work_from_a_thread_outside_tokio() {
let dir = TempDir::new();
let fake = FakeServer::new(vec![sample_library("photos")]);
let (copy, _) = open(&dir).await;
connect(©, &fake);
synced(©, "photos").await;
let reader = copy.clone();
let thread = std::thread::spawn(move || {
crate::mirror::runtime::tests::block_on(async move {
let view = reader.library("photos").await.unwrap();
let medias = reader.medias("photos", &grid_query(), 0, 10).await.unwrap();
let m1 = medias.iter().find(|m| m.item.id == "m1").unwrap();
let related = reader.related("photos", m1).await.unwrap();
let thumb = reader.mirror().thumb("photos", &m1.item).await.unwrap();
(view.count, medias.len(), related.people.len(), thumb.len())
})
});
let read = tokio::task::spawn_blocking(move || thread.join().unwrap())
.await
.unwrap();
assert_eq!(read, (3, 3, 1, 10));
}
#[tokio::test]
async fn a_new_token_is_told_as_a_server_change() {
let dir = TempDir::new();
let fake = FakeServer::new(vec![sample_library("photos")]);
let (copy, changes) = open(&dir).await;
connect(©, &fake);
synced(©, "photos").await;
let first = copy.base().unwrap();
tokio::time::sleep(BURST * 2).await;
changes.lock().unwrap().clear();
copy.refresh_base().await;
tokio::time::sleep(Duration::from_millis(50)).await;
assert!(!changes.lock().unwrap().contains(&Change::Server));
copy.api().unwrap().client().set_token(crate::ServerToken {
token: "renewed".into(),
expires: i64::MAX,
});
copy.refresh_base().await;
assert_eq!(copy.base().unwrap().token, "renewed");
assert_ne!(copy.base().unwrap(), first);
until("the change told", async || {
changes.lock().unwrap().contains(&Change::Server)
})
.await;
}
#[tokio::test]
async fn a_shows_library_reads_as_a_catalog_and_its_pages() {
use crate::app::catalog::{CatalogKind, Playable, TitleSort, WatchedFilter};
let dir = TempDir::new();
let mut library = sample_library("shows");
library.info["type"] = json!("shows");
let m3 = (library.medias.iter_mut())
.find(|m| m["id"] == "m3")
.unwrap();
m3["type"] = json!("video");
m3["mimetype"] = json!("video/mp4");
for i in 0..101 {
let mut image = media(
&format!("a{i:03}"),
100,
json!({"series": [{"id": "show", "season": 1, "episode": 2}]}),
);
image["name"] = json!(format!("a{i:03}.jpg"));
library.medias.push(image);
}
let fake = FakeServer::new(vec![library, sample_library("photos")]);
let (copy, _) = open(&dir).await;
connect(©, &fake);
synced(©, "shows").await;
synced(©, "photos").await;
assert!(copy.catalog("photos").await.unwrap().is_none());
let catalog = copy.catalog("shows").await.unwrap().unwrap();
assert_eq!((catalog.kind(), catalog.len()), (CatalogKind::Shows, 1));
let titles = catalog.titles(TitleSort::Name, WatchedFilter::All);
assert!(titles[0].available, "its episode has a file");
let page = copy.show_page("shows", "show").await.unwrap().unwrap();
assert_eq!(page.seasons.len(), 1);
assert_eq!(page.play.as_ref().unwrap().label, "Play S1, E2");
assert!(copy.show_page("shows", "nothing").await.unwrap().is_none());
let episode = Playable::Episode {
serie: "show".into(),
season: 1,
number: 2,
};
let files = copy.files("shows", &episode).await.unwrap();
assert_eq!(files.len(), 1, "its video");
(copy.record_playback("shows", &episode, 30_000, 1_000_000))
.await
.unwrap();
let page = copy.show_page("shows", "show").await.unwrap().unwrap();
assert_eq!(page.play.as_ref().unwrap().start, 30_000);
(copy.record_playback("shows", &episode, 950_000, 1_000_000))
.await
.unwrap();
let page = copy.show_page("shows", "show").await.unwrap().unwrap();
assert!(page.seasons[0].episodes[0].watched);
assert!(page.play.is_none(), "nothing left to watch");
}