rosier 0.4.0

A fast picture and video viewer for large folders
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
//! The library index: which folders are sources, what files they hold, and
//! playlists that group those files. Media files themselves are never
//! written; everything lives in one SQLite file under the user's data dir.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use anyhow::{Context, Result};
use rusqlite::{Connection, params};

use crate::media::{self, Entry, Kind};

const SCHEMA: &str = "
PRAGMA journal_mode = WAL;
PRAGMA foreign_keys = ON;
CREATE TABLE IF NOT EXISTS source (
    id    INTEGER PRIMARY KEY,
    path  BLOB NOT NULL UNIQUE,
    added INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS item (
    id        INTEGER PRIMARY KEY,
    source_id INTEGER NOT NULL REFERENCES source(id) ON DELETE CASCADE,
    path      BLOB NOT NULL UNIQUE,
    kind      INTEGER NOT NULL,
    size      INTEGER NOT NULL,
    mtime     INTEGER NOT NULL,
    -- 1 when the last scan did not find the file. Kept so playlists can
    -- show it as missing instead of silently losing it.
    missing   INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS item_source ON item(source_id);
-- Folders inside a source that the user chose to hide (files untouched).
CREATE TABLE IF NOT EXISTS excluded (
    path BLOB PRIMARY KEY
);
-- What rosier knows about each video: its length (read once in the
-- background, for the tiles) and where the user stopped watching it.
CREATE TABLE IF NOT EXISTS watch (
    item_id  INTEGER PRIMARY KEY REFERENCES item(id) ON DELETE CASCADE,
    duration REAL,
    position REAL NOT NULL DEFAULT 0,
    -- When the position was saved (seconds since the epoch).
    at       INTEGER NOT NULL DEFAULT 0
);
-- Seconds watched in each stretch of a video (little-endian f32s).
CREATE TABLE IF NOT EXISTS heat (
    item_id INTEGER PRIMARY KEY REFERENCES item(id) ON DELETE CASCADE,
    bins    BLOB NOT NULL
);
-- Stars the user gave a file (1 to 5; no row is unrated).
CREATE TABLE IF NOT EXISTS rating (
    item_id INTEGER PRIMARY KEY REFERENCES item(id) ON DELETE CASCADE,
    stars   INTEGER NOT NULL CHECK (stars BETWEEN 1 AND 5)
);
-- When each picture was taken, read once from its Exif (seconds since 1970
-- on the camera's clock; 0: it has no date).
CREATE TABLE IF NOT EXISTS taken (
    item_id INTEGER PRIMARY KEY REFERENCES item(id) ON DELETE CASCADE,
    at      INTEGER NOT NULL
);
-- Book view per folder or book (crate::book::Layout as bits). A folder
-- without a row is shown one item at a time.
CREATE TABLE IF NOT EXISTS book_layout (
    path BLOB PRIMARY KEY,
    bits INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS playlist (
    id      INTEGER PRIMARY KEY,
    name    TEXT NOT NULL UNIQUE,
    created INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS playlist_item (
    playlist_id INTEGER NOT NULL REFERENCES playlist(id) ON DELETE CASCADE,
    item_id     INTEGER NOT NULL REFERENCES item(id) ON DELETE CASCADE,
    position    INTEGER NOT NULL,
    PRIMARY KEY (playlist_id, item_id)
);
";

pub fn default_path() -> PathBuf {
    let base = std::env::var_os("XDG_DATA_HOME")
        .map(PathBuf::from)
        .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local/share")))
        .unwrap_or_else(std::env::temp_dir);
    base.join("rosier").join("rosier.db")
}

pub fn open(path: &Path) -> Result<Connection> {
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
    }
    let conn = Connection::open(path).with_context(|| format!("opening {}", path.display()))?;
    conn.execute_batch(SCHEMA)?;
    Ok(conn)
}

fn now() -> i64 {
    SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs() as i64)
}

/// Paths are stored as the platform's own encoding of the OS string, so any
/// file name round-trips (not only valid UTF-8).
fn path_blob(p: &Path) -> &[u8] {
    p.as_os_str().as_encoded_bytes()
}

fn blob_path(b: Vec<u8>) -> PathBuf {
    // SAFETY: every blob was written by `path_blob` on this platform, so it
    // is a valid encoding of an OS string here. The database lives in this
    // user's data directory and is not shared between systems.
    PathBuf::from(unsafe { std::ffi::OsString::from_encoded_bytes_unchecked(b) })
}

/// A video's length and where playback stopped. `position` 0 means from
/// the start (never watched, or watched to the end).
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Watch {
    pub duration: Option<f64>,
    pub position: f64,
    pub at: i64,
}

#[derive(Debug, Clone)]
pub struct Source {
    pub id: i64,
    pub path: PathBuf,
}

pub fn sources(conn: &Connection) -> Result<Vec<Source>> {
    let mut st = conn.prepare("SELECT id, path FROM source ORDER BY id")?;
    let rows = st.query_map([], |r| Ok(Source { id: r.get(0)?, path: blob_path(r.get(1)?) }))?;
    Ok(rows.collect::<Result<_, _>>()?)
}

/// Registers `path` as a source (no-op if already registered).
/// Adds `path` as a source, unless a source already holds it (then its
/// files are already in the library).
pub fn add_source(conn: &Connection, path: &Path) -> Result<()> {
    let path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
    if sources(conn)?.iter().any(|s| path.starts_with(&s.path)) {
        return Ok(());
    }
    conn.execute("INSERT OR IGNORE INTO source (path, added) VALUES (?1, ?2)", params![path_blob(&path), now()])?;
    Ok(())
}

/// Every file that the last scans found, sorted by path.
pub fn present_items(conn: &Connection) -> Result<Vec<Entry>> {
    let mut st = conn.prepare("SELECT id, path, kind, size, mtime FROM item WHERE missing = 0")?;
    let rows = st.query_map([], |r| {
        Ok(Entry {
            id: r.get(0)?,
            path: blob_path(r.get(1)?),
            kind: match r.get::<_, i64>(2)? {
                1 => Kind::Video,
                2 => Kind::Book,
                _ => Kind::Image,
            },
            size: r.get::<_, i64>(3)? as u64,
            mtime: r.get::<_, i64>(4)? as u64,
        })
    })?;
    let mut v: Vec<Entry> = rows.collect::<Result<_, _>>()?;
    v.sort_by(|a, b| media::natural_cmp(&a.path, &b.path));
    Ok(v)
}

/// Every file that the last scans found outside the hidden folders.
pub fn visible_items(conn: &Connection) -> Result<Vec<Entry>> {
    let hidden = excluded(conn)?;
    let mut items = present_items(conn)?;
    items.retain(|e| !hidden.iter().any(|x| e.path.starts_with(x)));
    Ok(items)
}

/// What a source sync changed.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct SyncStats {
    pub added: usize,
    pub changed: usize,
    pub missing: usize,
}

impl SyncStats {
    pub fn is_empty(&self) -> bool {
        *self == SyncStats::default()
    }
}

/// Rescans one source and reconciles the index with what is on disk.
pub fn sync_source(conn: &mut Connection, src: &Source) -> Result<SyncStats> {
    let scanned = media::scan(&src.path);
    let mut known: HashMap<Vec<u8>, (i64, u64, u64, bool)> = HashMap::new();
    {
        let mut st = conn.prepare("SELECT id, path, size, mtime, missing FROM item WHERE source_id = ?1")?;
        let rows = st.query_map([src.id], |r| {
            Ok((
                r.get::<_, Vec<u8>>(1)?,
                (r.get(0)?, r.get::<_, i64>(2)? as u64, r.get::<_, i64>(3)? as u64, r.get::<_, i64>(4)? != 0),
            ))
        })?;
        for row in rows {
            let (path, v) = row?;
            known.insert(path, v);
        }
    }
    let mut stats = SyncStats::default();
    let tx = conn.transaction()?;
    {
        let mut insert = tx
            .prepare("INSERT INTO item (source_id, path, kind, size, mtime, missing) VALUES (?1, ?2, ?3, ?4, ?5, 0)")?;
        let mut update = tx.prepare("UPDATE item SET kind = ?2, size = ?3, mtime = ?4, missing = 0 WHERE id = ?1")?;
        for e in &scanned {
            let kind = match e.kind {
                Kind::Image => 0,
                Kind::Video => 1,
                Kind::Book => 2,
            };
            match known.remove(path_blob(&e.path)) {
                None => {
                    insert.execute(params![src.id, path_blob(&e.path), kind, e.size as i64, e.mtime as i64])?;
                    stats.added += 1;
                }
                Some((id, size, mtime, missing)) => {
                    if size != e.size || mtime != e.mtime || missing {
                        update.execute(params![id, kind, e.size as i64, e.mtime as i64])?;
                        stats.changed += 1;
                    }
                }
            }
        }
        // Whatever is left in `known` was not found on disk this time.
        let mut gone = tx.prepare("UPDATE item SET missing = 1 WHERE id = ?1")?;
        for (_, (id, _, _, missing)) in known {
            if !missing {
                gone.execute([id])?;
                stats.missing += 1;
            }
        }
    }
    tx.commit()?;
    Ok(stats)
}

const FAVORITES: &str = "favorites";

/// The built-in favorites playlist, created on first use.
fn favorites_id(conn: &Connection) -> Result<i64> {
    conn.execute("INSERT OR IGNORE INTO playlist (name, created) VALUES (?1, ?2)", params![FAVORITES, now()])?;
    Ok(conn.query_row("SELECT id FROM playlist WHERE name = ?1", [FAVORITES], |r| r.get(0))?)
}

/// Item ids in the favorites playlist, in the order they were added.
pub fn favorites(conn: &Connection) -> Result<Vec<i64>> {
    let id = favorites_id(conn)?;
    let mut st = conn.prepare("SELECT item_id FROM playlist_item WHERE playlist_id = ?1 ORDER BY position")?;
    let rows = st.query_map([id], |r| r.get(0))?;
    Ok(rows.collect::<Result<_, _>>()?)
}

pub fn set_favorite(conn: &Connection, item_id: i64, on: bool) -> Result<()> {
    let id = favorites_id(conn)?;
    if on {
        conn.execute(
            "INSERT OR IGNORE INTO playlist_item (playlist_id, item_id, position)
             VALUES (?1, ?2, (SELECT COALESCE(MAX(position), 0) + 1 FROM playlist_item WHERE playlist_id = ?1))",
            params![id, item_id],
        )?;
    } else {
        conn.execute("DELETE FROM playlist_item WHERE playlist_id = ?1 AND item_id = ?2", params![id, item_id])?;
    }
    Ok(())
}

/// Stars of every rated file, by item id.
pub fn ratings(conn: &Connection) -> Result<HashMap<i64, u8>> {
    let mut st = conn.prepare("SELECT item_id, stars FROM rating")?;
    let rows = st.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?;
    Ok(rows.collect::<Result<_, _>>()?)
}

/// Gives a file 1 to 5 stars; 0 takes its rating away.
pub fn set_rating(conn: &Connection, item_id: i64, stars: u8) -> Result<()> {
    if stars == 0 {
        conn.execute("DELETE FROM rating WHERE item_id = ?1", [item_id])?;
    } else {
        conn.execute(
            "INSERT INTO rating (item_id, stars) VALUES (?1, ?2)
             ON CONFLICT(item_id) DO UPDATE SET stars = excluded.stars",
            params![item_id, stars.min(5)],
        )?;
    }
    Ok(())
}

/// Book view of each folder or book that has one.
pub fn layouts(conn: &Connection) -> Result<HashMap<PathBuf, i64>> {
    let mut st = conn.prepare("SELECT path, bits FROM book_layout")?;
    let rows = st.query_map([], |r| Ok((blob_path(r.get(0)?), r.get(1)?)))?;
    Ok(rows.collect::<Result<_, _>>()?)
}

/// Remembers the book view of `path`; None forgets it.
pub fn set_layout(conn: &Connection, path: &Path, bits: Option<i64>) -> Result<()> {
    match bits {
        Some(b) => conn.execute(
            "INSERT INTO book_layout (path, bits) VALUES (?1, ?2) ON CONFLICT(path) DO UPDATE SET bits = excluded.bits",
            params![path_blob(path), b],
        )?,
        None => conn.execute("DELETE FROM book_layout WHERE path = ?1", [path_blob(path)])?,
    };
    Ok(())
}

/// When each picture was taken (0 for those without a date), by item id.
pub fn taken(conn: &Connection) -> Result<HashMap<i64, i64>> {
    let mut st = conn.prepare("SELECT item_id, at FROM taken")?;
    let rows = st.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?;
    Ok(rows.collect::<Result<_, _>>()?)
}

pub fn set_taken(conn: &Connection, item_id: i64, at: i64) -> Result<()> {
    conn.execute(
        "INSERT INTO taken (item_id, at) VALUES (?1, ?2) ON CONFLICT(item_id) DO UPDATE SET at = excluded.at",
        params![item_id, at],
    )?;
    Ok(())
}

/// Length and stopping point of every video rosier has seen.
pub fn watch(conn: &Connection) -> Result<HashMap<i64, Watch>> {
    let mut st = conn.prepare("SELECT item_id, duration, position, at FROM watch")?;
    let rows =
        st.query_map([], |r| Ok((r.get(0)?, Watch { duration: r.get(1)?, position: r.get(2)?, at: r.get(3)? })))?;
    Ok(rows.collect::<Result<_, _>>()?)
}

pub fn set_duration(conn: &Connection, item_id: i64, duration: f64) -> Result<()> {
    conn.execute(
        "INSERT INTO watch (item_id, duration) VALUES (?1, ?2)
         ON CONFLICT(item_id) DO UPDATE SET duration = excluded.duration",
        params![item_id, duration],
    )?;
    Ok(())
}

/// Saves where the user is in a video (0 once it was watched to the end).
pub fn set_position(conn: &Connection, item_id: i64, w: &Watch) -> Result<()> {
    conn.execute(
        "INSERT INTO watch (item_id, duration, position, at) VALUES (?1, ?2, ?3, ?4)
         ON CONFLICT(item_id) DO UPDATE SET
             duration = COALESCE(excluded.duration, watch.duration),
             position = excluded.position, at = excluded.at",
        params![item_id, w.duration, w.position, w.at],
    )?;
    Ok(())
}

/// Watch profiles of the videos, by item id.
pub fn heat(conn: &Connection) -> Result<HashMap<i64, Vec<f32>>> {
    let mut st = conn.prepare("SELECT item_id, bins FROM heat")?;
    let rows = st.query_map([], |r| {
        let b: Vec<u8> = r.get(1)?;
        let bins = b.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect();
        Ok((r.get(0)?, bins))
    })?;
    Ok(rows.collect::<Result<_, _>>()?)
}

pub fn set_heat(conn: &Connection, item_id: i64, bins: &[f32]) -> Result<()> {
    let b: Vec<u8> = bins.iter().flat_map(|v| v.to_le_bytes()).collect();
    conn.execute("INSERT OR REPLACE INTO heat (item_id, bins) VALUES (?1, ?2)", params![item_id, b])?;
    Ok(())
}

/// Folders the user hid from the library.
pub fn excluded(conn: &Connection) -> Result<Vec<PathBuf>> {
    let mut st = conn.prepare("SELECT path FROM excluded ORDER BY path")?;
    let rows = st.query_map([], |r| Ok(blob_path(r.get(0)?)))?;
    Ok(rows.collect::<Result<_, _>>()?)
}

pub fn set_excluded(conn: &Connection, path: &Path, hidden: bool) -> Result<()> {
    if hidden {
        conn.execute("INSERT OR IGNORE INTO excluded (path) VALUES (?1)", [path_blob(path)])?;
    } else {
        conn.execute("DELETE FROM excluded WHERE path = ?1", [path_blob(path)])?;
    }
    Ok(())
}

/// Forgets a source and its files (and their playlist entries). The folder
/// on disk is untouched.
pub fn remove_source(conn: &Connection, id: i64) -> Result<()> {
    conn.execute("DELETE FROM source WHERE id = ?1", [id])?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn tmpdb() -> (tempdir::Dir, Connection) {
        let d = tempdir::Dir::new();
        let c = open(&d.0.join("t.db")).unwrap();
        (d, c)
    }

    mod tempdir {
        pub struct Dir(pub std::path::PathBuf);
        impl Dir {
            /// A fresh directory per call. Tests run in parallel, and the
            /// clock alone is too coarse on macOS to tell two calls apart, so
            /// a counter makes each name unique within the process.
            pub fn new() -> Self {
                use std::sync::atomic::{AtomicU64, Ordering};
                static NEXT: AtomicU64 = AtomicU64::new(0);
                let p = std::env::temp_dir().join(format!(
                    "rosier-test-{}-{}",
                    std::process::id(),
                    NEXT.fetch_add(1, Ordering::Relaxed)
                ));
                let _ = std::fs::remove_dir_all(&p);
                std::fs::create_dir_all(&p).unwrap();
                Dir(p)
            }
        }
        impl Drop for Dir {
            fn drop(&mut self) {
                let _ = std::fs::remove_dir_all(&self.0);
            }
        }
    }

    #[test]
    fn sync_tracks_added_changed_and_missing_files() {
        let (d, mut c) = tmpdb();
        let media = d.0.join("media");
        std::fs::create_dir_all(&media).unwrap();
        std::fs::write(media.join("a.jpg"), b"x").unwrap();
        std::fs::write(media.join("b.mp4"), b"y").unwrap();
        add_source(&c, &media).unwrap();
        let src = sources(&c).unwrap().remove(0);
        assert_eq!(sync_source(&mut c, &src).unwrap(), SyncStats { added: 2, changed: 0, missing: 0 });
        assert!(sync_source(&mut c, &src).unwrap().is_empty());
        std::fs::remove_file(media.join("a.jpg")).unwrap();
        assert_eq!(sync_source(&mut c, &src).unwrap().missing, 1);
        assert_eq!(present_items(&c).unwrap().len(), 1);
        // Back again: the same row comes back instead of a new one.
        std::fs::write(media.join("a.jpg"), b"x").unwrap();
        let s = sync_source(&mut c, &src).unwrap();
        assert_eq!((s.added, s.changed), (0, 1));
    }

    #[test]
    fn excluded_folders_round_trip() {
        let (_d, c) = tmpdb();
        let p = std::path::Path::new("/media/x/sub");
        set_excluded(&c, p, true).unwrap();
        set_excluded(&c, p, true).unwrap();
        assert_eq!(excluded(&c).unwrap(), vec![p.to_path_buf()]);
        set_excluded(&c, p, false).unwrap();
        assert!(excluded(&c).unwrap().is_empty());
    }

    #[test]
    fn hidden_folders_drop_out_of_the_visible_items() {
        let (d, mut c) = tmpdb();
        let media = d.0.join("m");
        std::fs::create_dir_all(media.join("keep")).unwrap();
        std::fs::create_dir_all(media.join("hide/deep")).unwrap();
        for n in ["keep/1.jpg", "hide/2.jpg", "hide/deep/3.png", "top.mp4"] {
            std::fs::write(media.join(n), b"x").unwrap();
        }
        add_source(&c, &media).unwrap();
        let src = sources(&c).unwrap().remove(0);
        sync_source(&mut c, &src).unwrap();
        set_excluded(&c, &src.path.join("hide"), true).unwrap();
        let names: Vec<String> =
            visible_items(&c).unwrap().iter().map(|e| e.path.file_name().unwrap().to_string_lossy().into()).collect();
        assert_eq!(names, vec!["1.jpg", "top.mp4"]);
    }

    #[test]
    fn favorites_keep_order_and_toggle() {
        let (d, mut c) = tmpdb();
        let media = d.0.join("m");
        std::fs::create_dir_all(&media).unwrap();
        for n in ["1.jpg", "2.jpg", "3.jpg"] {
            std::fs::write(media.join(n), b"x").unwrap();
        }
        add_source(&c, &media).unwrap();
        let src = sources(&c).unwrap().remove(0);
        sync_source(&mut c, &src).unwrap();
        let ids: Vec<i64> = present_items(&c).unwrap().iter().map(|e| e.id).collect();
        set_favorite(&c, ids[2], true).unwrap();
        set_favorite(&c, ids[0], true).unwrap();
        set_favorite(&c, ids[0], true).unwrap(); // idempotent
        assert_eq!(favorites(&c).unwrap(), vec![ids[2], ids[0]]);
        set_favorite(&c, ids[2], false).unwrap();
        assert_eq!(favorites(&c).unwrap(), vec![ids[0]]);
        // Removing the source drops its playlist entries too.
        remove_source(&c, src.id).unwrap();
        assert!(favorites(&c).unwrap().is_empty());
    }

    #[test]
    fn a_folder_inside_a_source_is_not_added_again() {
        let (d, c) = tmpdb();
        let inner = d.0.join("m/trip");
        std::fs::create_dir_all(&inner).unwrap();
        add_source(&c, &d.0.join("m")).unwrap();
        add_source(&c, &inner).unwrap();
        add_source(&c, &d.0.join("m")).unwrap();
        assert_eq!(sources(&c).unwrap().len(), 1);
    }

    #[test]
    fn ratings_are_set_changed_and_taken_away() {
        let (d, mut c) = tmpdb();
        let media = d.0.join("m");
        std::fs::create_dir_all(&media).unwrap();
        for n in ["1.jpg", "2.jpg"] {
            std::fs::write(media.join(n), b"x").unwrap();
        }
        add_source(&c, &media).unwrap();
        let src = sources(&c).unwrap().remove(0);
        sync_source(&mut c, &src).unwrap();
        let ids: Vec<i64> = present_items(&c).unwrap().iter().map(|e| e.id).collect();
        set_rating(&c, ids[0], 3).unwrap();
        set_rating(&c, ids[1], 5).unwrap();
        set_rating(&c, ids[0], 4).unwrap();
        assert_eq!(ratings(&c).unwrap(), HashMap::from([(ids[0], 4), (ids[1], 5)]));
        set_rating(&c, ids[1], 0).unwrap();
        assert_eq!(ratings(&c).unwrap(), HashMap::from([(ids[0], 4)]));
        // Forgetting the folder forgets its ratings.
        remove_source(&c, src.id).unwrap();
        assert!(ratings(&c).unwrap().is_empty());
    }

    #[test]
    fn watch_keeps_length_and_position_apart() {
        let (d, mut c) = tmpdb();
        let media = d.0.join("m");
        std::fs::create_dir_all(&media).unwrap();
        for n in ["a.mp4", "b.mp4"] {
            std::fs::write(media.join(n), b"x").unwrap();
        }
        add_source(&c, &media).unwrap();
        let src = sources(&c).unwrap().remove(0);
        sync_source(&mut c, &src).unwrap();
        let ids: Vec<i64> = present_items(&c).unwrap().iter().map(|e| e.id).collect();
        set_duration(&c, ids[0], 120.0).unwrap();
        // A position saved without a length keeps the one already known.
        set_position(&c, ids[0], &Watch { duration: None, position: 30.0, at: 7 }).unwrap();
        set_position(&c, ids[1], &Watch { duration: Some(60.0), position: 12.5, at: 9 }).unwrap();
        // And a length read later keeps the position.
        set_duration(&c, ids[1], 61.0).unwrap();
        let w = watch(&c).unwrap();
        assert_eq!(w[&ids[0]], Watch { duration: Some(120.0), position: 30.0, at: 7 });
        assert_eq!(w[&ids[1]], Watch { duration: Some(61.0), position: 12.5, at: 9 });
        set_heat(&c, ids[0], &[0.0, 1.5, 3.25]).unwrap();
        assert_eq!(heat(&c).unwrap()[&ids[0]], vec![0.0, 1.5, 3.25]);
        remove_source(&c, src.id).unwrap();
        assert!(watch(&c).unwrap().is_empty(), "removing the source forgets its videos");
        assert!(heat(&c).unwrap().is_empty());
    }
}