1
0

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. set :sentry_dsn, ENV['SENTRY_DSN']
  12. set :protection, except: [:frame_options, :xss_header]
  13. set :root, Pathname.new(File.expand_path('../..', __FILE__))
  14. set :sprockets, Sprockets::Environment.new(root)
  15. set :cdn_origin, ''
  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. Dir[docs_path, root.join(assets_prefix, '*/')].each do |path|
  29. sprockets.append_path(path)
  30. end
  31. Sprockets::Helpers.configure do |config|
  32. config.environment = sprockets
  33. config.prefix = "/#{assets_prefix}"
  34. config.public_path = public_folder
  35. config.protocol = :relative
  36. end
  37. end
  38. configure :test, :development do
  39. require 'active_support/per_thread_registry'
  40. require 'active_support/cache'
  41. sprockets.cache = ActiveSupport::Cache.lookup_store :file_store, root.join('tmp', 'cache', 'assets', environment.to_s)
  42. end
  43. configure :development do
  44. register Sinatra::Reloader
  45. use BetterErrors::Middleware
  46. BetterErrors.application_root = File.expand_path('..', __FILE__)
  47. BetterErrors.editor = :sublime
  48. set :csp, "default-src 'self' *; script-src 'self' 'nonce-devdocs' *; font-src 'none'; style-src 'self' 'unsafe-inline' *; img-src 'self' * data:;"
  49. end
  50. configure :production do
  51. set :static, false
  52. set :cdn_origin, 'https://cdn.devdocs.io'
  53. set :docs_origin, '//docs.devdocs.io'
  54. 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:;"
  55. use Rack::ConditionalGet
  56. use Rack::ETag
  57. use Rack::Deflater
  58. use Rack::Static,
  59. root: 'public',
  60. urls: %w(/assets /docs/ /images /favicon.ico /robots.txt /opensearch.xml /mathml.css /manifest.json),
  61. header_rules: [
  62. [:all, { 'Cache-Control' => 'no-cache, max-age=0' }],
  63. ['/assets', { 'Cache-Control' => 'public, max-age=604800' }],
  64. ['/docs', { 'Cache-Control' => 'public, max-age=86400' }],
  65. ['/images', { 'Cache-Control' => 'public, max-age=86400' }],
  66. ['/favicon.ico', { 'Cache-Control' => 'public, max-age=86400' }],
  67. ['/robots.txt', { 'Cache-Control' => 'public, max-age=86400' }],
  68. ['/opensearch.xml', { 'Cache-Control' => 'public, max-age=86400' }],
  69. ['/mathml.css', { 'Cache-Control' => 'public, max-age=86400' }],
  70. ['/manifest.json', { 'Cache-Control' => 'public, max-age=86400' }]
  71. ]
  72. sprockets.js_compressor = Uglifier.new output: { beautify: true, indent_level: 0 }
  73. sprockets.css_compressor = :sass
  74. Sprockets::Helpers.configure do |config|
  75. config.digest = true
  76. config.asset_host = 'cdn.devdocs.io'
  77. config.manifest = Sprockets::Manifest.new(sprockets, assets_manifest_path)
  78. end
  79. end
  80. configure :test do
  81. set :docs_manifest_path, File.join(root, 'test', 'files', 'docs.json')
  82. end
  83. def self.parse_docs
  84. Hash[JSON.parse(File.read(docs_manifest_path)).map! { |doc|
  85. doc['full_name'] = doc['name'].dup
  86. doc['full_name'] << " #{doc['version']}" if doc['version'] && !doc['version'].empty?
  87. doc['slug_without_version'] = doc['slug'].split('~').first
  88. [doc['slug'], doc]
  89. }]
  90. end
  91. def self.parse_news
  92. JSON.parse(File.read(news_path))
  93. end
  94. configure :development, :test do
  95. set :docs, -> { parse_docs }
  96. set :news, -> { parse_news }
  97. end
  98. configure :production do
  99. set :docs, parse_docs
  100. set :news, parse_news
  101. end
  102. helpers do
  103. include Sinatra::Cookies
  104. include Sprockets::Helpers
  105. def memoized_cookies
  106. @memoized_cookies ||= cookies.to_hash
  107. end
  108. def canonical_origin
  109. "https://#{request.host_with_port}"
  110. end
  111. def browser
  112. @browser ||= Browser.new(request.user_agent)
  113. end
  114. UNSUPPORTED_IE_VERSIONS = %w(6 7 8 9).freeze
  115. def unsupported_browser?
  116. browser.ie? && UNSUPPORTED_IE_VERSIONS.include?(browser.version)
  117. end
  118. def docs
  119. @docs ||= begin
  120. cookie = memoized_cookies['docs']
  121. if cookie.nil?
  122. settings.default_docs
  123. else
  124. cookie.split('/')
  125. end
  126. end
  127. end
  128. def find_doc(slug)
  129. settings.docs[slug] || begin
  130. settings.docs.each do |_, doc|
  131. return doc if doc['slug_without_version'] == slug
  132. end
  133. nil
  134. end
  135. end
  136. def user_has_docs?(slug)
  137. docs.include?(slug) || begin
  138. slug = "#{slug}~"
  139. docs.any? { |_slug| _slug.start_with?(slug) }
  140. end
  141. end
  142. def doc_index_urls
  143. docs.each_with_object [] do |slug, result|
  144. if doc = settings.docs[slug]
  145. result << File.join('', settings.docs_prefix, slug, 'index.json') + "?#{doc['mtime']}"
  146. end
  147. end
  148. end
  149. def doc_index_page?
  150. @doc && (request.path == "/#{@doc['slug']}/" || request.path == "/#{@doc['slug_without_version']}/")
  151. end
  152. def query_string_for_redirection
  153. request.query_string.empty? ? nil : "?#{request.query_string}"
  154. end
  155. def manifest_asset_urls
  156. @@manifest_asset_urls ||= [
  157. javascript_path('application', asset_host: false),
  158. stylesheet_path('application'),
  159. stylesheet_path('application-dark'),
  160. image_path('docs-1.png'),
  161. image_path('docs-1@2x.png'),
  162. image_path('docs-2.png'),
  163. image_path('docs-2@2x.png'),
  164. asset_path('docs.js')
  165. ]
  166. end
  167. def main_stylesheet_path
  168. stylesheet_paths[dark_theme? ? :dark : :default]
  169. end
  170. def alternate_stylesheet_path
  171. stylesheet_paths[dark_theme? ? :default : :dark]
  172. end
  173. def stylesheet_paths
  174. @@stylesheet_paths ||= {
  175. default: stylesheet_path('application'),
  176. dark: stylesheet_path('application-dark')
  177. }
  178. end
  179. def app_size
  180. @app_size ||= memoized_cookies['size'].nil? ? '20rem' : "#{memoized_cookies['size']}px"
  181. end
  182. def app_layout
  183. memoized_cookies['layout']
  184. end
  185. def app_theme
  186. @app_theme ||= memoized_cookies['dark'].nil? ? 'default' : 'dark'
  187. end
  188. def dark_theme?
  189. app_theme == 'dark'
  190. end
  191. def redirect_via_js(path) # courtesy of HTML5 App Cache
  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 '/manifest.appcache' do
  210. content_type 'text/cache-manifest'
  211. expires 0, :'no-cache'
  212. erb :manifest
  213. end
  214. get '/' do
  215. return redirect "/#q=#{params[:q]}" if params[:q]
  216. return redirect '/' unless request.query_string.empty? # courtesy of HTML5 App Cache
  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