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.

514 lines
21 KiB

  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. parse_xml,
  16. smuggle_url,
  17. unescapeHTML,
  18. unified_strdate,
  19. url_basename,
  20. )
  21. from .brightcove import BrightcoveIE
  22. from .ooyala import OoyalaIE
  23. class GenericIE(InfoExtractor):
  24. IE_DESC = 'Generic downloader that works on some sites'
  25. _VALID_URL = r'.*'
  26. IE_NAME = 'generic'
  27. _TESTS = [
  28. {
  29. 'url': 'http://www.hodiho.fr/2013/02/regis-plante-sa-jeep.html',
  30. 'file': '13601338388002.mp4',
  31. 'md5': '6e15c93721d7ec9e9ca3fdbf07982cfd',
  32. 'info_dict': {
  33. 'uploader': 'www.hodiho.fr',
  34. 'title': 'R\u00e9gis plante sa Jeep',
  35. }
  36. },
  37. # bandcamp page with custom domain
  38. {
  39. 'add_ie': ['Bandcamp'],
  40. 'url': 'http://bronyrock.com/track/the-pony-mash',
  41. 'file': '3235767654.mp3',
  42. 'info_dict': {
  43. 'title': 'The Pony Mash',
  44. 'uploader': 'M_Pallante',
  45. },
  46. 'skip': 'There is a limit of 200 free downloads / month for the test song',
  47. },
  48. # embedded brightcove video
  49. # it also tests brightcove videos that need to set the 'Referer' in the
  50. # http requests
  51. {
  52. 'add_ie': ['Brightcove'],
  53. 'url': 'http://www.bfmtv.com/video/bfmbusiness/cours-bourse/cours-bourse-l-analyse-technique-154522/',
  54. 'info_dict': {
  55. 'id': '2765128793001',
  56. 'ext': 'mp4',
  57. 'title': 'Le cours de bourse : l’analyse technique',
  58. 'description': 'md5:7e9ad046e968cb2d1114004aba466fd9',
  59. 'uploader': 'BFM BUSINESS',
  60. },
  61. 'params': {
  62. 'skip_download': True,
  63. },
  64. },
  65. {
  66. # https://github.com/rg3/youtube-dl/issues/2253
  67. 'url': 'http://bcove.me/i6nfkrc3',
  68. 'file': '3101154703001.mp4',
  69. 'md5': '0ba9446db037002366bab3b3eb30c88c',
  70. 'info_dict': {
  71. 'title': 'Still no power',
  72. 'uploader': 'thestar.com',
  73. '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.',
  74. },
  75. 'add_ie': ['Brightcove'],
  76. },
  77. # Direct link to a video
  78. {
  79. 'url': 'http://media.w3.org/2010/05/sintel/trailer.mp4',
  80. 'md5': '67d406c2bcb6af27fa886f31aa934bbe',
  81. 'info_dict': {
  82. 'id': 'trailer',
  83. 'ext': 'mp4',
  84. 'title': 'trailer',
  85. 'upload_date': '20100513',
  86. }
  87. },
  88. # ooyala video
  89. {
  90. 'url': 'http://www.rollingstone.com/music/videos/norwegian-dj-cashmere-cat-goes-spartan-on-with-me-premiere-20131219',
  91. 'md5': '5644c6ca5d5782c1d0d350dad9bd840c',
  92. 'info_dict': {
  93. 'id': 'BwY2RxaTrTkslxOfcan0UCf0YqyvWysJ',
  94. 'ext': 'mp4',
  95. 'title': '2cc213299525360.mov', # that's what we get
  96. },
  97. },
  98. # google redirect
  99. {
  100. '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',
  101. 'info_dict': {
  102. 'id': 'cmQHVoWB5FY',
  103. 'ext': 'mp4',
  104. 'upload_date': '20130224',
  105. 'uploader_id': 'TheVerge',
  106. '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.',
  107. 'uploader': 'The Verge',
  108. 'title': 'First Firefox OS phones side-by-side',
  109. },
  110. 'params': {
  111. 'skip_download': False,
  112. }
  113. },
  114. # embed.ly video
  115. {
  116. 'url': 'http://www.tested.com/science/weird/460206-tested-grinding-coffee-2000-frames-second/',
  117. 'info_dict': {
  118. 'id': '9ODmcdjQcHQ',
  119. 'ext': 'mp4',
  120. 'title': 'Tested: Grinding Coffee at 2000 Frames Per Second',
  121. 'upload_date': '20140225',
  122. 'description': 'md5:06a40fbf30b220468f1e0957c0f558ff',
  123. 'uploader': 'Tested',
  124. 'uploader_id': 'testedcom',
  125. },
  126. # No need to test YoutubeIE here
  127. 'params': {
  128. 'skip_download': True,
  129. },
  130. },
  131. # funnyordie embed
  132. {
  133. 'url': 'http://www.theguardian.com/world/2014/mar/11/obama-zach-galifianakis-between-two-ferns',
  134. 'md5': '7cf780be104d40fea7bae52eed4a470e',
  135. 'info_dict': {
  136. 'id': '18e820ec3f',
  137. 'ext': 'mp4',
  138. 'title': 'Between Two Ferns with Zach Galifianakis: President Barack Obama',
  139. 'description': 'Episode 18: President Barack Obama sits down with Zach Galifianakis for his most memorable interview yet.',
  140. }
  141. },
  142. ]
  143. def report_download_webpage(self, video_id):
  144. """Report webpage download."""
  145. if not self._downloader.params.get('test', False):
  146. self._downloader.report_warning('Falling back on generic information extractor.')
  147. super(GenericIE, self).report_download_webpage(video_id)
  148. def report_following_redirect(self, new_url):
  149. """Report information extraction."""
  150. self._downloader.to_screen('[redirect] Following redirect to %s' % new_url)
  151. def _send_head(self, url):
  152. """Check if it is a redirect, like url shorteners, in case return the new url."""
  153. class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  154. """
  155. Subclass the HTTPRedirectHandler to make it use our
  156. HEADRequest also on the redirected URL
  157. """
  158. def redirect_request(self, req, fp, code, msg, headers, newurl):
  159. if code in (301, 302, 303, 307):
  160. newurl = newurl.replace(' ', '%20')
  161. newheaders = dict((k,v) for k,v in req.headers.items()
  162. if k.lower() not in ("content-length", "content-type"))
  163. return HEADRequest(newurl,
  164. headers=newheaders,
  165. origin_req_host=req.get_origin_req_host(),
  166. unverifiable=True)
  167. else:
  168. raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
  169. class HTTPMethodFallback(compat_urllib_request.BaseHandler):
  170. """
  171. Fallback to GET if HEAD is not allowed (405 HTTP error)
  172. """
  173. def http_error_405(self, req, fp, code, msg, headers):
  174. fp.read()
  175. fp.close()
  176. newheaders = dict((k,v) for k,v in req.headers.items()
  177. if k.lower() not in ("content-length", "content-type"))
  178. return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
  179. headers=newheaders,
  180. origin_req_host=req.get_origin_req_host(),
  181. unverifiable=True))
  182. # Build our opener
  183. opener = compat_urllib_request.OpenerDirector()
  184. for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
  185. HTTPMethodFallback, HEADRedirectHandler,
  186. compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
  187. opener.add_handler(handler())
  188. response = opener.open(HEADRequest(url))
  189. if response is None:
  190. raise ExtractorError('Invalid URL protocol')
  191. return response
  192. def _extract_rss(self, url, video_id, doc):
  193. playlist_title = doc.find('./channel/title').text
  194. playlist_desc_el = doc.find('./channel/description')
  195. playlist_desc = None if playlist_desc_el is None else playlist_desc_el.text
  196. entries = [{
  197. '_type': 'url',
  198. 'url': e.find('link').text,
  199. 'title': e.find('title').text,
  200. } for e in doc.findall('./channel/item')]
  201. return {
  202. '_type': 'playlist',
  203. 'id': url,
  204. 'title': playlist_title,
  205. 'description': playlist_desc,
  206. 'entries': entries,
  207. }
  208. def _real_extract(self, url):
  209. parsed_url = compat_urlparse.urlparse(url)
  210. if not parsed_url.scheme:
  211. default_search = self._downloader.params.get('default_search')
  212. if default_search is None:
  213. default_search = 'auto'
  214. if default_search == 'auto':
  215. if '/' in url:
  216. self._downloader.report_warning('The url doesn\'t specify the protocol, trying with http')
  217. return self.url_result('http://' + url)
  218. else:
  219. return self.url_result('ytsearch:' + url)
  220. else:
  221. assert ':' in default_search
  222. return self.url_result(default_search + url)
  223. video_id = os.path.splitext(url.rstrip('/').split('/')[-1])[0]
  224. self.to_screen('%s: Requesting header' % video_id)
  225. try:
  226. response = self._send_head(url)
  227. # Check for redirect
  228. new_url = response.geturl()
  229. if url != new_url:
  230. self.report_following_redirect(new_url)
  231. return self.url_result(new_url)
  232. # Check for direct link to a video
  233. content_type = response.headers.get('Content-Type', '')
  234. m = re.match(r'^(?P<type>audio|video|application(?=/ogg$))/(?P<format_id>.+)$', content_type)
  235. if m:
  236. upload_date = response.headers.get('Last-Modified')
  237. if upload_date:
  238. upload_date = unified_strdate(upload_date)
  239. return {
  240. 'id': video_id,
  241. 'title': os.path.splitext(url_basename(url))[0],
  242. 'formats': [{
  243. 'format_id': m.group('format_id'),
  244. 'url': url,
  245. 'vcodec': 'none' if m.group('type') == 'audio' else None
  246. }],
  247. 'upload_date': upload_date,
  248. }
  249. except compat_urllib_error.HTTPError:
  250. # This may be a stupid server that doesn't like HEAD, our UA, or so
  251. pass
  252. try:
  253. webpage = self._download_webpage(url, video_id)
  254. except ValueError:
  255. # since this is the last-resort InfoExtractor, if
  256. # this error is thrown, it'll be thrown here
  257. raise ExtractorError('Failed to download URL: %s' % url)
  258. self.report_extraction(video_id)
  259. # Is it an RSS feed?
  260. try:
  261. doc = parse_xml(webpage)
  262. if doc.tag == 'rss':
  263. return self._extract_rss(url, video_id, doc)
  264. except compat_xml_parse_error:
  265. pass
  266. # it's tempting to parse this further, but you would
  267. # have to take into account all the variations like
  268. # Video Title - Site Name
  269. # Site Name | Video Title
  270. # Video Title - Tagline | Site Name
  271. # and so on and so forth; it's just not practical
  272. video_title = self._html_search_regex(
  273. r'(?s)<title>(.*?)</title>', webpage, 'video title',
  274. default='video')
  275. # video uploader is domain name
  276. video_uploader = self._search_regex(
  277. r'^(?:https?://)?([^/]*)/.*', url, 'video uploader')
  278. # Look for BrightCove:
  279. bc_urls = BrightcoveIE._extract_brightcove_urls(webpage)
  280. if bc_urls:
  281. self.to_screen('Brightcove video detected.')
  282. entries = [{
  283. '_type': 'url',
  284. 'url': smuggle_url(bc_url, {'Referer': url}),
  285. 'ie_key': 'Brightcove'
  286. } for bc_url in bc_urls]
  287. return {
  288. '_type': 'playlist',
  289. 'title': video_title,
  290. 'id': video_id,
  291. 'entries': entries,
  292. }
  293. # Look for embedded (iframe) Vimeo player
  294. mobj = re.search(
  295. r'<iframe[^>]+?src="((?:https?:)?//player\.vimeo\.com/video/.+?)"', webpage)
  296. if mobj:
  297. player_url = unescapeHTML(mobj.group(1))
  298. surl = smuggle_url(player_url, {'Referer': url})
  299. return self.url_result(surl, 'Vimeo')
  300. # Look for embedded (swf embed) Vimeo player
  301. mobj = re.search(
  302. r'<embed[^>]+?src="(https?://(?:www\.)?vimeo\.com/moogaloop\.swf.+?)"', webpage)
  303. if mobj:
  304. return self.url_result(mobj.group(1), 'Vimeo')
  305. # Look for embedded YouTube player
  306. matches = re.findall(r'''(?x)
  307. (?:<iframe[^>]+?src=|embedSWF\(\s*)
  308. (["\'])(?P<url>(?:https?:)?//(?:www\.)?youtube\.com/
  309. (?:embed|v)/.+?)
  310. \1''', webpage)
  311. if matches:
  312. urlrs = [self.url_result(unescapeHTML(tuppl[1]), 'Youtube')
  313. for tuppl in matches]
  314. return self.playlist_result(
  315. urlrs, playlist_id=video_id, playlist_title=video_title)
  316. # Look for embedded Dailymotion player
  317. matches = re.findall(
  318. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/embed/video/.+?)\1', webpage)
  319. if matches:
  320. urlrs = [self.url_result(unescapeHTML(tuppl[1]), 'Dailymotion')
  321. for tuppl in matches]
  322. return self.playlist_result(
  323. urlrs, playlist_id=video_id, playlist_title=video_title)
  324. # Look for embedded Wistia player
  325. match = re.search(
  326. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:fast\.)?wistia\.net/embed/iframe/.+?)\1', webpage)
  327. if match:
  328. return {
  329. '_type': 'url_transparent',
  330. 'url': unescapeHTML(match.group('url')),
  331. 'ie_key': 'Wistia',
  332. 'uploader': video_uploader,
  333. 'title': video_title,
  334. 'id': video_id,
  335. }
  336. # Look for embedded blip.tv player
  337. mobj = re.search(r'<meta\s[^>]*https?://api\.blip\.tv/\w+/redirect/\w+/(\d+)', webpage)
  338. if mobj:
  339. return self.url_result('http://blip.tv/a/a-'+mobj.group(1), 'BlipTV')
  340. mobj = re.search(r'<(?:iframe|embed|object)\s[^>]*(https?://(?:\w+\.)?blip\.tv/(?:play/|api\.swf#)[a-zA-Z0-9]+)', webpage)
  341. if mobj:
  342. return self.url_result(mobj.group(1), 'BlipTV')
  343. # Look for Bandcamp pages with custom domain
  344. mobj = re.search(r'<meta property="og:url"[^>]*?content="(.*?bandcamp\.com.*?)"', webpage)
  345. if mobj is not None:
  346. burl = unescapeHTML(mobj.group(1))
  347. # Don't set the extractor because it can be a track url or an album
  348. return self.url_result(burl)
  349. # Look for embedded Vevo player
  350. mobj = re.search(
  351. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:cache\.)?vevo\.com/.+?)\1', webpage)
  352. if mobj is not None:
  353. return self.url_result(mobj.group('url'))
  354. # Look for Ooyala videos
  355. mobj = re.search(r'player.ooyala.com/[^"?]+\?[^"]*?(?:embedCode|ec)=([^"&]+)', webpage)
  356. if mobj is not None:
  357. return OoyalaIE._build_url_result(mobj.group(1))
  358. # Look for Aparat videos
  359. mobj = re.search(r'<iframe src="(http://www\.aparat\.com/video/[^"]+)"', webpage)
  360. if mobj is not None:
  361. return self.url_result(mobj.group(1), 'Aparat')
  362. # Look for MPORA videos
  363. mobj = re.search(r'<iframe .*?src="(http://mpora\.(?:com|de)/videos/[^"]+)"', webpage)
  364. if mobj is not None:
  365. return self.url_result(mobj.group(1), 'Mpora')
  366. # Look for embedded NovaMov player
  367. mobj = re.search(
  368. r'<iframe[^>]+?src=(["\'])(?P<url>http://(?:(?:embed|www)\.)?novamov\.com/embed\.php.+?)\1', webpage)
  369. if mobj is not None:
  370. return self.url_result(mobj.group('url'), 'NovaMov')
  371. # Look for embedded NowVideo player
  372. mobj = re.search(
  373. r'<iframe[^>]+?src=(["\'])(?P<url>http://(?:(?:embed|www)\.)?nowvideo\.(?:ch|sx|eu)/embed\.php.+?)\1', webpage)
  374. if mobj is not None:
  375. return self.url_result(mobj.group('url'), 'NowVideo')
  376. # Look for embedded Facebook player
  377. mobj = re.search(
  378. r'<iframe[^>]+?src=(["\'])(?P<url>https://www\.facebook\.com/video/embed.+?)\1', webpage)
  379. if mobj is not None:
  380. return self.url_result(mobj.group('url'), 'Facebook')
  381. # Look for embedded VK player
  382. mobj = re.search(r'<iframe[^>]+?src=(["\'])(?P<url>https?://vk\.com/video_ext\.php.+?)\1', webpage)
  383. if mobj is not None:
  384. return self.url_result(mobj.group('url'), 'VK')
  385. # Look for embedded Huffington Post player
  386. mobj = re.search(
  387. r'<iframe[^>]+?src=(["\'])(?P<url>https?://embed\.live\.huffingtonpost\.com/.+?)\1', webpage)
  388. if mobj is not None:
  389. return self.url_result(mobj.group('url'), 'HuffPost')
  390. # Look for embed.ly
  391. mobj = re.search(r'class=["\']embedly-card["\'][^>]href=["\'](?P<url>[^"\']+)', webpage)
  392. if mobj is not None:
  393. return self.url_result(mobj.group('url'))
  394. mobj = re.search(r'class=["\']embedly-embed["\'][^>]src=["\'][^"\']*url=(?P<url>[^&]+)', webpage)
  395. if mobj is not None:
  396. return self.url_result(compat_urllib_parse.unquote(mobj.group('url')))
  397. # Look for funnyordie embed
  398. matches = re.findall(r'<iframe[^>]+?src="(https?://(?:www\.)?funnyordie\.com/embed/[^"]+)"', webpage)
  399. if matches:
  400. urlrs = [self.url_result(unescapeHTML(eurl), 'FunnyOrDie')
  401. for eurl in matches]
  402. return self.playlist_result(
  403. urlrs, playlist_id=video_id, playlist_title=video_title)
  404. # Start with something easy: JW Player in SWFObject
  405. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  406. if mobj is None:
  407. # Look for gorilla-vid style embedding
  408. mobj = re.search(r'(?s)(?:jw_plugins|JWPlayerOptions).*?file\s*:\s*["\'](.*?)["\']', webpage)
  409. if mobj is None:
  410. # Broaden the search a little bit
  411. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  412. if mobj is None:
  413. # Broaden the search a little bit: JWPlayer JS loader
  414. mobj = re.search(r'[^A-Za-z0-9]?file["\']?:\s*["\'](http(?![^\'"]+\.[0-9]+[\'"])[^\'"]+)["\']', webpage)
  415. if mobj is None:
  416. # Try to find twitter cards info
  417. mobj = re.search(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
  418. if mobj is None:
  419. # We look for Open Graph info:
  420. # We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
  421. m_video_type = re.search(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
  422. # We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
  423. if m_video_type is not None:
  424. mobj = re.search(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)
  425. if mobj is None:
  426. # HTML5 video
  427. mobj = re.search(r'<video[^<]*(?:>.*?<source.*?)? src="([^"]+)"', webpage, flags=re.DOTALL)
  428. if mobj is None:
  429. mobj = re.search(
  430. r'(?i)<meta\s+(?=(?:[a-z-]+="[^"]+"\s+)*http-equiv="refresh")'
  431. r'(?:[a-z-]+="[^"]+"\s+)*?content="[0-9]{,2};url=\'([^\']+)\'"',
  432. webpage)
  433. if mobj:
  434. new_url = mobj.group(1)
  435. self.report_following_redirect(new_url)
  436. return {
  437. '_type': 'url',
  438. 'url': new_url,
  439. }
  440. if mobj is None:
  441. raise ExtractorError('Unsupported URL: %s' % url)
  442. # It's possible that one of the regexes
  443. # matched, but returned an empty group:
  444. if mobj.group(1) is None:
  445. raise ExtractorError('Did not find a valid video URL at %s' % url)
  446. video_url = mobj.group(1)
  447. video_url = compat_urlparse.urljoin(url, video_url)
  448. video_id = compat_urllib_parse.unquote(os.path.basename(video_url))
  449. # Sometimes, jwplayer extraction will result in a YouTube URL
  450. if YoutubeIE.suitable(video_url):
  451. return self.url_result(video_url, 'Youtube')
  452. # here's a fun little line of code for you:
  453. video_id = os.path.splitext(video_id)[0]
  454. return {
  455. 'id': video_id,
  456. 'url': video_url,
  457. 'uploader': video_uploader,
  458. 'title': video_title,
  459. }