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.

376 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. self._downloader.report_warning('The url doesn\'t specify the protocol, trying with http')
  151. return self.url_result('http://' + url)
  152. video_id = os.path.splitext(url.split('/')[-1])[0]
  153. self.to_screen('%s: Requesting header' % video_id)
  154. try:
  155. response = self._send_head(url)
  156. # Check for redirect
  157. new_url = response.geturl()
  158. if url != new_url:
  159. self.report_following_redirect(new_url)
  160. return self.url_result(new_url)
  161. # Check for direct link to a video
  162. content_type = response.headers.get('Content-Type', '')
  163. m = re.match(r'^(?P<type>audio|video|application(?=/ogg$))/(?P<format_id>.+)$', content_type)
  164. if m:
  165. upload_date = response.headers.get('Last-Modified')
  166. if upload_date:
  167. upload_date = unified_strdate(upload_date)
  168. return {
  169. 'id': video_id,
  170. 'title': os.path.splitext(url_basename(url))[0],
  171. 'formats': [{
  172. 'format_id': m.group('format_id'),
  173. 'url': url,
  174. 'vcodec': 'none' if m.group('type') == 'audio' else None
  175. }],
  176. 'upload_date': upload_date,
  177. }
  178. except compat_urllib_error.HTTPError:
  179. # This may be a stupid server that doesn't like HEAD, our UA, or so
  180. pass
  181. try:
  182. webpage = self._download_webpage(url, video_id)
  183. except ValueError:
  184. # since this is the last-resort InfoExtractor, if
  185. # this error is thrown, it'll be thrown here
  186. raise ExtractorError('Failed to download URL: %s' % url)
  187. self.report_extraction(video_id)
  188. # it's tempting to parse this further, but you would
  189. # have to take into account all the variations like
  190. # Video Title - Site Name
  191. # Site Name | Video Title
  192. # Video Title - Tagline | Site Name
  193. # and so on and so forth; it's just not practical
  194. video_title = self._html_search_regex(
  195. r'(?s)<title>(.*?)</title>', webpage, 'video title',
  196. default='video')
  197. # video uploader is domain name
  198. video_uploader = self._search_regex(
  199. r'^(?:https?://)?([^/]*)/.*', url, 'video uploader')
  200. # Look for BrightCove:
  201. bc_url = BrightcoveIE._extract_brightcove_url(webpage)
  202. if bc_url is not None:
  203. self.to_screen('Brightcove video detected.')
  204. surl = smuggle_url(bc_url, {'Referer': url})
  205. return self.url_result(surl, 'Brightcove')
  206. # Look for embedded (iframe) Vimeo player
  207. mobj = re.search(
  208. r'<iframe[^>]+?src="((?:https?:)?//player.vimeo.com/video/.+?)"', webpage)
  209. if mobj:
  210. player_url = unescapeHTML(mobj.group(1))
  211. surl = smuggle_url(player_url, {'Referer': url})
  212. return self.url_result(surl, 'Vimeo')
  213. # Look for embedded (swf embed) Vimeo player
  214. mobj = re.search(
  215. r'<embed[^>]+?src="(https?://(?:www\.)?vimeo.com/moogaloop.swf.+?)"', webpage)
  216. if mobj:
  217. return self.url_result(mobj.group(1), 'Vimeo')
  218. # Look for embedded YouTube player
  219. matches = re.findall(r'''(?x)
  220. (?:<iframe[^>]+?src=|embedSWF\(\s*)
  221. (["\'])(?P<url>(?:https?:)?//(?:www\.)?youtube\.com/
  222. (?:embed|v)/.+?)
  223. \1''', webpage)
  224. if matches:
  225. urlrs = [self.url_result(unescapeHTML(tuppl[1]), 'Youtube')
  226. for tuppl in matches]
  227. return self.playlist_result(
  228. urlrs, playlist_id=video_id, playlist_title=video_title)
  229. # Look for embedded Dailymotion player
  230. matches = re.findall(
  231. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/embed/video/.+?)\1', webpage)
  232. if matches:
  233. urlrs = [self.url_result(unescapeHTML(tuppl[1]), 'Dailymotion')
  234. for tuppl in matches]
  235. return self.playlist_result(
  236. urlrs, playlist_id=video_id, playlist_title=video_title)
  237. # Look for embedded Wistia player
  238. match = re.search(
  239. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:fast\.)?wistia\.net/embed/iframe/.+?)\1', webpage)
  240. if match:
  241. return {
  242. '_type': 'url_transparent',
  243. 'url': unescapeHTML(match.group('url')),
  244. 'ie_key': 'Wistia',
  245. 'uploader': video_uploader,
  246. 'title': video_title,
  247. 'id': video_id,
  248. }
  249. # Look for embedded blip.tv player
  250. mobj = re.search(r'<meta\s[^>]*https?://api\.blip\.tv/\w+/redirect/\w+/(\d+)', webpage)
  251. if mobj:
  252. return self.url_result('http://blip.tv/a/a-'+mobj.group(1), 'BlipTV')
  253. mobj = re.search(r'<(?:iframe|embed|object)\s[^>]*(https?://(?:\w+\.)?blip\.tv/(?:play/|api\.swf#)[a-zA-Z0-9]+)', webpage)
  254. if mobj:
  255. return self.url_result(mobj.group(1), 'BlipTV')
  256. # Look for Bandcamp pages with custom domain
  257. mobj = re.search(r'<meta property="og:url"[^>]*?content="(.*?bandcamp\.com.*?)"', webpage)
  258. if mobj is not None:
  259. burl = unescapeHTML(mobj.group(1))
  260. # Don't set the extractor because it can be a track url or an album
  261. return self.url_result(burl)
  262. # Look for embedded Vevo player
  263. mobj = re.search(
  264. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:cache\.)?vevo\.com/.+?)\1', webpage)
  265. if mobj is not None:
  266. return self.url_result(mobj.group('url'))
  267. # Look for Ooyala videos
  268. mobj = re.search(r'player.ooyala.com/[^"?]+\?[^"]*?(?:embedCode|ec)=([^"&]+)', webpage)
  269. if mobj is not None:
  270. return OoyalaIE._build_url_result(mobj.group(1))
  271. # Look for Aparat videos
  272. mobj = re.search(r'<iframe src="(http://www\.aparat\.com/video/[^"]+)"', webpage)
  273. if mobj is not None:
  274. return self.url_result(mobj.group(1), 'Aparat')
  275. # Look for MPORA videos
  276. mobj = re.search(r'<iframe .*?src="(http://mpora\.com/videos/[^"]+)"', webpage)
  277. if mobj is not None:
  278. return self.url_result(mobj.group(1), 'Mpora')
  279. # Look for embedded Novamov player
  280. mobj = re.search(
  281. r'<iframe[^>]+?src=(["\'])(?P<url>http://(?:(?:embed|www)\.)?novamov\.com/embed\.php.+?)\1', webpage)
  282. if mobj is not None:
  283. return self.url_result(mobj.group('url'), 'Novamov')
  284. # Look for embedded Facebook player
  285. mobj = re.search(
  286. r'<iframe[^>]+?src=(["\'])(?P<url>https://www.facebook.com/video/embed.+?)\1', webpage)
  287. if mobj is not None:
  288. return self.url_result(mobj.group('url'), 'Facebook')
  289. # Start with something easy: JW Player in SWFObject
  290. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  291. if mobj is None:
  292. # Look for gorilla-vid style embedding
  293. mobj = re.search(r'(?s)jw_plugins.*?file:\s*["\'](.*?)["\']', webpage)
  294. if mobj is None:
  295. # Broaden the search a little bit
  296. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  297. if mobj is None:
  298. # Broaden the search a little bit: JWPlayer JS loader
  299. mobj = re.search(r'[^A-Za-z0-9]?file["\']?:\s*["\'](http(?![^\'"]+\.[0-9]+[\'"])[^\'"]+)["\']', webpage)
  300. if mobj is None:
  301. # Try to find twitter cards info
  302. mobj = re.search(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
  303. if mobj is None:
  304. # We look for Open Graph info:
  305. # We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
  306. m_video_type = re.search(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
  307. # We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
  308. if m_video_type is not None:
  309. mobj = re.search(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)
  310. if mobj is None:
  311. # HTML5 video
  312. mobj = re.search(r'<video[^<]*(?:>.*?<source.*?)? src="([^"]+)"', webpage, flags=re.DOTALL)
  313. if mobj is None:
  314. raise ExtractorError('Unsupported URL: %s' % url)
  315. # It's possible that one of the regexes
  316. # matched, but returned an empty group:
  317. if mobj.group(1) is None:
  318. raise ExtractorError('Did not find a valid video URL at %s' % url)
  319. video_url = mobj.group(1)
  320. video_url = compat_urlparse.urljoin(url, video_url)
  321. video_id = compat_urllib_parse.unquote(os.path.basename(video_url))
  322. # Sometimes, jwplayer extraction will result in a YouTube URL
  323. if YoutubeIE.suitable(video_url):
  324. return self.url_result(video_url, 'Youtube')
  325. # here's a fun little line of code for you:
  326. video_id = os.path.splitext(video_id)[0]
  327. return {
  328. 'id': video_id,
  329. 'url': video_url,
  330. 'uploader': video_uploader,
  331. 'title': video_title,
  332. }