]>
Commit | Line | Data |
---|---|---|
1 | #!/usr/bin/env python | |
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 BeautifulSoup import BeautifulSoup | |
26 | from subprocess import * | |
27 | import re | |
28 | import json | |
29 | from Crypto.Cipher import AES | |
30 | import struct | |
31 | import argparse | |
32 | import feedparser | |
33 | try: | |
34 | import urlparse | |
35 | except ImportError: | |
36 | pass | |
37 | import urllib2 | |
38 | try: | |
39 | import urllib2.urlparse as urlparse | |
40 | except ImportError: | |
41 | pass | |
42 | import sys, os | |
43 | ||
44 | def main(url, title): | |
45 | """ | |
46 | Try to scrape the site for video and download. | |
47 | """ | |
48 | if not url.startswith('http'): | |
49 | url = "http://www.svtplay.se" + url | |
50 | video = {} | |
51 | page = urllib2.urlopen(url).read() | |
52 | soup = BeautifulSoup(page,convertEntities=BeautifulSoup.HTML_ENTITIES) | |
53 | video_player = soup.body('a',{'data-json-href':True})[0] | |
54 | flashvars = json.loads(urllib2.urlopen("http://www.svtplay.se/%s"%video_player.attrMap['data-json-href']+"?output=json").read()) | |
55 | video['title'] = title | |
56 | if not title: | |
57 | video['title'] = soup.find('meta',{'property':'og:title'}).attrMap['content'].replace('|','_').replace('/','_') | |
58 | if 'dynamicStreams' in flashvars: | |
59 | video['url'] = flashvars['dynamicStreams'][0].split('url:')[1].split('.mp4,')[0] +'.mp4' | |
60 | filename = video['title']+".mp4" | |
61 | print Popen(["rtmpdump",u"-o"+filename,"-r", url], stdout=PIPE).communicate()[0] | |
62 | if 'pathflv' in flashvars: | |
63 | rtmp = flashvars['pathflv'][0] | |
64 | filename = video['title']+".flv" | |
65 | print Popen(["mplayer","-dumpstream","-dumpfile",filename, rtmp], stdout=PIPE).communicate()[0] | |
66 | if 'video' in flashvars: | |
67 | for reference in flashvars['video']['videoReferences']: | |
68 | if reference['url'].endswith("m3u8"): | |
69 | video['url']=reference['url'] | |
70 | video['filename'] = video['title']+'.ts' | |
71 | if 'statistics' in flashvars: | |
72 | video['category'] = flashvars['statistics']['category'] | |
73 | download_from_playlist(video) | |
74 | else: | |
75 | print "Could not find any streams" | |
76 | return | |
77 | return video | |
78 | ||
79 | def download_from_playlist(video): | |
80 | playlist = parse_playlist(urllib2.urlopen(video['url']).read()) | |
81 | videourl = sorted(playlist, key=lambda k: int(k['BANDWIDTH']))[-1]['url'] | |
82 | segments, metadata = parse_segment_playlist(urllib2.urlopen(videourl).read()) | |
83 | if "EXT-X-KEY" in metadata: | |
84 | key = urllib2.urlopen(metadata["EXT-X-KEY"]['URI'].strip('"')).read() | |
85 | decrypt=True | |
86 | else: | |
87 | decrypt=False | |
88 | with open("%s"%video['filename'],"w") as ofile: | |
89 | segment=0 | |
90 | size = 0 | |
91 | for url in segments: | |
92 | ufile = urllib2.urlopen(url) | |
93 | print "\r{} MB".format(size/1024/1024), | |
94 | sys.stdout.flush() | |
95 | if decrypt: | |
96 | iv=struct.pack("IIII",segment,0,0,0) | |
97 | decryptor = AES.new(key, AES.MODE_CBC, iv) | |
98 | while(True): | |
99 | buf = ufile.read(1024) | |
100 | if buf: | |
101 | if decrypt: | |
102 | buf = decryptor.decrypt(buf) | |
103 | ofile.write(buf) | |
104 | size += len(buf) | |
105 | else: | |
106 | ufile.close() | |
107 | break | |
108 | segment += 1 | |
109 | ||
110 | def parse_playlist(playlist): | |
111 | if not playlist.startswith("#EXTM3U"): | |
112 | print playlist | |
113 | return False | |
114 | playlist = playlist.splitlines()[1:] | |
115 | items=[] | |
116 | for (metadata_string,url) in zip(playlist[0::2], playlist[1::2]): | |
117 | md = dict() | |
118 | assert 'EXT-X-STREAM-INF' in metadata_string.split(':')[0] | |
119 | for item in metadata_string.split(':')[1].split(','): | |
120 | if '=' in item: | |
121 | md.update([item.split('='),]) | |
122 | md['url']=url | |
123 | items.append(md) | |
124 | return items | |
125 | ||
126 | def parse_segment_playlist(playlist): | |
127 | assert playlist.startswith("#EXTM3U") | |
128 | PATTERN = re.compile(r'''((?:[^,"']|"[^"]*"|'[^']*')+)''') | |
129 | segments = [] | |
130 | next_is_url=False | |
131 | metadata = {} | |
132 | for row in playlist.splitlines(): | |
133 | if next_is_url: | |
134 | segments.append(row) | |
135 | next_is_url=False | |
136 | continue | |
137 | if 'EXTINF' in row: | |
138 | next_is_url=True | |
139 | if "EXT-X-KEY" in row: | |
140 | row = row.split(':',1)[1] #skip first part | |
141 | parts = PATTERN.split(row)[1:-1] #do magic re split and keep quotes | |
142 | 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 | |
143 | return(segments, metadata) | |
144 | def parse_videolist(): | |
145 | page = urllib2.urlopen("http://www.svtplay.se/ajax/videos?antal=100").read() | |
146 | soup = BeautifulSoup(page,convertEntities=BeautifulSoup.HTML_ENTITIES) | |
147 | videos = [] | |
148 | for article in soup.findAll('article'): | |
149 | meta = dict(article.attrs) | |
150 | video = {} | |
151 | video['title'] = meta['data-title'] | |
152 | video['description'] = meta['data-description'] | |
153 | video['url'] = dict(article.find('a').attrs)['href'] | |
154 | videos.append(video) | |
155 | return videos | |
156 | ||
157 | if __name__ == "__main__": | |
158 | parser = argparse.ArgumentParser() | |
159 | parser.add_argument("-r", "--rss", help="Download all files in rss") | |
160 | parser.add_argument("-u", "--url", help="Download video in url") | |
161 | parser.add_argument("-m", "--mirror", help="Mirror all files", action="store_true") | |
162 | ||
163 | args = parser.parse_args() | |
164 | ||
165 | if args.rss: | |
166 | d = feedparser.parse(args.url) | |
167 | for e in d.entries: | |
168 | print("Downloading: %s"%e.title) | |
169 | filename = main(e.link, e.title) | |
170 | print Popen(["avconv","-i",filename,"-vcodec","copy","-acodec","copy", filename+'.mkv'], stdout=PIPE).communicate()[0] | |
171 | #print(e.description) | |
172 | if args.mirror: | |
173 | for video in parse_videolist(): | |
174 | video['title'] = video['title'].replace('/','_') | |
175 | print video['title']+'.mkv', | |
176 | if os.path.exists(video['title']+'.mkv'): | |
177 | print "Skipping" | |
178 | continue | |
179 | print("Downloading...") | |
180 | ret = main(video['url'], video['title']) | |
181 | ||
182 | print Popen(["avconv","-i",video['title']+'.ts',"-vcodec","copy","-acodec","copy", video['title']+'.mkv'], stdout=PIPE).communicate()[0] | |
183 | try: | |
184 | os.unlink(video['title']+'.ts') | |
185 | except: | |
186 | import pdb;pdb.set_trace() | |
187 | else: | |
188 | video = main(args.url, None) | |
189 | print("Downloaded {}".format(video['title'])) |