app.rb 15 KB

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