app.rb 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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: false, 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' 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:;"
  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 manifest_asset_urls
  157. @@manifest_asset_urls ||= [
  158. javascript_path('application', asset_host: false),
  159. stylesheet_path('application'),
  160. stylesheet_path('application-dark'),
  161. image_path('docs-1.png'),
  162. image_path('docs-1@2x.png'),
  163. image_path('docs-2.png'),
  164. image_path('docs-2@2x.png'),
  165. asset_path('docs.js')
  166. ]
  167. end
  168. def main_stylesheet_path
  169. stylesheet_paths[dark_theme? ? :dark : :default]
  170. end
  171. def alternate_stylesheet_path
  172. stylesheet_paths[dark_theme? ? :default : :dark]
  173. end
  174. def stylesheet_paths
  175. @@stylesheet_paths ||= {
  176. default: stylesheet_path('application'),
  177. dark: stylesheet_path('application-dark')
  178. }
  179. end
  180. def app_size
  181. @app_size ||= memoized_cookies['size'].nil? ? '20rem' : "#{memoized_cookies['size']}px"
  182. end
  183. def app_layout
  184. memoized_cookies['layout']
  185. end
  186. def app_theme
  187. @app_theme ||= memoized_cookies['dark'].nil? ? 'default' : 'dark'
  188. end
  189. def dark_theme?
  190. app_theme == 'dark'
  191. end
  192. def redirect_via_js(path) # courtesy of HTML5 App Cache
  193. response.set_cookie :initial_path, value: path, expires: Time.now + 15, path: '/'
  194. redirect '/', 302
  195. end
  196. def supports_js_redirection?
  197. browser.modern? && !memoized_cookies.empty?
  198. end
  199. end
  200. before do
  201. halt erb :unsupported if unsupported_browser?
  202. end
  203. OUT_HOST = 'out.devdocs.io'.freeze
  204. before do
  205. if request.host == OUT_HOST && !request.path.start_with?('/s/')
  206. query_string = "?#{request.query_string}" unless request.query_string.empty?
  207. redirect "https://devdocs.io#{request.path}#{query_string}", 302
  208. end
  209. end
  210. get '/manifest.appcache' do
  211. content_type 'text/cache-manifest'
  212. expires 0, :'no-cache'
  213. erb :manifest
  214. end
  215. get '/' do
  216. return redirect "/#q=#{params[:q]}" if params[:q]
  217. return redirect '/' unless request.query_string.empty? # courtesy of HTML5 App Cache
  218. response.headers['Content-Security-Policy'] = settings.csp if settings.csp
  219. erb :index
  220. end
  221. %w(settings offline about news help).each do |page|
  222. get "/#{page}" do
  223. if supports_js_redirection?
  224. redirect_via_js "/#{page}"
  225. else
  226. redirect "/#/#{page}", 302
  227. end
  228. end
  229. end
  230. get '/search' do
  231. redirect "/#q=#{params[:q]}"
  232. end
  233. get '/ping' do
  234. 200
  235. end
  236. %w(docs.json application.js application.css).each do |asset|
  237. class_eval <<-CODE, __FILE__, __LINE__ + 1
  238. get '/#{asset}' do
  239. redirect asset_path('#{asset}', protocol: 'http')
  240. end
  241. CODE
  242. end
  243. {
  244. '/s/maxcdn' => 'https://www.maxcdn.com/?utm_source=devdocs&utm_medium=banner&utm_campaign=devdocs',
  245. '/s/shopify' => 'https://www.shopify.com/careers?utm_source=devdocs&utm_medium=banner&utm_campaign=devdocs',
  246. '/s/jetbrains' => 'https://www.jetbrains.com/?utm_source=devdocs&utm_medium=sponsorship&utm_campaign=devdocs',
  247. '/s/jetbrains/ruby' => 'https://www.jetbrains.com/ruby/?utm_source=devdocs&utm_medium=sponsorship&utm_campaign=devdocs',
  248. '/s/jetbrains/python' => 'https://www.jetbrains.com/pycharm/?utm_source=devdocs&utm_medium=sponsorship&utm_campaign=devdocs',
  249. '/s/jetbrains/c' => 'https://www.jetbrains.com/clion/?utm_source=devdocs&utm_medium=sponsorship&utm_campaign=devdocs',
  250. '/s/jetbrains/web' => 'https://www.jetbrains.com/webstorm/?utm_source=devdocs&utm_medium=sponsorship&utm_campaign=devdocs',
  251. '/s/code-school' => 'https://www.codeschool.com/?utm_campaign=devdocs&utm_content=homepage&utm_source=devdocs&utm_medium=sponsorship',
  252. '/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',
  253. '/s/fb' => 'https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fdevdocs.io',
  254. '/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'
  255. }.each do |path, url|
  256. class_eval <<-CODE, __FILE__, __LINE__ + 1
  257. get '#{path}' do
  258. redirect '#{url}'
  259. end
  260. CODE
  261. end
  262. %w(/maxcdn /maxcdn/).each do |path|
  263. class_eval <<-CODE, __FILE__, __LINE__ + 1
  264. get '#{path}' do
  265. 410
  266. end
  267. CODE
  268. end
  269. {
  270. '/tips' => '/help',
  271. '/css-data-types/' => '/css-values-units/',
  272. '/css-at-rules/' => '/?q=css%20%40',
  273. '/dom/window/setinterval' => '/dom/windoworworkerglobalscope/setinterval',
  274. '/html/article' => '/html/element/article',
  275. '/html-html5/' => 'html-elements/',
  276. '/html-standard/' => 'html-elements/',
  277. '/http-status-codes/' => '/http-status/',
  278. '/ruby/bignum' => '/ruby~2.3/bignum',
  279. '/ruby/fixnum' => '/ruby~2.3/fixnum',
  280. }.each do |path, url|
  281. class_eval <<-CODE, __FILE__, __LINE__ + 1
  282. get '#{path}' do
  283. redirect '#{url}', 301
  284. end
  285. CODE
  286. end
  287. get %r{/feed(?:\.atom)?} do
  288. content_type 'application/atom+xml'
  289. settings.news_feed
  290. end
  291. DOC_REDIRECTS = {
  292. 'iojs' => 'node',
  293. 'node_lts' => 'node~6_lts',
  294. 'node~4.2_lts' => 'node~4_lts',
  295. 'yii1' => 'yii~1.1',
  296. 'python2' => 'python~2.7',
  297. 'xpath' => 'xslt_xpath',
  298. 'angular~4_typescript' => 'angular',
  299. 'angular~2_typescript' => 'angular~2',
  300. 'angular~2.0_typescript' => 'angular~2',
  301. 'angular~1.5' => 'angularjs~1.5',
  302. 'angular~1.4' => 'angularjs~1.4',
  303. 'angular~1.3' => 'angularjs~1.3',
  304. 'angular~1.2' => 'angularjs~1.2',
  305. 'codeigniter~3.0' => 'codeigniter~3',
  306. 'webpack~2' => 'webpack'
  307. }
  308. get %r{/([\w~\.%]+)(\-[\w\-]+)?(/.*)?} do |doc, type, rest|
  309. doc.sub! '%7E', '~'
  310. if DOC_REDIRECTS.key?(doc)
  311. return redirect "/#{DOC_REDIRECTS[doc]}#{type}#{rest}", 301
  312. end
  313. if rest && doc == 'angular' && rest.start_with?('/ng')
  314. return redirect "/angularjs/api#{rest}", 301
  315. end
  316. if rest && doc == 'dom'
  317. if rest.start_with?('/windowtimers')
  318. return redirect "/dom#{rest.sub('windowtimers', 'windoworworkerglobalscope')}", 301
  319. end
  320. if rest.start_with?('/window/url.')
  321. return redirect "/dom#{rest.sub('window/url.', 'url/')}", 301
  322. end
  323. if rest.start_with?('/window.')
  324. return redirect "/dom#{rest.sub('window.', 'window/')}", 301
  325. end
  326. if rest.start_with?('/element.')
  327. return redirect "/dom#{rest.sub('element.', 'element/')}", 301
  328. end
  329. if rest.start_with?('/event.')
  330. return redirect "/dom#{rest.sub('event.', 'event/')}", 301
  331. end
  332. if rest.start_with?('/document.')
  333. return redirect "/dom#{rest.sub('document.', 'document/')}", 301
  334. end
  335. end
  336. return 404 unless @doc = find_doc(doc)
  337. if rest.nil?
  338. redirect "/#{doc}#{type}/#{query_string_for_redirection}"
  339. elsif rest.length > 1 && rest.end_with?('/')
  340. redirect "/#{doc}#{type}#{rest[0...-1]}#{query_string_for_redirection}"
  341. elsif user_has_docs?(doc) && supports_js_redirection?
  342. redirect_via_js(request.path)
  343. else
  344. response.headers['Content-Security-Policy'] = settings.csp if settings.csp
  345. erb :other
  346. end
  347. end
  348. not_found do
  349. send_file File.join(settings.public_folder, '404.html'), status: status
  350. end
  351. error do
  352. send_file File.join(settings.public_folder, '500.html'), status: status
  353. end
  354. configure do
  355. require 'rss'
  356. feed = RSS::Maker.make('atom') do |maker|
  357. maker.channel.id = 'tag:devdocs.io,2014:/feed'
  358. maker.channel.title = 'DevDocs'
  359. maker.channel.author = 'DevDocs'
  360. maker.channel.updated = "#{settings.news.first.first}T14:00:00Z"
  361. maker.channel.links.new_link do |link|
  362. link.rel = 'self'
  363. link.href = 'https://devdocs.io/feed.atom'
  364. link.type = 'application/atom+xml'
  365. end
  366. maker.channel.links.new_link do |link|
  367. link.rel = 'alternate'
  368. link.href = 'https://devdocs.io/'
  369. link.type = 'text/html'
  370. end
  371. news.each_with_index do |news, i|
  372. maker.items.new_item do |item|
  373. item.id = "tag:devdocs.io,2014:News/#{settings.news.length - i}"
  374. item.title = news[1].split("\n").first.gsub(/<\/?[^>]*>/, '')
  375. item.description do |desc|
  376. desc.content = news[1..-1].join.gsub("\n", '<br>').gsub('href="/', 'href="https://devdocs.io/')
  377. desc.type = 'html'
  378. end
  379. item.updated = "#{news.first}T14:00:00Z"
  380. item.published = "#{news.first}T14:00:00Z"
  381. item.links.new_link do |link|
  382. link.rel = 'alternate'
  383. link.href = 'https://devdocs.io/'
  384. link.type = 'text/html'
  385. end
  386. end
  387. end
  388. end
  389. set :news_feed, feed.to_s
  390. end
  391. end