+ videourl = sorted(playlist, key=lambda k: int(k['BANDWIDTH']))[-1]['url']
+ if not videourl.startswith('http'): #if relative path
+ videourl = "{}/{}".format(os.path.dirname(video['url']), videourl)
+ segments, metadata = parse_segment_playlist(videourl)
+ if "EXT-X-KEY" in metadata:
+ key = requests.get(metadata["EXT-X-KEY"]['URI'].strip('"')).text
+ decrypt=True
+ else:
+ decrypt=False
+ with open("%s"%video['filename'],"wb") as ofile:
+ segment=0
+ size = 0
+ for url in segments:
+ ufile = requests.get(url, stream=True).raw
+ print("\r{0:.2f} MB".format(size/1024/1024),end="")
+ sys.stdout.flush()
+ if decrypt:
+ iv=struct.pack("IIII",segment,0,0,0)
+ decryptor = AES.new(key, AES.MODE_CBC, iv)
+ while(True):
+ try:
+ buf = ufile.read(4096)
+ except (socket.error, TypeError) as e:
+ print("Error reading, skipping file")
+ print(e)
+ return
+ if not buf:
+ break
+ if decrypt:
+ buf = decryptor.decrypt(buf)
+ ofile.write(buf)
+ size += len(buf)
+ segment += 1
+
+ if 'thumb-url' in video:
+ video['thumb'] = requests.get(video['thumb-url'],stream=True).raw
+
+def parse_playlist(playlist):
+ if not playlist.startswith("#EXTM3U"):
+ print(playlist)
+ return False
+ playlist = playlist.splitlines()
+ while not 'EXT-X-STREAM-INF' in playlist[0]:
+ playlist = playlist[1:]
+ items=[]
+ for (metadata_string,url) in zip(playlist[0::2], playlist[1::2]):
+ md = Video()
+ if not 'EXT-X-STREAM-INF' in metadata_string.split(':')[0]:
+ continue
+ 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(playlisturl):
+ playlist = requests.get(playlisturl).text
+ assert playlist.startswith("#EXTM3U")
+ PATTERN = re.compile(r'''((?:[^,"']|"[^"]*"|'[^']*')+)''')
+ segments = []
+ next_is_url=False
+ metadata = {}
+ for row in playlist.splitlines():
+ if next_is_url:
+ if not row.startswith('http'): #if relative path
+ row = "{}/{}".format(os.path.dirname(playlisturl), row)
+ 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 quotes
+ 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)
+
+def parse_videolist():
+ page_num = 1
+ soup = BeautifulSoup(requests.get("http://www.svtplay.se/ajax/videospager").text)#this call does not work for getting the pages, we use it for the page totals only
+ page_tot = int(soup.find('a',{'data-currentpage':True}).attrs['data-lastpage'])
+ videos_per_page = 8
+ video_num = 0
+ while(page_num <= page_tot):
+ base_url = "http://www.svtplay.se/ajax/videos?sida={}".format(page_num)
+ soup = BeautifulSoup(requests.get(base_url).text)
+ for article in soup.findAll('article'):
+ meta = dict(article.attrs)
+ video = Video()
+ video['title'] = meta['data-title']
+ video['description'] = meta['data-description']
+ video['url'] = dict(article.find('a').attrs)['href']
+ video['thumb-url'] = dict(article.find('img',{}).attrs)['src']
+ video['num'] = video_num
+ video['total'] = page_tot * videos_per_page
+ video_num += 1
+ yield video
+ page_num += 1
+
+def remux(video, xml=None):
+ basename = video['filename'].split('.ts')[0]
+ if 'genre' in video:
+ if not os.path.exists(video['genre']):
+ os.mkdir(video['genre'])
+ video['path'] = os.path.join(video['genre'],basename+'.mkv')
+ else:
+ video['path'] = basename+'.mkv'
+ command = ["mkvmerge","-o",video['path'], '--title',video['title']]
+
+ if xml:
+ with open(basename+'.xml','w') as f:
+ f.write(xml)
+ command.extend(['--global-tags',basename+'.xml'])
+ if 'thumb' in video:
+ with open('thumbnail.jpg','wb') as f: #FIXME use title instead for many downloaders
+ f.write(video['thumb'].read())
+ command.extend(['--attachment-description', "Thumbnail",
+ '--attachment-mime-type', 'image/jpeg',
+ '--attach-file', 'thumbnail.jpg'])
+ command.append(video['filename'])
+ print(Popen(command, stdout=PIPE).communicate()[0])
+ for fname in (video['filename'], basename+'.xml','thumbnail.jpg'):
+ try:
+ os.unlink(fname)
+ except:
+ pass
+ if 'timestamp' in video:
+ try:
+ os.utime(video['path'], times=(video['timestamp'].timestamp(),video['timestamp'].timestamp()))
+ except FileNotFoundError as e:
+ print(e)
+
+
+def mkv_metadata(video):
+ root = BeautifulSoup(features='xml')
+ root.append(Doctype('Tags SYSTEM "matroskatags.dtd"'))
+ tags = root.new_tag("Tags")
+ tag = root.new_tag("Tag")
+ tags.append(tag)
+ root.append(tags)
+ keep = ('title','description', 'url','genre')
+ targets = root.new_tag("Targets")
+ ttv = root.new_tag("TargetTypeValue")
+ ttv.string = str(50)
+ targets.append(ttv)
+ tag.append(targets)
+ for key in video:
+ if not key in keep:
+ continue
+ simple = root.new_tag('Simple')
+ name = root.new_tag('Name')
+ name.string=key.upper()
+ simple.append(name)
+ sstring = root.new_tag('String')
+ sstring.string=video[key]
+ simple.append(sstring)
+ tag.append(simple)
+ return str(root)