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.

357 lines
15 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. 'md5': '5644c6ca5d5782c1d0d350dad9bd840c',
  90. 'info_dict': {
  91. 'id': 'BwY2RxaTrTkslxOfcan0UCf0YqyvWysJ',
  92. 'ext': 'mp4',
  93. 'title': '2cc213299525360.mov', #that's what we get
  94. },
  95. },
  96. ]
  97. def report_download_webpage(self, video_id):
  98. """Report webpage download."""
  99. if not self._downloader.params.get('test', False):
  100. self._downloader.report_warning('Falling back on generic information extractor.')
  101. super(GenericIE, self).report_download_webpage(video_id)
  102. def report_following_redirect(self, new_url):
  103. """Report information extraction."""
  104. self._downloader.to_screen('[redirect] Following redirect to %s' % new_url)
  105. def _send_head(self, url):
  106. """Check if it is a redirect, like url shorteners, in case return the new url."""
  107. class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  108. """
  109. Subclass the HTTPRedirectHandler to make it use our
  110. HEADRequest also on the redirected URL
  111. """
  112. def redirect_request(self, req, fp, code, msg, headers, newurl):
  113. if code in (301, 302, 303, 307):
  114. newurl = newurl.replace(' ', '%20')
  115. newheaders = dict((k,v) for k,v in req.headers.items()
  116. if k.lower() not in ("content-length", "content-type"))
  117. return HEADRequest(newurl,
  118. headers=newheaders,
  119. origin_req_host=req.get_origin_req_host(),
  120. unverifiable=True)
  121. else:
  122. raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
  123. class HTTPMethodFallback(compat_urllib_request.BaseHandler):
  124. """
  125. Fallback to GET if HEAD is not allowed (405 HTTP error)
  126. """
  127. def http_error_405(self, req, fp, code, msg, headers):
  128. fp.read()
  129. fp.close()
  130. newheaders = dict((k,v) for k,v in req.headers.items()
  131. if k.lower() not in ("content-length", "content-type"))
  132. return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
  133. headers=newheaders,
  134. origin_req_host=req.get_origin_req_host(),
  135. unverifiable=True))
  136. # Build our opener
  137. opener = compat_urllib_request.OpenerDirector()
  138. for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
  139. HTTPMethodFallback, HEADRedirectHandler,
  140. compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
  141. opener.add_handler(handler())
  142. response = opener.open(HEADRequest(url))
  143. if response is None:
  144. raise ExtractorError('Invalid URL protocol')
  145. return response
  146. def _real_extract(self, url):
  147. parsed_url = compat_urlparse.urlparse(url)
  148. if not parsed_url.scheme:
  149. self._downloader.report_warning('The url doesn\'t specify the protocol, trying with http')
  150. return self.url_result('http://' + url)
  151. video_id = os.path.splitext(url.split('/')[-1])[0]
  152. self.to_screen('%s: Requesting header' % video_id)
  153. try:
  154. response = self._send_head(url)
  155. # Check for redirect
  156. new_url = response.geturl()
  157. if url != new_url:
  158. self.report_following_redirect(new_url)
  159. return self.url_result(new_url)
  160. # Check for direct link to a video
  161. content_type = response.headers.get('Content-Type', '')
  162. m = re.match(r'^(?P<type>audio|video|application(?=/ogg$))/(?P<format_id>.+)$', content_type)
  163. if m:
  164. upload_date = response.headers.get('Last-Modified')
  165. if upload_date:
  166. upload_date = unified_strdate(upload_date)
  167. return {
  168. 'id': video_id,
  169. 'title': os.path.splitext(url_basename(url))[0],
  170. 'formats': [{
  171. 'format_id': m.group('format_id'),
  172. 'url': url,
  173. 'vcodec': 'none' if m.group('type') == 'audio' else None
  174. }],
  175. 'upload_date': upload_date,
  176. }
  177. except compat_urllib_error.HTTPError:
  178. # This may be a stupid server that doesn't like HEAD, our UA, or so
  179. pass
  180. try:
  181. webpage = self._download_webpage(url, video_id)
  182. except ValueError:
  183. # since this is the last-resort InfoExtractor, if
  184. # this error is thrown, it'll be thrown here
  185. raise ExtractorError('Failed to download URL: %s' % url)
  186. self.report_extraction(video_id)
  187. # it's tempting to parse this further, but you would
  188. # have to take into account all the variations like
  189. # Video Title - Site Name
  190. # Site Name | Video Title
  191. # Video Title - Tagline | Site Name
  192. # and so on and so forth; it's just not practical
  193. video_title = self._html_search_regex(
  194. r'(?s)<title>(.*?)</title>', webpage, 'video title',
  195. default='video')
  196. # video uploader is domain name
  197. video_uploader = self._search_regex(
  198. r'^(?:https?://)?([^/]*)/.*', url, 'video uploader')
  199. # Look for BrightCove:
  200. bc_url = BrightcoveIE._extract_brightcove_url(webpage)
  201. if bc_url is not None:
  202. self.to_screen('Brightcove video detected.')
  203. return self.url_result(bc_url, 'Brightcove')
  204. # Look for embedded (iframe) Vimeo player
  205. mobj = re.search(
  206. r'<iframe[^>]+?src="(https?://player.vimeo.com/video/.+?)"', webpage)
  207. if mobj:
  208. player_url = unescapeHTML(mobj.group(1))
  209. surl = smuggle_url(player_url, {'Referer': url})
  210. return self.url_result(surl, 'Vimeo')
  211. # Look for embedded (swf embed) Vimeo player
  212. mobj = re.search(
  213. r'<embed[^>]+?src="(https?://(?:www\.)?vimeo.com/moogaloop.swf.+?)"', webpage)
  214. if mobj:
  215. return self.url_result(mobj.group(1), 'Vimeo')
  216. # Look for embedded YouTube player
  217. matches = re.findall(r'''(?x)
  218. (?:<iframe[^>]+?src=|embedSWF\(\s*)
  219. (["\'])(?P<url>(?:https?:)?//(?:www\.)?youtube\.com/
  220. (?:embed|v)/.+?)
  221. \1''', webpage)
  222. if matches:
  223. urlrs = [self.url_result(unescapeHTML(tuppl[1]), 'Youtube')
  224. for tuppl in matches]
  225. return self.playlist_result(
  226. urlrs, playlist_id=video_id, playlist_title=video_title)
  227. # Look for embedded Dailymotion player
  228. matches = re.findall(
  229. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/embed/video/.+?)\1', webpage)
  230. if matches:
  231. urlrs = [self.url_result(unescapeHTML(tuppl[1]), 'Dailymotion')
  232. for tuppl in matches]
  233. return self.playlist_result(
  234. urlrs, playlist_id=video_id, playlist_title=video_title)
  235. # Look for embedded Wistia player
  236. match = re.search(
  237. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:fast\.)?wistia\.net/embed/iframe/.+?)\1', webpage)
  238. if match:
  239. return {
  240. '_type': 'url_transparent',
  241. 'url': unescapeHTML(match.group('url')),
  242. 'ie_key': 'Wistia',
  243. 'uploader': video_uploader,
  244. 'title': video_title,
  245. 'id': video_id,
  246. }
  247. # Look for embedded blip.tv player
  248. mobj = re.search(r'<meta\s[^>]*https?://api\.blip\.tv/\w+/redirect/\w+/(\d+)', webpage)
  249. if mobj:
  250. return self.url_result('http://blip.tv/a/a-'+mobj.group(1), 'BlipTV')
  251. mobj = re.search(r'<(?:iframe|embed|object)\s[^>]*(https?://(?:\w+\.)?blip\.tv/(?:play/|api\.swf#)[a-zA-Z0-9]+)', webpage)
  252. if mobj:
  253. return self.url_result(mobj.group(1), 'BlipTV')
  254. # Look for Bandcamp pages with custom domain
  255. mobj = re.search(r'<meta property="og:url"[^>]*?content="(.*?bandcamp\.com.*?)"', webpage)
  256. if mobj is not None:
  257. burl = unescapeHTML(mobj.group(1))
  258. # Don't set the extractor because it can be a track url or an album
  259. return self.url_result(burl)
  260. # Look for embedded Vevo player
  261. mobj = re.search(
  262. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:cache\.)?vevo\.com/.+?)\1', webpage)
  263. if mobj is not None:
  264. return self.url_result(mobj.group('url'))
  265. # Look for Ooyala videos
  266. mobj = re.search(r'player.ooyala.com/[^"?]+\?[^"]*?(?:embedCode|ec)=([^"&]+)', webpage)
  267. if mobj is not None:
  268. return OoyalaIE._build_url_result(mobj.group(1))
  269. # Look for Aparat videos
  270. mobj = re.search(r'<iframe src="(http://www.aparat.com/video/[^"]+)"', webpage)
  271. if mobj is not None:
  272. return self.url_result(mobj.group(1), 'Aparat')
  273. # Start with something easy: JW Player in SWFObject
  274. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  275. if mobj is None:
  276. # Look for gorilla-vid style embedding
  277. mobj = re.search(r'(?s)jw_plugins.*?file:\s*["\'](.*?)["\']', webpage)
  278. if mobj is None:
  279. # Broaden the search a little bit
  280. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  281. if mobj is None:
  282. # Broaden the search a little bit: JWPlayer JS loader
  283. mobj = re.search(r'[^A-Za-z0-9]?file["\']?:\s*["\'](http[^\'"]*)', webpage)
  284. if mobj is None:
  285. # Try to find twitter cards info
  286. mobj = re.search(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
  287. if mobj is None:
  288. # We look for Open Graph info:
  289. # We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
  290. m_video_type = re.search(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
  291. # We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
  292. if m_video_type is not None:
  293. mobj = re.search(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)
  294. if mobj is None:
  295. # HTML5 video
  296. mobj = re.search(r'<video[^<]*(?:>.*?<source.*?)? src="([^"]+)"', webpage, flags=re.DOTALL)
  297. if mobj is None:
  298. raise ExtractorError('Unsupported URL: %s' % url)
  299. # It's possible that one of the regexes
  300. # matched, but returned an empty group:
  301. if mobj.group(1) is None:
  302. raise ExtractorError('Did not find a valid video URL at %s' % url)
  303. video_url = mobj.group(1)
  304. video_url = compat_urlparse.urljoin(url, video_url)
  305. video_id = compat_urllib_parse.unquote(os.path.basename(video_url))
  306. # Sometimes, jwplayer extraction will result in a YouTube URL
  307. if YoutubeIE.suitable(video_url):
  308. return self.url_result(video_url, 'Youtube')
  309. # here's a fun little line of code for you:
  310. video_id = os.path.splitext(video_id)[0]
  311. return {
  312. 'id': video_id,
  313. 'url': video_url,
  314. 'uploader': video_uploader,
  315. 'title': video_title,
  316. }