app.rb 15 KB

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