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.

215 lines
9.0 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. smuggle_url,
  12. unescapeHTML,
  13. )
  14. from .brightcove import BrightcoveIE
  15. class GenericIE(InfoExtractor):
  16. IE_DESC = u'Generic downloader that works on some sites'
  17. _VALID_URL = r'.*'
  18. IE_NAME = u'generic'
  19. _TESTS = [
  20. {
  21. u'url': u'http://www.hodiho.fr/2013/02/regis-plante-sa-jeep.html',
  22. u'file': u'13601338388002.mp4',
  23. u'md5': u'85b90ccc9d73b4acd9138d3af4c27f89',
  24. u'info_dict': {
  25. u"uploader": u"www.hodiho.fr",
  26. u"title": u"R\u00e9gis plante sa Jeep"
  27. }
  28. },
  29. # embedded vimeo video
  30. {
  31. u'url': u'http://skillsmatter.com/podcast/home/move-semanticsperfect-forwarding-and-rvalue-references',
  32. u'file': u'22444065.mp4',
  33. u'md5': u'2903896e23df39722c33f015af0666e2',
  34. u'info_dict': {
  35. u'title': u'ACCU 2011: Move Semantics,Perfect Forwarding, and Rvalue references- Scott Meyers- 13/04/2011',
  36. u"uploader_id": u"skillsmatter",
  37. u"uploader": u"Skills Matter",
  38. }
  39. }
  40. ]
  41. def report_download_webpage(self, video_id):
  42. """Report webpage download."""
  43. if not self._downloader.params.get('test', False):
  44. self._downloader.report_warning(u'Falling back on generic information extractor.')
  45. super(GenericIE, self).report_download_webpage(video_id)
  46. def report_following_redirect(self, new_url):
  47. """Report information extraction."""
  48. self._downloader.to_screen(u'[redirect] Following redirect to %s' % new_url)
  49. def _test_redirect(self, url):
  50. """Check if it is a redirect, like url shorteners, in case return the new url."""
  51. class HeadRequest(compat_urllib_request.Request):
  52. def get_method(self):
  53. return "HEAD"
  54. class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  55. """
  56. Subclass the HTTPRedirectHandler to make it use our
  57. HeadRequest also on the redirected URL
  58. """
  59. def redirect_request(self, req, fp, code, msg, headers, newurl):
  60. if code in (301, 302, 303, 307):
  61. newurl = newurl.replace(' ', '%20')
  62. newheaders = dict((k,v) for k,v in req.headers.items()
  63. if k.lower() not in ("content-length", "content-type"))
  64. return HeadRequest(newurl,
  65. headers=newheaders,
  66. origin_req_host=req.get_origin_req_host(),
  67. unverifiable=True)
  68. else:
  69. raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
  70. class HTTPMethodFallback(compat_urllib_request.BaseHandler):
  71. """
  72. Fallback to GET if HEAD is not allowed (405 HTTP error)
  73. """
  74. def http_error_405(self, req, fp, code, msg, headers):
  75. fp.read()
  76. fp.close()
  77. newheaders = dict((k,v) for k,v in req.headers.items()
  78. if k.lower() not in ("content-length", "content-type"))
  79. return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
  80. headers=newheaders,
  81. origin_req_host=req.get_origin_req_host(),
  82. unverifiable=True))
  83. # Build our opener
  84. opener = compat_urllib_request.OpenerDirector()
  85. for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
  86. HTTPMethodFallback, HEADRedirectHandler,
  87. compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
  88. opener.add_handler(handler())
  89. response = opener.open(HeadRequest(url))
  90. if response is None:
  91. raise ExtractorError(u'Invalid URL protocol')
  92. new_url = response.geturl()
  93. if url == new_url:
  94. return False
  95. self.report_following_redirect(new_url)
  96. return new_url
  97. def _real_extract(self, url):
  98. parsed_url = compat_urlparse.urlparse(url)
  99. if not parsed_url.scheme:
  100. self._downloader.report_warning('The url doesn\'t specify the protocol, trying with http')
  101. return self.url_result('http://' + url)
  102. try:
  103. new_url = self._test_redirect(url)
  104. if new_url:
  105. return [self.url_result(new_url)]
  106. except compat_urllib_error.HTTPError:
  107. # This may be a stupid server that doesn't like HEAD, our UA, or so
  108. pass
  109. video_id = url.split('/')[-1]
  110. try:
  111. webpage = self._download_webpage(url, video_id)
  112. except ValueError:
  113. # since this is the last-resort InfoExtractor, if
  114. # this error is thrown, it'll be thrown here
  115. raise ExtractorError(u'Failed to download URL: %s' % url)
  116. self.report_extraction(video_id)
  117. # Look for BrightCove:
  118. m_brightcove = re.search(r'<object[^>]+?class=([\'"])[^>]*?BrightcoveExperience.*?\1.+?</object>', webpage, re.DOTALL)
  119. if m_brightcove is not None:
  120. self.to_screen(u'Brightcove video detected.')
  121. bc_url = BrightcoveIE._build_brighcove_url(m_brightcove.group())
  122. return self.url_result(bc_url, 'Brightcove')
  123. # Look for embedded Vimeo player
  124. mobj = re.search(
  125. r'<iframe[^>]+?src="(https?://player.vimeo.com/video/.+?)"', webpage)
  126. if mobj:
  127. player_url = unescapeHTML(mobj.group(1))
  128. surl = smuggle_url(player_url, {'Referer': url})
  129. return self.url_result(surl, 'Vimeo')
  130. # Look for embedded YouTube player
  131. mobj = re.search(
  132. r'<iframe[^>]+?src="(https?://(?:www\.)?youtube.com/embed/.+?)"', webpage)
  133. if mobj:
  134. surl = unescapeHTML(mobj.group(1))
  135. return self.url_result(surl, 'Youtube')
  136. # Start with something easy: JW Player in SWFObject
  137. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  138. if mobj is None:
  139. # Broaden the search a little bit
  140. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  141. if mobj is None:
  142. # Broaden the search a little bit: JWPlayer JS loader
  143. mobj = re.search(r'[^A-Za-z0-9]?file["\']?:\s*["\'](http[^\'"&]*)', webpage)
  144. if mobj is None:
  145. # Try to find twitter cards info
  146. mobj = re.search(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
  147. if mobj is None:
  148. # We look for Open Graph info:
  149. # We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
  150. m_video_type = re.search(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
  151. # We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
  152. if m_video_type is not None:
  153. mobj = re.search(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)
  154. if mobj is None:
  155. # HTML5 video
  156. mobj = re.search(r'<video[^<]*(?:>.*?<source.*?)? src="([^"]+)"', webpage, flags=re.DOTALL)
  157. if mobj is None:
  158. raise ExtractorError(u'Unsupported URL: %s' % url)
  159. # It's possible that one of the regexes
  160. # matched, but returned an empty group:
  161. if mobj.group(1) is None:
  162. raise ExtractorError(u'Did not find a valid video URL at %s' % url)
  163. video_url = mobj.group(1)
  164. video_url = compat_urlparse.urljoin(url, video_url)
  165. video_id = compat_urllib_parse.unquote(os.path.basename(video_url))
  166. # here's a fun little line of code for you:
  167. video_extension = os.path.splitext(video_id)[1][1:]
  168. video_id = os.path.splitext(video_id)[0]
  169. # it's tempting to parse this further, but you would
  170. # have to take into account all the variations like
  171. # Video Title - Site Name
  172. # Site Name | Video Title
  173. # Video Title - Tagline | Site Name
  174. # and so on and so forth; it's just not practical
  175. video_title = self._html_search_regex(r'<title>(.*)</title>',
  176. webpage, u'video title', default=u'video', flags=re.DOTALL)
  177. # video uploader is domain name
  178. video_uploader = self._search_regex(r'(?:https?://)?([^/]*)/.*',
  179. url, u'video uploader')
  180. return [{
  181. 'id': video_id,
  182. 'url': video_url,
  183. 'uploader': video_uploader,
  184. 'upload_date': None,
  185. 'title': video_title,
  186. 'ext': video_extension,
  187. }]