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.

187 lines
7.8 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. )
  12. from .brightcove import BrightcoveIE
  13. class GenericIE(InfoExtractor):
  14. IE_DESC = u'Generic downloader that works on some sites'
  15. _VALID_URL = r'.*'
  16. IE_NAME = u'generic'
  17. _TESTS = [
  18. {
  19. u'url': u'http://www.hodiho.fr/2013/02/regis-plante-sa-jeep.html',
  20. u'file': u'13601338388002.mp4',
  21. u'md5': u'85b90ccc9d73b4acd9138d3af4c27f89',
  22. u'info_dict': {
  23. u"uploader": u"www.hodiho.fr",
  24. u"title": u"R\u00e9gis plante sa Jeep"
  25. }
  26. },
  27. ]
  28. def report_download_webpage(self, video_id):
  29. """Report webpage download."""
  30. if not self._downloader.params.get('test', False):
  31. self._downloader.report_warning(u'Falling back on generic information extractor.')
  32. super(GenericIE, self).report_download_webpage(video_id)
  33. def report_following_redirect(self, new_url):
  34. """Report information extraction."""
  35. self._downloader.to_screen(u'[redirect] Following redirect to %s' % new_url)
  36. def _test_redirect(self, url):
  37. """Check if it is a redirect, like url shorteners, in case return the new url."""
  38. class HeadRequest(compat_urllib_request.Request):
  39. def get_method(self):
  40. return "HEAD"
  41. class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  42. """
  43. Subclass the HTTPRedirectHandler to make it use our
  44. HeadRequest also on the redirected URL
  45. """
  46. def redirect_request(self, req, fp, code, msg, headers, newurl):
  47. if code in (301, 302, 303, 307):
  48. newurl = newurl.replace(' ', '%20')
  49. newheaders = dict((k,v) for k,v in req.headers.items()
  50. if k.lower() not in ("content-length", "content-type"))
  51. return HeadRequest(newurl,
  52. headers=newheaders,
  53. origin_req_host=req.get_origin_req_host(),
  54. unverifiable=True)
  55. else:
  56. raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
  57. class HTTPMethodFallback(compat_urllib_request.BaseHandler):
  58. """
  59. Fallback to GET if HEAD is not allowed (405 HTTP error)
  60. """
  61. def http_error_405(self, req, fp, code, msg, headers):
  62. fp.read()
  63. fp.close()
  64. newheaders = dict((k,v) for k,v in req.headers.items()
  65. if k.lower() not in ("content-length", "content-type"))
  66. return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
  67. headers=newheaders,
  68. origin_req_host=req.get_origin_req_host(),
  69. unverifiable=True))
  70. # Build our opener
  71. opener = compat_urllib_request.OpenerDirector()
  72. for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
  73. HTTPMethodFallback, HEADRedirectHandler,
  74. compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
  75. opener.add_handler(handler())
  76. response = opener.open(HeadRequest(url))
  77. if response is None:
  78. raise ExtractorError(u'Invalid URL protocol')
  79. new_url = response.geturl()
  80. if url == new_url:
  81. return False
  82. self.report_following_redirect(new_url)
  83. return new_url
  84. def _real_extract(self, url):
  85. parsed_url = compat_urlparse.urlparse(url)
  86. if not parsed_url.scheme:
  87. self._downloader.report_warning('The url doesn\'t specify the protocol, trying with http')
  88. return self.url_result('http://' + url)
  89. try:
  90. new_url = self._test_redirect(url)
  91. if new_url:
  92. return [self.url_result(new_url)]
  93. except compat_urllib_error.HTTPError:
  94. # This may be a stupid server that doesn't like HEAD, our UA, or so
  95. pass
  96. video_id = url.split('/')[-1]
  97. try:
  98. webpage = self._download_webpage(url, video_id)
  99. except ValueError:
  100. # since this is the last-resort InfoExtractor, if
  101. # this error is thrown, it'll be thrown here
  102. raise ExtractorError(u'Failed to download URL: %s' % url)
  103. self.report_extraction(video_id)
  104. # Look for BrightCove:
  105. m_brightcove = re.search(r'<object.+?class=([\'"]).*?BrightcoveExperience.*?\1.+?</object>', webpage, re.DOTALL)
  106. if m_brightcove is not None:
  107. self.to_screen(u'Brightcove video detected.')
  108. bc_url = BrightcoveIE._build_brighcove_url(m_brightcove.group())
  109. return self.url_result(bc_url, 'Brightcove')
  110. # Start with something easy: JW Player in SWFObject
  111. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  112. if mobj is None:
  113. # Broaden the search a little bit
  114. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  115. if mobj is None:
  116. # Broaden the search a little bit: JWPlayer JS loader
  117. mobj = re.search(r'[^A-Za-z0-9]?file["\']?:\s*["\'](http[^\'"&]*)', webpage)
  118. if mobj is None:
  119. # Try to find twitter cards info
  120. mobj = re.search(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
  121. if mobj is None:
  122. # We look for Open Graph info:
  123. # We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
  124. m_video_type = re.search(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
  125. # We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
  126. if m_video_type is not None:
  127. mobj = re.search(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)
  128. if mobj is None:
  129. # HTML5 video
  130. mobj = re.search(r'<video[^<]*(?:>.*?<source.*?)? src="([^"]+)"', webpage, flags=re.DOTALL)
  131. if mobj is None:
  132. raise ExtractorError(u'Unsupported URL: %s' % url)
  133. # It's possible that one of the regexes
  134. # matched, but returned an empty group:
  135. if mobj.group(1) is None:
  136. raise ExtractorError(u'Did not find a valid video URL at %s' % url)
  137. video_url = mobj.group(1)
  138. video_url = compat_urlparse.urljoin(url, video_url)
  139. video_id = compat_urllib_parse.unquote(os.path.basename(video_url))
  140. # here's a fun little line of code for you:
  141. video_extension = os.path.splitext(video_id)[1][1:]
  142. video_id = os.path.splitext(video_id)[0]
  143. # it's tempting to parse this further, but you would
  144. # have to take into account all the variations like
  145. # Video Title - Site Name
  146. # Site Name | Video Title
  147. # Video Title - Tagline | Site Name
  148. # and so on and so forth; it's just not practical
  149. video_title = self._html_search_regex(r'<title>(.*)</title>',
  150. webpage, u'video title', default=u'video', flags=re.DOTALL)
  151. # video uploader is domain name
  152. video_uploader = self._search_regex(r'(?:https?://)?([^/]*)/.*',
  153. url, u'video uploader')
  154. return [{
  155. 'id': video_id,
  156. 'url': video_url,
  157. 'uploader': video_uploader,
  158. 'upload_date': None,
  159. 'title': video_title,
  160. 'ext': video_extension,
  161. }]