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