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.

160 lines
6.7 KiB

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