app.rb 15 KB

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