-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
407 lines (348 loc) · 12.2 KB
/
utils.py
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
import os
import re
import math
import datetime as dt
import pycurl
import m3u8
import requests
from bs4 import BeautifulSoup
import config
import outputs
class Log:
def __init__(self, logline, eps=None):
if not logline:
self.anime = ''
self.source = config.anime_source
self.eps = ''
self.last_updated = None
return
data = logline.split()
if len(data) == 1: # only anime name
self.anime = data[0]
self.source = config.anime_source
else:
self.source = data[0]
self.anime = data[1]
if eps:
self.eps = eps
self.last_updated = dt.datetime.now()
else:
self.eps = data[2]
if len(data) > 3:
self.last_updated = dt.datetime.fromtimestamp(int(data[3]))
else:
self.last_updated = None
@property
def last_updated_fmt(self):
if self.last_updated:
return self.last_updated.strftime("%Y-%m-%d %H:%M %A")
return ''
def add(self, eps):
self.eps = compress_range(extract_range(f'{self.eps},{eps}'))
self.last_updated = dt.datetime.now()
return self
def edit(self, eps):
self.eps = eps
self.last_updated = dt.datetime.now()
return self
def __str__(self):
rep = (f'{self.source} {self.anime} {self.eps}')
if self.last_updated:
rep += f' {int(self.last_updated.timestamp())}'
return rep
@property
def _eps(self):
if len(self.eps) > 10:
data = re.split(',|-', self.eps)
return f'{data[0]}...{data[-1]}'
else:
return self.eps
def show(self):
rep = f'{outputs.Fore.BLUE}{self.source}{outputs.Fore.RESET}'
rep += f' {self._eps}\t\t{self.anime}'
if self.last_updated:
rep += f' ({self.last_updated_fmt})'
return rep
def get_soup(url):
r = requests.get(url, headers=config.req_headers)
if r.status_code != 200:
outputs.error_info(f"Request Failed: {url}")
raise SystemExit
return BeautifulSoup(r.text, 'html.parser')
def download_file(url, filepath, replace=False):
if os.path.exists(filepath) and not replace:
outputs.warning_info('File already downloaded, skipping.')
return
part_file = f'{filepath}.part'
c = pycurl.Curl()
c.setopt(pycurl.URL, url)
c.setopt(pycurl.NOPROGRESS, 0)
curl_header = [f'{k}: {v}' for k, v in config.down_headers.items()]
if os.path.exists(part_file) and not replace:
outputs.normal_info('Previously Downloaded part found.')
wmode = 'ab'
curl_header.append(
config.resume_t.substitute(size=os.path.getsize(part_file)))
else:
wmode = 'wb'
c.setopt(pycurl.HTTPHEADER, curl_header)
try:
with open(part_file, wmode) as writer:
c.setopt(pycurl.WRITEDATA, writer)
c.perform()
c.close()
except (KeyboardInterrupt, pycurl.error) as e:
c.close()
outputs.error_info(f"Download Failed {e}")
raise SystemExit
os.rename(part_file, filepath)
def download_m3u8(url, filepath, replace=False):
if os.path.exists(filepath) and not replace:
outputs.warning_info('File already downloaded, skipping.')
return
part_file = f'{filepath}.part'
if os.path.exists(part_file) and not replace:
outputs.normal_info('Previously Downloaded part found.')
# TODO: resume download
media = m3u8.load(url)
total = len(media.segments)
with open(part_file, 'wb') as writer:
c = pycurl.Curl()
curl_header = [f'{k}: {v}' for k, v in config.down_headers.items()]
c.setopt(pycurl.HTTPHEADER, curl_header)
c.setopt(pycurl.WRITEDATA, writer)
try:
for i, f in enumerate(media.segments):
uri = f.absolute_uri
c.setopt(pycurl.URL, uri)
c.perform()
outputs.normal_info('\rDownloaded :',
'#' * (((i + 1) * 40) // total),
f'{(i+1)*100//total}% ({i+1} of {total})',
end="")
c.close()
except (KeyboardInterrupt, pycurl.error) as e:
c.close()
raise SystemExit(f"Download Failed {e}")
outputs.normal_info()
os.rename(part_file, filepath)
def get_m3u8_stream(m3u8_url):
media = m3u8.load(m3u8_url)
if media.data['is_variant']:
res = sorted(((i, p.stream_info.resolution[1])
for i, p in enumerate(media.playlists)),
key=lambda x: x[1])
res_high = list(filter(lambda r: r[1] >= config.video_quality, res))
if len(res_high) == 0:
# if higher than config not available choose best
ind = res[-1][0]
else:
# choose the closest but > the config
ind = res_high[0][0]
return media.playlists[ind].absolute_uri
return m3u8_url
def read_cache(num=1, complete=False):
if not os.path.exists(config.cachefile):
return list() if complete else None
else:
with open(config.cachefile, 'r') as r:
lines = r.readlines()
if complete:
return list(map(lambda l: l.strip(), lines))
else:
try:
return lines[num - 1].strip()
except IndexError:
outputs.error_info("The choice number is too large.")
outputs.prompt_val("Total items in cache", len(lines), 'error')
raise SystemExit
def write_cache(anime, append=False):
with open(config.cachefile, 'a' if append else 'w') as w:
w.write(f'{anime}\n')
def clear_cache():
if os.path.exists(config.cachefile):
os.remove(config.cachefile)
def read_log(anime_name=None,
number=math.inf,
pattern=re.compile(r'.*'),
logfile=config.logfile):
if not os.path.exists(logfile):
log = dict()
else:
# TODO need to rewrite this to use Log class
log = {
line[1]: " ".join(line)
for i, line in enumerate(li.strip().split()
for li in open(logfile, 'r')
if pattern.match(li.split()[1]))
if i < number
}
if not anime_name:
return log
return log.get(anime_name)
def write_log(anime_name, episodes, append=True, logfile=config.logfile):
log = read_log(logfile=logfile)
if anime_name in log and append:
log[anime_name] = str(Log(log[anime_name]).add(episodes))
else:
log[anime_name] = str(Log(anime_name, episodes))
with open(logfile, 'w') as w:
w.writelines((f'{v}\n' for v in log.values()))
def remove_anime_from_log(anime_name, logfile=config.logfile):
anime_list = read_log(logfile=logfile)
if anime_name in anime_list:
anime_list.pop(anime_name)
else:
return
logs = sorted(
map(Log, anime_list.values()),
key=lambda l: ((
int(l.last_updated.timestamp())
if l.last_updated else 0) +
(ord(l.anime[0])-ord('a'))/26),
reverse=False)
with open(logfile, "w") as w:
for log in logs:
w.write(f"{str(log)}\n")
def update_tracklist(anime_name, episodes, append=True):
log = read_log(anime_name, logfile=config.ongoingfile)
if log:
write_log(anime_name,
episodes,
append=append,
logfile=config.ongoingfile)
def update_watchlater(anime_name, episode=None):
log = read_log(anime_name, logfile=config.watchlaterfile)
if log:
eps = set(extract_range(Log(log).eps)).difference(
set([episode])
)
if not eps:
remove_anime_from_log(anime_name, logfile=config.watchlaterfile)
else:
write_log(anime_name,
compress_range(eps),
append=True,
logfile=config.watchlaterfile)
def compress_range(range_list):
range_list = sorted(range_list)
if len(range_list) == 0:
return ''
rng_str = f'{range_list[0]}'
prev = range_list[0]
rng = False
for r in range_list[1:]:
if r == prev:
continue
if r == (prev + 1):
if not rng:
rng_str += '-'
rng = True
else:
if rng:
rng_str += f'{prev},{r}'
else:
rng_str += f',{r}'
rng = False
prev = r
if rng:
rng_str += f'{prev}'
return rng_str
def extract_range(range_str):
if range_str is None or range_str.strip() == '':
return
ranges = range_str.replace(" ", "").split(',')
try:
for r in ranges:
if r.strip() == '':
continue
if '-' in r:
rng = r.split('-')
if len(rng) > 2:
outputs.prompt_val('Incorrect formatting', r, 'error')
raise SystemExit
yield from range(int(rng[0]), int(rng[1]) + 1)
else:
yield int(r)
except ValueError as e:
outputs.error_info('Incorrect formatting: use integers for episodes')
outputs.error_tag(e)
raise SystemExit
def recursive_getattr(obj, attr=None):
if attr is None or '.' not in attr:
return dir(obj)
else:
attrs = attr.split('.', 1)
try:
return map(lambda s: f'{attrs[0]}.{s}',
recursive_getattr(getattr(obj, attrs[0]), attrs[1]))
except AttributeError:
return []
def get_anime_path(anime_name, *, make=False, check=False):
"""returns tuple (anime path, existed before)
"""
anime_dir = os.path.join(config.anime_dir, anime_name)
if not os.path.isdir(anime_dir):
if make:
os.mkdir(anime_dir)
return anime_dir, False
elif check:
return None, False
else:
return anime_dir, False
return anime_dir, True
def get_local_episodes(pattrn=r'^[0-9a-z-]+$'):
animes = dict()
for folder in os.listdir(config.anime_dir):
if not os.path.isdir(os.path.join(config.anime_dir, folder)) or \
not re.match(pattrn, folder):
continue
animes[folder] = ''
for f in os.listdir(os.path.join(config.anime_dir, folder)):
m = re.match(r'^ep([0-9]+)\.[a-z0-9]+$', f)
if m:
animes[folder] += f',{m.group(1)}'
return animes
def get_episode_path(anime_name,
episode,
*,
ext='.mp4',
make=False,
check=False):
anime_dir, existed = get_anime_path(anime_name, make=make, check=check)
if anime_dir is None:
return None
ep_path = os.path.join(anime_dir, f'ep{episode:02d}{ext}')
if check and not os.path.isfile(ep_path):
return None
return ep_path
def display_anime_eps_list(animes_dict):
tracklist = read_log(logfile=config.ongoingfile)
log = read_log()
clear_cache()
for name, ep in animes_dict:
outputs.normal_info(f"{name} : ep-{ep}" if ep else name, end=" ")
write_cache(name, append=True)
if name in tracklist:
watched = extract_range(Log(tracklist[name]).eps)
if not ep:
outputs.warning_tag("TRACKED", end="")
elif int(ep) in watched:
outputs.warning_tag("WATCHED", end="")
else:
outputs.success_tag("NEW", end="")
elif name in log:
outputs.normal_tag("LOGGED", end="")
outputs.normal_info()
return
def canon_episodes(anime_name, episodes=None):
url = f"https://www.animefillerlist.com/shows/{anime_name}"
soup = get_soup(url)
eps_str = soup.find("div", {"class": "manga_canon"}).text.split(":")[-1]
rng = extract_range(eps_str)
if episodes:
episodes = set(episodes)
rng = filter(lambda x: x in episodes, rng)
return compress_range(rng)
def completion_list(iterator):
return [f'{s} ' for s in iterator]