+def download_from_playlist(url, title):
+ playlist = parse_playlist(urllib2.urlopen(url).read())
+ videourl = sorted(playlist, key=lambda k: int(k['BANDWIDTH']))[-1]['url']
+ segments, metadata = parse_segment_playlist(urllib2.urlopen(videourl).read())
+ if "EXT-X-KEY" in metadata:
+ key = urllib2.urlopen(metadata["EXT-X-KEY"]['URI'].strip('"')).read()
+ decrypt=True
+ else:
+ decrypt=False
+ with open("%s"%title,"w") as ofile:
+ segment=0
+ for url in segments:
+ print "Downloading: %s"%(url)
+ ufile = urllib2.urlopen(url)
+ if decrypt:
+ iv=struct.pack("IIII",segment,0,0,0)
+ decryptor = AES.new(key, AES.MODE_CBC, iv)
+ while(True):
+ buf = ufile.read(1024)
+ if buf:
+ if decrypt:
+ buf = decryptor.decrypt(buf)
+ ofile.write(buf)
+ else:
+ ufile.close()
+ break
+ segment += 1
+
+def parse_playlist(playlist):
+ assert playlist.startswith("#EXTM3U")
+ playlist = playlist.splitlines()[1:]
+ items=[]
+ for (metadata_string,url) in zip(playlist[0::2], playlist[1::2]):
+ md = dict()
+ assert 'EXT-X-STREAM-INF' in metadata_string.split(':')[0]
+ for item in metadata_string.split(':')[1].split(','):
+ if '=' in item:
+ md.update([item.split('='),])
+ md['url']=url
+ items.append(md)
+ return items
+
+def parse_segment_playlist(playlist):
+ assert playlist.startswith("#EXTM3U")
+ PATTERN = re.compile(r'''((?:[^,"']|"[^"]*"|'[^']*')+)''')
+ segments = []
+ next_is_url=False
+ metadata = {}
+ for row in playlist.splitlines():
+ if next_is_url:
+ segments.append(row)
+ next_is_url=False
+ continue
+ if 'EXTINF' in row:
+ next_is_url=True
+ if "EXT-X-KEY" in row:
+ row = row.split(':',1)[1] #skip first part
+ parts = PATTERN.split(row)[1:-1] #do magic re split and keep quoting
+ metadata["EXT-X-KEY"] = dict([part.split('=',1) for part in parts if '=' in part]) #throw away the commas and make dict of the pairs
+ return(segments, metadata)
+