]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/vimeo.py
cc9c8d0188749761b79b90652d3c0c843a24eda3
[youtubedl] / youtube_dl / extractor / vimeo.py
1 import json
2 import re
3 import itertools
4
5 from .common import InfoExtractor
6 from ..utils import (
7 compat_urllib_parse,
8 compat_urllib_request,
9
10 clean_html,
11 get_element_by_attribute,
12 ExtractorError,
13 std_headers,
14 )
15
16 class VimeoIE(InfoExtractor):
17 """Information extractor for vimeo.com."""
18
19 # _VALID_URL matches Vimeo URLs
20 _VALID_URL = r'(?P<proto>https?://)?(?:(?:www|player)\.)?vimeo(?P<pro>pro)?\.com/(?:(?:(?:groups|album)/[^/]+)|(?:.*?)/)?(?P<direct_link>play_redirect_hls\?clip_id=)?(?:videos?/)?(?P<id>[0-9]+)(?:[?].*)?$'
21 _NETRC_MACHINE = 'vimeo'
22 IE_NAME = u'vimeo'
23 _TEST = {
24 u'url': u'http://vimeo.com/56015672',
25 u'file': u'56015672.mp4',
26 u'md5': u'8879b6cc097e987f02484baf890129e5',
27 u'info_dict': {
28 u"upload_date": u"20121220",
29 u"description": u"This is a test case for youtube-dl.\nFor more information, see github.com/rg3/youtube-dl\nTest chars: \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550",
30 u"uploader_id": u"user7108434",
31 u"uploader": u"Filippo Valsorda",
32 u"title": u"youtube-dl test video - \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550"
33 }
34 }
35
36 def _login(self):
37 (username, password) = self._get_login_info()
38 if username is None:
39 return
40 self.report_login()
41 login_url = 'https://vimeo.com/log_in'
42 webpage = self._download_webpage(login_url, None, False)
43 token = re.search(r'xsrft: \'(.*?)\'', webpage).group(1)
44 data = compat_urllib_parse.urlencode({'email': username,
45 'password': password,
46 'action': 'login',
47 'service': 'vimeo',
48 'token': token,
49 })
50 login_request = compat_urllib_request.Request(login_url, data)
51 login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
52 login_request.add_header('Cookie', 'xsrft=%s' % token)
53 self._download_webpage(login_request, None, False, u'Wrong login info')
54
55 def _verify_video_password(self, url, video_id, webpage):
56 password = self._downloader.params.get('videopassword', None)
57 if password is None:
58 raise ExtractorError(u'This video is protected by a password, use the --video-password option')
59 token = re.search(r'xsrft: \'(.*?)\'', webpage).group(1)
60 data = compat_urllib_parse.urlencode({'password': password,
61 'token': token})
62 # I didn't manage to use the password with https
63 if url.startswith('https'):
64 pass_url = url.replace('https','http')
65 else:
66 pass_url = url
67 password_request = compat_urllib_request.Request(pass_url+'/password', data)
68 password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
69 password_request.add_header('Cookie', 'xsrft=%s' % token)
70 self._download_webpage(password_request, video_id,
71 u'Verifying the password',
72 u'Wrong password')
73
74 def _real_initialize(self):
75 self._login()
76
77 def _real_extract(self, url, new_video=True):
78 # Extract ID from URL
79 mobj = re.match(self._VALID_URL, url)
80 if mobj is None:
81 raise ExtractorError(u'Invalid URL: %s' % url)
82
83 video_id = mobj.group('id')
84 if not mobj.group('proto'):
85 url = 'https://' + url
86 if mobj.group('direct_link') or mobj.group('pro'):
87 url = 'https://vimeo.com/' + video_id
88
89 # Retrieve video webpage to extract further information
90 request = compat_urllib_request.Request(url, None, std_headers)
91 webpage = self._download_webpage(request, video_id)
92
93 # Now we begin extracting as much information as we can from what we
94 # retrieved. First we extract the information common to all extractors,
95 # and latter we extract those that are Vimeo specific.
96 self.report_extraction(video_id)
97
98 # Extract the config JSON
99 try:
100 config = webpage.split(' = {config:')[1].split(',assets:')[0]
101 config = json.loads(config)
102 except:
103 if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
104 raise ExtractorError(u'The author has restricted the access to this video, try with the "--referer" option')
105
106 if re.search('If so please provide the correct password.', webpage):
107 self._verify_video_password(url, video_id, webpage)
108 return self._real_extract(url)
109 else:
110 raise ExtractorError(u'Unable to extract info section')
111
112 # Extract title
113 video_title = config["video"]["title"]
114
115 # Extract uploader and uploader_id
116 video_uploader = config["video"]["owner"]["name"]
117 video_uploader_id = config["video"]["owner"]["url"].split('/')[-1] if config["video"]["owner"]["url"] else None
118
119 # Extract video thumbnail
120 video_thumbnail = config["video"]["thumbnail"]
121
122 # Extract video description
123 video_description = get_element_by_attribute("itemprop", "description", webpage)
124 if video_description: video_description = clean_html(video_description)
125 else: video_description = u''
126
127 # Extract upload date
128 video_upload_date = None
129 mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
130 if mobj is not None:
131 video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
132
133 # Vimeo specific: extract request signature and timestamp
134 sig = config['request']['signature']
135 timestamp = config['request']['timestamp']
136
137 # Vimeo specific: extract video codec and quality information
138 # First consider quality, then codecs, then take everything
139 # TODO bind to format param
140 codecs = [('h264', 'mp4'), ('vp8', 'flv'), ('vp6', 'flv')]
141 files = { 'hd': [], 'sd': [], 'other': []}
142 for codec_name, codec_extension in codecs:
143 if codec_name in config["video"]["files"]:
144 if 'hd' in config["video"]["files"][codec_name]:
145 files['hd'].append((codec_name, codec_extension, 'hd'))
146 elif 'sd' in config["video"]["files"][codec_name]:
147 files['sd'].append((codec_name, codec_extension, 'sd'))
148 else:
149 files['other'].append((codec_name, codec_extension, config["video"]["files"][codec_name][0]))
150
151 for quality in ('hd', 'sd', 'other'):
152 if len(files[quality]) > 0:
153 video_quality = files[quality][0][2]
154 video_codec = files[quality][0][0]
155 video_extension = files[quality][0][1]
156 self.to_screen(u'%s: Downloading %s file at %s quality' % (video_id, video_codec.upper(), video_quality))
157 break
158 else:
159 raise ExtractorError(u'No known codec found')
160
161 video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
162 %(video_id, sig, timestamp, video_quality, video_codec.upper())
163
164 return [{
165 'id': video_id,
166 'url': video_url,
167 'uploader': video_uploader,
168 'uploader_id': video_uploader_id,
169 'upload_date': video_upload_date,
170 'title': video_title,
171 'ext': video_extension,
172 'thumbnail': video_thumbnail,
173 'description': video_description,
174 }]
175
176
177 class VimeoChannelIE(InfoExtractor):
178 IE_NAME = u'vimeo:channel'
179 _VALID_URL = r'(?:https?://)?vimeo.\com/channels/(?P<id>[^/]+)'
180 _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
181
182 def _real_extract(self, url):
183 mobj = re.match(self._VALID_URL, url)
184 channel_id = mobj.group('id')
185 video_ids = []
186
187 for pagenum in itertools.count(1):
188 webpage = self._download_webpage('http://vimeo.com/channels/%s/videos/page:%d' % (channel_id, pagenum),
189 channel_id, u'Downloading page %s' % pagenum)
190 video_ids.extend(re.findall(r'id="clip_(\d+?)"', webpage))
191 if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
192 break
193
194 entries = [self.url_result('http://vimeo.com/%s' % video_id, 'Vimeo')
195 for video_id in video_ids]
196 channel_title = self._html_search_regex(r'<a href="/channels/%s">(.*?)</a>' % channel_id,
197 webpage, u'channel title')
198 return {'_type': 'playlist',
199 'id': channel_id,
200 'title': channel_title,
201 'entries': entries,
202 }