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.

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