1010from datetime import datetime
1111
1212from .utility import HealthCheck , SES
13- from .exceptions import ServerNotSupported
13+ from .exceptions import ServerNotSupported , HardStoppedDownload
1414
1515
1616class Server :
@@ -128,7 +128,7 @@ def error(self, msg):
128128 }
129129
130130
131- def download (self , title : Optional [str ]= None , folder : str = '' , hook : Callable [[Dict ], None ] = lambda * args :None ) -> Optional [str ]:
131+ def download (self , title : Optional [str ]= None , folder : str = '' , * , hook : Callable [[Dict ], None ]= lambda * args :None , opt : List [ str ] = [] ) -> Optional [str ]:
132132 """
133133 Scarica l'episodio.
134134
@@ -141,8 +141,10 @@ def download(self, title: Optional[str]=None, folder: str='', hook: Callable[[Di
141141 - `speed`: Velocità di download (byte/s)
142142 - `elapsed`: Tempo trascorso dall'inizio del download.
143143 - `eta`: Tempo stimato rimanente per fine del download.
144- - `status`: 'downloading' | 'finished'
144+ - `status`: 'downloading' | 'finished' | 'aborted'
145145 - `filename`: Nome del file in download.
146+ - `opt`: Lista per delle opzioni aggiuntive.
147+ - `'abort'`: Ferma forzatamente il download.
146148
147149 ```
148150 return str # File scaricato
@@ -151,7 +153,8 @@ def download(self, title: Optional[str]=None, folder: str='', hook: Callable[[Di
151153 raise ServerNotSupported (self .name )
152154
153155 # Protected
154- def _downloadIn (self , title : str , folder : str , hook : Callable [[Dict ], None ]) -> bool : # Scarica l'episodio
156+ def _downloadIn (self , title : str , folder : str , * , hook : Callable [[Dict ], None ], opt : List [str ]) -> Optional [str ]: # Scarica l'episodio
157+
155158 """
156159 Scarica il file utilizzando requests.
157160
@@ -164,11 +167,13 @@ def _downloadIn(self, title: str, folder: str, hook: Callable[[Dict], None]) ->
164167 - `speed`: Velocità di download (byte/s)
165168 - `elapsed`: Tempo trascorso dall'inizio del download.
166169 - `eta`: Tempo stimato rimanente per fine del download.
167- - `status`: 'downloading' | 'finished'
170+ - `status`: 'downloading' | 'finished' | 'aborted'
168171 - `filename`: Nome del file in download.
172+ - `opt`: Lista per delle opzioni aggiuntive.
173+ - `'abort'`: Ferma forzatamente il download.
169174
170175 ```
171- return bool # File scaricato
176+ return str # File scaricato
172177 ```
173178 """
174179 with SES .get (self ._getFileLink (), stream = True ) as r :
@@ -182,43 +187,48 @@ def _downloadIn(self, title: str, folder: str, hook: Callable[[Dict], None]) ->
182187 start = time .time ()
183188 step = time .time ()
184189
185- with open (f"{ os .path .join (folder ,file )} " , 'wb' ) as f :
186- for chunk in r .iter_content (chunk_size = 524288 ):
187- if chunk :
188- f .write (chunk )
189- f .flush ()
190-
191- current_lenght += len (chunk )
192-
190+ try :
191+ with open (f"{ os .path .join (folder ,file )} " , 'wb' ) as f :
192+ for chunk in r .iter_content (chunk_size = 524288 ):
193+ if chunk :
194+ f .write (chunk )
195+ f .flush ()
196+
197+ current_lenght += len (chunk )
198+
199+ hook ({
200+ 'total_bytes' : total_length ,
201+ 'downloaded_bytes' : current_lenght ,
202+ 'percentage' : current_lenght / total_length ,
203+ 'speed' : len (chunk ) / (time .time () - step ) if (time .time () - step ) != 0 else 0 ,
204+ 'elapsed' : time .time () - start ,
205+ 'filename' : file ,
206+ 'eta' : ((total_length - current_lenght ) / len (chunk )) * (time .time () - step ),
207+ 'status' : 'downloading' if "abort" not in opt else "aborted"
208+ })
209+
210+ if "abort" in opt : raise HardStoppedDownload ()
211+
212+ step = time .time ()
213+
214+ else :
193215 hook ({
194216 'total_bytes' : total_length ,
195- 'downloaded_bytes' : current_lenght ,
196- 'percentage' : current_lenght / total_length ,
197- 'speed' : len ( chunk ) / ( time . time () - step ) if ( time . time () - step ) != 0 else 0 ,
217+ 'downloaded_bytes' : total_length ,
218+ 'percentage' : 1 ,
219+ 'speed' : 0 ,
198220 'elapsed' : time .time () - start ,
199- 'filename' : file ,
200- 'eta' : ((total_length - current_lenght ) / len (chunk )) * (time .time () - step ),
201- 'status' : 'downloading'
221+ 'eta' : 0 ,
222+ 'status' : 'finished'
202223 })
203224
204- step = time .time ()
205-
206- else :
207- hook ({
208- 'total_bytes' : total_length ,
209- 'downloaded_bytes' : total_length ,
210- 'percentage' : 1 ,
211- 'speed' : 0 ,
212- 'elapsed' : time .time () - start ,
213- 'eta' : 0 ,
214- 'status' : 'finished'
215- })
216-
217- return file # Se il file è stato scaricato correttamente
218- return None # Se è accaduto qualche imprevisto
225+ return file # Se il file è stato scaricato correttamente
226+ except HardStoppedDownload :
227+ os .remove (f"{ os .path .join (folder ,file )} " )
228+ return None
219229
220230 # Protected
221- def _dowloadEx (self , title : str , folder : str , hook : Callable [[Dict ], None ]) -> Optional [str ]:
231+ def _dowloadEx (self , title : str , folder : str , * , hook : Callable [[Dict ], None ], opt : List [ str ]) -> Optional [str ]:
222232 """
223233 Scarica il file utilizzando yutube_dl.
224234
@@ -231,9 +241,11 @@ def _dowloadEx(self, title: str, folder: str, hook: Callable[[Dict], None]) -> O
231241 - `speed`: Velocità di download (byte/s)
232242 - `elapsed`: Tempo trascorso dall'inizio del download.
233243 - `eta`: Tempo stimato rimanente per fine del download.
234- - `status`: 'downloading' | 'finished'
244+ - `status`: 'downloading' | 'finished' | 'aborted'
235245 - `filename`: Nome del file in download.
236-
246+ - `opt`: Lista per delle opzioni aggiuntive.
247+ - `'abort'`: Ferma forzatamente il download.
248+
237249 ```
238250 return str # File scaricato
239251 ```
@@ -249,6 +261,7 @@ def error(self, msg):
249261 return False
250262
251263 def my_hook (d ):
264+
252265 hook ({
253266 'total_bytes' : int (d ['total_bytes_estimate' ]),
254267 'downloaded_bytes' : int (d ['downloaded_bytes' ]),
@@ -257,10 +270,10 @@ def my_hook(d):
257270 'elapsed' : float (d ['elapsed' ]),
258271 'filename' : d ['filename' ],
259272 'eta' : int (d ['eta' ]),
260- 'status' : d ['status' ]
273+ 'status' : d ['status' ] if "abort" not in opt else "aborted"
261274 })
262- if d [ 'status' ] == 'finished' :
263- return True
275+
276+ if "abort" in opt : raise HardStoppedDownload ()
264277
265278 ydl_opts = {
266279 'outtmpl' : f"{ os .path .join (folder ,title )} .%(ext)s" ,
@@ -271,7 +284,11 @@ def my_hook(d):
271284 url = self ._getFileLink ()
272285 info = ydl .extract_info (url , download = False )
273286 filename = ydl .prepare_filename (info )
274- ydl .download ([url ])
287+ try :
288+ ydl .download ([url ])
289+ except HardStoppedDownload :
290+ os .remove (f"{ os .path .join (folder ,filename )} " )
291+ return None
275292 return filename
276293
277294
@@ -300,7 +317,7 @@ def fileInfo(self) -> Dict[str,str]:
300317
301318 return self ._fileInfoIn ()
302319
303- def download (self , title : Optional [str ]= None , folder : str = '' , hook : Callable [[Dict ], None ] = lambda * args :None ) -> bool :
320+ def download (self , title : Optional [str ]= None , folder : str = '' , * , hook : Callable [[Dict ], None ]= lambda * args :None , opt : List [ str ] = [] ) -> Optional [ str ] :
304321 """
305322 Scarica l'episodio.
306323
@@ -313,16 +330,18 @@ def download(self, title: Optional[str]=None, folder: str='', hook: Callable[[Di
313330 - `speed`: Velocità di download (byte/s)
314331 - `elapsed`: Tempo trascorso dall'inizio del download.
315332 - `eta`: Tempo stimato rimanente per fine del download.
316- - `status`: 'downloading' | 'finished'
333+ - `status`: 'downloading' | 'finished' | 'aborted'
317334 - `filename`: Nome del file in download.
335+ - `opt`: Lista per delle opzioni aggiuntive.
336+ - `'abort'`: Ferma forzatamente il download.
318337
319338 ```
320- return bool # File scaricato
339+ return str # File scaricato
321340 ```
322341 """
323342 if title is None : title = self ._defTitle
324343 else : title = self ._sanitize (title )
325- return self ._downloadIn (title ,folder ,hook )
344+ return self ._downloadIn (title ,folder ,hook = hook , opt = opt )
326345
327346class VVVVID (Server ):
328347 # Protected
@@ -360,7 +379,7 @@ def fileInfo(self) -> Dict[str,str]:
360379
361380 return self ._fileInfoEx ()
362381
363- def download (self , title : Optional [str ]= None , folder : str = '' , hook : Callable [[Dict ], None ] = lambda * args :None ) -> bool :
382+ def download (self , title : Optional [str ]= None , folder : str = '' , * , hook : Callable [[Dict ], None ]= lambda * args :None , opt : List [ str ] = [] ) -> Optional [ str ] :
364383 """
365384 Scarica l'episodio.
366385
@@ -373,16 +392,22 @@ def download(self, title: Optional[str]=None, folder: str='', hook: Callable[[Di
373392 - `speed`: Velocità di download (byte/s)
374393 - `elapsed`: Tempo trascorso dall'inizio del download.
375394 - `eta`: Tempo stimato rimanente per fine del download.
376- - `status`: 'downloading' | 'finished'
395+ - `status`: 'downloading' | 'finished' | 'aborted'
377396 - `filename`: Nome del file in download.
397+ - `opt`: Lista per delle opzioni aggiuntive.
398+ - `'abort'`: Ferma forzatamente il download.
378399
379400 ```
380- return bool # File scaricato
401+ return str # File scaricato
381402 ```
382403 """
404+
405+ # TODO: Il download usando VVVVID non funziona don youtube-dl
406+ raise ServerNotSupported (self .name )
407+
383408 if title is None : title = self ._defTitle
384409 else : title = self ._sanitize (title )
385- return self ._dowloadEx (title ,folder ,hook )
410+ return self ._dowloadEx (title ,folder ,hook = hook , opt = opt )
386411
387412
388413class YouTube (Server ):
@@ -423,7 +448,7 @@ def fileInfo(self) -> Dict[str,str]:
423448
424449 return self ._fileInfoEx ()
425450
426- def download (self , title : Optional [str ]= None , folder : str = '' , hook : Callable [[Dict ], None ] = lambda * args :None ) -> bool :
451+ def download (self , title : Optional [str ]= None , folder : str = '' , * , hook : Callable [[Dict ], None ]= lambda * args :None , opt : List [ str ] = [] ) -> Optional [ str ] :
427452 """
428453 Scarica l'episodio.
429454
@@ -436,16 +461,18 @@ def download(self, title: Optional[str]=None, folder: str='', hook: Callable[[Di
436461 - `speed`: Velocità di download (byte/s)
437462 - `elapsed`: Tempo trascorso dall'inizio del download.
438463 - `eta`: Tempo stimato rimanente per fine del download.
439- - `status`: 'downloading' | 'finished'
464+ - `status`: 'downloading' | 'finished' | 'aborted'
440465 - `filename`: Nome del file in download.
466+ - `opt`: Lista per delle opzioni aggiuntive.
467+ - `'abort'`: Ferma forzatamente il download.
441468
442469 ```
443- return bool # File scaricato
470+ return str # File scaricato
444471 ```
445472 """
446473 if title is None : title = self ._defTitle
447474 else : title = self ._sanitize (title )
448- return self ._dowloadEx (title ,folder ,hook )
475+ return self ._dowloadEx (title ,folder ,hook = hook , opt = opt )
449476
450477class Streamtape (Server ):
451478 # Protected
@@ -489,7 +516,7 @@ def fileInfo(self) -> Dict[str,str]:
489516
490517 return self ._fileInfoIn ()
491518
492- def download (self , title : Optional [str ]= None , folder : str = '' , hook : Callable [[Dict ], None ] = lambda * args :None ) -> bool :
519+ def download (self , title : Optional [str ]= None , folder : str = '' , * , hook : Callable [[Dict ], None ]= lambda * args :None , opt : List [ str ] = [] ) -> Optional [ str ] :
493520 """
494521 Scarica l'episodio.
495522
@@ -502,13 +529,15 @@ def download(self, title: Optional[str]=None, folder: str='', hook: Callable[[Di
502529 - `speed`: Velocità di download (byte/s)
503530 - `elapsed`: Tempo trascorso dall'inizio del download.
504531 - `eta`: Tempo stimato rimanente per fine del download.
505- - `status`: 'downloading' | 'finished'
532+ - `status`: 'downloading' | 'finished' | 'aborted'
506533 - `filename`: Nome del file in download.
534+ - `opt`: Lista per delle opzioni aggiuntive.
535+ - `'abort'`: Ferma forzatamente il download.
507536
508537 ```
509- return bool # File scaricato
538+ return str # File scaricato
510539 ```
511540 """
512541 if title is None : title = self ._defTitle
513542 else : title = self ._sanitize (title )
514- return self ._downloadIn (title ,folder ,hook )
543+ return self ._downloadIn (title ,folder ,hook = hook , opt = opt )
0 commit comments