Skip to content

Commit 2a2ce1d

Browse files
authored
Merge pull request #3 from MainKronos/dev
Update
2 parents d9c76af + d180818 commit 2a2ce1d

5 files changed

Lines changed: 104 additions & 69 deletions

File tree

animeworld/episodio.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ def fileInfo(self) -> Dict[str,str]:
9797

9898
raise err
9999

100-
def download(self, title: Optional[str]=None, folder: str='', hook: Callable[[Dict], None] = lambda *args:None) -> Optional[str]: # Scarica l'episodio con il primo link nella lista
100+
def download(self, title: Optional[str]=None, folder: str='', *, hook: Callable[[Dict], None]=lambda *args:None, opt: List[str]=[]) -> Optional[str]: # Scarica l'episodio con il primo link nella lista
101101
"""
102102
Scarica l'episodio dal primo server funzionante della lista links.
103103
@@ -110,8 +110,10 @@ def download(self, title: Optional[str]=None, folder: str='', hook: Callable[[Di
110110
- `speed`: Velocità di download (byte/s)
111111
- `elapsed`: Tempo trascorso dall'inizio del download.
112112
- `eta`: Tempo stimato rimanente per fine del download.
113-
- `status`: 'downloading' | 'finished'
113+
- `status`: 'downloading' | 'finished' | 'aborted'
114114
- `filename`: Nome del file in download.
115+
- `opt`: Lista per delle opzioni aggiuntive.
116+
- `'abort'`: Ferma forzatamente il download.
115117
116118
```
117119
return str # File scaricato
@@ -122,11 +124,9 @@ def download(self, title: Optional[str]=None, folder: str='', hook: Callable[[Di
122124
err = None
123125
for server in self.links:
124126
try:
125-
file = server.download(title,folder,hook)
126-
except ServerNotSupported:
127-
pass
128-
except requests.exceptions.RequestException as exc:
129-
err = exc
127+
file = server.download(title,folder,hook=hook,opt=opt)
128+
except (ServerNotSupported, requests.exceptions.RequestException) as e:
129+
err = e
130130
else:
131131
return file
132132

animeworld/exceptions.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,9 @@ def __init__(self, file, funName, line):
3131
self.line = line
3232
self.message = f"Il sito è cambiato, di conseguenza la libreria è DEPRECATA. -> [File {file} in {funName} - {line}]"
3333
super().__init__(self.message)
34+
35+
class HardStoppedDownload(Exception):
36+
"""Il file in download è stato forsatamente interrotto."""
37+
def __init__(self):
38+
self.message = "Il file in download è stato forsatamente interrotto."
39+
super().__init__(self.message)

animeworld/server.py

Lines changed: 87 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from datetime import datetime
1111

1212
from .utility import HealthCheck, SES
13-
from .exceptions import ServerNotSupported
13+
from .exceptions import ServerNotSupported, HardStoppedDownload
1414

1515

1616
class 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

327346
class 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

388413
class 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

450477
class 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)

documentation/example.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def my_hook(d):
2222

2323

2424
try:
25-
anime = aw.Anime(link="https://www.animeworld.tv/play/summertime-render.GDU38")
25+
anime = aw.Anime(link="https://www.animeworld.tv/play/summertime-render.GDU38/")
2626

2727
print("Titolo:", anime.getName()) # Titolo dell'anime
2828

@@ -41,7 +41,7 @@ def my_hook(d):
4141
print("Episodi:")
4242
try:
4343
episodi = anime.getEpisodes()
44-
except (aw.ServerNotSupported, aw.AnimeNotAvailable) as error:
44+
except aw.AnimeNotAvailable as error:
4545
print("Errore:", error)
4646
else:
4747
for x in episodi:
@@ -53,5 +53,5 @@ def my_hook(d):
5353
print("\n\tFile info: {\n\t\t" + "\n\t\t".join("{}: {}".format(k, v) for k, v in x.fileInfo().items()) + "\n\t}")
5454
x.download(hook=my_hook)
5555
break
56-
except (aw.DeprecatedLibrary, aw.Error404) as error:
56+
except (aw.DeprecatedLibrary, aw.Error404, aw.ServerNotSupported) as error:
5757
print(error)

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
setuptools.setup(
77
name="animeworld",
8-
version="1.4.19",
8+
version="1.4.20",
99
author="MainKronos",
1010
description="AnimeWorld UNOFFICIAL API",
1111
long_description=long_description,

0 commit comments

Comments
 (0)