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.

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