radio-cli 0.12.0

A lightweight terminal radio and podcast player
Documentation
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
use super::*;
use crate::store::Store;
use anyhow::Result;
use rusqlite::{OptionalExtension, TransactionBehavior, params};

pub(crate) fn register_functions(conn: &rusqlite::Connection) -> Result<()> {
    conn.create_scalar_function(
        "podcast_lower",
        1,
        rusqlite::functions::FunctionFlags::SQLITE_UTF8
            | rusqlite::functions::FunctionFlags::SQLITE_DETERMINISTIC,
        |context| Ok(context.get::<String>(0)?.to_lowercase()),
    )?;
    Ok(())
}

pub(crate) fn migrate(conn: &rusqlite::Connection) -> Result<()> {
    conn.execute_batch("CREATE TABLE IF NOT EXISTS podcast_feeds(id TEXT PRIMARY KEY,url TEXT NOT NULL UNIQUE,subscribed INTEGER NOT NULL,json TEXT NOT NULL);
    CREATE TABLE IF NOT EXISTS podcast_aliases(url TEXT PRIMARY KEY,feed_id TEXT NOT NULL REFERENCES podcast_feeds(id));
    CREATE TABLE IF NOT EXISTS podcast_episodes(id TEXT PRIMARY KEY,feed_id TEXT NOT NULL REFERENCES podcast_feeds(id),identity TEXT NOT NULL,json TEXT NOT NULL,UNIQUE(feed_id,identity));
    CREATE TABLE IF NOT EXISTS podcast_progress(episode_id TEXT PRIMARY KEY REFERENCES podcast_episodes(id),position_ms INTEGER NOT NULL,duration_ms INTEGER,completed INTEGER NOT NULL,updated_at TEXT NOT NULL);
    CREATE TABLE IF NOT EXISTS podcast_history(id INTEGER PRIMARY KEY,episode_id TEXT NOT NULL REFERENCES podcast_episodes(id),played_at TEXT NOT NULL);
    CREATE TABLE IF NOT EXISTS podcast_downloads(episode_id TEXT PRIMARY KEY REFERENCES podcast_episodes(id),json TEXT NOT NULL);
    CREATE TABLE IF NOT EXISTS podcast_queue(episode_id TEXT PRIMARY KEY REFERENCES podcast_episodes(id),position INTEGER NOT NULL);
    CREATE INDEX IF NOT EXISTS podcast_feed_episodes ON podcast_episodes(feed_id);")?;
    Ok(())
}
impl Store {
    pub fn podcast_feeds(&self) -> Result<Vec<Feed>> {
        let mut stmt = self.conn.prepare("SELECT json FROM podcast_feeds WHERE subscribed=1 ORDER BY json_extract(json,'$.title'),id")?;
        let rows = stmt.query_map([], |r| r.get::<_, String>(0))?;
        rows.map(|r| Ok(serde_json::from_str(&r?)?)).collect()
    }
    pub fn podcast_feed(&self, id: &str) -> Result<Feed> {
        let json: Option<String> = self
            .conn
            .query_row("SELECT json FROM podcast_feeds WHERE id=?1", [id], |r| {
                r.get(0)
            })
            .optional()?;
        Ok(serde_json::from_str(
            &json.ok_or_else(|| error(crate::t!("podcast_not_found")))?,
        )?)
    }
    pub fn podcast_by_url(&self, url: &str) -> Result<Option<Feed>> {
        let id: Option<String> = self.conn.query_row("SELECT id FROM podcast_feeds WHERE url=?1 UNION SELECT feed_id FROM podcast_aliases WHERE url=?1 LIMIT 1",[url],|r|r.get(0)).optional()?;
        id.map(|id| self.podcast_feed(&id)).transpose()
    }
    pub fn podcast_subscribe(&self, preview: &Preview, requested: &str) -> Result<Feed> {
        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
        let mut feed = self
            .podcast_by_url(requested)?
            .or(self.podcast_by_url(&preview.feed.url)?)
            .unwrap_or_else(|| Feed {
                id: uuid::Uuid::new_v4().to_string(),
                ..Default::default()
            });
        let id = feed.id.clone();
        let revision = feed.revision.saturating_add(1);
        feed = preview.feed.clone();
        feed.revision = revision;
        feed.id = id;
        feed.subscribed = true;
        self.podcast_write(&feed)?;
        for url in [requested, &feed.url] {
            self.conn.execute(
                "INSERT INTO podcast_aliases VALUES (?1,?2) ON CONFLICT(url) DO NOTHING",
                params![url, feed.id],
            )?;
        }
        self.podcast_merge(&feed.id, &preview.episodes)?;
        tx.commit()?;
        Ok(feed)
    }
    pub(crate) fn podcast_write(&self, feed: &Feed) -> Result<()> {
        self.conn.execute("INSERT INTO podcast_feeds VALUES (?1,?2,?3,?4) ON CONFLICT(id) DO UPDATE SET url=excluded.url,subscribed=excluded.subscribed,json=excluded.json",params![feed.id,feed.url,feed.subscribed,serde_json::to_string(feed)?])?;
        Ok(())
    }
    pub(crate) fn podcast_refresh_error(&self, f: &Feed) -> Result<()> {
        self.conn.execute("UPDATE podcast_feeds SET json=?2 WHERE id=?1 AND subscribed=1 AND json_extract(json,'$.revision')=?3",params![f.id,serde_json::to_string(f)?,f.revision])?;
        Ok(())
    }
    pub fn podcast_refresh_merge(&self, old: &Feed, preview: Option<Preview>) -> Result<()> {
        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
        let current = self.podcast_feed(&old.id)?;
        if !current.subscribed || current.revision != old.revision {
            return Ok(());
        }
        let mut feed = preview.as_ref().map(|p| p.feed.clone()).unwrap_or(current);
        feed.id = old.id.clone();
        feed.subscribed = true;
        feed.error = None;
        feed.failures = 0;
        feed.revision = old.revision.saturating_add(1);
        feed.refreshed_at = Some(chrono::Utc::now().to_rfc3339());
        self.podcast_write(&feed)?;
        self.conn.execute(
            "INSERT OR IGNORE INTO podcast_aliases VALUES (?1,?2)",
            params![feed.url, feed.id],
        )?;
        if let Some(p) = preview {
            self.podcast_merge(&feed.id, &p.episodes)?;
        }
        tx.commit()?;
        Ok(())
    }
    fn podcast_merge(&self, feed_id: &str, episodes: &[Episode]) -> Result<()> {
        for item in episodes {
            let identity = item
                .guid
                .as_ref()
                .map(|g| format!("guid:{g}"))
                .unwrap_or_else(|| format!("url:{}", item.url));
            let old: Option<String> = self
                .conn
                .query_row(
                    "SELECT json FROM podcast_episodes WHERE feed_id=?1 AND identity=?2",
                    params![feed_id, identity],
                    |r| r.get(0),
                )
                .optional()?;
            let mut e = item.clone();
            e.feed_id = feed_id.into();
            e.id = if let Some(old) = old {
                let old: Episode = serde_json::from_str(&old)?;
                if (old.bytes.is_some() && e.bytes.is_some() && old.bytes != e.bytes)
                    || (old.duration_ms.is_some()
                        && e.duration_ms.is_some()
                        && old.duration_ms != e.duration_ms)
                {
                    self.conn.execute(
                        "UPDATE podcast_progress SET completed=0 WHERE episode_id=?1",
                        [&old.id],
                    )?;
                }
                old.id
            } else {
                uuid::Uuid::new_v4().to_string()
            };
            self.conn.execute("INSERT INTO podcast_episodes VALUES (?1,?2,?3,?4) ON CONFLICT(feed_id,identity) DO UPDATE SET json=excluded.json",params![e.id,feed_id,identity,serde_json::to_string(&e)?])?;
        }
        Ok(())
    }
    pub fn podcast_unsubscribe(&self, id: &str) -> Result<()> {
        let mut f = self.podcast_feed(id)?;
        f.subscribed = false;
        f.revision = f.revision.saturating_add(1);
        self.podcast_write(&f)
    }
    pub fn podcast_episode(&self, id: &str) -> Result<Episode> {
        let json: Option<String> = self
            .conn
            .query_row("SELECT json FROM podcast_episodes WHERE id=?1", [id], |r| {
                r.get(0)
            })
            .optional()?;
        let mut e: Episode =
            serde_json::from_str(&json.ok_or_else(|| error(crate::t!("podcast_not_found")))?)?;
        let p=self.conn.query_row("SELECT position_ms,duration_ms,completed FROM podcast_progress WHERE episode_id=?1",[id],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?))).optional()?;
        if let Some((pos, dur, done)) = p {
            e.position_ms = pos;
            e.observed_duration_ms = dur;
            e.completed = done;
        }
        Ok(e)
    }
    pub fn podcast_episodes(&self, id: &str) -> Result<Vec<Episode>> {
        self.podcast_feed(id)?;
        self.podcast_episode_rows(id, "", -1, 0)
    }
    pub(crate) fn podcast_episode_position(&self, feed: &str, id: &str) -> Result<Option<usize>> {
        Ok(self
            .conn
            .query_row(
                "SELECT position FROM (
                SELECT id,row_number() OVER (
                    ORDER BY json_extract(json,'$.published') DESC,rowid DESC
                )-1 AS position FROM podcast_episodes WHERE feed_id=?1
             ) WHERE id=?2",
                params![feed, id],
                |r| r.get(0),
            )
            .optional()?)
    }
    pub fn podcast_episodes_page(
        &self,
        id: &str,
        query: &str,
        page: &crate::cli::Page,
    ) -> Result<(Vec<Episode>, usize)> {
        let query = query.to_lowercase();
        self.read_snapshot(|store| {
            store.podcast_feed(id)?;
            let total = store.conn.query_row(
                "SELECT count(*) FROM podcast_episodes WHERE feed_id=?1
                 AND (?2='' OR instr(podcast_lower(json_extract(json,'$.title')),?2)>0)",
                params![id, query],
                |r| r.get(0),
            )?;
            let items = store.podcast_episode_rows(
                id,
                &query,
                if page.all { -1 } else { i64::from(page.limit) },
                page.offset.min(i64::MAX as usize) as i64,
            )?;
            Ok((items, total))
        })
    }
    fn podcast_episode_rows(
        &self,
        id: &str,
        query: &str,
        limit: i64,
        offset: i64,
    ) -> Result<Vec<Episode>> {
        let mut stmt = self.conn.prepare(
            "SELECT e.json,p.position_ms,p.duration_ms,p.completed FROM podcast_episodes e
             LEFT JOIN podcast_progress p ON p.episode_id=e.id WHERE e.feed_id=?1
             AND (?2='' OR instr(podcast_lower(json_extract(e.json,'$.title')),?2)>0)
             ORDER BY json_extract(e.json,'$.published') DESC,e.rowid DESC LIMIT ?3 OFFSET ?4",
        )?;
        let rows = stmt.query_map(params![id, query, limit, offset], |r| {
            Ok((
                r.get::<_, String>(0)?,
                r.get::<_, Option<u64>>(1)?,
                r.get::<_, Option<u64>>(2)?,
                r.get::<_, Option<bool>>(3)?,
            ))
        })?;
        rows.map(|row| {
            let (json, position, duration, completed) = row?;
            let mut episode: Episode = serde_json::from_str(&json)?;
            if let Some(position) = position {
                episode.position_ms = position;
                episode.observed_duration_ms = duration;
                episode.completed = completed.unwrap_or(false);
            }
            Ok(episode)
        })
        .collect()
    }
    /// Save progress only while the supplied media snapshot is still current.
    pub fn podcast_progress(
        &self,
        episode: &Episode,
        pos: u64,
        duration: Option<u64>,
        completed: bool,
    ) -> Result<()> {
        self.podcast_save_progress(
            &episode.id,
            &EpisodeProgress {
                media: episode.media(),
                position_ms: pos,
                observed_duration_ms: duration,
                completed,
            },
        )
    }
    pub(crate) fn podcast_save_progress(&self, id: &str, progress: &EpisodeProgress) -> Result<()> {
        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
        Self::write_podcast_progress(&tx, id, progress)?;
        tx.commit()?;
        Ok(())
    }
    pub(crate) fn write_podcast_progress(
        tx: &rusqlite::Transaction<'_>,
        id: &str,
        progress: &EpisodeProgress,
    ) -> Result<()> {
        let json: Option<String> = tx
            .query_row("SELECT json FROM podcast_episodes WHERE id=?1", [id], |r| {
                r.get(0)
            })
            .optional()?;
        let Some(json) = json else { return Ok(()) };
        let episode: Episode = serde_json::from_str(&json)?;
        // The write transaction also excludes refreshes between this check and
        // the UPSERT. An old media snapshot must not undo a refresh's reset.
        if episode.media() != progress.media {
            return Ok(());
        }
        tx.execute("INSERT INTO podcast_progress VALUES (?1,?2,?3,?4,?5) ON CONFLICT(episode_id) DO UPDATE SET position_ms=excluded.position_ms,duration_ms=COALESCE(excluded.duration_ms,duration_ms),completed=excluded.completed,updated_at=excluded.updated_at",params![id,progress.position_ms.min(i64::MAX as u64),progress.observed_duration_ms.map(|d|d.min(i64::MAX as u64)),progress.completed,chrono::Utc::now().to_rfc3339()])?;
        Ok(())
    }
    pub fn podcast_played(&self, id: &str) -> Result<()> {
        self.conn.execute(
            "INSERT INTO podcast_history(episode_id,played_at) VALUES (?1,?2)",
            params![id, chrono::Utc::now().to_rfc3339()],
        )?;
        self.set_meta("pref_last_episode", id)?;
        self.set_meta("pref_last_media", "episode")
    }
    pub fn podcast_download(&self, id: &str) -> Result<Option<Download>> {
        let json: Option<String> = self
            .conn
            .query_row(
                "SELECT json FROM podcast_downloads WHERE episode_id=?1",
                [id],
                |r| r.get(0),
            )
            .optional()?;
        json.map(|j| Ok(serde_json::from_str(&j)?)).transpose()
    }
    pub(crate) fn podcast_claim_download(&self, expected: &Download) -> Result<Option<Download>> {
        let json: Option<String> = self
            .conn
            .query_row(
                "UPDATE podcast_downloads
                 SET json=json_set(json,'$.state','downloading','$.error',NULL,'$.generation',?4)
                 WHERE episode_id=?1 AND json_extract(json,'$.state')=?2
                 AND json_extract(json,'$.state') IN ('queued','downloading')
                 AND COALESCE(json_extract(json,'$.generation'),0)=?3
                 RETURNING json",
                params![
                    expected.episode_id,
                    expected.state,
                    expected.generation,
                    expected.generation.saturating_add(1)
                ],
                |r| r.get(0),
            )
            .optional()?;
        json.map(|j| Ok(serde_json::from_str(&j)?)).transpose()
    }
    pub(crate) fn podcast_download_transaction<T>(
        &self,
        id: &str,
        update: impl FnOnce(Option<Download>) -> Result<T>,
    ) -> Result<T> {
        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
        let value = update(self.podcast_download(id)?)?;
        tx.commit()?;
        Ok(value)
    }
    pub(crate) fn podcast_download_update(&self, d: &Download) -> Result<()> {
        let changed=self.conn.execute("UPDATE podcast_downloads SET json=?2 WHERE episode_id=?1 AND COALESCE(json_extract(json,'$.generation'),0)=?3",params![d.episode_id,serde_json::to_string(d)?,d.generation])?;
        if changed == 0 {
            return Err(DomainError::new(ErrorCode::Cancelled).into());
        }
        Ok(())
    }
    pub fn podcast_save_download(&self, d: &Download) -> Result<()> {
        self.conn.execute("INSERT INTO podcast_downloads VALUES (?1,?2) ON CONFLICT(episode_id) DO UPDATE SET json=excluded.json",params![d.episode_id,serde_json::to_string(d)?])?;
        Ok(())
    }
    pub fn podcast_downloads(&self) -> Result<Vec<Download>> {
        let mut stmt = self
            .conn
            .prepare("SELECT json FROM podcast_downloads ORDER BY episode_id")?;
        stmt.query_map([], |r| r.get::<_, String>(0))?
            .map(|j| Ok(serde_json::from_str(&j?)?))
            .collect()
    }
    pub fn podcast_queue(&self) -> Result<Vec<Episode>> {
        let mut stmt = self
            .conn
            .prepare("SELECT episode_id FROM podcast_queue ORDER BY position,rowid")?;
        stmt.query_map([], |r| r.get::<_, String>(0))?
            .map(|id| self.podcast_episode(&id?))
            .collect()
    }
    pub fn podcast_queue_set(&self, ids: &[String]) -> Result<()> {
        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
        self.podcast_queue_write(ids)?;
        tx.commit()?;
        Ok(())
    }
    pub fn podcast_queue_update(&self, action: QueueAction) -> Result<Vec<Episode>> {
        self.podcast_queue_update_revision(action)
            .map(|(items, _)| items)
    }
    pub(crate) fn podcast_queue_revision(&self) -> Result<u64> {
        Ok(self
            .meta("podcast_queue_revision")?
            .and_then(|v| v.parse().ok())
            .unwrap_or(0))
    }
    pub(crate) fn podcast_queue_snapshot(&self) -> Result<(Vec<Episode>, u64)> {
        self.read_snapshot(|store| Ok((store.podcast_queue()?, store.podcast_queue_revision()?)))
    }
    pub(crate) fn podcast_queue_update_revision(
        &self,
        action: QueueAction,
    ) -> Result<(Vec<Episode>, u64)> {
        if matches!(action, QueueAction::List) {
            return self.podcast_queue_snapshot();
        }
        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
        let mut ids = self
            .conn
            .prepare("SELECT episode_id FROM podcast_queue ORDER BY position,rowid")?
            .query_map([], |r| r.get::<_, String>(0))?
            .collect::<rusqlite::Result<Vec<_>>>()?;
        match action {
            QueueAction::Add { id } => {
                self.podcast_episode(&id)?;
                if !ids.contains(&id) {
                    ids.push(id);
                }
            }
            QueueAction::Remove { id } => ids.retain(|v| v != &id),
            QueueAction::Clear => ids.clear(),
            QueueAction::Move { id, position } => {
                if position == 0 || position > ids.len() || !ids.contains(&id) {
                    return Err(error(crate::t!("podcast_invalid_time")));
                }
                ids.retain(|v| v != &id);
                ids.insert(position - 1, id);
            }
            QueueAction::Play { .. } => return Err(error(crate::t!("podcast_playback_only"))),
            QueueAction::List => unreachable!(),
        }
        self.podcast_queue_write(&ids)?;
        let items = self.podcast_queue()?;
        let revision = self.podcast_queue_revision()?;
        tx.commit()?;
        Ok((items, revision))
    }
    fn podcast_queue_write(&self, ids: &[String]) -> Result<()> {
        self.conn.execute("DELETE FROM podcast_queue", [])?;
        for (i, id) in ids.iter().enumerate() {
            self.conn.execute(
                "INSERT OR IGNORE INTO podcast_queue VALUES (?1,?2)",
                params![id, i],
            )?;
        }
        self.conn.execute(
            "INSERT INTO meta(key,value) VALUES ('podcast_queue_revision','1')
            ON CONFLICT(key) DO UPDATE SET value=CAST(value AS INTEGER)+1",
            [],
        )?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Arc, Barrier, atomic::AtomicBool};

    fn queue_fixture() -> (tempfile::TempDir, crate::config::Config, Vec<Episode>) {
        let dir = tempfile::tempdir().unwrap();
        let config = crate::test_support::config(dir.path());
        let store = Store::open(&config.data_dir.join("radio.db")).unwrap();
        let preview = Preview {
            feed: Feed {
                url: "https://example.test/rss".into(),
                ..Default::default()
            },
            episodes: (0..2)
                .map(|i| Episode {
                    guid: Some(i.to_string()),
                    url: format!("https://example.test/{i}.mp3"),
                    ..Default::default()
                })
                .collect(),
        };
        let feed = store
            .podcast_subscribe(&preview, &preview.feed.url)
            .unwrap();
        let episodes = store.podcast_episodes(&feed.id).unwrap();
        (dir, config, episodes)
    }

    #[test]
    fn cli_marks_cannot_overwrite_progress_after_a_concurrent_media_refresh() {
        use rusqlite::hooks::{AuthAction, AuthContext, Authorization, TransactionOperation};
        use std::{sync::mpsc, time::Duration};

        for state in ["played", "unplayed"] {
            for changed in ["duration", "bytes", "url", "title", "unchanged"] {
                let dir = tempfile::tempdir().unwrap();
                let config = crate::test_support::config(dir.path());
                let store = Store::open(&config.data_dir.join("radio.db")).unwrap();
                let mut preview = Preview {
                    feed: Feed {
                        url: "https://example.test/rss".into(),
                        ..Default::default()
                    },
                    episodes: vec![Episode {
                        guid: Some("episode".into()),
                        url: "https://example.test/audio".into(),
                        duration_ms: Some(20000),
                        bytes: Some(100),
                        ..Default::default()
                    }],
                };
                let feed = store
                    .podcast_subscribe(&preview, &preview.feed.url)
                    .unwrap();
                let episode = store.podcast_episodes(&feed.id).unwrap().remove(0);
                store
                    .podcast_progress(&episode, 15000, Some(20000), true)
                    .unwrap();

                let (ready, wait) = mpsc::channel();
                let (release, go) = mpsc::channel();
                let id = episode.id.clone();
                let worker = std::thread::spawn(move || {
                    let store = Store::open(&config.data_dir.join("radio.db")).unwrap();
                    let mut synchronized = false;
                    // Mark has read its media snapshot before requesting the
                    // write transaction. The INSERT hook catches the old path
                    // which bypassed that transaction and its media guard.
                    store.conn.authorizer(Some(move |context: AuthContext<'_>| {
                        if !synchronized
                            && matches!(
                                context.action,
                                AuthAction::Transaction {
                                    operation: TransactionOperation::Begin
                                } | AuthAction::Insert {
                                    table_name: "podcast_progress"
                                }
                            )
                        {
                            synchronized = true;
                            ready.send(()).unwrap();
                            go.recv_timeout(Duration::from_secs(3)).unwrap();
                        }
                        Authorization::Allow
                    }));
                    manage(
                        &config,
                        &store,
                        Action::Mark {
                            id,
                            state: state.into(),
                        },
                        &Arc::new(AtomicBool::new(false)),
                    )
                    .unwrap()
                });
                wait.recv_timeout(Duration::from_secs(3)).unwrap();
                match changed {
                    "duration" => preview.episodes[0].duration_ms = Some(40000),
                    "bytes" => preview.episodes[0].bytes = Some(200),
                    "url" => preview.episodes[0].url = "https://example.test/new-audio".into(),
                    "title" => preview.episodes[0].title = "Updated title".into(),
                    "unchanged" => {}
                    _ => unreachable!(),
                }
                store.podcast_refresh_merge(&feed, Some(preview)).unwrap();
                let mut expected = store.podcast_episode(&episode.id).unwrap();
                if matches!(changed, "title" | "unchanged") {
                    expected.completed = state == "played";
                    expected.position_ms = if expected.completed { 20000 } else { 0 };
                }
                release.send(()).unwrap();
                let result = worker.join().unwrap();
                assert_eq!(
                    store.podcast_episode(&episode.id).unwrap(),
                    expected,
                    "{state}: {changed}"
                );
                assert_eq!(result, serde_json::to_value(&expected).unwrap());
            }
        }
    }

    #[test]
    fn download_controls_read_the_generation_after_a_concurrent_claim() {
        use rusqlite::hooks::{AuthAction, AuthContext, Authorization, TransactionOperation};
        use std::sync::mpsc;
        for control in ["pause", "cancel", "enqueue"] {
            let (_dir, config, episodes) = queue_fixture();
            let store = Store::open(&config.data_dir.join("radio.db")).unwrap();
            let snapshot = Download {
                episode_id: episodes[0].id.clone(),
                state: "queued".into(),
                generation: 7,
                ..Default::default()
            };
            store.podcast_save_download(&snapshot).unwrap();
            let (ready, wait) = mpsc::channel();
            let (release, go) = mpsc::channel();
            let id = snapshot.episode_id.clone();
            let config = config.clone();
            let worker = std::thread::spawn(move || {
                let store = Store::open(&config.data_dir.join("radio.db")).unwrap();
                let mut synchronized = false;
                // Pause immediately before acquiring the write lock. Without
                // a transaction this hook runs at INSERT, after the stale read.
                store.conn.authorizer(Some(move |context: AuthContext<'_>| {
                    if !synchronized
                        && matches!(
                            context.action,
                            AuthAction::Transaction {
                                operation: TransactionOperation::Begin
                            } | AuthAction::Insert {
                                table_name: "podcast_downloads"
                            }
                        )
                    {
                        synchronized = true;
                        ready.send(()).unwrap();
                        go.recv_timeout(std::time::Duration::from_secs(3)).unwrap();
                    }
                    Authorization::Allow
                }));
                if control == "enqueue" {
                    Runtime::enqueue(&store, &id).unwrap();
                } else {
                    manage(
                        &config,
                        &store,
                        Action::Downloads {
                            action: if control == "pause" {
                                DownloadAction::Pause { id: id.clone() }
                            } else {
                                DownloadAction::Cancel { id: id.clone() }
                            },
                        },
                        &Arc::new(AtomicBool::new(false)),
                    )
                    .unwrap();
                }
            });
            wait.recv_timeout(std::time::Duration::from_secs(3))
                .unwrap();
            let mut claimed = store.podcast_claim_download(&snapshot).unwrap().unwrap();
            claimed.bytes = 123;
            store.podcast_download_update(&claimed).unwrap();
            release.send(()).unwrap();
            worker.join().unwrap();
            let current = store
                .podcast_download(&snapshot.episode_id)
                .unwrap()
                .unwrap();
            assert_eq!(current.generation, claimed.generation + 1, "{control}");
            assert_eq!(current.bytes, 123);
            assert_eq!(
                current.state,
                match control {
                    "pause" => "paused",
                    "cancel" => "cancelled",
                    _ => "queued",
                }
            );
            assert!(store.podcast_download_update(&claimed).is_err());
        }
    }

    #[test]
    fn concurrent_queue_additions_preserve_both_updates() {
        use rusqlite::hooks::{AuthAction, AuthContext, Authorization, TransactionOperation};
        let (_dir, config, episodes) = queue_fixture();
        let barrier = Arc::new(Barrier::new(2));
        let workers: Vec<_> = episodes
            .iter()
            .map(|e| {
                let config = config.clone();
                let id = e.id.clone();
                let barrier = barrier.clone();
                std::thread::spawn(move || {
                    let store = Store::open(&config.data_dir.join("radio.db")).unwrap();
                    let mut synchronized = false;
                    // Align the first write transactions. Reading before BEGIN
                    // makes both workers overwrite the same old queue snapshot.
                    store.conn.authorizer(Some(move |context: AuthContext<'_>| {
                        if !synchronized
                            && matches!(
                                context.action,
                                AuthAction::Transaction {
                                    operation: TransactionOperation::Begin
                                }
                            )
                        {
                            synchronized = true;
                            barrier.wait();
                        }
                        Authorization::Allow
                    }));
                    manage(
                        &config,
                        &store,
                        Action::Queue {
                            action: QueueAction::Add { id },
                        },
                        &Arc::new(AtomicBool::new(false)),
                    )
                    .unwrap();
                })
            })
            .collect();
        for worker in workers {
            worker.join().unwrap();
        }
        let store = Store::open(&config.data_dir.join("radio.db")).unwrap();
        let mut actual: Vec<_> = store
            .podcast_queue()
            .unwrap()
            .into_iter()
            .map(|e| e.id)
            .collect();
        let mut expected: Vec<_> = episodes.into_iter().map(|e| e.id).collect();
        actual.sort();
        expected.sort();
        assert_eq!(actual, expected);
    }

    #[test]
    fn listing_the_queue_is_read_only() {
        let (_dir, config, episodes) = queue_fixture();
        let store = Store::open(&config.data_dir.join("radio.db")).unwrap();
        store.podcast_queue_set(&[episodes[0].id.clone()]).unwrap();
        store.conn.execute_batch("PRAGMA query_only=ON").unwrap();
        let value = manage(
            &config,
            &store,
            Action::Queue {
                action: QueueAction::List,
            },
            &Arc::new(AtomicBool::new(false)),
        )
        .unwrap();
        assert_eq!(value[0]["id"], episodes[0].id);
    }

    #[test]
    fn queue_edits_preserve_order_and_rollback_invalid_moves() {
        let (_dir, config, episodes) = queue_fixture();
        let store = Store::open(&config.data_dir.join("radio.db")).unwrap();
        for episode in [&episodes[0], &episodes[1], &episodes[0]] {
            store
                .podcast_queue_update(QueueAction::Add {
                    id: episode.id.clone(),
                })
                .unwrap();
        }
        let reordered = store
            .podcast_queue_update(QueueAction::Move {
                id: episodes[0].id.clone(),
                position: 2,
            })
            .unwrap();
        assert_eq!(
            reordered.iter().map(|e| &e.id).collect::<Vec<_>>(),
            vec![&episodes[1].id, &episodes[0].id]
        );
        assert!(
            store
                .podcast_queue_update(QueueAction::Move {
                    id: episodes[0].id.clone(),
                    position: 3,
                })
                .is_err()
        );
        assert_eq!(store.podcast_queue().unwrap(), reordered);
        let remaining = store
            .podcast_queue_update(QueueAction::Remove {
                id: episodes[1].id.clone(),
            })
            .unwrap();
        assert_eq!(remaining.len(), 1);
        assert_eq!(remaining[0].id, episodes[0].id);
        assert!(
            store
                .podcast_queue_update(QueueAction::Clear)
                .unwrap()
                .is_empty()
        );
    }
}