1
0

app.rb 15 KB

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