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