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.

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