app.rb 13 KB

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