| 1 | #! /usr/bin/python3 |
| 2 | ### -*- mode: python; coding: utf-8 -*- |
| 3 | |
| 4 | from contextlib import contextmanager |
| 5 | import optparse as OP |
| 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 | |
| 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 | |
| 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 |
| 93 | me.neps = None |
| 94 | me.used_titles = dict() |
| 95 | me.used_chapters = set() |
| 96 | me.nuses = 0 |
| 97 | def url(me, title = None, start_chapter = None, end_chapter = None): |
| 98 | if title == "-": |
| 99 | if me.TITLEP: raise ExpectedError("missing title number") |
| 100 | if start_chapter is not None or end_chapter is not None: |
| 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) |
| 105 | elif start_chapter is None: |
| 106 | if end_chapter is not None: |
| 107 | raise ExpectedError("can't specify end chapter without start chapter") |
| 108 | suffix = "#%d" % title |
| 109 | elif not me.CHAPTERP: |
| 110 | raise ExpectedError("can't specify chapter with `%s'" % me.fn) |
| 111 | elif end_chapter is None: |
| 112 | suffix = "#%d:%d" % (title, start_chapter) |
| 113 | else: |
| 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)) |
| 132 | return me.PREFIX + ROOT + urlencode(me.fn) + suffix |
| 133 | |
| 134 | class VideoDisc (Source): |
| 135 | PREFIX = "dvd://" |
| 136 | TITLEP = CHAPTERP = True |
| 137 | |
| 138 | def __init__(me, fn, *args, **kw): |
| 139 | super().__init__(fn, *args, **kw) |
| 140 | me.neps = 0 |
| 141 | |
| 142 | class VideoSeason (object): |
| 143 | def __init__(me, i, title): |
| 144 | me.i = i |
| 145 | me.title = title |
| 146 | me.episodes = {} |
| 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)) |
| 150 | me.episodes[i] = disc; disc.neps += 1 |
| 151 | |
| 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 |
| 156 | if s is not None: return s |
| 157 | if mustp: raise ValueError("no match found") |
| 158 | else: return dflt |
| 159 | |
| 160 | class VideoDir (object): |
| 161 | |
| 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+ ) \. \ .* """]])) |
| 174 | |
| 175 | _R_ISO_EP = RX.compile(r""" ^ |
| 176 | (?: S (?P<si> \d+) \ )? |
| 177 | E (?P<ei> \d+) (?: – (?P<ej> \d+))? $ |
| 178 | """, RX.X) |
| 179 | |
| 180 | def __init__(me, dir): |
| 181 | me.dir = dir |
| 182 | fns = OS.listdir(OS.path.join(ROOT, dir)) |
| 183 | fns.sort() |
| 184 | season = None |
| 185 | seasons = {} |
| 186 | styles = me._R_ISO_PRE |
| 187 | for fn in fns: |
| 188 | path = OS.path.join(dir, fn) |
| 189 | if not fn.endswith(".iso"): continue |
| 190 | #print(";; `%s'" % path, file = SYS.stderr) |
| 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 |
| 198 | else: |
| 199 | #print(";;\tignored (regex mismatch)", file = SYS.stderr) |
| 200 | continue |
| 201 | |
| 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, |
| 206 | "explicit season title without number in `%s'" % fn) |
| 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, |
| 210 | "season %d /= %d" % |
| 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) |
| 214 | else: |
| 215 | check(stitle == season.title, |
| 216 | "season title `%s' /= `%s'" % (stitle, season.title)) |
| 217 | |
| 218 | disc = VideoDisc(path) |
| 219 | ts = season |
| 220 | any, bad = False, False |
| 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(", ") |
| 224 | for eprange in eplist: |
| 225 | mm = me._R_ISO_EP.match(eprange) |
| 226 | if mm is None: |
| 227 | #print(";;\t`%s'?" % eprange, file = SYS.stderr) |
| 228 | bad = True; continue |
| 229 | if not any: any = True |
| 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) |
| 236 | start = filter(mm.group("ei"), int) |
| 237 | end = filter(mm.group("ej"), int, start) |
| 238 | for k in range(start, end + 1): |
| 239 | ts.set_episode_disc(k, disc) |
| 240 | #print(";;\tepisode %d.%d" % (ts.i, k), file = SYS.stderr) |
| 241 | if not any: |
| 242 | #print(";;\tignored", file = SYS.stderr) |
| 243 | pass |
| 244 | elif bad: |
| 245 | raise ExpectedError("bad ep list in `%s'", fn) |
| 246 | me.seasons = seasons |
| 247 | |
| 248 | class AudioDisc (Source): |
| 249 | PREFIX = "file://" |
| 250 | TITLEP = CHAPTERP = False |
| 251 | |
| 252 | class AudioEpisode (AudioDisc): |
| 253 | def __init__(me, fn, i, *args, **kw): |
| 254 | super().__init__(fn, *args, **kw) |
| 255 | me.i = i |
| 256 | |
| 257 | class AudioDir (object): |
| 258 | |
| 259 | _R_FLAC = RX.compile(r""" ^ |
| 260 | E (\d+) |
| 261 | (?: \. \ (.*))? |
| 262 | \. flac $ |
| 263 | """, RX.X) |
| 264 | |
| 265 | def __init__(me, dir): |
| 266 | me.dir = dir |
| 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 |
| 286 | me.url = episode.source.url(episode.tno, i, i + 1) |
| 287 | |
| 288 | class Episode (object): |
| 289 | def __init__(me, season, i, neps, title, src, tno = None, |
| 290 | startch = None, endch = None): |
| 291 | me.season = season |
| 292 | me.i, me.neps, me.title = i, neps, title |
| 293 | me.chapters = [] |
| 294 | me.source, me.tno = src, tno |
| 295 | me.url = src.url(tno, startch, endch) |
| 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 | |
| 303 | class BaseSeason (object): |
| 304 | def __init__(me, series, implicitp = False): |
| 305 | me.series = series |
| 306 | me.episodes = [] |
| 307 | me.implicitp = implicitp |
| 308 | me.ep_i, episodes = 1, [] |
| 309 | def add_episode(me, j, neps, title, src, tno, startch, endch): |
| 310 | ep = Episode(me, j, neps, title, src, tno, startch, endch) |
| 311 | me.episodes.append(ep) |
| 312 | src.nuses += neps; me.ep_i += neps |
| 313 | return ep |
| 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) |
| 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 |
| 324 | def _eplabel(me, i, neps, title): |
| 325 | epname, epn = me._epnames(i, neps) |
| 326 | if title is None: |
| 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) |
| 330 | else: |
| 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 |
| 335 | |
| 336 | class MovieSeason (BaseSeason): |
| 337 | def __init__(me, series, title, *args, **kw): |
| 338 | super().__init__(series, *args, **kw) |
| 339 | me.title = title |
| 340 | me.i = None |
| 341 | def add_episode(me, j, neps, title, src, tno, startch, endch): |
| 342 | if me.title is None and title is None: |
| 343 | raise ExpectedError("movie or movie season must have a title") |
| 344 | return super().add_episode(j, neps, title, src, tno, startch, endch) |
| 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 |
| 354 | |
| 355 | class Series (object): |
| 356 | def __init__(me, playlist, name, title = None, wantedp = True): |
| 357 | me.playlist = playlist |
| 358 | me.name, me.title = name, title |
| 359 | me.cur_season = None |
| 360 | me.wantedp = wantedp |
| 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)) |
| 365 | def add_movies(me, title = None): |
| 366 | me._add_season(MovieSeason(me, title)) |
| 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 |
| 372 | |
| 373 | class Playlist (object): |
| 374 | def __init__(me): |
| 375 | me.seasons = [] |
| 376 | me.episodes = [] |
| 377 | me.epname, me.epnames = "Episode", "Episodes" |
| 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 = [] |
| 385 | def write(me, f): |
| 386 | f.write("#EXTM3U\n") |
| 387 | for season in me.seasons: |
| 388 | f.write("\n") |
| 389 | for ep in season: |
| 390 | label = ep.label() |
| 391 | if me.nseries > 1: label = ep.season.series.title + " " + label |
| 392 | if not ep.chapters: |
| 393 | f.write("#EXTINF:0,,%s\n%s\n" % (label, ep.url)) |
| 394 | else: |
| 395 | for ch in ep.chapters: |
| 396 | f.write("#EXTINF:0,,%s: %s\n%s\n" % |
| 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: |
| 436 | series = me._series[None] = Series(me._pl, None) |
| 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) |
| 448 | return me._get_series(name) |
| 449 | |
| 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 |
| 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) |
| 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 |
| 482 | |
| 483 | elif cmd == "season": |
| 484 | series = me._opts_series(cmd, opts) |
| 485 | w = ww.nextword(); |
| 486 | check(w is not None, "missing season number") |
| 487 | if w == "-": |
| 488 | if not series.wantedp: return |
| 489 | series.add_movies(ww.rest()) |
| 490 | else: |
| 491 | title = ww.rest(); i = getint(w) |
| 492 | if not series.wantedp: return |
| 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": |
| 506 | series = me._opts_series(cmd, opts) |
| 507 | w = ww.rest(); check(w is not None, "missing episode number") |
| 508 | epi = getint(w) |
| 509 | if not series.wantedp: return |
| 510 | series.ensure_season().ep_i = epi |
| 511 | |
| 512 | elif cmd == "iso": |
| 513 | series = me._opts_series(cmd, opts) |
| 514 | fn = ww.rest(); check(fn is not None, "missing filename") |
| 515 | if not series.wantedp: return |
| 516 | if fn == "-": forget(me._isos, series.name) |
| 517 | else: |
| 518 | check(OS.path.exists(OS.path.join(ROOT, fn)), |
| 519 | "iso file `%s' not found" % fn) |
| 520 | me._isos[series.name] = VideoDisc(fn) |
| 521 | |
| 522 | elif cmd == "vdir": |
| 523 | series = me._opts_series(cmd, opts) |
| 524 | dir = ww.rest(); check(dir is not None, "missing directory") |
| 525 | if not series.wantedp: return |
| 526 | if dir == "-": forget(me._vdirs, series.name) |
| 527 | else: me._vdirs[series.name] = VideoDir(dir) |
| 528 | |
| 529 | elif cmd == "adir": |
| 530 | series = me._opts_series(cmd, opts) |
| 531 | dir = ww.rest(); check(dir is not None, "missing directory") |
| 532 | if not series.wantedp: return |
| 533 | if dir == "-": forget(me._audirs, series.name) |
| 534 | else: me._audirs[series.name] = AudioDir(dir) |
| 535 | |
| 536 | elif cmd == "displaced": |
| 537 | series = me._opts_series(cmd, opts) |
| 538 | w = ww.rest(); check(w is not None, "missing count"); n = getint(w) |
| 539 | src = me._auto_epsrc(series) |
| 540 | src.nuses += n |
| 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") |
| 547 | ti = None; sname = None; neps = 1; epi = None; loch = hich = None |
| 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) |
| 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 |
| 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() |
| 566 | if not series.wantedp: return |
| 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") |
| 572 | dir = lookup(me._audirs, series.name, |
| 573 | "no title, and no audio directory") |
| 574 | src = lookup(dir.episodes, season.ep_i, |
| 575 | "episode %d not found in audio dir `%s'" % (epi, dir.dir)) |
| 576 | |
| 577 | else: |
| 578 | try: src = me._isos[series.name] |
| 579 | except KeyError: src = me._auto_epsrc(series) |
| 580 | |
| 581 | episode = season.add_episode(epi, neps, title, src, ti, loch, hich) |
| 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(): |
| 610 | if not me._series[name].wantedp: continue |
| 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(): |
| 616 | discs.add(d) |
| 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 |
| 622 | |
| 623 | ROOT = "/mnt/dvd/archive/" |
| 624 | |
| 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) |
| 641 | try: |
| 642 | ep = EpisodeListParser(series_wanted, opts.chaptersp) |
| 643 | ep.parse_file(argv[0]) |
| 644 | pl = ep.done() |
| 645 | pl.write(SYS.stdout) |
| 646 | except (ExpectedError, IOError, OSError) as e: |
| 647 | LOC.report(e) |
| 648 | SYS.exit(2) |