You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

815 lines
33 KiB

11 years ago
11 years ago
11 years ago
  1. # encoding: utf-8
  2. from __future__ import unicode_literals
  3. import os
  4. import re
  5. from .common import InfoExtractor
  6. from .youtube import YoutubeIE
  7. from ..utils import (
  8. compat_urllib_error,
  9. compat_urllib_parse,
  10. compat_urllib_request,
  11. compat_urlparse,
  12. compat_xml_parse_error,
  13. ExtractorError,
  14. HEADRequest,
  15. orderedSet,
  16. parse_xml,
  17. smuggle_url,
  18. unescapeHTML,
  19. unified_strdate,
  20. url_basename,
  21. )
  22. from .brightcove import BrightcoveIE
  23. from .ooyala import OoyalaIE
  24. from .rutv import RUTVIE
  25. from .smotri import SmotriIE
  26. class GenericIE(InfoExtractor):
  27. IE_DESC = 'Generic downloader that works on some sites'
  28. _VALID_URL = r'.*'
  29. IE_NAME = 'generic'
  30. _TESTS = [
  31. {
  32. 'url': 'http://www.hodiho.fr/2013/02/regis-plante-sa-jeep.html',
  33. 'md5': '85b90ccc9d73b4acd9138d3af4c27f89',
  34. 'info_dict': {
  35. 'id': '13601338388002',
  36. 'ext': 'mp4',
  37. 'uploader': 'www.hodiho.fr',
  38. 'title': 'R\u00e9gis plante sa Jeep',
  39. }
  40. },
  41. # bandcamp page with custom domain
  42. {
  43. 'add_ie': ['Bandcamp'],
  44. 'url': 'http://bronyrock.com/track/the-pony-mash',
  45. 'info_dict': {
  46. 'id': '3235767654',
  47. 'ext': 'mp3',
  48. 'title': 'The Pony Mash',
  49. 'uploader': 'M_Pallante',
  50. },
  51. 'skip': 'There is a limit of 200 free downloads / month for the test song',
  52. },
  53. # embedded brightcove video
  54. # it also tests brightcove videos that need to set the 'Referer' in the
  55. # http requests
  56. {
  57. 'add_ie': ['Brightcove'],
  58. 'url': 'http://www.bfmtv.com/video/bfmbusiness/cours-bourse/cours-bourse-l-analyse-technique-154522/',
  59. 'info_dict': {
  60. 'id': '2765128793001',
  61. 'ext': 'mp4',
  62. 'title': 'Le cours de bourse : l’analyse technique',
  63. 'description': 'md5:7e9ad046e968cb2d1114004aba466fd9',
  64. 'uploader': 'BFM BUSINESS',
  65. },
  66. 'params': {
  67. 'skip_download': True,
  68. },
  69. },
  70. {
  71. # https://github.com/rg3/youtube-dl/issues/2253
  72. 'url': 'http://bcove.me/i6nfkrc3',
  73. 'md5': '0ba9446db037002366bab3b3eb30c88c',
  74. 'info_dict': {
  75. 'id': '3101154703001',
  76. 'ext': 'mp4',
  77. 'title': 'Still no power',
  78. 'uploader': 'thestar.com',
  79. 'description': 'Mississauga resident David Farmer is still out of power as a result of the ice storm a month ago. To keep the house warm, Farmer cuts wood from his property for a wood burning stove downstairs.',
  80. },
  81. 'add_ie': ['Brightcove'],
  82. },
  83. {
  84. 'url': 'http://www.championat.com/video/football/v/87/87499.html',
  85. 'md5': 'fb973ecf6e4a78a67453647444222983',
  86. 'info_dict': {
  87. 'id': '3414141473001',
  88. 'ext': 'mp4',
  89. 'title': 'Видео. Удаление Дзагоева (ЦСКА)',
  90. 'description': 'Онлайн-трансляция матча ЦСКА - "Волга"',
  91. 'uploader': 'Championat',
  92. },
  93. },
  94. # Direct link to a video
  95. {
  96. 'url': 'http://media.w3.org/2010/05/sintel/trailer.mp4',
  97. 'md5': '67d406c2bcb6af27fa886f31aa934bbe',
  98. 'info_dict': {
  99. 'id': 'trailer',
  100. 'ext': 'mp4',
  101. 'title': 'trailer',
  102. 'upload_date': '20100513',
  103. }
  104. },
  105. # ooyala video
  106. {
  107. 'url': 'http://www.rollingstone.com/music/videos/norwegian-dj-cashmere-cat-goes-spartan-on-with-me-premiere-20131219',
  108. 'md5': '5644c6ca5d5782c1d0d350dad9bd840c',
  109. 'info_dict': {
  110. 'id': 'BwY2RxaTrTkslxOfcan0UCf0YqyvWysJ',
  111. 'ext': 'mp4',
  112. 'title': '2cc213299525360.mov', # that's what we get
  113. },
  114. },
  115. # google redirect
  116. {
  117. 'url': 'http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&ved=0CCUQtwIwAA&url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DcmQHVoWB5FY&ei=F-sNU-LLCaXk4QT52ICQBQ&usg=AFQjCNEw4hL29zgOohLXvpJ-Bdh2bils1Q&bvm=bv.61965928,d.bGE',
  118. 'info_dict': {
  119. 'id': 'cmQHVoWB5FY',
  120. 'ext': 'mp4',
  121. 'upload_date': '20130224',
  122. 'uploader_id': 'TheVerge',
  123. 'description': 'Chris Ziegler takes a look at the Alcatel OneTouch Fire and the ZTE Open; two of the first Firefox OS handsets to be officially announced.',
  124. 'uploader': 'The Verge',
  125. 'title': 'First Firefox OS phones side-by-side',
  126. },
  127. 'params': {
  128. 'skip_download': False,
  129. }
  130. },
  131. # embed.ly video
  132. {
  133. 'url': 'http://www.tested.com/science/weird/460206-tested-grinding-coffee-2000-frames-second/',
  134. 'info_dict': {
  135. 'id': '9ODmcdjQcHQ',
  136. 'ext': 'mp4',
  137. 'title': 'Tested: Grinding Coffee at 2000 Frames Per Second',
  138. 'upload_date': '20140225',
  139. 'description': 'md5:06a40fbf30b220468f1e0957c0f558ff',
  140. 'uploader': 'Tested',
  141. 'uploader_id': 'testedcom',
  142. },
  143. # No need to test YoutubeIE here
  144. 'params': {
  145. 'skip_download': True,
  146. },
  147. },
  148. # funnyordie embed
  149. {
  150. 'url': 'http://www.theguardian.com/world/2014/mar/11/obama-zach-galifianakis-between-two-ferns',
  151. 'md5': '7cf780be104d40fea7bae52eed4a470e',
  152. 'info_dict': {
  153. 'id': '18e820ec3f',
  154. 'ext': 'mp4',
  155. 'title': 'Between Two Ferns with Zach Galifianakis: President Barack Obama',
  156. 'description': 'Episode 18: President Barack Obama sits down with Zach Galifianakis for his most memorable interview yet.',
  157. },
  158. },
  159. # RUTV embed
  160. {
  161. 'url': 'http://www.rg.ru/2014/03/15/reg-dfo/anklav-anons.html',
  162. 'info_dict': {
  163. 'id': '776940',
  164. 'ext': 'mp4',
  165. 'title': 'Охотское море стало целиком российским',
  166. 'description': 'md5:5ed62483b14663e2a95ebbe115eb8f43',
  167. },
  168. 'params': {
  169. # m3u8 download
  170. 'skip_download': True,
  171. },
  172. },
  173. # Embedded TED video
  174. {
  175. 'url': 'http://en.support.wordpress.com/videos/ted-talks/',
  176. 'md5': 'deeeabcc1085eb2ba205474e7235a3d5',
  177. 'info_dict': {
  178. 'id': '981',
  179. 'ext': 'mp4',
  180. 'title': 'My web playroom',
  181. 'uploader': 'Ze Frank',
  182. 'description': 'md5:ddb2a40ecd6b6a147e400e535874947b',
  183. }
  184. },
  185. # Embeded Ustream video
  186. {
  187. 'url': 'http://www.american.edu/spa/pti/nsa-privacy-janus-2014.cfm',
  188. 'md5': '27b99cdb639c9b12a79bca876a073417',
  189. 'info_dict': {
  190. 'id': '45734260',
  191. 'ext': 'flv',
  192. 'uploader': 'AU SPA: The NSA and Privacy',
  193. 'title': 'NSA and Privacy Forum Debate featuring General Hayden and Barton Gellman'
  194. }
  195. },
  196. # nowvideo embed hidden behind percent encoding
  197. {
  198. 'url': 'http://www.waoanime.tv/the-super-dimension-fortress-macross-episode-1/',
  199. 'md5': '2baf4ddd70f697d94b1c18cf796d5107',
  200. 'info_dict': {
  201. 'id': '06e53103ca9aa',
  202. 'ext': 'flv',
  203. 'title': 'Macross Episode 001 Watch Macross Episode 001 onl',
  204. 'description': 'No description',
  205. },
  206. },
  207. # arte embed
  208. {
  209. 'url': 'http://www.tv-replay.fr/redirection/20-03-14/x-enius-arte-10753389.html',
  210. 'md5': '7653032cbb25bf6c80d80f217055fa43',
  211. 'info_dict': {
  212. 'id': '048195-004_PLUS7-F',
  213. 'ext': 'flv',
  214. 'title': 'X:enius',
  215. 'description': 'md5:d5fdf32ef6613cdbfd516ae658abf168',
  216. 'upload_date': '20140320',
  217. },
  218. 'params': {
  219. 'skip_download': 'Requires rtmpdump'
  220. }
  221. },
  222. # smotri embed
  223. {
  224. 'url': 'http://rbctv.rbc.ru/archive/news/562949990879132.shtml',
  225. 'md5': 'ec40048448e9284c9a1de77bb188108b',
  226. 'info_dict': {
  227. 'id': 'v27008541fad',
  228. 'ext': 'mp4',
  229. 'title': 'Крым и Севастополь вошли в состав России',
  230. 'description': 'md5:fae01b61f68984c7bd2fa741e11c3175',
  231. 'duration': 900,
  232. 'upload_date': '20140318',
  233. 'uploader': 'rbctv_2012_4',
  234. 'uploader_id': 'rbctv_2012_4',
  235. },
  236. },
  237. # Condé Nast embed
  238. {
  239. 'url': 'http://www.wired.com/2014/04/honda-asimo/',
  240. 'md5': 'ba0dfe966fa007657bd1443ee672db0f',
  241. 'info_dict': {
  242. 'id': '53501be369702d3275860000',
  243. 'ext': 'mp4',
  244. 'title': 'Honda’s New Asimo Robot Is More Human Than Ever',
  245. }
  246. },
  247. # Dailymotion embed
  248. {
  249. 'url': 'http://www.spi0n.com/zap-spi0n-com-n216/',
  250. 'md5': '441aeeb82eb72c422c7f14ec533999cd',
  251. 'info_dict': {
  252. 'id': 'k2mm4bCdJ6CQ2i7c8o2',
  253. 'ext': 'mp4',
  254. 'title': 'Le Zap de Spi0n n°216 - Zapping du Web',
  255. 'uploader': 'Spi0n',
  256. },
  257. 'add_ie': ['Dailymotion'],
  258. },
  259. # YouTube embed
  260. {
  261. 'url': 'http://www.badzine.de/ansicht/datum/2014/06/09/so-funktioniert-die-neue-englische-badminton-liga.html',
  262. 'info_dict': {
  263. 'id': 'FXRb4ykk4S0',
  264. 'ext': 'mp4',
  265. 'title': 'The NBL Auction 2014',
  266. 'uploader': 'BADMINTON England',
  267. 'uploader_id': 'BADMINTONEvents',
  268. 'upload_date': '20140603',
  269. 'description': 'md5:9ef128a69f1e262a700ed83edb163a73',
  270. },
  271. 'add_ie': ['Youtube'],
  272. 'params': {
  273. 'skip_download': True,
  274. }
  275. },
  276. # MTVSercices embed
  277. {
  278. 'url': 'http://www.gametrailers.com/news-post/76093/north-america-europe-is-getting-that-mario-kart-8-mercedes-dlc-too',
  279. 'md5': '35727f82f58c76d996fc188f9755b0d5',
  280. 'info_dict': {
  281. 'id': '0306a69b-8adf-4fb5-aace-75f8e8cbfca9',
  282. 'ext': 'mp4',
  283. 'title': 'Review',
  284. 'description': 'Mario\'s life in the fast lane has never looked so good.',
  285. },
  286. },
  287. # YouTube embed via <data-embed-url="">
  288. {
  289. 'url': 'https://play.google.com/store/apps/details?id=com.gameloft.android.ANMP.GloftA8HM',
  290. 'info_dict': {
  291. 'id': 'jpSGZsgga_I',
  292. 'ext': 'mp4',
  293. 'title': 'Asphalt 8: Airborne - Launch Trailer',
  294. 'uploader': 'Gameloft',
  295. 'uploader_id': 'gameloft',
  296. 'upload_date': '20130821',
  297. 'description': 'md5:87bd95f13d8be3e7da87a5f2c443106a',
  298. },
  299. 'params': {
  300. 'skip_download': True,
  301. }
  302. }
  303. ]
  304. def report_download_webpage(self, video_id):
  305. """Report webpage download."""
  306. if not self._downloader.params.get('test', False):
  307. self._downloader.report_warning('Falling back on generic information extractor.')
  308. super(GenericIE, self).report_download_webpage(video_id)
  309. def report_following_redirect(self, new_url):
  310. """Report information extraction."""
  311. self._downloader.to_screen('[redirect] Following redirect to %s' % new_url)
  312. def _send_head(self, url):
  313. """Check if it is a redirect, like url shorteners, in case return the new url."""
  314. class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  315. """
  316. Subclass the HTTPRedirectHandler to make it use our
  317. HEADRequest also on the redirected URL
  318. """
  319. def redirect_request(self, req, fp, code, msg, headers, newurl):
  320. if code in (301, 302, 303, 307):
  321. newurl = newurl.replace(' ', '%20')
  322. newheaders = dict((k,v) for k,v in req.headers.items()
  323. if k.lower() not in ("content-length", "content-type"))
  324. try:
  325. # This function was deprecated in python 3.3 and removed in 3.4
  326. origin_req_host = req.get_origin_req_host()
  327. except AttributeError:
  328. origin_req_host = req.origin_req_host
  329. return HEADRequest(newurl,
  330. headers=newheaders,
  331. origin_req_host=origin_req_host,
  332. unverifiable=True)
  333. else:
  334. raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
  335. class HTTPMethodFallback(compat_urllib_request.BaseHandler):
  336. """
  337. Fallback to GET if HEAD is not allowed (405 HTTP error)
  338. """
  339. def http_error_405(self, req, fp, code, msg, headers):
  340. fp.read()
  341. fp.close()
  342. newheaders = dict((k,v) for k,v in req.headers.items()
  343. if k.lower() not in ("content-length", "content-type"))
  344. return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
  345. headers=newheaders,
  346. origin_req_host=req.get_origin_req_host(),
  347. unverifiable=True))
  348. # Build our opener
  349. opener = compat_urllib_request.OpenerDirector()
  350. for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
  351. HTTPMethodFallback, HEADRedirectHandler,
  352. compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
  353. opener.add_handler(handler())
  354. response = opener.open(HEADRequest(url))
  355. if response is None:
  356. raise ExtractorError('Invalid URL protocol')
  357. return response
  358. def _extract_rss(self, url, video_id, doc):
  359. playlist_title = doc.find('./channel/title').text
  360. playlist_desc_el = doc.find('./channel/description')
  361. playlist_desc = None if playlist_desc_el is None else playlist_desc_el.text
  362. entries = [{
  363. '_type': 'url',
  364. 'url': e.find('link').text,
  365. 'title': e.find('title').text,
  366. } for e in doc.findall('./channel/item')]
  367. return {
  368. '_type': 'playlist',
  369. 'id': url,
  370. 'title': playlist_title,
  371. 'description': playlist_desc,
  372. 'entries': entries,
  373. }
  374. def _real_extract(self, url):
  375. if url.startswith('//'):
  376. return {
  377. '_type': 'url',
  378. 'url': self.http_scheme() + url,
  379. }
  380. parsed_url = compat_urlparse.urlparse(url)
  381. if not parsed_url.scheme:
  382. default_search = self._downloader.params.get('default_search')
  383. if default_search is None:
  384. default_search = 'fixup_error'
  385. if default_search in ('auto', 'auto_warning', 'fixup_error'):
  386. if '/' in url:
  387. self._downloader.report_warning('The url doesn\'t specify the protocol, trying with http')
  388. return self.url_result('http://' + url)
  389. elif default_search != 'fixup_error':
  390. if default_search == 'auto_warning':
  391. if re.match(r'^(?:url|URL)$', url):
  392. raise ExtractorError(
  393. 'Invalid URL: %r . Call youtube-dl like this: youtube-dl -v "https://www.youtube.com/watch?v=BaW_jenozKc" ' % url,
  394. expected=True)
  395. else:
  396. self._downloader.report_warning(
  397. 'Falling back to youtube search for %s . Set --default-search "auto" to suppress this warning.' % url)
  398. return self.url_result('ytsearch:' + url)
  399. if default_search in ('error', 'fixup_error'):
  400. raise ExtractorError(
  401. ('%r is not a valid URL. '
  402. 'Set --default-search "ytsearch" (or run youtube-dl "ytsearch:%s" ) to search YouTube'
  403. ) % (url, url), expected=True)
  404. else:
  405. assert ':' in default_search
  406. return self.url_result(default_search + url)
  407. video_id = os.path.splitext(url.rstrip('/').split('/')[-1])[0]
  408. self.to_screen('%s: Requesting header' % video_id)
  409. try:
  410. response = self._send_head(url)
  411. # Check for redirect
  412. new_url = response.geturl()
  413. if url != new_url:
  414. self.report_following_redirect(new_url)
  415. return self.url_result(new_url)
  416. # Check for direct link to a video
  417. content_type = response.headers.get('Content-Type', '')
  418. m = re.match(r'^(?P<type>audio|video|application(?=/ogg$))/(?P<format_id>.+)$', content_type)
  419. if m:
  420. upload_date = response.headers.get('Last-Modified')
  421. if upload_date:
  422. upload_date = unified_strdate(upload_date)
  423. return {
  424. 'id': video_id,
  425. 'title': os.path.splitext(url_basename(url))[0],
  426. 'formats': [{
  427. 'format_id': m.group('format_id'),
  428. 'url': url,
  429. 'vcodec': 'none' if m.group('type') == 'audio' else None
  430. }],
  431. 'upload_date': upload_date,
  432. }
  433. except compat_urllib_error.HTTPError:
  434. # This may be a stupid server that doesn't like HEAD, our UA, or so
  435. pass
  436. try:
  437. webpage = self._download_webpage(url, video_id)
  438. except ValueError:
  439. # since this is the last-resort InfoExtractor, if
  440. # this error is thrown, it'll be thrown here
  441. raise ExtractorError('Failed to download URL: %s' % url)
  442. self.report_extraction(video_id)
  443. # Is it an RSS feed?
  444. try:
  445. doc = parse_xml(webpage)
  446. if doc.tag == 'rss':
  447. return self._extract_rss(url, video_id, doc)
  448. except compat_xml_parse_error:
  449. pass
  450. # Sometimes embedded video player is hidden behind percent encoding
  451. # (e.g. https://github.com/rg3/youtube-dl/issues/2448)
  452. # Unescaping the whole page allows to handle those cases in a generic way
  453. webpage = compat_urllib_parse.unquote(webpage)
  454. # it's tempting to parse this further, but you would
  455. # have to take into account all the variations like
  456. # Video Title - Site Name
  457. # Site Name | Video Title
  458. # Video Title - Tagline | Site Name
  459. # and so on and so forth; it's just not practical
  460. video_title = self._html_search_regex(
  461. r'(?s)<title>(.*?)</title>', webpage, 'video title',
  462. default='video')
  463. # video uploader is domain name
  464. video_uploader = self._search_regex(
  465. r'^(?:https?://)?([^/]*)/.*', url, 'video uploader')
  466. # Helper method
  467. def _playlist_from_matches(matches, getter, ie=None):
  468. urlrs = orderedSet(self.url_result(getter(m), ie) for m in matches)
  469. return self.playlist_result(
  470. urlrs, playlist_id=video_id, playlist_title=video_title)
  471. # Look for BrightCove:
  472. bc_urls = BrightcoveIE._extract_brightcove_urls(webpage)
  473. if bc_urls:
  474. self.to_screen('Brightcove video detected.')
  475. entries = [{
  476. '_type': 'url',
  477. 'url': smuggle_url(bc_url, {'Referer': url}),
  478. 'ie_key': 'Brightcove'
  479. } for bc_url in bc_urls]
  480. return {
  481. '_type': 'playlist',
  482. 'title': video_title,
  483. 'id': video_id,
  484. 'entries': entries,
  485. }
  486. # Look for embedded (iframe) Vimeo player
  487. mobj = re.search(
  488. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//player\.vimeo\.com/video/.+?)\1', webpage)
  489. if mobj:
  490. player_url = unescapeHTML(mobj.group('url'))
  491. surl = smuggle_url(player_url, {'Referer': url})
  492. return self.url_result(surl, 'Vimeo')
  493. # Look for embedded (swf embed) Vimeo player
  494. mobj = re.search(
  495. r'<embed[^>]+?src="(https?://(?:www\.)?vimeo\.com/moogaloop\.swf.+?)"', webpage)
  496. if mobj:
  497. return self.url_result(mobj.group(1), 'Vimeo')
  498. # Look for embedded YouTube player
  499. matches = re.findall(r'''(?x)
  500. (?:
  501. <iframe[^>]+?src=|
  502. data-video-url=|
  503. <embed[^>]+?src=|
  504. embedSWF\(?:\s*
  505. )
  506. (["\'])
  507. (?P<url>(?:https?:)?//(?:www\.)?youtube\.com/
  508. (?:embed|v)/.+?)
  509. \1''', webpage)
  510. if matches:
  511. return _playlist_from_matches(
  512. matches, lambda m: unescapeHTML(m[1]), ie='Youtube')
  513. # Look for embedded Dailymotion player
  514. matches = re.findall(
  515. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/embed/video/.+?)\1', webpage)
  516. if matches:
  517. return _playlist_from_matches(
  518. matches, lambda m: unescapeHTML(m[1]))
  519. # Look for embedded Wistia player
  520. match = re.search(
  521. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:fast\.)?wistia\.net/embed/iframe/.+?)\1', webpage)
  522. if match:
  523. return {
  524. '_type': 'url_transparent',
  525. 'url': unescapeHTML(match.group('url')),
  526. 'ie_key': 'Wistia',
  527. 'uploader': video_uploader,
  528. 'title': video_title,
  529. 'id': video_id,
  530. }
  531. # Look for embedded blip.tv player
  532. mobj = re.search(r'<meta\s[^>]*https?://api\.blip\.tv/\w+/redirect/\w+/(\d+)', webpage)
  533. if mobj:
  534. return self.url_result('http://blip.tv/a/a-'+mobj.group(1), 'BlipTV')
  535. mobj = re.search(r'<(?:iframe|embed|object)\s[^>]*(https?://(?:\w+\.)?blip\.tv/(?:play/|api\.swf#)[a-zA-Z0-9]+)', webpage)
  536. if mobj:
  537. return self.url_result(mobj.group(1), 'BlipTV')
  538. # Look for embedded condenast player
  539. matches = re.findall(
  540. r'<iframe\s+(?:[a-zA-Z-]+="[^"]+"\s+)*?src="(https?://player\.cnevids\.com/embed/[^"]+")',
  541. webpage)
  542. if matches:
  543. return {
  544. '_type': 'playlist',
  545. 'entries': [{
  546. '_type': 'url',
  547. 'ie_key': 'CondeNast',
  548. 'url': ma,
  549. } for ma in matches],
  550. 'title': video_title,
  551. 'id': video_id,
  552. }
  553. # Look for Bandcamp pages with custom domain
  554. mobj = re.search(r'<meta property="og:url"[^>]*?content="(.*?bandcamp\.com.*?)"', webpage)
  555. if mobj is not None:
  556. burl = unescapeHTML(mobj.group(1))
  557. # Don't set the extractor because it can be a track url or an album
  558. return self.url_result(burl)
  559. # Look for embedded Vevo player
  560. mobj = re.search(
  561. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:cache\.)?vevo\.com/.+?)\1', webpage)
  562. if mobj is not None:
  563. return self.url_result(mobj.group('url'))
  564. # Look for Ooyala videos
  565. mobj = (re.search(r'player.ooyala.com/[^"?]+\?[^"]*?(?:embedCode|ec)=(?P<ec>[^"&]+)', webpage) or
  566. re.search(r'OO.Player.create\([\'"].*?[\'"],\s*[\'"](?P<ec>.{32})[\'"]', webpage))
  567. if mobj is not None:
  568. return OoyalaIE._build_url_result(mobj.group('ec'))
  569. # Look for Aparat videos
  570. mobj = re.search(r'<iframe .*?src="(http://www\.aparat\.com/video/[^"]+)"', webpage)
  571. if mobj is not None:
  572. return self.url_result(mobj.group(1), 'Aparat')
  573. # Look for MPORA videos
  574. mobj = re.search(r'<iframe .*?src="(http://mpora\.(?:com|de)/videos/[^"]+)"', webpage)
  575. if mobj is not None:
  576. return self.url_result(mobj.group(1), 'Mpora')
  577. # Look for embedded NovaMov-based player
  578. mobj = re.search(
  579. r'''(?x)<(?:pagespeed_)?iframe[^>]+?src=(["\'])
  580. (?P<url>http://(?:(?:embed|www)\.)?
  581. (?:novamov\.com|
  582. nowvideo\.(?:ch|sx|eu|at|ag|co)|
  583. videoweed\.(?:es|com)|
  584. movshare\.(?:net|sx|ag)|
  585. divxstage\.(?:eu|net|ch|co|at|ag))
  586. /embed\.php.+?)\1''', webpage)
  587. if mobj is not None:
  588. return self.url_result(mobj.group('url'))
  589. # Look for embedded Facebook player
  590. mobj = re.search(
  591. r'<iframe[^>]+?src=(["\'])(?P<url>https://www\.facebook\.com/video/embed.+?)\1', webpage)
  592. if mobj is not None:
  593. return self.url_result(mobj.group('url'), 'Facebook')
  594. # Look for embedded VK player
  595. mobj = re.search(r'<iframe[^>]+?src=(["\'])(?P<url>https?://vk\.com/video_ext\.php.+?)\1', webpage)
  596. if mobj is not None:
  597. return self.url_result(mobj.group('url'), 'VK')
  598. # Look for embedded ivi player
  599. mobj = re.search(r'<embed[^>]+?src=(["\'])(?P<url>https?://(?:www\.)?ivi\.ru/video/player.+?)\1', webpage)
  600. if mobj is not None:
  601. return self.url_result(mobj.group('url'), 'Ivi')
  602. # Look for embedded Huffington Post player
  603. mobj = re.search(
  604. r'<iframe[^>]+?src=(["\'])(?P<url>https?://embed\.live\.huffingtonpost\.com/.+?)\1', webpage)
  605. if mobj is not None:
  606. return self.url_result(mobj.group('url'), 'HuffPost')
  607. # Look for embed.ly
  608. mobj = re.search(r'class=["\']embedly-card["\'][^>]href=["\'](?P<url>[^"\']+)', webpage)
  609. if mobj is not None:
  610. return self.url_result(mobj.group('url'))
  611. mobj = re.search(r'class=["\']embedly-embed["\'][^>]src=["\'][^"\']*url=(?P<url>[^&]+)', webpage)
  612. if mobj is not None:
  613. return self.url_result(compat_urllib_parse.unquote(mobj.group('url')))
  614. # Look for funnyordie embed
  615. matches = re.findall(r'<iframe[^>]+?src="(https?://(?:www\.)?funnyordie\.com/embed/[^"]+)"', webpage)
  616. if matches:
  617. return _playlist_from_matches(
  618. matches, getter=unescapeHTML, ie='FunnyOrDie')
  619. # Look for embedded RUTV player
  620. rutv_url = RUTVIE._extract_url(webpage)
  621. if rutv_url:
  622. return self.url_result(rutv_url, 'RUTV')
  623. # Look for embedded TED player
  624. mobj = re.search(
  625. r'<iframe[^>]+?src=(["\'])(?P<url>http://embed\.ted\.com/.+?)\1', webpage)
  626. if mobj is not None:
  627. return self.url_result(mobj.group('url'), 'TED')
  628. # Look for embedded Ustream videos
  629. mobj = re.search(
  630. r'<iframe[^>]+?src=(["\'])(?P<url>http://www\.ustream\.tv/embed/.+?)\1', webpage)
  631. if mobj is not None:
  632. return self.url_result(mobj.group('url'), 'Ustream')
  633. # Look for embedded arte.tv player
  634. mobj = re.search(
  635. r'<script [^>]*?src="(?P<url>http://www\.arte\.tv/playerv2/embed[^"]+)"',
  636. webpage)
  637. if mobj is not None:
  638. return self.url_result(mobj.group('url'), 'ArteTVEmbed')
  639. # Look for embedded smotri.com player
  640. smotri_url = SmotriIE._extract_url(webpage)
  641. if smotri_url:
  642. return self.url_result(smotri_url, 'Smotri')
  643. # Look for embeded soundcloud player
  644. mobj = re.search(
  645. r'<iframe src="(?P<url>https?://(?:w\.)?soundcloud\.com/player[^"]+)"',
  646. webpage)
  647. if mobj is not None:
  648. url = unescapeHTML(mobj.group('url'))
  649. return self.url_result(url)
  650. # Look for embedded vulture.com player
  651. mobj = re.search(
  652. r'<iframe src="(?P<url>https?://video\.vulture\.com/[^"]+)"',
  653. webpage)
  654. if mobj is not None:
  655. url = unescapeHTML(mobj.group('url'))
  656. return self.url_result(url, ie='Vulture')
  657. # Look for embedded mtvservices player
  658. mobj = re.search(
  659. r'<iframe src="(?P<url>https?://media\.mtvnservices\.com/embed/[^"]+)"',
  660. webpage)
  661. if mobj is not None:
  662. url = unescapeHTML(mobj.group('url'))
  663. return self.url_result(url, ie='MTVServicesEmbedded')
  664. # Look for embedded yahoo player
  665. mobj = re.search(
  666. r'<iframe[^>]+?src=(["\'])(?P<url>https?://(?:screen|movies)\.yahoo\.com/.+?\.html\?format=embed)\1',
  667. webpage)
  668. if mobj is not None:
  669. return self.url_result(mobj.group('url'), 'Yahoo')
  670. # Look for embedded sbs.com.au player
  671. mobj = re.search(
  672. r'<iframe[^>]+?src=(["\'])(?P<url>https?://(?:www\.)sbs\.com\.au/ondemand/video/single/.+?)\1',
  673. webpage)
  674. if mobj is not None:
  675. return self.url_result(mobj.group('url'), 'SBS')
  676. # Start with something easy: JW Player in SWFObject
  677. found = re.findall(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  678. if not found:
  679. # Look for gorilla-vid style embedding
  680. found = re.findall(r'''(?sx)
  681. (?:
  682. jw_plugins|
  683. JWPlayerOptions|
  684. jwplayer\s*\(\s*["'][^'"]+["']\s*\)\s*\.setup
  685. )
  686. .*?file\s*:\s*["\'](.*?)["\']''', webpage)
  687. if not found:
  688. # Broaden the search a little bit
  689. found = re.findall(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  690. if not found:
  691. # Broaden the findall a little bit: JWPlayer JS loader
  692. found = re.findall(r'[^A-Za-z0-9]?file["\']?:\s*["\'](http(?![^\'"]+\.[0-9]+[\'"])[^\'"]+)["\']', webpage)
  693. if not found:
  694. # Try to find twitter cards info
  695. found = re.findall(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
  696. if not found:
  697. # We look for Open Graph info:
  698. # We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
  699. m_video_type = re.findall(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
  700. # We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
  701. if m_video_type is not None:
  702. found = re.findall(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)
  703. if not found:
  704. # HTML5 video
  705. found = re.findall(r'(?s)<video[^<]*(?:>.*?<source.*?)? src="([^"]+)"', webpage)
  706. if not found:
  707. found = re.search(
  708. r'(?i)<meta\s+(?=(?:[a-z-]+="[^"]+"\s+)*http-equiv="refresh")'
  709. r'(?:[a-z-]+="[^"]+"\s+)*?content="[0-9]{,2};url=\'([^\']+)\'"',
  710. webpage)
  711. if found:
  712. new_url = found.group(1)
  713. self.report_following_redirect(new_url)
  714. return {
  715. '_type': 'url',
  716. 'url': new_url,
  717. }
  718. if not found:
  719. raise ExtractorError('Unsupported URL: %s' % url)
  720. entries = []
  721. for video_url in found:
  722. video_url = compat_urlparse.urljoin(url, video_url)
  723. video_id = compat_urllib_parse.unquote(os.path.basename(video_url))
  724. # Sometimes, jwplayer extraction will result in a YouTube URL
  725. if YoutubeIE.suitable(video_url):
  726. entries.append(self.url_result(video_url, 'Youtube'))
  727. continue
  728. # here's a fun little line of code for you:
  729. video_id = os.path.splitext(video_id)[0]
  730. entries.append({
  731. 'id': video_id,
  732. 'url': video_url,
  733. 'uploader': video_uploader,
  734. 'title': video_title,
  735. })
  736. if len(entries) == 1:
  737. return entries[0]
  738. else:
  739. for num, e in enumerate(entries, start=1):
  740. e['title'] = '%s (%d)' % (e['title'], num)
  741. return {
  742. '_type': 'playlist',
  743. 'entries': entries,
  744. }