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.

198 lines
8.4 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. 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. parsed_url = compat_urlparse.urlparse(url)
  97. if not parsed_url.scheme:
  98. self._downloader.report_warning('The url doesn\'t specify the protocol, trying with http')
  99. return self.url_result('http://' + url)
  100. try:
  101. new_url = self._test_redirect(url)
  102. if new_url:
  103. return [self.url_result(new_url)]
  104. except compat_urllib_error.HTTPError:
  105. # This may be a stupid server that doesn't like HEAD, our UA, or so
  106. pass
  107. video_id = url.split('/')[-1]
  108. try:
  109. webpage = self._download_webpage(url, video_id)
  110. except ValueError:
  111. # since this is the last-resort InfoExtractor, if
  112. # this error is thrown, it'll be thrown here
  113. raise ExtractorError(u'Invalid URL: %s' % url)
  114. self.report_extraction(video_id)
  115. # Look for BrightCove:
  116. m_brightcove = re.search(r'<object.+?class=([\'"]).*?BrightcoveExperience.*?\1.+?</object>', webpage, re.DOTALL)
  117. if m_brightcove is not None:
  118. self.to_screen(u'Brightcove video detected.')
  119. bc_url = BrightcoveIE._build_brighcove_url(m_brightcove.group())
  120. return self.url_result(bc_url, 'Brightcove')
  121. # Start with something easy: JW Player in SWFObject
  122. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  123. if mobj is None:
  124. # Broaden the search a little bit
  125. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  126. if mobj is None:
  127. # Broaden the search a little bit: JWPlayer JS loader
  128. mobj = re.search(r'[^A-Za-z0-9]?file["\']?:\s*["\'](http[^\'"&]*)', webpage)
  129. if mobj is None:
  130. # Try to find twitter cards info
  131. mobj = re.search(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
  132. if mobj is None:
  133. # We look for Open Graph info:
  134. # We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
  135. m_video_type = re.search(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
  136. # We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
  137. if m_video_type is not None:
  138. mobj = re.search(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)
  139. if mobj is None:
  140. # HTML5 video
  141. mobj = re.search(r'<video[^<]*(?:>.*?<source.*?)? src="([^"]+)"', webpage, flags=re.DOTALL)
  142. if mobj is None:
  143. raise ExtractorError(u'Invalid URL: %s' % url)
  144. # It's possible that one of the regexes
  145. # matched, but returned an empty group:
  146. if mobj.group(1) is None:
  147. raise ExtractorError(u'Invalid URL: %s' % url)
  148. video_url = mobj.group(1)
  149. video_url = compat_urlparse.urljoin(url, video_url)
  150. video_id = compat_urllib_parse.unquote(os.path.basename(video_url))
  151. # here's a fun little line of code for you:
  152. video_extension = os.path.splitext(video_id)[1][1:]
  153. video_id = os.path.splitext(video_id)[0]
  154. # it's tempting to parse this further, but you would
  155. # have to take into account all the variations like
  156. # Video Title - Site Name
  157. # Site Name | Video Title
  158. # Video Title - Tagline | Site Name
  159. # and so on and so forth; it's just not practical
  160. video_title = self._html_search_regex(r'<title>(.*)</title>',
  161. webpage, u'video title', default=u'video', flags=re.DOTALL)
  162. # video uploader is domain name
  163. video_uploader = self._search_regex(r'(?:https?://)?([^/]*)/.*',
  164. url, u'video uploader')
  165. return [{
  166. 'id': video_id,
  167. 'url': video_url,
  168. 'uploader': video_uploader,
  169. 'upload_date': None,
  170. 'title': video_title,
  171. 'ext': video_extension,
  172. }]