Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 22c898e38f | |||
| 7be8fca42b |
@@ -10,7 +10,9 @@ on this one **by git tag**, never by a path. The roadmap and the day pages are i
|
|||||||
crates/liber-format EPUB 2/3, FB2 (+ .fb2.zip), TXT, DRM-free MOBI/AZW3 -> one Document; the zip reader and
|
crates/liber-format EPUB 2/3, FB2 (+ .fb2.zip), TXT, DRM-free MOBI/AZW3 -> one Document; the zip reader and
|
||||||
writer; the sanitizer (whitelist, no scripts, no remote URLs); positions (CFI + text quote)
|
writer; the sanitizer (whitelist, no scripts, no remote URLs); positions (CFI + text quote)
|
||||||
crates/liber-library book identity (ISBN, text fingerprint), the library model, the event log and its merge
|
crates/liber-library book identity (ISBN, text fingerprint), the library model, the event log and its merge
|
||||||
(sync semantics), stats, Goodreads/StoryGraph CSV import, the liber-export format
|
(sync semantics), stats, Goodreads/StoryGraph CSV import, the liber-export format;
|
||||||
|
Day 5 `together`: what another person's Liber sends (strictly parsed), where a shared note
|
||||||
|
lands in one's own copy (exact / approximate / lost), the spoiler guard, recording approval
|
||||||
crates/liber-habit Day 2: the local day (the only day computation in Liber), days read, the forgiving streak,
|
crates/liber-habit Day 2: the local day (the only day computation in Liber), days read, the forgiving streak,
|
||||||
the reminder schedule, the medal rules (a pure function of the log)
|
the reminder schedule, the medal rules (a pure function of the log)
|
||||||
crates/liber-lang Day 3: words by UAX #29 with UTF-16 offsets, the Lemmatizer trait (a licensed table first,
|
crates/liber-lang Day 3: words by UAX #29 with UTF-16 offsets, the Lemmatizer trait (a licensed table first,
|
||||||
|
|||||||
Generated
+5
-5
@@ -327,7 +327,7 @@ checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "liber-audio"
|
name = "liber-audio"
|
||||||
version = "0.5.0"
|
version = "0.6.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
@@ -337,7 +337,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "liber-format"
|
name = "liber-format"
|
||||||
version = "0.5.0"
|
version = "0.6.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64",
|
"base64",
|
||||||
"chardetng",
|
"chardetng",
|
||||||
@@ -357,7 +357,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "liber-habit"
|
name = "liber-habit"
|
||||||
version = "0.5.0"
|
version = "0.6.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"liber-library",
|
"liber-library",
|
||||||
"proptest",
|
"proptest",
|
||||||
@@ -367,7 +367,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "liber-lang"
|
name = "liber-lang"
|
||||||
version = "0.5.0"
|
version = "0.6.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proptest",
|
"proptest",
|
||||||
"serde",
|
"serde",
|
||||||
@@ -379,7 +379,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "liber-library"
|
name = "liber-library"
|
||||||
version = "0.5.0"
|
version = "0.6.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"csv",
|
"csv",
|
||||||
"encoding_rs",
|
"encoding_rs",
|
||||||
|
|||||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
|||||||
members = ["crates/liber-format", "crates/liber-library", "crates/liber-habit", "crates/liber-lang", "crates/liber-audio"]
|
members = ["crates/liber-format", "crates/liber-library", "crates/liber-habit", "crates/liber-lang", "crates/liber-audio"]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.5.0"
|
version = "0.6.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
license = "MPL-2.0"
|
license = "MPL-2.0"
|
||||||
repository = "https://gitea.marek-novak.cz/mnovak/Liber-public"
|
repository = "https://gitea.marek-novak.cz/mnovak/Liber-public"
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
//! Events: what a device did, with a hybrid logical clock. The order of events is total and the same everywhere.
|
//! Events: what a device did, with a hybrid logical clock. The order of events is total and the same everywhere.
|
||||||
|
|
||||||
use crate::library::{BookFile, BookInfo, Colour, Field, GoalKind, HabitGoal, Mark, Outcome, Person, WordMark};
|
use crate::library::{BookFile, BookInfo, Colour, Field, GoalKind, HabitGoal, Mark, Outcome, Person, WordMark};
|
||||||
|
use crate::together::RecordingSource;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::cmp::Ordering;
|
use std::cmp::Ordering;
|
||||||
|
|
||||||
@@ -192,4 +193,66 @@ pub enum Op {
|
|||||||
sha256: String,
|
sha256: String,
|
||||||
language: Option<String>,
|
language: Option<String>,
|
||||||
},
|
},
|
||||||
|
/// Day 5: someone the reader reads with: `person` is their Tabellarius group (hex), `name` how Liber shows them.
|
||||||
|
/// Adding again renames.
|
||||||
|
PersonAdd {
|
||||||
|
person: String,
|
||||||
|
name: String,
|
||||||
|
},
|
||||||
|
PersonRemove {
|
||||||
|
person: String,
|
||||||
|
},
|
||||||
|
/// Day 5: hide (or show again) a person's notes, in one book or everywhere (`book: None`).
|
||||||
|
Hide {
|
||||||
|
person: String,
|
||||||
|
book: Option<String>,
|
||||||
|
hidden: bool,
|
||||||
|
},
|
||||||
|
/// Day 5: a highlight was shared with a person (the note itself travels in their group).
|
||||||
|
Share {
|
||||||
|
highlight: String,
|
||||||
|
person: String,
|
||||||
|
},
|
||||||
|
Unshare {
|
||||||
|
highlight: String,
|
||||||
|
person: String,
|
||||||
|
},
|
||||||
|
/// Day 5: a buddy read of a book with people.
|
||||||
|
BuddyRead {
|
||||||
|
id: String,
|
||||||
|
book: String,
|
||||||
|
people: Vec<String>,
|
||||||
|
},
|
||||||
|
/// Day 5: a link was made asking someone (`person`: the name the parent typed) to record a chapter. `key` opens
|
||||||
|
/// what is in the slot; it lives only here (the reader's own, end-to-end encrypted log) and in the link.
|
||||||
|
RecordAsk {
|
||||||
|
slot: String,
|
||||||
|
book: String,
|
||||||
|
chapter: u32,
|
||||||
|
person: String,
|
||||||
|
key: String,
|
||||||
|
created: u64,
|
||||||
|
},
|
||||||
|
/// Day 5: the link was cancelled (or the recording arrived and the parent closed it).
|
||||||
|
RecordAskClose {
|
||||||
|
slot: String,
|
||||||
|
},
|
||||||
|
/// Day 5: a recorded chapter, waiting for the parent's approval.
|
||||||
|
RecordingAdd {
|
||||||
|
id: String,
|
||||||
|
book: String,
|
||||||
|
chapter: u32,
|
||||||
|
by: String,
|
||||||
|
source: RecordingSource,
|
||||||
|
mime: String,
|
||||||
|
duration_ms: u64,
|
||||||
|
created: u64,
|
||||||
|
},
|
||||||
|
RecordingApprove {
|
||||||
|
id: String,
|
||||||
|
},
|
||||||
|
/// Day 5: deleted by the parent, or found deleted by the person who recorded it. Final.
|
||||||
|
RecordingRemove {
|
||||||
|
id: String,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -206,6 +206,46 @@ pub fn ops_from(lib: &Library) -> Vec<Op> {
|
|||||||
for (lang, band) in &lib.bands {
|
for (lang, band) in &lib.bands {
|
||||||
ops.push(Op::KnownBand { lang: lang.clone(), list: band.list.clone(), upto: band.upto });
|
ops.push(Op::KnownBand { lang: lang.clone(), list: band.list.clone(), upto: band.upto });
|
||||||
}
|
}
|
||||||
|
// Day 5: people, what was shared and hidden, buddy reads, links and recordings (deleted ones are simply absent).
|
||||||
|
for (person, p) in &lib.people {
|
||||||
|
ops.push(Op::PersonAdd { person: person.clone(), name: p.name.clone() });
|
||||||
|
}
|
||||||
|
for (person, book) in &lib.hides {
|
||||||
|
ops.push(Op::Hide { person: person.clone(), book: book.clone(), hidden: true });
|
||||||
|
}
|
||||||
|
for (highlight, people) in &lib.shares {
|
||||||
|
for person in people {
|
||||||
|
ops.push(Op::Share { highlight: highlight.clone(), person: person.clone() });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for r in lib.buddy_reads.values() {
|
||||||
|
ops.push(Op::BuddyRead { id: r.id.clone(), book: r.book.clone(), people: r.people.clone() });
|
||||||
|
}
|
||||||
|
for a in lib.asks.values() {
|
||||||
|
ops.push(Op::RecordAsk {
|
||||||
|
slot: a.slot.clone(),
|
||||||
|
book: a.book.clone(),
|
||||||
|
chapter: a.chapter,
|
||||||
|
person: a.person.clone(),
|
||||||
|
key: a.key.clone(),
|
||||||
|
created: a.created,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
for r in lib.recordings.values() {
|
||||||
|
ops.push(Op::RecordingAdd {
|
||||||
|
id: r.id.clone(),
|
||||||
|
book: r.book.clone(),
|
||||||
|
chapter: r.chapter,
|
||||||
|
by: r.by.clone(),
|
||||||
|
source: r.source.clone(),
|
||||||
|
mime: r.mime.clone(),
|
||||||
|
duration_ms: r.duration_ms,
|
||||||
|
created: r.created,
|
||||||
|
});
|
||||||
|
if r.approved {
|
||||||
|
ops.push(Op::RecordingApprove { id: r.id.clone() });
|
||||||
|
}
|
||||||
|
}
|
||||||
ops
|
ops
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ pub mod export;
|
|||||||
pub mod import;
|
pub mod import;
|
||||||
pub mod library;
|
pub mod library;
|
||||||
pub mod stats;
|
pub mod stats;
|
||||||
|
pub mod together;
|
||||||
|
|
||||||
pub use event::{Clock, Event, Hlc, Op};
|
pub use event::{Clock, Event, Hlc, Op};
|
||||||
pub use library::{Book, Highlight, Library, Loan, Possession, Read, ReadStatus, Text};
|
pub use library::{Book, Highlight, Library, Loan, Possession, Read, ReadStatus, Text};
|
||||||
|
|||||||
@@ -357,6 +357,42 @@ pub struct Goal {
|
|||||||
pub target: u32,
|
pub target: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Day 5: someone the reader reads with.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct PersonEntry {
|
||||||
|
pub name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct BuddyRead {
|
||||||
|
pub id: String,
|
||||||
|
pub book: String,
|
||||||
|
pub people: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct RecordAsk {
|
||||||
|
pub slot: String,
|
||||||
|
pub book: String,
|
||||||
|
pub chapter: u32,
|
||||||
|
pub person: String,
|
||||||
|
pub key: String,
|
||||||
|
pub created: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Recording {
|
||||||
|
pub id: String,
|
||||||
|
pub book: String,
|
||||||
|
pub chapter: u32,
|
||||||
|
pub by: String,
|
||||||
|
pub source: crate::together::RecordingSource,
|
||||||
|
pub mime: String,
|
||||||
|
pub duration_ms: u64,
|
||||||
|
pub created: u64,
|
||||||
|
pub approved: bool,
|
||||||
|
}
|
||||||
|
|
||||||
/// The whole library. Equal events in any arrival order give an equal library. Equality compares the content
|
/// The whole library. Equal events in any arrival order give an equal library. Equality compares the content
|
||||||
/// (books, highlights, sessions, goals), not the bookkeeping of how it was built.
|
/// (books, highlights, sessions, goals), not the bookkeeping of how it was built.
|
||||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||||
@@ -377,6 +413,27 @@ pub struct Library {
|
|||||||
/// Day 3: language → the frequency band marked as known.
|
/// Day 3: language → the frequency band marked as known.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub bands: BTreeMap<String, Band>,
|
pub bands: BTreeMap<String, Band>,
|
||||||
|
/// Day 5: the people the reader reads with, by group.
|
||||||
|
#[serde(default)]
|
||||||
|
pub people: BTreeMap<String, PersonEntry>,
|
||||||
|
/// Day 5: (person, book) pairs whose notes are hidden; `None` for every book.
|
||||||
|
#[serde(default)]
|
||||||
|
pub hides: BTreeSet<(String, Option<String>)>,
|
||||||
|
/// Day 5: highlight -> the people it was shared with.
|
||||||
|
#[serde(default)]
|
||||||
|
pub shares: BTreeMap<String, BTreeSet<String>>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub buddy_reads: BTreeMap<String, BuddyRead>,
|
||||||
|
/// Day 5: open "Ask someone to record" links, by slot.
|
||||||
|
#[serde(default)]
|
||||||
|
pub asks: BTreeMap<String, RecordAsk>,
|
||||||
|
/// Day 5: recorded chapters, approved or waiting.
|
||||||
|
#[serde(default)]
|
||||||
|
pub recordings: BTreeMap<String, Recording>,
|
||||||
|
#[serde(skip)]
|
||||||
|
removed_recordings: BTreeSet<String>,
|
||||||
|
#[serde(skip)]
|
||||||
|
approved_early: BTreeSet<String>,
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
aliases: BTreeMap<String, String>,
|
aliases: BTreeMap<String, String>,
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
@@ -401,6 +458,12 @@ impl PartialEq for Library {
|
|||||||
&& self.medals_seen == o.medals_seen
|
&& self.medals_seen == o.medals_seen
|
||||||
&& self.words == o.words
|
&& self.words == o.words
|
||||||
&& self.bands == o.bands
|
&& self.bands == o.bands
|
||||||
|
&& self.people == o.people
|
||||||
|
&& self.hides == o.hides
|
||||||
|
&& self.shares == o.shares
|
||||||
|
&& self.buddy_reads == o.buddy_reads
|
||||||
|
&& self.asks == o.asks
|
||||||
|
&& self.recordings == o.recordings
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -452,6 +515,28 @@ impl Library {
|
|||||||
self.versions.get(&(format!("hl:{id}"), "note")).map(String::as_str)
|
self.versions.get(&(format!("hl:{id}"), "note")).map(String::as_str)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Day 5: whether a person's notes are hidden in this book (or everywhere).
|
||||||
|
pub fn hidden(&self, person: &str, book: &str) -> bool {
|
||||||
|
let book = self.canonical(book);
|
||||||
|
self.hides.contains(&(person.to_owned(), None)) || self.hides.contains(&(person.to_owned(), Some(book)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Day 5: the approved recordings of a chapter: the only ones that may be played.
|
||||||
|
pub fn playable(&self, book: &str, chapter: u32) -> Vec<&Recording> {
|
||||||
|
let book = self.canonical(book);
|
||||||
|
self.recordings.values().filter(|r| r.approved && r.book == book && r.chapter == chapter).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Day 5: recordings waiting for the parent's approval.
|
||||||
|
pub fn pending(&self) -> Vec<&Recording> {
|
||||||
|
self.recordings.values().filter(|r| !r.approved).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Day 5: recordings deleted (their audio must go from every device).
|
||||||
|
pub fn removed_recordings(&self) -> &BTreeSet<String> {
|
||||||
|
&self.removed_recordings
|
||||||
|
}
|
||||||
|
|
||||||
/// An existing book with the same identity: ISBN-13, else text fingerprint.
|
/// An existing book with the same identity: ISBN-13, else text fingerprint.
|
||||||
pub fn find_identity(&self, isbn13: Option<&str>, fingerprint: Option<&str>) -> Option<&Book> {
|
pub fn find_identity(&self, isbn13: Option<&str>, fingerprint: Option<&str>) -> Option<&Book> {
|
||||||
if let Some(i) = isbn13
|
if let Some(i) = isbn13
|
||||||
@@ -786,6 +871,104 @@ impl Library {
|
|||||||
b.audio_position = Some((sha256.to_ascii_lowercase(), *ms));
|
b.audio_position = Some((sha256.to_ascii_lowercase(), *ms));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Op::PersonAdd { person, name } => {
|
||||||
|
if crate::together::id_ok(person) && crate::together::name_ok(name) {
|
||||||
|
self.people.insert(person.clone(), PersonEntry { name: name.trim().to_owned() });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Op::PersonRemove { person } => {
|
||||||
|
self.people.remove(person);
|
||||||
|
}
|
||||||
|
Op::Hide { person, book, hidden } => {
|
||||||
|
let key = (person.clone(), book.as_deref().map(|b| self.canonical(b)));
|
||||||
|
if *hidden {
|
||||||
|
self.hides.insert(key);
|
||||||
|
} else {
|
||||||
|
self.hides.remove(&key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Op::Share { highlight, person } => {
|
||||||
|
self.shares.entry(highlight.clone()).or_default().insert(person.clone());
|
||||||
|
}
|
||||||
|
Op::Unshare { highlight, person } => {
|
||||||
|
if let Some(s) = self.shares.get_mut(highlight) {
|
||||||
|
s.remove(person);
|
||||||
|
if s.is_empty() {
|
||||||
|
self.shares.remove(highlight);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Op::BuddyRead { id, book, people } => {
|
||||||
|
let book = self.canonical(book);
|
||||||
|
if crate::together::id_ok(id) && self.books.contains_key(&book) && people.len() <= 16 {
|
||||||
|
self.buddy_reads.insert(id.clone(), BuddyRead { id: id.clone(), book, people: people.clone() });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Op::RecordAsk { slot, book, chapter, person, key, created } => {
|
||||||
|
let book = self.canonical(book);
|
||||||
|
if crate::together::slot_ok(slot)
|
||||||
|
&& crate::together::key_ok(key)
|
||||||
|
&& crate::together::name_ok(person)
|
||||||
|
&& self.books.contains_key(&book)
|
||||||
|
{
|
||||||
|
let a = RecordAsk {
|
||||||
|
slot: slot.clone(),
|
||||||
|
book,
|
||||||
|
chapter: *chapter,
|
||||||
|
person: person.trim().to_owned(),
|
||||||
|
key: key.clone(),
|
||||||
|
created: *created,
|
||||||
|
};
|
||||||
|
self.asks.insert(slot.clone(), a);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Op::RecordAskClose { slot } => {
|
||||||
|
self.asks.remove(slot);
|
||||||
|
}
|
||||||
|
Op::RecordingAdd { id, book, chapter, by, source, mime, duration_ms, created } => {
|
||||||
|
let book = self.canonical(book);
|
||||||
|
if self.removed_recordings.contains(id)
|
||||||
|
|| self.recordings.contains_key(id)
|
||||||
|
|| !crate::together::id_ok(id)
|
||||||
|
|| !crate::together::name_ok(by)
|
||||||
|
|| !crate::together::mime_ok(mime)
|
||||||
|
|| !source.ok()
|
||||||
|
|| !self.books.contains_key(&book)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let approved = self.approved_early.remove(id);
|
||||||
|
self.recordings.insert(
|
||||||
|
id.clone(),
|
||||||
|
Recording {
|
||||||
|
id: id.clone(),
|
||||||
|
book,
|
||||||
|
chapter: *chapter,
|
||||||
|
by: by.trim().to_owned(),
|
||||||
|
source: source.clone(),
|
||||||
|
mime: mime.clone(),
|
||||||
|
duration_ms: *duration_ms,
|
||||||
|
created: *created,
|
||||||
|
approved,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Op::RecordingApprove { id } => {
|
||||||
|
if self.removed_recordings.contains(id) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
match self.recordings.get_mut(id) {
|
||||||
|
Some(r) => r.approved = true,
|
||||||
|
None => {
|
||||||
|
self.approved_early.insert(id.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Op::RecordingRemove { id } => {
|
||||||
|
self.recordings.remove(id);
|
||||||
|
self.approved_early.remove(id);
|
||||||
|
self.removed_recordings.insert(id.clone());
|
||||||
|
}
|
||||||
Op::Edition { book, sha256, language } => {
|
Op::Edition { book, sha256, language } => {
|
||||||
let ok = sha256.len() == 64 && sha256.bytes().all(|b| b.is_ascii_hexdigit());
|
let ok = sha256.len() == 64 && sha256.bytes().all(|b| b.is_ascii_hexdigit());
|
||||||
if let Some(b) = self.book_mut(book)
|
if let Some(b) = self.book_mut(book)
|
||||||
|
|||||||
@@ -0,0 +1,342 @@
|
|||||||
|
//! Day 5 (the app's `docs/05_together.md`): reading together. What one person's Liber sends another (strictly
|
||||||
|
//! parsed: the other side is as hostile as any outside file), where a shared note lands in the reader's copy, and the
|
||||||
|
//! spoiler guard. Recordings and the reader's own decisions are ops in the library (`Op::RecordingAdd` …).
|
||||||
|
|
||||||
|
use crate::library::{Book, BookInfo, Colour, Mark, ReadStatus};
|
||||||
|
use liber_format::Document;
|
||||||
|
use liber_format::position::{Anchor, Resolved, resolve};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// The most a body from another person may be, in bytes (Tabellarius allows 300 KiB a message).
|
||||||
|
pub const MAX_BODY: usize = 64 * 1024;
|
||||||
|
/// A shared note's text, in characters.
|
||||||
|
pub const MAX_NOTE: usize = 10_000;
|
||||||
|
/// The quoted text a note is anchored to, in characters.
|
||||||
|
pub const MAX_QUOTE: usize = 2_000;
|
||||||
|
/// A thread message, in characters.
|
||||||
|
pub const MAX_MESSAGE: usize = 4_000;
|
||||||
|
/// A name a person chose, in characters.
|
||||||
|
pub const MAX_NAME: usize = 80;
|
||||||
|
pub const MAX_TITLE: usize = 300;
|
||||||
|
|
||||||
|
/// Which book a shared item is about: enough to find the reader's own copy, nothing about the sender's files.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct BookRef {
|
||||||
|
pub isbn13: Option<String>,
|
||||||
|
pub fingerprint: Option<String>,
|
||||||
|
pub title: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BookRef {
|
||||||
|
pub fn of(info: &BookInfo) -> BookRef {
|
||||||
|
BookRef { isbn13: info.isbn13.clone(), fingerprint: info.fingerprint.clone(), title: info.title.clone() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The same book (not just the same title): ISBN-13 or text fingerprint equal.
|
||||||
|
pub fn is(&self, info: &BookInfo) -> bool {
|
||||||
|
let eq =
|
||||||
|
|a: &Option<String>, b: &Option<String>| matches!((a, b), (Some(x), Some(y)) if !x.is_empty() && x == y);
|
||||||
|
eq(&self.isbn13, &info.isbn13) || eq(&self.fingerprint, &info.fingerprint)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ok(&self) -> bool {
|
||||||
|
self.isbn13.as_deref().is_none_or(|i| i.len() == 13 && i.bytes().all(|b| b.is_ascii_digit()))
|
||||||
|
&& self.fingerprint.as_deref().is_none_or(|f| !f.is_empty() && f.len() <= 128 && f.is_ascii())
|
||||||
|
&& chars_in(&self.title, 1, MAX_TITLE)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where in the sender's copy an item belongs: the chapter and the progress through the book (0–1).
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct Spot {
|
||||||
|
pub chapter: u32,
|
||||||
|
pub progress: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Spot {
|
||||||
|
fn ok(&self) -> bool {
|
||||||
|
self.chapter <= 100_000 && self.progress.is_finite() && (0.0..=1.0).contains(&self.progress)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A highlight or note shared with a person.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct SharedNote {
|
||||||
|
/// The sender's highlight id.
|
||||||
|
pub id: String,
|
||||||
|
pub book: BookRef,
|
||||||
|
pub anchor: Anchor,
|
||||||
|
pub spot: Spot,
|
||||||
|
pub kind: Mark,
|
||||||
|
pub colour: Colour,
|
||||||
|
pub note: String,
|
||||||
|
pub created: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SharedNote {
|
||||||
|
fn ok(&self) -> bool {
|
||||||
|
let a = &self.anchor;
|
||||||
|
id_ok(&self.id)
|
||||||
|
&& self.book.ok()
|
||||||
|
&& self.spot.ok()
|
||||||
|
&& a.chapter <= 100_000
|
||||||
|
&& a.start.len() <= 1024
|
||||||
|
&& a.end.len() <= 1024
|
||||||
|
&& a.chapter_hash.len() <= 128
|
||||||
|
&& chars_in(&a.quote.exact, 1, MAX_QUOTE)
|
||||||
|
&& a.quote.prefix.chars().count() <= 200
|
||||||
|
&& a.quote.suffix.chars().count() <= 200
|
||||||
|
&& self.note.chars().count() <= MAX_NOTE
|
||||||
|
&& self.kind != Mark::Bookmark
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Everything that travels in a person's group (Tabellarius app events). Each kind has its own body.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub enum Wire {
|
||||||
|
/// `liber.hello`: the name the person chose.
|
||||||
|
Hello { name: String },
|
||||||
|
/// `liber.note`
|
||||||
|
Note(Box<SharedNote>),
|
||||||
|
/// `liber.note.withdraw`: the sender took a note back.
|
||||||
|
Withdraw { id: String },
|
||||||
|
/// `liber.buddy`: an invitation to read a book together.
|
||||||
|
Buddy { read: String, book: BookRef },
|
||||||
|
/// `liber.progress`: how far the person is in a buddy read.
|
||||||
|
Progress { read: String, spot: Spot },
|
||||||
|
/// `liber.thread`: a message in a chapter's thread.
|
||||||
|
Thread { read: String, id: String, spot: Spot, text: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const HELLO: &str = "liber.hello";
|
||||||
|
pub const NOTE: &str = "liber.note";
|
||||||
|
pub const WITHDRAW: &str = "liber.note.withdraw";
|
||||||
|
pub const BUDDY: &str = "liber.buddy";
|
||||||
|
pub const PROGRESS: &str = "liber.progress";
|
||||||
|
pub const THREAD: &str = "liber.thread";
|
||||||
|
|
||||||
|
#[derive(Deserialize, Serialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct HelloB {
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize, Serialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct WithdrawB {
|
||||||
|
id: String,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize, Serialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct BuddyB {
|
||||||
|
read: String,
|
||||||
|
book: BookRef,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize, Serialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct ProgressB {
|
||||||
|
read: String,
|
||||||
|
spot: Spot,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize, Serialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
struct ThreadB {
|
||||||
|
read: String,
|
||||||
|
id: String,
|
||||||
|
spot: Spot,
|
||||||
|
text: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Wire {
|
||||||
|
/// `None` for anything not exactly a Day 5 body: an unknown kind or field, a value out of its bounds.
|
||||||
|
pub fn parse(kind: &str, body: &[u8]) -> Option<Wire> {
|
||||||
|
if body.len() > MAX_BODY {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let w = match kind {
|
||||||
|
HELLO => {
|
||||||
|
let b: HelloB = serde_json::from_slice(body).ok()?;
|
||||||
|
Wire::Hello { name: b.name.trim().to_owned() }
|
||||||
|
}
|
||||||
|
NOTE => Wire::Note(Box::new(serde_json::from_slice(body).ok()?)),
|
||||||
|
WITHDRAW => Wire::Withdraw { id: serde_json::from_slice::<WithdrawB>(body).ok()?.id },
|
||||||
|
BUDDY => {
|
||||||
|
let b: BuddyB = serde_json::from_slice(body).ok()?;
|
||||||
|
Wire::Buddy { read: b.read, book: b.book }
|
||||||
|
}
|
||||||
|
PROGRESS => {
|
||||||
|
let b: ProgressB = serde_json::from_slice(body).ok()?;
|
||||||
|
Wire::Progress { read: b.read, spot: b.spot }
|
||||||
|
}
|
||||||
|
THREAD => {
|
||||||
|
let b: ThreadB = serde_json::from_slice(body).ok()?;
|
||||||
|
Wire::Thread { read: b.read, id: b.id, spot: b.spot, text: b.text }
|
||||||
|
}
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
w.ok().then_some(w)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ok(&self) -> bool {
|
||||||
|
match self {
|
||||||
|
Wire::Hello { name } => name_ok(name),
|
||||||
|
Wire::Note(n) => n.ok(),
|
||||||
|
Wire::Withdraw { id } => id_ok(id),
|
||||||
|
Wire::Buddy { read, book } => id_ok(read) && book.ok(),
|
||||||
|
Wire::Progress { read, spot } => id_ok(read) && spot.ok(),
|
||||||
|
Wire::Thread { read, id, spot, text } => {
|
||||||
|
id_ok(read) && id_ok(id) && spot.ok() && chars_in(text.trim(), 1, MAX_MESSAGE)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `(kind, body)` to send.
|
||||||
|
pub fn encode(&self) -> (&'static str, Vec<u8>) {
|
||||||
|
let j = |v: serde_json::Result<Vec<u8>>| v.unwrap_or_default();
|
||||||
|
match self {
|
||||||
|
Wire::Hello { name } => (HELLO, j(serde_json::to_vec(&HelloB { name: name.clone() }))),
|
||||||
|
Wire::Note(n) => (NOTE, j(serde_json::to_vec(n.as_ref()))),
|
||||||
|
Wire::Withdraw { id } => (WITHDRAW, j(serde_json::to_vec(&WithdrawB { id: id.clone() }))),
|
||||||
|
Wire::Buddy { read, book } => {
|
||||||
|
(BUDDY, j(serde_json::to_vec(&BuddyB { read: read.clone(), book: book.clone() })))
|
||||||
|
}
|
||||||
|
Wire::Progress { read, spot } => {
|
||||||
|
(PROGRESS, j(serde_json::to_vec(&ProgressB { read: read.clone(), spot: *spot })))
|
||||||
|
}
|
||||||
|
Wire::Thread { read, id, spot, text } => (
|
||||||
|
THREAD,
|
||||||
|
j(serde_json::to_vec(&ThreadB { read: read.clone(), id: id.clone(), spot: *spot, text: text.clone() })),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn chars_in(s: &str, min: usize, max: usize) -> bool {
|
||||||
|
let n = s.chars().count();
|
||||||
|
n >= min && n <= max
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An id another device made: 1–64 letters, digits, `-` or `_`.
|
||||||
|
pub fn id_ok(s: &str) -> bool {
|
||||||
|
!s.is_empty() && s.len() <= 64 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A name someone chose: 1–80 characters, no control characters.
|
||||||
|
pub fn name_ok(s: &str) -> bool {
|
||||||
|
chars_in(s.trim(), 1, MAX_NAME) && !s.chars().any(char::is_control)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a shared note lands in the reader's copy. Offsets are UTF-16 into the chapter's text.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||||
|
#[serde(tag = "kind", rename_all = "lowercase")]
|
||||||
|
pub enum Placement {
|
||||||
|
Exact {
|
||||||
|
chapter: usize,
|
||||||
|
start: usize,
|
||||||
|
end: usize,
|
||||||
|
},
|
||||||
|
/// "Position approximate": found by its quoted text (another edition, or the text moved).
|
||||||
|
Approximate {
|
||||||
|
chapter: usize,
|
||||||
|
start: usize,
|
||||||
|
end: usize,
|
||||||
|
},
|
||||||
|
/// Not in this copy: shown in the side list with its quote, never at a guessed place.
|
||||||
|
Lost,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Placement {
|
||||||
|
pub fn chapter(&self) -> Option<usize> {
|
||||||
|
match self {
|
||||||
|
Placement::Exact { chapter, .. } | Placement::Approximate { chapter, .. } => Some(*chapter),
|
||||||
|
Placement::Lost => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The note's anchor in `doc`, the reader's copy of the book `mine`. Only the same book (ISBN-13 or fingerprint)
|
||||||
|
/// can be exact; any other edition is at best approximate.
|
||||||
|
pub fn place(doc: &Document, mine: &BookInfo, note: &SharedNote) -> Placement {
|
||||||
|
let same = note.book.is(mine);
|
||||||
|
match resolve(doc, ¬e.anchor) {
|
||||||
|
Resolved::Exact { chapter, start, end } if same => Placement::Exact { chapter, start, end },
|
||||||
|
Resolved::Exact { chapter, start, end } | Resolved::Approximate { chapter, start, end } => {
|
||||||
|
Placement::Approximate { chapter, start, end }
|
||||||
|
}
|
||||||
|
Resolved::Lost => Placement::Lost,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How far the reader has got in a book: the furthest position on any device, or the end once it is read.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
|
pub struct Reach {
|
||||||
|
pub chapter: u32,
|
||||||
|
pub progress: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Reach {
|
||||||
|
pub fn of(book: &Book) -> Reach {
|
||||||
|
if book.status() == ReadStatus::Read
|
||||||
|
|| book.reads.iter().any(|r| r.outcome == Some(crate::library::Outcome::Read))
|
||||||
|
{
|
||||||
|
return Reach { chapter: u32::MAX, progress: 1.0 };
|
||||||
|
}
|
||||||
|
match &book.position {
|
||||||
|
Some(p) => Reach { chapter: p.chapter, progress: p.progress },
|
||||||
|
None => Reach { chapter: 0, progress: 0.0 },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The spoiler guard: whether a note or message stays folded. `placed`: the chapter it landed in in the reader's copy
|
||||||
|
/// (`None` for the side list and for thread messages); `same`: the same book as the sender's. The chapter being read
|
||||||
|
/// is open; anything beyond the furthest chapter is folded.
|
||||||
|
pub fn folded(spot: &Spot, placed: Option<usize>, same: bool, reach: &Reach) -> bool {
|
||||||
|
if reach.chapter == u32::MAX {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
match placed {
|
||||||
|
Some(ch) => ch as u64 > reach.chapter as u64,
|
||||||
|
None if same => spot.chapter > reach.chapter,
|
||||||
|
None => spot.progress > reach.progress,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a recording's audio is.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
|
||||||
|
pub enum RecordingSource {
|
||||||
|
/// A slot on the home server: the sealed audio (`sha256` of the blob as it was found, so an approval holds for
|
||||||
|
/// exactly that take), opened with `key` (base64url, 32 bytes).
|
||||||
|
Slot { slot: String, key: String, sha256: String },
|
||||||
|
/// Only on the device that recorded it, sealed in its store.
|
||||||
|
Local { sha256: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RecordingSource {
|
||||||
|
pub(crate) fn ok(&self) -> bool {
|
||||||
|
let hex = |s: &str| s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit());
|
||||||
|
match self {
|
||||||
|
RecordingSource::Slot { slot, key, sha256 } => slot_ok(slot) && key_ok(key) && hex(sha256),
|
||||||
|
RecordingSource::Local { sha256 } => hex(sha256),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A slot id: 22 base64url characters (128 bits).
|
||||||
|
pub fn slot_ok(s: &str) -> bool {
|
||||||
|
s.len() == 22 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A link key: 43 base64url characters (32 bytes).
|
||||||
|
pub fn key_ok(s: &str) -> bool {
|
||||||
|
s.len() == 43 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The audio types a recording may have (the browser's recorder: Opus in WebM or Ogg; Safari: AAC in MP4).
|
||||||
|
pub fn mime_ok(m: &str) -> bool {
|
||||||
|
let base = m.split(';').next().unwrap_or("").trim();
|
||||||
|
matches!(base, "audio/webm" | "audio/ogg" | "audio/mp4") && m.len() <= 64 && m.is_ascii()
|
||||||
|
}
|
||||||
@@ -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")), ¬e_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("e).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);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user