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.

273 lines
11 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'add_ie': ['Vimeo'],
  32. u'url': u'http://skillsmatter.com/podcast/home/move-semanticsperfect-forwarding-and-rvalue-references',
  33. u'file': u'22444065.mp4',
  34. u'md5': u'2903896e23df39722c33f015af0666e2',
  35. u'info_dict': {
  36. u'title': u'ACCU 2011: Move Semantics,Perfect Forwarding, and Rvalue references- Scott Meyers- 13/04/2011',
  37. u"uploader_id": u"skillsmatter",
  38. u"uploader": u"Skills Matter",
  39. }
  40. },
  41. # bandcamp page with custom domain
  42. {
  43. u'add_ie': ['Bandcamp'],
  44. u'url': u'http://bronyrock.com/track/the-pony-mash',
  45. u'file': u'3235767654.mp3',
  46. u'info_dict': {
  47. u'title': u'The Pony Mash',
  48. u'uploader': u'M_Pallante',
  49. },
  50. u'skip': u'There is a limit of 200 free downloads / month for the test song',
  51. },
  52. # embedded brightcove video
  53. # it also tests brightcove videos that need to set the 'Referer' in the
  54. # http requests
  55. {
  56. u'add_ie': ['Brightcove'],
  57. u'url': u'http://www.bfmtv.com/video/bfmbusiness/cours-bourse/cours-bourse-l-analyse-technique-154522/',
  58. u'info_dict': {
  59. u'id': u'2765128793001',
  60. u'ext': u'mp4',
  61. u'title': u'Le cours de bourse : l’analyse technique',
  62. u'description': u'md5:7e9ad046e968cb2d1114004aba466fd9',
  63. u'uploader': u'BFM BUSINESS',
  64. },
  65. u'params': {
  66. u'skip_download': True,
  67. },
  68. },
  69. ]
  70. def report_download_webpage(self, video_id):
  71. """Report webpage download."""
  72. if not self._downloader.params.get('test', False):
  73. self._downloader.report_warning(u'Falling back on generic information extractor.')
  74. super(GenericIE, self).report_download_webpage(video_id)
  75. def report_following_redirect(self, new_url):
  76. """Report information extraction."""
  77. self._downloader.to_screen(u'[redirect] Following redirect to %s' % new_url)
  78. def _test_redirect(self, url):
  79. """Check if it is a redirect, like url shorteners, in case return the new url."""
  80. class HeadRequest(compat_urllib_request.Request):
  81. def get_method(self):
  82. return "HEAD"
  83. class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  84. """
  85. Subclass the HTTPRedirectHandler to make it use our
  86. HeadRequest also on the redirected URL
  87. """
  88. def redirect_request(self, req, fp, code, msg, headers, newurl):
  89. if code in (301, 302, 303, 307):
  90. newurl = newurl.replace(' ', '%20')
  91. newheaders = dict((k,v) for k,v in req.headers.items()
  92. if k.lower() not in ("content-length", "content-type"))
  93. return HeadRequest(newurl,
  94. headers=newheaders,
  95. origin_req_host=req.get_origin_req_host(),
  96. unverifiable=True)
  97. else:
  98. raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
  99. class HTTPMethodFallback(compat_urllib_request.BaseHandler):
  100. """
  101. Fallback to GET if HEAD is not allowed (405 HTTP error)
  102. """
  103. def http_error_405(self, req, fp, code, msg, headers):
  104. fp.read()
  105. fp.close()
  106. newheaders = dict((k,v) for k,v in req.headers.items()
  107. if k.lower() not in ("content-length", "content-type"))
  108. return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
  109. headers=newheaders,
  110. origin_req_host=req.get_origin_req_host(),
  111. unverifiable=True))
  112. # Build our opener
  113. opener = compat_urllib_request.OpenerDirector()
  114. for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
  115. HTTPMethodFallback, HEADRedirectHandler,
  116. compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
  117. opener.add_handler(handler())
  118. response = opener.open(HeadRequest(url))
  119. if response is None:
  120. raise ExtractorError(u'Invalid URL protocol')
  121. new_url = response.geturl()
  122. if url == new_url:
  123. return False
  124. self.report_following_redirect(new_url)
  125. return new_url
  126. def _real_extract(self, url):
  127. parsed_url = compat_urlparse.urlparse(url)
  128. if not parsed_url.scheme:
  129. self._downloader.report_warning('The url doesn\'t specify the protocol, trying with http')
  130. return self.url_result('http://' + url)
  131. try:
  132. new_url = self._test_redirect(url)
  133. if new_url:
  134. return [self.url_result(new_url)]
  135. except compat_urllib_error.HTTPError:
  136. # This may be a stupid server that doesn't like HEAD, our UA, or so
  137. pass
  138. video_id = url.split('/')[-1]
  139. try:
  140. webpage = self._download_webpage(url, video_id)
  141. except ValueError:
  142. # since this is the last-resort InfoExtractor, if
  143. # this error is thrown, it'll be thrown here
  144. raise ExtractorError(u'Failed to download URL: %s' % url)
  145. self.report_extraction(video_id)
  146. # it's tempting to parse this further, but you would
  147. # have to take into account all the variations like
  148. # Video Title - Site Name
  149. # Site Name | Video Title
  150. # Video Title - Tagline | Site Name
  151. # and so on and so forth; it's just not practical
  152. video_title = self._html_search_regex(
  153. r'(?s)<title>(.*?)</title>', webpage, u'video title',
  154. default=u'video')
  155. # video uploader is domain name
  156. video_uploader = self._search_regex(
  157. r'^(?:https?://)?([^/]*)/.*', url, u'video uploader')
  158. # Look for BrightCove:
  159. bc_url = BrightcoveIE._extract_brightcove_url(webpage)
  160. if bc_url is not None:
  161. self.to_screen(u'Brightcove video detected.')
  162. return self.url_result(bc_url, 'Brightcove')
  163. # Look for embedded Vimeo player
  164. mobj = re.search(
  165. r'<iframe[^>]+?src="(https?://player.vimeo.com/video/.+?)"', webpage)
  166. if mobj:
  167. player_url = unescapeHTML(mobj.group(1))
  168. surl = smuggle_url(player_url, {'Referer': url})
  169. return self.url_result(surl, 'Vimeo')
  170. # Look for embedded YouTube player
  171. matches = re.findall(
  172. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?youtube\.com/embed/.+?)\1', webpage)
  173. if matches:
  174. urlrs = [self.url_result(unescapeHTML(tuppl[1]), 'Youtube')
  175. for tuppl in matches]
  176. return self.playlist_result(
  177. urlrs, playlist_id=video_id, playlist_title=video_title)
  178. # Look for embedded Dailymotion player
  179. matches = re.findall(
  180. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/embed/video/.+?)\1', webpage)
  181. if matches:
  182. urlrs = [self.url_result(unescapeHTML(tuppl[1]), 'Dailymotion')
  183. for tuppl in matches]
  184. return self.playlist_result(
  185. urlrs, playlist_id=video_id, playlist_title=video_title)
  186. # Look for embedded Wistia player
  187. match = re.search(
  188. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:fast\.)?wistia\.net/embed/iframe/.+?)\1', webpage)
  189. if match:
  190. return {
  191. '_type': 'url_transparent',
  192. 'url': unescapeHTML(match.group('url')),
  193. 'ie_key': 'Wistia',
  194. 'uploader': video_uploader,
  195. 'title': video_title,
  196. 'id': video_id,
  197. }
  198. # Look for Bandcamp pages with custom domain
  199. mobj = re.search(r'<meta property="og:url"[^>]*?content="(.*?bandcamp\.com.*?)"', webpage)
  200. if mobj is not None:
  201. burl = unescapeHTML(mobj.group(1))
  202. # Don't set the extractor because it can be a track url or an album
  203. return self.url_result(burl)
  204. # Start with something easy: JW Player in SWFObject
  205. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  206. if mobj is None:
  207. # Broaden the search a little bit
  208. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  209. if mobj is None:
  210. # Broaden the search a little bit: JWPlayer JS loader
  211. mobj = re.search(r'[^A-Za-z0-9]?file["\']?:\s*["\'](http[^\'"]*)', webpage)
  212. if mobj is None:
  213. # Try to find twitter cards info
  214. mobj = re.search(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
  215. if mobj is None:
  216. # We look for Open Graph info:
  217. # We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
  218. m_video_type = re.search(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
  219. # We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
  220. if m_video_type is not None:
  221. mobj = re.search(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)
  222. if mobj is None:
  223. # HTML5 video
  224. mobj = re.search(r'<video[^<]*(?:>.*?<source.*?)? src="([^"]+)"', webpage, flags=re.DOTALL)
  225. if mobj is None:
  226. raise ExtractorError(u'Unsupported URL: %s' % url)
  227. # It's possible that one of the regexes
  228. # matched, but returned an empty group:
  229. if mobj.group(1) is None:
  230. raise ExtractorError(u'Did not find a valid video URL at %s' % url)
  231. video_url = mobj.group(1)
  232. video_url = compat_urlparse.urljoin(url, video_url)
  233. video_id = compat_urllib_parse.unquote(os.path.basename(video_url))
  234. # here's a fun little line of code for you:
  235. video_id = os.path.splitext(video_id)[0]
  236. return {
  237. 'id': video_id,
  238. 'url': video_url,
  239. 'uploader': video_uploader,
  240. 'title': video_title,
  241. }