vimeo.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. # encoding: utf-8
  2. from __future__ import unicode_literals
  3. import json
  4. import re
  5. import itertools
  6. from .common import InfoExtractor
  7. from .subtitles import SubtitlesInfoExtractor
  8. from ..utils import (
  9. compat_HTTPError,
  10. compat_urllib_parse,
  11. compat_urllib_request,
  12. clean_html,
  13. get_element_by_attribute,
  14. ExtractorError,
  15. RegexNotFoundError,
  16. smuggle_url,
  17. std_headers,
  18. unsmuggle_url,
  19. urlencode_postdata,
  20. int_or_none,
  21. )
  22. class VimeoBaseInfoExtractor(InfoExtractor):
  23. _NETRC_MACHINE = 'vimeo'
  24. _LOGIN_REQUIRED = False
  25. def _login(self):
  26. (username, password) = self._get_login_info()
  27. if username is None:
  28. if self._LOGIN_REQUIRED:
  29. raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
  30. return
  31. self.report_login()
  32. login_url = 'https://vimeo.com/log_in'
  33. webpage = self._download_webpage(login_url, None, False)
  34. token = self._search_regex(r'xsrft: \'(.*?)\'', webpage, 'login token')
  35. data = urlencode_postdata({
  36. 'email': username,
  37. 'password': password,
  38. 'action': 'login',
  39. 'service': 'vimeo',
  40. 'token': token,
  41. })
  42. login_request = compat_urllib_request.Request(login_url, data)
  43. login_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  44. login_request.add_header('Cookie', 'xsrft=%s' % token)
  45. self._download_webpage(login_request, None, False, 'Wrong login info')
  46. class VimeoIE(VimeoBaseInfoExtractor, SubtitlesInfoExtractor):
  47. """Information extractor for vimeo.com."""
  48. # _VALID_URL matches Vimeo URLs
  49. _VALID_URL = r'''(?x)
  50. (?P<proto>(?:https?:)?//)?
  51. (?:(?:www|(?P<player>player))\.)?
  52. vimeo(?P<pro>pro)?\.com/
  53. (?!channels/[^/?#]+/?(?:$|[?#])|album/)
  54. (?:.*?/)?
  55. (?:(?:play_redirect_hls|moogaloop\.swf)\?clip_id=)?
  56. (?:videos?/)?
  57. (?P<id>[0-9]+)
  58. /?(?:[?&].*)?(?:[#].*)?$'''
  59. IE_NAME = 'vimeo'
  60. _TESTS = [
  61. {
  62. 'url': 'http://vimeo.com/56015672#at=0',
  63. 'md5': '8879b6cc097e987f02484baf890129e5',
  64. 'info_dict': {
  65. 'id': '56015672',
  66. 'ext': 'mp4',
  67. "upload_date": "20121220",
  68. "description": "This is a test case for youtube-dl.\nFor more information, see github.com/rg3/youtube-dl\nTest chars: \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550",
  69. "uploader_id": "user7108434",
  70. "uploader": "Filippo Valsorda",
  71. "title": "youtube-dl test video - \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550",
  72. "duration": 10,
  73. },
  74. },
  75. {
  76. 'url': 'http://vimeopro.com/openstreetmapus/state-of-the-map-us-2013/video/68093876',
  77. 'md5': '3b5ca6aa22b60dfeeadf50b72e44ed82',
  78. 'note': 'Vimeo Pro video (#1197)',
  79. 'info_dict': {
  80. 'id': '68093876',
  81. 'ext': 'mp4',
  82. 'uploader_id': 'openstreetmapus',
  83. 'uploader': 'OpenStreetMap US',
  84. 'title': 'Andy Allan - Putting the Carto into OpenStreetMap Cartography',
  85. 'duration': 1595,
  86. },
  87. },
  88. {
  89. 'url': 'http://player.vimeo.com/video/54469442',
  90. 'md5': '619b811a4417aa4abe78dc653becf511',
  91. 'note': 'Videos that embed the url in the player page',
  92. 'info_dict': {
  93. 'id': '54469442',
  94. 'ext': 'mp4',
  95. 'title': 'Kathy Sierra: Building the minimum Badass User, Business of Software 2012',
  96. 'uploader': 'The BLN & Business of Software',
  97. 'uploader_id': 'theblnbusinessofsoftware',
  98. 'duration': 3610,
  99. },
  100. },
  101. {
  102. 'url': 'http://vimeo.com/68375962',
  103. 'md5': 'aaf896bdb7ddd6476df50007a0ac0ae7',
  104. 'note': 'Video protected with password',
  105. 'info_dict': {
  106. 'id': '68375962',
  107. 'ext': 'mp4',
  108. 'title': 'youtube-dl password protected test video',
  109. 'upload_date': '20130614',
  110. 'uploader_id': 'user18948128',
  111. 'uploader': 'Jaime Marquínez Ferrándiz',
  112. 'duration': 10,
  113. },
  114. 'params': {
  115. 'videopassword': 'youtube-dl',
  116. },
  117. },
  118. {
  119. 'url': 'http://vimeo.com/channels/keypeele/75629013',
  120. 'md5': '2f86a05afe9d7abc0b9126d229bbe15d',
  121. 'note': 'Video is freely available via original URL '
  122. 'and protected with password when accessed via http://vimeo.com/75629013',
  123. 'info_dict': {
  124. 'id': '75629013',
  125. 'ext': 'mp4',
  126. 'title': 'Key & Peele: Terrorist Interrogation',
  127. 'description': 'md5:8678b246399b070816b12313e8b4eb5c',
  128. 'uploader_id': 'atencio',
  129. 'uploader': 'Peter Atencio',
  130. 'duration': 187,
  131. },
  132. },
  133. {
  134. 'url': 'http://vimeo.com/76979871',
  135. 'md5': '3363dd6ffebe3784d56f4132317fd446',
  136. 'note': 'Video with subtitles',
  137. 'info_dict': {
  138. 'id': '76979871',
  139. 'ext': 'mp4',
  140. 'title': 'The New Vimeo Player (You Know, For Videos)',
  141. 'description': 'md5:2ec900bf97c3f389378a96aee11260ea',
  142. 'upload_date': '20131015',
  143. 'uploader_id': 'staff',
  144. 'uploader': 'Vimeo Staff',
  145. 'duration': 62,
  146. }
  147. },
  148. ]
  149. def _verify_video_password(self, url, video_id, webpage):
  150. password = self._downloader.params.get('videopassword', None)
  151. if password is None:
  152. raise ExtractorError('This video is protected by a password, use the --video-password option')
  153. token = self._search_regex(r'xsrft: \'(.*?)\'', webpage, 'login token')
  154. data = compat_urllib_parse.urlencode({
  155. 'password': password,
  156. 'token': token,
  157. })
  158. # I didn't manage to use the password with https
  159. if url.startswith('https'):
  160. pass_url = url.replace('https', 'http')
  161. else:
  162. pass_url = url
  163. password_request = compat_urllib_request.Request(pass_url + '/password', data)
  164. password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  165. password_request.add_header('Cookie', 'xsrft=%s' % token)
  166. self._download_webpage(password_request, video_id,
  167. 'Verifying the password',
  168. 'Wrong password')
  169. def _verify_player_video_password(self, url, video_id):
  170. password = self._downloader.params.get('videopassword', None)
  171. if password is None:
  172. raise ExtractorError('This video is protected by a password, use the --video-password option')
  173. data = compat_urllib_parse.urlencode({'password': password})
  174. pass_url = url + '/check-password'
  175. password_request = compat_urllib_request.Request(pass_url, data)
  176. password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  177. return self._download_json(
  178. password_request, video_id,
  179. 'Verifying the password',
  180. 'Wrong password')
  181. def _real_initialize(self):
  182. self._login()
  183. def _real_extract(self, url):
  184. url, data = unsmuggle_url(url)
  185. headers = std_headers
  186. if data is not None:
  187. headers = headers.copy()
  188. headers.update(data)
  189. if 'Referer' not in headers:
  190. headers['Referer'] = url
  191. # Extract ID from URL
  192. mobj = re.match(self._VALID_URL, url)
  193. video_id = mobj.group('id')
  194. if mobj.group('pro') or mobj.group('player'):
  195. url = 'http://player.vimeo.com/video/' + video_id
  196. # Retrieve video webpage to extract further information
  197. request = compat_urllib_request.Request(url, None, headers)
  198. try:
  199. webpage = self._download_webpage(request, video_id)
  200. except ExtractorError as ee:
  201. if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
  202. errmsg = ee.cause.read()
  203. if b'Because of its privacy settings, this video cannot be played here' in errmsg:
  204. raise ExtractorError(
  205. 'Cannot download embed-only video without embedding '
  206. 'URL. Please call youtube-dl with the URL of the page '
  207. 'that embeds this video.',
  208. expected=True)
  209. raise
  210. # Now we begin extracting as much information as we can from what we
  211. # retrieved. First we extract the information common to all extractors,
  212. # and latter we extract those that are Vimeo specific.
  213. self.report_extraction(video_id)
  214. # Extract the config JSON
  215. try:
  216. try:
  217. config_url = self._html_search_regex(
  218. r' data-config-url="(.+?)"', webpage, 'config URL')
  219. config_json = self._download_webpage(config_url, video_id)
  220. config = json.loads(config_json)
  221. except RegexNotFoundError:
  222. # For pro videos or player.vimeo.com urls
  223. # We try to find out to which variable is assigned the config dic
  224. m_variable_name = re.search('(\w)\.video\.id', webpage)
  225. if m_variable_name is not None:
  226. config_re = r'%s=({.+?});' % re.escape(m_variable_name.group(1))
  227. else:
  228. config_re = [r' = {config:({.+?}),assets:', r'(?:[abc])=({.+?});']
  229. config = self._search_regex(config_re, webpage, 'info section',
  230. flags=re.DOTALL)
  231. config = json.loads(config)
  232. except Exception as e:
  233. if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
  234. raise ExtractorError('The author has restricted the access to this video, try with the "--referer" option')
  235. if re.search('<form[^>]+?id="pw_form"', webpage) is not None:
  236. self._verify_video_password(url, video_id, webpage)
  237. return self._real_extract(url)
  238. else:
  239. raise ExtractorError('Unable to extract info section',
  240. cause=e)
  241. else:
  242. if config.get('view') == 4:
  243. config = self._verify_player_video_password(url, video_id)
  244. # Extract title
  245. video_title = config["video"]["title"]
  246. # Extract uploader and uploader_id
  247. video_uploader = config["video"]["owner"]["name"]
  248. video_uploader_id = config["video"]["owner"]["url"].split('/')[-1] if config["video"]["owner"]["url"] else None
  249. # Extract video thumbnail
  250. video_thumbnail = config["video"].get("thumbnail")
  251. if video_thumbnail is None:
  252. video_thumbs = config["video"].get("thumbs")
  253. if video_thumbs and isinstance(video_thumbs, dict):
  254. _, video_thumbnail = sorted((int(width if width.isdigit() else 0), t_url) for (width, t_url) in video_thumbs.items())[-1]
  255. # Extract video description
  256. video_description = None
  257. try:
  258. video_description = get_element_by_attribute("class", "description_wrapper", webpage)
  259. if video_description:
  260. video_description = clean_html(video_description)
  261. except AssertionError as err:
  262. # On some pages like (http://player.vimeo.com/video/54469442) the
  263. # html tags are not closed, python 2.6 cannot handle it
  264. if err.args[0] == 'we should not get here!':
  265. pass
  266. else:
  267. raise
  268. # Extract video duration
  269. video_duration = int_or_none(config["video"].get("duration"))
  270. # Extract upload date
  271. video_upload_date = None
  272. mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
  273. if mobj is not None:
  274. video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
  275. try:
  276. view_count = int(self._search_regex(r'UserPlays:(\d+)', webpage, 'view count'))
  277. like_count = int(self._search_regex(r'UserLikes:(\d+)', webpage, 'like count'))
  278. comment_count = int(self._search_regex(r'UserComments:(\d+)', webpage, 'comment count'))
  279. except RegexNotFoundError:
  280. # This info is only available in vimeo.com/{id} urls
  281. view_count = None
  282. like_count = None
  283. comment_count = None
  284. # Vimeo specific: extract request signature and timestamp
  285. sig = config['request']['signature']
  286. timestamp = config['request']['timestamp']
  287. # Vimeo specific: extract video codec and quality information
  288. # First consider quality, then codecs, then take everything
  289. codecs = [('vp6', 'flv'), ('vp8', 'flv'), ('h264', 'mp4')]
  290. files = {'hd': [], 'sd': [], 'other': []}
  291. config_files = config["video"].get("files") or config["request"].get("files")
  292. for codec_name, codec_extension in codecs:
  293. for quality in config_files.get(codec_name, []):
  294. format_id = '-'.join((codec_name, quality)).lower()
  295. key = quality if quality in files else 'other'
  296. video_url = None
  297. if isinstance(config_files[codec_name], dict):
  298. file_info = config_files[codec_name][quality]
  299. video_url = file_info.get('url')
  300. else:
  301. file_info = {}
  302. if video_url is None:
  303. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  304. % (video_id, sig, timestamp, quality, codec_name.upper())
  305. files[key].append({
  306. 'ext': codec_extension,
  307. 'url': video_url,
  308. 'format_id': format_id,
  309. 'width': file_info.get('width'),
  310. 'height': file_info.get('height'),
  311. })
  312. formats = []
  313. for key in ('other', 'sd', 'hd'):
  314. formats += files[key]
  315. if len(formats) == 0:
  316. raise ExtractorError('No known codec found')
  317. subtitles = {}
  318. text_tracks = config['request'].get('text_tracks')
  319. if text_tracks:
  320. for tt in text_tracks:
  321. subtitles[tt['lang']] = 'http://vimeo.com' + tt['url']
  322. video_subtitles = self.extract_subtitles(video_id, subtitles)
  323. if self._downloader.params.get('listsubtitles', False):
  324. self._list_available_subtitles(video_id, subtitles)
  325. return
  326. return {
  327. 'id': video_id,
  328. 'uploader': video_uploader,
  329. 'uploader_id': video_uploader_id,
  330. 'upload_date': video_upload_date,
  331. 'title': video_title,
  332. 'thumbnail': video_thumbnail,
  333. 'description': video_description,
  334. 'duration': video_duration,
  335. 'formats': formats,
  336. 'webpage_url': url,
  337. 'view_count': view_count,
  338. 'like_count': like_count,
  339. 'comment_count': comment_count,
  340. 'subtitles': video_subtitles,
  341. }
  342. class VimeoChannelIE(InfoExtractor):
  343. IE_NAME = 'vimeo:channel'
  344. _VALID_URL = r'https?://vimeo\.com/channels/(?P<id>[^/?#]+)/?(?:$|[?#])'
  345. _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
  346. _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
  347. _TESTS = [{
  348. 'url': 'http://vimeo.com/channels/tributes',
  349. 'info_dict': {
  350. 'title': 'Vimeo Tributes',
  351. },
  352. 'playlist_mincount': 25,
  353. }]
  354. def _page_url(self, base_url, pagenum):
  355. return '%s/videos/page:%d/' % (base_url, pagenum)
  356. def _extract_list_title(self, webpage):
  357. return self._html_search_regex(self._TITLE_RE, webpage, 'list title')
  358. def _extract_videos(self, list_id, base_url):
  359. video_ids = []
  360. for pagenum in itertools.count(1):
  361. webpage = self._download_webpage(
  362. self._page_url(base_url, pagenum), list_id,
  363. 'Downloading page %s' % pagenum)
  364. video_ids.extend(re.findall(r'id="clip_(\d+?)"', webpage))
  365. if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
  366. break
  367. entries = [self.url_result('http://vimeo.com/%s' % video_id, 'Vimeo')
  368. for video_id in video_ids]
  369. return {'_type': 'playlist',
  370. 'id': list_id,
  371. 'title': self._extract_list_title(webpage),
  372. 'entries': entries,
  373. }
  374. def _real_extract(self, url):
  375. mobj = re.match(self._VALID_URL, url)
  376. channel_id = mobj.group('id')
  377. return self._extract_videos(channel_id, 'http://vimeo.com/channels/%s' % channel_id)
  378. class VimeoUserIE(VimeoChannelIE):
  379. IE_NAME = 'vimeo:user'
  380. _VALID_URL = r'https?://vimeo\.com/(?![0-9]+(?:$|[?#/]))(?P<name>[^/]+)(?:/videos|[#?]|$)'
  381. _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
  382. _TESTS = [{
  383. 'url': 'http://vimeo.com/nkistudio/videos',
  384. 'info_dict': {
  385. 'title': 'Nki',
  386. },
  387. 'playlist_mincount': 66,
  388. }]
  389. def _real_extract(self, url):
  390. mobj = re.match(self._VALID_URL, url)
  391. name = mobj.group('name')
  392. return self._extract_videos(name, 'http://vimeo.com/%s' % name)
  393. class VimeoAlbumIE(VimeoChannelIE):
  394. IE_NAME = 'vimeo:album'
  395. _VALID_URL = r'https?://vimeo\.com/album/(?P<id>\d+)'
  396. _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
  397. _TESTS = [{
  398. 'url': 'http://vimeo.com/album/2632481',
  399. 'info_dict': {
  400. 'title': 'Staff Favorites: November 2013',
  401. },
  402. 'playlist_mincount': 13,
  403. }]
  404. def _page_url(self, base_url, pagenum):
  405. return '%s/page:%d/' % (base_url, pagenum)
  406. def _real_extract(self, url):
  407. mobj = re.match(self._VALID_URL, url)
  408. album_id = mobj.group('id')
  409. return self._extract_videos(album_id, 'http://vimeo.com/album/%s' % album_id)
  410. class VimeoGroupsIE(VimeoAlbumIE):
  411. IE_NAME = 'vimeo:group'
  412. _VALID_URL = r'(?:https?://)?vimeo\.com/groups/(?P<name>[^/]+)'
  413. _TESTS = [{
  414. 'url': 'http://vimeo.com/groups/rolexawards',
  415. 'info_dict': {
  416. 'title': 'Rolex Awards for Enterprise',
  417. },
  418. 'playlist_mincount': 73,
  419. }]
  420. def _extract_list_title(self, webpage):
  421. return self._og_search_title(webpage)
  422. def _real_extract(self, url):
  423. mobj = re.match(self._VALID_URL, url)
  424. name = mobj.group('name')
  425. return self._extract_videos(name, 'http://vimeo.com/groups/%s' % name)
  426. class VimeoReviewIE(InfoExtractor):
  427. IE_NAME = 'vimeo:review'
  428. IE_DESC = 'Review pages on vimeo'
  429. _VALID_URL = r'https?://vimeo\.com/[^/]+/review/(?P<id>[^/]+)'
  430. _TESTS = [{
  431. 'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
  432. 'file': '75524534.mp4',
  433. 'md5': 'c507a72f780cacc12b2248bb4006d253',
  434. 'info_dict': {
  435. 'title': "DICK HARDWICK 'Comedian'",
  436. 'uploader': 'Richard Hardwick',
  437. }
  438. }, {
  439. 'note': 'video player needs Referer',
  440. 'url': 'http://vimeo.com/user22258446/review/91613211/13f927e053',
  441. 'md5': '6295fdab8f4bf6a002d058b2c6dce276',
  442. 'info_dict': {
  443. 'id': '91613211',
  444. 'ext': 'mp4',
  445. 'title': 'Death by dogma versus assembling agile - Sander Hoogendoorn',
  446. 'uploader': 'DevWeek Events',
  447. 'duration': 2773,
  448. 'thumbnail': 're:^https?://.*\.jpg$',
  449. }
  450. }]
  451. def _real_extract(self, url):
  452. mobj = re.match(self._VALID_URL, url)
  453. video_id = mobj.group('id')
  454. player_url = 'https://player.vimeo.com/player/' + video_id
  455. return self.url_result(player_url, 'Vimeo', video_id)
  456. class VimeoWatchLaterIE(VimeoBaseInfoExtractor, VimeoChannelIE):
  457. IE_NAME = 'vimeo:watchlater'
  458. IE_DESC = 'Vimeo watch later list, "vimeowatchlater" keyword (requires authentication)'
  459. _VALID_URL = r'https?://vimeo\.com/home/watchlater|:vimeowatchlater'
  460. _LOGIN_REQUIRED = True
  461. _TITLE_RE = r'href="/home/watchlater".*?>(.*?)<'
  462. _TESTS = [{
  463. 'url': 'http://vimeo.com/home/watchlater',
  464. 'only_matching': True,
  465. }]
  466. def _real_initialize(self):
  467. self._login()
  468. def _page_url(self, base_url, pagenum):
  469. url = '%s/page:%d/' % (base_url, pagenum)
  470. request = compat_urllib_request.Request(url)
  471. # Set the header to get a partial html page with the ids,
  472. # the normal page doesn't contain them.
  473. request.add_header('X-Requested-With', 'XMLHttpRequest')
  474. return request
  475. def _real_extract(self, url):
  476. return self._extract_videos('watchlater', 'https://vimeo.com/home/watchlater')
  477. class VimeoLikesIE(InfoExtractor):
  478. _VALID_URL = r'https?://(?:www\.)?vimeo\.com/user(?P<id>[0-9]+)/likes(?:$|[?#])'
  479. IE_NAME = 'vimeo:likes'
  480. IE_DESC = 'Vimeo user likes'
  481. _TEST = {
  482. 'url': 'https://vimeo.com/user20132939/likes',
  483. 'playlist_mincount': 4,
  484. 'add_ies': ['Generic'],
  485. "info_dict": {
  486. "description": "Videos Philipp Hagemeister likes on Vimeo.",
  487. "title": "Vimeo / Philipp Hagemeister's likes",
  488. },
  489. 'params': {
  490. 'extract_flat': False,
  491. },
  492. }
  493. def _real_extract(self, url):
  494. user_id = self._match_id(url)
  495. rss_url = '%s//vimeo.com/user%s/likes/rss' % (
  496. self.http_scheme(), user_id)
  497. surl = smuggle_url(rss_url, {
  498. 'force_videoid': '%s_likes' % user_id,
  499. 'to_generic': True,
  500. })
  501. return {
  502. '_type': 'url',
  503. 'url': surl,
  504. }