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.

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