redseat-api 0.14.0

Rust client for Redseat media servers
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
//! Downloads against the mirror's fake server.

use std::path::PathBuf;
use std::sync::{Arc, Mutex};

use super::{
    CHUNK, CopyState, Downloads, DownloadsEvent, OfflineId, OfflineSource, OfflineState, file_name,
};
use crate::Error;
use crate::app::ServerCopy;
use crate::app::catalog::Playable;
use crate::mirror::MirrorOptions;
use crate::mirror::tests::{FakeServer, TempDir, sample_library, server_api, until};
use crate::types::media::Media;

/// A file of `len` bytes that tells its bytes apart.
fn bytes(len: usize) -> Vec<u8> {
    (0..len).map(|i| (i % 251) as u8).collect()
}

struct Setup {
    dir: TempDir,
    fake: Arc<FakeServer>,
    copy: ServerCopy,
    events: Arc<Mutex<Vec<DownloadsEvent>>>,
}

impl Setup {
    /// A copy of the sample library, synced, its media `m3` (of the movie `film`)
    /// served as `file`.
    async fn new(file: Vec<u8>) -> Setup {
        let dir = TempDir::new();
        let fake = FakeServer::new(vec![sample_library("photos")]);
        fake.files.lock().unwrap().insert("m3".into(), file);
        let copy = ServerCopy::open(MirrorOptions::new(dir.0.join("mirror.db")), |_: &_| {})
            .await
            .unwrap();
        let setup = Setup {
            dir,
            fake,
            copy,
            events: Arc::default(),
        };
        setup.connect();
        until("synced", async || {
            setup.copy.media("photos", "m3").await.unwrap().is_some()
        })
        .await;
        setup
    }

    fn connect(&self) {
        let fake = Arc::clone(&self.fake);
        self.copy
            .connect(async move { Ok::<_, Error>(server_api(fake)) });
    }

    async fn downloads(&self) -> Downloads {
        let events = Arc::clone(&self.events);
        Downloads::open(self.copy.clone(), self.folder(), move |event| {
            events.lock().unwrap().push(event)
        })
        .await
        .unwrap()
    }

    fn folder(&self) -> PathBuf {
        self.dir.0.join("downloads")
    }

    async fn media(&self) -> Media {
        self.copy.media("photos", "m3").await.unwrap().unwrap().item
    }
}

fn film() -> Playable {
    Playable::Movie("film".into())
}

async fn available(downloads: &Downloads, id: &OfflineId) {
    until("available", async || {
        downloads
            .offline_file(&id.library, &id.media)
            .is_some_and(|f| f.state == OfflineState::Available)
    })
    .await;
}

#[tokio::test]
async fn keeps_a_file_offline_by_ranges_and_plays_it() {
    let file = bytes(2 * CHUNK as usize + 1000);
    let setup = Setup::new(file.clone()).await;
    let downloads = setup.downloads().await;
    let media = setup.media().await;
    downloads.keep_offline("photos", &media, &film());
    let id = OfflineId::new("photos", "m3");
    available(&downloads, &id).await;

    let kept = downloads.offline_file("photos", "m3").unwrap();
    assert_eq!(kept.total, Some(file.len() as u64));
    assert_eq!(kept.received, file.len() as u64);
    assert_eq!(kept.status(), "16 MB · Available offline");
    assert_eq!(downloads.offline_files_of("photos", &film()), vec![kept]);
    // Three ranges of a chunk each.
    assert_eq!(setup.fake.ranges.lock().unwrap().len(), 3);
    until("told", async || {
        let events = setup.events.lock().unwrap().clone();
        events.contains(&DownloadsEvent::Available(id.clone()))
    })
    .await;

    let Some(OfflineSource::File(path)) = downloads.source("photos", "m3").await.unwrap() else {
        panic!("a plain file");
    };
    assert_eq!(std::fs::read(&path).unwrap(), file);

    let page = downloads.page().await.unwrap();
    assert_eq!(page.available.len(), 1);
    let row = &page.available[0];
    assert_eq!(
        (row.title.as_str(), row.file_name.as_str()),
        ("Film", "m3.jpg")
    );
    assert!(row.movie.is_some());
    assert_eq!(page.summary.as_deref(), Some("1 movie · 16 MB"));

    // Removed: its file is gone, the media stays in the library.
    downloads.remove(&id).await.unwrap();
    assert!(!path.exists());
    assert!(downloads.offline_files().is_empty());
    assert!(downloads.source("photos", "m3").await.unwrap().is_none());
    assert!(setup.copy.media("photos", "m3").await.unwrap().is_some());
}

#[tokio::test]
async fn waits_for_the_server_then_goes_on_where_it_stopped() {
    let file = bytes(CHUNK as usize + 500);
    let setup = Setup::new(file.clone()).await;
    setup.copy.disconnect();
    let media = setup.media().await;
    {
        let downloads = setup.downloads().await;
        downloads.keep_offline("photos", &media, &film());
        let kept = downloads.offline_file("photos", "m3").unwrap();
        assert_eq!(kept.state, OfflineState::Queued);
        assert_eq!(kept.status(), "Waiting to download");
    }
    // The app closed with part of the file written.
    let part = setup
        .folder()
        .join("files")
        .join(file_name("photos", &media, false));
    std::fs::write(&part, &file[..1000]).unwrap();

    let downloads = setup.downloads().await;
    assert_eq!(
        downloads.offline_file("photos", "m3").unwrap().received,
        1000
    );
    setup.connect();
    available(&downloads, &OfflineId::new("photos", "m3")).await;
    assert_eq!(std::fs::read(&part).unwrap(), file);
    let ranges = setup.fake.ranges.lock().unwrap().clone();
    assert_eq!(ranges[0], format!("bytes=1000-{}", 1000 + CHUNK - 1));
}

#[tokio::test]
async fn a_paused_download_resumes_and_a_missing_file_says_so() {
    let file = bytes(3000);
    let setup = Setup::new(file.clone()).await;
    let media = setup.media().await;
    let id = OfflineId::new("photos", "m3");
    setup.copy.disconnect();
    let downloads = setup.downloads().await;
    downloads.keep_offline("photos", &media, &film());
    downloads.pause(&id);
    let paused = downloads.offline_file("photos", "m3").unwrap();
    assert_eq!(
        (paused.status(), paused.state),
        ("Paused".into(), OfflineState::Paused)
    );
    // Paused, the connection does not start it.
    setup.connect();
    until("connected", async || setup.copy.api().is_some()).await;
    assert_eq!(
        downloads.offline_file("photos", "m3").unwrap().state,
        OfflineState::Paused
    );
    downloads.resume(&id);
    available(&downloads, &id).await;

    // Its file removed behind the app's back: missing, and kept again on demand.
    let path = (setup.folder().join("files")).join(file_name("photos", &media, false));
    std::fs::remove_file(&path).unwrap();
    assert!(downloads.source("photos", "m3").await.unwrap().is_none());
    let missing = downloads.offline_file("photos", "m3").unwrap();
    assert_eq!(missing.state, OfflineState::Missing);
    assert_eq!(missing.status(), "File missing · Download again");
    let page = downloads.page().await.unwrap();
    assert_eq!((page.attention.len(), page.available.len()), (1, 0));
    downloads.keep_offline("photos", &media, &film());
    available(&downloads, &id).await;
    assert_eq!(std::fs::read(&path).unwrap(), file);
}

#[tokio::test]
async fn saves_a_copy_where_the_user_chose() {
    let file = bytes(5000);
    let setup = Setup::new(file.clone()).await;
    let downloads = setup.downloads().await;
    let media = setup.media().await;
    let target = setup.dir.0.join("Saved film.jpg");
    std::fs::write(&target, b"replaced once saved").unwrap();
    let id = downloads
        .save_copy("photos", &media, target.clone())
        .unwrap();
    until("saved", async || {
        downloads
            .copies()
            .first()
            .is_some_and(|c| c.state == CopyState::Saved)
    })
    .await;
    assert_eq!(std::fs::read(&target).unwrap(), file);
    // No partial file left.
    let leftovers: Vec<_> = std::fs::read_dir(&setup.dir.0)
        .unwrap()
        .filter_map(|entry| entry.ok())
        .filter(|entry| entry.file_name().to_string_lossy().ends_with(".part"))
        .collect();
    assert!(leftovers.is_empty());
    let copy = downloads.copies()[0].clone();
    assert_eq!(
        (copy.id, copy.received, copy.status()),
        (id, 5000, "4.9 KB".into())
    );
    let ended = setup
        .events
        .lock()
        .unwrap()
        .iter()
        .any(|event| matches!(event, DownloadsEvent::CopyEnded(ended) if ended.id == id));
    assert!(ended);

    // Kept between runs, and forgotten on demand.
    drop(downloads);
    let downloads = setup.downloads().await;
    assert_eq!(downloads.copies().len(), 1);
    downloads.clear_copies();
    assert!(downloads.copies().is_empty());

    // Offline, a copy cannot start.
    setup.copy.disconnect();
    assert!(downloads.save_copy("photos", &media, target).is_err());
}

#[tokio::test(flavor = "multi_thread")]
async fn plays_and_removes_from_a_thread_outside_tokio() {
    let file = bytes(3000);
    let setup = Setup::new(file.clone()).await;
    let downloads = setup.downloads().await;
    let media = setup.media().await;
    downloads.keep_offline("photos", &media, &film());
    let id = OfflineId::new("photos", "m3");
    available(&downloads, &id).await;
    let path = (setup.folder().join("files")).join(file_name("photos", &media, false));

    // An app's UI thread: no tokio runtime there.
    let app = downloads.clone();
    let thread = std::thread::spawn(move || {
        crate::mirror::runtime::tests::block_on(async move {
            let played = app.source("photos", "m3").await.unwrap().is_some();
            app.remove(&OfflineId::new("photos", "m3")).await.unwrap();
            played
        })
    });
    let played = tokio::task::spawn_blocking(move || thread.join().unwrap())
        .await
        .unwrap();
    assert!(played);
    assert!(!path.exists());
    assert!(downloads.offline_files().is_empty());
}

#[tokio::test(flavor = "multi_thread")]
async fn a_copy_that_cannot_start_says_so() {
    let setup = Setup::new(bytes(100)).await;
    let downloads = setup.downloads().await;
    let media = setup.media().await;
    // A folder that does not exist: its partial file fails at once.
    let target = setup.dir.0.join("missing").join("film.jpg");
    for _ in 0..20 {
        downloads
            .save_copy("photos", &media, target.clone())
            .unwrap();
    }
    until("ended", async || {
        !downloads.is_saving("m3") && !downloads.busy()
    })
    .await;
    let copies = downloads.copies();
    assert_eq!(copies.len(), 20);
    assert!(
        copies
            .iter()
            .all(|c| matches!(c.state, CopyState::Failed(_)))
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn paused_and_resumed_at_once_the_file_stays_whole() {
    let file = bytes(4 * CHUNK as usize + 1000);
    let setup = Setup::new(file.clone()).await;
    let downloads = setup.downloads().await;
    let media = setup.media().await;
    let id = OfflineId::new("photos", "m3");
    downloads.keep_offline("photos", &media, &film());
    // Each time a part lands, while its write may still run.
    let mut seen = 0;
    while let Some(kept) = downloads.offline_file("photos", "m3")
        && kept.state != OfflineState::Available
    {
        if kept.received != seen {
            seen = kept.received;
            downloads.pause(&id);
            downloads.resume(&id);
        }
        tokio::task::yield_now().await;
    }
    available(&downloads, &id).await;
    let Some(OfflineSource::File(path)) = downloads.source("photos", "m3").await.unwrap() else {
        panic!("a plain file");
    };
    assert!(std::fs::read(&path).unwrap() == file, "the file is whole");
}

#[tokio::test]
async fn a_file_that_cannot_be_removed_stays_listed() {
    let file = bytes(3000);
    let setup = Setup::new(file).await;
    let downloads = setup.downloads().await;
    let media = setup.media().await;
    let id = OfflineId::new("photos", "m3");
    downloads.keep_offline("photos", &media, &film());
    available(&downloads, &id).await;

    // A folder in its place cannot be removed as a file.
    let path = (setup.folder().join("files")).join(file_name("photos", &media, false));
    std::fs::remove_file(&path).unwrap();
    std::fs::create_dir(&path).unwrap();
    std::fs::write(path.join("inside"), b"x").unwrap();
    assert!(downloads.remove(&id).await.is_err());
    assert!(
        downloads.offline_file("photos", "m3").is_some(),
        "still listed"
    );

    // Once it can be, removed.
    std::fs::remove_dir_all(&path).unwrap();
    downloads.remove(&id).await.unwrap();
    assert!(downloads.offline_files().is_empty());
}

#[tokio::test]
async fn a_file_longer_than_the_servers_downloads_again() {
    let setup = Setup::new(bytes(3000)).await;
    let media = setup.media().await;
    let id = OfflineId::new("photos", "m3");
    let path = (setup.folder().join("files")).join(file_name("photos", &media, false));
    {
        let downloads = setup.downloads().await;
        downloads.keep_offline("photos", &media, &film());
        available(&downloads, &id).await;
    }
    // Grown behind the app's back: missing once reopened, kept again on demand.
    std::fs::write(&path, bytes(3500)).unwrap();
    let downloads = setup.downloads().await;
    let missing = downloads.offline_file("photos", "m3").unwrap();
    assert_eq!(missing.state, OfflineState::Missing);
    downloads.keep_offline("photos", &media, &film());
    available(&downloads, &id).await;
    assert!(
        std::fs::read(&path).unwrap() == bytes(3000),
        "the server's file"
    );
    assert_eq!(
        downloads.offline_file("photos", "m3").unwrap().total,
        Some(3000)
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn the_listener_hears_on_the_runtime_whoever_calls() {
    let setup = Setup::new(bytes(3000)).await;
    let media = setup.media().await;
    let (heard, outside) = (Arc::new(Mutex::new(0)), Arc::new(Mutex::new(0)));
    let downloads = {
        let (heard, outside) = (Arc::clone(&heard), Arc::clone(&outside));
        Downloads::open(setup.copy.clone(), setup.folder(), move |_| {
            *heard.lock().unwrap() += 1;
            if tokio::runtime::Handle::try_current().is_err() {
                *outside.lock().unwrap() += 1;
            }
        })
        .await
        .unwrap()
    };
    let id = OfflineId::new("photos", "m3");
    // From a thread of the app's, outside tokio.
    let calling = downloads.clone();
    std::thread::spawn(move || {
        calling.keep_offline("photos", &media, &film());
        calling.pause(&id);
        calling.resume(&id);
    })
    .join()
    .unwrap();
    until("heard", async || *heard.lock().unwrap() >= 3).await;
    assert_eq!(*outside.lock().unwrap(), 0, "always on the runtime");
}

#[tokio::test]
async fn a_download_cut_by_the_network_goes_on_by_itself() {
    let file = bytes(2 * CHUNK as usize + 100);
    let setup = Setup::new(file.clone()).await;
    let downloads = setup.downloads().await;
    let media = setup.media().await;
    let id = OfflineId::new("photos", "m3");
    // Its first part lost, the copy still connected.
    *setup.fake.failing_files.lock().unwrap() = 1;
    downloads.keep_offline("photos", &media, &film());
    available(&downloads, &id).await;
    let path = (setup.folder().join("files")).join(file_name("photos", &media, false));
    assert!(std::fs::read(&path).unwrap() == file, "the file is whole");
}