Commit | Line | Data |
---|---|---|
04a05f7f MW |
1 | #! /usr/bin/python3 |
2 | ### -*- mode: python; coding: utf-8 -*- | |
3 | ||
4 | from contextlib import contextmanager | |
151b3c4f | 5 | import optparse as OP |
04a05f7f MW |
6 | import os as OS |
7 | import re as RX | |
8 | import sys as SYS | |
9 | ||
10 | class ExpectedError (Exception): pass | |
11 | ||
12 | @contextmanager | |
13 | def location(loc): | |
14 | global LOC | |
15 | old, LOC = LOC, loc | |
16 | yield loc | |
17 | LOC = old | |
18 | ||
19 | def filter(value, func = None, dflt = None): | |
20 | if value is None: return dflt | |
21 | elif func is None: return value | |
22 | else: return func(value) | |
23 | ||
24 | def check(cond, msg): | |
25 | if not cond: raise ExpectedError(msg) | |
26 | ||
151b3c4f MW |
27 | def lookup(dict, key, msg): |
28 | try: return dict[key] | |
29 | except KeyError: raise ExpectedError(msg) | |
30 | ||
31 | def forget(dict, key): | |
32 | try: del dict[key] | |
33 | except KeyError: pass | |
34 | ||
04a05f7f MW |
35 | def getint(s): |
36 | if not s.isdigit(): raise ExpectedError("bad integer `%s'" % s) | |
37 | return int(s) | |
38 | ||
39 | class Words (object): | |
40 | def __init__(me, s): | |
41 | me._s = s | |
42 | me._i, me._n = 0, len(s) | |
43 | def _wordstart(me): | |
44 | s, i, n = me._s, me._i, me._n | |
45 | while i < n: | |
46 | if not s[i].isspace(): return i | |
47 | i += 1 | |
48 | return -1 | |
49 | def nextword(me): | |
50 | s, n = me._s, me._n | |
51 | begin = i = me._wordstart() | |
52 | if begin < 0: return None | |
53 | while i < n and not s[i].isspace(): i += 1 | |
54 | me._i = i | |
55 | return s[begin:i] | |
56 | def rest(me): | |
57 | s, n = me._s, me._n | |
58 | begin = me._wordstart() | |
59 | if begin < 0: return None | |
60 | else: return s[begin:].rstrip() | |
61 | ||
62 | URL_SAFE_P = 256*[False] | |
63 | for ch in \ | |
64 | b"ABCDEFGHIJKLMNOPQRSTUVWXYZ" \ | |
65 | b"abcdefghijklmnopqrstuvwxyz" \ | |
66 | b"0123456789" b"!$%-.,/": | |
67 | URL_SAFE_P[ch] = True | |
68 | def urlencode(s): | |
69 | return "".join((URL_SAFE_P[ch] and chr(ch) or "%%%02x" % ch | |
70 | for ch in s.encode("UTF-8"))) | |
71 | ||
72 | PROG = OS.path.basename(SYS.argv[0]) | |
73 | ||
74 | class BaseLocation (object): | |
75 | def report(me, exc): | |
76 | SYS.stderr.write("%s: %s%s\n" % (PROG, me._loc(), exc)) | |
77 | ||
78 | class DummyLocation (BaseLocation): | |
79 | def _loc(me): return "" | |
80 | ||
81 | class FileLocation (BaseLocation): | |
82 | def __init__(me, fn, lno = 1): me._fn, me._lno = fn, lno | |
83 | def _loc(me): return "%s:%d: " % (me._fn, me._lno) | |
84 | def stepline(me): me._lno += 1 | |
85 | ||
86 | LOC = DummyLocation() | |
87 | ||
88 | class Source (object): | |
89 | PREFIX = "" | |
90 | TITLEP = CHAPTERP = False | |
91 | def __init__(me, fn): | |
92 | me.fn = fn | |
b092d511 MW |
93 | me.neps = None |
94 | me.used_titles = dict() | |
95 | me.used_chapters = set() | |
96 | me.nuses = 0 | |
fd3b422f | 97 | def url(me, title = None, start_chapter = None, end_chapter = None): |
151b3c4f | 98 | if title == "-": |
04a05f7f | 99 | if me.TITLEP: raise ExpectedError("missing title number") |
fd3b422f | 100 | if start_chapter is not None or end_chapter is not None: |
04a05f7f MW |
101 | raise ExpectedError("can't specify chapter without title") |
102 | suffix = "" | |
103 | elif not me.TITLEP: | |
104 | raise ExpectedError("can't specify title with `%s'" % me.fn) | |
fd3b422f MW |
105 | elif start_chapter is None: |
106 | if end_chapter is not None: | |
107 | raise ExpectedError("can't specify end chapter without start chapter") | |
04a05f7f MW |
108 | suffix = "#%d" % title |
109 | elif not me.CHAPTERP: | |
110 | raise ExpectedError("can't specify chapter with `%s'" % me.fn) | |
fd3b422f MW |
111 | elif end_chapter is None: |
112 | suffix = "#%d:%d" % (title, start_chapter) | |
04a05f7f | 113 | else: |
fd3b422f MW |
114 | suffix = "#%d:%d-%d:%d" % (title, start_chapter, title, end_chapter - 1) |
115 | if end_chapter is not None: | |
116 | keys = [(title, ch) for ch in range(start_chapter, end_chapter)] | |
117 | set = me.used_chapters | |
118 | else: | |
119 | keys, set = [title], me.used_titles | |
120 | for k in keys: | |
121 | if k in set: | |
122 | if title == "-": | |
123 | raise ExpectedError("`%s' already used" % me.fn) | |
124 | elif end_chapter is None: | |
125 | raise ExpectedError("`%s' title %d already used" % (me.fn, title)) | |
126 | else: | |
127 | raise ExpectedError("`%s' title %d chapter %d already used" % | |
128 | (me.fn, title, k[1])) | |
129 | if end_chapter is not None: | |
130 | for ch in range(start_chapter, end_chapter): | |
131 | me.used_chapters.add((title, ch)) | |
04a05f7f MW |
132 | return me.PREFIX + ROOT + urlencode(me.fn) + suffix |
133 | ||
134 | class VideoDisc (Source): | |
135 | PREFIX = "dvd://" | |
136 | TITLEP = CHAPTERP = True | |
137 | ||
b092d511 MW |
138 | def __init__(me, fn, *args, **kw): |
139 | super().__init__(fn, *args, **kw) | |
140 | me.neps = 0 | |
141 | ||
04a05f7f MW |
142 | class VideoSeason (object): |
143 | def __init__(me, i, title): | |
144 | me.i = i | |
145 | me.title = title | |
146 | me.episodes = {} | |
32cd109c MW |
147 | def set_episode_disc(me, i, disc): |
148 | if i in me.episodes: | |
149 | raise ExpectedError("season %d episode %d already taken" % (me.i, i)) | |
b092d511 | 150 | me.episodes[i] = disc; disc.neps += 1 |
04a05f7f | 151 | |
dcb1cc6c MW |
152 | def match_group(m, *groups, dflt = None, mustp = False): |
153 | for g in groups: | |
154 | try: s = m.group(g) | |
155 | except IndexError: continue | |
04a05f7f | 156 | if s is not None: return s |
dcb1cc6c MW |
157 | if mustp: raise ValueError("no match found") |
158 | else: return dflt | |
04a05f7f MW |
159 | |
160 | class VideoDir (object): | |
161 | ||
4f8020f7 MW |
162 | _R_ISO_PRE = list(map(lambda pats: |
163 | list(map(lambda pat: | |
164 | RX.compile("^" + pat + r"\.iso$", RX.X), | |
165 | pats)), | |
166 | [[r""" S (?P<si> \d+) \. \ (?P<stitle> .*) — (?: D \d+ \. \ )? | |
167 | (?P<epex> .*) """, | |
168 | r""" S (?P<si> \d+) (?: D \d+)? \. \ (?P<epex> .*) """, | |
169 | r""" S (?P<si> \d+) \. \ (?P<epex> E \d+ .*) """, | |
170 | r""" S (?P<si> \d+) (?P<epex> E \d+) \. \ .* """], | |
171 | [r""" (?P<si> \d+) [A-Z]? \. \ (?P<stitle> .*) — (?P<epex> .*) """], | |
172 | [r""" \d+ \. \ (?P<epex> [ES] \d+ .*) """], | |
173 | [r""" (?P<epnum> \d+ ) \. \ .* """]])) | |
04a05f7f | 174 | |
9fc467bb | 175 | _R_ISO_EP = RX.compile(r""" ^ |
6b5cec73 | 176 | (?: S (?P<si> \d+) \ )? |
9fc467bb | 177 | E (?P<ei> \d+) (?: – (?P<ej> \d+))? $ |
04a05f7f MW |
178 | """, RX.X) |
179 | ||
180 | def __init__(me, dir): | |
b092d511 | 181 | me.dir = dir |
04a05f7f MW |
182 | fns = OS.listdir(OS.path.join(ROOT, dir)) |
183 | fns.sort() | |
6b5cec73 | 184 | season = None |
04a05f7f | 185 | seasons = {} |
4f8020f7 | 186 | styles = me._R_ISO_PRE |
04a05f7f MW |
187 | for fn in fns: |
188 | path = OS.path.join(dir, fn) | |
189 | if not fn.endswith(".iso"): continue | |
dcb1cc6c | 190 | #print(";; `%s'" % path, file = SYS.stderr) |
4f8020f7 MW |
191 | for sty in styles: |
192 | for r in sty: | |
193 | m = r.match(fn) | |
194 | if m: styles = [sty]; break | |
195 | else: | |
196 | continue | |
197 | break | |
dcb1cc6c MW |
198 | else: |
199 | #print(";;\tignored (regex mismatch)", file = SYS.stderr) | |
065a5db6 | 200 | continue |
04a05f7f | 201 | |
dcb1cc6c MW |
202 | si = filter(match_group(m, "si"), int) |
203 | stitle = match_group(m, "stitle") | |
204 | ||
205 | check(si is not None or stitle is None, | |
6b5cec73 | 206 | "explicit season title without number in `%s'" % fn) |
dcb1cc6c MW |
207 | if si is not None: |
208 | if season is None or si != season.i: | |
209 | check(season is None or si == season.i + 1, | |
6b5cec73 | 210 | "season %d /= %d" % |
dcb1cc6c MW |
211 | (si, season is None and -1 or season.i + 1)) |
212 | check(si not in seasons, "season %d already seen" % si) | |
213 | seasons[si] = season = VideoSeason(si, stitle) | |
6b5cec73 MW |
214 | else: |
215 | check(stitle == season.title, | |
216 | "season title `%s' /= `%s'" % (stitle, season.title)) | |
04a05f7f | 217 | |
32cd109c | 218 | disc = VideoDisc(path) |
6b5cec73 | 219 | ts = season |
32cd109c | 220 | any, bad = False, False |
dcb1cc6c MW |
221 | epnum = match_group(m, "epnum") |
222 | if epnum is not None: eplist = ["E" + epnum] | |
223 | else: eplist = match_group(m, "epex", mustp = True).split(", ") | |
35ecb6eb | 224 | for eprange in eplist: |
04a05f7f | 225 | mm = me._R_ISO_EP.match(eprange) |
3ee2c072 MW |
226 | if mm is None: |
227 | #print(";;\t`%s'?" % eprange, file = SYS.stderr) | |
228 | bad = True; continue | |
229 | if not any: any = True | |
6b5cec73 MW |
230 | i = filter(mm.group("si"), int) |
231 | if i is not None: | |
232 | try: ts = seasons[i] | |
233 | except KeyError: ts = seasons[i] = VideoSeason(i, None) | |
234 | if ts is None: | |
235 | ts = season = seasons[1] = VideoSeason(1, None) | |
04a05f7f MW |
236 | start = filter(mm.group("ei"), int) |
237 | end = filter(mm.group("ej"), int, start) | |
32cd109c | 238 | for k in range(start, end + 1): |
6b5cec73 | 239 | ts.set_episode_disc(k, disc) |
065a5db6 | 240 | #print(";;\tepisode %d.%d" % (ts.i, k), file = SYS.stderr) |
3ee2c072 | 241 | if not any: |
dcb1cc6c | 242 | #print(";;\tignored", file = SYS.stderr) |
3ee2c072 MW |
243 | pass |
244 | elif bad: | |
245 | raise ExpectedError("bad ep list in `%s'", fn) | |
04a05f7f MW |
246 | me.seasons = seasons |
247 | ||
248 | class AudioDisc (Source): | |
fbac3340 | 249 | PREFIX = "file://" |
04a05f7f MW |
250 | TITLEP = CHAPTERP = False |
251 | ||
d5c4caf1 | 252 | class AudioEpisode (AudioDisc): |
04a05f7f MW |
253 | def __init__(me, fn, i, *args, **kw): |
254 | super().__init__(fn, *args, **kw) | |
255 | me.i = i | |
256 | ||
257 | class AudioDir (object): | |
258 | ||
9fc467bb | 259 | _R_FLAC = RX.compile(r""" ^ |
04a05f7f MW |
260 | E (\d+) |
261 | (?: \. \ (.*))? | |
262 | \. flac $ | |
263 | """, RX.X) | |
264 | ||
265 | def __init__(me, dir): | |
b092d511 | 266 | me.dir = dir |
04a05f7f MW |
267 | fns = OS.listdir(OS.path.join(ROOT, dir)) |
268 | fns.sort() | |
269 | episodes = {} | |
270 | last_i = 0 | |
271 | for fn in fns: | |
272 | path = OS.path.join(dir, fn) | |
273 | if not fn.endswith(".flac"): continue | |
274 | m = me._R_FLAC.match(fn) | |
275 | if not m: continue | |
276 | i = filter(m.group(1), int) | |
277 | etitle = m.group(2) | |
278 | check(i == last_i + 1, "episode %d /= %d" % (i, last_i + 1)) | |
279 | episodes[i] = AudioEpisode(path, i) | |
280 | last_i = i | |
281 | me.episodes = episodes | |
282 | ||
283 | class Chapter (object): | |
284 | def __init__(me, episode, title, i): | |
285 | me.title, me.i = title, i | |
fd3b422f | 286 | me.url = episode.source.url(episode.tno, i, i + 1) |
04a05f7f MW |
287 | |
288 | class Episode (object): | |
0411af2c MW |
289 | def __init__(me, season, i, neps, title, src, tno = None, |
290 | startch = None, endch = None): | |
04a05f7f MW |
291 | me.season = season |
292 | me.i, me.neps, me.title = i, neps, title | |
293 | me.chapters = [] | |
294 | me.source, me.tno = src, tno | |
0411af2c | 295 | me.url = src.url(tno, startch, endch) |
04a05f7f MW |
296 | def add_chapter(me, title, j): |
297 | ch = Chapter(me, title, j) | |
298 | me.chapters.append(ch) | |
299 | return ch | |
300 | def label(me): | |
301 | return me.season._eplabel(me.i, me.neps, me.title) | |
302 | ||
151b3c4f MW |
303 | class BaseSeason (object): |
304 | def __init__(me, series, implicitp = False): | |
305 | me.series = series | |
04a05f7f | 306 | me.episodes = [] |
151b3c4f MW |
307 | me.implicitp = implicitp |
308 | me.ep_i, episodes = 1, [] | |
0411af2c MW |
309 | def add_episode(me, j, neps, title, src, tno, startch, endch): |
310 | ep = Episode(me, j, neps, title, src, tno, startch, endch) | |
04a05f7f | 311 | me.episodes.append(ep) |
151b3c4f | 312 | src.nuses += neps; me.ep_i += neps |
04a05f7f | 313 | return ep |
4a25b86c MW |
314 | def _epnames(me, i, neps): |
315 | playlist = me.series.playlist | |
316 | if neps == 1: return playlist.epname, "%d" % i | |
317 | elif neps == 2: return playlist.epnames, "%d, %d" % (i, i + 1) | |
318 | else: return playlist.epnames, "%d–%d" % (i, i + neps - 1) | |
151b3c4f MW |
319 | |
320 | class Season (BaseSeason): | |
321 | def __init__(me, series, title, i, *args, **kw): | |
322 | super().__init__(series, *args, **kw) | |
323 | me.title, me.i = title, i | |
04a05f7f | 324 | def _eplabel(me, i, neps, title): |
4a25b86c | 325 | epname, epn = me._epnames(i, neps) |
04a05f7f | 326 | if title is None: |
151b3c4f MW |
327 | if me.implicitp: label = "%s %s" % (epname, epn) |
328 | elif me.title is None: label = "%s %d.%s" % (epname, me.i, epn) | |
329 | else: label = "%s—%s %s" % (me.title, epname, epn) | |
04a05f7f | 330 | else: |
151b3c4f MW |
331 | if me.implicitp: label = "%s. %s" % (epn, title) |
332 | elif me.title is None: label = "%d.%s. %s" % (me.i, epn, title) | |
333 | else: label = "%s—%s. %s" % (me.title, epn, title) | |
334 | return label | |
04a05f7f | 335 | |
151b3c4f | 336 | class MovieSeason (BaseSeason): |
c3538df6 MW |
337 | def __init__(me, series, title, *args, **kw): |
338 | super().__init__(series, *args, **kw) | |
339 | me.title = title | |
5ca4c92e | 340 | me.i = None |
0411af2c | 341 | def add_episode(me, j, neps, title, src, tno, startch, endch): |
c3538df6 MW |
342 | if me.title is None and title is None: |
343 | raise ExpectedError("movie or movie season must have a title") | |
0411af2c | 344 | return super().add_episode(j, neps, title, src, tno, startch, endch) |
c3538df6 MW |
345 | def _eplabel(me, i, neps, title): |
346 | if me.title is None: | |
347 | label = title | |
348 | elif title is None: | |
349 | epname, epn = me._epnames(i, neps) | |
350 | label = "%s—%s %s" % (me.title, epname, epn) | |
351 | else: | |
352 | label = "%s—%s" % (me.title, title) | |
353 | return label | |
04a05f7f | 354 | |
151b3c4f | 355 | class Series (object): |
08f08e7c | 356 | def __init__(me, playlist, name, title = None, wantedp = True): |
151b3c4f | 357 | me.playlist = playlist |
08f08e7c | 358 | me.name, me.title = name, title |
151b3c4f | 359 | me.cur_season = None |
08f08e7c | 360 | me.wantedp = wantedp |
151b3c4f MW |
361 | def _add_season(me, season): |
362 | me.cur_season = season | |
363 | def add_season(me, title, i, implicitp = False): | |
364 | me._add_season(Season(me, title, i, implicitp)) | |
c3538df6 MW |
365 | def add_movies(me, title = None): |
366 | me._add_season(MovieSeason(me, title)) | |
151b3c4f MW |
367 | def ensure_season(me): |
368 | if me.cur_season is None: me.add_season(None, 1, implicitp = True) | |
369 | return me.cur_season | |
370 | def end_season(me): | |
371 | me.cur_season = None | |
04a05f7f | 372 | |
151b3c4f | 373 | class Playlist (object): |
04a05f7f MW |
374 | def __init__(me): |
375 | me.seasons = [] | |
151b3c4f | 376 | me.episodes = [] |
04a05f7f | 377 | me.epname, me.epnames = "Episode", "Episodes" |
151b3c4f MW |
378 | me.nseries = 0 |
379 | def add_episode(me, episode): | |
380 | me.episodes.append(episode) | |
381 | def done_season(me): | |
382 | if me.episodes: | |
383 | me.seasons.append(me.episodes) | |
384 | me.episodes = [] | |
04a05f7f MW |
385 | def write(me, f): |
386 | f.write("#EXTM3U\n") | |
387 | for season in me.seasons: | |
388 | f.write("\n") | |
151b3c4f MW |
389 | for ep in season: |
390 | label = ep.label() | |
391 | if me.nseries > 1: label = ep.season.series.title + " " + label | |
04a05f7f | 392 | if not ep.chapters: |
151b3c4f | 393 | f.write("#EXTINF:0,,%s\n%s\n" % (label, ep.url)) |
04a05f7f MW |
394 | else: |
395 | for ch in ep.chapters: | |
396 | f.write("#EXTINF:0,,%s: %s\n%s\n" % | |
151b3c4f MW |
397 | (label, ch.title, ch.url)) |
398 | ||
399 | MODE_UNSET = 0 | |
400 | MODE_SINGLE = 1 | |
401 | MODE_MULTI = 2 | |
402 | ||
403 | class EpisodeListParser (object): | |
404 | ||
405 | def __init__(me, series_wanted = None, chapters_wanted_p = False): | |
406 | me._pl = Playlist() | |
407 | me._cur_episode = me._cur_chapter = None | |
408 | me._series = {}; me._vdirs = {}; me._audirs = {}; me._isos = {} | |
409 | me._series_wanted = series_wanted | |
410 | me._chaptersp = chapters_wanted_p | |
411 | if series_wanted is None: me._mode = MODE_UNSET | |
412 | else: me._mode = MODE_MULTI | |
413 | ||
414 | def _bad_keyval(me, cmd, k, v): | |
415 | raise ExpectedError("invalid `!%s' option `%s'" % | |
416 | (cmd, v if k is None else k)) | |
417 | ||
418 | def _keyvals(me, opts): | |
419 | if opts is not None: | |
420 | for kv in opts.split(","): | |
421 | try: sep = kv.index("=") | |
422 | except ValueError: yield None, kv | |
423 | else: yield kv[:sep], kv[sep + 1:] | |
424 | ||
425 | def _set_mode(me, mode): | |
426 | if me._mode == MODE_UNSET: | |
427 | me._mode = mode | |
428 | elif me._mode != mode: | |
429 | raise ExpectedError("inconsistent single-/multi-series usage") | |
430 | ||
431 | def _get_series(me, name): | |
432 | if name is None: | |
433 | me._set_mode(MODE_SINGLE) | |
434 | try: series = me._series[None] | |
435 | except KeyError: | |
08f08e7c | 436 | series = me._series[None] = Series(me._pl, None) |
151b3c4f MW |
437 | me._pl.nseries += 1 |
438 | else: | |
439 | me._set_mode(MODE_MULTI) | |
440 | series = lookup(me._series, name, "unknown series `%s'" % name) | |
441 | return series | |
442 | ||
443 | def _opts_series(me, cmd, opts): | |
444 | name = None | |
445 | for k, v in me._keyvals(opts): | |
446 | if k is None: name = v | |
447 | else: me._bad_keyval(cmd, k, v) | |
08f08e7c | 448 | return me._get_series(name) |
151b3c4f | 449 | |
08f08e7c MW |
450 | def _auto_epsrc(me, series): |
451 | dir = lookup(me._vdirs, series.name, "no active video directory") | |
452 | season = series.ensure_season() | |
453 | check(season.i is not None, "must use explicit iso for movie seasons") | |
454 | vseason = lookup(dir.seasons, season.i, | |
455 | "season %d not found in video dir `%s'" % | |
456 | (season.i, dir.dir)) | |
457 | src = lookup(vseason.episodes, season.ep_i, | |
458 | "episode %d.%d not found in video dir `%s'" % | |
459 | (season.i, season.ep_i, dir.dir)) | |
460 | return src | |
151b3c4f MW |
461 | |
462 | def _process_cmd(me, ww): | |
463 | ||
464 | cmd = ww.nextword(); check(cmd is not None, "missing command") | |
465 | try: sep = cmd.index(":") | |
466 | except ValueError: opts = None | |
467 | else: cmd, opts = cmd[:sep], cmd[sep + 1:] | |
468 | ||
469 | if cmd == "series": | |
470 | name = None | |
471 | for k, v in me._keyvals(opts): | |
472 | if k is None: name = v | |
473 | else: me._bad_keyval(cmd, k, v) | |
474 | check(name is not None, "missing series name") | |
475 | check(name not in me._series, "series `%s' already defined" % name) | |
476 | title = ww.rest(); check(title is not None, "missing title") | |
477 | me._set_mode(MODE_MULTI) | |
08f08e7c MW |
478 | me._series[name] = series = Series(me._pl, name, title, |
479 | me._series_wanted is None or | |
480 | name in me._series_wanted) | |
481 | if series.wantedp: me._pl.nseries += 1 | |
151b3c4f MW |
482 | |
483 | elif cmd == "season": | |
08f08e7c | 484 | series = me._opts_series(cmd, opts) |
151b3c4f MW |
485 | w = ww.nextword(); |
486 | check(w is not None, "missing season number") | |
487 | if w == "-": | |
08f08e7c | 488 | if not series.wantedp: return |
c3538df6 | 489 | series.add_movies(ww.rest()) |
151b3c4f MW |
490 | else: |
491 | title = ww.rest(); i = getint(w) | |
08f08e7c | 492 | if not series.wantedp: return |
151b3c4f MW |
493 | series.add_season(ww.rest(), getint(w), implicitp = False) |
494 | me._cur_episode = me._cur_chapter = None | |
495 | me._pl.done_season() | |
496 | ||
497 | elif cmd == "epname": | |
498 | for k, v in me._keyvals(opts): me._bad_keyval("epname", k, v) | |
499 | name = ww.rest(); check(name is not None, "missing episode name") | |
500 | try: sep = name.index(",") | |
501 | except ValueError: names = name + "s" | |
502 | else: name, names = name[:sep], name[sep + 1:] | |
503 | me._pl.epname, me._pl.epnames = name, names | |
504 | ||
505 | elif cmd == "epno": | |
08f08e7c | 506 | series = me._opts_series(cmd, opts) |
151b3c4f MW |
507 | w = ww.rest(); check(w is not None, "missing episode number") |
508 | epi = getint(w) | |
08f08e7c | 509 | if not series.wantedp: return |
151b3c4f MW |
510 | series.ensure_season().ep_i = epi |
511 | ||
512 | elif cmd == "iso": | |
08f08e7c | 513 | series = me._opts_series(cmd, opts) |
151b3c4f | 514 | fn = ww.rest(); check(fn is not None, "missing filename") |
08f08e7c MW |
515 | if not series.wantedp: return |
516 | if fn == "-": forget(me._isos, series.name) | |
151b3c4f MW |
517 | else: |
518 | check(OS.path.exists(OS.path.join(ROOT, fn)), | |
519 | "iso file `%s' not found" % fn) | |
08f08e7c | 520 | me._isos[series.name] = VideoDisc(fn) |
151b3c4f MW |
521 | |
522 | elif cmd == "vdir": | |
08f08e7c | 523 | series = me._opts_series(cmd, opts) |
151b3c4f | 524 | dir = ww.rest(); check(dir is not None, "missing directory") |
08f08e7c MW |
525 | if not series.wantedp: return |
526 | if dir == "-": forget(me._vdirs, series.name) | |
527 | else: me._vdirs[series.name] = VideoDir(dir) | |
151b3c4f MW |
528 | |
529 | elif cmd == "adir": | |
08f08e7c | 530 | series = me._opts_series(cmd, opts) |
151b3c4f | 531 | dir = ww.rest(); check(dir is not None, "missing directory") |
08f08e7c MW |
532 | if not series.wantedp: return |
533 | if dir == "-": forget(me._audirs, series.name) | |
534 | else: me._audirs[series.name] = AudioDir(dir) | |
04a05f7f | 535 | |
0c4ca4f3 | 536 | elif cmd == "displaced": |
08f08e7c | 537 | series = me._opts_series(cmd, opts) |
0c4ca4f3 | 538 | w = ww.rest(); check(w is not None, "missing count"); n = getint(w) |
08f08e7c | 539 | src = me._auto_epsrc(series) |
0c4ca4f3 | 540 | src.nuses += n |
151b3c4f MW |
541 | else: |
542 | raise ExpectedError("unknown command `%s'" % cmd) | |
543 | ||
544 | def _process_episode(me, ww): | |
545 | ||
546 | opts = ww.nextword(); check(opts is not None, "missing title/options") | |
0411af2c | 547 | ti = None; sname = None; neps = 1; epi = None; loch = hich = None |
151b3c4f MW |
548 | for k, v in me._keyvals(opts): |
549 | if k is None: | |
550 | if v.isdigit(): ti = int(v) | |
551 | elif v == "-": ti = "-" | |
552 | else: sname = v | |
553 | elif k == "s": sname = v | |
554 | elif k == "n": neps = getint(v) | |
555 | elif k == "ep": epi = getint(v) | |
0411af2c MW |
556 | elif k == "ch": |
557 | try: sep = v.index("-") | |
558 | except ValueError: loch, hich = getint(v), None | |
559 | else: loch, hich = getint(v[:sep]), getint(v[sep + 1:]) + 1 | |
151b3c4f MW |
560 | else: raise ExpectedError("unknown episode option `%s'" % k) |
561 | check(ti is not None, "missing title number") | |
562 | series = me._get_series(sname) | |
563 | me._cur_chapter = None | |
564 | ||
565 | title = ww.rest() | |
08f08e7c | 566 | if not series.wantedp: return |
151b3c4f MW |
567 | season = series.ensure_season() |
568 | if epi is None: epi = season.ep_i | |
569 | ||
570 | if ti == "-": | |
571 | check(season.implicitp, "audio source, but explicit season") | |
08f08e7c MW |
572 | dir = lookup(me._audirs, series.name, |
573 | "no title, and no audio directory") | |
151b3c4f MW |
574 | src = lookup(dir.episodes, season.ep_i, |
575 | "episode %d not found in audio dir `%s'" % (epi, dir.dir)) | |
04a05f7f | 576 | |
151b3c4f | 577 | else: |
08f08e7c MW |
578 | try: src = me._isos[series.name] |
579 | except KeyError: src = me._auto_epsrc(series) | |
151b3c4f | 580 | |
0411af2c | 581 | episode = season.add_episode(epi, neps, title, src, ti, loch, hich) |
151b3c4f MW |
582 | me._pl.add_episode(episode) |
583 | me._cur_episode = episode | |
584 | ||
585 | def _process_chapter(me, ww): | |
586 | check(me._cur_episode is not None, "no current episode") | |
587 | check(me._cur_episode.source.CHAPTERP, | |
588 | "episode source doesn't allow chapters") | |
589 | if me._chaptersp: | |
590 | if me._cur_chapter is None: i = 1 | |
591 | else: i = me._cur_chapter.i + 1 | |
592 | me._cur_chapter = me._cur_episode.add_chapter(ww.rest(), i) | |
593 | ||
594 | def parse_file(me, fn): | |
595 | with location(FileLocation(fn, 0)) as floc: | |
596 | with open(fn, "r") as f: | |
597 | for line in f: | |
598 | floc.stepline() | |
599 | sline = line.lstrip() | |
600 | if sline == "" or sline.startswith(";"): continue | |
601 | ||
602 | if line.startswith("!"): me._process_cmd(Words(line[1:])) | |
603 | elif not line[0].isspace(): me._process_episode(Words(line)) | |
604 | else: me._process_chapter(Words(line)) | |
605 | me._pl.done_season() | |
606 | ||
607 | def done(me): | |
608 | discs = set() | |
609 | for name, vdir in me._vdirs.items(): | |
08f08e7c | 610 | if not me._series[name].wantedp: continue |
151b3c4f MW |
611 | for s in vdir.seasons.values(): |
612 | for d in s.episodes.values(): | |
613 | discs.add(d) | |
614 | for adir in me._audirs.values(): | |
615 | for d in adir.episodes.values(): | |
b092d511 | 616 | discs.add(d) |
151b3c4f MW |
617 | for d in sorted(discs, key = lambda d: d.fn): |
618 | if d.neps is not None and d.neps != d.nuses: | |
619 | raise ExpectedError("disc `%s' has %d episodes, used %d times" % | |
620 | (d.fn, d.neps, d.nuses)) | |
621 | return me._pl | |
04a05f7f MW |
622 | |
623 | ROOT = "/mnt/dvd/archive/" | |
624 | ||
151b3c4f MW |
625 | op = OP.OptionParser \ |
626 | (usage = "%prog [-c] [-s SERIES] EPLS", | |
627 | description = "Generate M3U playlists from an episode list.") | |
628 | op.add_option("-c", "--chapters", | |
629 | dest = "chaptersp", action = "store_true", default = False, | |
630 | help = "Output individual chapter names") | |
631 | op.add_option("-s", "--series", | |
632 | dest = "series", type = "str", default = None, | |
633 | help = "Output only the listed SERIES (comma-separated)") | |
634 | opts, argv = op.parse_args() | |
635 | if len(argv) != 1: op.print_usage(file = SYS.stderr); SYS.exit(2) | |
636 | if opts.series is None: | |
637 | series_wanted = None | |
638 | else: | |
639 | series_wanted = set() | |
640 | for name in opts.series.split(","): series_wanted.add(name) | |
04a05f7f | 641 | try: |
151b3c4f MW |
642 | ep = EpisodeListParser(series_wanted, opts.chaptersp) |
643 | ep.parse_file(argv[0]) | |
644 | pl = ep.done() | |
645 | pl.write(SYS.stdout) | |
04a05f7f MW |
646 | except (ExpectedError, IOError, OSError) as e: |
647 | LOC.report(e) | |
648 | SYS.exit(2) |