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 | ||
141 | _R_ISO_PRE = RX.compile(r""" | |
142 | ^ | |
143 | (?: S (?P<si> \d+) (?: \. \ (?P<st> .*)—)? (?: D (?P<sdi> \d+))? | | |
144 | (?P<di> \d+)) | |
145 | \. \ # | |
146 | (?P<eps> .*) | |
147 | \. iso $ | |
148 | """, RX.X) | |
149 | ||
150 | _R_ISO_EP = RX.compile(r""" | |
151 | ^ E (?P<ei> \d+) (?: – (?P<ej> \d+))? $ | |
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() | |
158 | season, last_j = None, 0 | |
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 | ||
166 | i = filter(m.group("si"), int, 1) | |
167 | stitle = m.group("st") | |
168 | if season is None or i != season.i: | |
169 | check(season is None or i == season.i + 1, | |
170 | "season %d /= %d" % (i, season is None and -1 or season.i + 1)) | |
171 | check(i not in seasons, "season %d already seen" % i) | |
172 | seasons[i] = season = VideoSeason(i, stitle) | |
173 | last_j = 0 | |
174 | else: | |
175 | check(stitle == season.title, | |
176 | "season title `%s' /= `%s'" % (stitle, season.title)) | |
177 | j = filter(some_group(m, "sdi", "di"), int) | |
178 | if j is not None: | |
179 | check(j == last_j + 1, | |
180 | "season %d disc %d /= %d" % (season.i, j, last_j + 1)) | |
181 | ||
32cd109c MW |
182 | disc = VideoDisc(path) |
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 | |
187 | start = filter(mm.group("ei"), int) | |
188 | end = filter(mm.group("ej"), int, start) | |
32cd109c MW |
189 | for k in range(start, end + 1): |
190 | season.set_episode_disc(k, disc) | |
191 | any = True | |
192 | if bad and any: | |
04a05f7f | 193 | raise ExpectedError("bad ep list in `%s'", fn) |
04a05f7f MW |
194 | last_j = j |
195 | me.seasons = seasons | |
196 | ||
197 | class AudioDisc (Source): | |
198 | #PREFIX = "file://" | |
199 | TITLEP = CHAPTERP = False | |
200 | ||
201 | class AudioEpisode (Source): | |
202 | #PREFIX = "file://" | |
203 | TITLEP = CHAPTERP = False | |
204 | def __init__(me, fn, i, *args, **kw): | |
205 | super().__init__(fn, *args, **kw) | |
206 | me.i = i | |
207 | ||
208 | class AudioDir (object): | |
209 | ||
210 | _R_FLAC = RX.compile(r""" | |
211 | ^ | |
212 | E (\d+) | |
213 | (?: \. \ (.*))? | |
214 | \. flac $ | |
215 | """, RX.X) | |
216 | ||
217 | def __init__(me, dir): | |
b092d511 | 218 | me.dir = dir |
04a05f7f MW |
219 | fns = OS.listdir(OS.path.join(ROOT, dir)) |
220 | fns.sort() | |
221 | episodes = {} | |
222 | last_i = 0 | |
223 | for fn in fns: | |
224 | path = OS.path.join(dir, fn) | |
225 | if not fn.endswith(".flac"): continue | |
226 | m = me._R_FLAC.match(fn) | |
227 | if not m: continue | |
228 | i = filter(m.group(1), int) | |
229 | etitle = m.group(2) | |
230 | check(i == last_i + 1, "episode %d /= %d" % (i, last_i + 1)) | |
231 | episodes[i] = AudioEpisode(path, i) | |
232 | last_i = i | |
233 | me.episodes = episodes | |
234 | ||
235 | class Chapter (object): | |
236 | def __init__(me, episode, title, i): | |
237 | me.title, me.i = title, i | |
238 | me.url = episode.source.url(episode.tno, i) | |
239 | ||
240 | class Episode (object): | |
241 | def __init__(me, season, i, neps, title, src, tno = None): | |
242 | me.season = season | |
243 | me.i, me.neps, me.title = i, neps, title | |
244 | me.chapters = [] | |
245 | me.source, me.tno = src, tno | |
246 | me.url = src.url(tno) | |
247 | def add_chapter(me, title, j): | |
248 | ch = Chapter(me, title, j) | |
249 | me.chapters.append(ch) | |
250 | return ch | |
251 | def label(me): | |
252 | return me.season._eplabel(me.i, me.neps, me.title) | |
253 | ||
254 | class Season (object): | |
255 | def __init__(me, playlist, title, i, implicitp = False): | |
256 | me.playlist = playlist | |
257 | me.title, me.i = title, i | |
258 | me.implicitp = implicitp | |
259 | me.episodes = [] | |
260 | def add_episode(me, j, neps, title, src, tno): | |
261 | ep = Episode(me, j, neps, title, src, tno) | |
262 | me.episodes.append(ep) | |
263 | return ep | |
264 | def _eplabel(me, i, neps, title): | |
265 | if neps == 1: epname = me.playlist.epname; epn = "%d" % i | |
266 | elif neps == 2: epname = me.playlist.epnames; epn = "%d, %d" % (i, i + 1) | |
267 | else: epname = me.playlist.epnames; epn = "%d–%d" % (i, i + neps - 1) | |
268 | if title is None: | |
269 | if me.implicitp: return "%s %s" % (epname, epn) | |
270 | elif me.title is None: return "%s %d.%s" % (epname, me.i, epn) | |
271 | else: return "%s—%s %s" % (me.title, epname, epn) | |
272 | else: | |
273 | if me.implicitp: return "%s. %s" % (epn, title) | |
274 | elif me.title is None: return "%d.%s. %s" % (me.i, epn, title) | |
275 | else: return "%s—%s. %s" % (me.title, epn, title) | |
276 | ||
277 | class MovieSeason (object): | |
278 | def __init__(me, playlist): | |
279 | me.playlist = playlist | |
280 | me.i = -1 | |
281 | me.implicitp = False | |
282 | me.episodes = [] | |
283 | def add_episode(me, j, neps, title, src, tno): | |
284 | if title is None: raise ExpectedError("movie must have a title") | |
285 | ep = Episode(me, j, neps, title, src, tno) | |
286 | me.episodes.append(ep) | |
287 | return ep | |
288 | def _eplabel(me, i, epn, title): | |
289 | return title | |
290 | ||
291 | class Playlist (object): | |
292 | ||
293 | def __init__(me): | |
294 | me.seasons = [] | |
295 | me.epname, me.epnames = "Episode", "Episodes" | |
296 | ||
297 | def add_season(me, title, i, implicitp = False): | |
298 | season = Season(me, title, i, implicitp) | |
299 | me.seasons.append(season) | |
300 | return season | |
301 | ||
302 | def add_movies(me): | |
303 | season = MovieSeason(me) | |
304 | me.seasons.append(season) | |
305 | return season | |
306 | ||
307 | def write(me, f): | |
308 | f.write("#EXTM3U\n") | |
309 | for season in me.seasons: | |
310 | f.write("\n") | |
311 | for i, ep in enumerate(season.episodes, 1): | |
312 | if not ep.chapters: | |
313 | f.write("#EXTINF:0,,%s\n%s\n" % (ep.label(), ep.url)) | |
314 | else: | |
315 | for ch in ep.chapters: | |
316 | f.write("#EXTINF:0,,%s: %s\n%s\n" % | |
317 | (ep.label(), ch.title, ch.url)) | |
318 | ||
319 | UNSET = ["UNSET"] | |
320 | ||
321 | def parse_list(fn): | |
322 | playlist = Playlist() | |
323 | season, episode, chapter, ep_i = None, None, None, 1 | |
324 | vds = {} | |
325 | ads = iso = None | |
326 | with location(FileLocation(fn, 0)) as floc: | |
327 | with open(fn, "r") as f: | |
328 | for line in f: | |
329 | floc.stepline() | |
330 | sline = line.lstrip() | |
331 | if sline == "" or sline.startswith(";"): continue | |
332 | ||
333 | if line.startswith("!"): | |
334 | ww = Words(line[1:]) | |
335 | cmd = ww.nextword() | |
336 | check(cmd is not None, "missing command") | |
337 | ||
338 | if cmd == "season": | |
339 | v = ww.nextword(); | |
340 | check(v is not None, "missing season number") | |
341 | if v == "-": | |
342 | check(v.rest() is None, "trailing junk") | |
343 | season = playlist.add_movies() | |
344 | else: | |
345 | i = getint(v) | |
346 | title = ww.rest() | |
347 | season = playlist.add_season(title, i, implicitp = False) | |
348 | episode = chapter = None | |
349 | ep_i = 1 | |
350 | ||
351 | elif cmd == "movie": | |
352 | check(ww.rest() is None, "trailing junk") | |
353 | season = playlist.add_movies() | |
354 | episode = chapter = None | |
355 | ep_i = 1 | |
356 | ||
357 | elif cmd == "epname": | |
358 | name = ww.rest() | |
359 | check(name is not None, "missing episode name") | |
360 | try: sep = name.index(":") | |
361 | except ValueError: names = name + "s" | |
362 | else: name, names = name[:sep], name[sep + 1:] | |
363 | playlist.epname, playlist.epnames = name, names | |
364 | ||
365 | elif cmd == "epno": | |
366 | i = ww.rest() | |
367 | check(i is not None, "missing episode number") | |
368 | ep_i = getint(i) | |
369 | ||
370 | elif cmd == "iso": | |
371 | fn = ww.rest(); check(fn is not None, "missing filename") | |
372 | if fn == "-": iso = None | |
373 | else: | |
374 | check(OS.path.exists(OS.path.join(ROOT, fn)), | |
375 | "iso file `%s' not found" % fn) | |
376 | iso = VideoDisc(fn) | |
377 | ||
378 | elif cmd == "vdir": | |
379 | name = ww.nextword(); check(name is not None, "missing name") | |
380 | fn = ww.rest(); check(fn is not None, "missing directory") | |
381 | if fn == "-": | |
382 | try: del vds[name] | |
383 | except KeyError: pass | |
384 | else: | |
385 | vds[name] = VideoDir(fn) | |
386 | ||
387 | elif cmd == "adir": | |
388 | fn = ww.rest(); check(fn is not None, "missing directory") | |
389 | if fn == "-": ads = None | |
390 | else: ads = AudioDir(fn) | |
391 | ||
392 | elif cmd == "end": | |
393 | break | |
394 | ||
395 | else: | |
396 | raise ExpectedError("unknown command `%s'" % cmd) | |
397 | ||
398 | else: | |
399 | ||
400 | if not line[0].isspace(): | |
401 | ww = Words(line) | |
402 | conf = ww.nextword() | |
403 | ||
404 | check(conf is not None, "missing config") | |
405 | i, vdname, neps, fake_epi = UNSET, "-", 1, ep_i | |
406 | for c in conf.split(","): | |
407 | if c.isdigit(): i = int(c) | |
408 | elif c == "-": i = None | |
409 | else: | |
410 | eq = c.find("="); check(eq >= 0, "bad assignment `%s'" % c) | |
411 | k, v = c[:eq], c[eq + 1:] | |
412 | if k == "vd": vdname = v | |
413 | elif k == "n": neps = getint(v) | |
414 | elif k == "ep": fake_epi = getint(v) | |
415 | else: raise ExpectedError("unknown setting `%s'" % k) | |
416 | ||
417 | title = ww.rest() | |
418 | check(i is not UNSET, "no title number") | |
419 | if season is None: | |
420 | season = playlist.add_season(None, 1, implicitp = True) | |
421 | ||
422 | if i is None: | |
423 | check(ads, "no title, but no audio directory") | |
424 | check(season.implicitp, "audio source, but explicit season") | |
0b8c4773 MW |
425 | try: src = ads.episodes[ep_i] |
426 | except KeyError: | |
427 | raise ExpectedError("episode %d not found in audio dir `%s'" % | |
428 | ep_i, ads.dir) | |
04a05f7f MW |
429 | |
430 | elif iso: | |
431 | src = iso | |
432 | ||
433 | else: | |
434 | check(vdname in vds, "title, but no iso or video directory") | |
0b8c4773 MW |
435 | try: vdir = vds[vdname] |
436 | except KeyError: | |
437 | raise ExpectedError("video dir label `%s' not set" % vdname) | |
438 | try: s = vdir.seasons[season.i] | |
439 | except KeyError: | |
440 | raise ExpectedError("season %d not found in video dir `%s'" % | |
441 | (season.i, vdir.dir)) | |
442 | try: src = s.episodes[ep_i] | |
443 | except KeyError: | |
444 | raise ExpectedError("episode %d.%d not found in video dir `%s'" % | |
445 | (season.i, ep_i, vdir.dir)) | |
04a05f7f MW |
446 | |
447 | episode = season.add_episode(fake_epi, neps, title, src, i) | |
448 | chapter = None | |
b092d511 | 449 | ep_i += neps; src.nuses += neps |
04a05f7f MW |
450 | |
451 | else: | |
452 | ww = Words(line) | |
453 | title = ww.rest() | |
454 | check(episode is not None, "no current episode") | |
455 | check(episode.source.CHAPTERP, | |
456 | "episode source doesn't allow chapters") | |
457 | if chapter is None: j = 1 | |
458 | else: j += 1 | |
459 | chapter = episode.add_chapter(title, j) | |
460 | ||
b092d511 MW |
461 | discs = set() |
462 | for vdir in vds.values(): | |
463 | for s in vdir.seasons.values(): | |
464 | for d in s.episodes.values(): | |
465 | discs.add(d) | |
466 | for d in sorted(discs, key = lambda d: d.fn): | |
467 | if d.neps != d.nuses: | |
468 | raise ExpectedError("disc `%s' has %d episodes, used %d times" % | |
469 | (d.fn, d.neps, d.nuses)) | |
470 | ||
04a05f7f MW |
471 | return playlist |
472 | ||
473 | ROOT = "/mnt/dvd/archive/" | |
474 | ||
475 | try: | |
476 | for f in SYS.argv[1:]: | |
477 | parse_list(f).write(SYS.stdout) | |
478 | except (ExpectedError, IOError, OSError) as e: | |
479 | LOC.report(e) | |
480 | SYS.exit(2) |