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.

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