[library] Together: shared notes and what travels between people (strictly parsed), placement in one's own copy (exact, approximate, lost), the spoiler guard, people, shares, hides, buddy reads, recording links and approval as ops; v0.6.0

This commit is contained in:
2026-11-22 11:21:55 +01:00
parent 7be8fca42b
commit 22c898e38f
9 changed files with 991 additions and 7 deletions
+353
View File
@@ -0,0 +1,353 @@
//! Day 5 (the app's `docs/05_together.md`): reading together. Mandatory tests 2 (matching), 3 (spoiler guard) and
//! 4 (approval, the core's half), and the strict parsing of what another person's Liber sends.
use liber_format::{Document, Limits};
use liber_library::library::{BookInfo, Colour, Mark};
use liber_library::together::{
self, BookRef, Placement, Reach, RecordingSource, SharedNote, Spot, Wire, folded, place,
};
use liber_library::{Clock, Event, Library, Op};
fn fb2(title: &str, chapters: &[(&str, &[&str])]) -> Document {
let mut body = String::new();
for (t, paras) in chapters {
body.push_str(&format!("<section><title><p>{t}</p></title>"));
for p in *paras {
body.push_str(&format!("<p>{p}</p>"));
}
body.push_str("</section>");
}
let x = format!(
r#"<?xml version="1.0" encoding="utf-8"?>
<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0"><description><title-info><book-title>{title}</book-title><lang>cs</lang></title-info></description><body>{body}</body></FictionBook>"#
);
liber_format::open(x.as_bytes(), Some("b.fb2"), &Limits::default()).expect("parses")
}
const C1: &[&str] =
&["Kapitán van Toch byl tlustý a dobrý člověk.", "Na ostrově Tana Masa žili mloci, kteří uměli házet kamením."];
const C2: &[&str] = &["Mloci se naučili mluvit a číst noviny.", "Pan Bondy založil Salamander Syndicate."];
const C3: &[&str] = &["Válka s mloky začala tiše.", "Nakonec zbyl jen spisovatel a jeho svědomí."];
/// The same book as the sender has.
fn edition_a() -> Document {
fb2("Válka s mloky", &[("I", C1), ("II", C2), ("III", C3)])
}
/// Another edition: a foreword before the story, and a sentence changed in chapter II.
fn edition_b() -> Document {
const FOREWORD: &[&str] = &["Předmluva vydavatele k tomuto vydání."];
const C2B: &[&str] = &["Mloci se naučili mluvit a číst noviny.", "Pan G. H. Bondy založil syndikát."];
fb2("Válka s mloky", &[("Předmluva", FOREWORD), ("I", C1), ("II", C2B), ("III", C3)])
}
fn chapter_of(d: &Document, needle: &str) -> usize {
d.chapters.iter().position(|c| c.root.text().contains(needle)).expect(needle)
}
fn note_on(d: &Document, quote: &str, book: BookRef) -> SharedNote {
let ch = chapter_of(d, quote);
let text = d.chapters[ch].root.text();
let at = text.find(quote).unwrap();
let s = text[..at].encode_utf16().count();
let e = s + quote.encode_utf16().count();
let anchor = liber_format::position::anchor(d, ch, s, e).expect("anchor");
SharedNote {
id: "n-1".into(),
book,
anchor,
spot: Spot { chapter: ch as u32, progress: ch as f64 / d.chapters.len() as f64 },
kind: Mark::Note,
colour: Colour::Green,
note: "Tohle si pamatuj.".into(),
created: 1,
}
}
fn info(isbn: Option<&str>, fp: Option<&str>) -> BookInfo {
BookInfo {
title: "Válka s mloky".into(),
isbn13: isbn.map(str::to_owned),
fingerprint: fp.map(str::to_owned),
..BookInfo::default()
}
}
fn reff(isbn: Option<&str>, fp: Option<&str>) -> BookRef {
BookRef { isbn13: isbn.map(str::to_owned), fingerprint: fp.map(str::to_owned), title: "Válka s mloky".into() }
}
// ---------- 2. matching ----------
#[test]
fn a_note_lands_exactly_in_the_same_edition() {
let a = edition_a();
let n = note_on(&a, "uměli házet kamením", reff(Some("9788020712479"), None));
let want = chapter_of(&a, "uměli házet");
match place(&a, &info(Some("9788020712479"), None), &n) {
Placement::Exact { chapter, start, end } => {
assert_eq!(chapter, want);
let t: Vec<u16> = a.chapters[chapter].root.text().encode_utf16().collect();
assert_eq!(String::from_utf16_lossy(&t[start..end]), "uměli házet kamením");
}
p => panic!("{p:?}"),
}
// The fingerprint identifies the book too.
assert!(matches!(
place(&a, &info(None, Some("fp")), &note_on(&a, "tlustý", reff(None, Some("fp")))),
Placement::Exact { .. }
));
}
#[test]
fn in_another_edition_the_note_is_approximate_and_at_the_right_words() {
let (a, b) = (edition_a(), edition_b());
let n = note_on(&a, "uměli házet kamením", reff(Some("9788020712479"), None));
match place(&b, &info(Some("9788000000000"), Some("other")), &n) {
Placement::Approximate { chapter, start, end } => {
assert_eq!(chapter, chapter_of(&b, "uměli házet"), "chapter I is the second chapter there");
let t: Vec<u16> = b.chapters[chapter].root.text().encode_utf16().collect();
assert_eq!(String::from_utf16_lossy(&t[start..end]), "uměli házet kamením");
}
p => panic!("{p:?}"),
}
// Even where the positions happen to point at the same words, another edition is never "exact".
let n = note_on(&a, "Kapitán van Toch", reff(None, Some("fp-a")));
assert!(matches!(place(&a, &info(None, Some("fp-b")), &n), Placement::Approximate { .. }));
}
#[test]
fn a_note_on_text_that_is_not_there_goes_to_the_side_list() {
let (a, b) = (edition_a(), edition_b());
// "Salamander Syndicate" was rewritten in edition B.
let n = note_on(&a, "založil Salamander Syndicate", reff(None, Some("fp-a")));
assert_eq!(place(&b, &info(None, Some("fp-b")), &n), Placement::Lost);
// Two equally good places in the reader's copy (the same sentence twice, neither with the note's context): never
// a guess.
let twice = fb2("x", &[("I", &["A. Mloci mluví dál. B. Mloci mluví dál. C."])]);
let mut n = note_on(&twice, "Mloci mluví dál.", reff(None, Some("fp-t")));
n.anchor.start = "epubcfi(/6/99!/4/2/1:0)".into();
n.anchor.quote.prefix = "X. ".into();
n.anchor.quote.suffix = " Y.".into();
assert_eq!(place(&twice, &info(None, Some("fp-other")), &n), Placement::Lost);
}
// ---------- 3. spoiler guard ----------
fn ev(id: &str, c: &mut Clock, t: u64, op: Op) -> Event {
Event { id: id.into(), hlc: c.tick(t), device: "phone".into(), op }
}
fn position(chapter: u32, progress: f64) -> Op {
Op::Position {
book: "b1".into(),
cfi: format!("epubcfi(/6/{}!/4/2/1:0)", 2 * chapter + 2),
chapter,
progress,
label: None,
}
}
#[test]
fn notes_beyond_the_furthest_chapter_stay_folded_across_chapters_and_after_reopening() {
let mut c = Clock::default();
let mut evs =
vec![ev("e0", &mut c, 1, Op::BookAdd { book: "b1".into(), info: info(None, Some("fp")), restore: false })];
evs.push(ev("e1", &mut c, 2, position(1, 0.30)));
let lib = Library::from_events(&evs);
let reach = Reach::of(&lib.books["b1"]);
let at = |ch: u32, p: f64| Spot { chapter: ch, progress: p };
// Placed notes: by the chapter they landed in, in the reader's copy.
assert!(!folded(&at(0, 0.1), Some(0), true, &reach));
assert!(!folded(&at(1, 0.4), Some(1), true, &reach), "the chapter being read is open");
assert!(folded(&at(2, 0.6), Some(2), true, &reach));
// A note placed in a later chapter of the reader's edition stays folded even if the sender's chapter was earlier.
assert!(folded(&at(1, 0.2), Some(3), false, &reach));
// Not placed (side list) or a thread message: the same book → by chapter; another edition → by progress.
assert!(folded(&at(2, 0.1), None, true, &reach));
assert!(!folded(&at(5, 0.25), None, false, &reach));
assert!(folded(&at(0, 0.31), None, false, &reach));
// Reading on into chapter II opens its notes; going back does not fold them again (the furthest place counts).
evs.push(ev("e2", &mut c, 3, position(2, 0.55)));
evs.push(ev("e3", &mut c, 4, position(0, 0.05)));
// Re-opening: the library is rebuilt from its events, in another arrival order.
evs.reverse();
let lib = Library::from_events(&evs);
let reach = Reach::of(&lib.books["b1"]);
assert!(!folded(&at(2, 0.6), Some(2), true, &reach));
assert!(folded(&at(3, 0.8), Some(3), true, &reach));
// A finished book has no spoilers left.
evs.push(ev(
"e4",
&mut c,
5,
Op::ReadStart { read: "r1".into(), book: "b1".into(), date: Some("2026-11-01".into()) },
));
evs.push(ev(
"e5",
&mut c,
6,
Op::ReadEnd {
read: "r1".into(),
date: Some("2026-11-20".into()),
outcome: liber_library::library::Outcome::Read,
},
));
let lib = Library::from_events(&evs);
assert!(!folded(&at(3, 0.99), Some(3), true, &Reach::of(&lib.books["b1"])));
}
// ---------- 4. approval (the core's half) ----------
fn rec(id: &str) -> Op {
Op::RecordingAdd {
id: id.into(),
book: "b1".into(),
chapter: 2,
by: "Babička".into(),
source: RecordingSource::Slot {
slot: "AAAAAAAAAAAAAAAAAAAAAA".into(),
key: "k".repeat(43),
sha256: "a".repeat(64),
},
mime: "audio/webm;codecs=opus".into(),
duration_ms: 600_000,
created: 10,
}
}
#[test]
fn an_unapproved_recording_is_never_playable_and_a_removed_one_stays_gone() {
let mut c = Clock::default();
let mut evs = vec![
ev("e0", &mut c, 1, Op::BookAdd { book: "b1".into(), info: info(None, Some("fp")), restore: false }),
ev("e1", &mut c, 2, rec("r1")),
];
let lib = Library::from_events(&evs);
assert_eq!(lib.recordings.len(), 1, "the parent sees it, waiting");
assert!(!lib.recordings["r1"].approved);
assert!(lib.playable("b1", 2).is_empty());
assert!(lib.pending().iter().any(|r| r.id == "r1"));
evs.push(ev("e2", &mut c, 3, Op::RecordingApprove { id: "r1".into() }));
let lib = Library::from_events(&evs);
assert_eq!(lib.playable("b1", 2).iter().map(|r| r.id.as_str()).collect::<Vec<_>>(), ["r1"]);
assert!(lib.playable("b1", 1).is_empty(), "only for its chapter");
assert!(lib.pending().is_empty());
// Deleted on one device: gone on every device that folds the log, and an old add arriving late does not bring it
// back, nor does a late approval.
evs.push(ev("e3", &mut c, 4, Op::RecordingRemove { id: "r1".into() }));
let mut late = Clock::default();
evs.push(ev("e4", &mut late, 2, rec("r1")));
evs.push(ev("e5", &mut c, 5, Op::RecordingApprove { id: "r1".into() }));
let lib = Library::from_events(&evs);
assert!(lib.recordings.is_empty());
assert!(lib.playable("b1", 2).is_empty());
assert!(lib.removed_recordings().contains("r1"));
}
#[test]
fn hostile_recording_and_ask_values_are_dropped() {
let mut c = Clock::default();
let mut bad = rec("r1");
if let Op::RecordingAdd { mime, .. } = &mut bad {
*mime = "text/html".into();
}
let mut no_book = rec("r2");
if let Op::RecordingAdd { book, .. } = &mut no_book {
*book = "missing".into();
}
let evs = vec![
ev("e0", &mut c, 1, Op::BookAdd { book: "b1".into(), info: info(None, Some("fp")), restore: false }),
ev("e1", &mut c, 2, bad),
ev("e2", &mut c, 3, no_book),
ev(
"e3",
&mut c,
4,
Op::RecordAsk {
slot: "short".into(),
book: "b1".into(),
chapter: 1,
person: "Babička".into(),
key: "k".repeat(43),
created: 1,
},
),
];
let lib = Library::from_events(&evs);
assert!(lib.recordings.is_empty());
assert!(lib.asks.is_empty());
}
// ---------- people, sharing, hiding ----------
#[test]
fn people_shares_and_hiding_fold_like_everything_else() {
let mut c = Clock::default();
let mut evs = vec![
ev("e0", &mut c, 1, Op::BookAdd { book: "b1".into(), info: info(None, Some("fp")), restore: false }),
ev("e1", &mut c, 2, Op::PersonAdd { person: "g1".into(), name: "Jana".into() }),
ev("e2", &mut c, 3, Op::Share { highlight: "h1".into(), person: "g1".into() }),
ev("e3", &mut c, 4, Op::Hide { person: "g1".into(), book: Some("b1".into()), hidden: true }),
ev("e4", &mut c, 5, Op::BuddyRead { id: "br1".into(), book: "b1".into(), people: vec!["g1".into()] }),
];
let lib = Library::from_events(&evs);
assert_eq!(lib.people["g1"].name, "Jana");
assert!(lib.shares["h1"].contains("g1"));
assert!(lib.hidden("g1", "b1"));
assert!(!lib.hidden("g1", "b2"));
assert_eq!(lib.buddy_reads["br1"].people, ["g1"]);
evs.push(ev("e5", &mut c, 6, Op::Hide { person: "g1".into(), book: None, hidden: true }));
evs.push(ev("e6", &mut c, 7, Op::Unshare { highlight: "h1".into(), person: "g1".into() }));
let lib = Library::from_events(&evs);
assert!(lib.hidden("g1", "b2"), "hidden everywhere");
assert!(lib.shares.get("h1").is_none_or(|s| s.is_empty()));
// An export restores all of it (with a recording, approved).
evs.push(ev("e8", &mut c, 9, rec("r1")));
evs.push(ev("e9", &mut c, 10, Op::RecordingApprove { id: "r1".into() }));
let lib = Library::from_events(&evs);
let mut rc = Clock::default();
let restored: Vec<Event> = liber_library::export::ops_from(&lib)
.into_iter()
.enumerate()
.map(|(i, op)| ev(&format!("x{i}"), &mut rc, i as u64 + 1, op))
.collect();
assert_eq!(Library::from_events(&restored), lib);
evs.push(ev("e7", &mut c, 8, Op::PersonRemove { person: "g1".into() }));
let lib = Library::from_events(&evs);
assert!(lib.people.is_empty());
}
// ---------- what another person's Liber sends ----------
#[test]
fn wire_bodies_are_parsed_strictly() {
let a = edition_a();
let n = note_on(&a, "tlustý a dobrý", reff(None, Some("fp")));
let body = serde_json::to_vec(&n).unwrap();
assert_eq!(Wire::parse("liber.note", &body), Some(Wire::Note(Box::new(n.clone()))));
assert_eq!(Wire::parse("liber.hello", br#"{"name":"Jana"}"#), Some(Wire::Hello { name: "Jana".into() }));
// Unknown kinds and fields, oversized values, bad numbers: refused.
assert_eq!(Wire::parse("liber.unknown", b"{}"), None);
assert_eq!(Wire::parse("liber.hello", br#"{"name":"Jana","admin":true}"#), None);
assert_eq!(Wire::parse("liber.hello", br#"{"name":""}"#), None);
let long = format!(r#"{{"name":"{}"}}"#, "x".repeat(81));
assert_eq!(Wire::parse("liber.hello", long.as_bytes()), None);
let mut big = n.clone();
big.note = "x".repeat(together::MAX_NOTE + 1);
assert_eq!(Wire::parse("liber.note", &serde_json::to_vec(&big).unwrap()), None);
let mut nan = n.clone();
nan.spot.progress = 2.0;
assert_eq!(Wire::parse("liber.note", &serde_json::to_vec(&nan).unwrap()), None);
let mut quote = n;
quote.anchor.quote.exact = String::new();
assert_eq!(Wire::parse("liber.note", &serde_json::to_vec(&quote).unwrap()), None);
let t = br#"{"read":"br1","id":"m1","spot":{"chapter":2,"progress":0.5},"text":"Ten konec!"}"#;
assert!(matches!(Wire::parse("liber.thread", t), Some(Wire::Thread { .. })));
assert_eq!(Wire::parse("liber.thread", &[0xff, 0xfe]), None);
assert_eq!(Wire::parse("liber.thread", &vec![b' '; together::MAX_BODY + 1]), None);
}