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.

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