app.rb 16 KB

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