app.rb 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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/erubis'
  8. Rack::Mime::MIME_TYPES['.webapp'] = 'application/x-web-app-manifest+json'
  9. configure do
  10. set :sentry_dsn, ENV['SENTRY_DSN']
  11. set :protection, except: [:frame_options, :xss_header]
  12. set :root, Pathname.new(File.expand_path('../..', __FILE__))
  13. set :sprockets, Sprockets::Environment.new(root)
  14. set :assets_prefix, 'assets'
  15. set :assets_path, -> { File.join(public_folder, assets_prefix) }
  16. set :assets_manifest_path, -> { File.join(assets_path, 'manifest.json') }
  17. set :assets_compile, %w(*.png docs.js docs.json application.js application.css application-dark.css)
  18. require 'yajl/json_gem'
  19. set :docs_prefix, 'docs'
  20. set :docs_host, -> { File.join('', docs_prefix) }
  21. set :docs_path, -> { File.join(public_folder, docs_prefix) }
  22. set :docs_manifest_path, -> { File.join(docs_path, 'docs.json') }
  23. set :default_docs, %w(css dom dom_events html http javascript)
  24. set :docs, -> {
  25. Hash[JSON.parse(File.read(docs_manifest_path)).map! { |doc|
  26. doc['full_name'] = doc['name'].dup
  27. doc['full_name'] << " #{doc['version']}" if doc['version']
  28. doc['slug_without_version'] = doc['slug'].split('~').first
  29. [doc['slug'], doc]
  30. }]
  31. }
  32. set :news_path, -> { File.join(root, assets_prefix, 'javascripts', 'news.json') }
  33. set :news, -> { JSON.parse(File.read(news_path)) }
  34. Dir[docs_path, root.join(assets_prefix, '*/')].each do |path|
  35. sprockets.append_path(path)
  36. end
  37. Sprockets::Helpers.configure do |config|
  38. config.environment = sprockets
  39. config.prefix = "/#{assets_prefix}"
  40. config.public_path = public_folder
  41. config.protocol = :relative
  42. end
  43. end
  44. configure :test, :development do
  45. require 'active_support/per_thread_registry'
  46. require 'active_support/cache'
  47. sprockets.cache = ActiveSupport::Cache.lookup_store :file_store, root.join('tmp', 'cache', 'assets', environment.to_s)
  48. end
  49. configure :development do
  50. register Sinatra::Reloader
  51. use BetterErrors::Middleware
  52. BetterErrors.application_root = File.expand_path('..', __FILE__)
  53. BetterErrors.editor = :sublime
  54. end
  55. configure :production do
  56. set :static, false
  57. set :docs_host, '//docs.devdocs.io'
  58. use Rack::ConditionalGet
  59. use Rack::ETag
  60. use Rack::Deflater
  61. use Rack::Static,
  62. root: 'public',
  63. urls: %w(/assets /docs/ /images /favicon.ico /robots.txt /opensearch.xml /manifest.webapp),
  64. header_rules: [
  65. [:all, {'Cache-Control' => 'no-cache, max-age=0'}],
  66. ['/assets', {'Cache-Control' => 'public, max-age=604800'}],
  67. ['/favicon.ico', {'Cache-Control' => 'public, max-age=86400'}],
  68. ['/images', {'Cache-Control' => 'public, max-age=86400'}] ]
  69. sprockets.js_compressor = Uglifier.new output: { beautify: true, indent_level: 0 }
  70. sprockets.css_compressor = :sass
  71. Sprockets::Helpers.configure do |config|
  72. config.digest = true
  73. config.asset_host = 'cdn.devdocs.io'
  74. config.manifest = Sprockets::Manifest.new(sprockets, assets_manifest_path)
  75. end
  76. end
  77. configure :test do
  78. set :docs_manifest_path, -> { File.join(root, 'test', 'files', 'docs.json') }
  79. end
  80. helpers do
  81. include Sinatra::Cookies
  82. include Sprockets::Helpers
  83. def browser
  84. @browser ||= Browser.new(request.user_agent)
  85. end
  86. UNSUPPORTED_IE_VERSIONS = %w(6 7 8 9).freeze
  87. def unsupported_browser?
  88. browser.ie? && UNSUPPORTED_IE_VERSIONS.include?(browser.version)
  89. end
  90. def docs
  91. @docs ||= begin
  92. cookie = cookies[:docs]
  93. if cookie.nil? || cookie.empty?
  94. settings.default_docs
  95. else
  96. cookie.split('/')
  97. end
  98. end
  99. end
  100. def find_doc(slug)
  101. settings.docs[slug] || begin
  102. settings.docs.each do |_, doc|
  103. return doc if doc['slug_without_version'] == slug
  104. end
  105. nil
  106. end
  107. end
  108. def user_has_docs?(slug)
  109. docs.include?(slug) || begin
  110. slug = "#{slug}~"
  111. docs.any? { |_slug| _slug.start_with?(slug) }
  112. end
  113. end
  114. def doc_index_urls
  115. docs.each_with_object [] do |slug, result|
  116. if doc = settings.docs[slug]
  117. result << File.join('', settings.docs_prefix, slug, 'index.json') + "?#{doc['mtime']}"
  118. end
  119. end
  120. end
  121. def doc_index_page?
  122. @doc && (request.path == "/#{@doc['slug']}/" || request.path == "/#{@doc['slug_without_version']}/")
  123. end
  124. def query_string_for_redirection
  125. request.query_string.empty? ? nil : "?#{request.query_string}"
  126. end
  127. def main_stylesheet_path
  128. stylesheet_paths[dark_theme? ? :dark : :default]
  129. end
  130. def alternate_stylesheet_path
  131. stylesheet_paths[dark_theme? ? :default : :dark]
  132. end
  133. def stylesheet_paths
  134. @stylesheet_paths ||= {
  135. default: stylesheet_path('application'),
  136. dark: stylesheet_path('application-dark')
  137. }
  138. end
  139. def app_size
  140. @app_size ||= cookies[:size].nil? ? '18rem' : "#{cookies[:size]}px"
  141. end
  142. def app_layout
  143. cookies[:layout]
  144. end
  145. def app_theme
  146. @app_theme ||= cookies[:dark].nil? ? 'default' : 'dark'
  147. end
  148. def dark_theme?
  149. app_theme == 'dark'
  150. end
  151. def redirect_via_js(path) # courtesy of HTML5 App Cache
  152. response.set_cookie :initial_path, value: path, expires: Time.now + 15, path: '/'
  153. redirect '/', 302
  154. end
  155. def supports_js_redirection?
  156. browser.modern? && !cookies.empty?
  157. end
  158. end
  159. before do
  160. halt erb :unsupported if unsupported_browser?
  161. end
  162. OUT_HOST = 'out.devdocs.io'.freeze
  163. before do
  164. if request.host == OUT_HOST && !request.path.start_with?('/s/')
  165. query_string = "?#{request.query_string}" unless request.query_string.empty?
  166. redirect "http://devdocs.io#{request.path}#{query_string}", 302
  167. end
  168. end
  169. get '/manifest.appcache' do
  170. content_type 'text/cache-manifest'
  171. expires 0, :'no-cache'
  172. erb :manifest
  173. end
  174. get '/' do
  175. return redirect '/' unless request.query_string.empty? # courtesy of HTML5 App Cache
  176. erb :index
  177. end
  178. %w(offline about news help).each do |page|
  179. get "/#{page}" do
  180. if supports_js_redirection?
  181. redirect_via_js "/#{page}"
  182. else
  183. redirect "/#/#{page}", 302
  184. end
  185. end
  186. end
  187. get '/search' do
  188. redirect "/#q=#{params[:q]}"
  189. end
  190. get '/ping' do
  191. 200
  192. end
  193. %w(docs.json application.js application.css).each do |asset|
  194. class_eval <<-CODE, __FILE__, __LINE__ + 1
  195. get '/#{asset}' do
  196. redirect asset_path('#{asset}', protocol: 'http')
  197. end
  198. CODE
  199. end
  200. {
  201. '/s/maxcdn' => 'https://www.maxcdn.com/?utm_source=devdocs&utm_medium=banner&utm_campaign=devdocs',
  202. '/s/shopify' => 'https://www.shopify.com/careers?utm_source=devdocs&utm_medium=banner&utm_campaign=devdocs',
  203. '/s/jetbrains' => 'https://www.jetbrains.com/?utm_source=devdocs&utm_medium=sponsorship&utm_campaign=devdocs',
  204. '/s/jetbrains/ruby' => 'https://www.jetbrains.com/ruby/?utm_source=devdocs&utm_medium=sponsorship&utm_campaign=devdocs',
  205. '/s/jetbrains/python' => 'https://www.jetbrains.com/pycharm/?utm_source=devdocs&utm_medium=sponsorship&utm_campaign=devdocs',
  206. '/s/jetbrains/c' => 'https://www.jetbrains.com/clion/?utm_source=devdocs&utm_medium=sponsorship&utm_campaign=devdocs',
  207. '/s/jetbrains/web' => 'https://www.jetbrains.com/webstorm/?utm_source=devdocs&utm_medium=sponsorship&utm_campaign=devdocs',
  208. '/s/code-school' => 'http://www.codeschool.com/?utm_campaign=devdocs&utm_content=homepage&utm_source=devdocs&utm_medium=sponsorship',
  209. '/s/tw' => 'https://twitter.com/intent/tweet?url=http%3A%2F%2Fdevdocs.io&via=DevDocs&text=All-in-one%2C%20offline%20API%20documentation%20browser%3A',
  210. '/s/fb' => 'https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fdevdocs.io',
  211. '/s/re' => 'http://www.reddit.com/submit?url=http%3A%2F%2Fdevdocs.io&title=All-in-one%2C%20offline%20API%20documentation%20browser&resubmit=true'
  212. }.each do |path, url|
  213. class_eval <<-CODE, __FILE__, __LINE__ + 1
  214. get '#{path}' do
  215. redirect '#{url}'
  216. end
  217. CODE
  218. end
  219. get %r{\A/feed(?:\.atom)?\z} do
  220. content_type 'application/atom+xml'
  221. settings.news_feed
  222. end
  223. DOC_REDIRECTS = {
  224. 'iojs' => 'node',
  225. 'yii1' => 'yii~1.1',
  226. 'python2' => 'python~2.7',
  227. 'xpath' => 'xslt_xpath'
  228. }
  229. get %r{\A/([\w~\.]+)(\-[\w\-]+)?(/.*)?\z} do |doc, type, rest|
  230. return redirect "/#{DOC_REDIRECTS[doc]}#{type}#{rest}" if DOC_REDIRECTS.key?(doc)
  231. return redirect "/angular/api#{rest}", 301 if doc == 'angular' && rest.start_with?('/ng')
  232. return 404 unless @doc = find_doc(doc)
  233. if rest.nil?
  234. redirect "/#{doc}#{type}/#{query_string_for_redirection}"
  235. elsif rest.length > 1 && rest.end_with?('/')
  236. redirect "/#{doc}#{type}#{rest[0...-1]}#{query_string_for_redirection}"
  237. elsif user_has_docs?(doc) && supports_js_redirection?
  238. redirect_via_js(request.path)
  239. else
  240. erb :other
  241. end
  242. end
  243. not_found do
  244. send_file File.join(settings.public_folder, '404.html'), status: status
  245. end
  246. error do
  247. send_file File.join(settings.public_folder, '500.html'), status: status
  248. end
  249. configure do
  250. require 'rss'
  251. feed = RSS::Maker.make('atom') do |maker|
  252. maker.channel.id = 'tag:devdocs.io,2014:/feed'
  253. maker.channel.title = 'DevDocs'
  254. maker.channel.author = 'DevDocs'
  255. maker.channel.updated = "#{settings.news.first.first}T14:00:00Z"
  256. maker.channel.links.new_link do |link|
  257. link.rel = 'self'
  258. link.href = 'http://devdocs.io/feed.atom'
  259. link.type = 'application/atom+xml'
  260. end
  261. maker.channel.links.new_link do |link|
  262. link.rel = 'alternate'
  263. link.href = 'http://devdocs.io/'
  264. link.type = 'text/html'
  265. end
  266. news.each_with_index do |news, i|
  267. maker.items.new_item do |item|
  268. item.id = "tag:devdocs.io,2014:News/#{settings.news.length - i}"
  269. item.title = news[1].split("\n").first.gsub(/<\/?[^>]*>/, '')
  270. item.description do |desc|
  271. desc.content = news[1..-1].join.gsub("\n", '<br>').gsub('href="/', 'href="http://devdocs.io/')
  272. desc.type = 'html'
  273. end
  274. item.updated = "#{news.first}T14:00:00Z"
  275. item.published = "#{news.first}T14:00:00Z"
  276. item.links.new_link do |link|
  277. link.rel = 'alternate'
  278. link.href = 'http://devdocs.io/'
  279. link.type = 'text/html'
  280. end
  281. end
  282. end
  283. end
  284. set :news_feed, feed.to_s
  285. end
  286. end