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
use std::fmt;
use std::future::Future;
use std::path::{Path, PathBuf};
use std::pin::Pin;

use futures::FutureExt;
use tokio::sync::{mpsc::{Receiver, Sender}, Mutex};
use tokio::sync::mpsc;

use crate::Result;

pub type OnProgressClosure = Box<dyn Fn(CallbackArguments)>;
pub type OnProgressAsyncClosure = Box<dyn Fn(CallbackArguments) -> Pin<Box<dyn Future<Output=()>>>>;
pub type OnCompleteClosure = Box<dyn Fn(Option<PathBuf>)>;
pub type OnCompleteAsyncClosure = Box<dyn Fn(Option<PathBuf>) -> Pin<Box<dyn Future<Output=()>>>>;

#[derive(Debug)]
pub(crate) enum InternalSignal {
    Value(usize),
    Finished,
}

pub(crate) type InternalSender = Sender<InternalSignal>;

/// Arguments given either to a on_progress callback or on_progress receiver
#[doc(cfg(feature = "callback"))]
#[derive(Clone, derivative::Derivative)]
#[derivative(Debug)]
pub struct CallbackArguments {
    pub current_chunk: usize,
    /// It's more idiomatic to use this content length instead of a prefetched value
    /// since the content of this field might change in the future during the download.
    pub content_length: Option<u64>,
}

/// Type to process on_progress
#[doc(cfg(feature = "callback"))]
pub enum OnProgressType {
    /// Box containing a closure to execute on progress
    Closure(OnProgressClosure),
    /// Box containing a async closure to execute on progress
    AsyncClosure(OnProgressAsyncClosure),
    /// Channel to send a message to on progress,
    /// bool indicates whether or not to cancel on a closed channel
    Channel(Sender<CallbackArguments>, bool),
    /// Box containing a closure to execute on progress
    /// Will get executed for every MB downloaded
    SlowClosure(OnProgressClosure),
    /// Box containing a async closure to execute on progress
    /// Will get executed for every MB downloaded
    SlowAsyncClosure(OnProgressAsyncClosure),
    /// Channel to send a message to on progress,
    /// bool indicates whether or not to cancel on a closed channel
    /// Will get executed for every MB downloaded
    SlowChannel(Sender<CallbackArguments>, bool),
    None,
}

impl fmt::Debug for OnProgressType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = match self {
            OnProgressType::AsyncClosure(_) => "AsyncClosure(async Fn)",
            OnProgressType::Channel(_, _) => "Channel(Sender, bool)",
            OnProgressType::Closure(_) => "Closure(Fn)",
            OnProgressType::None => "None",
            OnProgressType::SlowAsyncClosure(_) => "SlowAsyncClosure(async Fn)",
            OnProgressType::SlowChannel(_, _) => "SlowChannel(Sender, bool)",
            OnProgressType::SlowClosure(_) => "SlowClosure(Fn)",
        };
        f.write_str(name)
    }
}

#[doc(cfg(feature = "callback"))]
impl Default for OnProgressType {
    fn default() -> Self {
        OnProgressType::None
    }
}

/// Type to process on_progress
#[doc(cfg(feature = "callback"))]
pub enum OnCompleteType {
    /// Box containing a closure to execute on complete
    Closure(OnCompleteClosure),
    /// Box containing a async closure to execute on complete
    AsyncClosure(OnCompleteAsyncClosure),
    None,
}

impl fmt::Debug for OnCompleteType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = match self {
            OnCompleteType::AsyncClosure(_) => "AsyncClosure(async Fn)",
            OnCompleteType::Closure(_) => "Closure(Fn)",
            OnCompleteType::None => "None",
        };
        f.write_str(name)
    }
}

#[doc(cfg(feature = "callback"))]
impl Default for OnCompleteType {
    fn default() -> Self {
        OnCompleteType::None
    }
}

/// Methods and streams to process either on_progress or on_complete
#[doc(cfg(feature = "callback"))]
#[derive(Debug)]
pub struct Callback {
    pub on_progress: OnProgressType,
    pub on_complete: OnCompleteType,
    pub(crate) internal_sender: InternalSender,
    pub(crate) internal_receiver: Option<Receiver<InternalSignal>>,
}

#[doc(cfg(feature = "callback"))]
impl Callback {
    /// Create a new callback struct without actual callbacks
    pub fn new() -> Self {
        let (tx, rx) = mpsc::channel(100);
        Callback {
            on_progress: OnProgressType::None,
            on_complete: OnCompleteType::None,
            internal_sender: tx,
            internal_receiver: Some(rx),
        }
    }

    /// Attach a closure to be executed on progress
    ///
    /// ### Warning:
    /// This closure gets executed quite often, once every ~10kB progress.
    /// If it's too slow, some on_progress events will be dropped.
    /// If you are looking fore something that will be executed more seldom, look for
    /// [Callback::connect_on_progress_closure_slow](crate::stream::callback::Callback::connect_on_progress_closure_slow)
    #[doc(cfg(feature = "callback"))]
    #[inline]
    pub fn connect_on_progress_closure(mut self, closure: impl Fn(CallbackArguments) + 'static) -> Self {
        self.on_progress = OnProgressType::Closure(Box::new(closure));
        self
    }

    /// Attach a closure to be executed on progress. This closure will be executed
    /// more seldom, around once for every MB downloaded.
    #[doc(cfg(feature = "callback"))]
    #[inline]
    pub fn connect_on_progress_closure_slow(mut self, closure: impl Fn(CallbackArguments) + 'static) -> Self {
        self.on_progress = OnProgressType::SlowClosure(Box::new(closure));
        self
    }

    /// Attach a async closure to be executed on progress
    ///
    /// ### Warning:
    /// This closure gets executed quite often, once every ~10kB progress.
    /// If it's too slow, some on_progress events will be dropped.
    /// If you are looking fore something that will be executed more seldom, look for
    /// [Callback::connect_on_progress_closure_async_slow](crate::stream::callback::Callback::connect_on_progress_closure_async_slow)
    #[doc(cfg(feature = "callback"))]
    #[inline]
    pub fn connect_on_progress_closure_async<Fut: Future<Output=()> + Send + 'static, F: Fn(CallbackArguments) -> Fut + 'static>(mut self, closure: F) -> Self {
        self.on_progress = OnProgressType::AsyncClosure(box move |arg| closure(arg).boxed());
        self
    }

    /// Attach a async closure to be executed on progress. This closure will be executed
    /// more seldom, around once for every MB downloaded.
    #[doc(cfg(feature = "callback"))]
    #[inline]
    pub fn connect_on_progress_closure_async_slow<Fut: Future<Output=()> + Send + 'static, F: Fn(CallbackArguments) -> Fut + 'static + Sync + Send>(mut self, closure: F) -> Self {
        self.on_progress = OnProgressType::SlowAsyncClosure(box move |arg| closure(arg).boxed());
        self
    }

    /// Attach a bounded sender that receives messages on progress
    /// cancel_or_close indicates whether or not to cancel the download, if the receiver is closed
    ///
    /// ### Warning:
    /// This sender gets messages quite often, once every ~10kB progress.
    /// If it's too slow, some on_progress events will be dropped.
    #[doc(cfg(feature = "callback"))]
    #[inline]
    pub fn connect_on_progress_sender(
        mut self,
        sender: Sender<CallbackArguments>,
        cancel_on_close: bool,
    ) -> Self {
        self.on_progress = OnProgressType::Channel(sender, cancel_on_close);
        self
    }

    /// Attach a bounded sender that receives messages on progress
    /// cancel_or_close indicates whether or not to cancel the download, if the receiver is closed
    ///
    /// This closure will be executed more seldom, around once for every MB downloaded.
    #[doc(cfg(feature = "callback"))]
    #[inline]
    pub fn connect_on_progress_sender_slow(
        mut self,
        sender: Sender<CallbackArguments>,
        cancel_on_close: bool,
    ) -> Self {
        self.on_progress = OnProgressType::SlowChannel(sender, cancel_on_close);
        self
    }

    /// Attach a closure to be executed on complete
    #[doc(cfg(feature = "callback"))]
    #[inline]
    pub fn connect_on_complete_closure(mut self, closure: impl Fn(Option<PathBuf>) + 'static) -> Self {
        self.on_complete = OnCompleteType::Closure(Box::new(closure));
        self
    }

    /// Attach a async closure to be executed on complete
    #[doc(cfg(feature = "callback"))]
    #[inline]
    pub fn connect_on_complete_closure_async<Fut: Future<Output=()> + Send + 'static, F: Fn(Option<PathBuf>) -> Fut + 'static>(mut self, closure: F) -> Self {
        self.on_complete = OnCompleteType::AsyncClosure(box move |arg| closure(arg).boxed());
        self
    }
}

impl Default for Callback {
    fn default() -> Self {
        Self::new()
    }
}

impl super::Stream {
    /// Attempts to downloads the [`Stream`](super::Stream)s resource.
    /// This will download the video to <video_id>.mp4 in the current working directory.
    /// Takes an [`Callback`](crate::stream::callback::Callback)
    #[doc(cfg(feature = "callback"))]
    #[inline]
    pub async fn download_with_callback(&self, callback: Callback) -> Result<PathBuf> {
        self.wrap_callback(|channel| {
            self.internal_download(channel)
        }, callback).await
    }

    /// Attempts to downloads the [`Stream`](super::Stream)s resource.
    /// This will download the video to <video_id>.mp4 in the provided directory. 
    /// Takes an [`Callback`](crate::stream::callback::Callback)
    #[doc(cfg(feature = "callback"))]
    #[inline]
    pub async fn download_to_dir_with_callback<P: AsRef<Path>>(
        &self,
        dir: P,
        callback: Callback,
    ) -> Result<PathBuf> {
        self.wrap_callback(|channel| {
            self.internal_download_to_dir(dir, channel)
        }, callback).await
    }

    /// Attempts to downloads the [`Stream`](super::Stream)s resource.
    /// This will download the video to the provided file path.
    /// Takes an [`Callback`](crate::stream::callback::Callback)
    #[doc(cfg(feature = "callback"))]
    #[inline]
    pub async fn download_to_with_callback<P: AsRef<Path>>(&self, path: P, callback: Callback) -> Result<()> {
        let _ = self.wrap_callback(|channel| {
            self.internal_download_to(path, channel)
        }, callback).await?;
        Ok(())
    }

    async fn wrap_callback<F: Future<Output = Result<PathBuf>>>(
        &self,
        to_wrap: impl FnOnce(Option<InternalSender>)-> F,
        mut callback: Callback
    ) -> Result<PathBuf> {
        let wrap_fut = to_wrap(Some(callback.internal_sender.clone()));
        let aid_fut = self.on_progress(
            callback.internal_receiver.take().expect("Callback cannot be used twice"),
            std::mem::take(&mut callback.on_progress),
        );
        let (result, _) = futures::future::join(wrap_fut, aid_fut).await;

        let path = result.as_ref().map(|p| p.clone()).ok();

        Self::on_complete(std::mem::take(&mut callback.on_complete), path).await;

        result
    }

    #[inline]
    async fn on_progress(&self, mut receiver: Receiver<InternalSignal>, on_progress: OnProgressType) {
        let last_trigger = Mutex::new(0);
        let content_length = self.content_length().await.ok();
        match on_progress {
            OnProgressType::None => {}
            OnProgressType::Closure(closure) => {
                while let Some(data) = receiver.recv().await {
                    match data {
                        InternalSignal::Value(data) => {
                            let arguments = CallbackArguments {
                                current_chunk: data,
                                content_length,
                            };
                            closure(arguments);
                        }
                        InternalSignal::Finished => break,
                    }
                }
            }
            OnProgressType::AsyncClosure(closure) => {
                while let Some(data) = receiver.recv().await {
                    match data {
                        InternalSignal::Value(data) => {
                            let arguments = CallbackArguments {
                                current_chunk: data,
                                content_length,
                            };
                            closure(arguments).await;
                        }
                        InternalSignal::Finished => break,
                    }
                }
            }
            OnProgressType::Channel(sender, cancel_on_close) => {
                while let Some(data) = receiver.recv().await {
                    match data {
                        InternalSignal::Value(data) => {
                            let arguments = CallbackArguments {
                                current_chunk: data,
                                content_length,
                            };
                            // await if channel is full
                            if sender.send(arguments).await.is_err() && cancel_on_close {
                                receiver.close()
                            }
                        }
                        InternalSignal::Finished => break,
                    }
                }
            }
            OnProgressType::SlowClosure(closure) => {
                while let Some(data) = receiver.recv().await {
                    match data {
                        InternalSignal::Value(data) => {
                            if let Ok(mut trigger) = last_trigger.try_lock() {
                                // discard any digits beyond the million digit
                                let current_million = data / 1_000_000;
                                if *trigger < current_million {
                                    *trigger = current_million;
                                    let arguments = CallbackArguments {
                                        current_chunk: data,
                                        content_length,
                                    };
                                    closure(arguments)
                                }
                            }
                        }
                        InternalSignal::Finished => break,
                    }
                }
            }
            OnProgressType::SlowAsyncClosure(closure) => {
                while let Some(data) = receiver.recv().await {
                    match data {
                        InternalSignal::Value(data) => {
                            if let Ok(mut trigger) = last_trigger.try_lock() {
                                // discard any digits beyond the million digit
                                let current_million = data / 1_000_000;
                                if *trigger < current_million {
                                    *trigger = current_million;
                                    let arguments = CallbackArguments {
                                        current_chunk: data,
                                        content_length,
                                    };
                                    closure(arguments).await
                                }
                            }
                        }
                        InternalSignal::Finished => break,
                    }
                }
            }
            OnProgressType::SlowChannel(sender, cancel_on_close) => {
                while let Some(data) = receiver.recv().await {
                    match data {
                        InternalSignal::Value(data) => {
                            if let Ok(mut trigger) = last_trigger.try_lock() {
                                // discard any digits beyond the million digit
                                let current_million = data / 1_000_000;
                                if *trigger < current_million {
                                    *trigger = current_million;
                                    let arguments = CallbackArguments {
                                        current_chunk: data,
                                        content_length,
                                    };
                                    if sender.send(arguments).await.is_err() && cancel_on_close {
                                        receiver.close()
                                    }
                                }
                            }
                        }
                        InternalSignal::Finished => break,
                    }
                }
            }
        }
    }

    #[inline]
    async fn on_complete(on_complete: OnCompleteType, path: Option<PathBuf>) {
        match on_complete {
            OnCompleteType::None => {}
            OnCompleteType::Closure(closure) => {
                closure(path)
            }
            OnCompleteType::AsyncClosure(closure) => {
                closure(path).await
            }
        }
    }
}