16516a8c1e92823f0e516924915376fc75605681
[svtplaydump.git] / svtplaydump.py
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 #
4 # (C) Copyright 2010 Mikael Frykholm <mikael@frykholm.com>
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>
18 #
19 # Changelog:
20 # 0.4 added mirror mode.
21 # 0.3 added apple streaming playlist parsing and decryption
22 # 0.2 added python 2.4 urlparse compatibility
23 # 0.1 initial release
24
25 from bs4 import BeautifulSoup
26 from subprocess import *
27 import re
28 from Crypto.Cipher import AES
29 import struct
30 import argparse
31 import requests
32 import sys, os
33
34 def scrape_player_page(url, title):
35 """
36 Try to scrape the site for video and download.
37 """
38 if not url.startswith('http'):
39 url = "http://www.svtplay.se" + url
40 video = {}
41 soup = BeautifulSoup(requests.get(url).text)
42 video_player = soup.body('a',{'data-json-href':True})[0]
43 if 'oppetarkiv.se' in url:
44 flashvars = requests.get("http://www.oppetarkiv.se/%s"%video_player.attrs['data-json-href']+"?output=json").json()
45 else:
46 if video_player.attrs['data-json-href'].startswith("/wd"):
47 flashvars = requests.get("http://www.svt.se/%s"%video_player.attrs['data-json-href']).json()
48 else:
49 flashvars = requests.get("http://www.svtplay.se/%s"%video_player.attrs['data-json-href']+"?output=json").json()
50 video['duration'] = video_player.attrs.get('data-length',0)
51 video['title'] = title
52 if not title:
53 video['title'] = soup.find('meta',{'property':'og:title'}).attrs['content'].replace('|','_').replace('/','_')
54 if 'dynamicStreams' in flashvars:
55 video['url'] = flashvars['dynamicStreams'][0].split('url:')[1].split('.mp4,')[0] +'.mp4'
56 filename = video['title']+".mp4"
57 print(Popen(["rtmpdump","-o"+filename,"-r", url], stdout=PIPE).communicate()[0])
58 if 'pathflv' in flashvars:
59 rtmp = flashvars['pathflv'][0]
60 filename = video['title']+".flv"
61 print(Popen(["mplayer","-dumpstream","-dumpfile",filename, rtmp], stdout=PIPE).communicate()[0])
62 if 'video' in flashvars:
63 for reference in flashvars['video']['videoReferences']:
64 if reference['url'].endswith("m3u8"):
65 video['url']=reference['url']
66 video['filename'] = video['title']+'.ts'
67 if 'statistics' in flashvars:
68 video['category'] = flashvars['statistics']['category']
69 download_from_playlist(video)
70 else:
71 print("Could not find any streams")
72 return
73 return video
74
75 def download_from_playlist(video):
76 playlist = parse_playlist(requests.get(video['url']).text)
77 if not playlist:
78 return
79 videourl = sorted(playlist, key=lambda k: int(k['BANDWIDTH']))[-1]['url']
80 segments, metadata = parse_segment_playlist(requests.get(videourl).text)
81 if "EXT-X-KEY" in metadata:
82 key = requests.get(metadata["EXT-X-KEY"]['URI'].strip('"')).text
83 decrypt=True
84 else:
85 decrypt=False
86 with open("%s"%video['filename'],"wb") as ofile:
87 segment=0
88 size = 0
89 for url in segments:
90 ufile = requests.get(url, stream=True).raw
91 print("\r{} MB".format(size/1024/1024))
92 sys.stdout.flush()
93 if decrypt:
94 iv=struct.pack("IIII",segment,0,0,0)
95 decryptor = AES.new(key, AES.MODE_CBC, iv)
96 while(True):
97 buf = ufile.read(4096)
98 if not buf:
99 break
100 if decrypt:
101 buf = decryptor.decrypt(buf)
102 ofile.write(buf)
103 size += len(buf)
104 segment += 1
105
106 def parse_playlist(playlist):
107 if not playlist.startswith("#EXTM3U"):
108 print(playlist)
109 return False
110 playlist = playlist.splitlines()[1:]
111 items=[]
112 for (metadata_string,url) in zip(playlist[0::2], playlist[1::2]):
113 md = dict()
114 assert 'EXT-X-STREAM-INF' in metadata_string.split(':')[0]
115 for item in metadata_string.split(':')[1].split(','):
116 if '=' in item:
117 md.update([item.split('='),])
118 md['url']=url
119 items.append(md)
120 return items
121
122 def parse_segment_playlist(playlist):
123 assert playlist.startswith("#EXTM3U")
124 PATTERN = re.compile(r'''((?:[^,"']|"[^"]*"|'[^']*')+)''')
125 segments = []
126 next_is_url=False
127 metadata = {}
128 for row in playlist.splitlines():
129 if next_is_url:
130 segments.append(row)
131 next_is_url=False
132 continue
133 if 'EXTINF' in row:
134 next_is_url=True
135 if "EXT-X-KEY" in row:
136 row = row.split(':',1)[1] #skip first part
137 parts = PATTERN.split(row)[1:-1] #do magic re split and keep quotes
138 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
139 return(segments, metadata)
140
141 def parse_videolist():
142 page_num = 1
143 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
144 page_tot = int(soup.find('a',{'data-currentpage':True}).attrs['data-lastpage'])
145 videos_per_page = 8
146 video_num = 0
147 while(page_num <= page_tot):
148 base_url = "http://www.svtplay.se/ajax/videos?sida={}".format(page_num)
149 soup = BeautifulSoup(requests.get(base_url).text)
150 for article in soup.findAll('article'):
151 meta = dict(article.attrs)
152 video = {}
153 video['title'] = meta['data-title']
154 video['description'] = meta['data-description']
155 video['url'] = dict(article.find('a').attrs)['href']
156 video['thumb-url'] = dict(article.find('img',{}).attrs)['src']
157 video['num'] = video_num
158 video['total'] = page_tot * videos_per_page
159 video_num += 1
160 yield video
161 page_num += 1
162
163
164 if __name__ == "__main__":
165 parser = argparse.ArgumentParser()
166 group = parser.add_mutually_exclusive_group(required=True)
167 group.add_argument("-r", "--rss", help="Download all files in rss")
168 group.add_argument("-u", "--url", help="Download video in url")
169 group.add_argument("-m", "--mirror", help="Mirror all files", action="store_true")
170 parser.add_argument("-n", "--no_act", help="Just print what would be done, don't do any downloading.", action="store_true")
171 args = parser.parse_args()
172 if args.rss:
173 import feedparser
174 d = feedparser.parse(args.rss)
175 for e in d.entries:
176 print(("Downloading: %s"%e.title))
177 if args.no_act:
178 continue
179 filename = scrape_player_page(e.link, e.title)
180 print(Popen(["avconv","-i",filename,"-vcodec","copy","-acodec","copy", filename+'.mkv'], stdout=PIPE).communicate()[0])
181 #print(e.description)
182 if args.mirror:
183 for video in parse_videolist():
184 video['title'] = video['title'].replace('/','_')
185 print(video['title']+'.mkv')
186 print("{} of {}".format(video['num'], video['total']))
187 if os.path.exists(video['title']+'.mkv'):
188 print("Skipping")
189 continue
190 print("Downloading...")
191 if args.no_act:
192 continue
193 ret = scrape_player_page(video['url'], video['title'])
194 print(ret)
195 print(Popen(["avconv","-i",video['title']+'.ts',"-vcodec","copy","-acodec","copy", video['title']+'.mkv'], stdout=PIPE).communicate()[0])
196 try:
197 os.unlink(video['title']+'.ts')
198 except:
199 import pdb;pdb.set_trace()
200 else:
201 if not args.no_act:
202 video = scrape_player_page(args.url, None)
203 print(("Downloaded {}".format(args.url)))