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.

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