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.

369 lines
15 KiB

  1. # encoding: utf-8
  2. from __future__ import unicode_literals
  3. import os
  4. import re
  5. from .common import InfoExtractor
  6. from .youtube import YoutubeIE
  7. from ..utils import (
  8. compat_urllib_error,
  9. compat_urllib_parse,
  10. compat_urllib_request,
  11. compat_urlparse,
  12. ExtractorError,
  13. HEADRequest,
  14. smuggle_url,
  15. unescapeHTML,
  16. unified_strdate,
  17. url_basename,
  18. )
  19. from .brightcove import BrightcoveIE
  20. from .ooyala import OoyalaIE
  21. class GenericIE(InfoExtractor):
  22. IE_DESC = 'Generic downloader that works on some sites'
  23. _VALID_URL = r'.*'
  24. IE_NAME = 'generic'
  25. _TESTS = [
  26. {
  27. 'url': 'http://www.hodiho.fr/2013/02/regis-plante-sa-jeep.html',
  28. 'file': '13601338388002.mp4',
  29. 'md5': '6e15c93721d7ec9e9ca3fdbf07982cfd',
  30. 'info_dict': {
  31. 'uploader': 'www.hodiho.fr',
  32. 'title': 'R\u00e9gis plante sa Jeep',
  33. }
  34. },
  35. # embedded vimeo video
  36. {
  37. 'add_ie': ['Vimeo'],
  38. 'url': 'http://skillsmatter.com/podcast/home/move-semanticsperfect-forwarding-and-rvalue-references',
  39. 'file': '22444065.mp4',
  40. 'md5': '2903896e23df39722c33f015af0666e2',
  41. 'info_dict': {
  42. 'title': 'ACCU 2011: Move Semantics,Perfect Forwarding, and Rvalue references- Scott Meyers- 13/04/2011',
  43. 'uploader_id': 'skillsmatter',
  44. 'uploader': 'Skills Matter',
  45. }
  46. },
  47. # bandcamp page with custom domain
  48. {
  49. 'add_ie': ['Bandcamp'],
  50. 'url': 'http://bronyrock.com/track/the-pony-mash',
  51. 'file': '3235767654.mp3',
  52. 'info_dict': {
  53. 'title': 'The Pony Mash',
  54. 'uploader': 'M_Pallante',
  55. },
  56. 'skip': 'There is a limit of 200 free downloads / month for the test song',
  57. },
  58. # embedded brightcove video
  59. # it also tests brightcove videos that need to set the 'Referer' in the
  60. # http requests
  61. {
  62. 'add_ie': ['Brightcove'],
  63. 'url': 'http://www.bfmtv.com/video/bfmbusiness/cours-bourse/cours-bourse-l-analyse-technique-154522/',
  64. 'info_dict': {
  65. 'id': '2765128793001',
  66. 'ext': 'mp4',
  67. 'title': 'Le cours de bourse : l’analyse technique',
  68. 'description': 'md5:7e9ad046e968cb2d1114004aba466fd9',
  69. 'uploader': 'BFM BUSINESS',
  70. },
  71. 'params': {
  72. 'skip_download': True,
  73. },
  74. },
  75. # Direct link to a video
  76. {
  77. 'url': 'http://media.w3.org/2010/05/sintel/trailer.mp4',
  78. 'file': 'trailer.mp4',
  79. 'md5': '67d406c2bcb6af27fa886f31aa934bbe',
  80. 'info_dict': {
  81. 'id': 'trailer',
  82. 'title': 'trailer',
  83. 'upload_date': '20100513',
  84. }
  85. },
  86. # ooyala video
  87. {
  88. 'url': 'http://www.rollingstone.com/music/videos/norwegian-dj-cashmere-cat-goes-spartan-on-with-me-premiere-20131219',
  89. 'md5': '5644c6ca5d5782c1d0d350dad9bd840c',
  90. 'info_dict': {
  91. 'id': 'BwY2RxaTrTkslxOfcan0UCf0YqyvWysJ',
  92. 'ext': 'mp4',
  93. 'title': '2cc213299525360.mov', #that's what we get
  94. },
  95. },
  96. ]
  97. def report_download_webpage(self, video_id):
  98. """Report webpage download."""
  99. if not self._downloader.params.get('test', False):
  100. self._downloader.report_warning('Falling back on generic information extractor.')
  101. super(GenericIE, self).report_download_webpage(video_id)
  102. def report_following_redirect(self, new_url):
  103. """Report information extraction."""
  104. self._downloader.to_screen('[redirect] Following redirect to %s' % new_url)
  105. def _send_head(self, url):
  106. """Check if it is a redirect, like url shorteners, in case return the new url."""
  107. class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  108. """
  109. Subclass the HTTPRedirectHandler to make it use our
  110. HEADRequest also on the redirected URL
  111. """
  112. def redirect_request(self, req, fp, code, msg, headers, newurl):
  113. if code in (301, 302, 303, 307):
  114. newurl = newurl.replace(' ', '%20')
  115. newheaders = dict((k,v) for k,v in req.headers.items()
  116. if k.lower() not in ("content-length", "content-type"))
  117. return HEADRequest(newurl,
  118. headers=newheaders,
  119. origin_req_host=req.get_origin_req_host(),
  120. unverifiable=True)
  121. else:
  122. raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
  123. class HTTPMethodFallback(compat_urllib_request.BaseHandler):
  124. """
  125. Fallback to GET if HEAD is not allowed (405 HTTP error)
  126. """
  127. def http_error_405(self, req, fp, code, msg, headers):
  128. fp.read()
  129. fp.close()
  130. newheaders = dict((k,v) for k,v in req.headers.items()
  131. if k.lower() not in ("content-length", "content-type"))
  132. return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
  133. headers=newheaders,
  134. origin_req_host=req.get_origin_req_host(),
  135. unverifiable=True))
  136. # Build our opener
  137. opener = compat_urllib_request.OpenerDirector()
  138. for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
  139. HTTPMethodFallback, HEADRedirectHandler,
  140. compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
  141. opener.add_handler(handler())
  142. response = opener.open(HEADRequest(url))
  143. if response is None:
  144. raise ExtractorError('Invalid URL protocol')
  145. return response
  146. def _real_extract(self, url):
  147. parsed_url = compat_urlparse.urlparse(url)
  148. if not parsed_url.scheme:
  149. self._downloader.report_warning('The url doesn\'t specify the protocol, trying with http')
  150. return self.url_result('http://' + url)
  151. video_id = os.path.splitext(url.split('/')[-1])[0]
  152. self.to_screen('%s: Requesting header' % video_id)
  153. try:
  154. response = self._send_head(url)
  155. # Check for redirect
  156. new_url = response.geturl()
  157. if url != new_url:
  158. self.report_following_redirect(new_url)
  159. return self.url_result(new_url)
  160. # Check for direct link to a video
  161. content_type = response.headers.get('Content-Type', '')
  162. m = re.match(r'^(?P<type>audio|video|application(?=/ogg$))/(?P<format_id>.+)$', content_type)
  163. if m:
  164. upload_date = response.headers.get('Last-Modified')
  165. if upload_date:
  166. upload_date = unified_strdate(upload_date)
  167. return {
  168. 'id': video_id,
  169. 'title': os.path.splitext(url_basename(url))[0],
  170. 'formats': [{
  171. 'format_id': m.group('format_id'),
  172. 'url': url,
  173. 'vcodec': 'none' if m.group('type') == 'audio' else None
  174. }],
  175. 'upload_date': upload_date,
  176. }
  177. except compat_urllib_error.HTTPError:
  178. # This may be a stupid server that doesn't like HEAD, our UA, or so
  179. pass
  180. try:
  181. webpage = self._download_webpage(url, video_id)
  182. except ValueError:
  183. # since this is the last-resort InfoExtractor, if
  184. # this error is thrown, it'll be thrown here
  185. raise ExtractorError('Failed to download URL: %s' % url)
  186. self.report_extraction(video_id)
  187. # it's tempting to parse this further, but you would
  188. # have to take into account all the variations like
  189. # Video Title - Site Name
  190. # Site Name | Video Title
  191. # Video Title - Tagline | Site Name
  192. # and so on and so forth; it's just not practical
  193. video_title = self._html_search_regex(
  194. r'(?s)<title>(.*?)</title>', webpage, 'video title',
  195. default='video')
  196. # video uploader is domain name
  197. video_uploader = self._search_regex(
  198. r'^(?:https?://)?([^/]*)/.*', url, 'video uploader')
  199. # Look for BrightCove:
  200. bc_url = BrightcoveIE._extract_brightcove_url(webpage)
  201. if bc_url is not None:
  202. self.to_screen('Brightcove video detected.')
  203. surl = smuggle_url(bc_url, {'Referer': url})
  204. return self.url_result(surl, 'Brightcove')
  205. # Look for embedded (iframe) Vimeo player
  206. mobj = re.search(
  207. r'<iframe[^>]+?src="((?:https?:)?//player.vimeo.com/video/.+?)"', webpage)
  208. if mobj:
  209. player_url = unescapeHTML(mobj.group(1))
  210. surl = smuggle_url(player_url, {'Referer': url})
  211. return self.url_result(surl, 'Vimeo')
  212. # Look for embedded (swf embed) Vimeo player
  213. mobj = re.search(
  214. r'<embed[^>]+?src="(https?://(?:www\.)?vimeo.com/moogaloop.swf.+?)"', webpage)
  215. if mobj:
  216. return self.url_result(mobj.group(1), 'Vimeo')
  217. # Look for embedded YouTube player
  218. matches = re.findall(r'''(?x)
  219. (?:<iframe[^>]+?src=|embedSWF\(\s*)
  220. (["\'])(?P<url>(?:https?:)?//(?:www\.)?youtube\.com/
  221. (?:embed|v)/.+?)
  222. \1''', webpage)
  223. if matches:
  224. urlrs = [self.url_result(unescapeHTML(tuppl[1]), 'Youtube')
  225. for tuppl in matches]
  226. return self.playlist_result(
  227. urlrs, playlist_id=video_id, playlist_title=video_title)
  228. # Look for embedded Dailymotion player
  229. matches = re.findall(
  230. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/embed/video/.+?)\1', webpage)
  231. if matches:
  232. urlrs = [self.url_result(unescapeHTML(tuppl[1]), 'Dailymotion')
  233. for tuppl in matches]
  234. return self.playlist_result(
  235. urlrs, playlist_id=video_id, playlist_title=video_title)
  236. # Look for embedded Wistia player
  237. match = re.search(
  238. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:fast\.)?wistia\.net/embed/iframe/.+?)\1', webpage)
  239. if match:
  240. return {
  241. '_type': 'url_transparent',
  242. 'url': unescapeHTML(match.group('url')),
  243. 'ie_key': 'Wistia',
  244. 'uploader': video_uploader,
  245. 'title': video_title,
  246. 'id': video_id,
  247. }
  248. # Look for embedded blip.tv player
  249. mobj = re.search(r'<meta\s[^>]*https?://api\.blip\.tv/\w+/redirect/\w+/(\d+)', webpage)
  250. if mobj:
  251. return self.url_result('http://blip.tv/a/a-'+mobj.group(1), 'BlipTV')
  252. mobj = re.search(r'<(?:iframe|embed|object)\s[^>]*(https?://(?:\w+\.)?blip\.tv/(?:play/|api\.swf#)[a-zA-Z0-9]+)', webpage)
  253. if mobj:
  254. return self.url_result(mobj.group(1), 'BlipTV')
  255. # Look for Bandcamp pages with custom domain
  256. mobj = re.search(r'<meta property="og:url"[^>]*?content="(.*?bandcamp\.com.*?)"', webpage)
  257. if mobj is not None:
  258. burl = unescapeHTML(mobj.group(1))
  259. # Don't set the extractor because it can be a track url or an album
  260. return self.url_result(burl)
  261. # Look for embedded Vevo player
  262. mobj = re.search(
  263. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:cache\.)?vevo\.com/.+?)\1', webpage)
  264. if mobj is not None:
  265. return self.url_result(mobj.group('url'))
  266. # Look for Ooyala videos
  267. mobj = re.search(r'player.ooyala.com/[^"?]+\?[^"]*?(?:embedCode|ec)=([^"&]+)', webpage)
  268. if mobj is not None:
  269. return OoyalaIE._build_url_result(mobj.group(1))
  270. # Look for Aparat videos
  271. mobj = re.search(r'<iframe src="(http://www\.aparat\.com/video/[^"]+)"', webpage)
  272. if mobj is not None:
  273. return self.url_result(mobj.group(1), 'Aparat')
  274. # Look for MPORA videos
  275. mobj = re.search(r'<iframe .*?src="(http://mpora\.com/videos/[^"]+)"', webpage)
  276. if mobj is not None:
  277. return self.url_result(mobj.group(1), 'Mpora')
  278. # Look for embedded Novamov player
  279. mobj = re.search(
  280. r'<iframe[^>]+?src=(["\'])(?P<url>http://(?:(?:embed|www)\.)?novamov\.com/embed\.php.+?)\1', webpage)
  281. if mobj is not None:
  282. return self.url_result(mobj.group('url'), 'Novamov')
  283. # Start with something easy: JW Player in SWFObject
  284. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  285. if mobj is None:
  286. # Look for gorilla-vid style embedding
  287. mobj = re.search(r'(?s)jw_plugins.*?file:\s*["\'](.*?)["\']', webpage)
  288. if mobj is None:
  289. # Broaden the search a little bit
  290. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  291. if mobj is None:
  292. # Broaden the search a little bit: JWPlayer JS loader
  293. mobj = re.search(r'[^A-Za-z0-9]?file["\']?:\s*["\'](http(?![^\'"]+\.[0-9]+[\'"])[^\'"]+)["\']', webpage)
  294. if mobj is None:
  295. # Try to find twitter cards info
  296. mobj = re.search(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
  297. if mobj is None:
  298. # We look for Open Graph info:
  299. # We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
  300. m_video_type = re.search(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
  301. # We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
  302. if m_video_type is not None:
  303. mobj = re.search(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)
  304. if mobj is None:
  305. # HTML5 video
  306. mobj = re.search(r'<video[^<]*(?:>.*?<source.*?)? src="([^"]+)"', webpage, flags=re.DOTALL)
  307. if mobj is None:
  308. raise ExtractorError('Unsupported URL: %s' % url)
  309. # It's possible that one of the regexes
  310. # matched, but returned an empty group:
  311. if mobj.group(1) is None:
  312. raise ExtractorError('Did not find a valid video URL at %s' % url)
  313. video_url = mobj.group(1)
  314. video_url = compat_urlparse.urljoin(url, video_url)
  315. video_id = compat_urllib_parse.unquote(os.path.basename(video_url))
  316. # Sometimes, jwplayer extraction will result in a YouTube URL
  317. if YoutubeIE.suitable(video_url):
  318. return self.url_result(video_url, 'Youtube')
  319. # here's a fun little line of code for you:
  320. video_id = os.path.splitext(video_id)[0]
  321. return {
  322. 'id': video_id,
  323. 'url': video_url,
  324. 'uploader': video_uploader,
  325. 'title': video_title,
  326. }