app.rb 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. # frozen_string_literal: true
  2. require 'bundler/setup'
  3. Bundler.require :app
  4. class App < Sinatra::Application
  5. Bundler.require environment
  6. require 'sinatra/cookies'
  7. require 'tilt/erubis'
  8. Rack::Mime::MIME_TYPES['.webapp'] = 'application/x-web-app-manifest+json'
  9. configure do
  10. set :sentry_dsn, ENV['SENTRY_DSN']
  11. set :protection, except: [:frame_options, :xss_header]
  12. set :root, Pathname.new(File.expand_path('../..', __FILE__))
  13. set :sprockets, Sprockets::Environment.new(root)
  14. set :assets_prefix, 'assets'
  15. set :assets_path, -> { File.join(public_folder, assets_prefix) }
  16. set :assets_manifest_path, -> { File.join(assets_path, 'manifest.json') }
  17. set :assets_compile, %w(*.png docs.js docs.json application.js application.css application-dark.css)
  18. require 'yajl/json_gem'
  19. set :docs_prefix, 'docs'
  20. set :docs_host, -> { File.join('', docs_prefix) }
  21. set :docs_path, -> { File.join(public_folder, docs_prefix) }
  22. set :docs_manifest_path, -> { File.join(docs_path, 'docs.json') }
  23. set :default_docs, %w(css dom dom_events html http javascript)
  24. set :docs, -> {
  25. Hash[JSON.parse(File.read(docs_manifest_path)).map! { |doc|
  26. doc['full_name'] = doc['name'].dup
  27. doc['full_name'] << " #{doc['version']}" if doc['version']
  28. doc['slug_without_version'] = doc['slug'].split('~').first
  29. [doc['slug'], doc]
  30. }]
  31. }
  32. set :news_path, -> { File.join(root, assets_prefix, 'javascripts', 'news.json') }
  33. set :news, -> { JSON.parse(File.read(news_path)) }
  34. set :csp, false
  35. Dir[docs_path, root.join(assets_prefix, '*/')].each do |path|
  36. sprockets.append_path(path)
  37. end
  38. Sprockets::Helpers.configure do |config|
  39. config.environment = sprockets
  40. config.prefix = "/#{assets_prefix}"
  41. config.public_path = public_folder
  42. config.protocol = :relative
  43. end
  44. end
  45. configure :test, :development do
  46. require 'active_support/per_thread_registry'
  47. require 'active_support/cache'
  48. sprockets.cache = ActiveSupport::Cache.lookup_store :file_store, root.join('tmp', 'cache', 'assets', environment.to_s)
  49. end
  50. configure :development do
  51. register Sinatra::Reloader
  52. use BetterErrors::Middleware
  53. BetterErrors.application_root = File.expand_path('..', __FILE__)
  54. BetterErrors.editor = :sublime
  55. set :csp, "default-src 'self' *; script-src 'self' 'nonce-devdocs' *; font-src data:; style-src 'self' 'unsafe-inline' *; img-src 'self' * data:;"
  56. end
  57. configure :production do
  58. set :static, false
  59. set :docs_host, '//docs.devdocs.io'
  60. set :csp, "default-src 'self' *; script-src 'self' 'nonce-devdocs' http://cdn.devdocs.io https://cdn.devdocs.io https://www.google-analytics.com https://secure.gaug.es http://*.jquery.com https://*.jquery.com; font-src data:; style-src 'self' 'unsafe-inline' *; img-src 'self' * data:;"
  61. use Rack::ConditionalGet
  62. use Rack::ETag
  63. use Rack::Deflater
  64. use Rack::Static,
  65. root: 'public',
  66. urls: %w(/assets /docs/ /images /favicon.ico /robots.txt /opensearch.xml /manifest.webapp /mathml.css),
  67. header_rules: [
  68. [:all, {'Cache-Control' => 'no-cache, max-age=0'}],
  69. ['/assets', {'Cache-Control' => 'public, max-age=604800'}],
  70. ['/favicon.ico', {'Cache-Control' => 'public, max-age=86400'}],
  71. ['/mathml.css', {'Cache-Control' => 'public, max-age=604800'}],
  72. ['/images', {'Cache-Control' => 'public, max-age=86400'}] ]
  73. sprockets.js_compressor = Uglifier.new output: { beautify: true, indent_level: 0 }
  74. sprockets.css_compressor = :sass
  75. Sprockets::Helpers.configure do |config|
  76. config.digest = true
  77. config.asset_host = 'cdn.devdocs.io'
  78. config.manifest = Sprockets::Manifest.new(sprockets, assets_manifest_path)
  79. end
  80. end
  81. configure :test do
  82. set :docs_manifest_path, -> { File.join(root, 'test', 'files', 'docs.json') }
  83. end
  84. helpers do
  85. include Sinatra::Cookies
  86. include Sprockets::Helpers
  87. def browser
  88. @browser ||= Browser.new(request.user_agent)
  89. end
  90. UNSUPPORTED_IE_VERSIONS = %w(6 7 8 9).freeze
  91. def unsupported_browser?
  92. browser.ie? && UNSUPPORTED_IE_VERSIONS.include?(browser.version)
  93. end
  94. def docs
  95. @docs ||= begin
  96. cookie = cookies[:docs]
  97. if cookie.nil?
  98. settings.default_docs
  99. else
  100. cookie.split('/')
  101. end
  102. end
  103. end
  104. def find_doc(slug)
  105. settings.docs[slug] || begin
  106. settings.docs.each do |_, doc|
  107. return doc if doc['slug_without_version'] == slug
  108. end
  109. nil
  110. end
  111. end
  112. def user_has_docs?(slug)
  113. docs.include?(slug) || begin
  114. slug = "#{slug}~"
  115. docs.any? { |_slug| _slug.start_with?(slug) }
  116. end
  117. end
  118. def doc_index_urls
  119. docs.each_with_object [] do |slug, result|
  120. if doc = settings.docs[slug]
  121. result << File.join('', settings.docs_prefix, slug, 'index.json') + "?#{doc['mtime']}"
  122. end
  123. end
  124. end
  125. def doc_index_page?
  126. @doc && (request.path == "/#{@doc['slug']}/" || request.path == "/#{@doc['slug_without_version']}/")
  127. end
  128. def query_string_for_redirection
  129. request.query_string.empty? ? nil : "?#{request.query_string}"
  130. end
  131. def main_stylesheet_path
  132. stylesheet_paths[dark_theme? ? :dark : :default]
  133. end
  134. def alternate_stylesheet_path
  135. stylesheet_paths[dark_theme? ? :default : :dark]
  136. end
  137. def stylesheet_paths
  138. @stylesheet_paths ||= {
  139. default: stylesheet_path('application'),
  140. dark: stylesheet_path('application-dark')
  141. }
  142. end
  143. def app_size
  144. @app_size ||= cookies[:size].nil? ? '18rem' : "#{cookies[:size]}px"
  145. end
  146. def app_layout
  147. cookies[:layout]
  148. end
  149. def app_theme
  150. @app_theme ||= cookies[:dark].nil? ? 'default' : 'dark'
  151. end
  152. def dark_theme?
  153. app_theme == 'dark'
  154. end
  155. def redirect_via_js(path) # courtesy of HTML5 App Cache
  156. response.set_cookie :initial_path, value: path, expires: Time.now + 15, path: '/'
  157. redirect '/', 302
  158. end
  159. def supports_js_redirection?
  160. browser.modern? && !cookies.empty?
  161. end
  162. end
  163. before do
  164. halt erb :unsupported if unsupported_browser?
  165. end
  166. OUT_HOST = 'out.devdocs.io'.freeze
  167. before do
  168. if request.host == OUT_HOST && !request.path.start_with?('/s/')
  169. query_string = "?#{request.query_string}" unless request.query_string.empty?
  170. redirect "http://devdocs.io#{request.path}#{query_string}", 302
  171. end
  172. end
  173. get '/manifest.appcache' do
  174. content_type 'text/cache-manifest'
  175. expires 0, :'no-cache'
  176. erb :manifest
  177. end
  178. get '/' do
  179. return redirect '/' unless request.query_string.empty? # courtesy of HTML5 App Cache
  180. response.headers['Content-Security-Policy'] = settings.csp if settings.csp
  181. erb :index
  182. end
  183. %w(offline about news help).each do |page|
  184. get "/#{page}" do
  185. if supports_js_redirection?
  186. redirect_via_js "/#{page}"
  187. else
  188. redirect "/#/#{page}", 302
  189. end
  190. end
  191. end
  192. get '/search' do
  193. redirect "/#q=#{params[:q]}"
  194. end
  195. get '/ping' do
  196. 200
  197. end
  198. %w(docs.json application.js application.css).each do |asset|
  199. class_eval <<-CODE, __FILE__, __LINE__ + 1
  200. get '/#{asset}' do
  201. redirect asset_path('#{asset}', protocol: 'http')
  202. end
  203. CODE
  204. end
  205. {
  206. '/s/maxcdn' => 'https://www.maxcdn.com/?utm_source=devdocs&utm_medium=banner&utm_campaign=devdocs',
  207. '/s/shopify' => 'https://www.shopify.com/careers?utm_source=devdocs&utm_medium=banner&utm_campaign=devdocs',
  208. '/s/jetbrains' => 'https://www.jetbrains.com/?utm_source=devdocs&utm_medium=sponsorship&utm_campaign=devdocs',
  209. '/s/jetbrains/ruby' => 'https://www.jetbrains.com/ruby/?utm_source=devdocs&utm_medium=sponsorship&utm_campaign=devdocs',
  210. '/s/jetbrains/python' => 'https://www.jetbrains.com/pycharm/?utm_source=devdocs&utm_medium=sponsorship&utm_campaign=devdocs',
  211. '/s/jetbrains/c' => 'https://www.jetbrains.com/clion/?utm_source=devdocs&utm_medium=sponsorship&utm_campaign=devdocs',
  212. '/s/jetbrains/web' => 'https://www.jetbrains.com/webstorm/?utm_source=devdocs&utm_medium=sponsorship&utm_campaign=devdocs',
  213. '/s/code-school' => 'http://www.codeschool.com/?utm_campaign=devdocs&utm_content=homepage&utm_source=devdocs&utm_medium=sponsorship',
  214. '/s/tw' => 'https://twitter.com/intent/tweet?url=http%3A%2F%2Fdevdocs.io&via=DevDocs&text=All-in-one%20API%20documentation%20browser%20with%20offline%20mode%20and%20instant%20search%3A',
  215. '/s/fb' => 'https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fdevdocs.io',
  216. '/s/re' => 'https://www.reddit.com/submit?url=http%3A%2F%2Fdevdocs.io&title=All-in-one%20API%20documentation%20browser%20with%20offline%20mode%20and%20instant%20search&resubmit=true'
  217. }.each do |path, url|
  218. class_eval <<-CODE, __FILE__, __LINE__ + 1
  219. get '#{path}' do
  220. redirect '#{url}'
  221. end
  222. CODE
  223. end
  224. get %r{\A/feed(?:\.atom)?\z} do
  225. content_type 'application/atom+xml'
  226. settings.news_feed
  227. end
  228. DOC_REDIRECTS = {
  229. 'iojs' => 'node',
  230. 'yii1' => 'yii~1.1',
  231. 'python2' => 'python~2.7',
  232. 'xpath' => 'xslt_xpath',
  233. 'angular~1.5' => 'angularjs~1.5',
  234. 'angular~1.4' => 'angularjs~1.4',
  235. 'angular~1.3' => 'angularjs~1.3',
  236. 'angular~1.2' => 'angularjs~1.2',
  237. 'codeigniter~3.0' => 'codeigniter~3'
  238. }
  239. get %r{\A/([\w~\.%]+)(\-[\w\-]+)?(/.*)?\z} do |doc, type, rest|
  240. doc.sub! '%7E', '~'
  241. return redirect "/#{DOC_REDIRECTS[doc]}#{type}#{rest}" if DOC_REDIRECTS.key?(doc)
  242. return redirect "/angularjs/api#{rest}", 301 if doc == 'angular' && rest.start_with?('/ng')
  243. return 404 unless @doc = find_doc(doc)
  244. if rest.nil?
  245. redirect "/#{doc}#{type}/#{query_string_for_redirection}"
  246. elsif rest.length > 1 && rest.end_with?('/')
  247. redirect "/#{doc}#{type}#{rest[0...-1]}#{query_string_for_redirection}"
  248. elsif user_has_docs?(doc) && supports_js_redirection?
  249. redirect_via_js(request.path)
  250. else
  251. response.headers['Content-Security-Policy'] = settings.csp if settings.csp
  252. erb :other
  253. end
  254. end
  255. not_found do
  256. send_file File.join(settings.public_folder, '404.html'), status: status
  257. end
  258. error do
  259. send_file File.join(settings.public_folder, '500.html'), status: status
  260. end
  261. configure do
  262. require 'rss'
  263. feed = RSS::Maker.make('atom') do |maker|
  264. maker.channel.id = 'tag:devdocs.io,2014:/feed'
  265. maker.channel.title = 'DevDocs'
  266. maker.channel.author = 'DevDocs'
  267. maker.channel.updated = "#{settings.news.first.first}T14:00:00Z"
  268. maker.channel.links.new_link do |link|
  269. link.rel = 'self'
  270. link.href = 'http://devdocs.io/feed.atom'
  271. link.type = 'application/atom+xml'
  272. end
  273. maker.channel.links.new_link do |link|
  274. link.rel = 'alternate'
  275. link.href = 'http://devdocs.io/'
  276. link.type = 'text/html'
  277. end
  278. news.each_with_index do |news, i|
  279. maker.items.new_item do |item|
  280. item.id = "tag:devdocs.io,2014:News/#{settings.news.length - i}"
  281. item.title = news[1].split("\n").first.gsub(/<\/?[^>]*>/, '')
  282. item.description do |desc|
  283. desc.content = news[1..-1].join.gsub("\n", '<br>').gsub('href="/', 'href="http://devdocs.io/')
  284. desc.type = 'html'
  285. end
  286. item.updated = "#{news.first}T14:00:00Z"
  287. item.published = "#{news.first}T14:00:00Z"
  288. item.links.new_link do |link|
  289. link.rel = 'alternate'
  290. link.href = 'http://devdocs.io/'
  291. link.type = 'text/html'
  292. end
  293. end
  294. end
  295. end
  296. set :news_feed, feed.to_s
  297. end
  298. end