mkm3u: Overhaul video filename parsing again.
[epls] / mkm3u
diff --git a/mkm3u b/mkm3u
index 0078f4d..08ef4ff 100755 (executable)
--- a/mkm3u
+++ b/mkm3u
@@ -149,27 +149,26 @@ class VideoSeason (object):
       raise ExpectedError("season %d episode %d already taken" % (me.i, i))
     me.episodes[i] = disc; disc.neps += 1
 
-def some_group(m, *gg):
-  for g in gg:
-    s = m.group(g)
+def match_group(m, *groups, dflt = None, mustp = False):
+  for g in groups:
+    try: s = m.group(g)
+    except IndexError: continue
     if s is not None: return s
-  return None
+  if mustp: raise ValueError("no match found")
+  else: return dflt
 
 class VideoDir (object):
 
-  _R_ISO_PRE = RX.compile(r""" ^
-        (?: S (?P<si> \d+)
-              (?: \. \ (?P<st> .*) — (?: D \d+ \. \ )? |
-                  D \d+ \. \ |
-                  (?= E \d+ \. \ ) |
-                  \. \ ) |
-            \d+ \. \ )
-        (?: (?P<eplist>
-             (?: S \d+ \ )? E \d+ (?: – \d+)?
-             (?: , \ (?: S \d+ \ )? E \d+ (?: – \d+)?)*) |
-            (?P<epname> E \d+) \. \ .*)
-        \. iso $
-  """, RX.X)
+  _R_ISO_PRE = list(map(lambda pat: RX.compile("^" + pat + r"\.iso$", RX.X),
+    [r""" S? (?P<si> \d+) [A-Z]? \. \ (?P<stitle> .*) —
+            (?: D \d+ \. \ )?
+          (?P<epex> .*) """,
+     r""" S (?P<si> \d+) (?: D \d+)? \. \ (?P<epex> .*) """,
+     r""" S (?P<si> \d+) \. \ (?P<epex> E \d+ .*) """,
+     r""" S (?P<si> \d+) \. \ (?P<epex> E \d+ .*) """,
+     r""" S (?P<si> \d+) (?P<epex> E \d+) \. \ .* """,
+     r""" \d+ \. \ (?P<epex> [ES] \d+ .*) """,
+     r""" (?P<epnum> \d+ ) \. \ .* """]))
 
   _R_ISO_EP = RX.compile(r""" ^
         (?: S (?P<si> \d+) \ )?
@@ -185,22 +184,26 @@ class VideoDir (object):
     for fn in fns:
       path = OS.path.join(dir, fn)
       if not fn.endswith(".iso"): continue
-      m = me._R_ISO_PRE.match(fn)
-      if not m:
-        #print(";; `%s' ignored" % path, file = SYS.stderr)
+      #print(";; `%s'" % path, file = SYS.stderr)
+      for r in me._R_ISO_PRE:
+        m = r.match(fn)
+        if m: break
+      else:
+        #print(";;\tignored (regex mismatch)", file = SYS.stderr)
         continue
 
-      i = filter(m.group("si"), int)
-      stitle = m.group("st")
-      check(i is not None or stitle is None,
+      si = filter(match_group(m, "si"), int)
+      stitle = match_group(m, "stitle")
+
+      check(si is not None or stitle is None,
             "explicit season title without number in `%s'" % fn)
-      if i is not None:
-        if season is None or i != season.i:
-          check(season is None or i == season.i + 1,
+      if si is not None:
+        if season is None or si != season.i:
+          check(season is None or si == season.i + 1,
                 "season %d /= %d" %
-                  (i, season is None and -1 or season.i + 1))
-          check(i not in seasons, "season %d already seen" % i)
-          seasons[i] = season = VideoSeason(i, stitle)
+                  (si, season is None and -1 or season.i + 1))
+          check(si not in seasons, "season %d already seen" % si)
+          seasons[si] = season = VideoSeason(si, stitle)
         else:
           check(stitle == season.title,
                 "season title `%s' /= `%s'" % (stitle, season.title))
@@ -208,15 +211,15 @@ class VideoDir (object):
       disc = VideoDisc(path)
       ts = season
       any, bad = False, False
-      epname = m.group("epname")
-      if epname is not None: eplist = [epname]
-      else: eplist = m.group("eplist").split(", ")
+      epnum = match_group(m, "epnum")
+      if epnum is not None: eplist = ["E" + epnum]
+      else: eplist = match_group(m, "epex", mustp = True).split(", ")
       for eprange in eplist:
         mm = me._R_ISO_EP.match(eprange)
-        if mm is None: bad = True; continue
-        if not any:
-          #print(";; `%s'" % path, file = SYS.stderr)
-          any = True
+        if mm is None:
+          #print(";;\t`%s'?" % eprange, file = SYS.stderr)
+          bad = True; continue
+        if not any: any = True
         i = filter(mm.group("si"), int)
         if i is not None:
           try: ts = seasons[i]
@@ -228,8 +231,11 @@ class VideoDir (object):
         for k in range(start, end + 1):
           ts.set_episode_disc(k, disc)
           #print(";;\tepisode %d.%d" % (ts.i, k), file = SYS.stderr)
-      if not any: pass #print(";; `%s' ignored" % path, file = SYS.stderr)
-      elif bad: raise ExpectedError("bad ep list in `%s'", fn)
+      if not any:
+        #print(";;\tignored", file = SYS.stderr)
+        pass
+      elif bad:
+        raise ExpectedError("bad ep list in `%s'", fn)
     me.seasons = seasons
 
 class AudioDisc (Source):
@@ -275,12 +281,13 @@ class Chapter (object):
     me.url = episode.source.url(episode.tno, i, i + 1)
 
 class Episode (object):
-  def __init__(me, season, i, neps, title, src, tno = None, startch = None):
+  def __init__(me, season, i, neps, title, src, tno = None,
+               startch = None, endch = None):
     me.season = season
     me.i, me.neps, me.title = i, neps, title
     me.chapters = []
     me.source, me.tno = src, tno
-    me.url = src.url(tno, startch, None)
+    me.url = src.url(tno, startch, endch)
   def add_chapter(me, title, j):
     ch = Chapter(me, title, j)
     me.chapters.append(ch)
@@ -294,8 +301,8 @@ class BaseSeason (object):
     me.episodes = []
     me.implicitp = implicitp
     me.ep_i, episodes = 1, []
-  def add_episode(me, j, neps, title, src, tno, startch):
-    ep = Episode(me, j, neps, title, src, tno, startch)
+  def add_episode(me, j, neps, title, src, tno, startch, endch):
+    ep = Episode(me, j, neps, title, src, tno, startch, endch)
     me.episodes.append(ep)
     src.nuses += neps; me.ep_i += neps
     return ep
@@ -326,10 +333,10 @@ class MovieSeason (BaseSeason):
     super().__init__(series, *args, **kw)
     me.title = title
     me.i = None
-  def add_episode(me, j, neps, title, src, tno, startch):
+  def add_episode(me, j, neps, title, src, tno, startch, endch):
     if me.title is None and title is None:
       raise ExpectedError("movie or movie season must have a title")
-    return super().add_episode(j, neps, title, src, tno, startch)
+    return super().add_episode(j, neps, title, src, tno, startch, endch)
   def _eplabel(me, i, neps, title):
     if me.title is None:
       label = title
@@ -532,7 +539,7 @@ class EpisodeListParser (object):
   def _process_episode(me, ww):
 
     opts = ww.nextword(); check(opts is not None, "missing title/options")
-    ti = None; sname = None; neps = 1; epi = None; ch = None
+    ti = None; sname = None; neps = 1; epi = None; loch = hich = None
     for k, v in me._keyvals(opts):
       if k is None:
         if v.isdigit(): ti = int(v)
@@ -541,7 +548,10 @@ class EpisodeListParser (object):
       elif k == "s": sname = v
       elif k == "n": neps = getint(v)
       elif k == "ep": epi = getint(v)
-      elif k == "ch": ch = getint(v)
+      elif k == "ch":
+        try: sep = v.index("-")
+        except ValueError: loch, hich = getint(v), None
+        else: loch, hich = getint(v[:sep]), getint(v[sep + 1:]) + 1
       else: raise ExpectedError("unknown episode option `%s'" % k)
     check(ti is not None, "missing title number")
     series = me._get_series(sname)
@@ -563,7 +573,7 @@ class EpisodeListParser (object):
       try: src = me._isos[series.name]
       except KeyError: src = me._auto_epsrc(series)
 
-    episode = season.add_episode(epi, neps, title, src, ti, ch)
+    episode = season.add_episode(epi, neps, title, src, ti, loch, hich)
     me._pl.add_episode(episode)
     me._cur_episode = episode