Commit | Line | Data |
---|---|---|
04a05f7f MW |
1 | #! /usr/bin/python3 |
2 | ### -*- mode: python; coding: utf-8 -*- | |
3 | ||
4 | from contextlib import contextmanager | |
5 | import os as OS | |
6 | import re as RX | |
7 | import sys as SYS | |
8 | ||
9 | class ExpectedError (Exception): pass | |
10 | ||
11 | @contextmanager | |
12 | def location(loc): | |
13 | global LOC | |
14 | old, LOC = LOC, loc | |
15 | yield loc | |
16 | LOC = old | |
17 | ||
18 | def filter(value, func = None, dflt = None): | |
19 | if value is None: return dflt | |
20 | elif func is None: return value | |
21 | else: return func(value) | |
22 | ||
23 | def check(cond, msg): | |
24 | if not cond: raise ExpectedError(msg) | |
25 | ||
26 | def getint(s): | |
27 | if not s.isdigit(): raise ExpectedError("bad integer `%s'" % s) | |
28 | return int(s) | |
29 | ||
30 | class Words (object): | |
31 | def __init__(me, s): | |
32 | me._s = s | |
33 | me._i, me._n = 0, len(s) | |
34 | def _wordstart(me): | |
35 | s, i, n = me._s, me._i, me._n | |
36 | while i < n: | |
37 | if not s[i].isspace(): return i | |
38 | i += 1 | |
39 | return -1 | |
40 | def nextword(me): | |
41 | s, n = me._s, me._n | |
42 | begin = i = me._wordstart() | |
43 | if begin < 0: return None | |
44 | while i < n and not s[i].isspace(): i += 1 | |
45 | me._i = i | |
46 | return s[begin:i] | |
47 | def rest(me): | |
48 | s, n = me._s, me._n | |
49 | begin = me._wordstart() | |
50 | if begin < 0: return None | |
51 | else: return s[begin:].rstrip() | |
52 | ||
53 | URL_SAFE_P = 256*[False] | |
54 | for ch in \ | |
55 | b"ABCDEFGHIJKLMNOPQRSTUVWXYZ" \ | |
56 | b"abcdefghijklmnopqrstuvwxyz" \ | |
57 | b"0123456789" b"!$%-.,/": | |
58 | URL_SAFE_P[ch] = True | |
59 | def urlencode(s): | |
60 | return "".join((URL_SAFE_P[ch] and chr(ch) or "%%%02x" % ch | |
61 | for ch in s.encode("UTF-8"))) | |
62 | ||
63 | PROG = OS.path.basename(SYS.argv[0]) | |
64 | ||
65 | class BaseLocation (object): | |
66 | def report(me, exc): | |
67 | SYS.stderr.write("%s: %s%s\n" % (PROG, me._loc(), exc)) | |
68 | ||
69 | class DummyLocation (BaseLocation): | |
70 | def _loc(me): return "" | |
71 | ||
72 | class FileLocation (BaseLocation): | |
73 | def __init__(me, fn, lno = 1): me._fn, me._lno = fn, lno | |
74 | def _loc(me): return "%s:%d: " % (me._fn, me._lno) | |
75 | def stepline(me): me._lno += 1 | |
76 | ||
77 | LOC = DummyLocation() | |
78 | ||
79 | class Source (object): | |
80 | PREFIX = "" | |
81 | TITLEP = CHAPTERP = False | |
82 | def __init__(me, fn): | |
83 | me.fn = fn | |
b092d511 MW |
84 | me.neps = None |
85 | me.used_titles = dict() | |
86 | me.used_chapters = set() | |
87 | me.nuses = 0 | |
04a05f7f MW |
88 | def url(me, title = None, chapter = None): |
89 | if title is None: | |
90 | if me.TITLEP: raise ExpectedError("missing title number") | |
91 | if chapter is not None: | |
92 | raise ExpectedError("can't specify chapter without title") | |
93 | suffix = "" | |
94 | elif not me.TITLEP: | |
95 | raise ExpectedError("can't specify title with `%s'" % me.fn) | |
96 | elif chapter is None: | |
97 | suffix = "#%d" % title | |
98 | elif not me.CHAPTERP: | |
99 | raise ExpectedError("can't specify chapter with `%s'" % me.fn) | |
100 | else: | |
101 | suffix = "#%d:%d-%d:%d" % (title, chapter, title, chapter) | |
b092d511 MW |
102 | if chapter is not None: key, set = (title, chapter), me.used_chapters |
103 | else: key, set = title, me.used_titles | |
104 | if key in set: | |
105 | if title is None: | |
106 | raise ExpectedError("`%s' already used" % me.fn) | |
107 | elif chapter is None: | |
108 | raise ExpectedError("`%s' title %d already used" % (me.fn, title)) | |
109 | else: | |
110 | raise ExpectedError("`%s' title %d chapter %d already used" % | |
111 | (me.fn, title, chapter)) | |
112 | if chapter is not None: me.used_chapters.add((title, chapter)) | |
04a05f7f MW |
113 | return me.PREFIX + ROOT + urlencode(me.fn) + suffix |
114 | ||
115 | class VideoDisc (Source): | |
116 | PREFIX = "dvd://" | |
117 | TITLEP = CHAPTERP = True | |
118 | ||
b092d511 MW |
119 | def __init__(me, fn, *args, **kw): |
120 | super().__init__(fn, *args, **kw) | |
121 | me.neps = 0 | |
122 | ||
04a05f7f MW |
123 | class VideoSeason (object): |
124 | def __init__(me, i, title): | |
125 | me.i = i | |
126 | me.title = title | |
127 | me.episodes = {} | |
32cd109c MW |
128 | def set_episode_disc(me, i, disc): |
129 | if i in me.episodes: | |
130 | raise ExpectedError("season %d episode %d already taken" % (me.i, i)) | |
b092d511 | 131 | me.episodes[i] = disc; disc.neps += 1 |
04a05f7f MW |
132 | |
133 | def some_group(m, *gg): | |
134 | for g in gg: | |
135 | s = m.group(g) | |
136 | if s is not None: return s | |
137 | return None | |
138 | ||
139 | class VideoDir (object): | |
140 | ||
9fc467bb | 141 | _R_ISO_PRE = RX.compile(r""" ^ |
04a05f7f MW |
142 | (?: S (?P<si> \d+) (?: \. \ (?P<st> .*)—)? (?: D (?P<sdi> \d+))? | |
143 | (?P<di> \d+)) | |
144 | \. \ # | |
145 | (?P<eps> .*) | |
146 | \. iso $ | |
147 | """, RX.X) | |
148 | ||
9fc467bb | 149 | _R_ISO_EP = RX.compile(r""" ^ |
6b5cec73 | 150 | (?: S (?P<si> \d+) \ )? |
9fc467bb | 151 | E (?P<ei> \d+) (?: – (?P<ej> \d+))? $ |
04a05f7f MW |
152 | """, RX.X) |
153 | ||
154 | def __init__(me, dir): | |
b092d511 | 155 | me.dir = dir |
04a05f7f MW |
156 | fns = OS.listdir(OS.path.join(ROOT, dir)) |
157 | fns.sort() | |
6b5cec73 | 158 | season = None |
04a05f7f MW |
159 | seasons = {} |
160 | for fn in fns: | |
161 | path = OS.path.join(dir, fn) | |
162 | if not fn.endswith(".iso"): continue | |
163 | m = me._R_ISO_PRE.match(fn) | |
164 | if not m: continue | |
165 | ||
6b5cec73 | 166 | i = filter(m.group("si"), int) |
04a05f7f | 167 | stitle = m.group("st") |
6b5cec73 MW |
168 | check(i is not None or stitle is None, |
169 | "explicit season title without number in `%s'" % fn) | |
170 | if i is not None: | |
171 | if season is None or i != season.i: | |
172 | check(season is None or i == season.i + 1, | |
173 | "season %d /= %d" % | |
174 | (i, season is None and -1 or season.i + 1)) | |
175 | check(i not in seasons, "season %d already seen" % i) | |
176 | seasons[i] = season = VideoSeason(i, stitle) | |
177 | else: | |
178 | check(stitle == season.title, | |
179 | "season title `%s' /= `%s'" % (stitle, season.title)) | |
04a05f7f | 180 | |
32cd109c | 181 | disc = VideoDisc(path) |
6b5cec73 | 182 | ts = season |
32cd109c | 183 | any, bad = False, False |
04a05f7f MW |
184 | for eprange in m.group("eps").split(", "): |
185 | mm = me._R_ISO_EP.match(eprange) | |
186 | if mm is None: bad = True; continue | |
6b5cec73 MW |
187 | i = filter(mm.group("si"), int) |
188 | if i is not None: | |
189 | try: ts = seasons[i] | |
190 | except KeyError: ts = seasons[i] = VideoSeason(i, None) | |
191 | if ts is None: | |
192 | ts = season = seasons[1] = VideoSeason(1, None) | |
04a05f7f MW |
193 | start = filter(mm.group("ei"), int) |
194 | end = filter(mm.group("ej"), int, start) | |
32cd109c | 195 | for k in range(start, end + 1): |
6b5cec73 | 196 | ts.set_episode_disc(k, disc) |
32cd109c MW |
197 | any = True |
198 | if bad and any: | |
04a05f7f | 199 | raise ExpectedError("bad ep list in `%s'", fn) |
04a05f7f MW |
200 | me.seasons = seasons |
201 | ||
202 | class AudioDisc (Source): | |
fbac3340 | 203 | PREFIX = "file://" |
04a05f7f MW |
204 | TITLEP = CHAPTERP = False |
205 | ||
206 | class AudioEpisode (Source): | |
fbac3340 | 207 | PREFIX = "file://" |
04a05f7f MW |
208 | TITLEP = CHAPTERP = False |
209 | def __init__(me, fn, i, *args, **kw): | |
210 | super().__init__(fn, *args, **kw) | |
211 | me.i = i | |
212 | ||
213 | class AudioDir (object): | |
214 | ||
9fc467bb | 215 | _R_FLAC = RX.compile(r""" ^ |
04a05f7f MW |
216 | E (\d+) |
217 | (?: \. \ (.*))? | |
218 | \. flac $ | |
219 | """, RX.X) | |
220 | ||
221 | def __init__(me, dir): | |
b092d511 | 222 | me.dir = dir |
04a05f7f MW |
223 | fns = OS.listdir(OS.path.join(ROOT, dir)) |
224 | fns.sort() | |
225 | episodes = {} | |
226 | last_i = 0 | |
227 | for fn in fns: | |
228 | path = OS.path.join(dir, fn) | |
229 | if not fn.endswith(".flac"): continue | |
230 | m = me._R_FLAC.match(fn) | |
231 | if not m: continue | |
232 | i = filter(m.group(1), int) | |
233 | etitle = m.group(2) | |
234 | check(i == last_i + 1, "episode %d /= %d" % (i, last_i + 1)) | |
235 | episodes[i] = AudioEpisode(path, i) | |
236 | last_i = i | |
237 | me.episodes = episodes | |
238 | ||
239 | class Chapter (object): | |
240 | def __init__(me, episode, title, i): | |
241 | me.title, me.i = title, i | |
242 | me.url = episode.source.url(episode.tno, i) | |
243 | ||
244 | class Episode (object): | |
245 | def __init__(me, season, i, neps, title, src, tno = None): | |
246 | me.season = season | |
247 | me.i, me.neps, me.title = i, neps, title | |
248 | me.chapters = [] | |
249 | me.source, me.tno = src, tno | |
250 | me.url = src.url(tno) | |
251 | def add_chapter(me, title, j): | |
252 | ch = Chapter(me, title, j) | |
253 | me.chapters.append(ch) | |
254 | return ch | |
255 | def label(me): | |
256 | return me.season._eplabel(me.i, me.neps, me.title) | |
257 | ||
258 | class Season (object): | |
259 | def __init__(me, playlist, title, i, implicitp = False): | |
260 | me.playlist = playlist | |
261 | me.title, me.i = title, i | |
262 | me.implicitp = implicitp | |
263 | me.episodes = [] | |
264 | def add_episode(me, j, neps, title, src, tno): | |
265 | ep = Episode(me, j, neps, title, src, tno) | |
266 | me.episodes.append(ep) | |
267 | return ep | |
268 | def _eplabel(me, i, neps, title): | |
269 | if neps == 1: epname = me.playlist.epname; epn = "%d" % i | |
270 | elif neps == 2: epname = me.playlist.epnames; epn = "%d, %d" % (i, i + 1) | |
271 | else: epname = me.playlist.epnames; epn = "%d–%d" % (i, i + neps - 1) | |
272 | if title is None: | |
273 | if me.implicitp: return "%s %s" % (epname, epn) | |
274 | elif me.title is None: return "%s %d.%s" % (epname, me.i, epn) | |
275 | else: return "%s—%s %s" % (me.title, epname, epn) | |
276 | else: | |
277 | if me.implicitp: return "%s. %s" % (epn, title) | |
278 | elif me.title is None: return "%d.%s. %s" % (me.i, epn, title) | |
279 | else: return "%s—%s. %s" % (me.title, epn, title) | |
280 | ||
281 | class MovieSeason (object): | |
282 | def __init__(me, playlist): | |
283 | me.playlist = playlist | |
284 | me.i = -1 | |
285 | me.implicitp = False | |
286 | me.episodes = [] | |
287 | def add_episode(me, j, neps, title, src, tno): | |
288 | if title is None: raise ExpectedError("movie must have a title") | |
289 | ep = Episode(me, j, neps, title, src, tno) | |
290 | me.episodes.append(ep) | |
291 | return ep | |
292 | def _eplabel(me, i, epn, title): | |
293 | return title | |
294 | ||
295 | class Playlist (object): | |
296 | ||
297 | def __init__(me): | |
298 | me.seasons = [] | |
299 | me.epname, me.epnames = "Episode", "Episodes" | |
300 | ||
301 | def add_season(me, title, i, implicitp = False): | |
302 | season = Season(me, title, i, implicitp) | |
303 | me.seasons.append(season) | |
304 | return season | |
305 | ||
306 | def add_movies(me): | |
307 | season = MovieSeason(me) | |
308 | me.seasons.append(season) | |
309 | return season | |
310 | ||
311 | def write(me, f): | |
312 | f.write("#EXTM3U\n") | |
313 | for season in me.seasons: | |
314 | f.write("\n") | |
315 | for i, ep in enumerate(season.episodes, 1): | |
316 | if not ep.chapters: | |
317 | f.write("#EXTINF:0,,%s\n%s\n" % (ep.label(), ep.url)) | |
318 | else: | |
319 | for ch in ep.chapters: | |
320 | f.write("#EXTINF:0,,%s: %s\n%s\n" % | |
321 | (ep.label(), ch.title, ch.url)) | |
322 | ||
323 | UNSET = ["UNSET"] | |
324 | ||
325 | def parse_list(fn): | |
326 | playlist = Playlist() | |
327 | season, episode, chapter, ep_i = None, None, None, 1 | |
328 | vds = {} | |
329 | ads = iso = None | |
330 | with location(FileLocation(fn, 0)) as floc: | |
331 | with open(fn, "r") as f: | |
332 | for line in f: | |
333 | floc.stepline() | |
334 | sline = line.lstrip() | |
335 | if sline == "" or sline.startswith(";"): continue | |
336 | ||
337 | if line.startswith("!"): | |
338 | ww = Words(line[1:]) | |
339 | cmd = ww.nextword() | |
340 | check(cmd is not None, "missing command") | |
341 | ||
342 | if cmd == "season": | |
343 | v = ww.nextword(); | |
344 | check(v is not None, "missing season number") | |
345 | if v == "-": | |
346 | check(v.rest() is None, "trailing junk") | |
347 | season = playlist.add_movies() | |
348 | else: | |
349 | i = getint(v) | |
350 | title = ww.rest() | |
351 | season = playlist.add_season(title, i, implicitp = False) | |
352 | episode = chapter = None | |
353 | ep_i = 1 | |
354 | ||
355 | elif cmd == "movie": | |
356 | check(ww.rest() is None, "trailing junk") | |
357 | season = playlist.add_movies() | |
358 | episode = chapter = None | |
359 | ep_i = 1 | |
360 | ||
361 | elif cmd == "epname": | |
362 | name = ww.rest() | |
363 | check(name is not None, "missing episode name") | |
364 | try: sep = name.index(":") | |
365 | except ValueError: names = name + "s" | |
366 | else: name, names = name[:sep], name[sep + 1:] | |
367 | playlist.epname, playlist.epnames = name, names | |
368 | ||
369 | elif cmd == "epno": | |
370 | i = ww.rest() | |
371 | check(i is not None, "missing episode number") | |
372 | ep_i = getint(i) | |
373 | ||
374 | elif cmd == "iso": | |
375 | fn = ww.rest(); check(fn is not None, "missing filename") | |
376 | if fn == "-": iso = None | |
377 | else: | |
378 | check(OS.path.exists(OS.path.join(ROOT, fn)), | |
379 | "iso file `%s' not found" % fn) | |
380 | iso = VideoDisc(fn) | |
381 | ||
382 | elif cmd == "vdir": | |
383 | name = ww.nextword(); check(name is not None, "missing name") | |
384 | fn = ww.rest(); check(fn is not None, "missing directory") | |
385 | if fn == "-": | |
386 | try: del vds[name] | |
387 | except KeyError: pass | |
388 | else: | |
389 | vds[name] = VideoDir(fn) | |
390 | ||
391 | elif cmd == "adir": | |
392 | fn = ww.rest(); check(fn is not None, "missing directory") | |
393 | if fn == "-": ads = None | |
394 | else: ads = AudioDir(fn) | |
395 | ||
396 | elif cmd == "end": | |
397 | break | |
398 | ||
399 | else: | |
400 | raise ExpectedError("unknown command `%s'" % cmd) | |
401 | ||
402 | else: | |
403 | ||
404 | if not line[0].isspace(): | |
405 | ww = Words(line) | |
406 | conf = ww.nextword() | |
407 | ||
408 | check(conf is not None, "missing config") | |
409 | i, vdname, neps, fake_epi = UNSET, "-", 1, ep_i | |
410 | for c in conf.split(","): | |
411 | if c.isdigit(): i = int(c) | |
412 | elif c == "-": i = None | |
413 | else: | |
414 | eq = c.find("="); check(eq >= 0, "bad assignment `%s'" % c) | |
415 | k, v = c[:eq], c[eq + 1:] | |
416 | if k == "vd": vdname = v | |
417 | elif k == "n": neps = getint(v) | |
418 | elif k == "ep": fake_epi = getint(v) | |
419 | else: raise ExpectedError("unknown setting `%s'" % k) | |
420 | ||
421 | title = ww.rest() | |
422 | check(i is not UNSET, "no title number") | |
423 | if season is None: | |
424 | season = playlist.add_season(None, 1, implicitp = True) | |
425 | ||
426 | if i is None: | |
427 | check(ads, "no title, but no audio directory") | |
428 | check(season.implicitp, "audio source, but explicit season") | |
0b8c4773 MW |
429 | try: src = ads.episodes[ep_i] |
430 | except KeyError: | |
431 | raise ExpectedError("episode %d not found in audio dir `%s'" % | |
432 | ep_i, ads.dir) | |
04a05f7f MW |
433 | |
434 | elif iso: | |
435 | src = iso | |
436 | ||
437 | else: | |
438 | check(vdname in vds, "title, but no iso or video directory") | |
0b8c4773 MW |
439 | try: vdir = vds[vdname] |
440 | except KeyError: | |
441 | raise ExpectedError("video dir label `%s' not set" % vdname) | |
442 | try: s = vdir.seasons[season.i] | |
443 | except KeyError: | |
444 | raise ExpectedError("season %d not found in video dir `%s'" % | |
445 | (season.i, vdir.dir)) | |
446 | try: src = s.episodes[ep_i] | |
447 | except KeyError: | |
448 | raise ExpectedError("episode %d.%d not found in video dir `%s'" % | |
449 | (season.i, ep_i, vdir.dir)) | |
04a05f7f MW |
450 | |
451 | episode = season.add_episode(fake_epi, neps, title, src, i) | |
452 | chapter = None | |
b092d511 | 453 | ep_i += neps; src.nuses += neps |
04a05f7f MW |
454 | |
455 | else: | |
456 | ww = Words(line) | |
457 | title = ww.rest() | |
458 | check(episode is not None, "no current episode") | |
459 | check(episode.source.CHAPTERP, | |
460 | "episode source doesn't allow chapters") | |
461 | if chapter is None: j = 1 | |
462 | else: j += 1 | |
463 | chapter = episode.add_chapter(title, j) | |
464 | ||
b092d511 MW |
465 | discs = set() |
466 | for vdir in vds.values(): | |
467 | for s in vdir.seasons.values(): | |
468 | for d in s.episodes.values(): | |
469 | discs.add(d) | |
470 | for d in sorted(discs, key = lambda d: d.fn): | |
471 | if d.neps != d.nuses: | |
472 | raise ExpectedError("disc `%s' has %d episodes, used %d times" % | |
473 | (d.fn, d.neps, d.nuses)) | |
474 | ||
04a05f7f MW |
475 | return playlist |
476 | ||
477 | ROOT = "/mnt/dvd/archive/" | |
478 | ||
479 | try: | |
480 | for f in SYS.argv[1:]: | |
481 | parse_list(f).write(SYS.stdout) | |
482 | except (ExpectedError, IOError, OSError) as e: | |
483 | LOC.report(e) | |
484 | SYS.exit(2) |