From: Michal Fojtik <[email protected]>
Signed-off-by: Michal fojtik <[email protected]> --- server/lib/sinatra/lazy_auth.rb | 75 ------ server/lib/sinatra/rabbit.rb | 441 --------------------------------- server/lib/sinatra/rack_cimi.rb | 33 --- server/lib/sinatra/rack_runtime.rb | 47 ---- server/lib/sinatra/rack_syslog.rb | 93 ------- server/lib/sinatra/sinatra_verbose.rb | 73 ------ server/lib/sinatra/static_assets.rb | 99 -------- server/lib/sinatra/url_for.rb | 93 ------- 8 files changed, 954 deletions(-) delete mode 100644 server/lib/sinatra/lazy_auth.rb delete mode 100644 server/lib/sinatra/rabbit.rb delete mode 100644 server/lib/sinatra/rack_cimi.rb delete mode 100644 server/lib/sinatra/rack_runtime.rb delete mode 100644 server/lib/sinatra/rack_syslog.rb delete mode 100644 server/lib/sinatra/sinatra_verbose.rb delete mode 100644 server/lib/sinatra/static_assets.rb delete mode 100644 server/lib/sinatra/url_for.rb diff --git a/server/lib/sinatra/lazy_auth.rb b/server/lib/sinatra/lazy_auth.rb deleted file mode 100644 index fb94dd9..0000000 --- a/server/lib/sinatra/lazy_auth.rb +++ /dev/null @@ -1,75 +0,0 @@ -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -require 'sinatra/base' - -# Lazy Basic HTTP authentication. Authentication is only forced when the -# credentials are actually needed. -module Sinatra - module LazyAuth - class LazyCredentials - def initialize(app) - @app = app - @provided = false - end - - def user - credentials! - @user - end - - def password - credentials! - @password - end - - def provided? - @provided - end - - private - def credentials! - if ENV["API_USER"] && ENV["API_PASSWORD"] - @user = ENV["API_USER"] - @password = ENV["API_PASSWORD"] - @provided = true - end - unless provided? - auth = Rack::Auth::Basic::Request.new(@app.request.env) - @app.authorize! unless auth.provided? && auth.basic? && auth.credentials - @user = auth.credentials[0] - @password = auth.credentials[1] - @provided = true - end - end - - end - - def authorize! - r = "#{driver_symbol}-deltacloud@#{HOSTNAME}" - response['WWW-Authenticate'] = %(Basic realm="#{r}") - throw(:halt, [401, report_error(401)]) - end - - # Request the current user's credentials. Actual credentials are only - # requested when an attempt is made to get the user name or password - def credentials - LazyCredentials.new(self) - end - end - - helpers LazyAuth -end diff --git a/server/lib/sinatra/rabbit.rb b/server/lib/sinatra/rabbit.rb deleted file mode 100644 index 5c63fd9..0000000 --- a/server/lib/sinatra/rabbit.rb +++ /dev/null @@ -1,441 +0,0 @@ -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -require 'sinatra/base' -require 'sinatra/url_for' -require 'deltacloud/validation' -require 'deltacloud/backend_capability' - -module Sinatra - - module Rabbit - - def self.routes - @routes ||= [] - end - - class DuplicateParamException < Deltacloud::ExceptionHandler::DeltacloudException; end - class DuplicateOperationException < Deltacloud::ExceptionHandler::DeltacloudException; end - class DuplicateCollectionException < Deltacloud::ExceptionHandler::DeltacloudException; end - class UnsupportedCollectionException < Deltacloud::ExceptionHandler::DeltacloudException - def initialize - # The server understood the request, but is refusing to fulfill it. Authorization will not help and the request - # SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request - # has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish - # to make this information available to the client, the status code 404 (Not Found) can be used instead. - super(403, 'UnsupportedCollection', "Requested collection is not supported for current provider", []) - end - end - - class Operation - attr_reader :name, :method, :collection, :member - - include ::Deltacloud::BackendCapability - include ::Deltacloud::Validation - include ::ApplicationHelper - - STANDARD = { - :new => { :method => :get, :member => false, :form => true }, - :index => { :method => :get, :member => false }, - :show => { :method => :get, :member => true }, - :create => { :method => :post, :member => false }, - :update => { :method => :put, :member => true }, - :destroy => { :method => :delete, :member => true } - } - - def initialize(coll, name, opts, &block) - @name = name.to_sym - opts = STANDARD[@name].merge(opts) if standard? - @path_generator = opts[:path_generator] - @collection, @standard = coll, opts[:standard] - raise "No method for operation #{name}" unless opts[:method] - @method = opts[:method].to_sym - @member = opts[:member] - @description = "" - instance_eval(&block) if block_given? - generate_documentation - generate_options - end - - def http_method - @method - end - - def standard? - STANDARD.keys.include?(name) || @standard - end - - def form? - STANDARD[name] and STANDARD[name][:form] - end - - def description(text="") - return @description if text.blank? - @description = text - end - - def generate_documentation - coll, oper = @collection, self - Rabbit::routes << [:get, "#{settings.root_url}/docs/#{@collection.name}/#{@name}"] - ::Sinatra::Application.get("#{settings.root_url}/docs/#{@collection.name}/#{@name}") do - @collection, @operation = coll, oper - @features = driver.features_for_operation(coll.name, oper.name) - respond_to do |format| - format.html { haml :'docs/operation' } - format.xml { haml :'docs/operation' } - end - end - end - - def generate_options - current_operation = self - Rabbit::routes << [:options, "#{settings.root_url}/#{current_operation.collection.name}/#{current_operation.name}"] - ::Sinatra::Application.options("#{settings.root_url}/#{current_operation.collection.name}/#{current_operation.name}") do - required_params = current_operation.effective_params(driver).collect do |name, validation| - name.to_s if validation.type.eql?(:required) - end.compact.join(',') - optional_params = current_operation.effective_params(driver).collect do |name, validation| - name.to_s if validation.type.eql?(:optional) - end.compact.join(',') - headers 'X-Required-Parameters' => required_params - headers 'X-Optional-Parameters' => optional_params - [200, ''] - end - end - - def control(&block) - op = self - @control = Proc.new do - op.collection.check_supported(driver) - op.check_capability(driver) - op.validate(driver, op.effective_params(driver), params, credentials) - instance_eval(&block) - end - end - - def member? - if standard? - @member || STANDARD[name][:member] - else - @member - end - end - - def path(args = {}) - return @path_generator.call(self) if @path_generator - if member? - if standard? - "#{@collection.name}/:id" - else - "#{@collection.name}/:id/#{name}" - end - else - if form? - "#{@collection.name}/#{name}" - else - "#{@collection.name}" - end - end - end - - def generate - Rabbit::routes << [@method, "#{settings.root_url}/#{path}"] - ::Sinatra::Application.send(@method, "#{settings.root_url}/#{path}", {}, &@control) - # Set up some Rails-like URL helpers - if name == :index - gen_route "#{@collection.name}_url" - elsif name == :show - gen_route "#{@collection.name.to_s.singularize}_url" - else - gen_route "#{name}_#{@collection.name.to_s.singularize}_url" - end - end - - # Return a hash of all params, the params statically defined for this - # operation plus the params defined by any features in the +driver+ - # that might modify this operation - def effective_params(driver) - driver.features(@collection.name).collect do |f| - f.decl.operation(@name) - end.flatten.select { |op| op }.inject(params.dup) do |result, fop| - fop.params.each_key do |k| - if result.has_key?(k) - raise DuplicateParamException, "Parameter '#{k}' for operation #{fop.name} in collection #{@collection.name}" - else - result[k] = fop.params[k] - end - end - result - end - end - - private - def gen_route(name) - route_url = path - if @member - ::Sinatra::Application.send(:define_method, name) do |id, *args| - url = query_url(route_url, args[0]) - api_url_for url.gsub(/:id/, id.to_s), :full - end - else - ::Sinatra::Application.send(:define_method, name) do |*args| - url = query_url(route_url, args[0]) - api_url_for url, :full - end - end - end - end - - class Collection - attr_reader :name, :operations, :subcollections - - def initialize(name, options={}, &block) - @name = name - @description = "" - @operations, @subcollections = {}, {} - @global = options[:global] || false - instance_eval(&block) if block_given? - generate_documentation - generate_head - generate_options - end - - def subcollection? - self.class == SubCollection - end - - # Set/Return description for collection - # If first parameter is not present, full description will be - # returned. - def description(text='') - return @description if text.blank? - @description = text - end - - # Mark this collection as global, i.e. independent of any specific - # driver - def global! - @global = true - end - - # Return +true+ if this collection is global, i.e. independent of any - # specific driver - def global? - @global - end - - def generate_head - current_collection = self - Rabbit::routes << [:head, "#{settings.root_url}/#{name}"] - ::Sinatra::Application.head("#{settings.root_url}/#{name}") do - methods_allowed = current_collection.operations.collect { |o| o[1].method.to_s.upcase }.uniq.join(',') - headers 'Allow' => "HEAD,OPTIONS,#{methods_allowed}" - [200, ''] - end - end - - def generate_options - current_collection = self - Rabbit::routes << [:options, "#{settings.root_url}/#{name}"] - ::Sinatra::Application.options("#{settings.root_url}/#{name}") do - operations_allowed = current_collection.operations.collect { |o| o[0] }.join(',') - headers 'X-Operations-Allowed' => operations_allowed - [200, ''] - end - end - - def generate_documentation - coll = self - Rabbit::routes << [:get, "#{settings.root_url}/docs/#{@name}"] - ::Sinatra::Application.get("#{settings.root_url}/docs/#{@name}") do - coll.check_supported(driver) - @collection = coll - @operations = coll.operations - @features = driver.features(coll.name) - respond_to do |format| - format.html { haml :'docs/collection' } - format.xml { haml :'docs/collection' } - end - end - end - - # Add a new operation for this collection. For the standard REST - # operations :index, :show, :update, and :destroy, we already know - # what method to use and whether this is an operation on the URL for - # individual elements or for the whole collection. - # - # For non-standard operations, options must be passed: - # :method : one of the HTTP methods - # :member : whether this is an operation on the collection or an - # individual element (FIXME: custom operations on the - # collection will use a nonsensical URL) The URL for the - # operation is the element URL with the name of the operation - # appended - # - # This also defines a helper method like show_instance_url that returns - # the URL to this operation (in request context) - def operation(name, opts = {}, &block) - if @operations.keys.include?(name) - raise DuplicateOperationException::new(500, "DuplicateOperation", "Operation #{name} is already defined", []) - end - @operations[name] = Operation.new(self, name, opts, &block) - end - - def collection(name, opts={}, &block) - if subcollections.keys.include?(name) - raise DuplicateOperationException::new(500, "DuplicateSubcollection", "Subcollection #{name} is already defined", []) - end - subcollections[name] = SubCollection.new(self, name, opts, &block) - subcollections[name].generate - end - - def generate - operations.values.reject { |op| op.member }.each { |o| o.generate } - operations.values.select { |op| op.member }.each { |o| o.generate } - app = ::Sinatra::Application - collname = name # Work around Ruby's weird scoping/capture - app.send(:define_method, "#{name.to_s.singularize}_url") do |id| - api_url_for "#{collname}/#{id}", :full - end - if index_op = operations[:index] - app.send(:define_method, "#{name}_url") do - api_url_for index_op.path.gsub(/\/\?$/,''), :full - end - end - end - - def check_supported(driver) - unless global? || driver.has_collection?(@name) || self.kind_of?(Sinatra::Rabbit::SubCollection) - raise UnsupportedCollectionException - end - end - end - - class SubCollection < Collection - - attr_accessor :parent - - def initialize(parent, name, opts={}, &block) - self.parent = parent - super(name, &block) - end - - def operation(name, opts = {}, &block) - if @operations.keys.include?(name) - raise DuplicateOperationException::new(500, "DuplicateOperation", "Operation #{name} is already defined", []) - end - # Preserve self as local variable to workaround Ruby namespace - # weirdness - c = self - path_generator = Proc.new do |obj| - if obj.member? - if obj.standard? - "#{parent.name}/:#{parent.name.to_s.singularize}/:#{c.name.to_s.singularize}" - else - "#{parent.name}/:#{parent.name.to_s.singularize}/:#{c.name.to_s.singularize}/#{name}" - end - else - if obj.form? - "#{parent.name}/:id/:#{parent.name.to_s.singularize}/#{obj.name}" - else - "#{parent.name}/:#{parent.name.to_s.singularize}" - end - end - end - opts.merge!({ - :path_generator => path_generator - }) - @operations[name] = Operation.new(self, name, opts, &block) - end - - def generate - operations.values.reject { |op| op.member }.each { |o| o.generate } - operations.values.select { |op| op.member }.each { |o| o.generate } - app = ::Sinatra::Application - collname = name # Work around Ruby's weird scoping/capture - app.send(:define_method, "#{parent.name.to_s}_#{name.to_s.singularize}_url") do |id, subid| - api_url_for "#{collname}/#{id}/#{subid}", :full - end - if index_op = operations[:index] - app.send(:define_method, "#{parent.name.to_s}_#{name}_url") do - api_url_for index_op.path.gsub(/\/\?$/,''), :full - end - end - end - - end - - def collections - @collections ||= {} - end - - # Create a new collection. NAME should be the pluralized name of the - # collection. - # - # Adds a helper method #{name}_url which returns the URL to the :index - # operation on this collection. - def collection(name, &block) - raise DuplicateCollectionException if collections[name] - collections[name] = Collection.new(name, &block) - collections[name].generate - end - - def global_collection(name, &block) - raise DuplicateCollectionException if collections[name] - collections[name] = Collection.new(name, { :global => true }, &block) - collections[name].generate - end - - # Make sure this collection can be accessed, regardless of whether the - # driver supports it or not - def global_collection(name, &block) - raise DuplicateCollectionException if collections[name] - collections[name] = Collection.new(name, :global => true, &block) - collections[name].generate - end - end - - module RabbitHelper - def query_url(url, params) - return url if params.nil? || params.empty? - url + "?#{URI.escape(params.collect{|k,v| "#{k}=#{v}"}.join('&'))}" - end - - def entry_points - collections.values.select { |coll| - coll.global? || driver.has_collection?(coll.name) - }.inject([]) do |m, coll| - url = api_url_for coll.operations[:index].path, :full - m << [ coll.name, url ] - end - end - end - - register Rabbit - helpers RabbitHelper -end - -# In Sinatra < 1.2 there was no helper to create OPTIONS route -unless Sinatra::Base.respond_to? :options - configure do - class << Sinatra::Base - def options(path, opts={}, &block) - route 'OPTIONS', path, opts, &block - end - end - Sinatra::Delegator.delegate :options - end -end diff --git a/server/lib/sinatra/rack_cimi.rb b/server/lib/sinatra/rack_cimi.rb deleted file mode 100644 index 6d5ea78..0000000 --- a/server/lib/sinatra/rack_cimi.rb +++ /dev/null @@ -1,33 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -module Rack - # Automatically sets the X-CIMI-Specification-Version header on all responses. - # - class CIMI - - def initialize(app, no_cache_control = nil, cache_control = nil) - @app = app - end - - def call(env) - status, headers, body = @app.call(env) - headers['X-CIMI-Specification-Version'] = '0.0.66' - [status, headers, body] - end - - end -end - diff --git a/server/lib/sinatra/rack_runtime.rb b/server/lib/sinatra/rack_runtime.rb deleted file mode 100644 index dc56fc7..0000000 --- a/server/lib/sinatra/rack_runtime.rb +++ /dev/null @@ -1,47 +0,0 @@ -# Copyright (c) 2008 The Committers - -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL -# THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -module Rack - # Sets an "X-Runtime" response header, indicating the response - # time of the request, in seconds - # - # You can put it right before the application to see the processing - # time, or before all the other middlewares to include time for them, - # too. - class Runtime - def initialize(app, name = nil) - @app = app - @header_name = "X-Runtime" - @header_name << "-#{name}" if name - end - - def call(env) - start_time = Time.now - status, headers, body = @app.call(env) - request_time = Time.now - start_time - - if !headers.has_key?(@header_name) - headers[@header_name] = "%0.6f" % request_time - end - - [status, headers, body] - end - end -end - diff --git a/server/lib/sinatra/rack_syslog.rb b/server/lib/sinatra/rack_syslog.rb deleted file mode 100644 index 5565179..0000000 --- a/server/lib/sinatra/rack_syslog.rb +++ /dev/null @@ -1,93 +0,0 @@ -begin - require 'syslog' - USE_SYSLOG = true -rescue LoadError => e - USE_SYSLOG = false -end - -require 'sinatra/body_proxy' - -class SyslogFile < File - - def initialize - @log = USE_SYSLOG ? Syslog.open($0, Syslog::LOG_PID | Syslog::LOG_LOCAL5) : Logger.new(STDOUT) - end - - def write(string) - @log.warning(string) if string.strip.length > 0 - return string.chars.count - end - - def info(msg) - @log.info("%s" % msg) - end - - def err(msg) - @log.err("%s" % msg) - end - - alias :warning :err - -end - -# Code bellow was originaly copied from Rack::CommonLogger -# https://raw.github.com/rack/rack/master/lib/rack/commonlogger.rb - -module Rack - # Rack::CommonLogger forwards every request to an +app+ given, and - # logs a line in the Apache common log format to the +logger+, or - # rack.errors by default. - class SyslogLogger - - # Common Log Format: http://httpd.apache.org/docs/1.3/logs.html#common - # lilith.local - - [07/Aug/2006 23:58:02] "GET / HTTP/1.1" 500 - - # %{%s - %s [%s] "%s %s%s %s" %d %s\n} % - FORMAT = %{%s - %s [%s] "%s %s%s %s" %d %s %0.4f} - - def initialize(app, logger=nil) - @app = app - @logger = logger || @app.settings.logger || $stdout - end - - def call(env) - began_at = Time.now - status, header, body = @app.call(env) - header = Utils::HeaderHash.new(header) - body = Rack::BodyProxy.new(body) do - log(env, status, header, began_at) - end - body.close - [status, header, body] - end - - def log(env, status, header, began_at) - now = Time.now - length = extract_content_length(header) - - if status.to_s =~ /5(\d{2})/ - method = :err - else - method = :info - end - - logger = @logger - logger.send(method, FORMAT % [ - env['HTTP_X_FORWARDED_FOR'] || env["REMOTE_ADDR"] || "-", - env["REMOTE_USER"] || "-", - now.strftime("%d/%b/%Y %H:%M:%S"), - env["REQUEST_METHOD"], - env["PATH_INFO"], - env["QUERY_STRING"].empty? ? "" : "?"+env["QUERY_STRING"], - env["HTTP_VERSION"], - status.to_s[0..3], - length, - now - began_at ]) - end - - def extract_content_length(headers) - value = headers['Content-Length'] or return '-' - value.to_s == '0' ? '-' : value - end - end -end - diff --git a/server/lib/sinatra/sinatra_verbose.rb b/server/lib/sinatra/sinatra_verbose.rb deleted file mode 100644 index c016ec0..0000000 --- a/server/lib/sinatra/sinatra_verbose.rb +++ /dev/null @@ -1,73 +0,0 @@ -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -require 'sinatra/base' - -module Sinatra - module VerboseLogger - - module Helpers - - def info(message) - puts sprintf("\033[1;34m[INFO: #{caller_method_name}]\033[0m: %s", message.inspect) - end - - alias :debug :info - - def warn(message) - puts sprintf("\033[1;31m[WARN: #{caller_method_name}]\033[0m: %s", message.inspect) - end - - private - - def caller_method_name - caller(2).first - end - - end - - def enable_verbose_logging! - disable :logging - before { - puts sprintf("\n\033[1;29mProcessing %s\033[0m (for %s at #{Time.now}) [%s] [\033[1;29m%s\033[0m]", - request.path_info, request.ip, request.request_method, driver_name) - puts "Parameters: #{params.inspect}" - if provider=Thread::current[:provider] || ENV['API_PROVIDER'] - puts "Provider: #{provider}" - end - puts "Authentication: #{request.env['HTTP_AUTHORIZATION'].split(' ').first}" if request.env['HTTP_AUTHORIZATION'] - puts "Server: #{request.env['SERVER_SOFTWARE']}" - puts "Accept: #{request.env['HTTP_ACCEPT']}" - puts - } - after { - puts sprintf("\nCompleted in \033[1;29m%4f\033[0m | %4f | %s | \033[1;36m%s\033[0m | %s\n", - response.header['X-Backend-Runtime'] || 0, response.header['X-Runtime'] || 0, response.status, response.content_type, request.url) - } - end - - def self.registered(app) - app.helpers VerboseLogger::Helpers - app.enable_verbose_logging! if ENV['API_VERBOSE'] - end - end -end - -Sinatra::Application.register Sinatra::VerboseLogger - -Deltacloud::BaseDriver.class_eval do - include Sinatra::VerboseLogger::Helpers -end diff --git a/server/lib/sinatra/static_assets.rb b/server/lib/sinatra/static_assets.rb deleted file mode 100644 index 5233965..0000000 --- a/server/lib/sinatra/static_assets.rb +++ /dev/null @@ -1,99 +0,0 @@ -# -# Licensed to the Apache Software Foundation (ASF) under one or more -# contributor license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright ownership. The -# ASF licenses this file to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance with the -# License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -require 'sinatra/base' -require 'sinatra/url_for' - -module Sinatra - module StaticAssets - module Helpers - # In HTML <link> and <img> tags have no end tag. - # In XHTML, on the contrary, these tags must be properly closed. - # - # We can choose the appropriate behaviour with +closed+ option: - # - # image_tag "/images/foo.png", :alt => "Foo itself", :closed => true - # - # The default value of +closed+ option is +false+. - # - def image_tag(source, options = {}) - options[:src] = url_for(source) - tag("img", options) - end - - def stylesheet_link_tag(*sources) - list, options = extract_options(sources) - list.collect { |source| stylesheet_tag(source, options) }.join("\n") - end - - def javascript_script_tag(*sources) - list, options = extract_options(sources) - list.collect { |source| javascript_tag(source, options) }.join("\n") - end - - def link_to(desc, url, options = {}) - tag("a", options.merge(:href => url_for(url))) do - desc - end - end - - private - - def tag(name, local_options = {}) - start_tag = "<#{name}#{tag_options(local_options) if local_options}" - if block_given? - content = yield - "#{start_tag}>#{content}</#{name}>" - else - "#{start_tag}#{"/" if settings.xhtml}>" - end - end - - def tag_options(options) - unless options.empty? - attrs = [] - attrs = options.map { |key, value| %(#{key}="#{Rack::Utils.escape_html(value)}") } - " #{attrs.sort * ' '}" unless attrs.empty? - end - end - - def stylesheet_tag(source, options = {}) - tag("link", { :type => "text/css", - :charset => "utf-8", :media => "screen", :rel => "stylesheet", - :href => url_for(source) }.merge(options)) - end - - def javascript_tag(source, options = {}) - tag("script", { :type => "text/javascript", :charset => "utf-8", - :src => url_for(source) }.merge(options)) do - end - end - - def extract_options(a) - opts = a.last.is_a?(::Hash) ? a.pop : {} - [a, opts] - end - - end - - def self.registered(app) - app.helpers StaticAssets::Helpers - app.disable :xhtml - end - end - - register StaticAssets -end diff --git a/server/lib/sinatra/url_for.rb b/server/lib/sinatra/url_for.rb deleted file mode 100644 index fba6668..0000000 --- a/server/lib/sinatra/url_for.rb +++ /dev/null @@ -1,93 +0,0 @@ -# -# Based on https://github.com/emk/sinatra-url-for/ -# Commit 1df339284203f8f6ed8d -# -# Original license: -# Copyright (C) 2009 Eric Kidd -# -# Permission is hereby granted, free of charge, to any person obtaining a -# copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to permit -# persons to whom the Software is furnished to do so, subject to the -# following conditions: -# -# The above copyright notice and this permission notice shall be included -# in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -# USE OR OTHER DEALINGS IN THE SOFTWARE. - -require 'uri' - -module Sinatra - module UrlForHelper - - def api_url_for(url_fragment, mode=:path_only) - matrix_params = '' - if request.params['api'] - matrix_params += ";provider=%s" % request.params['api']['provider'] if request.params['api']['provider'] - matrix_params += ";driver=%s" % request.params['api']['driver'] if request.params['api']['driver'] - end - url_fragment = "/#{url_fragment}" unless url_fragment =~ /^\// # There is no need to prefix URI with '/' - url_for "#{settings.root_url}#{matrix_params}#{url_fragment}", mode - end - - # Construct a link to +url_fragment+, which should be given relative to - # the base of this Sinatra app. The mode should be either - # <code>:path_only</code>, which will generate an absolute path within - # the current domain (the default), or <code>:full</code>, which will - # include the site name and port number. (The latter is typically - # necessary for links in RSS feeds.) Example usage: - # - # url_for "/" # Returns "/myapp/" - # url_for "/foo" # Returns "/myapp/foo" - # url_for "/foo", :full # Returns "http://example.com/myapp/foo" - #-- - # See README.rdoc for a list of some of the people who helped me clean - # up earlier versions of this code. - def url_for url_fragment, mode=:path_only - case mode - when :path_only - base = request.script_name - when :full - scheme = request.scheme - port = request.port - request_host = request.host - if request.env['HTTP_X_FORWARDED_FOR'] - scheme = request.env['HTTP_X_FORWARDED_SCHEME'] || scheme - port = request.env['HTTP_X_FORWARDED_PORT'] - request_host = request.env['HTTP_X_FORWARDED_HOST'] - end - if (port.nil? || port == "" || - (scheme == 'http' && port.to_s == '80') || - (scheme == 'https' && port.to_s == '443')) - port = "" - else - port = ":#{port}" - end - base = "#{scheme}://#{request_host}#{port}#{request.script_name}" - else - raise TypeError, "Unknown url_for mode #{mode}" - end - url_escape = URI.escape(url_fragment) - # Don't add the base fragment if url_for gets called more than once - # per url or the url_fragment passed in is an absolute url - if url_escape.match(/^#{base}/) or url_escape.match(/^http/) - url_escape - else - "#{base}#{url_escape}" - end - end - end - - - - helpers UrlForHelper -end -- 1.7.10
