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