app.rb 14 KB

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