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

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

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=()>>>>;

/// 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,
}

/// 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: Sender<usize>,
    pub(crate) internal_receiver: Option<Receiver<usize>>,
}

#[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 {
    #[inline]
    pub(crate) async fn on_progress(mut receiver: Receiver<usize>, on_progress: OnProgressType) {
        let counter = Mutex::new(100);
        match on_progress {
            OnProgressType::None => {}
            OnProgressType::Closure(closure) => {
                while let Some(data) = receiver.recv().await {
                    let arguments = CallbackArguments { current_chunk: data };
                    closure(arguments);
                }
            }
            OnProgressType::AsyncClosure(closure) => {
                while let Some(data) = receiver.recv().await {
                    let arguments = CallbackArguments { current_chunk: data };
                    closure(arguments).await;
                }
            }
            OnProgressType::Channel(sender, cancel_on_close) => {
                while let Some(data) = receiver.recv().await {
                    let arguments = CallbackArguments { current_chunk: data };
                    // await if channel is full
                    if sender.send(arguments).await.is_err() && cancel_on_close {
                        receiver.close()
                    }
                }
            }
            OnProgressType::SlowClosure(closure) => {
                while let Some(data) = receiver.recv().await {
                    if let Ok(mut counter) = counter.try_lock() {
                        *counter += 1;
                        if *counter > 100 {
                            *counter = 0;
                            let arguments = CallbackArguments { current_chunk: data };
                            closure(arguments)
                        }
                    }
                }
            }
            OnProgressType::SlowAsyncClosure(closure) => {
                while let Some(data) = receiver.recv().await {
                    if let Ok(mut counter) = counter.try_lock() {
                        *counter += 1;
                        if *counter > 100 {
                            *counter = 0;
                            let arguments = CallbackArguments { current_chunk: data };
                            closure(arguments).await
                        }
                    }
                }
            }
            OnProgressType::SlowChannel(sender, cancel_on_close) => {
                while let Some(data) = receiver.recv().await {
                    if let Ok(mut counter) = counter.try_lock() {
                        *counter += 1;
                        if *counter > 100 {
                            *counter = 0;
                            let arguments = CallbackArguments { current_chunk: data };
                            if sender.send(arguments).await.is_err() && cancel_on_close {
                                receiver.close()
                            }
                        }
                    }
                }
            }
        }
    }

    #[inline]
    pub(crate) 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
            }
        }
    }
}