generic.py 15 KB

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