[format][library] Books: EPUB/FB2/TXT/MOBI/AZW3 into one sanitized model, CFI anchors, the event-log library, stats, CSV import, export
This commit is contained in:
@@ -0,0 +1,160 @@
|
||||
//! 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, Mark, Outcome, Person};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::cmp::Ordering;
|
||||
|
||||
/// A hybrid logical clock value: wall milliseconds, then a counter.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub struct Hlc {
|
||||
pub wall: u64,
|
||||
pub logical: u32,
|
||||
}
|
||||
|
||||
/// One device's clock. `now_ms` is always a parameter.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Clock {
|
||||
last: Hlc,
|
||||
}
|
||||
|
||||
impl Clock {
|
||||
pub fn tick(&mut self, now_ms: u64) -> Hlc {
|
||||
self.last = if now_ms > self.last.wall {
|
||||
Hlc { wall: now_ms, logical: 0 }
|
||||
} else {
|
||||
Hlc { wall: self.last.wall, logical: self.last.logical + 1 }
|
||||
};
|
||||
self.last
|
||||
}
|
||||
|
||||
/// Takes in a clock value seen on another device, so later local events order after it.
|
||||
pub fn observe(&mut self, seen: Hlc) {
|
||||
if seen > self.last {
|
||||
self.last = seen;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn last(&self) -> Hlc {
|
||||
self.last
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Event {
|
||||
/// Unique: made by the device (random, or derived from the device and a counter).
|
||||
pub id: String,
|
||||
pub hlc: Hlc,
|
||||
pub device: String,
|
||||
pub op: Op,
|
||||
}
|
||||
|
||||
impl Event {
|
||||
/// The total order: clock, then device, then id.
|
||||
pub fn order(&self, other: &Event) -> Ordering {
|
||||
(self.hlc, &self.device, &self.id).cmp(&(other.hlc, &other.device, &other.id))
|
||||
}
|
||||
}
|
||||
|
||||
/// Every change Liber records. Unknown fields are refused, so an event from a newer schema is rejected rather than
|
||||
/// half-applied.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum Op {
|
||||
/// `restore`: from an export, where two books may share an identity on purpose: never merge.
|
||||
BookAdd {
|
||||
book: String,
|
||||
info: BookInfo,
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
restore: bool,
|
||||
},
|
||||
/// `base`: the id of the event whose value the editor saw (`Library::version`). For text fields, a different
|
||||
/// base means a concurrent edit: both versions are kept.
|
||||
BookSet {
|
||||
book: String,
|
||||
field: Field,
|
||||
value: serde_json::Value,
|
||||
base: Option<String>,
|
||||
},
|
||||
BookRemove {
|
||||
book: String,
|
||||
},
|
||||
BookFileAdd {
|
||||
book: String,
|
||||
file: BookFile,
|
||||
},
|
||||
BookFileRemove {
|
||||
book: String,
|
||||
sha256: String,
|
||||
},
|
||||
ShelfAdd {
|
||||
book: String,
|
||||
shelf: String,
|
||||
},
|
||||
ShelfRemove {
|
||||
book: String,
|
||||
shelf: String,
|
||||
},
|
||||
ReadStart {
|
||||
book: String,
|
||||
read: String,
|
||||
date: Option<String>,
|
||||
},
|
||||
ReadEnd {
|
||||
read: String,
|
||||
date: Option<String>,
|
||||
outcome: Outcome,
|
||||
},
|
||||
ReadRemove {
|
||||
read: String,
|
||||
},
|
||||
Lend {
|
||||
loan: String,
|
||||
book: String,
|
||||
person: Person,
|
||||
since: String,
|
||||
due: Option<String>,
|
||||
},
|
||||
Return {
|
||||
loan: String,
|
||||
date: String,
|
||||
},
|
||||
Position {
|
||||
book: String,
|
||||
cfi: String,
|
||||
chapter: u32,
|
||||
progress: f64,
|
||||
label: Option<String>,
|
||||
},
|
||||
HighlightAdd {
|
||||
id: String,
|
||||
book: String,
|
||||
kind: Mark,
|
||||
anchor: serde_json::Value,
|
||||
colour: Colour,
|
||||
note: String,
|
||||
created: u64,
|
||||
},
|
||||
HighlightSet {
|
||||
id: String,
|
||||
colour: Option<Colour>,
|
||||
note: Option<String>,
|
||||
base: Option<String>,
|
||||
},
|
||||
HighlightRemove {
|
||||
id: String,
|
||||
},
|
||||
Session {
|
||||
id: String,
|
||||
book: String,
|
||||
start: u64,
|
||||
end: u64,
|
||||
active_ms: u64,
|
||||
pages: u32,
|
||||
date: String,
|
||||
},
|
||||
Goal {
|
||||
year: i32,
|
||||
kind: GoalKind,
|
||||
target: u32,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
//! The `liber-export` format: one zip with `library.json` (the whole library), `books.csv`, `highlights/<book>.md`
|
||||
//! and, on request, the original book files under `files/`. Importing `library.json` into an empty library gives
|
||||
//! back exactly the same library (`ops_from`).
|
||||
|
||||
use crate::library::{Book, BookFile, Field, Library, Mark, Text};
|
||||
use crate::{Event, Hlc, Op};
|
||||
use liber_format::zip::ZipWriter;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
use std::io::{self, Read, Write};
|
||||
|
||||
pub const FORMAT: &str = "liber-export";
|
||||
pub const VERSION: u32 = 1;
|
||||
pub const MAX_JSON: usize = 256 * 1024 * 1024;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Envelope {
|
||||
format: String,
|
||||
version: u32,
|
||||
exported_at: String,
|
||||
library: Library,
|
||||
}
|
||||
|
||||
pub fn to_json(lib: &Library, exported_at: &str) -> String {
|
||||
let env =
|
||||
Envelope { format: FORMAT.into(), version: VERSION, exported_at: exported_at.into(), library: lib.clone() };
|
||||
serde_json::to_string_pretty(&env).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Reads `library.json`. The library it holds is checked by replaying it through events (`ops_from`), so whatever
|
||||
/// the file says passes the same rules as every other change.
|
||||
pub fn from_json(s: &str) -> Result<Library, String> {
|
||||
if s.len() > MAX_JSON {
|
||||
return Err("The export is larger than 256 MiB.".into());
|
||||
}
|
||||
let env: Envelope = serde_json::from_str(s).map_err(|e| format!("This is not a Liber export ({e})."))?;
|
||||
if env.format != FORMAT || env.version != VERSION {
|
||||
return Err(format!(
|
||||
"This export is {} version {}; Liber reads {FORMAT} version {VERSION}.",
|
||||
env.format, env.version
|
||||
));
|
||||
}
|
||||
let events = events_from(&env.library, "restore", 0);
|
||||
Ok(Library::from_events(&events))
|
||||
}
|
||||
|
||||
/// The events that rebuild `lib` in an empty library, stamped from `device` starting at `wall`.
|
||||
pub fn events_from(lib: &Library, device: &str, wall: u64) -> Vec<Event> {
|
||||
ops_from(lib)
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, op)| Event {
|
||||
id: format!("{device}-{i}"),
|
||||
hlc: Hlc { wall, logical: i as u32 },
|
||||
device: device.into(),
|
||||
op,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn text_ops(t: &Text, mut set: impl FnMut(String, Option<String>) -> Op) -> Vec<Op> {
|
||||
match &t.conflict {
|
||||
// The other version first, then the current one as a concurrent edit: the fold keeps both, as here.
|
||||
Some(c) => vec![set(c.clone(), None), set(t.value.clone(), Some("restore-concurrent".into()))],
|
||||
None if !t.value.is_empty() => vec![set(t.value.clone(), None)],
|
||||
None => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ops_from(lib: &Library) -> Vec<Op> {
|
||||
let mut ops = Vec::new();
|
||||
for b in lib.books.values() {
|
||||
let id = b.id.clone();
|
||||
let set = |field: Field, value: serde_json::Value| Op::BookSet { book: id.clone(), field, value, base: None };
|
||||
ops.push(Op::BookAdd { book: id.clone(), info: b.info.clone(), restore: true });
|
||||
for f in &b.files {
|
||||
ops.push(Op::BookFileAdd { book: id.clone(), file: f.clone() });
|
||||
}
|
||||
if b.paper {
|
||||
ops.push(set(Field::Paper, json!(true)));
|
||||
}
|
||||
ops.push(set(Field::Possession, serde_json::to_value(&b.possession).unwrap_or_default()));
|
||||
for s in &b.shelves {
|
||||
ops.push(Op::ShelfAdd { book: id.clone(), shelf: s.clone() });
|
||||
}
|
||||
if let Some(r) = b.rating {
|
||||
ops.push(set(Field::Rating, json!(r)));
|
||||
}
|
||||
ops.extend(text_ops(&b.review, |v, base| Op::BookSet {
|
||||
book: id.clone(),
|
||||
field: Field::Review,
|
||||
value: json!(v),
|
||||
base,
|
||||
}));
|
||||
ops.extend(text_ops(&b.notes, |v, base| Op::BookSet {
|
||||
book: id.clone(),
|
||||
field: Field::Notes,
|
||||
value: json!(v),
|
||||
base,
|
||||
}));
|
||||
if !b.moods.is_empty() {
|
||||
ops.push(set(Field::Moods, json!(b.moods)));
|
||||
}
|
||||
if !b.tags.is_empty() {
|
||||
ops.push(set(Field::Tags, json!(b.tags)));
|
||||
}
|
||||
if b.cover.is_some() {
|
||||
ops.push(set(Field::Cover, json!(b.cover)));
|
||||
}
|
||||
for l in &b.loans {
|
||||
ops.push(Op::Lend {
|
||||
loan: l.id.clone(),
|
||||
book: id.clone(),
|
||||
person: l.person.clone(),
|
||||
since: l.since.clone(),
|
||||
due: l.due.clone(),
|
||||
});
|
||||
if let Some(d) = &l.returned {
|
||||
ops.push(Op::Return { loan: l.id.clone(), date: d.clone() });
|
||||
}
|
||||
}
|
||||
for r in &b.reads {
|
||||
ops.push(Op::ReadStart { book: id.clone(), read: r.id.clone(), date: r.started.clone() });
|
||||
if let Some(o) = r.outcome {
|
||||
ops.push(Op::ReadEnd { read: r.id.clone(), date: r.finished.clone(), outcome: o });
|
||||
}
|
||||
}
|
||||
if b.to_read {
|
||||
ops.push(set(Field::ToRead, json!(true)));
|
||||
}
|
||||
let pos = |p: &crate::library::Position| Op::Position {
|
||||
book: id.clone(),
|
||||
cfi: p.cfi.clone(),
|
||||
chapter: p.chapter,
|
||||
progress: p.progress,
|
||||
label: p.label.clone(),
|
||||
};
|
||||
if let Some(f) = &b.position {
|
||||
ops.push(pos(f));
|
||||
}
|
||||
if let Some(l) = &b.last_position
|
||||
&& Some(l) != b.position.as_ref()
|
||||
{
|
||||
ops.push(pos(l));
|
||||
}
|
||||
}
|
||||
for h in lib.highlights.values() {
|
||||
let (first, rest) = match &h.note.conflict {
|
||||
Some(c) => (c.clone(), Some(h.note.value.clone())),
|
||||
None => (h.note.value.clone(), None),
|
||||
};
|
||||
ops.push(Op::HighlightAdd {
|
||||
id: h.id.clone(),
|
||||
book: h.book.clone(),
|
||||
kind: h.kind,
|
||||
anchor: h.anchor.clone(),
|
||||
colour: h.colour,
|
||||
note: first,
|
||||
created: h.created,
|
||||
});
|
||||
if let Some(v) = rest {
|
||||
ops.push(Op::HighlightSet {
|
||||
id: h.id.clone(),
|
||||
colour: None,
|
||||
note: Some(v),
|
||||
base: Some("restore-concurrent".into()),
|
||||
});
|
||||
}
|
||||
}
|
||||
for s in lib.sessions.values() {
|
||||
ops.push(Op::Session {
|
||||
id: s.id.clone(),
|
||||
book: s.book.clone(),
|
||||
start: s.start,
|
||||
end: s.end,
|
||||
active_ms: s.active_ms,
|
||||
pages: s.pages,
|
||||
date: s.date.clone(),
|
||||
});
|
||||
}
|
||||
for g in lib.goals.values() {
|
||||
ops.push(Op::Goal { year: g.year, kind: g.kind, target: g.target });
|
||||
}
|
||||
ops
|
||||
}
|
||||
|
||||
/// A spreadsheet cell that cannot run as a formula: a leading `= + - @`, tab or CR gets a `'`.
|
||||
pub fn safe_cell(s: &str) -> String {
|
||||
if s.starts_with(['=', '+', '-', '@', '\t', '\r']) { format!("'{s}") } else { s.to_owned() }
|
||||
}
|
||||
|
||||
pub fn books_csv(lib: &Library) -> String {
|
||||
let mut w = csv::Writer::from_writer(Vec::new());
|
||||
let _ = w.write_record([
|
||||
"id",
|
||||
"title",
|
||||
"authors",
|
||||
"isbn13",
|
||||
"status",
|
||||
"possession",
|
||||
"lent_to",
|
||||
"shelves",
|
||||
"rating_half_stars",
|
||||
"pages",
|
||||
"series",
|
||||
"started",
|
||||
"finished",
|
||||
"moods",
|
||||
"tags",
|
||||
"review",
|
||||
]);
|
||||
for b in lib.books.values() {
|
||||
let last = b.reads.last();
|
||||
let possession = match &b.possession {
|
||||
crate::Possession::Owned => "owned".to_owned(),
|
||||
crate::Possession::Borrowed { from, .. } => format!("borrowed from {}", from.name),
|
||||
crate::Possession::Wishlist => "wishlist".to_owned(),
|
||||
crate::Possession::None => String::new(),
|
||||
};
|
||||
let row = [
|
||||
b.id.clone(),
|
||||
b.info.title.clone(),
|
||||
b.info.authors.join("; "),
|
||||
b.info.isbn13.clone().unwrap_or_default(),
|
||||
serde_json::to_value(b.status()).ok().and_then(|v| v.as_str().map(str::to_owned)).unwrap_or_default(),
|
||||
possession,
|
||||
b.lent_to().map(|l| l.person.name.clone()).unwrap_or_default(),
|
||||
b.shelves.iter().cloned().collect::<Vec<_>>().join("; "),
|
||||
b.rating.map(|r| r.to_string()).unwrap_or_default(),
|
||||
b.info.pages.map(|p| p.to_string()).unwrap_or_default(),
|
||||
b.info.series.as_ref().map(|s| s.name.clone()).unwrap_or_default(),
|
||||
last.and_then(|r| r.started.clone()).unwrap_or_default(),
|
||||
last.and_then(|r| r.finished.clone()).unwrap_or_default(),
|
||||
b.moods.iter().cloned().collect::<Vec<_>>().join("; "),
|
||||
b.tags.iter().cloned().collect::<Vec<_>>().join("; "),
|
||||
b.review.value.clone(),
|
||||
];
|
||||
let _ = w.write_record(row.iter().map(|c| safe_cell(c)));
|
||||
}
|
||||
String::from_utf8(w.into_inner().unwrap_or_default()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A file name for a book: letters, digits, `-`, at most 60 characters, plus the id's start.
|
||||
pub fn slug(b: &Book) -> String {
|
||||
let mut s: String = b
|
||||
.info
|
||||
.title
|
||||
.chars()
|
||||
.map(|c| if c.is_alphanumeric() { c.to_ascii_lowercase() } else { '-' })
|
||||
.collect::<String>()
|
||||
.split('-')
|
||||
.filter(|x| !x.is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join("-");
|
||||
s = s.chars().take(60).collect();
|
||||
let id: String = b.id.chars().filter(|c| c.is_ascii_alphanumeric()).take(8).collect();
|
||||
if s.is_empty() { id } else { format!("{s}-{id}") }
|
||||
}
|
||||
|
||||
pub fn highlights_markdown(lib: &Library, book: &str) -> String {
|
||||
let Some(b) = lib.books.get(book) else { return String::new() };
|
||||
let mut out = format!("# {}\n", b.info.title);
|
||||
if !b.info.authors.is_empty() {
|
||||
out.push_str(&format!("\n*{}*\n", b.info.authors.join(", ")));
|
||||
}
|
||||
let mut hs: Vec<_> = lib.highlights.values().filter(|h| h.book == b.id).collect();
|
||||
hs.sort_by_key(|h| (h.anchor.get("chapter").and_then(|c| c.as_u64()).unwrap_or(0), h.created));
|
||||
for h in hs {
|
||||
let quote = h.anchor.pointer("/quote/exact").and_then(|q| q.as_str()).unwrap_or("");
|
||||
out.push('\n');
|
||||
match h.kind {
|
||||
Mark::Bookmark => out.push_str("- Bookmark\n"),
|
||||
_ if !quote.is_empty() => {
|
||||
for line in quote.lines() {
|
||||
out.push_str(&format!("> {line}\n"));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if !h.note.value.is_empty() {
|
||||
out.push_str(&format!("\n{}\n", h.note.value));
|
||||
}
|
||||
if let Some(c) = &h.note.conflict {
|
||||
out.push_str(&format!("\n(Other version: {c})\n"));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Gives a reader for a book file to include in the export, or `None` to leave it out.
|
||||
pub type FileSource<'a> = dyn FnMut(&Book, &BookFile) -> Option<Box<dyn Read>> + 'a;
|
||||
|
||||
/// Writes the whole export. `file` returns a reader for a book file the person chose to include, or `None`.
|
||||
pub fn write_zip<W: Write>(lib: &Library, w: W, exported_at: &str, file: &mut FileSource<'_>) -> io::Result<W> {
|
||||
let mut z = ZipWriter::new(w);
|
||||
z.add("library.json", to_json(lib, exported_at).as_bytes(), true)?;
|
||||
z.add("books.csv", books_csv(lib).as_bytes(), true)?;
|
||||
for b in lib.books.values() {
|
||||
if lib.highlights.values().any(|h| h.book == b.id) {
|
||||
z.add(&format!("highlights/{}.md", slug(b)), highlights_markdown(lib, &b.id).as_bytes(), true)?;
|
||||
}
|
||||
for f in &b.files {
|
||||
if let Some(mut r) = file(b, f) {
|
||||
let ext: String = f.format.chars().filter(|c| c.is_ascii_alphanumeric()).take(8).collect();
|
||||
z.add_stream(&format!("files/{}-{}.{ext}", slug(b), &f.sha256[..f.sha256.len().min(8)]), &mut r)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
z.finish()
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
//! Goodreads and StoryGraph CSV import. Every row is imported or listed with its reason; columns Liber does not
|
||||
//! map are kept on the book (`import_extra`) and named in the report. The CSV is hostile: the input and each field
|
||||
//! are capped, values are stored as text and never evaluated.
|
||||
|
||||
use crate::library::{BookInfo, Field, Library, Outcome, Possession};
|
||||
use crate::{MOODS, Op, isbn13, parse_date};
|
||||
use serde::Serialize;
|
||||
use serde_json::json;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
pub const MAX_INPUT: usize = 32 * 1024 * 1024;
|
||||
pub const MAX_FIELD: usize = 64 * 1024;
|
||||
pub const MAX_ROWS: usize = 100_000;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Source {
|
||||
Goodreads,
|
||||
StoryGraph,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct Report {
|
||||
pub source: Source,
|
||||
pub rows: usize,
|
||||
pub imported: usize,
|
||||
/// (row number, 1-based after the header; why)
|
||||
pub skipped: Vec<(usize, String)>,
|
||||
/// Columns Liber does not know: their values are kept on each book.
|
||||
pub unknown_columns: Vec<String>,
|
||||
/// Columns Liber knows but does not use (also kept on each book).
|
||||
pub unused_columns: Vec<String>,
|
||||
/// (row, column) of fields cut at 64 KiB.
|
||||
pub truncated: Vec<(usize, String)>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum ImportError {
|
||||
#[error("The file is larger than 32 MiB, which is too large for a reading-list export.")]
|
||||
TooLarge,
|
||||
#[error("This is not a Goodreads or StoryGraph export (the header is not one Liber knows).")]
|
||||
UnknownFormat,
|
||||
#[error("The file is not valid CSV: {0}")]
|
||||
Csv(String),
|
||||
#[error("The file has more than 100,000 rows.")]
|
||||
TooManyRows,
|
||||
}
|
||||
|
||||
const GOODREADS_USED: &[&str] = &[
|
||||
"Title",
|
||||
"Author",
|
||||
"Additional Authors",
|
||||
"ISBN",
|
||||
"ISBN13",
|
||||
"My Rating",
|
||||
"Publisher",
|
||||
"Binding",
|
||||
"Number of Pages",
|
||||
"Year Published",
|
||||
"Original Publication Year",
|
||||
"Date Read",
|
||||
"Date Added",
|
||||
"Bookshelves",
|
||||
"Exclusive Shelf",
|
||||
"My Review",
|
||||
"Private Notes",
|
||||
"Read Count",
|
||||
"Owned Copies",
|
||||
];
|
||||
const GOODREADS_UNUSED: &[&str] = &["Book Id", "Author l-f", "Average Rating", "Bookshelves with positions", "Spoiler"];
|
||||
const STORYGRAPH_USED: &[&str] = &[
|
||||
"Title",
|
||||
"Authors",
|
||||
"ISBN/UID",
|
||||
"Format",
|
||||
"Read Status",
|
||||
"Date Added",
|
||||
"Last Date Read",
|
||||
"Dates Read",
|
||||
"Read Count",
|
||||
"Moods",
|
||||
"Star Rating",
|
||||
"Review",
|
||||
"Tags",
|
||||
"Owned?",
|
||||
];
|
||||
const STORYGRAPH_UNUSED: &[&str] = &[
|
||||
"Contributors",
|
||||
"Pace",
|
||||
"Character- or Plot-Driven?",
|
||||
"Strong Character Development?",
|
||||
"Loveable Characters?",
|
||||
"Diverse Characters?",
|
||||
"Flawed Characters?",
|
||||
"Content Warnings",
|
||||
"Content Warning Description",
|
||||
];
|
||||
|
||||
/// Goodreads writes `="0441172717"` so spreadsheets keep leading zeros.
|
||||
fn unwrap_excel(s: &str) -> &str {
|
||||
s.trim().strip_prefix("=\"").and_then(|x| x.strip_suffix('"')).unwrap_or(s.trim())
|
||||
}
|
||||
|
||||
fn ms_of(date: &str) -> Option<u64> {
|
||||
let d = parse_date(date)?;
|
||||
let (y, m, dd) = (d[..4].parse().ok()?, d[5..7].parse().ok()?, d[8..].parse().ok()?);
|
||||
let days = crate::days_from_civil(y, m, dd);
|
||||
(days >= 0).then(|| days as u64 * 86_400_000)
|
||||
}
|
||||
|
||||
/// Goodreads reviews are HTML with `<br/>`.
|
||||
fn review_text(s: &str) -> String {
|
||||
let s = s.replace("<br/>", "\n").replace("<br />", "\n").replace("<br>", "\n");
|
||||
let mut out = String::new();
|
||||
let mut tag = false;
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'<' => tag = true,
|
||||
'>' if tag => tag = false,
|
||||
c if !tag => out.push(c),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out.trim().to_owned()
|
||||
}
|
||||
|
||||
fn list(s: &str) -> Vec<String> {
|
||||
s.split(',').map(|x| x.trim().to_owned()).filter(|x| !x.is_empty()).collect()
|
||||
}
|
||||
|
||||
fn norm_key(title: &str, author: &str) -> String {
|
||||
let f = |s: &str| s.to_lowercase().chars().filter(|c| c.is_alphanumeric()).collect::<String>();
|
||||
format!("{}|{}", f(title), f(author))
|
||||
}
|
||||
|
||||
struct Row<'a> {
|
||||
cols: &'a [String],
|
||||
vals: Vec<String>,
|
||||
}
|
||||
|
||||
impl Row<'_> {
|
||||
fn get(&self, c: &str) -> &str {
|
||||
self.cols.iter().position(|x| x == c).and_then(|i| self.vals.get(i)).map(|s| s.trim()).unwrap_or("")
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses an export into events. `new_id` makes ids (books, reads); `now_ms` is the fallback "added" time.
|
||||
pub fn import_csv(
|
||||
bytes: &[u8],
|
||||
existing: &Library,
|
||||
new_id: &mut dyn FnMut() -> String,
|
||||
now_ms: u64,
|
||||
) -> Result<(Vec<Op>, Report), ImportError> {
|
||||
if bytes.len() > MAX_INPUT {
|
||||
return Err(ImportError::TooLarge);
|
||||
}
|
||||
let (text, _) = liber_format::text::decode_text(bytes);
|
||||
let mut rdr = csv::ReaderBuilder::new().flexible(true).has_headers(true).from_reader(text.as_bytes());
|
||||
let cols: Vec<String> = rdr
|
||||
.headers()
|
||||
.map_err(|e| ImportError::Csv(e.to_string()))?
|
||||
.iter()
|
||||
.map(|h| h.trim().trim_start_matches('\u{feff}').to_owned())
|
||||
.collect();
|
||||
let has = |c: &str| cols.iter().any(|x| x == c);
|
||||
let source = if has("Exclusive Shelf") && has("Title") {
|
||||
Source::Goodreads
|
||||
} else if has("Read Status") && has("Title") {
|
||||
Source::StoryGraph
|
||||
} else {
|
||||
return Err(ImportError::UnknownFormat);
|
||||
};
|
||||
let (used, unused) = match source {
|
||||
Source::Goodreads => (GOODREADS_USED, GOODREADS_UNUSED),
|
||||
Source::StoryGraph => (STORYGRAPH_USED, STORYGRAPH_UNUSED),
|
||||
};
|
||||
let mut report = Report {
|
||||
source,
|
||||
rows: 0,
|
||||
imported: 0,
|
||||
skipped: vec![],
|
||||
unknown_columns: cols
|
||||
.iter()
|
||||
.filter(|c| !c.is_empty() && !used.contains(&c.as_str()) && !unused.contains(&c.as_str()))
|
||||
.cloned()
|
||||
.collect(),
|
||||
unused_columns: cols.iter().filter(|c| unused.contains(&c.as_str())).cloned().collect(),
|
||||
truncated: vec![],
|
||||
};
|
||||
let mut seen: BTreeSet<String> = existing
|
||||
.books
|
||||
.values()
|
||||
.map(|b| norm_key(&b.info.title, b.info.authors.first().map(String::as_str).unwrap_or("")))
|
||||
.collect();
|
||||
let mut seen_isbn: BTreeSet<String> = existing.books.values().filter_map(|b| b.info.isbn13.clone()).collect();
|
||||
let mut ops = Vec::new();
|
||||
for (i, rec) in rdr.records().enumerate() {
|
||||
let n = i + 1;
|
||||
if n > MAX_ROWS {
|
||||
return Err(ImportError::TooManyRows);
|
||||
}
|
||||
report.rows += 1;
|
||||
let rec = match rec {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
report.skipped.push((n, format!("not valid CSV: {e}")));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mut vals = Vec::with_capacity(rec.len());
|
||||
for (ci, v) in rec.iter().enumerate() {
|
||||
if v.len() > MAX_FIELD {
|
||||
let mut end = MAX_FIELD;
|
||||
while !v.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
report.truncated.push((n, cols.get(ci).cloned().unwrap_or_default()));
|
||||
vals.push(v[..end].to_owned());
|
||||
} else {
|
||||
vals.push(v.to_owned());
|
||||
}
|
||||
}
|
||||
let row = Row { cols: &cols, vals };
|
||||
let title = row.get("Title").to_owned();
|
||||
if title.is_empty() {
|
||||
report.skipped.push((n, "no title".into()));
|
||||
continue;
|
||||
}
|
||||
let mut extra = BTreeMap::new();
|
||||
for (ci, c) in cols.iter().enumerate() {
|
||||
if !used.contains(&c.as_str()) && !c.is_empty() {
|
||||
let v = row.vals.get(ci).map(|s| s.trim()).unwrap_or("");
|
||||
if !v.is_empty() {
|
||||
let prefix = match source {
|
||||
Source::Goodreads => "goodreads",
|
||||
Source::StoryGraph => "storygraph",
|
||||
};
|
||||
extra.insert(format!("{prefix}:{c}"), v.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
let r = match source {
|
||||
Source::Goodreads => goodreads(&row, extra, now_ms),
|
||||
Source::StoryGraph => storygraph(&row, extra, now_ms),
|
||||
};
|
||||
let author = r.info.authors.first().cloned().unwrap_or_default();
|
||||
let key = norm_key(&r.info.title, &author);
|
||||
if r.info.isbn13.as_ref().is_some_and(|i| seen_isbn.contains(i)) || seen.contains(&key) {
|
||||
report.skipped.push((n, format!("“{}” is already in your library", r.info.title)));
|
||||
continue;
|
||||
}
|
||||
seen.insert(key);
|
||||
if let Some(i) = &r.info.isbn13 {
|
||||
seen_isbn.insert(i.clone());
|
||||
}
|
||||
let book = new_id();
|
||||
ops.push(Op::BookAdd { book: book.clone(), info: r.info, restore: false });
|
||||
let set = |field: Field, value: serde_json::Value| Op::BookSet { book: book.clone(), field, value, base: None };
|
||||
if let Some(rt) = r.rating {
|
||||
ops.push(set(Field::Rating, json!(rt)));
|
||||
}
|
||||
if !r.review.is_empty() {
|
||||
ops.push(set(Field::Review, json!(r.review)));
|
||||
}
|
||||
if !r.notes.is_empty() {
|
||||
ops.push(set(Field::Notes, json!(r.notes)));
|
||||
}
|
||||
if r.owned {
|
||||
ops.push(set(Field::Possession, serde_json::to_value(Possession::Owned).unwrap_or_default()));
|
||||
}
|
||||
if r.paper {
|
||||
ops.push(set(Field::Paper, json!(true)));
|
||||
}
|
||||
if !r.moods.is_empty() {
|
||||
ops.push(set(Field::Moods, json!(r.moods)));
|
||||
}
|
||||
if !r.tags.is_empty() {
|
||||
ops.push(set(Field::Tags, json!(r.tags)));
|
||||
}
|
||||
if r.to_read {
|
||||
ops.push(set(Field::ToRead, json!(true)));
|
||||
}
|
||||
for s in r.shelves {
|
||||
ops.push(Op::ShelfAdd { book: book.clone(), shelf: s });
|
||||
}
|
||||
for (start, end, outcome) in r.reads {
|
||||
let read = new_id();
|
||||
ops.push(Op::ReadStart { book: book.clone(), read: read.clone(), date: start });
|
||||
if let Some(o) = outcome {
|
||||
ops.push(Op::ReadEnd { read, date: end, outcome: o });
|
||||
}
|
||||
}
|
||||
report.imported += 1;
|
||||
}
|
||||
Ok((ops, report))
|
||||
}
|
||||
|
||||
struct Parsed {
|
||||
info: BookInfo,
|
||||
rating: Option<u8>,
|
||||
review: String,
|
||||
notes: String,
|
||||
owned: bool,
|
||||
paper: bool,
|
||||
moods: BTreeSet<String>,
|
||||
tags: BTreeSet<String>,
|
||||
to_read: bool,
|
||||
shelves: Vec<String>,
|
||||
/// (started, finished, outcome)
|
||||
reads: Vec<(Option<String>, Option<String>, Option<Outcome>)>,
|
||||
}
|
||||
|
||||
fn paper_binding(b: &str) -> bool {
|
||||
let b = b.to_lowercase();
|
||||
["paperback", "hardcover", "mass market", "hardback", "board book", "library binding", "leather", "spiral"]
|
||||
.iter()
|
||||
.any(|p| b.contains(p))
|
||||
}
|
||||
|
||||
fn goodreads(row: &Row, extra: BTreeMap<String, String>, now_ms: u64) -> Parsed {
|
||||
let mut authors = vec![row.get("Author").to_owned()];
|
||||
authors.extend(list(row.get("Additional Authors")));
|
||||
authors.retain(|a| !a.is_empty());
|
||||
let isbn = isbn13(unwrap_excel(row.get("ISBN13"))).or_else(|| isbn13(unwrap_excel(row.get("ISBN"))));
|
||||
let published = [row.get("Original Publication Year"), row.get("Year Published")]
|
||||
.iter()
|
||||
.find(|y| !y.is_empty())
|
||||
.map(|y| y.to_string());
|
||||
let rating: u8 = row.get("My Rating").parse().unwrap_or(0);
|
||||
let exclusive = row.get("Exclusive Shelf").to_owned();
|
||||
let mut shelves: Vec<String> = list(row.get("Bookshelves"))
|
||||
.into_iter()
|
||||
.filter(|s| !matches!(s.as_str(), "read" | "currently-reading" | "to-read"))
|
||||
.collect();
|
||||
let read_count: usize = row.get("Read Count").parse().unwrap_or(0);
|
||||
let date_read = parse_date(row.get("Date Read"));
|
||||
let mut reads = Vec::new();
|
||||
let mut to_read = false;
|
||||
match exclusive.as_str() {
|
||||
"read" => {
|
||||
for _ in 1..read_count.clamp(1, 50) {
|
||||
reads.push((None, None, Some(Outcome::Read)));
|
||||
}
|
||||
reads.push((None, date_read.clone(), Some(Outcome::Read)));
|
||||
}
|
||||
"currently-reading" => reads.push((None, None, None)),
|
||||
"to-read" => to_read = true,
|
||||
other if !other.is_empty() && !shelves.iter().any(|s| s == other) => {
|
||||
shelves.push(other.to_owned());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Parsed {
|
||||
info: BookInfo {
|
||||
title: row.get("Title").to_owned(),
|
||||
authors,
|
||||
isbn13: isbn,
|
||||
publisher: Some(row.get("Publisher").to_owned()).filter(|s| !s.is_empty()),
|
||||
published,
|
||||
pages: row.get("Number of Pages").parse().ok().filter(|p| *p > 0),
|
||||
added: ms_of(row.get("Date Added")).unwrap_or(now_ms),
|
||||
import_extra: extra,
|
||||
..BookInfo::default()
|
||||
},
|
||||
rating: (1..=5).contains(&rating).then_some(rating * 2),
|
||||
review: review_text(row.get("My Review")),
|
||||
notes: row.get("Private Notes").to_owned(),
|
||||
owned: row.get("Owned Copies").parse::<u32>().unwrap_or(0) > 0,
|
||||
paper: paper_binding(row.get("Binding")),
|
||||
moods: BTreeSet::new(),
|
||||
tags: BTreeSet::new(),
|
||||
to_read,
|
||||
shelves,
|
||||
reads,
|
||||
}
|
||||
}
|
||||
|
||||
fn storygraph(row: &Row, extra: BTreeMap<String, String>, now_ms: u64) -> Parsed {
|
||||
let uid = row.get("ISBN/UID");
|
||||
let star: f64 = row.get("Star Rating").parse().unwrap_or(0.0);
|
||||
let rating = (star > 0.0 && star <= 5.0).then(|| ((star * 2.0).round() as u8).clamp(1, 10));
|
||||
let status = row.get("Read Status").to_lowercase();
|
||||
let mut reads = Vec::new();
|
||||
for range in list(row.get("Dates Read")) {
|
||||
let (a, b) =
|
||||
range.split_once('-').map(|(a, b)| (parse_date(a), parse_date(b))).unwrap_or((None, parse_date(&range)));
|
||||
reads.push((a, b, Some(Outcome::Read)));
|
||||
}
|
||||
let mut to_read = false;
|
||||
match status.as_str() {
|
||||
"read" if reads.is_empty() => {
|
||||
let n: usize = row.get("Read Count").parse().unwrap_or(1);
|
||||
for i in 0..n.clamp(1, 50) {
|
||||
let last = (i + 1 == n.max(1)).then(|| parse_date(row.get("Last Date Read"))).flatten();
|
||||
reads.push((None, last, Some(Outcome::Read)));
|
||||
}
|
||||
}
|
||||
"read" => {}
|
||||
"currently-reading" | "paused" => reads.push((None, None, None)),
|
||||
"did-not-finish" => reads.push((None, parse_date(row.get("Last Date Read")), Some(Outcome::DidNotFinish))),
|
||||
"to-read" => to_read = true,
|
||||
_ => {}
|
||||
}
|
||||
let mut moods = BTreeSet::new();
|
||||
let mut tags: BTreeSet<String> = list(row.get("Tags")).into_iter().collect();
|
||||
for m in list(row.get("Moods")) {
|
||||
let l = m.to_lowercase();
|
||||
if MOODS.contains(&l.as_str()) {
|
||||
moods.insert(l);
|
||||
} else {
|
||||
tags.insert(m);
|
||||
}
|
||||
}
|
||||
let mut info = BookInfo {
|
||||
title: row.get("Title").to_owned(),
|
||||
authors: list(row.get("Authors")),
|
||||
isbn13: isbn13(uid),
|
||||
added: ms_of(row.get("Date Added")).unwrap_or(now_ms),
|
||||
import_extra: extra,
|
||||
..BookInfo::default()
|
||||
};
|
||||
if info.isbn13.is_none() && !uid.is_empty() {
|
||||
info.import_extra.insert("storygraph:ISBN/UID".into(), uid.to_owned());
|
||||
}
|
||||
let format = row.get("Format").to_lowercase();
|
||||
Parsed {
|
||||
info,
|
||||
rating,
|
||||
review: row.get("Review").to_owned(),
|
||||
notes: String::new(),
|
||||
owned: matches!(row.get("Owned?").to_lowercase().as_str(), "yes" | "true"),
|
||||
paper: format.contains("paperback") || format.contains("hardcover"),
|
||||
moods,
|
||||
tags,
|
||||
to_read,
|
||||
shelves: vec![],
|
||||
reads,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
//! Liber's library (docs in the app repo, `docs/01_books.md`): the model, the event log and its merge, stats,
|
||||
//! Goodreads/StoryGraph import and the `liber-export` format. Pure: time, ids and devices are parameters.
|
||||
//!
|
||||
//! Every change is an [`Event`]; the [`Library`] is a fold of the events in their total order
|
||||
//! (hybrid logical clock, then device, then id). Two devices holding the same events hold the same library,
|
||||
//! whatever order the events arrived in: that is the whole sync guarantee.
|
||||
|
||||
pub mod event;
|
||||
pub mod export;
|
||||
pub mod import;
|
||||
pub mod library;
|
||||
pub mod stats;
|
||||
|
||||
pub use event::{Clock, Event, Hlc, Op};
|
||||
pub use library::{Book, Highlight, Library, Loan, Possession, Read, ReadStatus, Text};
|
||||
|
||||
pub use liber_format::text::isbn13;
|
||||
|
||||
/// StoryGraph's moods: Liber's fixed mood list (own tags are separate).
|
||||
pub const MOODS: &[&str] = &[
|
||||
"adventurous",
|
||||
"challenging",
|
||||
"dark",
|
||||
"emotional",
|
||||
"funny",
|
||||
"hopeful",
|
||||
"informative",
|
||||
"inspiring",
|
||||
"lighthearted",
|
||||
"mysterious",
|
||||
"reflective",
|
||||
"relaxing",
|
||||
"sad",
|
||||
"tense",
|
||||
];
|
||||
|
||||
/// Days since 1970-01-01 for a civil date (Howard Hinnant's algorithm).
|
||||
pub fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
|
||||
let y = if m <= 2 { y - 1 } else { y };
|
||||
let era = if y >= 0 { y } else { y - 399 } / 400;
|
||||
let yoe = y - era * 400;
|
||||
let mp = (m as i64 + 9) % 12;
|
||||
let doy = (153 * mp + 2) / 5 + d as i64 - 1;
|
||||
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
|
||||
era * 146_097 + doe - 719_468
|
||||
}
|
||||
|
||||
/// `YYYY-MM-DD` (or `YYYY/MM/DD`) → `YYYY-MM-DD`, checked.
|
||||
pub fn parse_date(s: &str) -> Option<String> {
|
||||
let s = s.trim();
|
||||
let parts: Vec<&str> = s.split(['-', '/']).collect();
|
||||
if parts.len() != 3 {
|
||||
return None;
|
||||
}
|
||||
let y: i32 = parts[0].parse().ok()?;
|
||||
let m: u32 = parts[1].parse().ok()?;
|
||||
let d: u32 = parts[2].parse().ok()?;
|
||||
if !(1..=9999).contains(&y) || !(1..=12).contains(&m) || !(1..=31).contains(&d) {
|
||||
return None;
|
||||
}
|
||||
let dim = [
|
||||
31,
|
||||
if y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) { 29 } else { 28 },
|
||||
31,
|
||||
30,
|
||||
31,
|
||||
30,
|
||||
31,
|
||||
31,
|
||||
30,
|
||||
31,
|
||||
30,
|
||||
31,
|
||||
];
|
||||
if d > dim[(m - 1) as usize] {
|
||||
return None;
|
||||
}
|
||||
Some(format!("{y:04}-{m:02}-{d:02}"))
|
||||
}
|
||||
|
||||
/// The year of a `YYYY-MM-DD` date.
|
||||
pub fn year_of(date: &str) -> Option<i32> {
|
||||
date.get(..4)?.parse().ok()
|
||||
}
|
||||
@@ -0,0 +1,660 @@
|
||||
//! The library as a fold of events (see `lib.rs`): books and their states, shelves, reads, loans, positions,
|
||||
//! highlights, reading sessions and goals.
|
||||
|
||||
use crate::event::{Event, Op};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
/// Someone from the people directory (`id`), or a plain name until it is wired.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Person {
|
||||
pub id: Option<String>,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Series {
|
||||
pub name: String,
|
||||
pub index: Option<f64>,
|
||||
}
|
||||
|
||||
/// What is known about a book when it is added.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct BookInfo {
|
||||
pub title: String,
|
||||
pub authors: Vec<String>,
|
||||
pub isbn13: Option<String>,
|
||||
/// The text fingerprint of an e-book (liber-format), for merging the same book from two sources.
|
||||
pub fingerprint: Option<String>,
|
||||
pub series: Option<Series>,
|
||||
pub language: Option<String>,
|
||||
pub publisher: Option<String>,
|
||||
pub published: Option<String>,
|
||||
pub description: Option<String>,
|
||||
pub pages: Option<u32>,
|
||||
pub genres: Vec<String>,
|
||||
/// Unix ms, given by the device.
|
||||
pub added: u64,
|
||||
/// Columns an import did not map, kept rather than dropped.
|
||||
pub import_extra: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct BookFile {
|
||||
pub sha256: String,
|
||||
pub format: String,
|
||||
pub size: u64,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||
pub enum Possession {
|
||||
Owned,
|
||||
Borrowed {
|
||||
from: Person,
|
||||
due: Option<String>,
|
||||
},
|
||||
Wishlist,
|
||||
#[default]
|
||||
None,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Outcome {
|
||||
Read,
|
||||
DidNotFinish,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ReadStatus {
|
||||
ToRead,
|
||||
Reading,
|
||||
Read,
|
||||
DidNotFinish,
|
||||
None,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Read {
|
||||
pub id: String,
|
||||
pub started: Option<String>,
|
||||
pub finished: Option<String>,
|
||||
pub outcome: Option<Outcome>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Loan {
|
||||
pub id: String,
|
||||
pub person: Person,
|
||||
pub since: String,
|
||||
pub due: Option<String>,
|
||||
pub returned: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Position {
|
||||
pub cfi: String,
|
||||
pub chapter: u32,
|
||||
pub progress: f64,
|
||||
pub label: Option<String>,
|
||||
}
|
||||
|
||||
/// A text field that may hold two versions after concurrent edits on two devices.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Text {
|
||||
pub value: String,
|
||||
/// The other version, shown with a marker until someone edits the field again.
|
||||
pub conflict: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Field {
|
||||
Title,
|
||||
Authors,
|
||||
Series,
|
||||
Language,
|
||||
Publisher,
|
||||
Published,
|
||||
Description,
|
||||
Pages,
|
||||
Isbn13,
|
||||
Genres,
|
||||
Paper,
|
||||
Possession,
|
||||
Rating,
|
||||
Review,
|
||||
Notes,
|
||||
Moods,
|
||||
Tags,
|
||||
ToRead,
|
||||
Cover,
|
||||
}
|
||||
|
||||
impl Field {
|
||||
fn key(self) -> &'static str {
|
||||
match self {
|
||||
Field::Title => "title",
|
||||
Field::Authors => "authors",
|
||||
Field::Series => "series",
|
||||
Field::Language => "language",
|
||||
Field::Publisher => "publisher",
|
||||
Field::Published => "published",
|
||||
Field::Description => "description",
|
||||
Field::Pages => "pages",
|
||||
Field::Isbn13 => "isbn13",
|
||||
Field::Genres => "genres",
|
||||
Field::Paper => "paper",
|
||||
Field::Possession => "possession",
|
||||
Field::Rating => "rating",
|
||||
Field::Review => "review",
|
||||
Field::Notes => "notes",
|
||||
Field::Moods => "moods",
|
||||
Field::Tags => "tags",
|
||||
Field::ToRead => "to_read",
|
||||
Field::Cover => "cover",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Mark {
|
||||
Highlight,
|
||||
Note,
|
||||
Bookmark,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Colour {
|
||||
Yellow,
|
||||
Green,
|
||||
Blue,
|
||||
Pink,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum GoalKind {
|
||||
Books,
|
||||
Pages,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Book {
|
||||
pub id: String,
|
||||
pub info: BookInfo,
|
||||
pub files: Vec<BookFile>,
|
||||
pub paper: bool,
|
||||
pub possession: Possession,
|
||||
pub loans: Vec<Loan>,
|
||||
pub reads: Vec<Read>,
|
||||
pub to_read: bool,
|
||||
pub shelves: BTreeSet<String>,
|
||||
/// Half stars, 1–10.
|
||||
pub rating: Option<u8>,
|
||||
pub review: Text,
|
||||
pub notes: Text,
|
||||
pub moods: BTreeSet<String>,
|
||||
pub tags: BTreeSet<String>,
|
||||
/// A blob reference (the cover image's sha256).
|
||||
pub cover: Option<String>,
|
||||
/// The furthest position reached on any device.
|
||||
pub position: Option<Position>,
|
||||
/// The most recent position, when it is behind the furthest: "Jump back to page X?".
|
||||
pub last_position: Option<Position>,
|
||||
}
|
||||
|
||||
impl Book {
|
||||
fn new(id: &str, info: BookInfo) -> Book {
|
||||
Book {
|
||||
id: id.to_owned(),
|
||||
info,
|
||||
files: vec![],
|
||||
paper: false,
|
||||
possession: Possession::None,
|
||||
loans: vec![],
|
||||
reads: vec![],
|
||||
to_read: false,
|
||||
shelves: BTreeSet::new(),
|
||||
rating: None,
|
||||
review: Text::default(),
|
||||
notes: Text::default(),
|
||||
moods: BTreeSet::new(),
|
||||
tags: BTreeSet::new(),
|
||||
cover: None,
|
||||
position: None,
|
||||
last_position: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn status(&self) -> ReadStatus {
|
||||
match self.reads.last() {
|
||||
Some(r) => match r.outcome {
|
||||
None => ReadStatus::Reading,
|
||||
Some(Outcome::Read) => ReadStatus::Read,
|
||||
Some(Outcome::DidNotFinish) => ReadStatus::DidNotFinish,
|
||||
},
|
||||
None if self.to_read => ReadStatus::ToRead,
|
||||
None => ReadStatus::None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The loan that is out now.
|
||||
pub fn lent_to(&self) -> Option<&Loan> {
|
||||
self.loans.iter().find(|l| l.returned.is_none())
|
||||
}
|
||||
|
||||
/// The position to offer "Jump back to …" for.
|
||||
pub fn jump_back(&self) -> Option<&Position> {
|
||||
let (Some(f), Some(l)) = (&self.position, &self.last_position) else { return None };
|
||||
(l.progress + 1e-9 < f.progress).then_some(l)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Highlight {
|
||||
pub id: String,
|
||||
pub book: String,
|
||||
pub kind: Mark,
|
||||
/// A `liber_format::Anchor` (or a page for PDFs), opaque here.
|
||||
pub anchor: serde_json::Value,
|
||||
pub colour: Colour,
|
||||
pub note: Text,
|
||||
pub created: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Session {
|
||||
pub id: String,
|
||||
pub book: String,
|
||||
pub start: u64,
|
||||
pub end: u64,
|
||||
pub active_ms: u64,
|
||||
pub pages: u32,
|
||||
/// The local day it counts for (`YYYY-MM-DD`, from the device).
|
||||
pub date: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Goal {
|
||||
pub year: i32,
|
||||
pub kind: GoalKind,
|
||||
pub target: u32,
|
||||
}
|
||||
|
||||
/// 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.
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
pub struct Library {
|
||||
pub books: BTreeMap<String, Book>,
|
||||
pub highlights: BTreeMap<String, Highlight>,
|
||||
pub sessions: BTreeMap<String, Session>,
|
||||
pub goals: BTreeMap<i32, Goal>,
|
||||
#[serde(skip)]
|
||||
aliases: BTreeMap<String, String>,
|
||||
#[serde(skip)]
|
||||
versions: BTreeMap<(String, &'static str), String>,
|
||||
#[serde(skip)]
|
||||
removed_books: BTreeSet<String>,
|
||||
#[serde(skip)]
|
||||
removed_highlights: BTreeSet<String>,
|
||||
#[serde(skip)]
|
||||
read_book: BTreeMap<String, String>,
|
||||
#[serde(skip)]
|
||||
loan_book: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl PartialEq for Library {
|
||||
fn eq(&self, o: &Library) -> bool {
|
||||
self.books == o.books && self.highlights == o.highlights && self.sessions == o.sessions && self.goals == o.goals
|
||||
}
|
||||
}
|
||||
|
||||
/// Field values longer than this are cut (a review, a note).
|
||||
pub const MAX_TEXT: usize = 64 * 1024;
|
||||
|
||||
fn clip(s: String) -> String {
|
||||
if s.len() <= MAX_TEXT {
|
||||
return s;
|
||||
}
|
||||
let mut end = MAX_TEXT;
|
||||
while !s.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
s[..end].to_owned()
|
||||
}
|
||||
|
||||
impl Library {
|
||||
/// Folds events in their total order.
|
||||
pub fn from_events<'a>(events: impl IntoIterator<Item = &'a Event>) -> Library {
|
||||
let mut v: Vec<&Event> = events.into_iter().collect();
|
||||
v.sort_by(|a, b| a.order(b));
|
||||
v.dedup_by(|a, b| a.id == b.id);
|
||||
let mut lib = Library::default();
|
||||
for e in v {
|
||||
lib.apply(e);
|
||||
}
|
||||
lib
|
||||
}
|
||||
|
||||
/// The canonical id of a book (after identity merges).
|
||||
pub fn canonical(&self, id: &str) -> String {
|
||||
let mut cur = id.to_owned();
|
||||
for _ in 0..64 {
|
||||
match self.aliases.get(&cur) {
|
||||
Some(n) => cur = n.clone(),
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
cur
|
||||
}
|
||||
|
||||
/// The event id that last set a field (the `base` for the next edit).
|
||||
pub fn version(&self, book: &str, field: Field) -> Option<&str> {
|
||||
self.versions.get(&(self.canonical(book), field.key())).map(String::as_str)
|
||||
}
|
||||
|
||||
pub fn highlight_version(&self, id: &str) -> Option<&str> {
|
||||
self.versions.get(&(format!("hl:{id}"), "note")).map(String::as_str)
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
if let Some(i) = isbn13
|
||||
&& let Some(b) = self.books.values().find(|b| b.info.isbn13.as_deref() == Some(i))
|
||||
{
|
||||
return Some(b);
|
||||
}
|
||||
if let Some(f) = fingerprint {
|
||||
return self.books.values().find(|b| b.info.fingerprint.as_deref() == Some(f));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn book_mut(&mut self, id: &str) -> Option<&mut Book> {
|
||||
let c = self.canonical(id);
|
||||
self.books.get_mut(&c)
|
||||
}
|
||||
|
||||
fn set_text(
|
||||
versions: &mut BTreeMap<(String, &'static str), String>,
|
||||
key: (String, &'static str),
|
||||
t: &mut Text,
|
||||
value: String,
|
||||
base: &Option<String>,
|
||||
event: &str,
|
||||
) {
|
||||
let current = versions.get(&key);
|
||||
let concurrent = current.is_some() && base.as_deref() != current.map(String::as_str) && t.value != value;
|
||||
if concurrent {
|
||||
t.conflict = Some(std::mem::replace(&mut t.value, clip(value)));
|
||||
} else {
|
||||
t.value = clip(value);
|
||||
t.conflict = None;
|
||||
}
|
||||
versions.insert(key, event.to_owned());
|
||||
}
|
||||
|
||||
pub fn apply(&mut self, e: &Event) {
|
||||
match &e.op {
|
||||
Op::BookAdd { book, info, restore } => {
|
||||
if self.removed_books.contains(book) || self.books.contains_key(book) || self.aliases.contains_key(book)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let isbn = info.isbn13.as_deref().and_then(crate::isbn13);
|
||||
let mut info = info.clone();
|
||||
info.isbn13 = isbn;
|
||||
info.title = clip(info.title);
|
||||
info.description = info.description.map(clip);
|
||||
let same = if *restore {
|
||||
None
|
||||
} else {
|
||||
self.find_identity(info.isbn13.as_deref(), info.fingerprint.as_deref()).map(|b| b.id.clone())
|
||||
};
|
||||
match same {
|
||||
Some(existing) => {
|
||||
self.aliases.insert(book.clone(), existing.clone());
|
||||
if let Some(b) = self.books.get_mut(&existing) {
|
||||
let i = &mut b.info;
|
||||
if i.isbn13.is_none() {
|
||||
i.isbn13 = info.isbn13;
|
||||
}
|
||||
if i.fingerprint.is_none() {
|
||||
i.fingerprint = info.fingerprint;
|
||||
}
|
||||
if i.pages.is_none() {
|
||||
i.pages = info.pages;
|
||||
}
|
||||
if i.series.is_none() {
|
||||
i.series = info.series;
|
||||
}
|
||||
for (k, v) in info.import_extra {
|
||||
i.import_extra.entry(k).or_insert(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
self.books.insert(book.clone(), Book::new(book, info));
|
||||
}
|
||||
}
|
||||
}
|
||||
Op::BookRemove { book } => {
|
||||
let c = self.canonical(book);
|
||||
self.books.remove(&c);
|
||||
self.removed_books.insert(c.clone());
|
||||
self.highlights.retain(|_, h| h.book != c);
|
||||
}
|
||||
Op::BookSet { book, field, value, base } => {
|
||||
let c = self.canonical(book);
|
||||
let key = (c.clone(), field.key());
|
||||
let Some(b) = self.books.get_mut(&c) else { return };
|
||||
let s = |v: &serde_json::Value| v.as_str().map(|s| clip(s.to_owned()));
|
||||
let set_of = |v: &serde_json::Value| -> Option<BTreeSet<String>> {
|
||||
serde_json::from_value::<BTreeSet<String>>(v.clone())
|
||||
.ok()
|
||||
.map(|s| s.into_iter().take(256).map(clip).collect())
|
||||
};
|
||||
let ok = match field {
|
||||
Field::Review | Field::Notes => {
|
||||
let Some(v) = s(value) else { return };
|
||||
let t = if *field == Field::Review { &mut b.review } else { &mut b.notes };
|
||||
Self::set_text(&mut self.versions, key, t, v, base, &e.id);
|
||||
return;
|
||||
}
|
||||
Field::Title => s(value).filter(|t| !t.is_empty()).map(|t| b.info.title = t).is_some(),
|
||||
Field::Authors => {
|
||||
serde_json::from_value::<Vec<String>>(value.clone()).map(|a| b.info.authors = a).is_ok()
|
||||
}
|
||||
Field::Series => {
|
||||
serde_json::from_value::<Option<Series>>(value.clone()).map(|v| b.info.series = v).is_ok()
|
||||
}
|
||||
Field::Language => serde_json::from_value(value.clone()).map(|v| b.info.language = v).is_ok(),
|
||||
Field::Publisher => serde_json::from_value(value.clone()).map(|v| b.info.publisher = v).is_ok(),
|
||||
Field::Published => serde_json::from_value(value.clone()).map(|v| b.info.published = v).is_ok(),
|
||||
Field::Description => serde_json::from_value::<Option<String>>(value.clone())
|
||||
.map(|v| b.info.description = v.map(clip))
|
||||
.is_ok(),
|
||||
Field::Pages => serde_json::from_value(value.clone()).map(|v| b.info.pages = v).is_ok(),
|
||||
Field::Isbn13 => serde_json::from_value::<Option<String>>(value.clone())
|
||||
.map(|v| b.info.isbn13 = v.as_deref().and_then(crate::isbn13))
|
||||
.is_ok(),
|
||||
Field::Genres => serde_json::from_value(value.clone()).map(|v| b.info.genres = v).is_ok(),
|
||||
Field::Paper => value.as_bool().map(|v| b.paper = v).is_some(),
|
||||
Field::Possession => serde_json::from_value(value.clone()).map(|v| b.possession = v).is_ok(),
|
||||
Field::Rating => serde_json::from_value::<Option<u8>>(value.clone())
|
||||
.ok()
|
||||
.map(|v| b.rating = v.filter(|r| (1..=10).contains(r)))
|
||||
.is_some(),
|
||||
Field::Moods => set_of(value).map(|v| b.moods = v).is_some(),
|
||||
Field::Tags => set_of(value).map(|v| b.tags = v).is_some(),
|
||||
Field::ToRead => value.as_bool().map(|v| b.to_read = v).is_some(),
|
||||
Field::Cover => serde_json::from_value(value.clone()).map(|v| b.cover = v).is_ok(),
|
||||
};
|
||||
if ok {
|
||||
self.versions.insert(key, e.id.clone());
|
||||
}
|
||||
}
|
||||
Op::BookFileAdd { book, file } => {
|
||||
if let Some(b) = self.book_mut(book)
|
||||
&& !b.files.iter().any(|f| f.sha256 == file.sha256)
|
||||
{
|
||||
b.files.push(file.clone());
|
||||
}
|
||||
}
|
||||
Op::BookFileRemove { book, sha256 } => {
|
||||
if let Some(b) = self.book_mut(book) {
|
||||
b.files.retain(|f| f.sha256 != *sha256);
|
||||
}
|
||||
}
|
||||
Op::ShelfAdd { book, shelf } => {
|
||||
if let Some(b) = self.book_mut(book)
|
||||
&& !shelf.trim().is_empty()
|
||||
&& b.shelves.len() < 256
|
||||
{
|
||||
b.shelves.insert(clip(shelf.trim().to_owned()));
|
||||
}
|
||||
}
|
||||
Op::ShelfRemove { book, shelf } => {
|
||||
if let Some(b) = self.book_mut(book) {
|
||||
b.shelves.remove(shelf.trim());
|
||||
}
|
||||
}
|
||||
Op::ReadStart { book, read, date } => {
|
||||
let c = self.canonical(book);
|
||||
if self.read_book.contains_key(read) {
|
||||
return;
|
||||
}
|
||||
if let Some(b) = self.books.get_mut(&c) {
|
||||
b.reads.push(Read { id: read.clone(), started: date.clone(), finished: None, outcome: None });
|
||||
b.to_read = false;
|
||||
self.read_book.insert(read.clone(), c);
|
||||
}
|
||||
}
|
||||
Op::ReadEnd { read, date, outcome } => {
|
||||
if let Some(c) = self.read_book.get(read).cloned()
|
||||
&& let Some(b) = self.books.get_mut(&c)
|
||||
&& let Some(r) = b.reads.iter_mut().find(|r| r.id == *read)
|
||||
{
|
||||
r.finished = date.clone();
|
||||
r.outcome = Some(*outcome);
|
||||
}
|
||||
}
|
||||
Op::ReadRemove { read } => {
|
||||
if let Some(c) = self.read_book.get(read).cloned()
|
||||
&& let Some(b) = self.books.get_mut(&c)
|
||||
{
|
||||
b.reads.retain(|r| r.id != *read);
|
||||
}
|
||||
}
|
||||
Op::Lend { loan, book, person, since, due } => {
|
||||
let c = self.canonical(book);
|
||||
if self.loan_book.contains_key(loan) {
|
||||
return;
|
||||
}
|
||||
if let Some(b) = self.books.get_mut(&c) {
|
||||
b.loans.push(Loan {
|
||||
id: loan.clone(),
|
||||
person: person.clone(),
|
||||
since: since.clone(),
|
||||
due: due.clone(),
|
||||
returned: None,
|
||||
});
|
||||
self.loan_book.insert(loan.clone(), c);
|
||||
}
|
||||
}
|
||||
Op::Return { loan, date } => {
|
||||
if let Some(c) = self.loan_book.get(loan).cloned()
|
||||
&& let Some(b) = self.books.get_mut(&c)
|
||||
&& let Some(l) = b.loans.iter_mut().find(|l| l.id == *loan)
|
||||
&& l.returned.is_none()
|
||||
{
|
||||
l.returned = Some(date.clone());
|
||||
}
|
||||
}
|
||||
Op::Position { book, cfi, chapter, progress, label } => {
|
||||
if !progress.is_finite() {
|
||||
return;
|
||||
}
|
||||
let p = Position {
|
||||
cfi: cfi.clone(),
|
||||
chapter: *chapter,
|
||||
progress: progress.clamp(0.0, 1.0),
|
||||
label: label.clone(),
|
||||
};
|
||||
if let Some(b) = self.book_mut(book) {
|
||||
if b.position.as_ref().is_none_or(|f| p.progress >= f.progress) {
|
||||
b.position = Some(p.clone());
|
||||
}
|
||||
b.last_position = Some(p);
|
||||
}
|
||||
}
|
||||
Op::HighlightAdd { id, book, kind, anchor, colour, note, created } => {
|
||||
if self.removed_highlights.contains(id) || self.highlights.contains_key(id) {
|
||||
return;
|
||||
}
|
||||
let c = self.canonical(book);
|
||||
if !self.books.contains_key(&c) {
|
||||
return;
|
||||
}
|
||||
self.highlights.insert(
|
||||
id.clone(),
|
||||
Highlight {
|
||||
id: id.clone(),
|
||||
book: c,
|
||||
kind: *kind,
|
||||
anchor: anchor.clone(),
|
||||
colour: *colour,
|
||||
note: Text { value: clip(note.clone()), conflict: None },
|
||||
created: *created,
|
||||
},
|
||||
);
|
||||
self.versions.insert((format!("hl:{id}"), "note"), e.id.clone());
|
||||
}
|
||||
Op::HighlightSet { id, colour, note, base } => {
|
||||
let Some(h) = self.highlights.get_mut(id) else { return };
|
||||
if let Some(c) = colour {
|
||||
h.colour = *c;
|
||||
}
|
||||
if let Some(n) = note {
|
||||
Self::set_text(
|
||||
&mut self.versions,
|
||||
(format!("hl:{id}"), "note"),
|
||||
&mut h.note,
|
||||
n.clone(),
|
||||
base,
|
||||
&e.id,
|
||||
);
|
||||
}
|
||||
}
|
||||
Op::HighlightRemove { id } => {
|
||||
self.highlights.remove(id);
|
||||
self.removed_highlights.insert(id.clone());
|
||||
}
|
||||
Op::Session { id, book, start, end, active_ms, pages, date } => {
|
||||
let c = self.canonical(book);
|
||||
if self.books.contains_key(&c) && end >= start {
|
||||
self.sessions.entry(id.clone()).or_insert(Session {
|
||||
id: id.clone(),
|
||||
book: c,
|
||||
start: *start,
|
||||
end: *end,
|
||||
active_ms: (*active_ms).min(end - start),
|
||||
pages: *pages,
|
||||
date: date.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Op::Goal { year, kind, target } => {
|
||||
self.goals.insert(*year, Goal { year: *year, kind: *kind, target: *target });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
//! Reading stats per year and all time (no comparison with anyone).
|
||||
|
||||
use crate::library::{Goal, GoalKind, Library, Outcome};
|
||||
use crate::year_of;
|
||||
use serde::Serialize;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
|
||||
pub struct Stats {
|
||||
/// `None`: all time.
|
||||
pub year: Option<i32>,
|
||||
pub books: u32,
|
||||
pub did_not_finish: u32,
|
||||
/// Pages of the books finished (from their page counts).
|
||||
pub pages: u64,
|
||||
pub active_minutes: u64,
|
||||
/// Pages turned in sessions per active hour.
|
||||
pub pace: Option<f64>,
|
||||
pub moods: BTreeMap<String, u32>,
|
||||
pub genres: BTreeMap<String, u32>,
|
||||
/// (book id, pages)
|
||||
pub longest: Option<(String, u32)>,
|
||||
pub shortest: Option<(String, u32)>,
|
||||
pub goal: Option<GoalProgress>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
pub struct GoalProgress {
|
||||
pub kind: GoalKind,
|
||||
pub target: u32,
|
||||
pub done: u64,
|
||||
}
|
||||
|
||||
/// Stats for one year (`Some(y)`, by finish date and session day) or all time (`None`).
|
||||
pub fn stats(lib: &Library, year: Option<i32>) -> Stats {
|
||||
let mut s = Stats { year, ..Stats::default() };
|
||||
let in_year = |date: Option<&str>| match year {
|
||||
None => true,
|
||||
Some(y) => date.and_then(year_of) == Some(y),
|
||||
};
|
||||
for b in lib.books.values() {
|
||||
for r in &b.reads {
|
||||
let Some(outcome) = r.outcome else { continue };
|
||||
if !in_year(r.finished.as_deref()) {
|
||||
continue;
|
||||
}
|
||||
match outcome {
|
||||
Outcome::DidNotFinish => s.did_not_finish += 1,
|
||||
Outcome::Read => {
|
||||
s.books += 1;
|
||||
if let Some(p) = b.info.pages {
|
||||
s.pages += p as u64;
|
||||
if s.longest.as_ref().is_none_or(|(_, l)| p > *l) {
|
||||
s.longest = Some((b.id.clone(), p));
|
||||
}
|
||||
if s.shortest.as_ref().is_none_or(|(_, l)| p < *l) {
|
||||
s.shortest = Some((b.id.clone(), p));
|
||||
}
|
||||
}
|
||||
for m in &b.moods {
|
||||
*s.moods.entry(m.clone()).or_default() += 1;
|
||||
}
|
||||
for g in &b.info.genres {
|
||||
*s.genres.entry(g.clone()).or_default() += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut active_ms = 0u64;
|
||||
let mut pages_turned = 0u64;
|
||||
for x in lib.sessions.values() {
|
||||
if in_year(Some(&x.date)) {
|
||||
active_ms += x.active_ms;
|
||||
pages_turned += x.pages as u64;
|
||||
}
|
||||
}
|
||||
s.active_minutes = active_ms / 60_000;
|
||||
if active_ms >= 60_000 {
|
||||
s.pace = Some(pages_turned as f64 / (active_ms as f64 / 3_600_000.0));
|
||||
}
|
||||
if let Some(y) = year
|
||||
&& let Some(Goal { kind, target, .. }) = lib.goals.get(&y)
|
||||
{
|
||||
let done = match kind {
|
||||
GoalKind::Books => s.books as u64,
|
||||
GoalKind::Pages => s.pages,
|
||||
};
|
||||
s.goal = Some(GoalProgress { kind: *kind, target: *target, done });
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Active reading time for one page view (docs/01_books.md): the time on the page, at most two minutes.
|
||||
pub const IDLE_CAP_MS: u64 = 2 * 60 * 1000;
|
||||
|
||||
pub fn active_ms(on_page_ms: u64) -> u64 {
|
||||
on_page_ms.min(IDLE_CAP_MS)
|
||||
}
|
||||
Reference in New Issue
Block a user