app.rb 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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 'thor'
  41. load 'tasks/sprites.thor'
  42. SpritesCLI.new.invoke(:generate)
  43. require 'active_support/per_thread_registry'
  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 :cdn_origin, 'https://cdn.devdocs.io'
  57. set :docs_origin, '//docs.devdocs.io'
  58. 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:;"
  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.asset_host = 'cdn.devdocs.io'
  81. config.manifest = Sprockets::Manifest.new(sprockets, assets_manifest_path)
  82. end
  83. end
  84. configure :test do
  85. set :docs_manifest_path, File.join(root, 'test', 'files', 'docs.json')
  86. end
  87. def self.parse_docs
  88. Hash[JSON.parse(File.read(docs_manifest_path)).map! { |doc|
  89. doc['full_name'] = doc['name'].dup
  90. doc['full_name'] << " #{doc['version']}" if doc['version'] && !doc['version'].empty?
  91. doc['slug_without_version'] = doc['slug'].split('~').first
  92. [doc['slug'], doc]
  93. }]
  94. end
  95. def self.parse_news
  96. JSON.parse(File.read(news_path))
  97. end
  98. configure :development, :test do
  99. set :docs, -> { parse_docs }
  100. set :news, -> { parse_news }
  101. end
  102. configure :production do
  103. set :docs, parse_docs
  104. set :news, parse_news
  105. end
  106. helpers do
  107. include Sinatra::Cookies
  108. include Sprockets::Helpers
  109. def memoized_cookies
  110. @memoized_cookies ||= cookies.to_hash
  111. end
  112. def canonical_origin
  113. "https://#{request.host_with_port}"
  114. end
  115. def browser
  116. @browser ||= Browser.new(request.user_agent)
  117. end
  118. UNSUPPORTED_IE_VERSIONS = %w(6 7 8 9).freeze
  119. def unsupported_browser?
  120. browser.ie? && UNSUPPORTED_IE_VERSIONS.include?(browser.version)
  121. end
  122. def docs
  123. @docs ||= begin
  124. cookie = memoized_cookies['docs']
  125. if cookie.nil?
  126. settings.default_docs
  127. else
  128. cookie.split('/')
  129. end
  130. end
  131. end
  132. def find_doc(slug)
  133. settings.docs[slug] || begin
  134. settings.docs.each do |_, doc|
  135. return doc if doc['slug_without_version'] == slug
  136. end
  137. nil
  138. end
  139. end
  140. def user_has_docs?(slug)
  141. docs.include?(slug) || begin
  142. slug = "#{slug}~"
  143. docs.any? { |_slug| _slug.start_with?(slug) }
  144. end
  145. end
  146. def doc_index_urls
  147. docs.each_with_object [] do |slug, result|
  148. if doc = settings.docs[slug]
  149. result << File.join('', settings.docs_prefix, slug, 'index.json') + "?#{doc['mtime']}"
  150. end
  151. end
  152. end
  153. def doc_index_page?
  154. @doc && (request.path == "/#{@doc['slug']}/" || request.path == "/#{@doc['slug_without_version']}/")
  155. end
  156. def query_string_for_redirection
  157. request.query_string.empty? ? nil : "?#{request.query_string}"
  158. end
  159. def manifest_asset_urls
  160. @@manifest_asset_urls ||= [
  161. javascript_path('application', asset_host: false),
  162. stylesheet_path('application'),
  163. image_path('sprites/docs.png'),
  164. image_path('sprites/docs@2x.png'),
  165. asset_path('docs.js')
  166. ]
  167. end
  168. def app_size
  169. @app_size ||= memoized_cookies['size'].nil? ? '20rem' : "#{memoized_cookies['size']}px"
  170. end
  171. def app_layout
  172. memoized_cookies['layout']
  173. end
  174. def app_theme
  175. @app_theme ||= memoized_cookies['dark'].nil? ? 'default' : 'dark'
  176. end
  177. def dark_theme?
  178. app_theme == 'dark'
  179. end
  180. def redirect_via_js(path) # courtesy of HTML5 App Cache
  181. response.set_cookie :initial_path, value: path, expires: Time.now + 15, path: '/'
  182. redirect '/', 302
  183. end
  184. def supports_js_redirection?
  185. browser.modern? && !memoized_cookies.empty?
  186. end
  187. end
  188. before do
  189. halt erb :unsupported if unsupported_browser?
  190. end
  191. OUT_HOST = 'out.devdocs.io'.freeze
  192. before do
  193. if request.host == OUT_HOST && !request.path.start_with?('/s/')
  194. query_string = "?#{request.query_string}" unless request.query_string.empty?
  195. redirect "https://devdocs.io#{request.path}#{query_string}", 302
  196. end
  197. end
  198. get '/manifest.appcache' do
  199. content_type 'text/cache-manifest'
  200. expires 0, :'no-cache'
  201. erb :manifest
  202. end
  203. get '/' do
  204. return redirect "/#q=#{params[:q]}" if params[:q]
  205. return redirect '/' unless request.query_string.empty? # courtesy of HTML5 App Cache
  206. response.headers['Content-Security-Policy'] = settings.csp if settings.csp
  207. erb :index
  208. end
  209. %w(settings offline about news help).each do |page|
  210. get "/#{page}" do
  211. if supports_js_redirection?
  212. redirect_via_js "/#{page}"
  213. else
  214. redirect "/#/#{page}", 302
  215. end
  216. end
  217. end
  218. get '/search' do
  219. redirect "/#q=#{params[:q]}"
  220. end
  221. get '/ping' do
  222. 200
  223. end
  224. %w(docs.json application.js application.css).each do |asset|
  225. class_eval <<-CODE, __FILE__, __LINE__ + 1
  226. get '/#{asset}' do
  227. redirect asset_path('#{asset}', protocol: 'http')
  228. end
  229. CODE
  230. end
  231. {
  232. '/s/maxcdn' => 'https://www.maxcdn.com/?utm_source=devdocs&utm_medium=banner&utm_campaign=devdocs',
  233. '/s/shopify' => 'https://www.shopify.com/careers?utm_source=devdocs&utm_medium=banner&utm_campaign=devdocs',
  234. '/s/jetbrains' => 'https://www.jetbrains.com/?utm_source=devdocs&utm_medium=sponsorship&utm_campaign=devdocs',
  235. '/s/jetbrains/ruby' => 'https://www.jetbrains.com/ruby/?utm_source=devdocs&utm_medium=sponsorship&utm_campaign=devdocs',
  236. '/s/jetbrains/python' => 'https://www.jetbrains.com/pycharm/?utm_source=devdocs&utm_medium=sponsorship&utm_campaign=devdocs',
  237. '/s/jetbrains/c' => 'https://www.jetbrains.com/clion/?utm_source=devdocs&utm_medium=sponsorship&utm_campaign=devdocs',
  238. '/s/jetbrains/web' => 'https://www.jetbrains.com/webstorm/?utm_source=devdocs&utm_medium=sponsorship&utm_campaign=devdocs',
  239. '/s/code-school' => 'https://www.codeschool.com/?utm_campaign=devdocs&utm_content=homepage&utm_source=devdocs&utm_medium=sponsorship',
  240. '/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',
  241. '/s/fb' => 'https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fdevdocs.io',
  242. '/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'
  243. }.each do |path, url|
  244. class_eval <<-CODE, __FILE__, __LINE__ + 1
  245. get '#{path}' do
  246. redirect '#{url}'
  247. end
  248. CODE
  249. end
  250. %w(/maxcdn /maxcdn/).each do |path|
  251. class_eval <<-CODE, __FILE__, __LINE__ + 1
  252. get '#{path}' do
  253. 410
  254. end
  255. CODE
  256. end
  257. {
  258. '/tips' => '/help',
  259. '/css-data-types/' => '/css-values-units/',
  260. '/css-at-rules/' => '/?q=css%20%40',
  261. '/dom/window/setinterval' => '/dom/windoworworkerglobalscope/setinterval',
  262. '/html/article' => '/html/element/article',
  263. '/html-html5/' => 'html-elements/',
  264. '/html-standard/' => 'html-elements/',
  265. '/http-status-codes/' => '/http-status/',
  266. '/ruby/bignum' => '/ruby~2.3/bignum',
  267. '/ruby/fixnum' => '/ruby~2.3/fixnum',
  268. }.each do |path, url|
  269. class_eval <<-CODE, __FILE__, __LINE__ + 1
  270. get '#{path}' do
  271. redirect '#{url}', 301
  272. end
  273. CODE
  274. end
  275. get %r{/feed(?:\.atom)?} do
  276. content_type 'application/atom+xml'
  277. settings.news_feed
  278. end
  279. DOC_REDIRECTS = {
  280. 'iojs' => 'node',
  281. 'node_lts' => 'node~6_lts',
  282. 'node~4.2_lts' => 'node~4_lts',
  283. 'yii1' => 'yii~1.1',
  284. 'python2' => 'python~2.7',
  285. 'xpath' => 'xslt_xpath',
  286. 'angular~4_typescript' => 'angular',
  287. 'angular~2_typescript' => 'angular~2',
  288. 'angular~2.0_typescript' => 'angular~2',
  289. 'angular~1.5' => 'angularjs~1.5',
  290. 'angular~1.4' => 'angularjs~1.4',
  291. 'angular~1.3' => 'angularjs~1.3',
  292. 'angular~1.2' => 'angularjs~1.2',
  293. 'codeigniter~3.0' => 'codeigniter~3',
  294. 'webpack~2' => 'webpack'
  295. }
  296. get %r{/([\w~\.%]+)(\-[\w\-]+)?(/.*)?} do |doc, type, rest|
  297. doc.sub! '%7E', '~'
  298. if DOC_REDIRECTS.key?(doc)
  299. return redirect "/#{DOC_REDIRECTS[doc]}#{type}#{rest}", 301
  300. end
  301. if rest && doc == 'angular' && rest.start_with?('/ng')
  302. return redirect "/angularjs/api#{rest}", 301
  303. end
  304. if rest && doc == 'dom'
  305. if rest.start_with?('/windowtimers')
  306. return redirect "/dom#{rest.sub('windowtimers', 'windoworworkerglobalscope')}", 301
  307. end
  308. if rest.start_with?('/window/url.')
  309. return redirect "/dom#{rest.sub('window/url.', 'url/')}", 301
  310. end
  311. if rest.start_with?('/window.')
  312. return redirect "/dom#{rest.sub('window.', 'window/')}", 301
  313. end
  314. if rest.start_with?('/element.')
  315. return redirect "/dom#{rest.sub('element.', 'element/')}", 301
  316. end
  317. if rest.start_with?('/event.')
  318. return redirect "/dom#{rest.sub('event.', 'event/')}", 301
  319. end
  320. if rest.start_with?('/document.')
  321. return redirect "/dom#{rest.sub('document.', 'document/')}", 301
  322. end
  323. end
  324. return 404 unless @doc = find_doc(doc)
  325. if rest.nil?
  326. redirect "/#{doc}#{type}/#{query_string_for_redirection}"
  327. elsif rest.length > 1 && rest.end_with?('/')
  328. redirect "/#{doc}#{type}#{rest[0...-1]}#{query_string_for_redirection}"
  329. elsif user_has_docs?(doc) && supports_js_redirection?
  330. redirect_via_js(request.path)
  331. else
  332. response.headers['Content-Security-Policy'] = settings.csp if settings.csp
  333. erb :other
  334. end
  335. end
  336. not_found do
  337. send_file File.join(settings.public_folder, '404.html'), status: status
  338. end
  339. error do
  340. send_file File.join(settings.public_folder, '500.html'), status: status
  341. end
  342. configure do
  343. require 'rss'
  344. feed = RSS::Maker.make('atom') do |maker|
  345. maker.channel.id = 'tag:devdocs.io,2014:/feed'
  346. maker.channel.title = 'DevDocs'
  347. maker.channel.author = 'DevDocs'
  348. maker.channel.updated = "#{settings.news.first.first}T14:00:00Z"
  349. maker.channel.links.new_link do |link|
  350. link.rel = 'self'
  351. link.href = 'https://devdocs.io/feed.atom'
  352. link.type = 'application/atom+xml'
  353. end
  354. maker.channel.links.new_link do |link|
  355. link.rel = 'alternate'
  356. link.href = 'https://devdocs.io/'
  357. link.type = 'text/html'
  358. end
  359. news.each_with_index do |news, i|
  360. maker.items.new_item do |item|
  361. item.id = "tag:devdocs.io,2014:News/#{settings.news.length - i}"
  362. item.title = news[1].split("\n").first.gsub(/<\/?[^>]*>/, '')
  363. item.description do |desc|
  364. desc.content = news[1..-1].join.gsub("\n", '<br>').gsub('href="/', 'href="https://devdocs.io/')
  365. desc.type = 'html'
  366. end
  367. item.updated = "#{news.first}T14:00:00Z"
  368. item.published = "#{news.first}T14:00:00Z"
  369. item.links.new_link do |link|
  370. link.rel = 'alternate'
  371. link.href = 'https://devdocs.io/'
  372. link.type = 'text/html'
  373. end
  374. end
  375. end
  376. end
  377. set :news_feed, feed.to_s
  378. end
  379. end