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.

393 lines
16 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. ExtractorError,
  13. HEADRequest,
  14. smuggle_url,
  15. unescapeHTML,
  16. unified_strdate,
  17. url_basename,
  18. )
  19. from .brightcove import BrightcoveIE
  20. from .ooyala import OoyalaIE
  21. class GenericIE(InfoExtractor):
  22. IE_DESC = 'Generic downloader that works on some sites'
  23. _VALID_URL = r'.*'
  24. IE_NAME = 'generic'
  25. _TESTS = [
  26. {
  27. 'url': 'http://www.hodiho.fr/2013/02/regis-plante-sa-jeep.html',
  28. 'file': '13601338388002.mp4',
  29. 'md5': '6e15c93721d7ec9e9ca3fdbf07982cfd',
  30. 'info_dict': {
  31. 'uploader': 'www.hodiho.fr',
  32. 'title': 'R\u00e9gis plante sa Jeep',
  33. }
  34. },
  35. # embedded vimeo video
  36. {
  37. 'add_ie': ['Vimeo'],
  38. 'url': 'http://skillsmatter.com/podcast/home/move-semanticsperfect-forwarding-and-rvalue-references',
  39. 'file': '22444065.mp4',
  40. 'md5': '2903896e23df39722c33f015af0666e2',
  41. 'info_dict': {
  42. 'title': 'ACCU 2011: Move Semantics,Perfect Forwarding, and Rvalue references- Scott Meyers- 13/04/2011',
  43. 'uploader_id': 'skillsmatter',
  44. 'uploader': 'Skills Matter',
  45. }
  46. },
  47. # bandcamp page with custom domain
  48. {
  49. 'add_ie': ['Bandcamp'],
  50. 'url': 'http://bronyrock.com/track/the-pony-mash',
  51. 'file': '3235767654.mp3',
  52. 'info_dict': {
  53. 'title': 'The Pony Mash',
  54. 'uploader': 'M_Pallante',
  55. },
  56. 'skip': 'There is a limit of 200 free downloads / month for the test song',
  57. },
  58. # embedded brightcove video
  59. # it also tests brightcove videos that need to set the 'Referer' in the
  60. # http requests
  61. {
  62. 'add_ie': ['Brightcove'],
  63. 'url': 'http://www.bfmtv.com/video/bfmbusiness/cours-bourse/cours-bourse-l-analyse-technique-154522/',
  64. 'info_dict': {
  65. 'id': '2765128793001',
  66. 'ext': 'mp4',
  67. 'title': 'Le cours de bourse : l’analyse technique',
  68. 'description': 'md5:7e9ad046e968cb2d1114004aba466fd9',
  69. 'uploader': 'BFM BUSINESS',
  70. },
  71. 'params': {
  72. 'skip_download': True,
  73. },
  74. },
  75. # Direct link to a video
  76. {
  77. 'url': 'http://media.w3.org/2010/05/sintel/trailer.mp4',
  78. 'file': 'trailer.mp4',
  79. 'md5': '67d406c2bcb6af27fa886f31aa934bbe',
  80. 'info_dict': {
  81. 'id': 'trailer',
  82. 'title': 'trailer',
  83. 'upload_date': '20100513',
  84. }
  85. },
  86. # ooyala video
  87. {
  88. 'url': 'http://www.rollingstone.com/music/videos/norwegian-dj-cashmere-cat-goes-spartan-on-with-me-premiere-20131219',
  89. 'file': 'BwY2RxaTrTkslxOfcan0UCf0YqyvWysJ.mp4',
  90. 'md5': '5644c6ca5d5782c1d0d350dad9bd840c',
  91. 'info_dict': {
  92. 'id': 'BwY2RxaTrTkslxOfcan0UCf0YqyvWysJ',
  93. 'ext': 'mp4',
  94. 'title': '2cc213299525360.mov', # that's what we get
  95. },
  96. },
  97. ]
  98. def report_download_webpage(self, video_id):
  99. """Report webpage download."""
  100. if not self._downloader.params.get('test', False):
  101. self._downloader.report_warning('Falling back on generic information extractor.')
  102. super(GenericIE, self).report_download_webpage(video_id)
  103. def report_following_redirect(self, new_url):
  104. """Report information extraction."""
  105. self._downloader.to_screen('[redirect] Following redirect to %s' % new_url)
  106. def _send_head(self, url):
  107. """Check if it is a redirect, like url shorteners, in case return the new url."""
  108. class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  109. """
  110. Subclass the HTTPRedirectHandler to make it use our
  111. HEADRequest also on the redirected URL
  112. """
  113. def redirect_request(self, req, fp, code, msg, headers, newurl):
  114. if code in (301, 302, 303, 307):
  115. newurl = newurl.replace(' ', '%20')
  116. newheaders = dict((k,v) for k,v in req.headers.items()
  117. if k.lower() not in ("content-length", "content-type"))
  118. return HEADRequest(newurl,
  119. headers=newheaders,
  120. origin_req_host=req.get_origin_req_host(),
  121. unverifiable=True)
  122. else:
  123. raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
  124. class HTTPMethodFallback(compat_urllib_request.BaseHandler):
  125. """
  126. Fallback to GET if HEAD is not allowed (405 HTTP error)
  127. """
  128. def http_error_405(self, req, fp, code, msg, headers):
  129. fp.read()
  130. fp.close()
  131. newheaders = dict((k,v) for k,v in req.headers.items()
  132. if k.lower() not in ("content-length", "content-type"))
  133. return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
  134. headers=newheaders,
  135. origin_req_host=req.get_origin_req_host(),
  136. unverifiable=True))
  137. # Build our opener
  138. opener = compat_urllib_request.OpenerDirector()
  139. for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
  140. HTTPMethodFallback, HEADRedirectHandler,
  141. compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
  142. opener.add_handler(handler())
  143. response = opener.open(HEADRequest(url))
  144. if response is None:
  145. raise ExtractorError('Invalid URL protocol')
  146. return response
  147. def _real_extract(self, url):
  148. parsed_url = compat_urlparse.urlparse(url)
  149. if not parsed_url.scheme:
  150. default_search = self._downloader.params.get('default_search')
  151. if default_search is None:
  152. default_search = 'auto'
  153. if default_search == 'auto':
  154. if '/' in url:
  155. self._downloader.report_warning('The url doesn\'t specify the protocol, trying with http')
  156. return self.url_result('http://' + url)
  157. else:
  158. return self.url_result('ytsearch:' + url)
  159. else:
  160. assert ':' in default_search
  161. return self.url_result(default_search + url)
  162. video_id = os.path.splitext(url.split('/')[-1])[0]
  163. self.to_screen('%s: Requesting header' % video_id)
  164. try:
  165. response = self._send_head(url)
  166. # Check for redirect
  167. new_url = response.geturl()
  168. if url != new_url:
  169. self.report_following_redirect(new_url)
  170. return self.url_result(new_url)
  171. # Check for direct link to a video
  172. content_type = response.headers.get('Content-Type', '')
  173. m = re.match(r'^(?P<type>audio|video|application(?=/ogg$))/(?P<format_id>.+)$', content_type)
  174. if m:
  175. upload_date = response.headers.get('Last-Modified')
  176. if upload_date:
  177. upload_date = unified_strdate(upload_date)
  178. return {
  179. 'id': video_id,
  180. 'title': os.path.splitext(url_basename(url))[0],
  181. 'formats': [{
  182. 'format_id': m.group('format_id'),
  183. 'url': url,
  184. 'vcodec': 'none' if m.group('type') == 'audio' else None
  185. }],
  186. 'upload_date': upload_date,
  187. }
  188. except compat_urllib_error.HTTPError:
  189. # This may be a stupid server that doesn't like HEAD, our UA, or so
  190. pass
  191. try:
  192. webpage = self._download_webpage(url, video_id)
  193. except ValueError:
  194. # since this is the last-resort InfoExtractor, if
  195. # this error is thrown, it'll be thrown here
  196. raise ExtractorError('Failed to download URL: %s' % url)
  197. self.report_extraction(video_id)
  198. # it's tempting to parse this further, but you would
  199. # have to take into account all the variations like
  200. # Video Title - Site Name
  201. # Site Name | Video Title
  202. # Video Title - Tagline | Site Name
  203. # and so on and so forth; it's just not practical
  204. video_title = self._html_search_regex(
  205. r'(?s)<title>(.*?)</title>', webpage, 'video title',
  206. default='video')
  207. # video uploader is domain name
  208. video_uploader = self._search_regex(
  209. r'^(?:https?://)?([^/]*)/.*', url, 'video uploader')
  210. # Look for BrightCove:
  211. bc_url = BrightcoveIE._extract_brightcove_url(webpage)
  212. if bc_url is not None:
  213. self.to_screen('Brightcove video detected.')
  214. surl = smuggle_url(bc_url, {'Referer': url})
  215. return self.url_result(surl, 'Brightcove')
  216. # Look for embedded (iframe) Vimeo player
  217. mobj = re.search(
  218. r'<iframe[^>]+?src="((?:https?:)?//player.vimeo.com/video/.+?)"', webpage)
  219. if mobj:
  220. player_url = unescapeHTML(mobj.group(1))
  221. surl = smuggle_url(player_url, {'Referer': url})
  222. return self.url_result(surl, 'Vimeo')
  223. # Look for embedded (swf embed) Vimeo player
  224. mobj = re.search(
  225. r'<embed[^>]+?src="(https?://(?:www\.)?vimeo.com/moogaloop.swf.+?)"', webpage)
  226. if mobj:
  227. return self.url_result(mobj.group(1), 'Vimeo')
  228. # Look for embedded YouTube player
  229. matches = re.findall(r'''(?x)
  230. (?:<iframe[^>]+?src=|embedSWF\(\s*)
  231. (["\'])(?P<url>(?:https?:)?//(?:www\.)?youtube\.com/
  232. (?:embed|v)/.+?)
  233. \1''', webpage)
  234. if matches:
  235. urlrs = [self.url_result(unescapeHTML(tuppl[1]), 'Youtube')
  236. for tuppl in matches]
  237. return self.playlist_result(
  238. urlrs, playlist_id=video_id, playlist_title=video_title)
  239. # Look for embedded Dailymotion player
  240. matches = re.findall(
  241. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/embed/video/.+?)\1', webpage)
  242. if matches:
  243. urlrs = [self.url_result(unescapeHTML(tuppl[1]), 'Dailymotion')
  244. for tuppl in matches]
  245. return self.playlist_result(
  246. urlrs, playlist_id=video_id, playlist_title=video_title)
  247. # Look for embedded Wistia player
  248. match = re.search(
  249. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:fast\.)?wistia\.net/embed/iframe/.+?)\1', webpage)
  250. if match:
  251. return {
  252. '_type': 'url_transparent',
  253. 'url': unescapeHTML(match.group('url')),
  254. 'ie_key': 'Wistia',
  255. 'uploader': video_uploader,
  256. 'title': video_title,
  257. 'id': video_id,
  258. }
  259. # Look for embedded blip.tv player
  260. mobj = re.search(r'<meta\s[^>]*https?://api\.blip\.tv/\w+/redirect/\w+/(\d+)', webpage)
  261. if mobj:
  262. return self.url_result('http://blip.tv/a/a-'+mobj.group(1), 'BlipTV')
  263. mobj = re.search(r'<(?:iframe|embed|object)\s[^>]*(https?://(?:\w+\.)?blip\.tv/(?:play/|api\.swf#)[a-zA-Z0-9]+)', webpage)
  264. if mobj:
  265. return self.url_result(mobj.group(1), 'BlipTV')
  266. # Look for Bandcamp pages with custom domain
  267. mobj = re.search(r'<meta property="og:url"[^>]*?content="(.*?bandcamp\.com.*?)"', webpage)
  268. if mobj is not None:
  269. burl = unescapeHTML(mobj.group(1))
  270. # Don't set the extractor because it can be a track url or an album
  271. return self.url_result(burl)
  272. # Look for embedded Vevo player
  273. mobj = re.search(
  274. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:cache\.)?vevo\.com/.+?)\1', webpage)
  275. if mobj is not None:
  276. return self.url_result(mobj.group('url'))
  277. # Look for Ooyala videos
  278. mobj = re.search(r'player.ooyala.com/[^"?]+\?[^"]*?(?:embedCode|ec)=([^"&]+)', webpage)
  279. if mobj is not None:
  280. return OoyalaIE._build_url_result(mobj.group(1))
  281. # Look for Aparat videos
  282. mobj = re.search(r'<iframe src="(http://www\.aparat\.com/video/[^"]+)"', webpage)
  283. if mobj is not None:
  284. return self.url_result(mobj.group(1), 'Aparat')
  285. # Look for MPORA videos
  286. mobj = re.search(r'<iframe .*?src="(http://mpora\.com/videos/[^"]+)"', webpage)
  287. if mobj is not None:
  288. return self.url_result(mobj.group(1), 'Mpora')
  289. # Look for embedded Novamov player
  290. mobj = re.search(
  291. r'<iframe[^>]+?src=(["\'])(?P<url>http://(?:(?:embed|www)\.)?novamov\.com/embed\.php.+?)\1', webpage)
  292. if mobj is not None:
  293. return self.url_result(mobj.group('url'), 'Novamov')
  294. # Look for embedded Facebook player
  295. mobj = re.search(
  296. r'<iframe[^>]+?src=(["\'])(?P<url>https://www\.facebook\.com/video/embed.+?)\1', webpage)
  297. if mobj is not None:
  298. return self.url_result(mobj.group('url'), 'Facebook')
  299. # Look for embedded Huffington Post player
  300. mobj = re.search(
  301. r'<iframe[^>]+?src=(["\'])(?P<url>https?://embed\.live.huffingtonpost\.com/.+?)\1', webpage)
  302. if mobj is not None:
  303. return self.url_result(mobj.group('url'), 'HuffPost')
  304. # Start with something easy: JW Player in SWFObject
  305. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  306. if mobj is None:
  307. # Look for gorilla-vid style embedding
  308. mobj = re.search(r'(?s)jw_plugins.*?file:\s*["\'](.*?)["\']', webpage)
  309. if mobj is None:
  310. # Broaden the search a little bit
  311. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  312. if mobj is None:
  313. # Broaden the search a little bit: JWPlayer JS loader
  314. mobj = re.search(r'[^A-Za-z0-9]?file["\']?:\s*["\'](http(?![^\'"]+\.[0-9]+[\'"])[^\'"]+)["\']', webpage)
  315. if mobj is None:
  316. # Try to find twitter cards info
  317. mobj = re.search(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
  318. if mobj is None:
  319. # We look for Open Graph info:
  320. # We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
  321. m_video_type = re.search(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
  322. # We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
  323. if m_video_type is not None:
  324. mobj = re.search(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)
  325. if mobj is None:
  326. # HTML5 video
  327. mobj = re.search(r'<video[^<]*(?:>.*?<source.*?)? src="([^"]+)"', webpage, flags=re.DOTALL)
  328. if mobj is None:
  329. raise ExtractorError('Unsupported URL: %s' % url)
  330. # It's possible that one of the regexes
  331. # matched, but returned an empty group:
  332. if mobj.group(1) is None:
  333. raise ExtractorError('Did not find a valid video URL at %s' % url)
  334. video_url = mobj.group(1)
  335. video_url = compat_urlparse.urljoin(url, video_url)
  336. video_id = compat_urllib_parse.unquote(os.path.basename(video_url))
  337. # Sometimes, jwplayer extraction will result in a YouTube URL
  338. if YoutubeIE.suitable(video_url):
  339. return self.url_result(video_url, 'Youtube')
  340. # here's a fun little line of code for you:
  341. video_id = os.path.splitext(video_id)[0]
  342. return {
  343. 'id': video_id,
  344. 'url': video_url,
  345. 'uploader': video_uploader,
  346. 'title': video_title,
  347. }