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 MW |
151 | |
152 | def some_group(m, *gg): | |
153 | for g in gg: | |
154 | s = m.group(g) | |
155 | if s is not None: return s | |
156 | return None | |
157 | ||
158 | class VideoDir (object): | |
159 | ||
9fc467bb | 160 | _R_ISO_PRE = RX.compile(r""" ^ |
35ecb6eb MW |
161 | (?: S (?P<si> \d+) |
162 | (?: \. \ (?P<st> .*) — (?: D \d+ \. \ )? | | |
163 | D \d+ \. \ | | |
164 | (?= E \d+ \. \ ) | | |
165 | \. \ ) | | |
9b82ff07 | 166 | (?P<epnum> \d+) \. \ ) |
35ecb6eb MW |
167 | (?: (?P<eplist> |
168 | (?: S \d+ \ )? E \d+ (?: – \d+)? | |
169 | (?: , \ (?: S \d+ \ )? E \d+ (?: – \d+)?)*) | | |
9b82ff07 MW |
170 | (?P<epname> E \d+) \. \ .* | |
171 | .*) | |
04a05f7f MW |
172 | \. iso $ |
173 | """, RX.X) | |
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 MW |
185 | seasons = {} |
186 | for fn in fns: | |
187 | path = OS.path.join(dir, fn) | |
188 | if not fn.endswith(".iso"): continue | |
189 | m = me._R_ISO_PRE.match(fn) | |
065a5db6 | 190 | if not m: |
3ee2c072 | 191 | #print(";; `%s' ignored (regex mismatch)" % path, file = SYS.stderr) |
065a5db6 | 192 | continue |
04a05f7f | 193 | |
6b5cec73 | 194 | i = filter(m.group("si"), int) |
04a05f7f | 195 | stitle = m.group("st") |
6b5cec73 MW |
196 | check(i is not None or stitle is None, |
197 | "explicit season title without number in `%s'" % fn) | |
198 | if i is not None: | |
199 | if season is None or i != season.i: | |
200 | check(season is None or i == season.i + 1, | |
201 | "season %d /= %d" % | |
202 | (i, season is None and -1 or season.i + 1)) | |
203 | check(i not in seasons, "season %d already seen" % i) | |
204 | seasons[i] = season = VideoSeason(i, stitle) | |
205 | else: | |
206 | check(stitle == season.title, | |
207 | "season title `%s' /= `%s'" % (stitle, season.title)) | |
04a05f7f | 208 | |
32cd109c | 209 | disc = VideoDisc(path) |
6b5cec73 | 210 | ts = season |
32cd109c | 211 | any, bad = False, False |
35ecb6eb | 212 | epname = m.group("epname") |
9b82ff07 MW |
213 | epexpr = m.group("eplist") |
214 | epnum = m.group("epnum") | |
35ecb6eb | 215 | if epname is not None: eplist = [epname] |
9b82ff07 MW |
216 | elif epexpr is not None: eplist = epexpr.split(", ") |
217 | elif epnum is not None: eplist = ["E" + epnum] | |
218 | else: continue | |
3ee2c072 | 219 | #print(";; `%s'" % path, file = SYS.stderr) |
35ecb6eb | 220 | for eprange in eplist: |
04a05f7f | 221 | mm = me._R_ISO_EP.match(eprange) |
3ee2c072 MW |
222 | if mm is None: |
223 | #print(";;\t`%s'?" % eprange, file = SYS.stderr) | |
224 | bad = True; continue | |
225 | if not any: any = True | |
6b5cec73 MW |
226 | i = filter(mm.group("si"), int) |
227 | if i is not None: | |
228 | try: ts = seasons[i] | |
229 | except KeyError: ts = seasons[i] = VideoSeason(i, None) | |
230 | if ts is None: | |
231 | ts = season = seasons[1] = VideoSeason(1, None) | |
04a05f7f MW |
232 | start = filter(mm.group("ei"), int) |
233 | end = filter(mm.group("ej"), int, start) | |
32cd109c | 234 | for k in range(start, end + 1): |
6b5cec73 | 235 | ts.set_episode_disc(k, disc) |
065a5db6 | 236 | #print(";;\tepisode %d.%d" % (ts.i, k), file = SYS.stderr) |
3ee2c072 MW |
237 | if not any: |
238 | #print(";;\tignored" % path, file = SYS.stderr) | |
239 | pass | |
240 | elif bad: | |
241 | raise ExpectedError("bad ep list in `%s'", fn) | |
04a05f7f MW |
242 | me.seasons = seasons |
243 | ||
244 | class AudioDisc (Source): | |
fbac3340 | 245 | PREFIX = "file://" |
04a05f7f MW |
246 | TITLEP = CHAPTERP = False |
247 | ||
248 | class AudioEpisode (Source): | |
fbac3340 | 249 | PREFIX = "file://" |
04a05f7f MW |
250 | TITLEP = CHAPTERP = False |
251 | def __init__(me, fn, i, *args, **kw): | |
252 | super().__init__(fn, *args, **kw) | |
253 | me.i = i | |
254 | ||
255 | class AudioDir (object): | |
256 | ||
9fc467bb | 257 | _R_FLAC = RX.compile(r""" ^ |
04a05f7f MW |
258 | E (\d+) |
259 | (?: \. \ (.*))? | |
260 | \. flac $ | |
261 | """, RX.X) | |
262 | ||
263 | def __init__(me, dir): | |
b092d511 | 264 | me.dir = dir |
04a05f7f MW |
265 | fns = OS.listdir(OS.path.join(ROOT, dir)) |
266 | fns.sort() | |
267 | episodes = {} | |
268 | last_i = 0 | |
269 | for fn in fns: | |
270 | path = OS.path.join(dir, fn) | |
271 | if not fn.endswith(".flac"): continue | |
272 | m = me._R_FLAC.match(fn) | |
273 | if not m: continue | |
274 | i = filter(m.group(1), int) | |
275 | etitle = m.group(2) | |
276 | check(i == last_i + 1, "episode %d /= %d" % (i, last_i + 1)) | |
277 | episodes[i] = AudioEpisode(path, i) | |
278 | last_i = i | |
279 | me.episodes = episodes | |
280 | ||
281 | class Chapter (object): | |
282 | def __init__(me, episode, title, i): | |
283 | me.title, me.i = title, i | |
fd3b422f | 284 | me.url = episode.source.url(episode.tno, i, i + 1) |
04a05f7f MW |
285 | |
286 | class Episode (object): | |
0411af2c MW |
287 | def __init__(me, season, i, neps, title, src, tno = None, |
288 | startch = None, endch = None): | |
04a05f7f MW |
289 | me.season = season |
290 | me.i, me.neps, me.title = i, neps, title | |
291 | me.chapters = [] | |
292 | me.source, me.tno = src, tno | |
0411af2c | 293 | me.url = src.url(tno, startch, endch) |
04a05f7f MW |
294 | def add_chapter(me, title, j): |
295 | ch = Chapter(me, title, j) | |
296 | me.chapters.append(ch) | |
297 | return ch | |
298 | def label(me): | |
299 | return me.season._eplabel(me.i, me.neps, me.title) | |
300 | ||
151b3c4f MW |
301 | class BaseSeason (object): |
302 | def __init__(me, series, implicitp = False): | |
303 | me.series = series | |
04a05f7f | 304 | me.episodes = [] |
151b3c4f MW |
305 | me.implicitp = implicitp |
306 | me.ep_i, episodes = 1, [] | |
0411af2c MW |
307 | def add_episode(me, j, neps, title, src, tno, startch, endch): |
308 | ep = Episode(me, j, neps, title, src, tno, startch, endch) | |
04a05f7f | 309 | me.episodes.append(ep) |
151b3c4f | 310 | src.nuses += neps; me.ep_i += neps |
04a05f7f | 311 | return ep |
4a25b86c MW |
312 | def _epnames(me, i, neps): |
313 | playlist = me.series.playlist | |
314 | if neps == 1: return playlist.epname, "%d" % i | |
315 | elif neps == 2: return playlist.epnames, "%d, %d" % (i, i + 1) | |
316 | else: return playlist.epnames, "%d–%d" % (i, i + neps - 1) | |
151b3c4f MW |
317 | |
318 | class Season (BaseSeason): | |
319 | def __init__(me, series, title, i, *args, **kw): | |
320 | super().__init__(series, *args, **kw) | |
321 | me.title, me.i = title, i | |
04a05f7f | 322 | def _eplabel(me, i, neps, title): |
4a25b86c | 323 | epname, epn = me._epnames(i, neps) |
04a05f7f | 324 | if title is None: |
151b3c4f MW |
325 | if me.implicitp: label = "%s %s" % (epname, epn) |
326 | elif me.title is None: label = "%s %d.%s" % (epname, me.i, epn) | |
327 | else: label = "%s—%s %s" % (me.title, epname, epn) | |
04a05f7f | 328 | else: |
151b3c4f MW |
329 | if me.implicitp: label = "%s. %s" % (epn, title) |
330 | elif me.title is None: label = "%d.%s. %s" % (me.i, epn, title) | |
331 | else: label = "%s—%s. %s" % (me.title, epn, title) | |
332 | return label | |
04a05f7f | 333 | |
151b3c4f | 334 | class MovieSeason (BaseSeason): |
c3538df6 MW |
335 | def __init__(me, series, title, *args, **kw): |
336 | super().__init__(series, *args, **kw) | |
337 | me.title = title | |
5ca4c92e | 338 | me.i = None |
0411af2c | 339 | def add_episode(me, j, neps, title, src, tno, startch, endch): |
c3538df6 MW |
340 | if me.title is None and title is None: |
341 | raise ExpectedError("movie or movie season must have a title") | |
0411af2c | 342 | return super().add_episode(j, neps, title, src, tno, startch, endch) |
c3538df6 MW |
343 | def _eplabel(me, i, neps, title): |
344 | if me.title is None: | |
345 | label = title | |
346 | elif title is None: | |
347 | epname, epn = me._epnames(i, neps) | |
348 | label = "%s—%s %s" % (me.title, epname, epn) | |
349 | else: | |
350 | label = "%s—%s" % (me.title, title) | |
351 | return label | |
04a05f7f | 352 | |
151b3c4f | 353 | class Series (object): |
08f08e7c | 354 | def __init__(me, playlist, name, title = None, wantedp = True): |
151b3c4f | 355 | me.playlist = playlist |
08f08e7c | 356 | me.name, me.title = name, title |
151b3c4f | 357 | me.cur_season = None |
08f08e7c | 358 | me.wantedp = wantedp |
151b3c4f MW |
359 | def _add_season(me, season): |
360 | me.cur_season = season | |
361 | def add_season(me, title, i, implicitp = False): | |
362 | me._add_season(Season(me, title, i, implicitp)) | |
c3538df6 MW |
363 | def add_movies(me, title = None): |
364 | me._add_season(MovieSeason(me, title)) | |
151b3c4f MW |
365 | def ensure_season(me): |
366 | if me.cur_season is None: me.add_season(None, 1, implicitp = True) | |
367 | return me.cur_season | |
368 | def end_season(me): | |
369 | me.cur_season = None | |
04a05f7f | 370 | |
151b3c4f | 371 | class Playlist (object): |
04a05f7f MW |
372 | def __init__(me): |
373 | me.seasons = [] | |
151b3c4f | 374 | me.episodes = [] |
04a05f7f | 375 | me.epname, me.epnames = "Episode", "Episodes" |
151b3c4f MW |
376 | me.nseries = 0 |
377 | def add_episode(me, episode): | |
378 | me.episodes.append(episode) | |
379 | def done_season(me): | |
380 | if me.episodes: | |
381 | me.seasons.append(me.episodes) | |
382 | me.episodes = [] | |
04a05f7f MW |
383 | def write(me, f): |
384 | f.write("#EXTM3U\n") | |
385 | for season in me.seasons: | |
386 | f.write("\n") | |
151b3c4f MW |
387 | for ep in season: |
388 | label = ep.label() | |
389 | if me.nseries > 1: label = ep.season.series.title + " " + label | |
04a05f7f | 390 | if not ep.chapters: |
151b3c4f | 391 | f.write("#EXTINF:0,,%s\n%s\n" % (label, ep.url)) |
04a05f7f MW |
392 | else: |
393 | for ch in ep.chapters: | |
394 | f.write("#EXTINF:0,,%s: %s\n%s\n" % | |
151b3c4f MW |
395 | (label, ch.title, ch.url)) |
396 | ||
397 | MODE_UNSET = 0 | |
398 | MODE_SINGLE = 1 | |
399 | MODE_MULTI = 2 | |
400 | ||
401 | class EpisodeListParser (object): | |
402 | ||
403 | def __init__(me, series_wanted = None, chapters_wanted_p = False): | |
404 | me._pl = Playlist() | |
405 | me._cur_episode = me._cur_chapter = None | |
406 | me._series = {}; me._vdirs = {}; me._audirs = {}; me._isos = {} | |
407 | me._series_wanted = series_wanted | |
408 | me._chaptersp = chapters_wanted_p | |
409 | if series_wanted is None: me._mode = MODE_UNSET | |
410 | else: me._mode = MODE_MULTI | |
411 | ||
412 | def _bad_keyval(me, cmd, k, v): | |
413 | raise ExpectedError("invalid `!%s' option `%s'" % | |
414 | (cmd, v if k is None else k)) | |
415 | ||
416 | def _keyvals(me, opts): | |
417 | if opts is not None: | |
418 | for kv in opts.split(","): | |
419 | try: sep = kv.index("=") | |
420 | except ValueError: yield None, kv | |
421 | else: yield kv[:sep], kv[sep + 1:] | |
422 | ||
423 | def _set_mode(me, mode): | |
424 | if me._mode == MODE_UNSET: | |
425 | me._mode = mode | |
426 | elif me._mode != mode: | |
427 | raise ExpectedError("inconsistent single-/multi-series usage") | |
428 | ||
429 | def _get_series(me, name): | |
430 | if name is None: | |
431 | me._set_mode(MODE_SINGLE) | |
432 | try: series = me._series[None] | |
433 | except KeyError: | |
08f08e7c | 434 | series = me._series[None] = Series(me._pl, None) |
151b3c4f MW |
435 | me._pl.nseries += 1 |
436 | else: | |
437 | me._set_mode(MODE_MULTI) | |
438 | series = lookup(me._series, name, "unknown series `%s'" % name) | |
439 | return series | |
440 | ||
441 | def _opts_series(me, cmd, opts): | |
442 | name = None | |
443 | for k, v in me._keyvals(opts): | |
444 | if k is None: name = v | |
445 | else: me._bad_keyval(cmd, k, v) | |
08f08e7c | 446 | return me._get_series(name) |
151b3c4f | 447 | |
08f08e7c MW |
448 | def _auto_epsrc(me, series): |
449 | dir = lookup(me._vdirs, series.name, "no active video directory") | |
450 | season = series.ensure_season() | |
451 | check(season.i is not None, "must use explicit iso for movie seasons") | |
452 | vseason = lookup(dir.seasons, season.i, | |
453 | "season %d not found in video dir `%s'" % | |
454 | (season.i, dir.dir)) | |
455 | src = lookup(vseason.episodes, season.ep_i, | |
456 | "episode %d.%d not found in video dir `%s'" % | |
457 | (season.i, season.ep_i, dir.dir)) | |
458 | return src | |
151b3c4f MW |
459 | |
460 | def _process_cmd(me, ww): | |
461 | ||
462 | cmd = ww.nextword(); check(cmd is not None, "missing command") | |
463 | try: sep = cmd.index(":") | |
464 | except ValueError: opts = None | |
465 | else: cmd, opts = cmd[:sep], cmd[sep + 1:] | |
466 | ||
467 | if cmd == "series": | |
468 | name = None | |
469 | for k, v in me._keyvals(opts): | |
470 | if k is None: name = v | |
471 | else: me._bad_keyval(cmd, k, v) | |
472 | check(name is not None, "missing series name") | |
473 | check(name not in me._series, "series `%s' already defined" % name) | |
474 | title = ww.rest(); check(title is not None, "missing title") | |
475 | me._set_mode(MODE_MULTI) | |
08f08e7c MW |
476 | me._series[name] = series = Series(me._pl, name, title, |
477 | me._series_wanted is None or | |
478 | name in me._series_wanted) | |
479 | if series.wantedp: me._pl.nseries += 1 | |
151b3c4f MW |
480 | |
481 | elif cmd == "season": | |
08f08e7c | 482 | series = me._opts_series(cmd, opts) |
151b3c4f MW |
483 | w = ww.nextword(); |
484 | check(w is not None, "missing season number") | |
485 | if w == "-": | |
08f08e7c | 486 | if not series.wantedp: return |
c3538df6 | 487 | series.add_movies(ww.rest()) |
151b3c4f MW |
488 | else: |
489 | title = ww.rest(); i = getint(w) | |
08f08e7c | 490 | if not series.wantedp: return |
151b3c4f MW |
491 | series.add_season(ww.rest(), getint(w), implicitp = False) |
492 | me._cur_episode = me._cur_chapter = None | |
493 | me._pl.done_season() | |
494 | ||
495 | elif cmd == "epname": | |
496 | for k, v in me._keyvals(opts): me._bad_keyval("epname", k, v) | |
497 | name = ww.rest(); check(name is not None, "missing episode name") | |
498 | try: sep = name.index(",") | |
499 | except ValueError: names = name + "s" | |
500 | else: name, names = name[:sep], name[sep + 1:] | |
501 | me._pl.epname, me._pl.epnames = name, names | |
502 | ||
503 | elif cmd == "epno": | |
08f08e7c | 504 | series = me._opts_series(cmd, opts) |
151b3c4f MW |
505 | w = ww.rest(); check(w is not None, "missing episode number") |
506 | epi = getint(w) | |
08f08e7c | 507 | if not series.wantedp: return |
151b3c4f MW |
508 | series.ensure_season().ep_i = epi |
509 | ||
510 | elif cmd == "iso": | |
08f08e7c | 511 | series = me._opts_series(cmd, opts) |
151b3c4f | 512 | fn = ww.rest(); check(fn is not None, "missing filename") |
08f08e7c MW |
513 | if not series.wantedp: return |
514 | if fn == "-": forget(me._isos, series.name) | |
151b3c4f MW |
515 | else: |
516 | check(OS.path.exists(OS.path.join(ROOT, fn)), | |
517 | "iso file `%s' not found" % fn) | |
08f08e7c | 518 | me._isos[series.name] = VideoDisc(fn) |
151b3c4f MW |
519 | |
520 | elif cmd == "vdir": | |
08f08e7c | 521 | series = me._opts_series(cmd, opts) |
151b3c4f | 522 | dir = ww.rest(); check(dir is not None, "missing directory") |
08f08e7c MW |
523 | if not series.wantedp: return |
524 | if dir == "-": forget(me._vdirs, series.name) | |
525 | else: me._vdirs[series.name] = VideoDir(dir) | |
151b3c4f MW |
526 | |
527 | elif cmd == "adir": | |
08f08e7c | 528 | series = me._opts_series(cmd, opts) |
151b3c4f | 529 | dir = ww.rest(); check(dir is not None, "missing directory") |
08f08e7c MW |
530 | if not series.wantedp: return |
531 | if dir == "-": forget(me._audirs, series.name) | |
532 | else: me._audirs[series.name] = AudioDir(dir) | |
04a05f7f | 533 | |
0c4ca4f3 | 534 | elif cmd == "displaced": |
08f08e7c | 535 | series = me._opts_series(cmd, opts) |
0c4ca4f3 | 536 | w = ww.rest(); check(w is not None, "missing count"); n = getint(w) |
08f08e7c | 537 | src = me._auto_epsrc(series) |
0c4ca4f3 | 538 | src.nuses += n |
151b3c4f MW |
539 | else: |
540 | raise ExpectedError("unknown command `%s'" % cmd) | |
541 | ||
542 | def _process_episode(me, ww): | |
543 | ||
544 | opts = ww.nextword(); check(opts is not None, "missing title/options") | |
0411af2c | 545 | ti = None; sname = None; neps = 1; epi = None; loch = hich = None |
151b3c4f MW |
546 | for k, v in me._keyvals(opts): |
547 | if k is None: | |
548 | if v.isdigit(): ti = int(v) | |
549 | elif v == "-": ti = "-" | |
550 | else: sname = v | |
551 | elif k == "s": sname = v | |
552 | elif k == "n": neps = getint(v) | |
553 | elif k == "ep": epi = getint(v) | |
0411af2c MW |
554 | elif k == "ch": |
555 | try: sep = v.index("-") | |
556 | except ValueError: loch, hich = getint(v), None | |
557 | else: loch, hich = getint(v[:sep]), getint(v[sep + 1:]) + 1 | |
151b3c4f MW |
558 | else: raise ExpectedError("unknown episode option `%s'" % k) |
559 | check(ti is not None, "missing title number") | |
560 | series = me._get_series(sname) | |
561 | me._cur_chapter = None | |
562 | ||
563 | title = ww.rest() | |
08f08e7c | 564 | if not series.wantedp: return |
151b3c4f MW |
565 | season = series.ensure_season() |
566 | if epi is None: epi = season.ep_i | |
567 | ||
568 | if ti == "-": | |
569 | check(season.implicitp, "audio source, but explicit season") | |
08f08e7c MW |
570 | dir = lookup(me._audirs, series.name, |
571 | "no title, and no audio directory") | |
151b3c4f MW |
572 | src = lookup(dir.episodes, season.ep_i, |
573 | "episode %d not found in audio dir `%s'" % (epi, dir.dir)) | |
04a05f7f | 574 | |
151b3c4f | 575 | else: |
08f08e7c MW |
576 | try: src = me._isos[series.name] |
577 | except KeyError: src = me._auto_epsrc(series) | |
151b3c4f | 578 | |
0411af2c | 579 | episode = season.add_episode(epi, neps, title, src, ti, loch, hich) |
151b3c4f MW |
580 | me._pl.add_episode(episode) |
581 | me._cur_episode = episode | |
582 | ||
583 | def _process_chapter(me, ww): | |
584 | check(me._cur_episode is not None, "no current episode") | |
585 | check(me._cur_episode.source.CHAPTERP, | |
586 | "episode source doesn't allow chapters") | |
587 | if me._chaptersp: | |
588 | if me._cur_chapter is None: i = 1 | |
589 | else: i = me._cur_chapter.i + 1 | |
590 | me._cur_chapter = me._cur_episode.add_chapter(ww.rest(), i) | |
591 | ||
592 | def parse_file(me, fn): | |
593 | with location(FileLocation(fn, 0)) as floc: | |
594 | with open(fn, "r") as f: | |
595 | for line in f: | |
596 | floc.stepline() | |
597 | sline = line.lstrip() | |
598 | if sline == "" or sline.startswith(";"): continue | |
599 | ||
600 | if line.startswith("!"): me._process_cmd(Words(line[1:])) | |
601 | elif not line[0].isspace(): me._process_episode(Words(line)) | |
602 | else: me._process_chapter(Words(line)) | |
603 | me._pl.done_season() | |
604 | ||
605 | def done(me): | |
606 | discs = set() | |
607 | for name, vdir in me._vdirs.items(): | |
08f08e7c | 608 | if not me._series[name].wantedp: continue |
151b3c4f MW |
609 | for s in vdir.seasons.values(): |
610 | for d in s.episodes.values(): | |
611 | discs.add(d) | |
612 | for adir in me._audirs.values(): | |
613 | for d in adir.episodes.values(): | |
b092d511 | 614 | discs.add(d) |
151b3c4f MW |
615 | for d in sorted(discs, key = lambda d: d.fn): |
616 | if d.neps is not None and d.neps != d.nuses: | |
617 | raise ExpectedError("disc `%s' has %d episodes, used %d times" % | |
618 | (d.fn, d.neps, d.nuses)) | |
619 | return me._pl | |
04a05f7f MW |
620 | |
621 | ROOT = "/mnt/dvd/archive/" | |
622 | ||
151b3c4f MW |
623 | op = OP.OptionParser \ |
624 | (usage = "%prog [-c] [-s SERIES] EPLS", | |
625 | description = "Generate M3U playlists from an episode list.") | |
626 | op.add_option("-c", "--chapters", | |
627 | dest = "chaptersp", action = "store_true", default = False, | |
628 | help = "Output individual chapter names") | |
629 | op.add_option("-s", "--series", | |
630 | dest = "series", type = "str", default = None, | |
631 | help = "Output only the listed SERIES (comma-separated)") | |
632 | opts, argv = op.parse_args() | |
633 | if len(argv) != 1: op.print_usage(file = SYS.stderr); SYS.exit(2) | |
634 | if opts.series is None: | |
635 | series_wanted = None | |
636 | else: | |
637 | series_wanted = set() | |
638 | for name in opts.series.split(","): series_wanted.add(name) | |
04a05f7f | 639 | try: |
151b3c4f MW |
640 | ep = EpisodeListParser(series_wanted, opts.chaptersp) |
641 | ep.parse_file(argv[0]) | |
642 | pl = ep.done() | |
643 | pl.write(SYS.stdout) | |
04a05f7f MW |
644 | except (ExpectedError, IOError, OSError) as e: |
645 | LOC.report(e) | |
646 | SYS.exit(2) |