app.rb 14 KB

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