redseat-api 0.19.1

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
436
437
438
439
440
441
442
443
444
445
446
447
448
//! The server's video conversions as they go (the web app's `LibraryConvertStore`):
//! told by its `convert_progress` events, which the copy hands over
//! ([`MirrorEvent::Convert`]), and read from its list of plugin jobs.

use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};

use tokio::sync::broadcast::error::RecvError;

use crate::app::{ServerCopy, text};
use crate::error::{Error, ErrorKind, Result};
use crate::mirror::runtime::{Task, spawn};
use crate::mirror::{ConnectionState, MirrorEvent};
use crate::types::media::{ConvertMessage, Media};
use crate::types::plugin_convert_queue::{PluginConvertQueueItem, PluginConvertQueueStatus};
use rs_plugin_common_interfaces::video::{RsVideoTranscodeStatus, VideoConvertRequest};

/// Where a conversion stands.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConversionStatus {
    /// Waiting for the converter.
    Queued,
    /// The converter fetches the source.
    Downloading,
    Converting,
    Done,
    Failed,
    Canceled,
}

impl ConversionStatus {
    /// Whether it ended, well or not.
    pub fn ended(self) -> bool {
        matches!(
            self,
            ConversionStatus::Done | ConversionStatus::Failed | ConversionStatus::Canceled
        )
    }

    fn from_server(status: &RsVideoTranscodeStatus) -> Self {
        match status {
            RsVideoTranscodeStatus::Pending | RsVideoTranscodeStatus::Queued => Self::Queued,
            RsVideoTranscodeStatus::Downloading => Self::Downloading,
            RsVideoTranscodeStatus::Processing => Self::Converting,
            RsVideoTranscodeStatus::Completed => Self::Done,
            RsVideoTranscodeStatus::Failed => Self::Failed,
            RsVideoTranscodeStatus::Canceled => Self::Canceled,
        }
    }

    fn from_job(status: &PluginConvertQueueStatus) -> Self {
        match status {
            PluginConvertQueueStatus::Queued | PluginConvertQueueStatus::Submitted => Self::Queued,
            PluginConvertQueueStatus::Downloading => Self::Downloading,
            PluginConvertQueueStatus::Processing => Self::Converting,
            PluginConvertQueueStatus::Completed => Self::Done,
            PluginConvertQueueStatus::Failed => Self::Failed,
            PluginConvertQueueStatus::Canceled => Self::Canceled,
        }
    }
}

/// One conversion.
#[derive(Debug, Clone, PartialEq)]
pub struct Conversion {
    /// The request's id.
    pub id: String,
    pub library: String,
    /// The source, when known (started here, or a plugin's job).
    pub media: Option<String>,
    /// The new file's name.
    pub filename: String,
    pub status: ConversionStatus,
    /// From 0 to 1.
    pub progress: f64,
    /// Seconds left, when the converter says.
    pub remaining: Option<u64>,
    /// The new media, once done.
    pub converted: Option<String>,
    /// Why it failed, when the server says.
    pub error: Option<String>,
    pub request: Option<VideoConvertRequest>,
    /// Run by a plugin: the server lists it, and removing it cancels it there.
    pub plugin: bool,
}

impl Conversion {
    /// Where it stands, in a few words: "Waiting…", "Downloading the source…",
    /// "42% · 3:20 left", "Done", "Failed: …", "Canceled".
    pub fn status_text(&self) -> String {
        match self.status {
            ConversionStatus::Queued => "Waiting…".to_owned(),
            ConversionStatus::Downloading => "Downloading the source…".to_owned(),
            ConversionStatus::Converting => {
                let percent = format!("{}%", (self.progress * 100.0).floor() as u64);
                match self.remaining {
                    Some(left) if left > 0 => {
                        format!("{percent} · {} left", text::duration(left))
                    }
                    _ => percent,
                }
            }
            ConversionStatus::Done => "Done".to_owned(),
            ConversionStatus::Failed => match &self.error {
                Some(error) => format!("Failed: {error}"),
                None => "Failed".to_owned(),
            },
            ConversionStatus::Canceled => "Canceled".to_owned(),
        }
    }
}

/// The conversions of a server's libraries, in the order they started. Cheap to
/// clone; clones share them. The listener is called on the copy's runtime each time
/// they change; read [`Self::list`] again then.
#[derive(Clone)]
pub struct Conversions {
    shared: Arc<Shared>,
}

struct Shared {
    copy: ServerCopy,
    listener: Arc<dyn Fn() + Send + Sync>,
    list: Mutex<Vec<Conversion>>,
    follow: Mutex<Option<Task>>,
}

impl Drop for Shared {
    fn drop(&mut self) {
        if let Some(task) = lock(&self.follow).take() {
            task.abort();
        }
    }
}

impl Conversions {
    /// Follows the conversions of `copy`'s server: its events, and its plugin jobs,
    /// read each time it connects. `listener` is called on the copy's runtime.
    pub fn open(copy: ServerCopy, listener: impl Fn() + Send + Sync + 'static) -> Conversions {
        let conversions = Conversions {
            shared: Arc::new(Shared {
                copy,
                listener: Arc::new(listener),
                list: Mutex::default(),
                follow: Mutex::default(),
            }),
        };
        conversions.follow();
        if matches!(
            conversions.shared.copy.mirror().status().connection,
            ConnectionState::Connected
        ) {
            conversions.refresh();
        }
        conversions
    }

    /// Every conversion, in the order they started.
    pub fn list(&self) -> Vec<Conversion> {
        lock(&self.shared.list).clone()
    }

    /// The conversions not ended.
    pub fn active(&self) -> usize {
        (lock(&self.shared.list).iter())
            .filter(|c| !c.status.ended())
            .count()
    }

    /// The progress of those under way, on average, from 0 to 1: `None` when none
    /// is.
    pub fn progress(&self) -> Option<f64> {
        let list = lock(&self.shared.list);
        let active: Vec<f64> = (list.iter())
            .filter(|c| !c.status.ended())
            .map(|c| c.progress)
            .collect();
        (!active.is_empty()).then(|| active.iter().sum::<f64>() / active.len() as f64)
    }

    /// Has the server convert `media` of `library` with `request`, by its own
    /// converter or a video convert plugin (`plugin`). Listed at once, waiting. Needs
    /// the server, and the write role.
    pub async fn convert(
        &self,
        library: &str,
        media: &Media,
        request: VideoConvertRequest,
        plugin: Option<&str>,
    ) -> Result<()> {
        let api = (self.shared.copy.mirror())
            .library_api(library)
            .ok_or_else(not_connected)?;
        api.convert_media(&media.id, &request, plugin).await?;
        let extension = request.format.to_string();
        let filename = match media.name.rsplit_once('.') {
            Some((stem, _)) if !stem.is_empty() => format!("{stem}.{extension}"),
            _ => format!("{}.{extension}", media.name),
        };
        let conversion = Conversion {
            id: request.id.clone(),
            library: library.to_owned(),
            media: Some(media.id.clone()),
            filename,
            status: ConversionStatus::Queued,
            progress: 0.0,
            remaining: None,
            converted: None,
            error: None,
            plugin: plugin.is_some(),
            request: Some(request),
        };
        self.shared.put(conversion, Keep::Ours);
        self.shared.tell();
        Ok(())
    }

    /// Reads the plugins' jobs of every library again.
    pub fn refresh(&self) {
        let weak = Arc::downgrade(&self.shared);
        let future = async move {
            let Some(shared) = weak.upgrade() else {
                return;
            };
            let Ok(libraries) = shared.copy.libraries().await else {
                return;
            };
            for library in libraries {
                if shared.copy.mirror().library_api(&library.id).is_none() {
                    return;
                }
                read_jobs(&shared, &library.id).await;
            }
        };
        spawn(self.shared.copy.runtime().as_ref(), Box::pin(future));
    }

    /// Cancels a conversion under way ([`crate::LibraryApi::cancel_convert`]; a
    /// plugin's on a server older than the cancel, by removing its job): it stays in
    /// the list, `Canceled`. One that ended is removed from the list, and a plugin's
    /// from the server too. One the server no longer has is forgotten.
    pub async fn remove(&self, id: &str) -> Result<()> {
        let Some(conversion) = (lock(&self.shared.list).iter())
            .find(|c| c.id == id)
            .cloned()
        else {
            return Ok(());
        };
        if !conversion.status.ended() {
            let api = (self.shared.copy.mirror())
                .library_api(&conversion.library)
                .ok_or_else(not_connected)?;
            let mut cancelled = api.cancel_convert(id).await;
            if conversion.plugin && is_not_found(&cancelled) {
                cancelled = api.remove_video_convert_job(id).await;
            }
            match cancelled {
                Ok(()) => {
                    if let Some(known) = lock(&self.shared.list).iter_mut().find(|c| c.id == id) {
                        known.status = ConversionStatus::Canceled;
                        known.remaining = None;
                    }
                    self.shared.tell();
                    return Ok(());
                }
                // Gone from the server: forgotten below.
                Err(error) if error.kind() == ErrorKind::NotFound => {}
                Err(error) => return Err(error),
            }
        } else if conversion.plugin {
            let api = (self.shared.copy.mirror())
                .library_api(&conversion.library)
                .ok_or_else(not_connected)?;
            match api.remove_video_convert_job(id).await {
                Err(error) if error.kind() != ErrorKind::NotFound => return Err(error),
                _ => {}
            }
        }
        lock(&self.shared.list).retain(|c| c.id != id);
        self.shared.tell();
        Ok(())
    }

    /// Removes every ended conversion (the web app's "Clear finished"). The first
    /// error is returned once the others are removed.
    pub async fn clear_ended(&self) -> Result<()> {
        let ended: Vec<String> = (lock(&self.shared.list).iter())
            .filter(|c| c.status.ended())
            .map(|c| c.id.clone())
            .collect();
        let mut first_error = None;
        for id in ended {
            if let Err(error) = self.remove(&id).await {
                first_error.get_or_insert(error);
            }
        }
        first_error.map_or(Ok(()), Err)
    }

    /// Applies the copy's convert events, and reads the jobs again at each connection.
    fn follow(&self) {
        let mut events = self.shared.copy.mirror().subscribe();
        let weak: Weak<Shared> = Arc::downgrade(&self.shared);
        let future = async move {
            loop {
                let event = events.recv().await;
                let Some(shared) = weak.upgrade() else {
                    return;
                };
                match event {
                    Ok(MirrorEvent::Convert(message)) => {
                        let conversion = event_conversion(*message);
                        // An event never says why it failed: a plugin's job does.
                        let failed = (conversion.status == ConversionStatus::Failed)
                            .then(|| conversion.library.clone());
                        shared.put(conversion, Keep::Theirs);
                        shared.tell();
                        if let Some(library) = failed {
                            read_jobs(&shared, &library).await;
                        }
                    }
                    Ok(MirrorEvent::Connection(ConnectionState::Connected))
                    | Err(RecvError::Lagged(_)) => Conversions { shared }.refresh(),
                    Ok(_) => {}
                    Err(RecvError::Closed) => return,
                }
            }
        };
        let task = spawn(self.shared.copy.runtime().as_ref(), Box::pin(future));
        *lock(&self.shared.follow) = Some(task);
    }
}

/// Whose name and source win when a conversion is listed again.
enum Keep {
    /// Started here: our name (an encrypted library's server names it encrypted).
    Ours,
    /// From the server: the name and source known here stay.
    Theirs,
}

impl Shared {
    fn put(&self, conversion: Conversion, keep: Keep) {
        let mut list = lock(&self.list);
        match list.iter_mut().find(|c| c.id == conversion.id) {
            Some(known) => {
                let (filename, media, request, plugin, error) = (
                    known.filename.clone(),
                    known.media.clone(),
                    known.request.clone(),
                    known.plugin,
                    known.error.clone(),
                );
                *known = conversion;
                if matches!(keep, Keep::Theirs) {
                    if !filename.is_empty() {
                        known.filename = filename;
                    }
                    known.media = known.media.take().or(media);
                    known.request = known.request.take().or(request);
                    known.plugin |= plugin;
                    // An event says no error: the one read from the jobs stays.
                    if known.status == ConversionStatus::Failed {
                        known.error = known.error.take().or(error);
                    }
                }
            }
            None => list.push(conversion),
        }
    }

    /// Tells the listener on the copy's runtime, never inside the app's own call.
    fn tell(&self) {
        let listener = Arc::clone(&self.listener);
        spawn(
            self.copy.runtime().as_ref(),
            Box::pin(async move { listener() }),
        );
    }
}

/// Reads a library's plugin jobs again, and tells when it could.
async fn read_jobs(shared: &Shared, library: &str) {
    let Some(api) = shared.copy.mirror().library_api(library) else {
        return;
    };
    // A library without plugins, or that the user cannot read, has none.
    let Ok(jobs) = api.video_convert_jobs().await else {
        return;
    };
    for job in jobs {
        shared.put(job_conversion(job), Keep::Theirs);
    }
    shared.tell();
}

fn event_conversion(message: ConvertMessage) -> Conversion {
    let progress = message.progress;
    let status = ConversionStatus::from_server(&progress.status);
    let status = if progress.done && !status.ended() {
        ConversionStatus::Done
    } else {
        status
    };
    Conversion {
        id: progress.id,
        library: message.library,
        media: None,
        filename: progress.filename,
        status,
        progress: progress.percent.clamp(0.0, 1.0),
        remaining: progress.remaining_secondes,
        converted: progress.converted_id,
        error: None,
        request: progress.request,
        plugin: false,
    }
}

fn job_conversion(job: PluginConvertQueueItem) -> Conversion {
    Conversion {
        id: job.id,
        library: job.library_id,
        media: Some(job.media_id),
        filename: job.filename,
        status: ConversionStatus::from_job(&job.status),
        progress: job.progress.clamp(0.0, 1.0),
        remaining: None,
        converted: job.converted_id,
        error: job.error,
        request: Some(job.request),
        plugin: true,
    }
}

fn not_connected() -> Error {
    Error::Network {
        message: "Connect to the server to convert videos.".to_owned(),
        path: None,
    }
}

fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    mutex.lock().unwrap_or_else(PoisonError::into_inner)
}

fn is_not_found(result: &Result<()>) -> bool {
    matches!(result, Err(error) if error.kind() == ErrorKind::NotFound)
}