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.

253 lines
10 KiB

  1. # encoding: utf-8
  2. import os
  3. import re
  4. from .common import InfoExtractor
  5. from ..utils import (
  6. compat_urllib_error,
  7. compat_urllib_parse,
  8. compat_urllib_request,
  9. compat_urlparse,
  10. ExtractorError,
  11. smuggle_url,
  12. unescapeHTML,
  13. )
  14. from .brightcove import BrightcoveIE
  15. class GenericIE(InfoExtractor):
  16. IE_DESC = u'Generic downloader that works on some sites'
  17. _VALID_URL = r'.*'
  18. IE_NAME = u'generic'
  19. _TESTS = [
  20. {
  21. u'url': u'http://www.hodiho.fr/2013/02/regis-plante-sa-jeep.html',
  22. u'file': u'13601338388002.mp4',
  23. u'md5': u'6e15c93721d7ec9e9ca3fdbf07982cfd',
  24. u'info_dict': {
  25. u"uploader": u"www.hodiho.fr",
  26. u"title": u"R\u00e9gis plante sa Jeep"
  27. }
  28. },
  29. # embedded vimeo video
  30. {
  31. u'add_ie': ['Vimeo'],
  32. u'url': u'http://skillsmatter.com/podcast/home/move-semanticsperfect-forwarding-and-rvalue-references',
  33. u'file': u'22444065.mp4',
  34. u'md5': u'2903896e23df39722c33f015af0666e2',
  35. u'info_dict': {
  36. u'title': u'ACCU 2011: Move Semantics,Perfect Forwarding, and Rvalue references- Scott Meyers- 13/04/2011',
  37. u"uploader_id": u"skillsmatter",
  38. u"uploader": u"Skills Matter",
  39. }
  40. },
  41. # bandcamp page with custom domain
  42. {
  43. u'add_ie': ['Bandcamp'],
  44. u'url': u'http://bronyrock.com/track/the-pony-mash',
  45. u'file': u'3235767654.mp3',
  46. u'info_dict': {
  47. u'title': u'The Pony Mash',
  48. u'uploader': u'M_Pallante',
  49. },
  50. u'skip': u'There is a limit of 200 free downloads / month for the test song',
  51. },
  52. # embedded brightcove video
  53. # it also tests brightcove videos that need to set the 'Referer' in the
  54. # http requests
  55. {
  56. u'add_ie': ['Brightcove'],
  57. u'url': u'http://www.bfmtv.com/video/bfmbusiness/cours-bourse/cours-bourse-l-analyse-technique-154522/',
  58. u'info_dict': {
  59. u'id': u'2765128793001',
  60. u'ext': u'mp4',
  61. u'title': u'Le cours de bourse : l’analyse technique',
  62. u'description': u'md5:7e9ad046e968cb2d1114004aba466fd9',
  63. u'uploader': u'BFM BUSINESS',
  64. },
  65. u'params': {
  66. u'skip_download': True,
  67. },
  68. },
  69. ]
  70. def report_download_webpage(self, video_id):
  71. """Report webpage download."""
  72. if not self._downloader.params.get('test', False):
  73. self._downloader.report_warning(u'Falling back on generic information extractor.')
  74. super(GenericIE, self).report_download_webpage(video_id)
  75. def report_following_redirect(self, new_url):
  76. """Report information extraction."""
  77. self._downloader.to_screen(u'[redirect] Following redirect to %s' % new_url)
  78. def _test_redirect(self, url):
  79. """Check if it is a redirect, like url shorteners, in case return the new url."""
  80. class HeadRequest(compat_urllib_request.Request):
  81. def get_method(self):
  82. return "HEAD"
  83. class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  84. """
  85. Subclass the HTTPRedirectHandler to make it use our
  86. HeadRequest also on the redirected URL
  87. """
  88. def redirect_request(self, req, fp, code, msg, headers, newurl):
  89. if code in (301, 302, 303, 307):
  90. newurl = newurl.replace(' ', '%20')
  91. newheaders = dict((k,v) for k,v in req.headers.items()
  92. if k.lower() not in ("content-length", "content-type"))
  93. return HeadRequest(newurl,
  94. headers=newheaders,
  95. origin_req_host=req.get_origin_req_host(),
  96. unverifiable=True)
  97. else:
  98. raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
  99. class HTTPMethodFallback(compat_urllib_request.BaseHandler):
  100. """
  101. Fallback to GET if HEAD is not allowed (405 HTTP error)
  102. """
  103. def http_error_405(self, req, fp, code, msg, headers):
  104. fp.read()
  105. fp.close()
  106. newheaders = dict((k,v) for k,v in req.headers.items()
  107. if k.lower() not in ("content-length", "content-type"))
  108. return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
  109. headers=newheaders,
  110. origin_req_host=req.get_origin_req_host(),
  111. unverifiable=True))
  112. # Build our opener
  113. opener = compat_urllib_request.OpenerDirector()
  114. for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
  115. HTTPMethodFallback, HEADRedirectHandler,
  116. compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
  117. opener.add_handler(handler())
  118. response = opener.open(HeadRequest(url))
  119. if response is None:
  120. raise ExtractorError(u'Invalid URL protocol')
  121. new_url = response.geturl()
  122. if url == new_url:
  123. return False
  124. self.report_following_redirect(new_url)
  125. return new_url
  126. def _real_extract(self, url):
  127. parsed_url = compat_urlparse.urlparse(url)
  128. if not parsed_url.scheme:
  129. self._downloader.report_warning('The url doesn\'t specify the protocol, trying with http')
  130. return self.url_result('http://' + url)
  131. try:
  132. new_url = self._test_redirect(url)
  133. if new_url:
  134. return [self.url_result(new_url)]
  135. except compat_urllib_error.HTTPError:
  136. # This may be a stupid server that doesn't like HEAD, our UA, or so
  137. pass
  138. video_id = url.split('/')[-1]
  139. try:
  140. webpage = self._download_webpage(url, video_id)
  141. except ValueError:
  142. # since this is the last-resort InfoExtractor, if
  143. # this error is thrown, it'll be thrown here
  144. raise ExtractorError(u'Failed to download URL: %s' % url)
  145. self.report_extraction(video_id)
  146. # it's tempting to parse this further, but you would
  147. # have to take into account all the variations like
  148. # Video Title - Site Name
  149. # Site Name | Video Title
  150. # Video Title - Tagline | Site Name
  151. # and so on and so forth; it's just not practical
  152. video_title = self._html_search_regex(r'<title>(.*)</title>',
  153. webpage, u'video title', default=u'video', flags=re.DOTALL)
  154. # Look for BrightCove:
  155. bc_url = BrightcoveIE._extract_brightcove_url(webpage)
  156. if bc_url is not None:
  157. self.to_screen(u'Brightcove video detected.')
  158. return self.url_result(bc_url, 'Brightcove')
  159. # Look for embedded Vimeo player
  160. mobj = re.search(
  161. r'<iframe[^>]+?src="(https?://player.vimeo.com/video/.+?)"', webpage)
  162. if mobj:
  163. player_url = unescapeHTML(mobj.group(1))
  164. surl = smuggle_url(player_url, {'Referer': url})
  165. return self.url_result(surl, 'Vimeo')
  166. # Look for embedded YouTube player
  167. matches = re.findall(
  168. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?youtube.com/embed/.+?)\1', webpage)
  169. if matches:
  170. urlrs = [self.url_result(unescapeHTML(tuppl[1]), 'Youtube')
  171. for tuppl in matches]
  172. return self.playlist_result(
  173. urlrs, playlist_id=video_id, playlist_title=video_title)
  174. # Look for Bandcamp pages with custom domain
  175. mobj = re.search(r'<meta property="og:url"[^>]*?content="(.*?bandcamp\.com.*?)"', webpage)
  176. if mobj is not None:
  177. burl = unescapeHTML(mobj.group(1))
  178. # Don't set the extractor because it can be a track url or an album
  179. return self.url_result(burl)
  180. # Start with something easy: JW Player in SWFObject
  181. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  182. if mobj is None:
  183. # Broaden the search a little bit
  184. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  185. if mobj is None:
  186. # Broaden the search a little bit: JWPlayer JS loader
  187. mobj = re.search(r'[^A-Za-z0-9]?file["\']?:\s*["\'](http[^\'"&]*)', webpage)
  188. if mobj is None:
  189. # Try to find twitter cards info
  190. mobj = re.search(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
  191. if mobj is None:
  192. # We look for Open Graph info:
  193. # We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
  194. m_video_type = re.search(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
  195. # We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
  196. if m_video_type is not None:
  197. mobj = re.search(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)
  198. if mobj is None:
  199. # HTML5 video
  200. mobj = re.search(r'<video[^<]*(?:>.*?<source.*?)? src="([^"]+)"', webpage, flags=re.DOTALL)
  201. if mobj is None:
  202. raise ExtractorError(u'Unsupported URL: %s' % url)
  203. # It's possible that one of the regexes
  204. # matched, but returned an empty group:
  205. if mobj.group(1) is None:
  206. raise ExtractorError(u'Did not find a valid video URL at %s' % url)
  207. video_url = mobj.group(1)
  208. video_url = compat_urlparse.urljoin(url, video_url)
  209. video_id = compat_urllib_parse.unquote(os.path.basename(video_url))
  210. # here's a fun little line of code for you:
  211. video_extension = os.path.splitext(video_id)[1][1:]
  212. video_id = os.path.splitext(video_id)[0]
  213. # video uploader is domain name
  214. video_uploader = self._search_regex(r'(?:https?://)?([^/]*)/.*',
  215. url, u'video uploader')
  216. return [{
  217. 'id': video_id,
  218. 'url': video_url,
  219. 'uploader': video_uploader,
  220. 'upload_date': None,
  221. 'title': video_title,
  222. 'ext': video_extension,
  223. }]