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.

349 lines
15 KiB

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