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.

431 lines
18 KiB

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