app.rb 9.6 KB

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