vimeo.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import base64
  4. import json
  5. import re
  6. import itertools
  7. from .common import InfoExtractor
  8. from ..compat import (
  9. compat_HTTPError,
  10. compat_str,
  11. compat_urlparse,
  12. )
  13. from ..utils import (
  14. determine_ext,
  15. ExtractorError,
  16. js_to_json,
  17. InAdvancePagedList,
  18. int_or_none,
  19. merge_dicts,
  20. NO_DEFAULT,
  21. parse_filesize,
  22. qualities,
  23. RegexNotFoundError,
  24. sanitized_Request,
  25. smuggle_url,
  26. std_headers,
  27. try_get,
  28. unified_timestamp,
  29. unsmuggle_url,
  30. urlencode_postdata,
  31. unescapeHTML,
  32. )
  33. class VimeoBaseInfoExtractor(InfoExtractor):
  34. _NETRC_MACHINE = 'vimeo'
  35. _LOGIN_REQUIRED = False
  36. _LOGIN_URL = 'https://vimeo.com/log_in'
  37. def _login(self):
  38. username, password = self._get_login_info()
  39. if username is None:
  40. if self._LOGIN_REQUIRED:
  41. raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
  42. return
  43. webpage = self._download_webpage(
  44. self._LOGIN_URL, None, 'Downloading login page')
  45. token, vuid = self._extract_xsrft_and_vuid(webpage)
  46. data = {
  47. 'action': 'login',
  48. 'email': username,
  49. 'password': password,
  50. 'service': 'vimeo',
  51. 'token': token,
  52. }
  53. self._set_vimeo_cookie('vuid', vuid)
  54. try:
  55. self._download_webpage(
  56. self._LOGIN_URL, None, 'Logging in',
  57. data=urlencode_postdata(data), headers={
  58. 'Content-Type': 'application/x-www-form-urlencoded',
  59. 'Referer': self._LOGIN_URL,
  60. })
  61. except ExtractorError as e:
  62. if isinstance(e.cause, compat_HTTPError) and e.cause.code == 418:
  63. raise ExtractorError(
  64. 'Unable to log in: bad username or password',
  65. expected=True)
  66. raise ExtractorError('Unable to log in')
  67. def _verify_video_password(self, url, video_id, webpage):
  68. password = self._downloader.params.get('videopassword')
  69. if password is None:
  70. raise ExtractorError('This video is protected by a password, use the --video-password option', expected=True)
  71. token, vuid = self._extract_xsrft_and_vuid(webpage)
  72. data = urlencode_postdata({
  73. 'password': password,
  74. 'token': token,
  75. })
  76. if url.startswith('http://'):
  77. # vimeo only supports https now, but the user can give an http url
  78. url = url.replace('http://', 'https://')
  79. password_request = sanitized_Request(url + '/password', data)
  80. password_request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  81. password_request.add_header('Referer', url)
  82. self._set_vimeo_cookie('vuid', vuid)
  83. return self._download_webpage(
  84. password_request, video_id,
  85. 'Verifying the password', 'Wrong password')
  86. def _extract_xsrft_and_vuid(self, webpage):
  87. xsrft = self._search_regex(
  88. r'(?:(?P<q1>["\'])xsrft(?P=q1)\s*:|xsrft\s*[=:])\s*(?P<q>["\'])(?P<xsrft>.+?)(?P=q)',
  89. webpage, 'login token', group='xsrft')
  90. vuid = self._search_regex(
  91. r'["\']vuid["\']\s*:\s*(["\'])(?P<vuid>.+?)\1',
  92. webpage, 'vuid', group='vuid')
  93. return xsrft, vuid
  94. def _set_vimeo_cookie(self, name, value):
  95. self._set_cookie('vimeo.com', name, value)
  96. def _vimeo_sort_formats(self, formats):
  97. # Bitrates are completely broken. Single m3u8 may contain entries in kbps and bps
  98. # at the same time without actual units specified. This lead to wrong sorting.
  99. self._sort_formats(formats, field_preference=('preference', 'height', 'width', 'fps', 'tbr', 'format_id'))
  100. def _parse_config(self, config, video_id):
  101. video_data = config['video']
  102. video_title = video_data['title']
  103. is_live = try_get(video_data, lambda x: x['live_event']['status']) == 'started'
  104. formats = []
  105. config_files = video_data.get('files') or config['request'].get('files', {})
  106. for f in config_files.get('progressive', []):
  107. video_url = f.get('url')
  108. if not video_url:
  109. continue
  110. formats.append({
  111. 'url': video_url,
  112. 'format_id': 'http-%s' % f.get('quality'),
  113. 'width': int_or_none(f.get('width')),
  114. 'height': int_or_none(f.get('height')),
  115. 'fps': int_or_none(f.get('fps')),
  116. 'tbr': int_or_none(f.get('bitrate')),
  117. })
  118. for files_type in ('hls', 'dash'):
  119. for cdn_name, cdn_data in config_files.get(files_type, {}).get('cdns', {}).items():
  120. manifest_url = cdn_data.get('url')
  121. if not manifest_url:
  122. continue
  123. format_id = '%s-%s' % (files_type, cdn_name)
  124. if files_type == 'hls':
  125. formats.extend(self._extract_m3u8_formats(
  126. manifest_url, video_id, 'mp4',
  127. 'm3u8' if is_live else 'm3u8_native', m3u8_id=format_id,
  128. note='Downloading %s m3u8 information' % cdn_name,
  129. fatal=False))
  130. elif files_type == 'dash':
  131. mpd_pattern = r'/%s/(?:sep/)?video/' % video_id
  132. mpd_manifest_urls = []
  133. if re.search(mpd_pattern, manifest_url):
  134. for suffix, repl in (('', 'video'), ('_sep', 'sep/video')):
  135. mpd_manifest_urls.append((format_id + suffix, re.sub(
  136. mpd_pattern, '/%s/%s/' % (video_id, repl), manifest_url)))
  137. else:
  138. mpd_manifest_urls = [(format_id, manifest_url)]
  139. for f_id, m_url in mpd_manifest_urls:
  140. if 'json=1' in m_url:
  141. real_m_url = (self._download_json(m_url, video_id, fatal=False) or {}).get('url')
  142. if real_m_url:
  143. m_url = real_m_url
  144. mpd_formats = self._extract_mpd_formats(
  145. m_url.replace('/master.json', '/master.mpd'), video_id, f_id,
  146. 'Downloading %s MPD information' % cdn_name,
  147. fatal=False)
  148. for f in mpd_formats:
  149. if f.get('vcodec') == 'none':
  150. f['preference'] = -50
  151. elif f.get('acodec') == 'none':
  152. f['preference'] = -40
  153. formats.extend(mpd_formats)
  154. subtitles = {}
  155. text_tracks = config['request'].get('text_tracks')
  156. if text_tracks:
  157. for tt in text_tracks:
  158. subtitles[tt['lang']] = [{
  159. 'ext': 'vtt',
  160. 'url': 'https://vimeo.com' + tt['url'],
  161. }]
  162. thumbnails = []
  163. if not is_live:
  164. for key, thumb in video_data.get('thumbs', {}).items():
  165. thumbnails.append({
  166. 'id': key,
  167. 'width': int_or_none(key),
  168. 'url': thumb,
  169. })
  170. thumbnail = video_data.get('thumbnail')
  171. if thumbnail:
  172. thumbnails.append({
  173. 'url': thumbnail,
  174. })
  175. owner = video_data.get('owner') or {}
  176. video_uploader_url = owner.get('url')
  177. return {
  178. 'title': self._live_title(video_title) if is_live else video_title,
  179. 'uploader': owner.get('name'),
  180. 'uploader_id': video_uploader_url.split('/')[-1] if video_uploader_url else None,
  181. 'uploader_url': video_uploader_url,
  182. 'thumbnails': thumbnails,
  183. 'duration': int_or_none(video_data.get('duration')),
  184. 'formats': formats,
  185. 'subtitles': subtitles,
  186. 'is_live': is_live,
  187. }
  188. def _extract_original_format(self, url, video_id):
  189. download_data = self._download_json(
  190. url, video_id, fatal=False,
  191. query={'action': 'load_download_config'},
  192. headers={'X-Requested-With': 'XMLHttpRequest'})
  193. if download_data:
  194. source_file = download_data.get('source_file')
  195. if isinstance(source_file, dict):
  196. download_url = source_file.get('download_url')
  197. if download_url and not source_file.get('is_cold') and not source_file.get('is_defrosting'):
  198. source_name = source_file.get('public_name', 'Original')
  199. if self._is_valid_url(download_url, video_id, '%s video' % source_name):
  200. ext = (try_get(
  201. source_file, lambda x: x['extension'],
  202. compat_str) or determine_ext(
  203. download_url, None) or 'mp4').lower()
  204. return {
  205. 'url': download_url,
  206. 'ext': ext,
  207. 'width': int_or_none(source_file.get('width')),
  208. 'height': int_or_none(source_file.get('height')),
  209. 'filesize': parse_filesize(source_file.get('size')),
  210. 'format_id': source_name,
  211. 'preference': 1,
  212. }
  213. class VimeoIE(VimeoBaseInfoExtractor):
  214. """Information extractor for vimeo.com."""
  215. # _VALID_URL matches Vimeo URLs
  216. _VALID_URL = r'''(?x)
  217. https?://
  218. (?:
  219. (?:
  220. www|
  221. (?P<player>player)
  222. )
  223. \.
  224. )?
  225. vimeo(?P<pro>pro)?\.com/
  226. (?!(?:channels|album)/[^/?#]+/?(?:$|[?#])|[^/]+/review/|ondemand/)
  227. (?:.*?/)?
  228. (?:
  229. (?:
  230. play_redirect_hls|
  231. moogaloop\.swf)\?clip_id=
  232. )?
  233. (?:videos?/)?
  234. (?P<id>[0-9]+)
  235. (?:/[\da-f]+)?
  236. /?(?:[?&].*)?(?:[#].*)?$
  237. '''
  238. IE_NAME = 'vimeo'
  239. _TESTS = [
  240. {
  241. 'url': 'http://vimeo.com/56015672#at=0',
  242. 'md5': '8879b6cc097e987f02484baf890129e5',
  243. 'info_dict': {
  244. 'id': '56015672',
  245. 'ext': 'mp4',
  246. 'title': "youtube-dl test video - \u2605 \" ' \u5e78 / \\ \u00e4 \u21ad \U0001d550",
  247. 'description': 'md5:509a9ad5c9bf97c60faee9203aca4479',
  248. 'timestamp': 1355990239,
  249. 'upload_date': '20121220',
  250. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/user7108434',
  251. 'uploader_id': 'user7108434',
  252. 'uploader': 'Filippo Valsorda',
  253. 'duration': 10,
  254. 'license': 'by-sa',
  255. },
  256. },
  257. {
  258. 'url': 'http://vimeopro.com/openstreetmapus/state-of-the-map-us-2013/video/68093876',
  259. 'md5': '3b5ca6aa22b60dfeeadf50b72e44ed82',
  260. 'note': 'Vimeo Pro video (#1197)',
  261. 'info_dict': {
  262. 'id': '68093876',
  263. 'ext': 'mp4',
  264. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/openstreetmapus',
  265. 'uploader_id': 'openstreetmapus',
  266. 'uploader': 'OpenStreetMap US',
  267. 'title': 'Andy Allan - Putting the Carto into OpenStreetMap Cartography',
  268. 'description': 'md5:fd69a7b8d8c34a4e1d2ec2e4afd6ec30',
  269. 'duration': 1595,
  270. },
  271. },
  272. {
  273. 'url': 'http://player.vimeo.com/video/54469442',
  274. 'md5': '619b811a4417aa4abe78dc653becf511',
  275. 'note': 'Videos that embed the url in the player page',
  276. 'info_dict': {
  277. 'id': '54469442',
  278. 'ext': 'mp4',
  279. 'title': 'Kathy Sierra: Building the minimum Badass User, Business of Software 2012',
  280. 'uploader': 'The BLN & Business of Software',
  281. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/theblnbusinessofsoftware',
  282. 'uploader_id': 'theblnbusinessofsoftware',
  283. 'duration': 3610,
  284. 'description': None,
  285. },
  286. },
  287. {
  288. 'url': 'http://vimeo.com/68375962',
  289. 'md5': 'aaf896bdb7ddd6476df50007a0ac0ae7',
  290. 'note': 'Video protected with password',
  291. 'info_dict': {
  292. 'id': '68375962',
  293. 'ext': 'mp4',
  294. 'title': 'youtube-dl password protected test video',
  295. 'timestamp': 1371200155,
  296. 'upload_date': '20130614',
  297. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/user18948128',
  298. 'uploader_id': 'user18948128',
  299. 'uploader': 'Jaime Marquínez Ferrándiz',
  300. 'duration': 10,
  301. 'description': 'md5:dca3ea23adb29ee387127bc4ddfce63f',
  302. },
  303. 'params': {
  304. 'videopassword': 'youtube-dl',
  305. },
  306. },
  307. {
  308. 'url': 'http://vimeo.com/channels/keypeele/75629013',
  309. 'md5': '2f86a05afe9d7abc0b9126d229bbe15d',
  310. 'info_dict': {
  311. 'id': '75629013',
  312. 'ext': 'mp4',
  313. 'title': 'Key & Peele: Terrorist Interrogation',
  314. 'description': 'md5:8678b246399b070816b12313e8b4eb5c',
  315. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/atencio',
  316. 'uploader_id': 'atencio',
  317. 'uploader': 'Peter Atencio',
  318. 'channel_id': 'keypeele',
  319. 'channel_url': r're:https?://(?:www\.)?vimeo\.com/channels/keypeele',
  320. 'timestamp': 1380339469,
  321. 'upload_date': '20130928',
  322. 'duration': 187,
  323. },
  324. 'expected_warnings': ['Unable to download JSON metadata'],
  325. },
  326. {
  327. 'url': 'http://vimeo.com/76979871',
  328. 'note': 'Video with subtitles',
  329. 'info_dict': {
  330. 'id': '76979871',
  331. 'ext': 'mp4',
  332. 'title': 'The New Vimeo Player (You Know, For Videos)',
  333. 'description': 'md5:2ec900bf97c3f389378a96aee11260ea',
  334. 'timestamp': 1381846109,
  335. 'upload_date': '20131015',
  336. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/staff',
  337. 'uploader_id': 'staff',
  338. 'uploader': 'Vimeo Staff',
  339. 'duration': 62,
  340. }
  341. },
  342. {
  343. # from https://www.ouya.tv/game/Pier-Solar-and-the-Great-Architects/
  344. 'url': 'https://player.vimeo.com/video/98044508',
  345. 'note': 'The js code contains assignments to the same variable as the config',
  346. 'info_dict': {
  347. 'id': '98044508',
  348. 'ext': 'mp4',
  349. 'title': 'Pier Solar OUYA Official Trailer',
  350. 'uploader': 'Tulio Gonçalves',
  351. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/user28849593',
  352. 'uploader_id': 'user28849593',
  353. },
  354. },
  355. {
  356. # contains original format
  357. 'url': 'https://vimeo.com/33951933',
  358. 'md5': '53c688fa95a55bf4b7293d37a89c5c53',
  359. 'info_dict': {
  360. 'id': '33951933',
  361. 'ext': 'mp4',
  362. 'title': 'FOX CLASSICS - Forever Classic ID - A Full Minute',
  363. 'uploader': 'The DMCI',
  364. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/dmci',
  365. 'uploader_id': 'dmci',
  366. 'timestamp': 1324343742,
  367. 'upload_date': '20111220',
  368. 'description': 'md5:ae23671e82d05415868f7ad1aec21147',
  369. },
  370. },
  371. {
  372. # only available via https://vimeo.com/channels/tributes/6213729 and
  373. # not via https://vimeo.com/6213729
  374. 'url': 'https://vimeo.com/channels/tributes/6213729',
  375. 'info_dict': {
  376. 'id': '6213729',
  377. 'ext': 'mp4',
  378. 'title': 'Vimeo Tribute: The Shining',
  379. 'uploader': 'Casey Donahue',
  380. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/caseydonahue',
  381. 'uploader_id': 'caseydonahue',
  382. 'channel_url': r're:https?://(?:www\.)?vimeo\.com/channels/tributes',
  383. 'channel_id': 'tributes',
  384. 'timestamp': 1250886430,
  385. 'upload_date': '20090821',
  386. 'description': 'md5:bdbf314014e58713e6e5b66eb252f4a6',
  387. },
  388. 'params': {
  389. 'skip_download': True,
  390. },
  391. 'expected_warnings': ['Unable to download JSON metadata'],
  392. },
  393. {
  394. # redirects to ondemand extractor and should be passed through it
  395. # for successful extraction
  396. 'url': 'https://vimeo.com/73445910',
  397. 'info_dict': {
  398. 'id': '73445910',
  399. 'ext': 'mp4',
  400. 'title': 'The Reluctant Revolutionary',
  401. 'uploader': '10Ft Films',
  402. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/tenfootfilms',
  403. 'uploader_id': 'tenfootfilms',
  404. },
  405. 'params': {
  406. 'skip_download': True,
  407. },
  408. },
  409. {
  410. 'url': 'http://player.vimeo.com/video/68375962',
  411. 'md5': 'aaf896bdb7ddd6476df50007a0ac0ae7',
  412. 'info_dict': {
  413. 'id': '68375962',
  414. 'ext': 'mp4',
  415. 'title': 'youtube-dl password protected test video',
  416. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/user18948128',
  417. 'uploader_id': 'user18948128',
  418. 'uploader': 'Jaime Marquínez Ferrándiz',
  419. 'duration': 10,
  420. },
  421. 'params': {
  422. 'videopassword': 'youtube-dl',
  423. },
  424. },
  425. {
  426. 'url': 'http://vimeo.com/moogaloop.swf?clip_id=2539741',
  427. 'only_matching': True,
  428. },
  429. {
  430. 'url': 'https://vimeo.com/109815029',
  431. 'note': 'Video not completely processed, "failed" seed status',
  432. 'only_matching': True,
  433. },
  434. {
  435. 'url': 'https://vimeo.com/groups/travelhd/videos/22439234',
  436. 'only_matching': True,
  437. },
  438. {
  439. 'url': 'https://vimeo.com/album/2632481/video/79010983',
  440. 'only_matching': True,
  441. },
  442. {
  443. # source file returns 403: Forbidden
  444. 'url': 'https://vimeo.com/7809605',
  445. 'only_matching': True,
  446. },
  447. {
  448. 'url': 'https://vimeo.com/160743502/abd0e13fb4',
  449. 'only_matching': True,
  450. }
  451. # https://gettingthingsdone.com/workflowmap/
  452. # vimeo embed with check-password page protected by Referer header
  453. ]
  454. @staticmethod
  455. def _smuggle_referrer(url, referrer_url):
  456. return smuggle_url(url, {'http_headers': {'Referer': referrer_url}})
  457. @staticmethod
  458. def _extract_urls(url, webpage):
  459. urls = []
  460. # Look for embedded (iframe) Vimeo player
  461. for mobj in re.finditer(
  462. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//player\.vimeo\.com/video/\d+.*?)\1',
  463. webpage):
  464. urls.append(VimeoIE._smuggle_referrer(unescapeHTML(mobj.group('url')), url))
  465. PLAIN_EMBED_RE = (
  466. # Look for embedded (swf embed) Vimeo player
  467. r'<embed[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?vimeo\.com/moogaloop\.swf.+?)\1',
  468. # Look more for non-standard embedded Vimeo player
  469. r'<video[^>]+src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?vimeo\.com/[0-9]+)\1',
  470. )
  471. for embed_re in PLAIN_EMBED_RE:
  472. for mobj in re.finditer(embed_re, webpage):
  473. urls.append(mobj.group('url'))
  474. return urls
  475. @staticmethod
  476. def _extract_url(url, webpage):
  477. urls = VimeoIE._extract_urls(url, webpage)
  478. return urls[0] if urls else None
  479. def _verify_player_video_password(self, url, video_id, headers):
  480. password = self._downloader.params.get('videopassword')
  481. if password is None:
  482. raise ExtractorError('This video is protected by a password, use the --video-password option')
  483. data = urlencode_postdata({
  484. 'password': base64.b64encode(password.encode()),
  485. })
  486. headers = merge_dicts(headers, {
  487. 'Content-Type': 'application/x-www-form-urlencoded',
  488. })
  489. checked = self._download_json(
  490. url + '/check-password', video_id,
  491. 'Verifying the password', data=data, headers=headers)
  492. if checked is False:
  493. raise ExtractorError('Wrong video password', expected=True)
  494. return checked
  495. def _real_initialize(self):
  496. self._login()
  497. def _real_extract(self, url):
  498. url, data = unsmuggle_url(url, {})
  499. headers = std_headers.copy()
  500. if 'http_headers' in data:
  501. headers.update(data['http_headers'])
  502. if 'Referer' not in headers:
  503. headers['Referer'] = url
  504. channel_id = self._search_regex(
  505. r'vimeo\.com/channels/([^/]+)', url, 'channel id', default=None)
  506. # Extract ID from URL
  507. mobj = re.match(self._VALID_URL, url)
  508. video_id = mobj.group('id')
  509. orig_url = url
  510. if mobj.group('pro'):
  511. # some videos require portfolio_id to be present in player url
  512. # https://github.com/ytdl-org/youtube-dl/issues/20070
  513. url = self._extract_url(url, self._download_webpage(url, video_id))
  514. elif mobj.group('player'):
  515. url = 'https://player.vimeo.com/video/' + video_id
  516. elif any(p in url for p in ('play_redirect_hls', 'moogaloop.swf')):
  517. url = 'https://vimeo.com/' + video_id
  518. # Retrieve video webpage to extract further information
  519. request = sanitized_Request(url, headers=headers)
  520. try:
  521. webpage, urlh = self._download_webpage_handle(request, video_id)
  522. redirect_url = compat_str(urlh.geturl())
  523. # Some URLs redirect to ondemand can't be extracted with
  524. # this extractor right away thus should be passed through
  525. # ondemand extractor (e.g. https://vimeo.com/73445910)
  526. if VimeoOndemandIE.suitable(redirect_url):
  527. return self.url_result(redirect_url, VimeoOndemandIE.ie_key())
  528. except ExtractorError as ee:
  529. if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 403:
  530. errmsg = ee.cause.read()
  531. if b'Because of its privacy settings, this video cannot be played here' in errmsg:
  532. raise ExtractorError(
  533. 'Cannot download embed-only video without embedding '
  534. 'URL. Please call youtube-dl with the URL of the page '
  535. 'that embeds this video.',
  536. expected=True)
  537. raise
  538. # Now we begin extracting as much information as we can from what we
  539. # retrieved. First we extract the information common to all extractors,
  540. # and latter we extract those that are Vimeo specific.
  541. self.report_extraction(video_id)
  542. vimeo_config = self._search_regex(
  543. r'vimeo\.config\s*=\s*(?:({.+?})|_extend\([^,]+,\s+({.+?})\));', webpage,
  544. 'vimeo config', default=None)
  545. if vimeo_config:
  546. seed_status = self._parse_json(vimeo_config, video_id).get('seed_status', {})
  547. if seed_status.get('state') == 'failed':
  548. raise ExtractorError(
  549. '%s said: %s' % (self.IE_NAME, seed_status['title']),
  550. expected=True)
  551. cc_license = None
  552. timestamp = None
  553. # Extract the config JSON
  554. try:
  555. try:
  556. config_url = self._html_search_regex(
  557. r' data-config-url="(.+?)"', webpage,
  558. 'config URL', default=None)
  559. if not config_url:
  560. # Sometimes new react-based page is served instead of old one that require
  561. # different config URL extraction approach (see
  562. # https://github.com/ytdl-org/youtube-dl/pull/7209)
  563. vimeo_clip_page_config = self._search_regex(
  564. r'vimeo\.clip_page_config\s*=\s*({.+?});', webpage,
  565. 'vimeo clip page config')
  566. page_config = self._parse_json(vimeo_clip_page_config, video_id)
  567. config_url = page_config['player']['config_url']
  568. cc_license = page_config.get('cc_license')
  569. timestamp = try_get(
  570. page_config, lambda x: x['clip']['uploaded_on'],
  571. compat_str)
  572. config_json = self._download_webpage(config_url, video_id)
  573. config = json.loads(config_json)
  574. except RegexNotFoundError:
  575. # For pro videos or player.vimeo.com urls
  576. # We try to find out to which variable is assigned the config dic
  577. m_variable_name = re.search(r'(\w)\.video\.id', webpage)
  578. if m_variable_name is not None:
  579. config_re = [r'%s=({[^}].+?});' % re.escape(m_variable_name.group(1))]
  580. else:
  581. config_re = [r' = {config:({.+?}),assets:', r'(?:[abc])=({.+?});']
  582. config_re.append(r'\bvar\s+r\s*=\s*({.+?})\s*;')
  583. config_re.append(r'\bconfig\s*=\s*({.+?})\s*;')
  584. config = self._search_regex(config_re, webpage, 'info section',
  585. flags=re.DOTALL)
  586. config = json.loads(config)
  587. except Exception as e:
  588. if re.search('The creator of this video has not given you permission to embed it on this domain.', webpage):
  589. raise ExtractorError('The author has restricted the access to this video, try with the "--referer" option')
  590. if re.search(r'<form[^>]+?id="pw_form"', webpage) is not None:
  591. if '_video_password_verified' in data:
  592. raise ExtractorError('video password verification failed!')
  593. self._verify_video_password(redirect_url, video_id, webpage)
  594. return self._real_extract(
  595. smuggle_url(redirect_url, {'_video_password_verified': 'verified'}))
  596. else:
  597. raise ExtractorError('Unable to extract info section',
  598. cause=e)
  599. else:
  600. if config.get('view') == 4:
  601. config = self._verify_player_video_password(redirect_url, video_id, headers)
  602. vod = config.get('video', {}).get('vod', {})
  603. def is_rented():
  604. if '>You rented this title.<' in webpage:
  605. return True
  606. if config.get('user', {}).get('purchased'):
  607. return True
  608. for purchase_option in vod.get('purchase_options', []):
  609. if purchase_option.get('purchased'):
  610. return True
  611. label = purchase_option.get('label_string')
  612. if label and (label.startswith('You rented this') or label.endswith(' remaining')):
  613. return True
  614. return False
  615. if is_rented() and vod.get('is_trailer'):
  616. feature_id = vod.get('feature_id')
  617. if feature_id and not data.get('force_feature_id', False):
  618. return self.url_result(smuggle_url(
  619. 'https://player.vimeo.com/player/%s' % feature_id,
  620. {'force_feature_id': True}), 'Vimeo')
  621. # Extract video description
  622. video_description = self._html_search_regex(
  623. r'(?s)<div\s+class="[^"]*description[^"]*"[^>]*>(.*?)</div>',
  624. webpage, 'description', default=None)
  625. if not video_description:
  626. video_description = self._html_search_meta(
  627. 'description', webpage, default=None)
  628. if not video_description and mobj.group('pro'):
  629. orig_webpage = self._download_webpage(
  630. orig_url, video_id,
  631. note='Downloading webpage for description',
  632. fatal=False)
  633. if orig_webpage:
  634. video_description = self._html_search_meta(
  635. 'description', orig_webpage, default=None)
  636. if not video_description and not mobj.group('player'):
  637. self._downloader.report_warning('Cannot find video description')
  638. # Extract upload date
  639. if not timestamp:
  640. timestamp = self._search_regex(
  641. r'<time[^>]+datetime="([^"]+)"', webpage,
  642. 'timestamp', default=None)
  643. try:
  644. view_count = int(self._search_regex(r'UserPlays:(\d+)', webpage, 'view count'))
  645. like_count = int(self._search_regex(r'UserLikes:(\d+)', webpage, 'like count'))
  646. comment_count = int(self._search_regex(r'UserComments:(\d+)', webpage, 'comment count'))
  647. except RegexNotFoundError:
  648. # This info is only available in vimeo.com/{id} urls
  649. view_count = None
  650. like_count = None
  651. comment_count = None
  652. formats = []
  653. source_format = self._extract_original_format(
  654. 'https://vimeo.com/' + video_id, video_id)
  655. if source_format:
  656. formats.append(source_format)
  657. info_dict_config = self._parse_config(config, video_id)
  658. formats.extend(info_dict_config['formats'])
  659. self._vimeo_sort_formats(formats)
  660. json_ld = self._search_json_ld(webpage, video_id, default={})
  661. if not cc_license:
  662. cc_license = self._search_regex(
  663. r'<link[^>]+rel=["\']license["\'][^>]+href=(["\'])(?P<license>(?:(?!\1).)+)\1',
  664. webpage, 'license', default=None, group='license')
  665. channel_url = 'https://vimeo.com/channels/%s' % channel_id if channel_id else None
  666. info_dict = {
  667. 'id': video_id,
  668. 'formats': formats,
  669. 'timestamp': unified_timestamp(timestamp),
  670. 'description': video_description,
  671. 'webpage_url': url,
  672. 'view_count': view_count,
  673. 'like_count': like_count,
  674. 'comment_count': comment_count,
  675. 'license': cc_license,
  676. 'channel_id': channel_id,
  677. 'channel_url': channel_url,
  678. }
  679. info_dict = merge_dicts(info_dict, info_dict_config, json_ld)
  680. return info_dict
  681. class VimeoOndemandIE(VimeoBaseInfoExtractor):
  682. IE_NAME = 'vimeo:ondemand'
  683. _VALID_URL = r'https?://(?:www\.)?vimeo\.com/ondemand/(?P<id>[^/?#&]+)'
  684. _TESTS = [{
  685. # ondemand video not available via https://vimeo.com/id
  686. 'url': 'https://vimeo.com/ondemand/20704',
  687. 'md5': 'c424deda8c7f73c1dfb3edd7630e2f35',
  688. 'info_dict': {
  689. 'id': '105442900',
  690. 'ext': 'mp4',
  691. 'title': 'המעבדה - במאי יותם פלדמן',
  692. 'uploader': 'גם סרטים',
  693. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/gumfilms',
  694. 'uploader_id': 'gumfilms',
  695. },
  696. 'params': {
  697. 'format': 'best[protocol=https]',
  698. },
  699. }, {
  700. # requires Referer to be passed along with og:video:url
  701. 'url': 'https://vimeo.com/ondemand/36938/126682985',
  702. 'info_dict': {
  703. 'id': '126682985',
  704. 'ext': 'mp4',
  705. 'title': 'Rävlock, rätt läte på rätt plats',
  706. 'uploader': 'Lindroth & Norin',
  707. 'uploader_url': r're:https?://(?:www\.)?vimeo\.com/user14430847',
  708. 'uploader_id': 'user14430847',
  709. },
  710. 'params': {
  711. 'skip_download': True,
  712. },
  713. }, {
  714. 'url': 'https://vimeo.com/ondemand/nazmaalik',
  715. 'only_matching': True,
  716. }, {
  717. 'url': 'https://vimeo.com/ondemand/141692381',
  718. 'only_matching': True,
  719. }, {
  720. 'url': 'https://vimeo.com/ondemand/thelastcolony/150274832',
  721. 'only_matching': True,
  722. }]
  723. def _real_extract(self, url):
  724. video_id = self._match_id(url)
  725. webpage = self._download_webpage(url, video_id)
  726. return self.url_result(
  727. # Some videos require Referer to be passed along with og:video:url
  728. # similarly to generic vimeo embeds (e.g.
  729. # https://vimeo.com/ondemand/36938/126682985).
  730. VimeoIE._smuggle_referrer(self._og_search_video_url(webpage), url),
  731. VimeoIE.ie_key())
  732. class VimeoChannelIE(VimeoBaseInfoExtractor):
  733. IE_NAME = 'vimeo:channel'
  734. _VALID_URL = r'https://vimeo\.com/channels/(?P<id>[^/?#]+)/?(?:$|[?#])'
  735. _MORE_PAGES_INDICATOR = r'<a.+?rel="next"'
  736. _TITLE = None
  737. _TITLE_RE = r'<link rel="alternate"[^>]+?title="(.*?)"'
  738. _TESTS = [{
  739. 'url': 'https://vimeo.com/channels/tributes',
  740. 'info_dict': {
  741. 'id': 'tributes',
  742. 'title': 'Vimeo Tributes',
  743. },
  744. 'playlist_mincount': 25,
  745. }]
  746. def _page_url(self, base_url, pagenum):
  747. return '%s/videos/page:%d/' % (base_url, pagenum)
  748. def _extract_list_title(self, webpage):
  749. return self._TITLE or self._html_search_regex(self._TITLE_RE, webpage, 'list title')
  750. def _login_list_password(self, page_url, list_id, webpage):
  751. login_form = self._search_regex(
  752. r'(?s)<form[^>]+?id="pw_form"(.*?)</form>',
  753. webpage, 'login form', default=None)
  754. if not login_form:
  755. return webpage
  756. password = self._downloader.params.get('videopassword')
  757. if password is None:
  758. raise ExtractorError('This album is protected by a password, use the --video-password option', expected=True)
  759. fields = self._hidden_inputs(login_form)
  760. token, vuid = self._extract_xsrft_and_vuid(webpage)
  761. fields['token'] = token
  762. fields['password'] = password
  763. post = urlencode_postdata(fields)
  764. password_path = self._search_regex(
  765. r'action="([^"]+)"', login_form, 'password URL')
  766. password_url = compat_urlparse.urljoin(page_url, password_path)
  767. password_request = sanitized_Request(password_url, post)
  768. password_request.add_header('Content-type', 'application/x-www-form-urlencoded')
  769. self._set_vimeo_cookie('vuid', vuid)
  770. self._set_vimeo_cookie('xsrft', token)
  771. return self._download_webpage(
  772. password_request, list_id,
  773. 'Verifying the password', 'Wrong password')
  774. def _title_and_entries(self, list_id, base_url):
  775. for pagenum in itertools.count(1):
  776. page_url = self._page_url(base_url, pagenum)
  777. webpage = self._download_webpage(
  778. page_url, list_id,
  779. 'Downloading page %s' % pagenum)
  780. if pagenum == 1:
  781. webpage = self._login_list_password(page_url, list_id, webpage)
  782. yield self._extract_list_title(webpage)
  783. # Try extracting href first since not all videos are available via
  784. # short https://vimeo.com/id URL (e.g. https://vimeo.com/channels/tributes/6213729)
  785. clips = re.findall(
  786. r'id="clip_(\d+)"[^>]*>\s*<a[^>]+href="(/(?:[^/]+/)*\1)(?:[^>]+\btitle="([^"]+)")?', webpage)
  787. if clips:
  788. for video_id, video_url, video_title in clips:
  789. yield self.url_result(
  790. compat_urlparse.urljoin(base_url, video_url),
  791. VimeoIE.ie_key(), video_id=video_id, video_title=video_title)
  792. # More relaxed fallback
  793. else:
  794. for video_id in re.findall(r'id=["\']clip_(\d+)', webpage):
  795. yield self.url_result(
  796. 'https://vimeo.com/%s' % video_id,
  797. VimeoIE.ie_key(), video_id=video_id)
  798. if re.search(self._MORE_PAGES_INDICATOR, webpage, re.DOTALL) is None:
  799. break
  800. def _extract_videos(self, list_id, base_url):
  801. title_and_entries = self._title_and_entries(list_id, base_url)
  802. list_title = next(title_and_entries)
  803. return self.playlist_result(title_and_entries, list_id, list_title)
  804. def _real_extract(self, url):
  805. mobj = re.match(self._VALID_URL, url)
  806. channel_id = mobj.group('id')
  807. return self._extract_videos(channel_id, 'https://vimeo.com/channels/%s' % channel_id)
  808. class VimeoUserIE(VimeoChannelIE):
  809. IE_NAME = 'vimeo:user'
  810. _VALID_URL = r'https://vimeo\.com/(?!(?:[0-9]+|watchlater)(?:$|[?#/]))(?P<name>[^/]+)(?:/videos|[#?]|$)'
  811. _TITLE_RE = r'<a[^>]+?class="user">([^<>]+?)</a>'
  812. _TESTS = [{
  813. 'url': 'https://vimeo.com/nkistudio/videos',
  814. 'info_dict': {
  815. 'title': 'Nki',
  816. 'id': 'nkistudio',
  817. },
  818. 'playlist_mincount': 66,
  819. }]
  820. def _real_extract(self, url):
  821. mobj = re.match(self._VALID_URL, url)
  822. name = mobj.group('name')
  823. return self._extract_videos(name, 'https://vimeo.com/%s' % name)
  824. class VimeoAlbumIE(VimeoChannelIE):
  825. IE_NAME = 'vimeo:album'
  826. _VALID_URL = r'https://vimeo\.com/album/(?P<id>\d+)(?:$|[?#]|/(?!video))'
  827. _TITLE_RE = r'<header id="page_header">\n\s*<h1>(.*?)</h1>'
  828. _TESTS = [{
  829. 'url': 'https://vimeo.com/album/2632481',
  830. 'info_dict': {
  831. 'id': '2632481',
  832. 'title': 'Staff Favorites: November 2013',
  833. },
  834. 'playlist_mincount': 13,
  835. }, {
  836. 'note': 'Password-protected album',
  837. 'url': 'https://vimeo.com/album/3253534',
  838. 'info_dict': {
  839. 'title': 'test',
  840. 'id': '3253534',
  841. },
  842. 'playlist_count': 1,
  843. 'params': {
  844. 'videopassword': 'youtube-dl',
  845. }
  846. }, {
  847. 'url': 'https://vimeo.com/album/2632481/sort:plays/format:thumbnail',
  848. 'only_matching': True,
  849. }, {
  850. # TODO: respect page number
  851. 'url': 'https://vimeo.com/album/2632481/page:2/sort:plays/format:thumbnail',
  852. 'only_matching': True,
  853. }]
  854. def _page_url(self, base_url, pagenum):
  855. return '%s/page:%d/' % (base_url, pagenum)
  856. def _real_extract(self, url):
  857. album_id = self._match_id(url)
  858. return self._extract_videos(album_id, 'https://vimeo.com/album/%s' % album_id)
  859. class VimeoGroupsIE(VimeoAlbumIE):
  860. IE_NAME = 'vimeo:group'
  861. _VALID_URL = r'https://vimeo\.com/groups/(?P<name>[^/]+)(?:/(?!videos?/\d+)|$)'
  862. _TESTS = [{
  863. 'url': 'https://vimeo.com/groups/rolexawards',
  864. 'info_dict': {
  865. 'id': 'rolexawards',
  866. 'title': 'Rolex Awards for Enterprise',
  867. },
  868. 'playlist_mincount': 73,
  869. }]
  870. def _extract_list_title(self, webpage):
  871. return self._og_search_title(webpage)
  872. def _real_extract(self, url):
  873. mobj = re.match(self._VALID_URL, url)
  874. name = mobj.group('name')
  875. return self._extract_videos(name, 'https://vimeo.com/groups/%s' % name)
  876. class VimeoReviewIE(VimeoBaseInfoExtractor):
  877. IE_NAME = 'vimeo:review'
  878. IE_DESC = 'Review pages on vimeo'
  879. _VALID_URL = r'(?P<url>https://vimeo\.com/[^/]+/review/(?P<id>[^/]+)/[0-9a-f]{10})'
  880. _TESTS = [{
  881. 'url': 'https://vimeo.com/user21297594/review/75524534/3c257a1b5d',
  882. 'md5': 'c507a72f780cacc12b2248bb4006d253',
  883. 'info_dict': {
  884. 'id': '75524534',
  885. 'ext': 'mp4',
  886. 'title': "DICK HARDWICK 'Comedian'",
  887. 'uploader': 'Richard Hardwick',
  888. 'uploader_id': 'user21297594',
  889. }
  890. }, {
  891. 'note': 'video player needs Referer',
  892. 'url': 'https://vimeo.com/user22258446/review/91613211/13f927e053',
  893. 'md5': '6295fdab8f4bf6a002d058b2c6dce276',
  894. 'info_dict': {
  895. 'id': '91613211',
  896. 'ext': 'mp4',
  897. 'title': 're:(?i)^Death by dogma versus assembling agile . Sander Hoogendoorn',
  898. 'uploader': 'DevWeek Events',
  899. 'duration': 2773,
  900. 'thumbnail': r're:^https?://.*\.jpg$',
  901. 'uploader_id': 'user22258446',
  902. }
  903. }, {
  904. 'note': 'Password protected',
  905. 'url': 'https://vimeo.com/user37284429/review/138823582/c4d865efde',
  906. 'info_dict': {
  907. 'id': '138823582',
  908. 'ext': 'mp4',
  909. 'title': 'EFFICIENT PICKUP MASTERCLASS MODULE 1',
  910. 'uploader': 'TMB',
  911. 'uploader_id': 'user37284429',
  912. },
  913. 'params': {
  914. 'videopassword': 'holygrail',
  915. },
  916. 'skip': 'video gone',
  917. }]
  918. def _real_initialize(self):
  919. self._login()
  920. def _get_config_url(self, webpage_url, video_id, video_password_verified=False):
  921. webpage = self._download_webpage(webpage_url, video_id)
  922. config_url = self._html_search_regex(
  923. r'data-config-url=(["\'])(?P<url>(?:(?!\1).)+)\1', webpage,
  924. 'config URL', default=None, group='url')
  925. if not config_url:
  926. data = self._parse_json(self._search_regex(
  927. r'window\s*=\s*_extend\(window,\s*({.+?})\);', webpage, 'data',
  928. default=NO_DEFAULT if video_password_verified else '{}'), video_id)
  929. config = data.get('vimeo_esi', {}).get('config', {})
  930. config_url = config.get('configUrl') or try_get(config, lambda x: x['clipData']['configUrl'])
  931. if config_url is None:
  932. self._verify_video_password(webpage_url, video_id, webpage)
  933. config_url = self._get_config_url(
  934. webpage_url, video_id, video_password_verified=True)
  935. return config_url
  936. def _real_extract(self, url):
  937. page_url, video_id = re.match(self._VALID_URL, url).groups()
  938. config_url = self._get_config_url(url, video_id)
  939. config = self._download_json(config_url, video_id)
  940. info_dict = self._parse_config(config, video_id)
  941. source_format = self._extract_original_format(page_url, video_id)
  942. if source_format:
  943. info_dict['formats'].append(source_format)
  944. self._vimeo_sort_formats(info_dict['formats'])
  945. info_dict['id'] = video_id
  946. return info_dict
  947. class VimeoWatchLaterIE(VimeoChannelIE):
  948. IE_NAME = 'vimeo:watchlater'
  949. IE_DESC = 'Vimeo watch later list, "vimeowatchlater" keyword (requires authentication)'
  950. _VALID_URL = r'https://vimeo\.com/(?:home/)?watchlater|:vimeowatchlater'
  951. _TITLE = 'Watch Later'
  952. _LOGIN_REQUIRED = True
  953. _TESTS = [{
  954. 'url': 'https://vimeo.com/watchlater',
  955. 'only_matching': True,
  956. }]
  957. def _real_initialize(self):
  958. self._login()
  959. def _page_url(self, base_url, pagenum):
  960. url = '%s/page:%d/' % (base_url, pagenum)
  961. request = sanitized_Request(url)
  962. # Set the header to get a partial html page with the ids,
  963. # the normal page doesn't contain them.
  964. request.add_header('X-Requested-With', 'XMLHttpRequest')
  965. return request
  966. def _real_extract(self, url):
  967. return self._extract_videos('watchlater', 'https://vimeo.com/watchlater')
  968. class VimeoLikesIE(InfoExtractor):
  969. _VALID_URL = r'https://(?:www\.)?vimeo\.com/(?P<id>[^/]+)/likes/?(?:$|[?#]|sort:)'
  970. IE_NAME = 'vimeo:likes'
  971. IE_DESC = 'Vimeo user likes'
  972. _TESTS = [{
  973. 'url': 'https://vimeo.com/user755559/likes/',
  974. 'playlist_mincount': 293,
  975. 'info_dict': {
  976. 'id': 'user755559_likes',
  977. 'description': 'See all the videos urza likes',
  978. 'title': 'Videos urza likes',
  979. },
  980. }, {
  981. 'url': 'https://vimeo.com/stormlapse/likes',
  982. 'only_matching': True,
  983. }]
  984. def _real_extract(self, url):
  985. user_id = self._match_id(url)
  986. webpage = self._download_webpage(url, user_id)
  987. page_count = self._int(
  988. self._search_regex(
  989. r'''(?x)<li><a\s+href="[^"]+"\s+data-page="([0-9]+)">
  990. .*?</a></li>\s*<li\s+class="pagination_next">
  991. ''', webpage, 'page count', default=1),
  992. 'page count', fatal=True)
  993. PAGE_SIZE = 12
  994. title = self._html_search_regex(
  995. r'(?s)<h1>(.+?)</h1>', webpage, 'title', fatal=False)
  996. description = self._html_search_meta('description', webpage)
  997. def _get_page(idx):
  998. page_url = 'https://vimeo.com/%s/likes/page:%d/sort:date' % (
  999. user_id, idx + 1)
  1000. webpage = self._download_webpage(
  1001. page_url, user_id,
  1002. note='Downloading page %d/%d' % (idx + 1, page_count))
  1003. video_list = self._search_regex(
  1004. r'(?s)<ol class="js-browse_list[^"]+"[^>]*>(.*?)</ol>',
  1005. webpage, 'video content')
  1006. paths = re.findall(
  1007. r'<li[^>]*>\s*<a\s+href="([^"]+)"', video_list)
  1008. for path in paths:
  1009. yield {
  1010. '_type': 'url',
  1011. 'url': compat_urlparse.urljoin(page_url, path),
  1012. }
  1013. pl = InAdvancePagedList(_get_page, page_count, PAGE_SIZE)
  1014. return {
  1015. '_type': 'playlist',
  1016. 'id': '%s_likes' % user_id,
  1017. 'title': title,
  1018. 'description': description,
  1019. 'entries': pl,
  1020. }
  1021. class VHXEmbedIE(InfoExtractor):
  1022. IE_NAME = 'vhx:embed'
  1023. _VALID_URL = r'https?://embed\.vhx\.tv/videos/(?P<id>\d+)'
  1024. def _call_api(self, video_id, access_token, path='', query=None):
  1025. return self._download_json(
  1026. 'https://api.vhx.tv/videos/' + video_id + path, video_id, headers={
  1027. 'Authorization': 'Bearer ' + access_token,
  1028. }, query=query)
  1029. def _real_extract(self, url):
  1030. video_id = self._match_id(url)
  1031. webpage = self._download_webpage(url, video_id)
  1032. credentials = self._parse_json(self._search_regex(
  1033. r'(?s)credentials\s*:\s*({.+?}),', webpage,
  1034. 'config'), video_id, js_to_json)
  1035. access_token = credentials['access_token']
  1036. query = {}
  1037. for k, v in credentials.items():
  1038. if k in ('authorization', 'authUserToken', 'ticket') and v and v != 'undefined':
  1039. if k == 'authUserToken':
  1040. query['auth_user_token'] = v
  1041. else:
  1042. query[k] = v
  1043. files = self._call_api(video_id, access_token, '/files', query)
  1044. formats = []
  1045. for f in files:
  1046. href = try_get(f, lambda x: x['_links']['source']['href'])
  1047. if not href:
  1048. continue
  1049. method = f.get('method')
  1050. if method == 'hls':
  1051. formats.extend(self._extract_m3u8_formats(
  1052. href, video_id, 'mp4', 'm3u8_native',
  1053. m3u8_id='hls', fatal=False))
  1054. elif method == 'dash':
  1055. formats.extend(self._extract_mpd_formats(
  1056. href, video_id, mpd_id='dash', fatal=False))
  1057. else:
  1058. fmt = {
  1059. 'filesize': int_or_none(try_get(f, lambda x: x['size']['bytes'])),
  1060. 'format_id': 'http',
  1061. 'preference': 1,
  1062. 'url': href,
  1063. 'vcodec': f.get('codec'),
  1064. }
  1065. quality = f.get('quality')
  1066. if quality:
  1067. fmt.update({
  1068. 'format_id': 'http-' + quality,
  1069. 'height': int_or_none(self._search_regex(r'(\d+)p', quality, 'height', default=None)),
  1070. })
  1071. formats.append(fmt)
  1072. self._sort_formats(formats)
  1073. video_data = self._call_api(video_id, access_token)
  1074. title = video_data.get('title') or video_data['name']
  1075. subtitles = {}
  1076. for subtitle in try_get(video_data, lambda x: x['tracks']['subtitles'], list) or []:
  1077. lang = subtitle.get('srclang') or subtitle.get('label')
  1078. for _link in subtitle.get('_links', {}).values():
  1079. href = _link.get('href')
  1080. if not href:
  1081. continue
  1082. subtitles.setdefault(lang, []).append({
  1083. 'url': href,
  1084. })
  1085. q = qualities(['small', 'medium', 'large', 'source'])
  1086. thumbnails = []
  1087. for thumbnail_id, thumbnail_url in video_data.get('thumbnail', {}).items():
  1088. thumbnails.append({
  1089. 'id': thumbnail_id,
  1090. 'url': thumbnail_url,
  1091. 'preference': q(thumbnail_id),
  1092. })
  1093. return {
  1094. 'id': video_id,
  1095. 'title': title,
  1096. 'description': video_data.get('description'),
  1097. 'duration': int_or_none(try_get(video_data, lambda x: x['duration']['seconds'])),
  1098. 'formats': formats,
  1099. 'subtitles': subtitles,
  1100. 'thumbnails': thumbnails,
  1101. 'timestamp': unified_timestamp(video_data.get('created_at')),
  1102. 'view_count': int_or_none(video_data.get('plays_count')),
  1103. }