app.rb 14 KB

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