Files
Liber-public/crates/liber-habit/src/lib.rs
T

315 lines
11 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Liber's reading habit (the app's `docs/02_habit.md`): the local day, days read, the forgiving streak, the reminder
//! schedule and the medal rules. Pure: the time, the UTC offset and the rollover hour are always parameters, and this
//! crate is the only place in Liber that turns a moment into a day.
use liber_library::Library;
use liber_library::library::{DailyKind, HabitGoal, Outcome};
use serde::Serialize;
use std::collections::{BTreeMap, BTreeSet};
const DAY_MS: i64 = 86_400_000;
/// A local day: days since 1970-01-01 in the reader's calendar.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
pub struct Day(pub i64);
impl Day {
/// Monday = 0 … Sunday = 6 (1970-01-01 was a Thursday).
pub fn weekday(self) -> u8 {
(self.0 + 3).rem_euclid(7) as u8
}
/// The Monday of this day's week.
pub fn week(self) -> Day {
Day(self.0 - self.weekday() as i64)
}
pub fn plus(self, n: i64) -> Day {
Day(self.0 + n)
}
/// `YYYY-MM-DD`.
pub fn date(self) -> String {
let z = self.0 + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + i64::from(m <= 2);
format!("{y:04}-{m:02}-{d:02}")
}
pub fn parse(date: &str) -> Option<Day> {
let d = liber_library::parse_date(date)?;
let (y, m, dd) = (d[..4].parse().ok()?, d[5..7].parse().ok()?, d[8..].parse().ok()?);
Some(Day(liber_library::days_from_civil(y, m, dd)))
}
}
/// The local day a moment belongs to: its local time (UTC + `offset_min`) minus `rollover_hour`, so reading at
/// 01:30 with a 03:00 rollover counts for the evening before. **The only day computation in Liber.**
pub fn local_day(utc_ms: i64, offset_min: i32, rollover_hour: u8) -> Day {
let local = utc_ms + offset_min as i64 * 60_000 - rollover_hour.min(23) as i64 * 3_600_000;
Day(local.div_euclid(DAY_MS))
}
/// The day a session counts for: the day it started (a session across the rollover counts once). Sessions from before
/// Day 2 carry no offset and keep their stored date.
pub fn session_day(s: &liber_library::library::Session, rollover_hour: u8) -> Option<Day> {
match s.offset_min {
Some(o) => Some(local_day(s.start as i64, o, rollover_hour)),
None => Day::parse(&s.date),
}
}
/// What the reader did on each day: pages turned and active minutes.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
pub struct DayLog {
pub pages: u32,
pub active_ms: u64,
}
pub fn goal(lib: &Library) -> HabitGoal {
lib.habit.unwrap_or_default()
}
pub fn met(g: &HabitGoal, d: &DayLog) -> bool {
match g.kind {
DailyKind::Pages => d.pages >= g.amount.max(1),
DailyKind::Minutes => d.active_ms >= g.amount.max(1) as u64 * 60_000,
}
}
/// Every day with reading, summed over its sessions.
pub fn day_logs(lib: &Library) -> BTreeMap<Day, DayLog> {
let g = goal(lib);
let mut out: BTreeMap<Day, DayLog> = BTreeMap::new();
for s in lib.sessions.values() {
if let Some(d) = session_day(s, g.rollover_hour) {
let e = out.entry(d).or_default();
e.pages = e.pages.saturating_add(s.pages);
e.active_ms = e.active_ms.saturating_add(s.active_ms);
}
}
out
}
/// The days the goal was met.
pub fn days_read(lib: &Library) -> BTreeSet<Day> {
let g = goal(lib);
day_logs(lib).into_iter().filter(|(_, l)| met(&g, l)).map(|(d, _)| d).collect()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Mark {
Read,
/// A missed day the week forgives (the first in its week).
Forgiven,
/// A second missed day in a week: the streak ended here.
Missed,
/// Today, not read yet (not a miss until it is over).
Today,
/// Before the first day read, or after today.
None,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Habit {
pub today: String,
pub today_met: bool,
pub today_log: DayLog,
pub goal: HabitGoal,
/// Days read, ever. Never goes down.
pub total_days: u32,
/// Consecutive weeks (Monday–Sunday, this one included) with at most one missed day.
pub streak_weeks: u32,
/// The last weeks, oldest first, Monday first.
pub calendar: Vec<[Mark; 7]>,
}
fn mark(days: &BTreeSet<Day>, first: Option<Day>, today: Day, d: Day, misses_before: &mut u8) -> Mark {
let Some(first) = first else { return if d == today { Mark::Today } else { Mark::None } };
if d > today || d < first {
return Mark::None;
}
if days.contains(&d) {
return Mark::Read;
}
if d == today {
return Mark::Today;
}
*misses_before += 1;
if *misses_before == 1 { Mark::Forgiven } else { Mark::Missed }
}
/// The habit as of `today` (computed with [`local_day`]), with a calendar of the last `weeks` weeks.
pub fn habit(lib: &Library, today: Day, weeks: usize) -> Habit {
let g = goal(lib);
let logs = day_logs(lib);
let days: BTreeSet<Day> = logs.iter().filter(|(_, l)| met(&g, l)).map(|(d, _)| *d).collect();
let first = days.iter().next().copied();
// Streak: back from this week while a week has at most one missed day.
let mut streak = 0u32;
if let Some(f) = first {
let mut w = today.week();
while w.plus(6) >= f {
let mut misses = 0u8;
for i in 0..7 {
let d = w.plus(i);
if d >= f && d < today && !days.contains(&d) {
misses += 1;
}
}
if misses >= 2 {
break;
}
streak += 1;
w = w.plus(-7);
}
}
let mut calendar = Vec::with_capacity(weeks);
let start = today.week().plus(-7 * (weeks.max(1) as i64 - 1));
for k in 0..weeks.max(1) {
let w = start.plus(7 * k as i64);
let mut misses = 0u8;
let mut row = [Mark::None; 7];
for (i, slot) in row.iter_mut().enumerate() {
*slot = mark(&days, first, today, w.plus(i as i64), &mut misses);
}
calendar.push(row);
}
let today_log = logs.get(&today).copied().unwrap_or_default();
Habit {
today: today.date(),
today_met: met(&g, &today_log),
today_log,
goal: g,
total_days: days.len() as u32,
streak_weeks: streak,
calendar,
}
}
/// The reminder: one local notification at `minute` (0–1439) local time, off by default.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, serde::Deserialize)]
pub struct Reminder {
pub enabled: bool,
pub minute: u16,
}
/// When the next reminder should fire, as (day, minute of the local day): today if the goal is not met and the time is
/// still ahead, else tomorrow. `None` when the reminder is off. Never today when today's goal is met.
pub fn next_reminder(r: &Reminder, today: Day, now_minute: u16, today_met: bool) -> Option<(Day, u16)> {
if !r.enabled {
return None;
}
let m = r.minute.min(1439);
if !today_met && now_minute < m { Some((today, m)) } else { Some((today.plus(1), m)) }
}
/// The medals, in this order (docs/02_habit.md). `available: false`: earned from a later Liber version on.
pub const MEDALS: &[(&str, &str, bool)] = &[
("first-book", "First book finished", true),
("days-7", "Seven days read", true),
("days-30", "Thirty days read", true),
("days-100", "A hundred days read", true),
("days-365", "A year of days read", true),
("books-10", "Ten books", true),
("books-50", "Fifty books", true),
("books-100", "A hundred books", true),
("first-reread", "A book read again", true),
("let-go", "Let a book go", true),
("five-moods", "Five moods", true),
("other-language", "A book in another language", false),
("heard-aloud", "A chapter heard aloud", false),
("buddy-read", "Read with a friend", false),
];
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Medal {
pub id: &'static str,
pub name: &'static str,
pub available: bool,
/// The day it was earned (`YYYY-MM-DD`), `"earlier"` for an imported history without dates, `None` if not yet.
pub earned: Option<String>,
pub seen: bool,
}
/// The medals: a pure function of the library. Recomputing gives the same value, so medals never drift between devices
/// or versions; only "seen" is stored.
pub fn medals(lib: &Library) -> Vec<Medal> {
let days: Vec<Day> = days_read(lib).into_iter().collect();
// Finished reads, dated ones in date order, then undated (imported) ones.
struct Fin {
date: Option<String>,
book: String,
outcome: Outcome,
}
let mut fins: Vec<Fin> = Vec::new();
for b in lib.books.values() {
for r in &b.reads {
if let Some(o) = r.outcome {
fins.push(Fin { date: r.finished.clone(), book: b.id.clone(), outcome: o });
}
}
}
fins.sort_by(|a, b| match (&a.date, &b.date) {
(Some(x), Some(y)) => x.cmp(y).then(a.book.cmp(&b.book)),
(Some(_), None) => std::cmp::Ordering::Less,
(None, Some(_)) => std::cmp::Ordering::Greater,
(None, None) => a.book.cmp(&b.book),
});
let when = |f: &Fin| Some(f.date.clone().unwrap_or_else(|| "earlier".into()));
let read: Vec<&Fin> = fins.iter().filter(|f| f.outcome == Outcome::Read).collect();
let nth_book = |n: usize| read.get(n - 1).and_then(|f| when(f));
let nth_day = |n: usize| days.get(n - 1).map(|d| d.date());
let reread = {
let mut seen = BTreeSet::new();
read.iter().find(|f| !seen.insert(f.book.clone())).and_then(|f| when(f))
};
let let_go = fins.iter().find(|f| f.outcome == Outcome::DidNotFinish).and_then(when);
let five_moods = {
let mut moods = BTreeSet::new();
let mut at = None;
for f in &read {
if let Some(b) = lib.books.get(&f.book) {
moods.extend(b.moods.iter().cloned());
}
if moods.len() >= 5 {
at = when(f);
break;
}
}
at
};
MEDALS
.iter()
.map(|&(id, name, available)| {
let earned = match id {
"first-book" => nth_book(1),
"days-7" => nth_day(7),
"days-30" => nth_day(30),
"days-100" => nth_day(100),
"days-365" => nth_day(365),
"books-10" => nth_book(10),
"books-50" => nth_book(50),
"books-100" => nth_book(100),
"first-reread" => reread.clone(),
"let-go" => let_go.clone(),
"five-moods" => five_moods.clone(),
_ => None,
};
Medal { id, name, available, earned, seen: lib.medals_seen.contains(id) }
})
.collect()
}
/// Medals earned and not shown yet: what the end of a reading session reveals (at most one at a time).
pub fn unseen(lib: &Library) -> Vec<Medal> {
medals(lib).into_iter().filter(|m| m.earned.is_some() && !m.seen).collect()
}