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.

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