Сделана корректная обработка "неаккуратных" файлов с пропущенными кавычками вокруг...
[vpproxy.git] / plugins / modules / M3uParser.py
index 01dbcc9f73ecdf2d1ba7cf04bdcf0739746afa8c..5bee611475d247073a6a0023d2afe938d7d8e321 100644 (file)
@@ -2,12 +2,15 @@
 # http://n4k3d.com/the-m3u-file-format/
 
 import sys
+import hexdump
+import codecs
 
 class track():
-    def __init__(self, length, title, path):
+    def __init__(self, length, title, path, attrs=None):
         self.length = length
         self.title = title
         self.path = path
+        self.attrs = attrs
 
 
 # # # song info lines are formatted like:
@@ -23,6 +26,9 @@ def parseM3U(infile):
         #EXTM3U
     # this is not a valid M3U and we should stop..
     line = inf.readline()
+    line = line.lstrip('\xef\xbb\xbf')
+    line = line.rstrip('\n')
+    line = line.strip()
     if not line.startswith('#EXTM3U'):
        return
 
@@ -31,11 +37,34 @@ def parseM3U(infile):
     song=track(None,None,None)
 
     for line in inf:
-        line=line.strip()
+        line = line.lstrip('\xef\xbb\xbf')
+        line = line.rstrip('\n')
+        line = line.strip()
         if line.startswith('#EXTINF:'):
             # pull length and title from #EXTINF line
-            length,title=line.split('#EXTINF:')[1].split(',',1)
-            song=track(length,title,None)
+            prefix,title=line.split('#EXTINF:')[1].split(',',1)
+            title=title.strip()
+            length,attrstr=prefix.split(' ',1)
+            attrs={}
+
+            while attrstr:
+
+              attrstr=attrstr.strip()
+              key,tail=attrstr.split('=',1)
+              if tail[0]=='\"':
+                tail=tail[1:]
+                value,attrstr=tail.split('"',1)
+              else:
+                try:
+                  value,attrstr=tail.split(' ',1)
+                except ValueError:
+                  value=tail
+                  attrstr=''
+              attrstr=attrstr.strip()
+              attrs[key]=value 
+            
+            title=title.decode('string_escape')
+            song=track(length,title,None,attrs)
         elif (len(line) != 0):
             # pull song path from all other, non-blank lines
             song.path=line