app.rb 10 KB

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