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.

405 lines
17 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. {
  76. # https://github.com/rg3/youtube-dl/issues/2253
  77. 'url': 'http://bcove.me/i6nfkrc3',
  78. 'file': '3101154703001.mp4',
  79. 'md5': '0ba9446db037002366bab3b3eb30c88c',
  80. 'info_dict': {
  81. 'title': 'Still no power',
  82. 'uploader': 'thestar.com',
  83. 'description': 'Mississauga resident David Farmer is still out of power as a result of the ice storm a month ago. To keep the house warm, Farmer cuts wood from his property for a wood burning stove downstairs.',
  84. },
  85. 'add_ie': ['Brightcove'],
  86. },
  87. # Direct link to a video
  88. {
  89. 'url': 'http://media.w3.org/2010/05/sintel/trailer.mp4',
  90. 'file': 'trailer.mp4',
  91. 'md5': '67d406c2bcb6af27fa886f31aa934bbe',
  92. 'info_dict': {
  93. 'id': 'trailer',
  94. 'title': 'trailer',
  95. 'upload_date': '20100513',
  96. }
  97. },
  98. # ooyala video
  99. {
  100. 'url': 'http://www.rollingstone.com/music/videos/norwegian-dj-cashmere-cat-goes-spartan-on-with-me-premiere-20131219',
  101. 'file': 'BwY2RxaTrTkslxOfcan0UCf0YqyvWysJ.mp4',
  102. 'md5': '5644c6ca5d5782c1d0d350dad9bd840c',
  103. 'info_dict': {
  104. 'id': 'BwY2RxaTrTkslxOfcan0UCf0YqyvWysJ',
  105. 'ext': 'mp4',
  106. 'title': '2cc213299525360.mov', # that's what we get
  107. },
  108. },
  109. ]
  110. def report_download_webpage(self, video_id):
  111. """Report webpage download."""
  112. if not self._downloader.params.get('test', False):
  113. self._downloader.report_warning('Falling back on generic information extractor.')
  114. super(GenericIE, self).report_download_webpage(video_id)
  115. def report_following_redirect(self, new_url):
  116. """Report information extraction."""
  117. self._downloader.to_screen('[redirect] Following redirect to %s' % new_url)
  118. def _send_head(self, url):
  119. """Check if it is a redirect, like url shorteners, in case return the new url."""
  120. class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  121. """
  122. Subclass the HTTPRedirectHandler to make it use our
  123. HEADRequest also on the redirected URL
  124. """
  125. def redirect_request(self, req, fp, code, msg, headers, newurl):
  126. if code in (301, 302, 303, 307):
  127. newurl = newurl.replace(' ', '%20')
  128. newheaders = dict((k,v) for k,v in req.headers.items()
  129. if k.lower() not in ("content-length", "content-type"))
  130. return HEADRequest(newurl,
  131. headers=newheaders,
  132. origin_req_host=req.get_origin_req_host(),
  133. unverifiable=True)
  134. else:
  135. raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
  136. class HTTPMethodFallback(compat_urllib_request.BaseHandler):
  137. """
  138. Fallback to GET if HEAD is not allowed (405 HTTP error)
  139. """
  140. def http_error_405(self, req, fp, code, msg, headers):
  141. fp.read()
  142. fp.close()
  143. newheaders = dict((k,v) for k,v in req.headers.items()
  144. if k.lower() not in ("content-length", "content-type"))
  145. return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
  146. headers=newheaders,
  147. origin_req_host=req.get_origin_req_host(),
  148. unverifiable=True))
  149. # Build our opener
  150. opener = compat_urllib_request.OpenerDirector()
  151. for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
  152. HTTPMethodFallback, HEADRedirectHandler,
  153. compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
  154. opener.add_handler(handler())
  155. response = opener.open(HEADRequest(url))
  156. if response is None:
  157. raise ExtractorError('Invalid URL protocol')
  158. return response
  159. def _real_extract(self, url):
  160. parsed_url = compat_urlparse.urlparse(url)
  161. if not parsed_url.scheme:
  162. default_search = self._downloader.params.get('default_search')
  163. if default_search is None:
  164. default_search = 'auto'
  165. if default_search == 'auto':
  166. if '/' in url:
  167. self._downloader.report_warning('The url doesn\'t specify the protocol, trying with http')
  168. return self.url_result('http://' + url)
  169. else:
  170. return self.url_result('ytsearch:' + url)
  171. else:
  172. assert ':' in default_search
  173. return self.url_result(default_search + url)
  174. video_id = os.path.splitext(url.split('/')[-1])[0]
  175. self.to_screen('%s: Requesting header' % video_id)
  176. try:
  177. response = self._send_head(url)
  178. # Check for redirect
  179. new_url = response.geturl()
  180. if url != new_url:
  181. self.report_following_redirect(new_url)
  182. return self.url_result(new_url)
  183. # Check for direct link to a video
  184. content_type = response.headers.get('Content-Type', '')
  185. m = re.match(r'^(?P<type>audio|video|application(?=/ogg$))/(?P<format_id>.+)$', content_type)
  186. if m:
  187. upload_date = response.headers.get('Last-Modified')
  188. if upload_date:
  189. upload_date = unified_strdate(upload_date)
  190. return {
  191. 'id': video_id,
  192. 'title': os.path.splitext(url_basename(url))[0],
  193. 'formats': [{
  194. 'format_id': m.group('format_id'),
  195. 'url': url,
  196. 'vcodec': 'none' if m.group('type') == 'audio' else None
  197. }],
  198. 'upload_date': upload_date,
  199. }
  200. except compat_urllib_error.HTTPError:
  201. # This may be a stupid server that doesn't like HEAD, our UA, or so
  202. pass
  203. try:
  204. webpage = self._download_webpage(url, video_id)
  205. except ValueError:
  206. # since this is the last-resort InfoExtractor, if
  207. # this error is thrown, it'll be thrown here
  208. raise ExtractorError('Failed to download URL: %s' % url)
  209. self.report_extraction(video_id)
  210. # it's tempting to parse this further, but you would
  211. # have to take into account all the variations like
  212. # Video Title - Site Name
  213. # Site Name | Video Title
  214. # Video Title - Tagline | Site Name
  215. # and so on and so forth; it's just not practical
  216. video_title = self._html_search_regex(
  217. r'(?s)<title>(.*?)</title>', webpage, 'video title',
  218. default='video')
  219. # video uploader is domain name
  220. video_uploader = self._search_regex(
  221. r'^(?:https?://)?([^/]*)/.*', url, 'video uploader')
  222. # Look for BrightCove:
  223. bc_url = BrightcoveIE._extract_brightcove_url(webpage)
  224. if bc_url is not None:
  225. self.to_screen('Brightcove video detected.')
  226. surl = smuggle_url(bc_url, {'Referer': url})
  227. return self.url_result(surl, 'Brightcove')
  228. # Look for embedded (iframe) Vimeo player
  229. mobj = re.search(
  230. r'<iframe[^>]+?src="((?:https?:)?//player.vimeo.com/video/.+?)"', webpage)
  231. if mobj:
  232. player_url = unescapeHTML(mobj.group(1))
  233. surl = smuggle_url(player_url, {'Referer': url})
  234. return self.url_result(surl, 'Vimeo')
  235. # Look for embedded (swf embed) Vimeo player
  236. mobj = re.search(
  237. r'<embed[^>]+?src="(https?://(?:www\.)?vimeo.com/moogaloop.swf.+?)"', webpage)
  238. if mobj:
  239. return self.url_result(mobj.group(1), 'Vimeo')
  240. # Look for embedded YouTube player
  241. matches = re.findall(r'''(?x)
  242. (?:<iframe[^>]+?src=|embedSWF\(\s*)
  243. (["\'])(?P<url>(?:https?:)?//(?:www\.)?youtube\.com/
  244. (?:embed|v)/.+?)
  245. \1''', webpage)
  246. if matches:
  247. urlrs = [self.url_result(unescapeHTML(tuppl[1]), 'Youtube')
  248. for tuppl in matches]
  249. return self.playlist_result(
  250. urlrs, playlist_id=video_id, playlist_title=video_title)
  251. # Look for embedded Dailymotion player
  252. matches = re.findall(
  253. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/embed/video/.+?)\1', webpage)
  254. if matches:
  255. urlrs = [self.url_result(unescapeHTML(tuppl[1]), 'Dailymotion')
  256. for tuppl in matches]
  257. return self.playlist_result(
  258. urlrs, playlist_id=video_id, playlist_title=video_title)
  259. # Look for embedded Wistia player
  260. match = re.search(
  261. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:fast\.)?wistia\.net/embed/iframe/.+?)\1', webpage)
  262. if match:
  263. return {
  264. '_type': 'url_transparent',
  265. 'url': unescapeHTML(match.group('url')),
  266. 'ie_key': 'Wistia',
  267. 'uploader': video_uploader,
  268. 'title': video_title,
  269. 'id': video_id,
  270. }
  271. # Look for embedded blip.tv player
  272. mobj = re.search(r'<meta\s[^>]*https?://api\.blip\.tv/\w+/redirect/\w+/(\d+)', webpage)
  273. if mobj:
  274. return self.url_result('http://blip.tv/a/a-'+mobj.group(1), 'BlipTV')
  275. mobj = re.search(r'<(?:iframe|embed|object)\s[^>]*(https?://(?:\w+\.)?blip\.tv/(?:play/|api\.swf#)[a-zA-Z0-9]+)', webpage)
  276. if mobj:
  277. return self.url_result(mobj.group(1), 'BlipTV')
  278. # Look for Bandcamp pages with custom domain
  279. mobj = re.search(r'<meta property="og:url"[^>]*?content="(.*?bandcamp\.com.*?)"', webpage)
  280. if mobj is not None:
  281. burl = unescapeHTML(mobj.group(1))
  282. # Don't set the extractor because it can be a track url or an album
  283. return self.url_result(burl)
  284. # Look for embedded Vevo player
  285. mobj = re.search(
  286. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:cache\.)?vevo\.com/.+?)\1', webpage)
  287. if mobj is not None:
  288. return self.url_result(mobj.group('url'))
  289. # Look for Ooyala videos
  290. mobj = re.search(r'player.ooyala.com/[^"?]+\?[^"]*?(?:embedCode|ec)=([^"&]+)', webpage)
  291. if mobj is not None:
  292. return OoyalaIE._build_url_result(mobj.group(1))
  293. # Look for Aparat videos
  294. mobj = re.search(r'<iframe src="(http://www\.aparat\.com/video/[^"]+)"', webpage)
  295. if mobj is not None:
  296. return self.url_result(mobj.group(1), 'Aparat')
  297. # Look for MPORA videos
  298. mobj = re.search(r'<iframe .*?src="(http://mpora\.com/videos/[^"]+)"', webpage)
  299. if mobj is not None:
  300. return self.url_result(mobj.group(1), 'Mpora')
  301. # Look for embedded Novamov player
  302. mobj = re.search(
  303. r'<iframe[^>]+?src=(["\'])(?P<url>http://(?:(?:embed|www)\.)?novamov\.com/embed\.php.+?)\1', webpage)
  304. if mobj is not None:
  305. return self.url_result(mobj.group('url'), 'Novamov')
  306. # Look for embedded Facebook player
  307. mobj = re.search(
  308. r'<iframe[^>]+?src=(["\'])(?P<url>https://www\.facebook\.com/video/embed.+?)\1', webpage)
  309. if mobj is not None:
  310. return self.url_result(mobj.group('url'), 'Facebook')
  311. # Look for embedded Huffington Post player
  312. mobj = re.search(
  313. r'<iframe[^>]+?src=(["\'])(?P<url>https?://embed\.live.huffingtonpost\.com/.+?)\1', webpage)
  314. if mobj is not None:
  315. return self.url_result(mobj.group('url'), 'HuffPost')
  316. # Start with something easy: JW Player in SWFObject
  317. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  318. if mobj is None:
  319. # Look for gorilla-vid style embedding
  320. mobj = re.search(r'(?s)jw_plugins.*?file:\s*["\'](.*?)["\']', webpage)
  321. if mobj is None:
  322. # Broaden the search a little bit
  323. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  324. if mobj is None:
  325. # Broaden the search a little bit: JWPlayer JS loader
  326. mobj = re.search(r'[^A-Za-z0-9]?file["\']?:\s*["\'](http(?![^\'"]+\.[0-9]+[\'"])[^\'"]+)["\']', webpage)
  327. if mobj is None:
  328. # Try to find twitter cards info
  329. mobj = re.search(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
  330. if mobj is None:
  331. # We look for Open Graph info:
  332. # We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
  333. m_video_type = re.search(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
  334. # We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
  335. if m_video_type is not None:
  336. mobj = re.search(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)
  337. if mobj is None:
  338. # HTML5 video
  339. mobj = re.search(r'<video[^<]*(?:>.*?<source.*?)? src="([^"]+)"', webpage, flags=re.DOTALL)
  340. if mobj is None:
  341. raise ExtractorError('Unsupported URL: %s' % url)
  342. # It's possible that one of the regexes
  343. # matched, but returned an empty group:
  344. if mobj.group(1) is None:
  345. raise ExtractorError('Did not find a valid video URL at %s' % url)
  346. video_url = mobj.group(1)
  347. video_url = compat_urlparse.urljoin(url, video_url)
  348. video_id = compat_urllib_parse.unquote(os.path.basename(video_url))
  349. # Sometimes, jwplayer extraction will result in a YouTube URL
  350. if YoutubeIE.suitable(video_url):
  351. return self.url_result(video_url, 'Youtube')
  352. # here's a fun little line of code for you:
  353. video_id = os.path.splitext(video_id)[0]
  354. return {
  355. 'id': video_id,
  356. 'url': video_url,
  357. 'uploader': video_uploader,
  358. 'title': video_title,
  359. }