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.

495 lines
20 KiB

  1. # encoding: utf-8
  2. from __future__ import unicode_literals
  3. import os
  4. import re
  5. import xml.etree.ElementTree
  6. from .common import InfoExtractor
  7. from .youtube import YoutubeIE
  8. from ..utils import (
  9. compat_urllib_error,
  10. compat_urllib_parse,
  11. compat_urllib_request,
  12. compat_urlparse,
  13. compat_xml_parse_error,
  14. ExtractorError,
  15. HEADRequest,
  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. ]
  132. def report_download_webpage(self, video_id):
  133. """Report webpage download."""
  134. if not self._downloader.params.get('test', False):
  135. self._downloader.report_warning('Falling back on generic information extractor.')
  136. super(GenericIE, self).report_download_webpage(video_id)
  137. def report_following_redirect(self, new_url):
  138. """Report information extraction."""
  139. self._downloader.to_screen('[redirect] Following redirect to %s' % new_url)
  140. def _send_head(self, url):
  141. """Check if it is a redirect, like url shorteners, in case return the new url."""
  142. class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  143. """
  144. Subclass the HTTPRedirectHandler to make it use our
  145. HEADRequest also on the redirected URL
  146. """
  147. def redirect_request(self, req, fp, code, msg, headers, newurl):
  148. if code in (301, 302, 303, 307):
  149. newurl = newurl.replace(' ', '%20')
  150. newheaders = dict((k,v) for k,v in req.headers.items()
  151. if k.lower() not in ("content-length", "content-type"))
  152. return HEADRequest(newurl,
  153. headers=newheaders,
  154. origin_req_host=req.get_origin_req_host(),
  155. unverifiable=True)
  156. else:
  157. raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
  158. class HTTPMethodFallback(compat_urllib_request.BaseHandler):
  159. """
  160. Fallback to GET if HEAD is not allowed (405 HTTP error)
  161. """
  162. def http_error_405(self, req, fp, code, msg, headers):
  163. fp.read()
  164. fp.close()
  165. newheaders = dict((k,v) for k,v in req.headers.items()
  166. if k.lower() not in ("content-length", "content-type"))
  167. return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
  168. headers=newheaders,
  169. origin_req_host=req.get_origin_req_host(),
  170. unverifiable=True))
  171. # Build our opener
  172. opener = compat_urllib_request.OpenerDirector()
  173. for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
  174. HTTPMethodFallback, HEADRedirectHandler,
  175. compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
  176. opener.add_handler(handler())
  177. response = opener.open(HEADRequest(url))
  178. if response is None:
  179. raise ExtractorError('Invalid URL protocol')
  180. return response
  181. def _extract_rss(self, url, video_id, doc):
  182. playlist_title = doc.find('./channel/title').text
  183. playlist_desc_el = doc.find('./channel/description')
  184. playlist_desc = None if playlist_desc_el is None else playlist_desc_el.text
  185. entries = [{
  186. '_type': 'url',
  187. 'url': e.find('link').text,
  188. 'title': e.find('title').text,
  189. } for e in doc.findall('./channel/item')]
  190. return {
  191. '_type': 'playlist',
  192. 'id': url,
  193. 'title': playlist_title,
  194. 'description': playlist_desc,
  195. 'entries': entries,
  196. }
  197. def _real_extract(self, url):
  198. parsed_url = compat_urlparse.urlparse(url)
  199. if not parsed_url.scheme:
  200. default_search = self._downloader.params.get('default_search')
  201. if default_search is None:
  202. default_search = 'auto'
  203. if default_search == 'auto':
  204. if '/' in url:
  205. self._downloader.report_warning('The url doesn\'t specify the protocol, trying with http')
  206. return self.url_result('http://' + url)
  207. else:
  208. return self.url_result('ytsearch:' + url)
  209. else:
  210. assert ':' in default_search
  211. return self.url_result(default_search + url)
  212. video_id = os.path.splitext(url.rstrip('/').split('/')[-1])[0]
  213. self.to_screen('%s: Requesting header' % video_id)
  214. try:
  215. response = self._send_head(url)
  216. # Check for redirect
  217. new_url = response.geturl()
  218. if url != new_url:
  219. self.report_following_redirect(new_url)
  220. return self.url_result(new_url)
  221. # Check for direct link to a video
  222. content_type = response.headers.get('Content-Type', '')
  223. m = re.match(r'^(?P<type>audio|video|application(?=/ogg$))/(?P<format_id>.+)$', content_type)
  224. if m:
  225. upload_date = response.headers.get('Last-Modified')
  226. if upload_date:
  227. upload_date = unified_strdate(upload_date)
  228. return {
  229. 'id': video_id,
  230. 'title': os.path.splitext(url_basename(url))[0],
  231. 'formats': [{
  232. 'format_id': m.group('format_id'),
  233. 'url': url,
  234. 'vcodec': 'none' if m.group('type') == 'audio' else None
  235. }],
  236. 'upload_date': upload_date,
  237. }
  238. except compat_urllib_error.HTTPError:
  239. # This may be a stupid server that doesn't like HEAD, our UA, or so
  240. pass
  241. try:
  242. webpage = self._download_webpage(url, video_id)
  243. except ValueError:
  244. # since this is the last-resort InfoExtractor, if
  245. # this error is thrown, it'll be thrown here
  246. raise ExtractorError('Failed to download URL: %s' % url)
  247. self.report_extraction(video_id)
  248. # Is it an RSS feed?
  249. try:
  250. doc = xml.etree.ElementTree.fromstring(webpage.encode('utf-8'))
  251. if doc.tag == 'rss':
  252. return self._extract_rss(url, video_id, doc)
  253. except compat_xml_parse_error:
  254. pass
  255. # it's tempting to parse this further, but you would
  256. # have to take into account all the variations like
  257. # Video Title - Site Name
  258. # Site Name | Video Title
  259. # Video Title - Tagline | Site Name
  260. # and so on and so forth; it's just not practical
  261. video_title = self._html_search_regex(
  262. r'(?s)<title>(.*?)</title>', webpage, 'video title',
  263. default='video')
  264. # video uploader is domain name
  265. video_uploader = self._search_regex(
  266. r'^(?:https?://)?([^/]*)/.*', url, 'video uploader')
  267. # Look for BrightCove:
  268. bc_urls = BrightcoveIE._extract_brightcove_urls(webpage)
  269. if bc_urls:
  270. self.to_screen('Brightcove video detected.')
  271. entries = [{
  272. '_type': 'url',
  273. 'url': smuggle_url(bc_url, {'Referer': url}),
  274. 'ie_key': 'Brightcove'
  275. } for bc_url in bc_urls]
  276. return {
  277. '_type': 'playlist',
  278. 'title': video_title,
  279. 'id': video_id,
  280. 'entries': entries,
  281. }
  282. # Look for embedded (iframe) Vimeo player
  283. mobj = re.search(
  284. r'<iframe[^>]+?src="((?:https?:)?//player\.vimeo\.com/video/.+?)"', webpage)
  285. if mobj:
  286. player_url = unescapeHTML(mobj.group(1))
  287. surl = smuggle_url(player_url, {'Referer': url})
  288. return self.url_result(surl, 'Vimeo')
  289. # Look for embedded (swf embed) Vimeo player
  290. mobj = re.search(
  291. r'<embed[^>]+?src="(https?://(?:www\.)?vimeo\.com/moogaloop\.swf.+?)"', webpage)
  292. if mobj:
  293. return self.url_result(mobj.group(1), 'Vimeo')
  294. # Look for embedded YouTube player
  295. matches = re.findall(r'''(?x)
  296. (?:<iframe[^>]+?src=|embedSWF\(\s*)
  297. (["\'])(?P<url>(?:https?:)?//(?:www\.)?youtube\.com/
  298. (?:embed|v)/.+?)
  299. \1''', webpage)
  300. if matches:
  301. urlrs = [self.url_result(unescapeHTML(tuppl[1]), 'Youtube')
  302. for tuppl in matches]
  303. return self.playlist_result(
  304. urlrs, playlist_id=video_id, playlist_title=video_title)
  305. # Look for embedded Dailymotion player
  306. matches = re.findall(
  307. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/embed/video/.+?)\1', webpage)
  308. if matches:
  309. urlrs = [self.url_result(unescapeHTML(tuppl[1]), 'Dailymotion')
  310. for tuppl in matches]
  311. return self.playlist_result(
  312. urlrs, playlist_id=video_id, playlist_title=video_title)
  313. # Look for embedded Wistia player
  314. match = re.search(
  315. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:fast\.)?wistia\.net/embed/iframe/.+?)\1', webpage)
  316. if match:
  317. return {
  318. '_type': 'url_transparent',
  319. 'url': unescapeHTML(match.group('url')),
  320. 'ie_key': 'Wistia',
  321. 'uploader': video_uploader,
  322. 'title': video_title,
  323. 'id': video_id,
  324. }
  325. # Look for embedded blip.tv player
  326. mobj = re.search(r'<meta\s[^>]*https?://api\.blip\.tv/\w+/redirect/\w+/(\d+)', webpage)
  327. if mobj:
  328. return self.url_result('http://blip.tv/a/a-'+mobj.group(1), 'BlipTV')
  329. mobj = re.search(r'<(?:iframe|embed|object)\s[^>]*(https?://(?:\w+\.)?blip\.tv/(?:play/|api\.swf#)[a-zA-Z0-9]+)', webpage)
  330. if mobj:
  331. return self.url_result(mobj.group(1), 'BlipTV')
  332. # Look for Bandcamp pages with custom domain
  333. mobj = re.search(r'<meta property="og:url"[^>]*?content="(.*?bandcamp\.com.*?)"', webpage)
  334. if mobj is not None:
  335. burl = unescapeHTML(mobj.group(1))
  336. # Don't set the extractor because it can be a track url or an album
  337. return self.url_result(burl)
  338. # Look for embedded Vevo player
  339. mobj = re.search(
  340. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:cache\.)?vevo\.com/.+?)\1', webpage)
  341. if mobj is not None:
  342. return self.url_result(mobj.group('url'))
  343. # Look for Ooyala videos
  344. mobj = re.search(r'player.ooyala.com/[^"?]+\?[^"]*?(?:embedCode|ec)=([^"&]+)', webpage)
  345. if mobj is not None:
  346. return OoyalaIE._build_url_result(mobj.group(1))
  347. # Look for Aparat videos
  348. mobj = re.search(r'<iframe src="(http://www\.aparat\.com/video/[^"]+)"', webpage)
  349. if mobj is not None:
  350. return self.url_result(mobj.group(1), 'Aparat')
  351. # Look for MPORA videos
  352. mobj = re.search(r'<iframe .*?src="(http://mpora\.(?:com|de)/videos/[^"]+)"', webpage)
  353. if mobj is not None:
  354. return self.url_result(mobj.group(1), 'Mpora')
  355. # Look for embedded NovaMov player
  356. mobj = re.search(
  357. r'<iframe[^>]+?src=(["\'])(?P<url>http://(?:(?:embed|www)\.)?novamov\.com/embed\.php.+?)\1', webpage)
  358. if mobj is not None:
  359. return self.url_result(mobj.group('url'), 'NovaMov')
  360. # Look for embedded NowVideo player
  361. mobj = re.search(
  362. r'<iframe[^>]+?src=(["\'])(?P<url>http://(?:(?:embed|www)\.)?nowvideo\.(?:ch|sx|eu)/embed\.php.+?)\1', webpage)
  363. if mobj is not None:
  364. return self.url_result(mobj.group('url'), 'NowVideo')
  365. # Look for embedded Facebook player
  366. mobj = re.search(
  367. r'<iframe[^>]+?src=(["\'])(?P<url>https://www\.facebook\.com/video/embed.+?)\1', webpage)
  368. if mobj is not None:
  369. return self.url_result(mobj.group('url'), 'Facebook')
  370. # Look for embedded VK player
  371. mobj = re.search(r'<iframe[^>]+?src=(["\'])(?P<url>https?://vk\.com/video_ext\.php.+?)\1', webpage)
  372. if mobj is not None:
  373. return self.url_result(mobj.group('url'), 'VK')
  374. # Look for embedded Huffington Post player
  375. mobj = re.search(
  376. r'<iframe[^>]+?src=(["\'])(?P<url>https?://embed\.live\.huffingtonpost\.com/.+?)\1', webpage)
  377. if mobj is not None:
  378. return self.url_result(mobj.group('url'), 'HuffPost')
  379. # Look for embed.ly
  380. mobj = re.search(r'class=["\']embedly-card["\'][^>]href=["\'](?P<url>[^"\']+)', webpage)
  381. if mobj is not None:
  382. return self.url_result(mobj.group('url'))
  383. mobj = re.search(r'class=["\']embedly-embed["\'][^>]src=["\'][^"\']*url=(?P<url>[^&]+)', webpage)
  384. if mobj is not None:
  385. return self.url_result(compat_urllib_parse.unquote(mobj.group('url')))
  386. # Start with something easy: JW Player in SWFObject
  387. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  388. if mobj is None:
  389. # Look for gorilla-vid style embedding
  390. mobj = re.search(r'(?s)(?:jw_plugins|JWPlayerOptions).*?file\s*:\s*["\'](.*?)["\']', webpage)
  391. if mobj is None:
  392. # Broaden the search a little bit
  393. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  394. if mobj is None:
  395. # Broaden the search a little bit: JWPlayer JS loader
  396. mobj = re.search(r'[^A-Za-z0-9]?file["\']?:\s*["\'](http(?![^\'"]+\.[0-9]+[\'"])[^\'"]+)["\']', webpage)
  397. if mobj is None:
  398. # Try to find twitter cards info
  399. mobj = re.search(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
  400. if mobj is None:
  401. # We look for Open Graph info:
  402. # We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
  403. m_video_type = re.search(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
  404. # We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
  405. if m_video_type is not None:
  406. mobj = re.search(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)
  407. if mobj is None:
  408. # HTML5 video
  409. mobj = re.search(r'<video[^<]*(?:>.*?<source.*?)? src="([^"]+)"', webpage, flags=re.DOTALL)
  410. if mobj is None:
  411. mobj = re.search(
  412. r'(?i)<meta\s+(?=(?:[a-z-]+="[^"]+"\s+)*http-equiv="refresh")'
  413. r'(?:[a-z-]+="[^"]+"\s+)*?content="[0-9]{,2};url=\'([^\']+)\'"',
  414. webpage)
  415. if mobj:
  416. new_url = mobj.group(1)
  417. self.report_following_redirect(new_url)
  418. return {
  419. '_type': 'url',
  420. 'url': new_url,
  421. }
  422. if mobj is None:
  423. raise ExtractorError('Unsupported URL: %s' % url)
  424. # It's possible that one of the regexes
  425. # matched, but returned an empty group:
  426. if mobj.group(1) is None:
  427. raise ExtractorError('Did not find a valid video URL at %s' % url)
  428. video_url = mobj.group(1)
  429. video_url = compat_urlparse.urljoin(url, video_url)
  430. video_id = compat_urllib_parse.unquote(os.path.basename(video_url))
  431. # Sometimes, jwplayer extraction will result in a YouTube URL
  432. if YoutubeIE.suitable(video_url):
  433. return self.url_result(video_url, 'Youtube')
  434. # here's a fun little line of code for you:
  435. video_id = os.path.splitext(video_id)[0]
  436. return {
  437. 'id': video_id,
  438. 'url': video_url,
  439. 'uploader': video_uploader,
  440. 'title': video_title,
  441. }