CombinedText
stringlengths
4
3.42M
require 'omniauth-oauth' module OmniAuth module Strategies class Ravelry < OmniAuth::Strategies::OAuth option :name, 'ravelry' option :client_options, { site: 'https://api.ravelry.com', authorize_url: 'https://www.ravelry.com/oauth/authorize', request_token_url: 'https://www.ravelry.com/oauth/request_token', access_token_url: 'https://www.ravelry.com/oauth/access_token' } uid{ request.params['username'] } info do { :name => raw_info['name'], :location => raw_info['city'] } end extra do { 'raw_info' => raw_info } end def raw_info @raw_info ||= MultiJson.decode(access_token.get("/people/#{uid}.json").body) end end end end Update raw_info and info calls require 'omniauth-oauth' module OmniAuth module Strategies class Ravelry < OmniAuth::Strategies::OAuth option :name, 'ravelry' option :client_options, { site: 'https://api.ravelry.com', authorize_url: 'https://www.ravelry.com/oauth/authorize', request_token_url: 'https://www.ravelry.com/oauth/request_token', access_token_url: 'https://www.ravelry.com/oauth/access_token' } uid{ request.params['username'] } info do { 'name' => raw_info['first_name'], 'location' => raw_info['location'], 'nickname' => raw_info['username'], 'first_name' => raw_info['first_name'], 'description' => raw_info['about_me'], 'image' => raw_info['small_photo_url'] } end extra do { 'raw_info' => raw_info } end def raw_info @raw_info ||= MultiJson.decode(access_token.get("https://api.ravelry.com/people/#{uid}.json").body)['user'] end end end end
require 'omniauth/strategies/oauth2' module OmniAuth module Strategies class TheCity < OmniAuth::Strategies::OAuth2 DEFAULT_SCOPE = 'user_basic' option :name, :thecity option :client_options, { site: "https://authentication.onthecity.org", authorize_path: "/oauth/authorize" } def request_phase redirect client.auth_code.authorize_url({:redirect_uri => callback_url}.merge(authorize_params)) end def authorize_params super.tap do |params| params[:scope] ||= DEFAULT_SCOPE end end uid do raw_info["global_user"]["id"] end info do raw_info end def raw_info if session[:subdomain].present? @raw_info ||= access_token.get("/authorization?subdomain=#{session[:subdomain]}").parsed else @raw_info ||= access_token.get("/authorization").parsed end end end end end OmniAuth.config.add_camelization 'thecity', 'TheCity' pass in subdomain as request param or header require 'omniauth/strategies/oauth2' module OmniAuth module Strategies class TheCity < OmniAuth::Strategies::OAuth2 DEFAULT_SCOPE = 'user_basic' option :name, :thecity option :client_options, { site: "https://authentication.onthecity.org", authorize_path: "/oauth/authorize" } def request_phase redirect client.auth_code.authorize_url({:redirect_uri => callback_url, :subdomain => subdomain}.merge(authorize_params)) end def authorize_params super.tap do |params| params[:scope] ||= DEFAULT_SCOPE end end def subdomain @subdomain ||= session[:subdomain] || request.params["subdomain"] || request.headers['HTTP_X_CITY_SUBDOMAIN'] || nil rescue nil end uid do raw_info["global_user"]["id"] end info do raw_info end def raw_info if @subdomain @raw_info ||= access_token.get("/authorization?subdomain=#{session[:subdomain]}").parsed else @raw_info ||= access_token.get("/authorization").parsed end end end end end OmniAuth.config.add_camelization 'thecity', 'TheCity'
module Ore module Template # # Handles the expansion of paths and substitution of path keywords. # The following keywords are supported: # # * `[name]` - The name of the project. # * `[project_dir]` - The directory base-name derived from the project # name. # * `[namespace_path]` - The full directory path derived from the # project name. # * `[namespace_dir]` - The last directory name derived from the # project name. # module Interpolations # The accepted interpolation keywords that may be used in paths @@keywords = %w[ name project_dir namespace_path namespace_dir markup ] protected # # Expands the given path by substituting the interpolation keywords # for the related instance variables. # # @param [String] path # The path to expand. # # @return [String] # The expanded path. # # @example Assuming `@project_dir` contains `my_project`. # interpolate("lib/[project_dir].rb") # # => "lib/my_project.rb" # # @example Assuming `@namespace_path` contains `my/project`. # interpolate("spec/[namespace_path]_spec.rb") # # => "spec/my/project_spec.rb" # def interpolate(path) dirs = path.split(File::SEPARATOR) dirs.each do |dir| dir.gsub!(/(\[[a-z_]+\])/) do |capture| keyword = capture[1..-2] if @@keywords.include?(keyword) instance_variable_get("@#{keyword}") else capture end end end return File.join(dirs.reject { |dir| dir.empty? }) end end end end Added version, date, year, month, day to Ore::Template::Interpolations. module Ore module Template # # Handles the expansion of paths and substitution of path keywords. # The following keywords are supported: # # * `[name]` - The name of the project. # * `[project_dir]` - The directory base-name derived from the project # name. # * `[namespace_path]` - The full directory path derived from the # project name. # * `[namespace_dir]` - The last directory name derived from the # project name. # module Interpolations # The accepted interpolation keywords that may be used in paths @@keywords = %w[ name version project_dir namespace_path namespace_dir markup date year month day ] protected # # Expands the given path by substituting the interpolation keywords # for the related instance variables. # # @param [String] path # The path to expand. # # @return [String] # The expanded path. # # @example Assuming `@project_dir` contains `my_project`. # interpolate("lib/[project_dir].rb") # # => "lib/my_project.rb" # # @example Assuming `@namespace_path` contains `my/project`. # interpolate("spec/[namespace_path]_spec.rb") # # => "spec/my/project_spec.rb" # def interpolate(path) dirs = path.split(File::SEPARATOR) dirs.each do |dir| dir.gsub!(/(\[[a-z_]+\])/) do |capture| keyword = capture[1..-2] if @@keywords.include?(keyword) instance_variable_get("@#{keyword}") else capture end end end return File.join(dirs.reject { |dir| dir.empty? }) end end end end
require 'net/smtp' require 'tmail' require 'erb' module Rack # Catches all exceptions raised from the app it wraps and # sends a useful email with the exception, stacktrace, and # contents of the environment. class MailExceptions attr_reader :config def initialize(app) @app = app @config = { :to => nil, :from => ENV['USER'] || 'rack', :subject => '[exception] %s', :smtp => { :server => 'localhost', :domain => 'localhost', :port => 25, :authentication => :login, :user_name => nil, :password => nil } } @template = ERB.new(TEMPLATE) yield self if block_given? end def call(env) status, headers, body = begin @app.call(env) rescue => boom # TODO don't allow exceptions from send_notification to # propogate send_notification boom, env raise end send_notification env['mail.exception'], env if env['mail.exception'] [status, headers, body] end %w[to from subject].each do |meth| define_method(meth) { |value| @config[meth.to_sym] = value } end def smtp(settings={}) @config[:smtp].merge! settings end private def generate_mail(exception, env) mail = TMail::Mail.new mail.to = Array(config[:to]) mail.from = config[:from] mail.subject = config[:subject] % [exception.to_s] mail.date = Time.now mail.set_content_type 'text/plain' mail.charset = 'UTF-8' mail.body = @template.result(binding) mail end def send_notification(exception, env) mail = generate_mail(exception, env) smtp = config[:smtp] env['mail.sent'] = true return if smtp[:server] == 'example.com' Net::SMTP.start smtp[:address], smtp[:port], smtp[:domain], smtp[:user_name], smtp[:password], smtp[:authentication] do |server| mail.to.each do |recipient| server.send_message mail.to_s, mail.from, recipient end end end def extract_body(env) if io = env['rack.input'] io.rewind if io.respond_to?(:rewind) io.read end end TEMPLATE = (<<-'EMAIL').gsub(/^ {4}/, '') A <%= exception.class.to_s %> occured: <%= exception.to_s %> <% if body = extract_body(env) %> =================================================================== Request Body: =================================================================== <%= body.gsub(/^/, ' ') %> <% end %> =================================================================== Rack Environment: =================================================================== PID: <%= $$ %> PWD: <%= Dir.getwd %> <%= env.to_a. sort{|a,b| a.first <=> b.first}. map{ |k,v| "%-25s%p" % [k+':', v] }. join("\n ") %> <% if exception.respond_to?(:backtrace) %> =================================================================== Backtrace: =================================================================== <%= exception.backtrace.join("\n ") %> <% end %> EMAIL end end Connection should be opened to smtp[:server] and not smtp[:address] require 'net/smtp' require 'tmail' require 'erb' module Rack # Catches all exceptions raised from the app it wraps and # sends a useful email with the exception, stacktrace, and # contents of the environment. class MailExceptions attr_reader :config def initialize(app) @app = app @config = { :to => nil, :from => ENV['USER'] || 'rack', :subject => '[exception] %s', :smtp => { :server => 'localhost', :domain => 'localhost', :port => 25, :authentication => :login, :user_name => nil, :password => nil } } @template = ERB.new(TEMPLATE) yield self if block_given? end def call(env) status, headers, body = begin @app.call(env) rescue => boom # TODO don't allow exceptions from send_notification to # propogate send_notification boom, env raise end send_notification env['mail.exception'], env if env['mail.exception'] [status, headers, body] end %w[to from subject].each do |meth| define_method(meth) { |value| @config[meth.to_sym] = value } end def smtp(settings={}) @config[:smtp].merge! settings end private def generate_mail(exception, env) mail = TMail::Mail.new mail.to = Array(config[:to]) mail.from = config[:from] mail.subject = config[:subject] % [exception.to_s] mail.date = Time.now mail.set_content_type 'text/plain' mail.charset = 'UTF-8' mail.body = @template.result(binding) mail end def send_notification(exception, env) mail = generate_mail(exception, env) smtp = config[:smtp] env['mail.sent'] = true return if smtp[:server] == 'example.com' Net::SMTP.start smtp[:server], smtp[:port], smtp[:domain], smtp[:user_name], smtp[:password], smtp[:authentication] do |server| mail.to.each do |recipient| server.send_message mail.to_s, mail.from, recipient end end end def extract_body(env) if io = env['rack.input'] io.rewind if io.respond_to?(:rewind) io.read end end TEMPLATE = (<<-'EMAIL').gsub(/^ {4}/, '') A <%= exception.class.to_s %> occured: <%= exception.to_s %> <% if body = extract_body(env) %> =================================================================== Request Body: =================================================================== <%= body.gsub(/^/, ' ') %> <% end %> =================================================================== Rack Environment: =================================================================== PID: <%= $$ %> PWD: <%= Dir.getwd %> <%= env.to_a. sort{|a,b| a.first <=> b.first}. map{ |k,v| "%-25s%p" % [k+':', v] }. join("\n ") %> <% if exception.respond_to?(:backtrace) %> =================================================================== Backtrace: =================================================================== <%= exception.backtrace.join("\n ") %> <% end %> EMAIL end end
# optional http client begin; require 'restclient' ; rescue LoadError; end begin; require 'em-http-request'; rescue LoadError; end # optional gem begin; require 'rack' ; rescue LoadError; end # stdlib require 'openssl' require 'cgi' RestCore::Builder.client('RestGraph', :app_id, :secret, :old_site, :old_server, :graph_server) do use DefaultSite , 'https://graph.facebook.com/' use ErrorDetector , lambda{ |env| env[RESPONSE_BODY]['error'] || env[RESPONSE_BODY]['error_code'] } use AutoJsonDecode, true use Cache , {} use Timeout , 10 use DefaultHeaders, {'Accept' => 'application/json', 'Accept-Language' => 'en-us'} use ErrorHandler , lambda{ |env| raise ::RestGraph::Error.call(env) } use CommonLogger , method(:puts) run RestClient end class RestGraph::Error < RuntimeError include RestCore class AccessToken < RestGraph::Error; end class InvalidAccessToken < AccessToken ; end class MissingAccessToken < AccessToken ; end attr_reader :error, :url def initialize error, url='' @error, @url = error, url super("#{error.inspect} from #{url}") end def self.call env error, url = env[RESPONSE_BODY], env[REQUEST_URI] return new(error, url) unless error.kind_of?(Hash) if invalid_token?(error) InvalidAccessToken.new(error, url) elsif missing_token?(error) MissingAccessToken.new(error, url) else new(error, url) end end def self.invalid_token? error (%w[OAuthInvalidTokenException OAuthException].include?((error['error'] || {})['type'])) || (error['error_code'] == 190) # Invalid OAuth 2.0 Access Token end def self.missing_token? error (error['error'] || {})['message'] =~ /^An active access token/ || (error['error_code'] == 104) # Requires valid signature end end # module Hmac # # Fallback to ruby-hmac gem in case system openssl # # lib doesn't support SHA256 (OSX 10.5) # def hmac_sha256 key, data # OpenSSL::HMAC.digest('sha256', key, data) # rescue RuntimeError # require 'hmac-sha2' # HMAC::SHA256.digest(key, data) # end # end rest-graph.rb: restore other facebook related methods require 'rest-core' # optional http client begin; require 'restclient' ; rescue LoadError; end begin; require 'em-http-request'; rescue LoadError; end # optional gem begin; require 'rack' ; rescue LoadError; end # stdlib require 'openssl' require 'cgi' RestCore::Builder.client('RestGraph', :app_id, :secret, :old_site, :old_server, :graph_server) do use DefaultSite , 'https://graph.facebook.com/' use ErrorDetector , lambda{ |env| env[RESPONSE_BODY]['error'] || env[RESPONSE_BODY]['error_code'] } use AutoJsonDecode, true use Cache , {} use Timeout , 10 use DefaultHeaders, {'Accept' => 'application/json', 'Accept-Language' => 'en-us'} use ErrorHandler , lambda{ |env| raise ::RestGraph::Error.call(env) } use CommonLogger , method(:puts) run RestClient end class RestGraph::Error < RuntimeError include RestCore class AccessToken < RestGraph::Error; end class InvalidAccessToken < AccessToken ; end class MissingAccessToken < AccessToken ; end attr_reader :error, :url def initialize error, url='' @error, @url = error, url super("#{error.inspect} from #{url}") end def self.call env error, url = env[RESPONSE_BODY], env[REQUEST_URI] return new(error, url) unless error.kind_of?(Hash) if invalid_token?(error) InvalidAccessToken.new(error, url) elsif missing_token?(error) MissingAccessToken.new(error, url) else new(error, url) end end def self.invalid_token? error (%w[OAuthInvalidTokenException OAuthException].include?((error['error'] || {})['type'])) || (error['error_code'] == 190) # Invalid OAuth 2.0 Access Token end def self.missing_token? error (error['error'] || {})['message'] =~ /^An active access token/ || (error['error_code'] == 104) # Requires valid signature end end module RestGraph::Client def next_page hash, opts={}, &cb if hash['paging'].kind_of?(Hash) && hash['paging']['next'] request(opts, [:get, URI.encode(hash['paging']['next'])], &cb) else yield(nil) if block_given? end end def prev_page hash, opts={}, &cb if hash['paging'].kind_of?(Hash) && hash['paging']['previous'] request(opts, [:get, URI.encode(hash['paging']['previous'])], &cb) else yield(nil) if block_given? end end alias_method :previous_page, :prev_page def for_pages hash, pages=1, opts={}, kind=:next_page, &cb if pages > 1 merge_data(send(kind, hash, opts){ |result| yield(result.freeze) if block_given? for_pages(result, pages - 1, opts, kind, &cb) if result }, hash) else yield(nil) if block_given? hash end end # cookies, app_id, secrect related below def parse_rack_env! env env['HTTP_COOKIE'].to_s =~ /fbs_#{app_id}=([^\;]+)/ self.data = parse_fbs!($1) end def parse_cookies! cookies self.data = parse_fbs!(cookies["fbs_#{app_id}"]) end def parse_fbs! fbs self.data = check_sig_and_return_data( # take out facebook sometimes there but sometimes not quotes in cookies Rack::Utils.parse_query(fbs.to_s.gsub('"', ''))) end def parse_json! json self.data = json && check_sig_and_return_data(AutoJsonDecode.json_decode(json)) rescue ParseError self.data = nil end def fbs "#{fbs_without_sig(data).join('&')}&sig=#{calculate_sig(data)}" end # facebook's new signed_request... def parse_signed_request! request sig_encoded, json_encoded = request.split('.') sig, json = [sig_encoded, json_encoded].map{ |str| "#{str.tr('-_', '+/')}==".unpack('m').first } self.data = check_sig_and_return_data( AutoJsonDecode.json_decode(json).merge('sig' => sig)){ self.class.hmac_sha256(secret, json_encoded) } rescue ParseError self.data = nil end # oauth related def authorize_url opts={} query = {:client_id => app_id, :access_token => nil}.merge(opts) "#{site}oauth/authorize#{build_query_string(query)}" end def authorize! opts={} query = {:client_id => app_id, :client_secret => secret}.merge(opts) self.data = Rack::Utils.parse_query( request({:auto_decode => false}.merge(opts), [:get, url('oauth/access_token', query)])) end # old rest facebook api, i will definitely love to remove them someday def old_rest path, query={}, opts={}, &cb uri = url("method/#{path}", {:format => 'json'}.merge(query), old_server, opts) if opts[:post] request( opts.merge(:uri => uri), [:post, url("method/#{path}", {:format => 'json'}, old_server, opts), query], &cb) else request(opts, [:get, uri], &cb) end end def secret_old_rest path, query={}, opts={}, &cb old_rest(path, query, {:secret => true}.merge(opts), &cb) end def fql code, query={}, opts={}, &cb old_rest('fql.query', {:query => code}.merge(query), opts, &cb) end def fql_multi codes, query={}, opts={}, &cb old_rest('fql.multiquery', {:queries => AutoJsonDecode.json_encode(codes)}.merge(query), opts, &cb) end def exchange_sessions query={}, opts={}, &cb q = {:client_id => app_id, :client_secret => secret, :type => 'client_cred'}.merge(query) request(opts, [:post, url('oauth/exchange_sessions', q)], &cb) end end RestGraph.send(:include, RestGraph::Client) # module Hmac # # Fallback to ruby-hmac gem in case system openssl # # lib doesn't support SHA256 (OSX 10.5) # def hmac_sha256 key, data # OpenSSL::HMAC.digest('sha256', key, data) # rescue RuntimeError # require 'hmac-sha2' # HMAC::SHA256.digest(key, data) # end # end
# frozen_string_literal: true module RuboCop module Cop module RSpec # Checks that spec file paths are consistent with the test subject. # # Checks the path of the spec file and enforces that it reflects the # described class/module and its optionally called out method. # # With the configuration option `CustomTransform` modules or classes can # be specified that should not as usual be transformed from CamelCase to # snake_case (e.g. 'RuboCop' => 'rubocop' ). # # @example # my_class/method_spec.rb # describe MyClass, '#method' # my_class_method_spec.rb # describe MyClass, '#method' # my_class_spec.rb # describe MyClass class FilePath < Cop include RuboCop::RSpec::SpecOnly, RuboCop::RSpec::TopLevelDescribe MESSAGE = 'Spec path should end with `%s`'.freeze METHOD_STRING_MATCHER = /^[\#\.].+/ ROUTING_PAIR = s(:pair, s(:sym, :type), s(:sym, :routing)) def on_top_level_describe(node, args) return if routing_spec?(args) return unless single_top_level_describe? object = args.first.const_name return unless object path_matcher = matcher(object, args.at(1)) return if source_filename =~ regexp_from_glob(path_matcher) add_offense(node, :expression, format(MESSAGE, path_matcher)) end private def routing_spec?(args) args.any? do |arg| arg.children.include?(ROUTING_PAIR) end end def matcher(object, method) path = File.join(parts(object)) if method && method.type.equal?(:str) path += '*' + method.str_content.gsub(/\W+/, '') end "#{path}*_spec.rb" end def parts(object) object.split('::').map do |p| custom_transform[p] || camel_to_underscore(p) end end def source_filename processed_source.buffer.name end def camel_to_underscore(string) string .gsub(/([^A-Z])([A-Z]+)/, '\\1_\\2') .gsub(/([A-Z])([A-Z\d][^A-Z\d]+)/, '\\1_\\2') .downcase end def regexp_from_glob(glob) Regexp.new(glob.sub('.', '\\.').gsub('*', '.*') + '$') end def custom_transform cop_config['CustomTransform'] || {} end end end end end Remove unused constant # frozen_string_literal: true module RuboCop module Cop module RSpec # Checks that spec file paths are consistent with the test subject. # # Checks the path of the spec file and enforces that it reflects the # described class/module and its optionally called out method. # # With the configuration option `CustomTransform` modules or classes can # be specified that should not as usual be transformed from CamelCase to # snake_case (e.g. 'RuboCop' => 'rubocop' ). # # @example # my_class/method_spec.rb # describe MyClass, '#method' # my_class_method_spec.rb # describe MyClass, '#method' # my_class_spec.rb # describe MyClass class FilePath < Cop include RuboCop::RSpec::SpecOnly, RuboCop::RSpec::TopLevelDescribe MESSAGE = 'Spec path should end with `%s`'.freeze ROUTING_PAIR = s(:pair, s(:sym, :type), s(:sym, :routing)) def on_top_level_describe(node, args) return if routing_spec?(args) return unless single_top_level_describe? object = args.first.const_name return unless object path_matcher = matcher(object, args.at(1)) return if source_filename =~ regexp_from_glob(path_matcher) add_offense(node, :expression, format(MESSAGE, path_matcher)) end private def routing_spec?(args) args.any? do |arg| arg.children.include?(ROUTING_PAIR) end end def matcher(object, method) path = File.join(parts(object)) if method && method.type.equal?(:str) path += '*' + method.str_content.gsub(/\W+/, '') end "#{path}*_spec.rb" end def parts(object) object.split('::').map do |p| custom_transform[p] || camel_to_underscore(p) end end def source_filename processed_source.buffer.name end def camel_to_underscore(string) string .gsub(/([^A-Z])([A-Z]+)/, '\\1_\\2') .gsub(/([A-Z])([A-Z\d][^A-Z\d]+)/, '\\1_\\2') .downcase end def regexp_from_glob(glob) Regexp.new(glob.sub('.', '\\.').gsub('*', '.*') + '$') end def custom_transform cop_config['CustomTransform'] || {} end end end end end
require 'rubyXL/objects/reference' module RubyXL module OOXMLObjectClassMethods # Get the value of a [sub]class variable if it exists, or create the respective variable # with the passed-in +default+ (or +{}+, if not specified) # # Throughout this class, we are setting class variables through explicit method calls # rather than by directly addressing the name of the variable because of context issues: # addressing variable by name creates it in the context of defining class, while calling # the setter/getter method addresses it in the context of descendant class, # which is what we need. def obtain_class_variable(var_name, default = {}) if class_variable_defined?(var_name) then self.class_variable_get(var_name) else self.class_variable_set(var_name, default) end end # Defines an attribute of OOXML object. # === Parameters # * +attribute_name+ - Name of the element attribute as seen in the source XML. Can be either <tt>"String"</tt> or <tt>:Symbol</tt> # * Special attibute name <tt>'_'</tt> (underscore) denotes the value of the element rather than attribute. # * +attribute_type+ - Specifies the conversion type for the attribute when parsing. Available options are: # * +:int+ - <tt>Integer</tt> # * +:uint+ - Unsigned <tt>Integer</tt> # * +:double+ - <tt>Float</tt></u> # * +:string+ - <tt>String</tt> (no conversion) # * +:sqref+ - RubyXL::Sqref # * +:ref+ - RubyXL::Reference # * +:bool+ - <tt>Boolean</tt> ("1" and "true" convert to +true+, others to +false+) # * one of +simple_types+ - <tt>String</tt>, plus the list of acceptable values is saved for future validation (not used yet). # * +extra_parameters+ - Hash of optional parameters as follows: # * +:accessor+ - Name of the accessor for this attribute to be defined on the object. If not provided, defaults to classidied +attribute_name+. # * +:default+ - Value this attribute defaults to if not explicitly provided. # * +:required+ - Whether this attribute is required when writing XML. If the value of the attrinute is not explicitly provided, +:default+ is written instead. # * +:computed+ - Do not store this attribute on +parse+, but do call the object-provided read accessor on +write_xml+. # ==== Examples # define_attribute(:outline, :bool, :default => true) # A <tt>Boolean</tt> attribute 'outline' with default value +true+ will be accessible by calling +obj.outline+ # define_attribute(:uniqueCount, :int) # An <tt>Integer</tt> attribute 'uniqueCount' accessible as +obj.unique_count+ # define_attribute(:_, :string, :accessor => :expression) # The value of the element will be accessible as a <tt>String</tt> by calling +obj.expression+ # define_attribute(:errorStyle, %w{ stop warning information }, :default => 'stop',) # A <tt>String</tt> attribute named 'errorStyle' will be accessible as +obj.error_style+, valid values are <tt>"stop"</tt>, <tt>"warning"</tt>, <tt>"information"</tt> def define_attribute(attr_name, attr_type, extra_params = {}) attrs = obtain_class_variable(:@@ooxml_attributes) attr_hash = extra_params.merge({ :attr_type => attr_type }) attr_hash[:accessor] ||= accessorize(attr_name) attrs[attr_name.to_s] = attr_hash self.send(:attr_accessor, attr_hash[:accessor]) unless attr_hash[:computed] end # Defines a child node of OOXML object. # === Parameters # * +klass+ - Class (descendant of RubyXL::OOXMLObject) of the child nodes. Child node objects will be produced by calling +parse+ method of that class. # * +extra_parameters+ - Hash of optional parameters as follows: # * +:accessor+ - Name of the accessor for this attribute to be defined on the object. If not provided, defaults to classidied +attribute_name+. # * +:node_name+ - Node name for the child node, in case it does not match the one defined by the +klass+. # * +:collection+ - Whether the child node should be treated as a single node or a collection of nodes: # * +false+ (default) - child node is directly accessible through the respective accessor; # * +true+ - a collection of child nodes is accessed as +Array+ through the respective accessor; # * +:with_count+ - same as +true+, but in addition, the attribute +count+ is defined on the current object, that will be automatically set to the number of elements in the collection at the start of +write_xml+ call. # ==== Examples # define_child_node(RubyXL::Alignment) # Define a singular child node parsed by the RubyXL::BorderEdge.parse() and accessed by the default <tt>obj.alignment</tt> accessor # define_child_node(RubyXL::Hyperlink, :collection => true, :accessor => :hyperlinks) # Define an array of nodes accessed by <tt>obj.hyperlinks</tt> accessor, each of which will be parsed by the RubyXL::Hyperlink.parse() # define_child_node(RubyXL::BorderEdge, :node_name => :left) # define_child_node(RubyXL::BorderEdge, :node_name => :right) # Use class RubyXL::BorderEdge when parsing both the elements <tt><left ...></tt> and <tt><right ...></tt> elements. # define_child_node(RubyXL::Font, :collection => :with_count, :accessor => :fonts) # Upon writing of the object this was defined on, its <tt>count</tt> attribute will be set to the count of nodes in <tt>fonts</tt> array def define_child_node(klass, extra_params = {}) child_nodes = obtain_class_variable(:@@ooxml_child_nodes) child_node_name = (extra_params[:node_name] || klass.class_variable_get(:@@ooxml_tag_name)).to_s accessor = (extra_params[:accessor] || accessorize(child_node_name)).to_sym child_nodes[child_node_name] = { :class => klass, :is_array => extra_params[:collection], :accessor => accessor } define_count_attribute if extra_params[:collection] == :with_count self.send(:attr_accessor, accessor) end def define_count_attribute define_attribute(:count, :uint, :required => true) end private :define_count_attribute # Defines the name of the element that represents the current OOXML object. Should only be used once per object. # In case of different objects represented by the same class in different parts of OOXML tree, +:node_name+ # extra parameter can be used to override the default element name. # === Parameters # * +element_name+ # ==== Examples # define_element_name 'externalReference' def define_element_name(element_name) self.class_variable_set(:@@ooxml_tag_name, element_name) end def parse(node, known_namespaces = nil) case node when String, IO, Zip::InputStream then node = Nokogiri::XML.parse(node) end if node.is_a?(Nokogiri::XML::Document) then @namespaces = node.namespaces node = node.root # ignorable_attr = node.attributes['Ignorable'] # @ignorables << ignorable_attr.value if ignorable_attr end obj = self.new known_attributes = obtain_class_variable(:@@ooxml_attributes) content_params = known_attributes['_'] process_attribute(obj, node.text, content_params) if content_params node.attributes.each_pair { |attr_name, attr| attr_name = if attr.namespace then "#{attr.namespace.prefix}:#{attr.name}" else attr.name end attr_params = known_attributes[attr_name] next if attr_params.nil? # raise "Unknown attribute [#{attr_name}] for element [#{node.name}]" if attr_params.nil? process_attribute(obj, attr.value, attr_params) unless attr_params[:computed] } known_child_nodes = obtain_class_variable(:@@ooxml_child_nodes) unless known_child_nodes.empty? known_namespaces ||= obtain_class_variable(:@@ooxml_namespaces) node.element_children.each { |child_node| ns = child_node.namespace prefix = known_namespaces[ns.href] || ns.prefix child_node_name = case prefix when '', nil then child_node.name else "#{prefix}:#{child_node.name}" end child_node_params = known_child_nodes[child_node_name] raise "Unknown child node [#{child_node_name}] for element [#{node.name}]" if child_node_params.nil? parsed_object = child_node_params[:class].parse(child_node, known_namespaces) if child_node_params[:is_array] then index = parsed_object.index_in_collection collection = if (self < RubyXL::OOXMLContainerObject) then obj else obj.send(child_node_params[:accessor]) end if index.nil? then collection << parsed_object else collection[index] = parsed_object end else obj.send("#{child_node_params[:accessor]}=", parsed_object) end } end obj end private def accessorize(str) acc = str.to_s.dup acc.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2') acc.gsub!(/([a-z\d])([A-Z])/,'\1_\2') acc.gsub!(':','_') acc.downcase.to_sym end def process_attribute(obj, raw_value, params) val = raw_value && case params[:attr_type] when :double then Float(raw_value) # http://www.datypic.com/sc/xsd/t-xsd_double.html when :string then raw_value when Array then raw_value # Case of Simple Types when :sqref then RubyXL::Sqref.new(raw_value) when :ref then RubyXL::Reference.new(raw_value) when :bool then ['1', 'true'].include?(raw_value) when :int then Integer(raw_value) when :uint then v = Integer(raw_value) raise ArgumentError.new("invalid value for unsigned Integer(): \"#{raw_value}\"") if v < 0 v end obj.send("#{params[:accessor]}=", val) end end module OOXMLObjectInstanceMethods def self.included(klass) klass.extend RubyXL::OOXMLObjectClassMethods end def obtain_class_variable(var_name, default = {}) self.class.obtain_class_variable(var_name, default) end private :obtain_class_variable def initialize(params = {}) obtain_class_variable(:@@ooxml_attributes).each_value { |v| instance_variable_set("@#{v[:accessor]}", params[v[:accessor]]) unless v[:computed] } init_child_nodes(params) instance_variable_set("@count", 0) if obtain_class_variable(:@@ooxml_countable, false) end def init_child_nodes(params) obtain_class_variable(:@@ooxml_child_nodes).each_value { |v| initial_value = if params.has_key?(v[:accessor]) then params[v[:accessor]] elsif v[:is_array] then [] else nil end instance_variable_set("@#{v[:accessor]}", initial_value) } end private :init_child_nodes # Recursively write the OOXML object and all its children out as Nokogiri::XML. Immediately before the actual # generation, +before_write_xml()+ is called to perform last-minute cleanup and validation operations; if it # returns +false+, an empty string is returned (rather than +nil+, so Nokogiri::XML's <tt>&lt;&lt;</tt> operator # can be used without additional +nil+ checking) # === Parameters # * +xml+ - Base Nokogiri::XML object used for building. If omitted, a blank document will be generated. # * +node_name_override+ - if present, is used instead of the default element name for this object provided by +define_element_name+ # ==== Examples # obj.write_xml() # Creates a new empty +Nokogiri::XML+, populates it with the OOXML structure as described in the respective definition, and returns the resulting +Nokogiri::XML+ object. # obj.write_xml(seed_xml) # Using the passed-in +Nokogiri+ +xml+ object, creates a new element corresponding to +obj+ according to its definition, along with all its properties and children, and returns the newly created element. # obj.write_xml(seed_xml, 'overriden_element_name') # Same as above, but uses the passed-in +node_name_override+ as the new element name, instead of its default name set by +define_element_name+. def write_xml(xml = nil, node_name_override = nil) if xml.nil? then seed_xml = Nokogiri::XML('<?xml version = "1.0" standalone ="yes"?>') seed_xml.encoding = 'UTF-8' result = self.write_xml(seed_xml) return result if result == '' seed_xml << result return seed_xml.to_xml({ :indent => 0, :save_with => Nokogiri::XML::Node::SaveOptions::AS_XML }) end return '' unless before_write_xml # Populate namespaces, if any attrs = {} obtain_class_variable(:@@ooxml_namespaces).each_pair { |k, v| attrs[v.empty? ? 'xmlns' : "xmlns:#{v}"] = k } obtain_class_variable(:@@ooxml_attributes).each_pair { |k, v| val = self.send(v[:accessor]) if val.nil? then next unless v[:required] val = v[:default] end val = val && case v[:attr_type] when :bool then val ? '1' : '0' when :double then val.to_s.gsub(/\.0*\Z/, '') # Trim trailing zeroes else val end attrs[k] = val } element_text = attrs.delete('_') elem = xml.create_element(node_name_override || obtain_class_variable(:@@ooxml_tag_name), attrs, element_text) child_nodes = obtain_class_variable(:@@ooxml_child_nodes) child_nodes.each_pair { |child_node_name, child_node_params| node_obj = get_node_object(child_node_params) next if node_obj.nil? if node_obj.respond_to?(:write_xml) && !node_obj.equal?(self) then # If child node is either +OOXMLObject+, or +OOXMLContainerObject+ on its first (envelope) pass, # serialize that object. elem << node_obj.write_xml(xml, child_node_name) else # If child node is either vanilla +Array+, or +OOXMLContainerObject+ on its seconds (content) pass, # serialize write its members. node_obj.each { |item| elem << item.write_xml(xml, child_node_name) unless item.nil? } end } elem end def dup new_copy = super new_copy.count = 0 if obtain_class_variable(:@@ooxml_countable, false) new_copy end # Prototype method. For sparse collections (+Rows+, +Cells+, etc.) must return index at which this object # is expected to reside in the collection. If +nil+ is returned, then object is simply added # to the end of the collection. def index_in_collection nil end def get_node_object(child_node_params) self.send(child_node_params[:accessor]) end private :get_node_object # Subclass provided filter to perform last-minute operations (cleanup, count, etc.) immediately prior to write, # along with option to terminate the actual write if +false+ is returned (for example, to avoid writing # the collection's root node if the collection is empty). def before_write_xml #TODO# This will go away once containers are fully implemented. child_nodes = obtain_class_variable(:@@ooxml_child_nodes) child_nodes.each_pair { |child_node_name, child_node_params| self.count = self.send(child_node_params[:accessor]).size if child_node_params[:is_array] == :with_count } true end end # Parent class for defining OOXML based objects (not unlike Rails' +ActiveRecord+!) # Most importantly, provides functionality of parsing such objects from XML, # and marshalling them to XML. class OOXMLObject include OOXMLObjectInstanceMethods end # Parent class for OOXML conainer objects (for example, # <tt>&lt;fonts&gt;&lt;font&gt;...&lt;/font&gt;&lt;font&gt;...&lt;/font&gt;&lt;/fonts&gt;</tt> # that obscures the top-level container, allowing direct access to the contents as +Array+. class OOXMLContainerObject < Array include OOXMLObjectInstanceMethods def initialize(params = {}) array_content = params.delete(:_) super array_content.each_with_index { |v, i| self[i] = v } if array_content end def get_node_object(child_node_params) if child_node_params[:is_array] then self else super end end protected :get_node_object def init_child_nodes(params) obtain_class_variable(:@@ooxml_child_nodes).each_value { |v| next if v[:is_array] # Only one collection node allowed per OOXMLContainerObject, and it is contained in itself. instance_variable_set("@#{v[:accessor]}", params[v[:accessor]]) } end protected :init_child_nodes def before_write_xml true end def inspect vars = [ super ] vars = self.instance_variables.each { |v| vars << "#{v}=#{instance_variable_get(v).inspect}" } "<#{self.class}: #{super} #{vars.join(", ")}>" end class << self def define_count_attribute # Count will be inherited from Array. so no need to define it explicitly. define_attribute(:count, :uint, :required => true, :computed => true) end protected :define_count_attribute end end # Extension class providing functionality for top-level OOXML objects that are represented by # their own <tt>.xml</tt> files in <tt>.xslx</tt> zip container. class OOXMLTopLevelObject < OOXMLObject SAVE_ORDER = 500 ROOT = ::Pathname.new('/') attr_accessor :root # Prototype method. For top-level OOXML object, returns the path at which the current object's XML file # is located within the <tt>.xslx</tt> zip container. def xlsx_path raise 'Subclass responsebility' end # Sets the list of namespaces on this object to be added when writing out XML. Valid only on top-level objects. # === Parameters # * +namespace_hash+ - Hash of namespaces in the form of <tt>"prefix" => "url"</tt> # ==== Examples # set_namespaces('http://schemas.openxmlformats.org/spreadsheetml/2006/main' => '', # 'http://schemas.openxmlformats.org/officeDocument/2006/relationships' => 'r') def self.set_namespaces(namespace_hash) self.class_variable_set(:@@ooxml_namespaces, namespace_hash) end # Generates the top-level OOXML object by parsing its XML file from the temporary # directory containing the unzipped contents of <tt>.xslx</tt> # === Parameters # * +dirpath+ - path to the directory with the unzipped <tt>.xslx</tt> contents. def self.parse_file(zip_file, file_path) entry = zip_file.find_entry(RubyXL::from_root(file_path)) # Accomodate for Nokogiri Java implementation which is incapable of reading from a stream entry && (entry.get_input_stream { |f| parse(defined?(JRUBY_VERSION) ? f.read : f) }) end # Saves the contents of the object as XML to respective location in <tt>.xslx</tt> zip container. # === Parameters # * +zipfile+ - ::Zip::File to which the resulting XNMML should be added. def add_to_zip(zip_stream) xml_string = write_xml return if xml_string.empty? zip_stream.put_next_entry(RubyXL::from_root(self.xlsx_path)) zip_stream.write(xml_string) end def file_index root.rels_hash[self.class].index{ |f| f.equal?(self) }.to_i + 1 end end end Utilizing exception mechanism instead of explicitly checking the variable name. require 'rubyXL/objects/reference' module RubyXL module OOXMLObjectClassMethods # Get the value of a [sub]class variable if it exists, or create the respective variable # with the passed-in +default+ (or +{}+, if not specified) # # Throughout this class, we are setting class variables through explicit method calls # rather than by directly addressing the name of the variable because of context issues: # addressing variable by name creates it in the context of defining class, while calling # the setter/getter method addresses it in the context of descendant class, # which is what we need. def obtain_class_variable(var_name, default = {}) begin self.class_variable_get(var_name) rescue NameError self.class_variable_set(var_name, default) end end # Defines an attribute of OOXML object. # === Parameters # * +attribute_name+ - Name of the element attribute as seen in the source XML. Can be either <tt>"String"</tt> or <tt>:Symbol</tt> # * Special attibute name <tt>'_'</tt> (underscore) denotes the value of the element rather than attribute. # * +attribute_type+ - Specifies the conversion type for the attribute when parsing. Available options are: # * +:int+ - <tt>Integer</tt> # * +:uint+ - Unsigned <tt>Integer</tt> # * +:double+ - <tt>Float</tt></u> # * +:string+ - <tt>String</tt> (no conversion) # * +:sqref+ - RubyXL::Sqref # * +:ref+ - RubyXL::Reference # * +:bool+ - <tt>Boolean</tt> ("1" and "true" convert to +true+, others to +false+) # * one of +simple_types+ - <tt>String</tt>, plus the list of acceptable values is saved for future validation (not used yet). # * +extra_parameters+ - Hash of optional parameters as follows: # * +:accessor+ - Name of the accessor for this attribute to be defined on the object. If not provided, defaults to classidied +attribute_name+. # * +:default+ - Value this attribute defaults to if not explicitly provided. # * +:required+ - Whether this attribute is required when writing XML. If the value of the attrinute is not explicitly provided, +:default+ is written instead. # * +:computed+ - Do not store this attribute on +parse+, but do call the object-provided read accessor on +write_xml+. # ==== Examples # define_attribute(:outline, :bool, :default => true) # A <tt>Boolean</tt> attribute 'outline' with default value +true+ will be accessible by calling +obj.outline+ # define_attribute(:uniqueCount, :int) # An <tt>Integer</tt> attribute 'uniqueCount' accessible as +obj.unique_count+ # define_attribute(:_, :string, :accessor => :expression) # The value of the element will be accessible as a <tt>String</tt> by calling +obj.expression+ # define_attribute(:errorStyle, %w{ stop warning information }, :default => 'stop',) # A <tt>String</tt> attribute named 'errorStyle' will be accessible as +obj.error_style+, valid values are <tt>"stop"</tt>, <tt>"warning"</tt>, <tt>"information"</tt> def define_attribute(attr_name, attr_type, extra_params = {}) attrs = obtain_class_variable(:@@ooxml_attributes) attr_hash = extra_params.merge({ :attr_type => attr_type }) attr_hash[:accessor] ||= accessorize(attr_name) attrs[attr_name.to_s] = attr_hash self.send(:attr_accessor, attr_hash[:accessor]) unless attr_hash[:computed] end # Defines a child node of OOXML object. # === Parameters # * +klass+ - Class (descendant of RubyXL::OOXMLObject) of the child nodes. Child node objects will be produced by calling +parse+ method of that class. # * +extra_parameters+ - Hash of optional parameters as follows: # * +:accessor+ - Name of the accessor for this attribute to be defined on the object. If not provided, defaults to classidied +attribute_name+. # * +:node_name+ - Node name for the child node, in case it does not match the one defined by the +klass+. # * +:collection+ - Whether the child node should be treated as a single node or a collection of nodes: # * +false+ (default) - child node is directly accessible through the respective accessor; # * +true+ - a collection of child nodes is accessed as +Array+ through the respective accessor; # * +:with_count+ - same as +true+, but in addition, the attribute +count+ is defined on the current object, that will be automatically set to the number of elements in the collection at the start of +write_xml+ call. # ==== Examples # define_child_node(RubyXL::Alignment) # Define a singular child node parsed by the RubyXL::BorderEdge.parse() and accessed by the default <tt>obj.alignment</tt> accessor # define_child_node(RubyXL::Hyperlink, :collection => true, :accessor => :hyperlinks) # Define an array of nodes accessed by <tt>obj.hyperlinks</tt> accessor, each of which will be parsed by the RubyXL::Hyperlink.parse() # define_child_node(RubyXL::BorderEdge, :node_name => :left) # define_child_node(RubyXL::BorderEdge, :node_name => :right) # Use class RubyXL::BorderEdge when parsing both the elements <tt><left ...></tt> and <tt><right ...></tt> elements. # define_child_node(RubyXL::Font, :collection => :with_count, :accessor => :fonts) # Upon writing of the object this was defined on, its <tt>count</tt> attribute will be set to the count of nodes in <tt>fonts</tt> array def define_child_node(klass, extra_params = {}) child_nodes = obtain_class_variable(:@@ooxml_child_nodes) child_node_name = (extra_params[:node_name] || klass.class_variable_get(:@@ooxml_tag_name)).to_s accessor = (extra_params[:accessor] || accessorize(child_node_name)).to_sym child_nodes[child_node_name] = { :class => klass, :is_array => extra_params[:collection], :accessor => accessor } define_count_attribute if extra_params[:collection] == :with_count self.send(:attr_accessor, accessor) end def define_count_attribute define_attribute(:count, :uint, :required => true) end private :define_count_attribute # Defines the name of the element that represents the current OOXML object. Should only be used once per object. # In case of different objects represented by the same class in different parts of OOXML tree, +:node_name+ # extra parameter can be used to override the default element name. # === Parameters # * +element_name+ # ==== Examples # define_element_name 'externalReference' def define_element_name(element_name) self.class_variable_set(:@@ooxml_tag_name, element_name) end def parse(node, known_namespaces = nil) case node when String, IO, Zip::InputStream then node = Nokogiri::XML.parse(node) end if node.is_a?(Nokogiri::XML::Document) then @namespaces = node.namespaces node = node.root # ignorable_attr = node.attributes['Ignorable'] # @ignorables << ignorable_attr.value if ignorable_attr end obj = self.new known_attributes = obtain_class_variable(:@@ooxml_attributes) content_params = known_attributes['_'] process_attribute(obj, node.text, content_params) if content_params node.attributes.each_pair { |attr_name, attr| attr_name = if attr.namespace then "#{attr.namespace.prefix}:#{attr.name}" else attr.name end attr_params = known_attributes[attr_name] next if attr_params.nil? # raise "Unknown attribute [#{attr_name}] for element [#{node.name}]" if attr_params.nil? process_attribute(obj, attr.value, attr_params) unless attr_params[:computed] } known_child_nodes = obtain_class_variable(:@@ooxml_child_nodes) unless known_child_nodes.empty? known_namespaces ||= obtain_class_variable(:@@ooxml_namespaces) node.element_children.each { |child_node| ns = child_node.namespace prefix = known_namespaces[ns.href] || ns.prefix child_node_name = case prefix when '', nil then child_node.name else "#{prefix}:#{child_node.name}" end child_node_params = known_child_nodes[child_node_name] raise "Unknown child node [#{child_node_name}] for element [#{node.name}]" if child_node_params.nil? parsed_object = child_node_params[:class].parse(child_node, known_namespaces) if child_node_params[:is_array] then index = parsed_object.index_in_collection collection = if (self < RubyXL::OOXMLContainerObject) then obj else obj.send(child_node_params[:accessor]) end if index.nil? then collection << parsed_object else collection[index] = parsed_object end else obj.send("#{child_node_params[:accessor]}=", parsed_object) end } end obj end private def accessorize(str) acc = str.to_s.dup acc.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2') acc.gsub!(/([a-z\d])([A-Z])/,'\1_\2') acc.gsub!(':','_') acc.downcase.to_sym end def process_attribute(obj, raw_value, params) val = raw_value && case params[:attr_type] when :double then Float(raw_value) # http://www.datypic.com/sc/xsd/t-xsd_double.html when :string then raw_value when Array then raw_value # Case of Simple Types when :sqref then RubyXL::Sqref.new(raw_value) when :ref then RubyXL::Reference.new(raw_value) when :bool then ['1', 'true'].include?(raw_value) when :int then Integer(raw_value) when :uint then v = Integer(raw_value) raise ArgumentError.new("invalid value for unsigned Integer(): \"#{raw_value}\"") if v < 0 v end obj.send("#{params[:accessor]}=", val) end end module OOXMLObjectInstanceMethods def self.included(klass) klass.extend RubyXL::OOXMLObjectClassMethods end def obtain_class_variable(var_name, default = {}) self.class.obtain_class_variable(var_name, default) end private :obtain_class_variable def initialize(params = {}) obtain_class_variable(:@@ooxml_attributes).each_value { |v| instance_variable_set("@#{v[:accessor]}", params[v[:accessor]]) unless v[:computed] } init_child_nodes(params) instance_variable_set("@count", 0) if obtain_class_variable(:@@ooxml_countable, false) end def init_child_nodes(params) obtain_class_variable(:@@ooxml_child_nodes).each_value { |v| initial_value = if params.has_key?(v[:accessor]) then params[v[:accessor]] elsif v[:is_array] then [] else nil end instance_variable_set("@#{v[:accessor]}", initial_value) } end private :init_child_nodes # Recursively write the OOXML object and all its children out as Nokogiri::XML. Immediately before the actual # generation, +before_write_xml()+ is called to perform last-minute cleanup and validation operations; if it # returns +false+, an empty string is returned (rather than +nil+, so Nokogiri::XML's <tt>&lt;&lt;</tt> operator # can be used without additional +nil+ checking) # === Parameters # * +xml+ - Base Nokogiri::XML object used for building. If omitted, a blank document will be generated. # * +node_name_override+ - if present, is used instead of the default element name for this object provided by +define_element_name+ # ==== Examples # obj.write_xml() # Creates a new empty +Nokogiri::XML+, populates it with the OOXML structure as described in the respective definition, and returns the resulting +Nokogiri::XML+ object. # obj.write_xml(seed_xml) # Using the passed-in +Nokogiri+ +xml+ object, creates a new element corresponding to +obj+ according to its definition, along with all its properties and children, and returns the newly created element. # obj.write_xml(seed_xml, 'overriden_element_name') # Same as above, but uses the passed-in +node_name_override+ as the new element name, instead of its default name set by +define_element_name+. def write_xml(xml = nil, node_name_override = nil) if xml.nil? then seed_xml = Nokogiri::XML('<?xml version = "1.0" standalone ="yes"?>') seed_xml.encoding = 'UTF-8' result = self.write_xml(seed_xml) return result if result == '' seed_xml << result return seed_xml.to_xml({ :indent => 0, :save_with => Nokogiri::XML::Node::SaveOptions::AS_XML }) end return '' unless before_write_xml # Populate namespaces, if any attrs = {} obtain_class_variable(:@@ooxml_namespaces).each_pair { |k, v| attrs[v.empty? ? 'xmlns' : "xmlns:#{v}"] = k } obtain_class_variable(:@@ooxml_attributes).each_pair { |k, v| val = self.send(v[:accessor]) if val.nil? then next unless v[:required] val = v[:default] end val = val && case v[:attr_type] when :bool then val ? '1' : '0' when :double then val.to_s.gsub(/\.0*\Z/, '') # Trim trailing zeroes else val end attrs[k] = val } element_text = attrs.delete('_') elem = xml.create_element(node_name_override || obtain_class_variable(:@@ooxml_tag_name), attrs, element_text) child_nodes = obtain_class_variable(:@@ooxml_child_nodes) child_nodes.each_pair { |child_node_name, child_node_params| node_obj = get_node_object(child_node_params) next if node_obj.nil? if node_obj.respond_to?(:write_xml) && !node_obj.equal?(self) then # If child node is either +OOXMLObject+, or +OOXMLContainerObject+ on its first (envelope) pass, # serialize that object. elem << node_obj.write_xml(xml, child_node_name) else # If child node is either vanilla +Array+, or +OOXMLContainerObject+ on its seconds (content) pass, # serialize write its members. node_obj.each { |item| elem << item.write_xml(xml, child_node_name) unless item.nil? } end } elem end def dup new_copy = super new_copy.count = 0 if obtain_class_variable(:@@ooxml_countable, false) new_copy end # Prototype method. For sparse collections (+Rows+, +Cells+, etc.) must return index at which this object # is expected to reside in the collection. If +nil+ is returned, then object is simply added # to the end of the collection. def index_in_collection nil end def get_node_object(child_node_params) self.send(child_node_params[:accessor]) end private :get_node_object # Subclass provided filter to perform last-minute operations (cleanup, count, etc.) immediately prior to write, # along with option to terminate the actual write if +false+ is returned (for example, to avoid writing # the collection's root node if the collection is empty). def before_write_xml #TODO# This will go away once containers are fully implemented. child_nodes = obtain_class_variable(:@@ooxml_child_nodes) child_nodes.each_pair { |child_node_name, child_node_params| self.count = self.send(child_node_params[:accessor]).size if child_node_params[:is_array] == :with_count } true end end # Parent class for defining OOXML based objects (not unlike Rails' +ActiveRecord+!) # Most importantly, provides functionality of parsing such objects from XML, # and marshalling them to XML. class OOXMLObject include OOXMLObjectInstanceMethods end # Parent class for OOXML conainer objects (for example, # <tt>&lt;fonts&gt;&lt;font&gt;...&lt;/font&gt;&lt;font&gt;...&lt;/font&gt;&lt;/fonts&gt;</tt> # that obscures the top-level container, allowing direct access to the contents as +Array+. class OOXMLContainerObject < Array include OOXMLObjectInstanceMethods def initialize(params = {}) array_content = params.delete(:_) super array_content.each_with_index { |v, i| self[i] = v } if array_content end def get_node_object(child_node_params) if child_node_params[:is_array] then self else super end end protected :get_node_object def init_child_nodes(params) obtain_class_variable(:@@ooxml_child_nodes).each_value { |v| next if v[:is_array] # Only one collection node allowed per OOXMLContainerObject, and it is contained in itself. instance_variable_set("@#{v[:accessor]}", params[v[:accessor]]) } end protected :init_child_nodes def before_write_xml true end def inspect vars = [ super ] vars = self.instance_variables.each { |v| vars << "#{v}=#{instance_variable_get(v).inspect}" } "<#{self.class}: #{super} #{vars.join(", ")}>" end class << self def define_count_attribute # Count will be inherited from Array. so no need to define it explicitly. define_attribute(:count, :uint, :required => true, :computed => true) end protected :define_count_attribute end end # Extension class providing functionality for top-level OOXML objects that are represented by # their own <tt>.xml</tt> files in <tt>.xslx</tt> zip container. class OOXMLTopLevelObject < OOXMLObject SAVE_ORDER = 500 ROOT = ::Pathname.new('/') attr_accessor :root # Prototype method. For top-level OOXML object, returns the path at which the current object's XML file # is located within the <tt>.xslx</tt> zip container. def xlsx_path raise 'Subclass responsebility' end # Sets the list of namespaces on this object to be added when writing out XML. Valid only on top-level objects. # === Parameters # * +namespace_hash+ - Hash of namespaces in the form of <tt>"prefix" => "url"</tt> # ==== Examples # set_namespaces('http://schemas.openxmlformats.org/spreadsheetml/2006/main' => '', # 'http://schemas.openxmlformats.org/officeDocument/2006/relationships' => 'r') def self.set_namespaces(namespace_hash) self.class_variable_set(:@@ooxml_namespaces, namespace_hash) end # Generates the top-level OOXML object by parsing its XML file from the temporary # directory containing the unzipped contents of <tt>.xslx</tt> # === Parameters # * +dirpath+ - path to the directory with the unzipped <tt>.xslx</tt> contents. def self.parse_file(zip_file, file_path) entry = zip_file.find_entry(RubyXL::from_root(file_path)) # Accomodate for Nokogiri Java implementation which is incapable of reading from a stream entry && (entry.get_input_stream { |f| parse(defined?(JRUBY_VERSION) ? f.read : f) }) end # Saves the contents of the object as XML to respective location in <tt>.xslx</tt> zip container. # === Parameters # * +zipfile+ - ::Zip::File to which the resulting XNMML should be added. def add_to_zip(zip_stream) xml_string = write_xml return if xml_string.empty? zip_stream.put_next_entry(RubyXL::from_root(self.xlsx_path)) zip_stream.write(xml_string) end def file_index root.rels_hash[self.class].index{ |f| f.equal?(self) }.to_i + 1 end end end
module RubyProvisioningApi class Group < Entity attr_accessor :group_id, :group_name, :description, :email_permission attr_reader :GROUP_PATH GROUP_PATH = "/group/2.0/#{RubyProvisioningApi.configuration[:domain]}" ACTIONS = { :create => { method: "POST" , url: "#{GROUP_PATH}"}, :update => { method: "PUT" , url: "#{GROUP_PATH}/groupId"}, :delete => { method: "DELETE" , url: "#{GROUP_PATH}/groupId"}, :retrieve_all => { method: "GET" , url: "#{GROUP_PATH}" }, :retrieve_groups => { method: "GET" , url: "#{GROUP_PATH}/?member=memberId" }, :retrieve => { method: "GET" , url: "#{GROUP_PATH}/groupId" } } HTTP_OK_STATUS = [200,201] def initialize(group_id, group_name, description, email_permission) self.group_id = group_id self.group_name = group_name self.description = description self.email_permission = email_permission end def initialize end # Retrieve all groups in a domain GET https://apps-apis.google.com/a/feeds/group/2.0/domain[?[start=]] def self.all response = perform(ACTIONS[:retrieve_all]) case response.status when 200 # Parse the response xml = Nokogiri::XML(response.body) groups = [] xml.children.css("entry").each do |entry| group = Group.new for attribute_name in ['groupId','groupName','description','emailPermission'] group.send("#{attribute_name.underscore}=", entry.css("apps|property[name='#{attribute_name}']").attribute("value").value) end groups << group end groups when 400 # Gapps error? xml = Nokogiri::XML(response.body) error_code = xml.xpath('//error').first.attributes["errorCode"].value error_description = xml.xpath('//error').first.attributes["reason"].value puts "Google provisioning Api error #{error_code}: #{error_description}" end end # Save(Create) a group POST https://apps-apis.google.com/a/feeds/group/2.0/domain def save Group.create(group_id, group_name, description, email_permission) end # Create a group POST https://apps-apis.google.com/a/feeds/group/2.0/domain def self.create(group_id, group_name, description, email_permission) builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml| xml.send(:'atom:entry', 'xmlns:atom' => 'http://www.w3.org/2005/Atom', 'xmlns:apps' => 'http://schemas.google.com/apps/2006') { xml.send(:'atom:category', 'scheme' => 'http://schemas.google.com/g/2005#kind', 'term' => 'http://schemas.google.com/apps/2006#emailList') xml.send(:'apps:property', 'name' => 'groupId', 'value' => group_id) xml.send(:'apps:property', 'name' => 'groupName', 'value' => group_name) xml.send(:'apps:property', 'name' => 'description', 'value' => description) xml.send(:'apps:property', 'name' => 'emailPermission', 'value' => email_permission) } end HTTP_OK_STATUS.include?(perform(ACTIONS[:create],builder.to_xml).status) end # Retrieve a group GET https://apps-apis.google.com/a/feeds/group/2.0/domain/groupId def self.find(group_id) # Creating a deep copy of ACTION object params = Marshal.load(Marshal.dump(ACTIONS[:retrieve])) # Replacing place holder groupId with correct group_id params[:url].gsub!("groupId",group_id) response = perform(params) # Check if the response contains an error check_response(response) # Parse the response xml = Nokogiri::XML(response.body) group = Group.new for attribute_name in ['groupId','groupName','description','emailPermission'] group.send("#{attribute_name.underscore}=",xml.children.css("entry apps|property[name='#{attribute_name}']").attribute("value").value) end group end #update attributes # Update group information PUT https://apps-apis.google.com/a/feeds/group/2.0/domain/groupId def update # Creating a deep copy of ACTION object params = Marshal.load(Marshal.dump(ACTIONS[:update])) # Replacing place holder groupId with correct group_id params[:url].gsub!("groupId",group_id) builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml| xml.send(:'atom:entry', 'xmlns:atom' => 'http://www.w3.org/2005/Atom', 'xmlns:apps' => 'http://schemas.google.com/apps/2006') { xml.send(:'atom:category', 'scheme' => 'http://schemas.google.com/g/2005#kind', 'term' => 'http://schemas.google.com/apps/2006#emailList') xml.send(:'apps:property', 'name' => 'groupName', 'value' => group_name) xml.send(:'apps:property', 'name' => 'description', 'value' => description) xml.send(:'apps:property', 'name' => 'emailPermission', 'value' => email_permission) } end HTTP_OK_STATUS.include?(Entity.perform(params,builder.to_xml).status) end # Delete group DELETE https://apps-apis.google.com/a/feeds/group/2.0/domain/groupId def self.delete(group_id) # Creating a deep copy of ACTION object params = Marshal.load(Marshal.dump(ACTIONS[:delete])) # Replacing place holder groupId with correct group_id params[:url].gsub!("groupId",group_id) HTTP_OK_STATUS.include?(perform(params).status) end # Retrieve all groups for a member GET https://apps-apis.google.com/a/feeds/group/2.0/domain/?member=memberId[&directOnly=true|false] def self.groups(member_id) # Creating a deep copy of ACTION object params = Marshal.load(Marshal.dump(ACTIONS[:retrieve_groups])) # Replacing place holder groupId with correct group_id params[:url].gsub!("memberId",member_id) response = perform(params) case response.status when 200 # Parse the response xml = Nokogiri::XML(response.body) groups = [] xml.children.css("entry").each do |entry| group = Group.new for attribute_name in ['groupId','groupName','description','emailPermission'] group.send("#{attribute_name.underscore}=", entry.css("apps|property[name='#{attribute_name}']").attribute("value").value) end groups << group end groups when 400 # Gapps error? xml = Nokogiri::XML(response.body) error_code = xml.xpath('//error').first.attributes["errorCode"].value error_description = xml.xpath('//error').first.attributes["reason"].value puts "Google provisioning Api error #{error_code}: #{error_description}" end end end end Update , update attributes and create relate now to save module RubyProvisioningApi class Group < Entity attr_accessor :group_id, :group_name, :description, :email_permission attr_reader :GROUP_PATH GROUP_PATH = "/group/2.0/#{RubyProvisioningApi.configuration[:domain]}" ACTIONS = { :create => { method: "POST" , url: "#{GROUP_PATH}"}, :update => { method: "PUT" , url: "#{GROUP_PATH}/groupId"}, :delete => { method: "DELETE" , url: "#{GROUP_PATH}/groupId"}, :retrieve_all => { method: "GET" , url: "#{GROUP_PATH}" }, :retrieve_groups => { method: "GET" , url: "#{GROUP_PATH}/?member=memberId" }, :retrieve => { method: "GET" , url: "#{GROUP_PATH}/groupId" } } GROUP_ATTRIBUTES = [:groupId,:groupName,:description,:emailPermission] # Group initialization # Params: # groupId, groupName, description, emailPermission def initialize(params = nil) if params.nil? || (params.has_key?(:group_id) && params.has_key?(:group_name) && params.has_key?(:description) && params.has_key?(:email_permission)) if params self.group_id = params[:group_id] self.group_name = params[:group_name] self.description = params[:description] self.email_permission = params[:email_permission] end else raise InvalidArgument end end # Retrieve all groups in a domain GET https://apps-apis.google.com/a/feeds/group/2.0/domain[?[start=]] def self.all # Perform the request & Check if the response contains an error check_response(perform(ACTIONS[:retrieve_all])) # Parse the response xml = Nokogiri::XML(response.body) # Prepare a Groups array groups = [] xml.children.css("entry").each do |entry| group = Group.new GROUP_ATTRIBUTES.each do |attribute_name| group.send("#{attribute_name.underscore}=", entry.css("apps|property[name='#{attribute_name}']").attribute("value").value) end # Fill groups array groups << group end # Return the array of Groups groups end # Save(Create) a group POST https://apps-apis.google.com/a/feeds/group/2.0/domain def save update = false begin Group.find(group_id) update = true rescue "RubyProvisioningApi::EntityDoesNotExist" end # Creating the XML request builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml| xml.send(:'atom:entry', 'xmlns:atom' => 'http://www.w3.org/2005/Atom', 'xmlns:apps' => 'http://schemas.google.com/apps/2006') { xml.send(:'atom:category', 'scheme' => 'http://schemas.google.com/g/2005#kind', 'term' => 'http://schemas.google.com/apps/2006#emailList') xml.send(:'apps:property', 'name' => 'groupId', 'value' => group_id) if !update xml.send(:'apps:property', 'name' => 'groupName', 'value' => group_name) xml.send(:'apps:property', 'name' => 'description', 'value' => description) xml.send(:'apps:property', 'name' => 'emailPermission', 'value' => email_permission) } end if !update #Acting on a new object # Check if the response contains an error Entity.check_response(Entity.perform(ACTIONS[:create],builder.to_xml)) else #Acting on an existing object # Creating a deep copy of ACTION object params = Marshal.load(Marshal.dump(ACTIONS[:update])) # Replacing placeholder groupId with correct group_id params[:url].gsub!("groupId",group_id) # Perform the request & Check if the response contains an error Entity.check_response(Entity.perform(params,builder.to_xml)) end end # Create a group POST https://apps-apis.google.com/a/feeds/group/2.0/domain # Group initialization # Params: # groupId, groupName, description, emailPermission def self.create(params = {}) if params.has_key?(:group_id) && params.has_key?(:group_name) && params.has_key?(:description) && params.has_key?(:email_permission) # Set attributes group = Group.new(:group_id => params[:group_id], :group_name => params[:group_name], :description => params[:description], :email_permission => params[:email_permission]) # Save group group.save else raise InvalidArgument end end # Retrieve a group GET https://apps-apis.google.com/a/feeds/group/2.0/domain/groupId def self.find(group_id) # Creating a deep copy of ACTION object params = Marshal.load(Marshal.dump(ACTIONS[:retrieve])) # Replacing place holder groupId with correct group_id params[:url].gsub!("groupId",group_id) response = perform(params) # Check if the response contains an error check_response(response) # Parse the response xml = Nokogiri::XML(response.body) group = Group.new for attribute_name in ['groupId','groupName','description','emailPermission'] group.send("#{attribute_name.underscore}=",xml.children.css("entry apps|property[name='#{attribute_name}']").attribute("value").value) end group end # Update group information PUT https://apps-apis.google.com/a/feeds/group/2.0/domain/groupId def update_attributes(params) self.group_name = params[:group_name] if params[:group_name] self.description = params[:description] if params[:description] self.email_permission = params[:email_permission] if params[:email_permission] update end def update save end # Delete group DELETE https://apps-apis.google.com/a/feeds/group/2.0/domain/groupId def delete # Creating a deep copy of ACTION object params = Marshal.load(Marshal.dump(ACTIONS[:delete])) # Replacing placeholder groupId with correct group_id params[:url].gsub!("groupId",group_id) # Perform the request & Check if the response contains an error Entity.check_response(Entity.perform(params)) end # Retrieve all groups for a member GET https://apps-apis.google.com/a/feeds/group/2.0/domain/?member=memberId[&directOnly=true|false] def self.groups(member_id) # Creating a deep copy of ACTION object params = Marshal.load(Marshal.dump(ACTIONS[:retrieve_groups])) # Replacing place holder groupId with correct group_id params[:url].gsub!("memberId",member_id) response = perform(params) # Perform the request & Check if the response contains an error check_response(response) # Parse the response xml = Nokogiri::XML(response.body) # Prepare a Groups array groups = [] xml.children.css("entry").each do |entry| # Prepare a Group object group = Group.new GROUP_ATTRIBUTES.each do |attribute_name| # Set group attributes group.send("#{attribute_name.underscore}=", entry.css("apps|property[name='#{attribute_name}']").attribute("value").value) end # Fill groups array groups << group end # Return the array of Groups groups end end end
module ScopedSearch # The QueryBuilder class builds an SQL query based on aquery string that is # provided to the search_for named scope. It uses a SearchDefinition instance # to shape the query. class QueryBuilder attr_reader :ast, :definition # Creates a find parameter hash that can be passed to ActiveRecord::Base#find, # given a search definition and query string. This method is called from the # search_for named scope. # # This method will parse the query string and build an SQL query using the search # query. It will return an ampty hash if the search query is empty, in which case # the scope call will simply return all records. def self.build_query(definition, *args) query = args[0] options = args[1] || {} query_builder_class = self.class_for(definition) if query.kind_of?(ScopedSearch::QueryLanguage::AST::Node) return query_builder_class.new(definition, query, options[:profile]).build_find_params elsif query.kind_of?(String) return query_builder_class.new(definition, ScopedSearch::QueryLanguage::Compiler.parse(query), options[:profile]).build_find_params elsif query.nil? return { } else raise "Unsupported query object: #{query.inspect}!" end end # Loads the QueryBuilder class for the connection of the given definition. # If no specific adapter is found, the default QueryBuilder class is returned. def self.class_for(definition) self.const_get(definition.klass.connection.class.name.split('::').last) rescue self end # Initializes the instance by setting the relevant parameters def initialize(definition, ast, profile) @definition, @ast, @definition.profile = definition, ast, profile end # Actually builds the find parameters hash that should be used in the search_for # named scope. def build_find_params parameters = [] includes = [] # Build SQL WHERE clause using the AST sql = @ast.to_sql(self, definition) do |notification, value| # Handle the notifications encountered during the SQL generation: # Store the parameters, includes, etc so that they can be added to # the find-hash later on. case notification when :parameter then parameters << value when :include then includes << value else raise ScopedSearch::QueryNotSupported, "Cannot handle #{notification.inspect}: #{value.inspect}" end end # Build hash for ActiveRecord::Base#find for the named scope find_attributes = {} find_attributes[:conditions] = [sql] + parameters unless sql.nil? find_attributes[:include] = includes.uniq unless includes.empty? # p find_attributes # Uncomment for debugging return find_attributes end # A hash that maps the operators of the query language with the corresponding SQL operator. SQL_OPERATORS = { :eq =>'=', :ne => '<>', :like => 'LIKE', :unlike => 'NOT LIKE', :gt => '>', :lt =>'<', :lte => '<=', :gte => '>=' } # Return the SQL operator to use given an operator symbol and field definition. # # By default, it will simply look up the correct SQL operator in the SQL_OPERATORS # hash, but this can be overrided by a database adapter. def sql_operator(operator, field) SQL_OPERATORS[operator] end # Perform a comparison between a field and a Date(Time) value. # # This function makes sure the date is valid and adjust the comparison in # some cases to return more logical results. # # This function needs a block that can be used to pass other information about the query # (parameters that should be escaped, includes) to the query builder. # # <tt>field</tt>:: The field to test. # <tt>operator</tt>:: The operator used for comparison. # <tt>value</tt>:: The value to compare the field with. def datetime_test(field, operator, value, &block) # :yields: finder_option_type, value # Parse the value as a date/time and ignore invalid timestamps timestamp = parse_temporal(value) return nil unless timestamp timestamp = Date.parse(timestamp.strftime('%Y-%m-%d')) if field.date? # Check for the case that a date-only value is given as search keyword, # but the field is of datetime type. Change the comparison to return # more logical results. if timestamp.day_fraction == 0 && field.datetime? if [:eq, :ne].include?(operator) # Instead of looking for an exact (non-)match, look for dates that # fall inside/outside the range of timestamps of that day. yield(:parameter, timestamp) yield(:parameter, timestamp + 1) negate = (operator == :ne) ? 'NOT' : '' field_sql = field.to_sql(operator, &block) return "#{negate}(#{field_sql} >= ? AND #{field_sql} < ?)" elsif operator == :gt # Make sure timestamps on the given date are not included in the results # by moving the date to the next day. timestamp += 1 operator = :gte elsif operator == :lte # Make sure the timestamps of the given date are included by moving the # date to the next date. timestamp += 1 operator = :lt end end # Yield the timestamp and return the SQL test yield(:parameter, timestamp) "#{field.to_sql(operator, &block)} #{sql_operator(operator, field)} ?" end # Generates a simple SQL test expression, for a field and value using an operator. # # This function needs a block that can be used to pass other information about the query # (parameters that should be escaped, includes) to the query builder. # # <tt>field</tt>:: The field to test. # <tt>operator</tt>:: The operator used for comparison. # <tt>value</tt>:: The value to compare the field with. def sql_test(field, operator, value, &block) # :yields: finder_option_type, value if [:like, :unlike].include?(operator) && value !~ /^\%/ && value !~ /\%$/ yield(:parameter, "%#{value}%") return "#{field.to_sql(operator, &block)} #{self.sql_operator(operator, field)} ?" elsif field.temporal? return datetime_test(field, operator, value, &block) else yield(:parameter, value) return "#{field.to_sql(operator, &block)} #{self.sql_operator(operator, field)} ?" end end # Try to parse a string as a datetime. def parse_temporal(value) DateTime.parse(value, true) rescue nil end # This module gets included into the Field class to add SQL generation. module Field # Return an SQL representation for this field. Also make sure that # the relation which includes the search field is included in the # SQL query. # # This function may yield an :include that should be used in the # ActiveRecord::Base#find call, to make sure that the field is avalable # for the SQL query. def to_sql(builder, operator = nil, &block) # :yields: finder_option_type, value yield(:include, relation) if relation definition.klass.connection.quote_table_name(klass.table_name) + "." + definition.klass.connection.quote_column_name(field) end end # This module contains modules for every AST::Node class to add SQL generation. module AST # Defines the to_sql method for AST LeadNodes module LeafNode def to_sql(builder, definition, &block) # Search keywords found without context, just search on all the default fields fragments = definition.default_fields_for(value).map do |field| builder.sql_test(field, field.default_operator, value, &block) end "(#{fragments.join(' OR ')})" end end # Defines the to_sql method for AST operator nodes module OperatorNode # Returns a NOT(...) SQL fragment that negates the current AST node's children def to_not_sql(builder, definition, &block) "(NOT(#{rhs.to_sql(builder, definition, &block)}) OR #{rhs.to_sql(builder, definition, &block)} IS NULL)" end # Returns an IS (NOT) NULL SQL fragment def to_null_sql(builder, definition, &block) field = definition.fields[rhs.value.to_sym] raise ScopedSearch::QueryNotSupported, "Field '#{rhs.value}' not recognized for searching!" unless field case operator when :null then "#{field.to_sql(builder, &block)} IS NULL" when :notnull then "#{field.to_sql(builder, &block)} IS NOT NULL" end end # No explicit field name given, run the operator on all default fields def to_default_fields_sql(builder, definition, &block) raise ScopedSearch::QueryNotSupported, "Value not a leaf node" unless rhs.kind_of?(ScopedSearch::QueryLanguage::AST::LeafNode) # Search keywords found without context, just search on all the default fields fragments = definition.default_fields_for(rhs.value, operator).map { |field| builder.sql_test(field, operator, rhs.value, &block) }.compact fragments.empty? ? nil : "(#{fragments.join(' OR ')})" end # Explicit field name given, run the operator on the specified field only def to_single_field_sql(builder, definition, &block) raise ScopedSearch::QueryNotSupported, "Field name not a leaf node" unless lhs.kind_of?(ScopedSearch::QueryLanguage::AST::LeafNode) raise ScopedSearch::QueryNotSupported, "Value not a leaf node" unless rhs.kind_of?(ScopedSearch::QueryLanguage::AST::LeafNode) # Search only on the given field. field = definition.fields[lhs.value.to_sym] raise ScopedSearch::QueryNotSupported, "Field '#{lhs.value}' not recognized for searching!" unless field builder.sql_test(field, operator, rhs.value, &block) end # Convert this AST node to an SQL fragment. def to_sql(builder, definition, &block) if operator == :not && children.length == 1 to_not_sql(builder, definition, &block) elsif [:null, :notnull].include?(operator) to_null_sql(builder, definition, &block) elsif children.length == 1 to_default_fields_sql(builder, definition, &block) elsif children.length == 2 to_single_field_sql(builder, definition, &block) else raise ScopedSearch::QueryNotSupported, "Don't know how to handle this operator node: #{operator.inspect} with #{children.inspect}!" end end end # Defines the to_sql method for AST AND/OR operators module LogicalOperatorNode def to_sql(builder, definition, &block) fragments = children.map { |c| c.to_sql(builder, definition, &block) }.compact fragments.empty? ? nil : "(#{fragments.join(" #{operator.to_s.upcase} ")})" end end end # The MysqlAdapter makes sure that case sensitive comparisons are used # when using the (not) equals operator, regardless of the field's # collation setting. class MysqlAdapter < ScopedSearch::QueryBuilder # Patches the default <tt>sql_operator</tt> method to add # <tt>BINARY</tt> after the equals and not equals operator to force # case-sensitive comparisons. def sql_operator(operator, field) if [:ne, :eq].include?(operator) && field.textual? "#{SQL_OPERATORS[operator]} BINARY" else super(operator, field) end end end # The PostgreSQLAdapter make sure that searches are case sensitive when # using the like/unlike operators, by using the PostrgeSQL-specific # <tt>ILIKE operator</tt> instead of <tt>LIKE</tt>. class PostgreSQLAdapter < ScopedSearch::QueryBuilder # Switches out the default LIKE operator for ILIKE in the default # <tt>sql_operator</tt> method. def sql_operator(operator, field) case operator when :like then 'ILIKE' when :unlike then 'NOT ILIKE' else super(operator, field) end end end # The Oracle adapter also requires some tweaks to make the case insensitive LIKE work. class OracleEnhancedAdapter < ScopedSearch::QueryBuilder # Use REGEXP_LIKE for case insensitive comparisons def sql_operator(operator, field) case operator when :like then 'REGEXP_LIKE' when :unlike then 'NOT REGEXP_LIKE' else super(operator, field) end end def sql_test(field, operator, value, &block) # :yields: finder_option_type, value if field.textual? && [:like, :unlike].include?(operator) regexp_value = if value !~ /^\%/ && value !~ /\%$/ Regexp.quote(value) else "^#{Regexp.quote(value)}$".sub(/^\^%/, '').sub(/%\$$/, '') end yield(:parameter, regexp_value) return "#{self.sql_operator(operator, field)}(#{field.to_sql(operator, &block)}, ?, 'i')" else super(field, operator, value, &block) end end end end # Include the modules into the corresponding classes # to add SQL generation capabilities to them. Definition::Field.send(:include, QueryBuilder::Field) QueryLanguage::AST::LeafNode.send(:include, QueryBuilder::AST::LeafNode) QueryLanguage::AST::OperatorNode.send(:include, QueryBuilder::AST::OperatorNode) QueryLanguage::AST::LogicalOperatorNode.send(:include, QueryBuilder::AST::LogicalOperatorNode) end Fix attempt for Oracle adapter. module ScopedSearch # The QueryBuilder class builds an SQL query based on aquery string that is # provided to the search_for named scope. It uses a SearchDefinition instance # to shape the query. class QueryBuilder attr_reader :ast, :definition # Creates a find parameter hash that can be passed to ActiveRecord::Base#find, # given a search definition and query string. This method is called from the # search_for named scope. # # This method will parse the query string and build an SQL query using the search # query. It will return an ampty hash if the search query is empty, in which case # the scope call will simply return all records. def self.build_query(definition, *args) query = args[0] options = args[1] || {} query_builder_class = self.class_for(definition) if query.kind_of?(ScopedSearch::QueryLanguage::AST::Node) return query_builder_class.new(definition, query, options[:profile]).build_find_params elsif query.kind_of?(String) return query_builder_class.new(definition, ScopedSearch::QueryLanguage::Compiler.parse(query), options[:profile]).build_find_params elsif query.nil? return { } else raise "Unsupported query object: #{query.inspect}!" end end # Loads the QueryBuilder class for the connection of the given definition. # If no specific adapter is found, the default QueryBuilder class is returned. def self.class_for(definition) self.const_get(definition.klass.connection.class.name.split('::').last) rescue self end # Initializes the instance by setting the relevant parameters def initialize(definition, ast, profile) @definition, @ast, @definition.profile = definition, ast, profile end # Actually builds the find parameters hash that should be used in the search_for # named scope. def build_find_params parameters = [] includes = [] # Build SQL WHERE clause using the AST sql = @ast.to_sql(self, definition) do |notification, value| # Handle the notifications encountered during the SQL generation: # Store the parameters, includes, etc so that they can be added to # the find-hash later on. case notification when :parameter then parameters << value when :include then includes << value else raise ScopedSearch::QueryNotSupported, "Cannot handle #{notification.inspect}: #{value.inspect}" end end # Build hash for ActiveRecord::Base#find for the named scope find_attributes = {} find_attributes[:conditions] = [sql] + parameters unless sql.nil? find_attributes[:include] = includes.uniq unless includes.empty? # p find_attributes # Uncomment for debugging return find_attributes end # A hash that maps the operators of the query language with the corresponding SQL operator. SQL_OPERATORS = { :eq =>'=', :ne => '<>', :like => 'LIKE', :unlike => 'NOT LIKE', :gt => '>', :lt =>'<', :lte => '<=', :gte => '>=' } # Return the SQL operator to use given an operator symbol and field definition. # # By default, it will simply look up the correct SQL operator in the SQL_OPERATORS # hash, but this can be overrided by a database adapter. def sql_operator(operator, field) SQL_OPERATORS[operator] end # Perform a comparison between a field and a Date(Time) value. # # This function makes sure the date is valid and adjust the comparison in # some cases to return more logical results. # # This function needs a block that can be used to pass other information about the query # (parameters that should be escaped, includes) to the query builder. # # <tt>field</tt>:: The field to test. # <tt>operator</tt>:: The operator used for comparison. # <tt>value</tt>:: The value to compare the field with. def datetime_test(field, operator, value, &block) # :yields: finder_option_type, value # Parse the value as a date/time and ignore invalid timestamps timestamp = parse_temporal(value) return nil unless timestamp timestamp = Date.parse(timestamp.strftime('%Y-%m-%d')) if field.date? # Check for the case that a date-only value is given as search keyword, # but the field is of datetime type. Change the comparison to return # more logical results. if timestamp.day_fraction == 0 && field.datetime? if [:eq, :ne].include?(operator) # Instead of looking for an exact (non-)match, look for dates that # fall inside/outside the range of timestamps of that day. yield(:parameter, timestamp) yield(:parameter, timestamp + 1) negate = (operator == :ne) ? 'NOT' : '' field_sql = field.to_sql(operator, &block) return "#{negate}(#{field_sql} >= ? AND #{field_sql} < ?)" elsif operator == :gt # Make sure timestamps on the given date are not included in the results # by moving the date to the next day. timestamp += 1 operator = :gte elsif operator == :lte # Make sure the timestamps of the given date are included by moving the # date to the next date. timestamp += 1 operator = :lt end end # Yield the timestamp and return the SQL test yield(:parameter, timestamp) "#{field.to_sql(operator, &block)} #{sql_operator(operator, field)} ?" end # Generates a simple SQL test expression, for a field and value using an operator. # # This function needs a block that can be used to pass other information about the query # (parameters that should be escaped, includes) to the query builder. # # <tt>field</tt>:: The field to test. # <tt>operator</tt>:: The operator used for comparison. # <tt>value</tt>:: The value to compare the field with. def sql_test(field, operator, value, &block) # :yields: finder_option_type, value if [:like, :unlike].include?(operator) && value !~ /^\%/ && value !~ /\%$/ yield(:parameter, "%#{value}%") return "#{field.to_sql(operator, &block)} #{self.sql_operator(operator, field)} ?" elsif field.temporal? return datetime_test(field, operator, value, &block) else yield(:parameter, value) return "#{field.to_sql(operator, &block)} #{self.sql_operator(operator, field)} ?" end end # Try to parse a string as a datetime. def parse_temporal(value) DateTime.parse(value, true) rescue nil end # This module gets included into the Field class to add SQL generation. module Field # Return an SQL representation for this field. Also make sure that # the relation which includes the search field is included in the # SQL query. # # This function may yield an :include that should be used in the # ActiveRecord::Base#find call, to make sure that the field is avalable # for the SQL query. def to_sql(operator = nil, &block) # :yields: finder_option_type, value yield(:include, relation) if relation definition.klass.connection.quote_table_name(klass.table_name) + "." + definition.klass.connection.quote_column_name(field) end end # This module contains modules for every AST::Node class to add SQL generation. module AST # Defines the to_sql method for AST LeadNodes module LeafNode def to_sql(builder, definition, &block) # Search keywords found without context, just search on all the default fields fragments = definition.default_fields_for(value).map do |field| builder.sql_test(field, field.default_operator, value, &block) end "(#{fragments.join(' OR ')})" end end # Defines the to_sql method for AST operator nodes module OperatorNode # Returns a NOT(...) SQL fragment that negates the current AST node's children def to_not_sql(builder, definition, &block) "(NOT(#{rhs.to_sql(builder, definition, &block)}) OR #{rhs.to_sql(builder, definition, &block)} IS NULL)" end # Returns an IS (NOT) NULL SQL fragment def to_null_sql(builder, definition, &block) field = definition.fields[rhs.value.to_sym] raise ScopedSearch::QueryNotSupported, "Field '#{rhs.value}' not recognized for searching!" unless field case operator when :null then "#{field.to_sql(builder, &block)} IS NULL" when :notnull then "#{field.to_sql(builder, &block)} IS NOT NULL" end end # No explicit field name given, run the operator on all default fields def to_default_fields_sql(builder, definition, &block) raise ScopedSearch::QueryNotSupported, "Value not a leaf node" unless rhs.kind_of?(ScopedSearch::QueryLanguage::AST::LeafNode) # Search keywords found without context, just search on all the default fields fragments = definition.default_fields_for(rhs.value, operator).map { |field| builder.sql_test(field, operator, rhs.value, &block) }.compact fragments.empty? ? nil : "(#{fragments.join(' OR ')})" end # Explicit field name given, run the operator on the specified field only def to_single_field_sql(builder, definition, &block) raise ScopedSearch::QueryNotSupported, "Field name not a leaf node" unless lhs.kind_of?(ScopedSearch::QueryLanguage::AST::LeafNode) raise ScopedSearch::QueryNotSupported, "Value not a leaf node" unless rhs.kind_of?(ScopedSearch::QueryLanguage::AST::LeafNode) # Search only on the given field. field = definition.fields[lhs.value.to_sym] raise ScopedSearch::QueryNotSupported, "Field '#{lhs.value}' not recognized for searching!" unless field builder.sql_test(field, operator, rhs.value, &block) end # Convert this AST node to an SQL fragment. def to_sql(builder, definition, &block) if operator == :not && children.length == 1 to_not_sql(builder, definition, &block) elsif [:null, :notnull].include?(operator) to_null_sql(builder, definition, &block) elsif children.length == 1 to_default_fields_sql(builder, definition, &block) elsif children.length == 2 to_single_field_sql(builder, definition, &block) else raise ScopedSearch::QueryNotSupported, "Don't know how to handle this operator node: #{operator.inspect} with #{children.inspect}!" end end end # Defines the to_sql method for AST AND/OR operators module LogicalOperatorNode def to_sql(builder, definition, &block) fragments = children.map { |c| c.to_sql(builder, definition, &block) }.compact fragments.empty? ? nil : "(#{fragments.join(" #{operator.to_s.upcase} ")})" end end end # The MysqlAdapter makes sure that case sensitive comparisons are used # when using the (not) equals operator, regardless of the field's # collation setting. class MysqlAdapter < ScopedSearch::QueryBuilder # Patches the default <tt>sql_operator</tt> method to add # <tt>BINARY</tt> after the equals and not equals operator to force # case-sensitive comparisons. def sql_operator(operator, field) if [:ne, :eq].include?(operator) && field.textual? "#{SQL_OPERATORS[operator]} BINARY" else super(operator, field) end end end # The PostgreSQLAdapter make sure that searches are case sensitive when # using the like/unlike operators, by using the PostrgeSQL-specific # <tt>ILIKE operator</tt> instead of <tt>LIKE</tt>. class PostgreSQLAdapter < ScopedSearch::QueryBuilder # Switches out the default LIKE operator for ILIKE in the default # <tt>sql_operator</tt> method. def sql_operator(operator, field) case operator when :like then 'ILIKE' when :unlike then 'NOT ILIKE' else super(operator, field) end end end # The Oracle adapter also requires some tweaks to make the case insensitive LIKE work. class OracleEnhancedAdapter < ScopedSearch::QueryBuilder def sql_test(field, operator, value, &block) # :yields: finder_option_type, value if field.textual? && [:like, :unlike].include?(operator) yield(:parameter, (value !~ /^\%/ && value !~ /\%$/) ? "%#{value.downcase}%" : value.downcase) return "LOWER(#{field.to_sql(operator, &block)}) #{self.sql_operator(operator, field)} ?" else super(field, operator, value, &block) end end end end # Include the modules into the corresponding classes # to add SQL generation capabilities to them. Definition::Field.send(:include, QueryBuilder::Field) QueryLanguage::AST::LeafNode.send(:include, QueryBuilder::AST::LeafNode) QueryLanguage::AST::OperatorNode.send(:include, QueryBuilder::AST::OperatorNode) QueryLanguage::AST::LogicalOperatorNode.send(:include, QueryBuilder::AST::LogicalOperatorNode) end
require 'pacproxy' require 'pacproxy/runtimes/base' require 'open-uri' require 'dnode' require 'thread' require 'os' module Pacproxy module Runtimes # Pacproxy::Runtimes::Node represet node js runtime class Node < Base include Loggable TIMEOUT_JS_CALL = 0.5 TIMEOUT_JS_SERVER = 5 attr_reader :source def self.runtime if Util.which('node').nil? error('No PAC supported runtime') fail(RuntimeUnavailable, 'No PAC supported runtime') end new end def initialize js = File.join(File.dirname(__FILE__), 'find.js') retries = 3 begin Timeout.timeout(TIMEOUT_JS_SERVER) do server = TCPServer.new('127.0.0.1', 0) @port = server.addr[1] server.close if OS.windows? @server_pid = start_server else @server_pid = fork { exec('node', js, @port.to_s) } Process.detach(@server_pid) end sleep 0.01 until port_open? @queue = Queue.new @client_thread = Thread.new do DNode.new.connect('127.0.0.1', @port) do |remote| q = @queue.pop if q[:uri] && q[:uri].host && q[:call_back] remote.find(@source, q[:uri], q[:uri].host, q[:call_back]) end end end end rescue Timeout::Error if retries > 0 retries -= 1 lwarn('Timeout. Initialize Node.js server.') retry else error('Gave up to retry Initialize Node.js server.') raise 'Gave up to retry Initialize Node.js server.' end end end def shutdown if OS.windows? stop_server(@server_pid) else @client_thread.kill Process.kill(:INT, @server_pid) end end def update(file_location) @source = open(file_location, proxy: false).read rescue @source = nil end def find(url) return 'DIRECT' unless @source uri = URI.parse(url) call_find(uri) end private def port_open? Timeout.timeout(TIMEOUT_JS_CALL) do begin TCPSocket.new('127.0.0.1', @port).close return true rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH return false end end rescue Timeout::Error false end def call_find(uri, retries = 3) proxy = nil begin thread = Thread.new do called = false @queue.push(uri: uri, call_back: proc do |p| proxy = p called = true end) loop do break if called sleep 0.01 end end thread.join(TIMEOUT_JS_CALL) proxy rescue Timeout::Error if retries > 0 retries -= 1 lwarn('Timeout. Retring call_find.') retry else error('Gave up Retry call_find.') nil end end end def rand_string (0...16).map { ('a'..'z').to_a[rand(26)] }.join end def start_server require 'win32/process' Process.create( app_name: Util.which('node'), creation_flags: Process::DETACHED_PROCESS ) end def stop_server(server_info) require 'win32/process' return unless server_info || server_info.respond_to?(:process_id) Process.kill('ExitProcess', [server_info.process_id]) end end end end Wait for call_back with Monitor cond_wait require 'pacproxy' require 'pacproxy/runtimes/base' require 'open-uri' require 'dnode' require 'thread' require 'monitor' require 'os' module Pacproxy module Runtimes # Pacproxy::Runtimes::Node represet node js runtime class Node < Base include Loggable TIMEOUT_JS_CALL = 0.5 TIMEOUT_JS_SERVER = 5 attr_reader :source def self.runtime if Util.which('node').nil? error('No PAC supported runtime') fail(RuntimeUnavailable, 'No PAC supported runtime') end new end def initialize js = File.join(File.dirname(__FILE__), 'find.js') retries = 3 begin Timeout.timeout(TIMEOUT_JS_SERVER) do server = TCPServer.new('127.0.0.1', 0) @port = server.addr[1] server.close if OS.windows? @server_pid = start_server else @server_pid = fork { exec('node', js, @port.to_s) } Process.detach(@server_pid) end sleep 0.01 until port_open? @queue = Queue.new @client_thread = Thread.new do DNode.new.connect('127.0.0.1', @port) do |remote| q = @queue.pop if q[:uri] && q[:uri].host && q[:call_back] remote.find(@source, q[:uri], q[:uri].host, q[:call_back]) end end end end rescue Timeout::Error if retries > 0 retries -= 1 lwarn('Timeout. Initialize Node.js server.') retry else error('Gave up to retry Initialize Node.js server.') raise 'Gave up to retry Initialize Node.js server.' end end end def shutdown if OS.windows? stop_server(@server_pid) else @client_thread.kill Process.kill(:INT, @server_pid) end end def update(file_location) @source = open(file_location, proxy: false).read rescue @source = nil end def find(url) return 'DIRECT' unless @source uri = URI.parse(url) call_find(uri) end private def port_open? Timeout.timeout(TIMEOUT_JS_CALL) do begin TCPSocket.new('127.0.0.1', @port).close return true rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH return false end end rescue Timeout::Error false end def call_find(uri, retries = 3) proxy = nil begin mon = Monitor.new cond = mon.new_cond thread = Thread.new do mon.synchronize do @queue.push(uri: uri, call_back: proc do |p| proxy = p cond.signal end) cond.wait end end thread.join(TIMEOUT_JS_CALL) proxy rescue Timeout::Error if retries > 0 retries -= 1 lwarn('Timeout. Retring call_find.') retry else error('Gave up Retry call_find.') nil end end end def rand_string (0...16).map { ('a'..'z').to_a[rand(26)] }.join end def start_server require 'win32/process' Process.create( app_name: Util.which('node'), creation_flags: Process::DETACHED_PROCESS ) end def stop_server(server_info) require 'win32/process' return unless server_info || server_info.respond_to?(:process_id) Process.kill('ExitProcess', [server_info.process_id]) end end end end
module PagesCore module ActsAsTextable class << self def textable_fields @@textable_fields ||= {} end def textable_options @@textable_options ||= {} end end # Model for <tt>acts_as_textable</tt> module Model # Class methods for <tt>acts_as_textable</tt> models module ClassMethods def languages(options={}) options = {:type => self.to_s}.merge(options) Textbit.languages(options) end def fields( options={} ) options = {:type => self.to_s}.merge(options) Textbit.fields( options ) end def textable_options PagesCore::ActsAsTextable.textable_options[self] || {} end end def root_class rc = self.class while rc.superclass != ActiveRecord::Base rc = rc.superclass end rc end # Set the working language def working_language=(language) @working_language = language.to_s end # Get the working language def working_language @working_language ||= Language.default end # Set the fallback language def fallback_language=(language) @fallback_language = language.to_s end # Get the fallback language def fallback_language @fallback_language || self.root_class.textable_options[:fallback_language] end # Does this model have a fallback language? def fallback_language? self.fallback_language ? true : false end def attributes=(new_attributes, guard_protected_attributes=true) attributes = new_attributes.dup attributes.stringify_keys! attributes = remove_attributes_protected_from_mass_assignment(attributes) if guard_protected_attributes attributes.each do |attribute, value| if self.has_field?(attribute) attributes.delete(attribute) set_textbit_body(attribute, value) end end super(attributes, guard_protected_attributes) end # Returns true if this page has the named textbit def has_field?(name, options={}) return true if (PagesCore::ActsAsTextable.textable_fields[self.root_class].include?(name)) (self.fields.include?(name.to_s)) ? true : false end # Get the textbit with specified name (and optional language), create and add it if necessary def get_textbit(name, options={}) name = name.to_s languages = options[:language] ? [options[:language]] : [self.working_language, self.fallback_language].compact named_textbits = self.textbits.select{|tb| tb.name == name} textbit = nil # Find the first applicable textbit languages.each do |lang| if !textbit && named_textbits.select{|tb| tb.language == lang.to_s}.length > 0 textbit = named_textbits.select{|tb| tb.language == lang.to_s}.first end end # Default to a blank one textbit ||= Textbit.new(:name => name, :textable => self, :language => languages.first) self.textbits.push(textbit) if textbit.new_record? textbit end # Set the body of a named textbit (usually, through method_missing) def set_textbit_body( name, value, options={} ) if value.kind_of? Hash value.each do |language,string| set_textbit_body( name, string, options.merge( { :language => language } ) ) end else options = {:language => self.working_language}.merge(options) textbit = get_textbit( name, options ) textbit.body = value end end # Save all related textbits def save_textbits self.textbits.each do |tb| tb.save end end # Returns an array of all language codes present on this page. def languages self.textbits.collect {|tb| tb.language }.uniq.compact end # Returns an array of language codes this field is translated into. def languages_for_field( name ) self.textbits.collect {|tb| tb.language if tb.name == name }.uniq.compact end def field_has_language?(name, language=nil) languages = (language ? language : [self.working_language, self.fallback_language].compact) languages = [languages] unless languages.kind_of?(Array) languages = languages.map{|l| l.to_s} available_languages = self.languages_for_field(name) languages.each{|l| return true if available_languages.include?(l)} return false end # Returns an array with the names of all text blocks excluding special fields. def fields self.textbits.collect{|tb| tb.name }.uniq.compact.reject{|name| PagesCore::ActsAsTextable.textable_fields[self.root_class].include?(name)} end # Returns an array with the names of all text blocks. def all_fields self.textbits.collect {|tb| tb.name }.uniq.compact end # Returns an array with the names of all text blocks with the given # language code. def fields_for_languague(language) self.textbits.collect {|tb| tb.name if tb.language == language.to_s }.uniq.compact.reject {|name| PagesCore::ActsAsTextable.textable_fields[ self.root_class ].include? name } end # Delete all text blocks with the given language code(s). # This operation is destructive, hence the name. def destroy_language( language ) language = language.to_s textbits = self.textbits.collect {|tb| tb if tb.language == language }.compact textbits.each {|tb| self.textbits.delete( tb ); tb.destroy } end # Delete all text blocks with the given name(s). # This operation is destructive, hence the name. def destroy_field( name ) if name.kind_of? String textbits = self.textbits.collect {|tb| tb if tb.name == name }.compact textbits.each {|tb| self.textbits.delete( tb ); tb.destroy } elsif name.kind_of? Enumerable name.each {|n| destroy_field( n ) } end end # Add a field def add_field( name ) languages = self.languages languages << Language.default if languages.empty? languages.each do |lang| tb = get_textbit( name, { :language => lang } ) end fields end # Add a language def add_language( language ) language = language.to_s fields = self.all_fields fields = fields.concat( PagesCore::ActsAsTextable.textable_fields[ self.root_class ] ) if fields.empty? fields.each do |name| tb = get_textbit( name, { :language => language } ) end languages end # Get a translated version of this page def translate(language, options={}) language = language.to_s #self.add_language( language ) dupe = self.dup dupe.working_language = language dupe.fallback_language = options[:fallback_language] if options[:fallback_language] (block_given?) ? (yield dupe) : dupe end # Enable virtual setters and getters for existing (and enforced) textbits def method_missing( method_name, *args ) name,type = method_name.to_s.match( /(.*?)([\?=]?)$/ )[1..2] if has_field? name case type when "?" field_has_language?(name) when "=" set_textbit_body(name, args.first) else get_textbit(name) end else super end end end end end # ActsAsTextable adds <tt>acts_as_textable</tt> to ActionController::Base module ActiveRecord class Base # Controller is textable. This adds the methods from <tt>ActsAsTextable::Model</tt>. def self.acts_as_textable(*args) options = args.last.kind_of?(Hash) ? args.pop : {} options.symbolize_keys! fields = args.flatten include PagesCore::ActsAsTextable::Model self.class.send(:include, PagesCore::ActsAsTextable::Model::ClassMethods) has_many :textbits, :as => :textable, :dependent => :destroy, :order => "name" after_save :save_textbits PagesCore::ActsAsTextable.textable_fields[self] = fields.map{|f| f.to_s} PagesCore::ActsAsTextable.textable_options[self] = options before_validation do |textable| invalid_textbits = textable.textbits.select{ |tb| !tb.valid? } unless invalid_textbits.empty? textable.textbits.delete( invalid_textbits ) end end end end end ActsAsTextable#translate! module PagesCore module ActsAsTextable class << self def textable_fields @@textable_fields ||= {} end def textable_options @@textable_options ||= {} end end # Model for <tt>acts_as_textable</tt> module Model # Class methods for <tt>acts_as_textable</tt> models module ClassMethods def languages(options={}) options = {:type => self.to_s}.merge(options) Textbit.languages(options) end def fields( options={} ) options = {:type => self.to_s}.merge(options) Textbit.fields( options ) end def textable_options PagesCore::ActsAsTextable.textable_options[self] || {} end end def root_class rc = self.class while rc.superclass != ActiveRecord::Base rc = rc.superclass end rc end # Set the working language def working_language=(language) @working_language = language.to_s end # Get the working language def working_language @working_language ||= Language.default end # Set the fallback language def fallback_language=(language) @fallback_language = language.to_s end # Get the fallback language def fallback_language @fallback_language || self.root_class.textable_options[:fallback_language] end # Does this model have a fallback language? def fallback_language? self.fallback_language ? true : false end def attributes=(new_attributes, guard_protected_attributes=true) attributes = new_attributes.dup attributes.stringify_keys! attributes = remove_attributes_protected_from_mass_assignment(attributes) if guard_protected_attributes attributes.each do |attribute, value| if self.has_field?(attribute) attributes.delete(attribute) set_textbit_body(attribute, value) end end super(attributes, guard_protected_attributes) end # Returns true if this page has the named textbit def has_field?(name, options={}) return true if (PagesCore::ActsAsTextable.textable_fields[self.root_class].include?(name)) (self.fields.include?(name.to_s)) ? true : false end # Get the textbit with specified name (and optional language), create and add it if necessary def get_textbit(name, options={}) name = name.to_s languages = options[:language] ? [options[:language]] : [self.working_language, self.fallback_language].compact named_textbits = self.textbits.select{|tb| tb.name == name} textbit = nil # Find the first applicable textbit languages.each do |lang| if !textbit && named_textbits.select{|tb| tb.language == lang.to_s}.length > 0 textbit = named_textbits.select{|tb| tb.language == lang.to_s}.first end end # Default to a blank one textbit ||= Textbit.new(:name => name, :textable => self, :language => languages.first) self.textbits.push(textbit) if textbit.new_record? textbit end # Set the body of a named textbit (usually, through method_missing) def set_textbit_body( name, value, options={} ) if value.kind_of? Hash value.each do |language,string| set_textbit_body( name, string, options.merge( { :language => language } ) ) end else options = {:language => self.working_language}.merge(options) textbit = get_textbit( name, options ) textbit.body = value end end # Save all related textbits def save_textbits self.textbits.each do |tb| tb.save end end # Returns an array of all language codes present on this page. def languages self.textbits.collect {|tb| tb.language }.uniq.compact end # Returns an array of language codes this field is translated into. def languages_for_field( name ) self.textbits.collect {|tb| tb.language if tb.name == name }.uniq.compact end def field_has_language?(name, language=nil) languages = (language ? language : [self.working_language, self.fallback_language].compact) languages = [languages] unless languages.kind_of?(Array) languages = languages.map{|l| l.to_s} available_languages = self.languages_for_field(name) languages.each{|l| return true if available_languages.include?(l)} return false end # Returns an array with the names of all text blocks excluding special fields. def fields self.textbits.collect{|tb| tb.name }.uniq.compact.reject{|name| PagesCore::ActsAsTextable.textable_fields[self.root_class].include?(name)} end # Returns an array with the names of all text blocks. def all_fields self.textbits.collect {|tb| tb.name }.uniq.compact end # Returns an array with the names of all text blocks with the given # language code. def fields_for_languague(language) self.textbits.collect {|tb| tb.name if tb.language == language.to_s }.uniq.compact.reject {|name| PagesCore::ActsAsTextable.textable_fields[ self.root_class ].include? name } end # Delete all text blocks with the given language code(s). # This operation is destructive, hence the name. def destroy_language( language ) language = language.to_s textbits = self.textbits.collect {|tb| tb if tb.language == language }.compact textbits.each {|tb| self.textbits.delete( tb ); tb.destroy } end # Delete all text blocks with the given name(s). # This operation is destructive, hence the name. def destroy_field( name ) if name.kind_of? String textbits = self.textbits.collect {|tb| tb if tb.name == name }.compact textbits.each {|tb| self.textbits.delete( tb ); tb.destroy } elsif name.kind_of? Enumerable name.each {|n| destroy_field( n ) } end end # Add a field def add_field( name ) languages = self.languages languages << Language.default if languages.empty? languages.each do |lang| tb = get_textbit( name, { :language => lang } ) end fields end # Add a language def add_language( language ) language = language.to_s fields = self.all_fields fields = fields.concat( PagesCore::ActsAsTextable.textable_fields[ self.root_class ] ) if fields.empty? fields.each do |name| tb = get_textbit( name, { :language => language } ) end languages end # Get a translated version of this record def translate(language, options={}) dupe = self.dup.translate!(language, options) (block_given?) ? (yield dupe) : dupe end # Translate this record def translate!(language, options={}) language = language.to_s self.working_language = language self.fallback_language = options[:fallback_language] if options[:fallback_language] self end # Enable virtual setters and getters for existing (and enforced) textbits def method_missing( method_name, *args ) name,type = method_name.to_s.match( /(.*?)([\?=]?)$/ )[1..2] if has_field? name case type when "?" field_has_language?(name) when "=" set_textbit_body(name, args.first) else get_textbit(name) end else super end end end end end # ActsAsTextable adds <tt>acts_as_textable</tt> to ActionController::Base module ActiveRecord class Base # Controller is textable. This adds the methods from <tt>ActsAsTextable::Model</tt>. def self.acts_as_textable(*args) options = args.last.kind_of?(Hash) ? args.pop : {} options.symbolize_keys! fields = args.flatten include PagesCore::ActsAsTextable::Model self.class.send(:include, PagesCore::ActsAsTextable::Model::ClassMethods) has_many :textbits, :as => :textable, :dependent => :destroy, :order => "name" after_save :save_textbits PagesCore::ActsAsTextable.textable_fields[self] = fields.map{|f| f.to_s} PagesCore::ActsAsTextable.textable_options[self] = options before_validation do |textable| invalid_textbits = textable.textbits.select{ |tb| !tb.valid? } unless invalid_textbits.empty? textable.textbits.delete( invalid_textbits ) end end end end end
require 'active_support/concern' module PaperTrail module VersionConcern extend ::ActiveSupport::Concern included do belongs_to :item, :polymorphic => true # Since the test suite has test coverage for this, we want to declare # the association when the test suite is running. This makes it pass when # DB is not initialized prior to test runs such as when we run on Travis # CI (there won't be a db in `test/dummy/db/`). if PaperTrail.config.track_associations? has_many :version_associations, :dependent => :destroy end validates_presence_of :event if PaperTrail.active_record_protected_attributes? attr_accessible( :item_type, :item_id, :event, :whodunnit, :object, :object_changes, :transaction_id, :created_at ) end after_create :enforce_version_limit! scope :within_transaction, lambda { |id| where :transaction_id => id } end module ClassMethods def with_item_keys(item_type, item_id) where :item_type => item_type, :item_id => item_id end def creates where :event => 'create' end def updates where :event => 'update' end def destroys where :event => 'destroy' end def not_creates where 'event <> ?', 'create' end # Expects `obj` to be an instance of `PaperTrail::Version` by default, # but can accept a timestamp if `timestamp_arg` receives `true` def subsequent(obj, timestamp_arg = false) if timestamp_arg != true && self.primary_key_is_int? return where(arel_table[primary_key].gt(obj.id)).order(arel_table[primary_key].asc) end obj = obj.send(PaperTrail.timestamp_field) if obj.is_a?(self) where(arel_table[PaperTrail.timestamp_field].gt(obj)).order(self.timestamp_sort_order) end def preceding(obj, timestamp_arg = false) if timestamp_arg != true && self.primary_key_is_int? return where(arel_table[primary_key].lt(obj.id)).order(arel_table[primary_key].desc) end obj = obj.send(PaperTrail.timestamp_field) if obj.is_a?(self) where(arel_table[PaperTrail.timestamp_field].lt(obj)).order(self.timestamp_sort_order('desc')) end def between(start_time, end_time) where( arel_table[PaperTrail.timestamp_field].gt(start_time). and(arel_table[PaperTrail.timestamp_field].lt(end_time)) ).order(self.timestamp_sort_order) end # Defaults to using the primary key as the secondary sort order if # possible. def timestamp_sort_order(direction = 'asc') [arel_table[PaperTrail.timestamp_field].send(direction.downcase)].tap do |array| array << arel_table[primary_key].send(direction.downcase) if self.primary_key_is_int? end end # Performs an attribute search on the serialized object by invoking the # identically-named method in the serializer being used. def where_object(args = {}) raise ArgumentError, 'expected to receive a Hash' unless args.is_a?(Hash) if columns_hash['object'].type == :jsonb where_conditions = "object @> '#{args.to_json}'::jsonb" elsif columns_hash['object'].type == :json where_conditions = args.map do |field, value| "object->>'#{field}' = '#{value}'" end where_conditions = where_conditions.join(" AND ") else arel_field = arel_table[:object] where_conditions = args.map do |field, value| PaperTrail.serializer.where_object_condition(arel_field, field, value) end.reduce do |condition1, condition2| condition1.and(condition2) end end where(where_conditions) end def where_object_changes(args = {}) raise ArgumentError, 'expected to receive a Hash' unless args.is_a?(Hash) if columns_hash['object_changes'].type == :jsonb args.each { |field, value| args[field] = [value] } where_conditions = "object_changes @> '#{args.to_json}'::jsonb" elsif columns_hash['object'].type == :json where_conditions = args.map do |field, value| "((object_changes->>'#{field}' ILIKE '[#{value.to_json},%') OR (object_changes->>'#{field}' ILIKE '[%,#{value.to_json}]%'))" end where_conditions = where_conditions.join(" AND ") else arel_field = arel_table[:object_changes] where_conditions = args.map do |field, value| PaperTrail.serializer.where_object_changes_condition(arel_field, field, value) end.reduce do |condition1, condition2| condition1.and(condition2) end end where(where_conditions) end def primary_key_is_int? @primary_key_is_int ||= columns_hash[primary_key].type == :integer rescue true end # Returns whether the `object` column is using the `json` type supported # by PostgreSQL. def object_col_is_json? [:json, :jsonb].include?(columns_hash['object'].type) end # Returns whether the `object_changes` column is using the `json` type # supported by PostgreSQL. def object_changes_col_is_json? [:json, :jsonb].include?(columns_hash['object_changes'].try(:type)) end end # Restore the item from this version. # # Optionally this can also restore all :has_one and :has_many (including # has_many :through) associations as they were "at the time", if they are # also being versioned by PaperTrail. # # Options: # # - :has_one # - `true` - Also reify has_one associations. # - `false - Default. # - :has_many # - `true` - Also reify has_many and has_many :through associations. # - `false` - Default. # - :mark_for_destruction # - `true` - Mark the has_one/has_many associations that did not exist in # the reified version for destruction, instead of removing them. # - `false` - Default. Useful for persisting the reified version. # - :dup # - `false` - Default. # - `true` - Always create a new object instance. Useful for # comparing two versions of the same object. # - :unversioned_attributes # - `:nil` - Default. Attributes undefined in version record are set to # nil in reified record. # - `:preserve` - Attributes undefined in version record are not modified. # def reify(options = {}) return nil if object.nil? without_identity_map do ::PaperTrail::Reifier.reify(self, options) end end # Returns what changed in this version of the item. # `ActiveModel::Dirty#changes`. returns `nil` if your `versions` table does # not have an `object_changes` text column. def changeset return nil unless self.class.column_names.include? 'object_changes' _changes = self.class.object_changes_col_is_json? ? object_changes : PaperTrail.serializer.load(object_changes) @changeset ||= HashWithIndifferentAccess.new(_changes).tap do |changes| if PaperTrail.serialized_attributes? item_type.constantize.unserialize_attribute_changes_for_paper_trail!(changes) end end rescue {} end # Returns who put the item into the state stored in this version. def paper_trail_originator @paper_trail_originator ||= previous.whodunnit rescue nil end def originator ::ActiveSupport::Deprecation.warn "Use paper_trail_originator instead of originator." self.paper_trail_originator end # Returns who changed the item from the state it had in this version. This # is an alias for `whodunnit`. def terminator @terminator ||= whodunnit end alias_method :version_author, :terminator def sibling_versions(reload = false) @sibling_versions = nil if reload == true @sibling_versions ||= self.class.with_item_keys(item_type, item_id) end def next @next ||= sibling_versions.subsequent(self).first end def previous @previous ||= sibling_versions.preceding(self).first end # Returns an integer representing the chronological position of the # version among its siblings (see `sibling_versions`). The "create" event, # for example, has an index of 0. # @api public def index @index ||= RecordHistory.new(sibling_versions, self.class).index(self) end # TODO: The `private` method has no effect here. Remove it? # AFAICT it is not possible to have private instance methods in a mixin, # though private *class* methods are possible. private # In Rails 3.1+, calling reify on a previous version confuses the # IdentityMap, if enabled. This prevents insertion into the map. # @api private def without_identity_map(&block) if defined?(::ActiveRecord::IdentityMap) && ::ActiveRecord::IdentityMap.respond_to?(:without) ::ActiveRecord::IdentityMap.without(&block) else block.call end end # Checks that a value has been set for the `version_limit` config # option, and if so enforces it. # @api private def enforce_version_limit! limit = PaperTrail.config.version_limit return unless limit.is_a? Numeric previous_versions = sibling_versions.not_creates return unless previous_versions.size > limit excess_versions = previous_versions - previous_versions.last(limit) excess_versions.map(&:destroy) end end end Docs: .subsequent and .preceding require 'active_support/concern' module PaperTrail module VersionConcern extend ::ActiveSupport::Concern included do belongs_to :item, :polymorphic => true # Since the test suite has test coverage for this, we want to declare # the association when the test suite is running. This makes it pass when # DB is not initialized prior to test runs such as when we run on Travis # CI (there won't be a db in `test/dummy/db/`). if PaperTrail.config.track_associations? has_many :version_associations, :dependent => :destroy end validates_presence_of :event if PaperTrail.active_record_protected_attributes? attr_accessible( :item_type, :item_id, :event, :whodunnit, :object, :object_changes, :transaction_id, :created_at ) end after_create :enforce_version_limit! scope :within_transaction, lambda { |id| where :transaction_id => id } end module ClassMethods def with_item_keys(item_type, item_id) where :item_type => item_type, :item_id => item_id end def creates where :event => 'create' end def updates where :event => 'update' end def destroys where :event => 'destroy' end def not_creates where 'event <> ?', 'create' end # Returns versions after `obj`. # # @param obj - a `Version` or a timestamp # @param timestamp_arg - boolean - When true, `obj` is a timestamp. # Default: false. # @return `ActiveRecord::Relation` # @api public def subsequent(obj, timestamp_arg = false) if timestamp_arg != true && self.primary_key_is_int? return where(arel_table[primary_key].gt(obj.id)).order(arel_table[primary_key].asc) end obj = obj.send(PaperTrail.timestamp_field) if obj.is_a?(self) where(arel_table[PaperTrail.timestamp_field].gt(obj)).order(self.timestamp_sort_order) end # Returns versions before `obj`. # # @param obj - a `Version` or a timestamp # @param timestamp_arg - boolean - When true, `obj` is a timestamp. # Default: false. # @return `ActiveRecord::Relation` # @api public def preceding(obj, timestamp_arg = false) if timestamp_arg != true && self.primary_key_is_int? return where(arel_table[primary_key].lt(obj.id)).order(arel_table[primary_key].desc) end obj = obj.send(PaperTrail.timestamp_field) if obj.is_a?(self) where(arel_table[PaperTrail.timestamp_field].lt(obj)).order(self.timestamp_sort_order('desc')) end def between(start_time, end_time) where( arel_table[PaperTrail.timestamp_field].gt(start_time). and(arel_table[PaperTrail.timestamp_field].lt(end_time)) ).order(self.timestamp_sort_order) end # Defaults to using the primary key as the secondary sort order if # possible. def timestamp_sort_order(direction = 'asc') [arel_table[PaperTrail.timestamp_field].send(direction.downcase)].tap do |array| array << arel_table[primary_key].send(direction.downcase) if self.primary_key_is_int? end end # Performs an attribute search on the serialized object by invoking the # identically-named method in the serializer being used. def where_object(args = {}) raise ArgumentError, 'expected to receive a Hash' unless args.is_a?(Hash) if columns_hash['object'].type == :jsonb where_conditions = "object @> '#{args.to_json}'::jsonb" elsif columns_hash['object'].type == :json where_conditions = args.map do |field, value| "object->>'#{field}' = '#{value}'" end where_conditions = where_conditions.join(" AND ") else arel_field = arel_table[:object] where_conditions = args.map do |field, value| PaperTrail.serializer.where_object_condition(arel_field, field, value) end.reduce do |condition1, condition2| condition1.and(condition2) end end where(where_conditions) end def where_object_changes(args = {}) raise ArgumentError, 'expected to receive a Hash' unless args.is_a?(Hash) if columns_hash['object_changes'].type == :jsonb args.each { |field, value| args[field] = [value] } where_conditions = "object_changes @> '#{args.to_json}'::jsonb" elsif columns_hash['object'].type == :json where_conditions = args.map do |field, value| "((object_changes->>'#{field}' ILIKE '[#{value.to_json},%') OR (object_changes->>'#{field}' ILIKE '[%,#{value.to_json}]%'))" end where_conditions = where_conditions.join(" AND ") else arel_field = arel_table[:object_changes] where_conditions = args.map do |field, value| PaperTrail.serializer.where_object_changes_condition(arel_field, field, value) end.reduce do |condition1, condition2| condition1.and(condition2) end end where(where_conditions) end def primary_key_is_int? @primary_key_is_int ||= columns_hash[primary_key].type == :integer rescue true end # Returns whether the `object` column is using the `json` type supported # by PostgreSQL. def object_col_is_json? [:json, :jsonb].include?(columns_hash['object'].type) end # Returns whether the `object_changes` column is using the `json` type # supported by PostgreSQL. def object_changes_col_is_json? [:json, :jsonb].include?(columns_hash['object_changes'].try(:type)) end end # Restore the item from this version. # # Optionally this can also restore all :has_one and :has_many (including # has_many :through) associations as they were "at the time", if they are # also being versioned by PaperTrail. # # Options: # # - :has_one # - `true` - Also reify has_one associations. # - `false - Default. # - :has_many # - `true` - Also reify has_many and has_many :through associations. # - `false` - Default. # - :mark_for_destruction # - `true` - Mark the has_one/has_many associations that did not exist in # the reified version for destruction, instead of removing them. # - `false` - Default. Useful for persisting the reified version. # - :dup # - `false` - Default. # - `true` - Always create a new object instance. Useful for # comparing two versions of the same object. # - :unversioned_attributes # - `:nil` - Default. Attributes undefined in version record are set to # nil in reified record. # - `:preserve` - Attributes undefined in version record are not modified. # def reify(options = {}) return nil if object.nil? without_identity_map do ::PaperTrail::Reifier.reify(self, options) end end # Returns what changed in this version of the item. # `ActiveModel::Dirty#changes`. returns `nil` if your `versions` table does # not have an `object_changes` text column. def changeset return nil unless self.class.column_names.include? 'object_changes' _changes = self.class.object_changes_col_is_json? ? object_changes : PaperTrail.serializer.load(object_changes) @changeset ||= HashWithIndifferentAccess.new(_changes).tap do |changes| if PaperTrail.serialized_attributes? item_type.constantize.unserialize_attribute_changes_for_paper_trail!(changes) end end rescue {} end # Returns who put the item into the state stored in this version. def paper_trail_originator @paper_trail_originator ||= previous.whodunnit rescue nil end def originator ::ActiveSupport::Deprecation.warn "Use paper_trail_originator instead of originator." self.paper_trail_originator end # Returns who changed the item from the state it had in this version. This # is an alias for `whodunnit`. def terminator @terminator ||= whodunnit end alias_method :version_author, :terminator def sibling_versions(reload = false) @sibling_versions = nil if reload == true @sibling_versions ||= self.class.with_item_keys(item_type, item_id) end def next @next ||= sibling_versions.subsequent(self).first end def previous @previous ||= sibling_versions.preceding(self).first end # Returns an integer representing the chronological position of the # version among its siblings (see `sibling_versions`). The "create" event, # for example, has an index of 0. # @api public def index @index ||= RecordHistory.new(sibling_versions, self.class).index(self) end # TODO: The `private` method has no effect here. Remove it? # AFAICT it is not possible to have private instance methods in a mixin, # though private *class* methods are possible. private # In Rails 3.1+, calling reify on a previous version confuses the # IdentityMap, if enabled. This prevents insertion into the map. # @api private def without_identity_map(&block) if defined?(::ActiveRecord::IdentityMap) && ::ActiveRecord::IdentityMap.respond_to?(:without) ::ActiveRecord::IdentityMap.without(&block) else block.call end end # Checks that a value has been set for the `version_limit` config # option, and if so enforces it. # @api private def enforce_version_limit! limit = PaperTrail.config.version_limit return unless limit.is_a? Numeric previous_versions = sibling_versions.not_creates return unless previous_versions.size > limit excess_versions = previous_versions - previous_versions.last(limit) excess_versions.map(&:destroy) end end end
module PhatPgsearch module ActiveRecord def self.included(base) base.extend ClassMethods end module ClassMethods #:nodoc: def pgsearch_index(*args, &block) unless @pgsearch_definitions.is_a? Hash include InstanceMethods extend SingletonMethods @pgsearch_definitions = {} before_save :build_pgsearch_index end @pgsearch_definitions[args.first.to_sym] = IndexDefinition.new(*args, &block) end end module SingletonMethods #:nodoc: def pgsearch_definitions @pgsearch_definitions end def pgsearch(*args) options = args.extract_options! normalization = options.delete(:normalization) || 32 rank = options.delete(:rank) scope = self search_query = pgsearch_query(args.first, args.second, options) if args.first.is_a? Symbol or args.first.to_s.split('.', 2) == 1 vector_column = "#{self.connection.quote_table_name(self.table_name)}.#{self.connection.quote_column_name(args.first.to_s)}" else vector_column = args.first.split('.', 2).collect{ |f| self.connection.quote_column_name(f) }.join('.') end if rank.nil? or rank == true scope = scope.select("#{self.connection.quote_table_name(self.table_name)}.*, ts_rank_cd(#{vector_column}, #{search_query}, #{normalization.to_i}) AS rank") end scope.where("#{vector_column} @@ #{search_query}") end def pgsearch_query(*args) options = args.extract_options! plain = options.delete(:plain) || true raise ArgumentError, "invalid field given" if args.first.nil? or not (args.first.is_a? String or args.first.is_a? Symbol) raise ArgumentError, "invalid query given" if args.second.nil? or not (args.second.is_a? String) field = args.first.to_s.split(".", 2) table_class = self if field.count == 2 begin table_class = field.first.classify.constantize rescue raise ArgumentError, "unknown table in field given" end end raise ArgumentError, "table has no index defined" unless table_class.respond_to? :pgsearch_definitions raise ArgumentError, "table has no index defined for '#{field.last.to_sym}'" if table_class.pgsearch_definitions[field.last.to_sym].nil? definition = table_class.pgsearch_definitions[field.last.to_sym] if definition catalog = options[:catalog] || definition.catalog else catalog = options[:catalog] || definition.catalog end "#{plain ? 'plain' : ''}to_tsquery(#{self.sanitize(catalog)}, #{self.sanitize(args.second)})" end # rebuild complete index for model def rebuild_pgindex! self.all.each { |model| model.rebuild_pgindex! } end end module InstanceMethods #:nodoc: # rebuild pgindex für object without update timestamps def rebuild_pgindex! last_state = self.class.record_timestamps self.class.record_timestamps = false self.build_pgsearch_index self.save! self.class.record_timestamps = last_state end protected def build_pgsearch_index self.class.pgsearch_definitions.each_pair do |index_field, index_definition| IndexBuilder.new(self, index_definition) end end end end end remove tab module PhatPgsearch module ActiveRecord def self.included(base) base.extend ClassMethods end module ClassMethods #:nodoc: def pgsearch_index(*args, &block) unless @pgsearch_definitions.is_a? Hash include InstanceMethods extend SingletonMethods @pgsearch_definitions = {} before_save :build_pgsearch_index end @pgsearch_definitions[args.first.to_sym] = IndexDefinition.new(*args, &block) end end module SingletonMethods #:nodoc: def pgsearch_definitions @pgsearch_definitions end def pgsearch(*args) options = args.extract_options! normalization = options.delete(:normalization) || 32 rank = options.delete(:rank) scope = self search_query = pgsearch_query(args.first, args.second, options) if args.first.is_a? Symbol or args.first.to_s.split('.', 2) == 1 vector_column = "#{self.connection.quote_table_name(self.table_name)}.#{self.connection.quote_column_name(args.first.to_s)}" else vector_column = args.first.split('.', 2).collect{ |f| self.connection.quote_column_name(f) }.join('.') end if rank.nil? or rank == true scope = scope.select("#{self.connection.quote_table_name(self.table_name)}.*, ts_rank_cd(#{vector_column}, #{search_query}, #{normalization.to_i}) AS rank") end scope.where("#{vector_column} @@ #{search_query}") end def pgsearch_query(*args) options = args.extract_options! plain = options.delete(:plain) || true raise ArgumentError, "invalid field given" if args.first.nil? or not (args.first.is_a? String or args.first.is_a? Symbol) raise ArgumentError, "invalid query given" if args.second.nil? or not (args.second.is_a? String) field = args.first.to_s.split(".", 2) table_class = self if field.count == 2 begin table_class = field.first.classify.constantize rescue raise ArgumentError, "unknown table in field given" end end raise ArgumentError, "table has no index defined" unless table_class.respond_to? :pgsearch_definitions raise ArgumentError, "table has no index defined for '#{field.last.to_sym}'" if table_class.pgsearch_definitions[field.last.to_sym].nil? definition = table_class.pgsearch_definitions[field.last.to_sym] if definition catalog = options[:catalog] || definition.catalog else catalog = options[:catalog] || definition.catalog end "#{plain ? 'plain' : ''}to_tsquery(#{self.sanitize(catalog)}, #{self.sanitize(args.second)})" end # rebuild complete index for model def rebuild_pgindex! self.all.each { |model| model.rebuild_pgindex! } end end module InstanceMethods #:nodoc: # rebuild pgindex für object without update timestamps def rebuild_pgindex! last_state = self.class.record_timestamps self.class.record_timestamps = false self.build_pgsearch_index self.save! self.class.record_timestamps = last_state end protected def build_pgsearch_index self.class.pgsearch_definitions.each_pair do |index_field, index_definition| IndexBuilder.new(self, index_definition) end end end end end
require 'rack' Rack::Handler::WEBrick.run Proc.new {|env| ['200', {'Content-Type' => 'text/html'}, ["Hello Rack!"]]}, :Port => 9898 rack call require 'rack' class HelloRack def call(env) ['200', {'Content-Type' => 'text/html'}, ["Hello Rack!"]] end end Rack::Handler::WEBrick.run HelloRack.new, :Port => 9898
# # Copyright 2015, Noah Kantrowitz # # Licensed 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 'chef/mash' require 'poise/provider' require 'poise/resource' require 'poise/utils' module PoiseApplication module AppMixin include Poise::Utils::ResourceProviderMixin module Resource include Poise::Resource def app_state parent.app_state end def app_state_environment app_state[:environment] ||= Mash.new end module ClassMethods # @api private def included(klass) super klass.extend(ClassMethods) klass.poise_subresource(:application, true) end end extend ClassMethods end module Provider include Poise::Provider end end end Make #path part of the app mixin. # # Copyright 2015, Noah Kantrowitz # # Licensed 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 'chef/mash' require 'poise/provider' require 'poise/resource' require 'poise/utils' module PoiseApplication module AppMixin include Poise::Utils::ResourceProviderMixin module Resource include Poise::Resource def app_state parent.app_state end def app_state_environment app_state[:environment] ||= Mash.new end module ClassMethods # @api private def included(klass) super klass.extend(ClassMethods) klass.poise_subresource(:application, true) klass.attribute(:path, kind_of: String, name_attribute: true) end end extend ClassMethods end module Provider include Poise::Provider end end end
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "game-queue" s.version = "0.2.3" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["V_M"] s.date = "2012-06-29" s.description = "Simple game queue for redis" s.email = "nobody@nowhere.com" s.extra_rdoc_files = [ "LICENSE.txt", "README.rdoc" ] s.files = [ ".document", ".rspec", "Gemfile", "Gemfile.lock", "LICENSE.txt", "README.rdoc", "Rakefile", "VERSION", "game-queue.gemspec", "lib/game-queue.rb", "spec/game-queue_spec.rb", "spec/spec_helper.rb" ] s.homepage = "http://github.com/NONE/game-queue" s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = "1.8.16" s.summary = "Game queue" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<redis>, [">= 3.0.1"]) s.add_development_dependency(%q<rspec>, ["~> 2.10.0"]) s.add_development_dependency(%q<rdoc>, ["~> 3.12"]) s.add_development_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.8.4"]) s.add_development_dependency(%q<simplecov>, [">= 0"]) else s.add_dependency(%q<redis>, [">= 3.0.1"]) s.add_dependency(%q<rspec>, ["~> 2.10.0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.8.4"]) s.add_dependency(%q<simplecov>, [">= 0"]) end else s.add_dependency(%q<redis>, [">= 3.0.1"]) s.add_dependency(%q<rspec>, ["~> 2.10.0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.8.4"]) s.add_dependency(%q<simplecov>, [">= 0"]) end end Regenerate gemspec for version 0.2.4 # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "game-queue" s.version = "0.2.4" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["V_M"] s.date = "2012-11-14" s.description = "Simple game queue for redis" s.email = "nobody@nowhere.com" s.extra_rdoc_files = [ "LICENSE.txt", "README.rdoc" ] s.files = [ ".document", ".rspec", "Gemfile", "Gemfile.lock", "LICENSE.txt", "README.rdoc", "Rakefile", "VERSION", "game-queue.gemspec", "lib/game-queue.rb", "spec/game-queue_spec.rb", "spec/spec_helper.rb" ] s.homepage = "http://github.com/NONE/game-queue" s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = "1.8.24" s.summary = "Game queue" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<redis>, [">= 3.0.1"]) s.add_development_dependency(%q<rspec>, ["~> 2.12.0"]) s.add_development_dependency(%q<rdoc>, ["~> 3.12"]) s.add_development_dependency(%q<bundler>, ["~> 1.2.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.8.4"]) s.add_development_dependency(%q<simplecov>, [">= 0"]) else s.add_dependency(%q<redis>, [">= 3.0.1"]) s.add_dependency(%q<rspec>, ["~> 2.12.0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, ["~> 1.2.0"]) s.add_dependency(%q<jeweler>, ["~> 1.8.4"]) s.add_dependency(%q<simplecov>, [">= 0"]) end else s.add_dependency(%q<redis>, [">= 3.0.1"]) s.add_dependency(%q<rspec>, ["~> 2.12.0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, ["~> 1.2.0"]) s.add_dependency(%q<jeweler>, ["~> 1.8.4"]) s.add_dependency(%q<simplecov>, [">= 0"]) end end
require 'java' require 'builder' require 'pathname' require 'fileutils' require 'time' require 'mime/types' # Grab the good builds and the changelogs from the bad builds (so the good # build that follows a bad build gets the bad build's changelog appended to # its own). def get_builds(latest_build) b=latest_build builds=[] c=[] begin c += b.getChangeSet.getItems.map { |c| c.getMsg } if b.getResult.to_s == 'SUCCESS' builds.push({ :build => b, :changes => c}) c=[] end end while (b=b.getPreviousBuild) #getPreviousSuccessfulBuild builds end # One line per change entry right now. Consider moving to markdown. def format_changelog(changes) changes.map {|c| c+"\n" }.join('') end # The mime-types gem doesn't have x-apple-diskimage by default. Consider giving them a pull request. MIME::Types.add(MIME::Type.from_hash('Content-Type' => 'application/x-apple-diskimage', 'Content-Transfer-Encoding' => '8bit', 'Extensions' => ['dmg'])) class Sparkle_appcastPublisher < Jenkins::Tasks::Publisher display_name "Publish Sparkle Appcast (RSS)" attr_reader :url_base, :output_directory, :author, :title, :description, :rss_filename # Invoked with the form parameters when this extension point # is created from a configuration screen. def initialize(attrs = {}) attrs.each { |k, v| v = nil if v == ""; instance_variable_set "@#{k}", v } @output_directory = Pathname.new(attrs["output_directory"]) if attrs["output_directory"] end ## # Runs before the build begins # # @param [Jenkins::Model::Build] build the build which will begin # @param [Jenkins::Model::Listener] listener the listener for this build. def prebuild(build, listener) # do any setup that needs to be done before this build runs. end ## # Runs the step over the given build and reports the progress to the listener. # # @param [Jenkins::Model::Build] build on which to run this step # @param [Jenkins::Launcher] launcher the launcher that can run code on the node running this build # @param [Jenkins::Model::Listener] listener the listener for this build. def perform(build_ruby, launcher, listener) build = build_ruby.native unless build.getResult.to_s == 'SUCCESS' listener.info "Not writing Appcast file for failed build." return end project_name = build.project.getDisplayName builds = get_builds(build) @rss_filename ||= project_name + ".rss" # Build symlink tree and keep track of URLs and filenames builds.each do |b| build = b[:build] version_dir = project_name + "-" + build.number.to_s raise "Can't build appcast #{@rss_filename}: Too many artifacts" if build.getArtifacts.size > 1 first_artifact = build.getArtifacts.first.getFile b[:file] = @output_directory + version_dir + first_artifact.getName FileUtils.mkdir_p @output_directory + version_dir FileUtils.ln_sf first_artifact.getAbsolutePath, b[:file] b[:url] = "#{@url_base}/#{version_dir}/#{first_artifact.getName}" end rss = Builder::XmlMarkup.new(:indent => 2) rss.instruct! rss_s = rss.rss("version" => "2.0", "xmlns:content" => "http://purl.org/rss/1.0/modules/content/", "xmlns:dc" => "http://purl.org/dc/elements/1.1/", "xmlns:sparkle" => "http://www.andymatuschak.org/xml-namespaces/sparkle", ) { rss.channel { rss.author @author || "Jenkins" rss.updated Time.now.to_s rss.link "#{@url_base}/#{@rss_filename}" rss.title @title || "#{project_name} Versions" rss.description @description || "#{project_name} Versions" builds.each do |b| rss.item { rss.link b[:url] rss.title "#{project_name} #{b[:build].number} Released" rss.updated File.mtime(b[:file]) rss.enclosure("url" => b[:url], "type" => MIME::Types.type_for(b[:file].to_s).last || "application/octet-stream", "length" => File.size(b[:file]), "sparkle:version" => b[:build].number) rss.pubDate File.ctime(b[:file]) rss.dc(:date, File.ctime(b[:file]).iso8601) rss.description { rss.cdata! format_changelog(b[:changes]) } } end } } listener.info "Writing Appcast file \"#{@output_directory + @rss_filename}\"..." File.open(@output_directory + @rss_filename, "w") { |f| f.write(rss_s) } end end [sparkle_appcast_publisher.rb] Fix changeset coalescing so it coalesces in the right direction. require 'java' require 'builder' require 'pathname' require 'fileutils' require 'time' require 'mime/types' # Grab the good builds and the changelogs from the bad builds (so the good # build that follows a bad build gets the bad build's changelog appended to # its own). def get_builds(latest_build) b=latest_build builds=[] begin builds.push({ :build => b, :changes => []}) if b.getResult.to_s == 'SUCCESS' builds.last[:changes] += b.getChangeSet.getItems.map { |c| c.getMsg } if builds.last end while (b=b.getPreviousBuild) #getPreviousSuccessfulBuild builds end # One line per change entry right now. Consider moving to markdown. def format_changelog(changes) changes.map {|c| c+"\n" }.join('') end # The mime-types gem doesn't have x-apple-diskimage by default. Consider giving them a pull request. MIME::Types.add(MIME::Type.from_hash('Content-Type' => 'application/x-apple-diskimage', 'Content-Transfer-Encoding' => '8bit', 'Extensions' => ['dmg'])) class Sparkle_appcastPublisher < Jenkins::Tasks::Publisher display_name "Publish Sparkle Appcast (RSS)" attr_reader :url_base, :output_directory, :author, :title, :description, :rss_filename # Invoked with the form parameters when this extension point # is created from a configuration screen. def initialize(attrs = {}) attrs.each { |k, v| v = nil if v == ""; instance_variable_set "@#{k}", v } @output_directory = Pathname.new(attrs["output_directory"]) if attrs["output_directory"] end ## # Runs before the build begins # # @param [Jenkins::Model::Build] build the build which will begin # @param [Jenkins::Model::Listener] listener the listener for this build. def prebuild(build, listener) # do any setup that needs to be done before this build runs. end ## # Runs the step over the given build and reports the progress to the listener. # # @param [Jenkins::Model::Build] build on which to run this step # @param [Jenkins::Launcher] launcher the launcher that can run code on the node running this build # @param [Jenkins::Model::Listener] listener the listener for this build. def perform(build_ruby, launcher, listener) build = build_ruby.native unless build.getResult.to_s == 'SUCCESS' listener.info "Not writing Appcast file for failed build." return end project_name = build.project.getDisplayName builds = get_builds(build) @rss_filename ||= project_name + ".rss" # Build symlink tree and keep track of URLs and filenames builds.each do |b| build = b[:build] version_dir = project_name + "-" + build.number.to_s raise "Can't build appcast #{@rss_filename}: Too many artifacts" if build.getArtifacts.size > 1 first_artifact = build.getArtifacts.first.getFile b[:file] = @output_directory + version_dir + first_artifact.getName FileUtils.mkdir_p @output_directory + version_dir FileUtils.ln_sf first_artifact.getAbsolutePath, b[:file] b[:url] = "#{@url_base}/#{version_dir}/#{first_artifact.getName}" end rss = Builder::XmlMarkup.new(:indent => 2) rss.instruct! rss_s = rss.rss("version" => "2.0", "xmlns:content" => "http://purl.org/rss/1.0/modules/content/", "xmlns:dc" => "http://purl.org/dc/elements/1.1/", "xmlns:sparkle" => "http://www.andymatuschak.org/xml-namespaces/sparkle", ) { rss.channel { rss.author @author || "Jenkins" rss.updated Time.now.to_s rss.link "#{@url_base}/#{@rss_filename}" rss.title @title || "#{project_name} Versions" rss.description @description || "#{project_name} Versions" builds.each do |b| rss.item { rss.link b[:url] rss.title "#{project_name} #{b[:build].number} Released" rss.updated File.mtime(b[:file]) rss.enclosure("url" => b[:url], "type" => MIME::Types.type_for(b[:file].to_s).last || "application/octet-stream", "length" => File.size(b[:file]), "sparkle:version" => b[:build].number) rss.pubDate File.ctime(b[:file]) rss.dc(:date, File.ctime(b[:file]).iso8601) rss.description { rss.cdata! format_changelog(b[:changes]) } } end } } listener.info "Writing Appcast file \"#{@output_directory + @rss_filename}\"..." File.open(@output_directory + @rss_filename, "w") { |f| f.write(rss_s) } end end
require File.dirname(__FILE__) + '/rule' class Condition attr_reader :node_type, :child_rule, :value, :variable def initialize options = {} @node_type = options[:node_type] @child_rule = options[:child_rule] @creates_node = options[:creates_node] @removes_node = options[:removes_node] @prevents_match = options[:prevents_match] @matches_multiple_nodes = options[:matches_multiple_nodes] @value = options[:value] @variable = options[:variable] end def creates_node? @creates_node end def removes_node? @removes_node end def prevents_match? @prevents_match end def must_match_a_node? can_match_a_node? && !prevents_match? && !matches_multiple_nodes? end def can_match_a_node? !creates_node? end def node_must_match_variable_value? variable && can_match_a_node? end def node_sets_variable_value? variable && must_match_a_node? end def has_value_set_by_variable? variable && creates_node? end def matches_multiple_nodes? @matches_multiple_nodes end def value_type if value.is_a? Fixnum: :integer elsif value.is_a? Float: :decimal elsif value.is_a? String: :string elsif value.nil?: :none end end end ruby 1.9 compatable if statement require File.dirname(__FILE__) + '/rule' class Condition attr_reader :node_type, :child_rule, :value, :variable def initialize options = {} @node_type = options[:node_type] @child_rule = options[:child_rule] @creates_node = options[:creates_node] @removes_node = options[:removes_node] @prevents_match = options[:prevents_match] @matches_multiple_nodes = options[:matches_multiple_nodes] @value = options[:value] @variable = options[:variable] end def creates_node? @creates_node end def removes_node? @removes_node end def prevents_match? @prevents_match end def must_match_a_node? can_match_a_node? && !prevents_match? && !matches_multiple_nodes? end def can_match_a_node? !creates_node? end def node_must_match_variable_value? variable && can_match_a_node? end def node_sets_variable_value? variable && must_match_a_node? end def has_value_set_by_variable? variable && creates_node? end def matches_multiple_nodes? @matches_multiple_nodes end def value_type if value.is_a? Fixnum then :integer elsif value.is_a? Float then :decimal elsif value.is_a? String then :string elsif value.nil? then :none end end end
require 'singleton' require 'logging' require 'ruby-prof' module Profiler # # TODO KI make gem out of this... # # @see https://github.com/ruby-prof/ruby-prof # class RubyProfProfiler DEFAULT_CONFIG = { root_dir: '.', profile_dir: 'log/profile', enabled: true, cpu: false, memory: false, min_percent: 10.0, min_profile_time: 10, output: :graph }.freeze ROOT_DIR = '/tmp' include Singleton def initialize @file_index = 0 @output_dir = nil config = @@config @enabled = config[:enabled] @root_dir = config[:root_dir] @profile_dir = config[:profile_dir] @cpu = config[:cpu] @memory = config[:memory] @min_percent = config[:min_percent] @min_profile_time = config[:min_profile_time] @output = config[:output] @output = @output.to_s.to_sym if @enabled @output_dir = "#{@root_dir}/#{@profile_dir}" unless Dir.exist? @output_dir Dir.mkdir @output_dir end if @memory RubyProf.measure_mode = RubyProf::MEMORY end if @cpu RubyProf.measure_mode = RubyProf::WALL_TIME end end end def logger @logger ||= Logging.logger['Profile'] end def enabled? @enabled end def self.set_config(config = {}) @@config = DEFAULT_CONFIG.merge(config) end # # @return profile file residing in profiling dir # def full_file(file_name) @file_index += 1 File.join @output_dir, "#{DateTime.now.strftime '%Y%m%d_%H%M'}_#{'%04d' % @file_index}_#{file_name}" end def start RubyProf.start @profile_start_time = Time.now end def end(file_name) results = RubyProf.stop profile_start_time = @profile_start_time @profile_start_time = nil profile_end_time = Time.now diff = profile_end_time - profile_start_time if diff < @min_profile_time logger.info "skipping: too_short_time, file=#{file_name}, time=#{diff}s, min=#{@min_profile_time}s" return end # ensure name is safe file_name = file_name .gsub(/^.*(\\|\/)/, '') .gsub!(/[^0-9A-Za-z.\-]/, '_') base_name = full_file(file_name) # results.eliminate_methods!([/ProfileHelper/]) if @output == :graph File.open "#{base_name}-graph.html", 'w' do |file| logger.info "Saving: #{file.path}" RubyProf::GraphHtmlPrinter.new(results).print file, min_percent: @min_percent end elsif @output == :call_stack File.open "#{base_name}-stack.html", 'w' do |file| logger.info "Saving: #{file}" RubyProf::CallStackPrinter.new(results).print file, min_percent: @min_percent end elsif @profile == :flat File.open "#{base_name}-flat.txt", 'w' do |file| logger.info "Saving: #{file}" RubyProf::FlatPrinter.new(results).print file, min_percent: @min_percent end elsif @profile == :call_tree File.open "#{base_name}-tree.prof", 'w' do |file| logger.info "Saving: #{file}" RubyProf::CallTreePrinter.new(results).print file, min_percent: @min_percent end end end end RubyProfProfiler.set_config end PROF: no profiling if not enabled require 'singleton' require 'logging' require 'ruby-prof' module Profiler # # TODO KI make gem out of this... # # @see https://github.com/ruby-prof/ruby-prof # class RubyProfProfiler DEFAULT_CONFIG = { root_dir: '.', profile_dir: 'log/profile', enabled: true, cpu: false, memory: false, min_percent: 10.0, min_profile_time: 10, output: :graph }.freeze ROOT_DIR = '/tmp' include Singleton def initialize @file_index = 0 @output_dir = nil config = @@config @enabled = config[:enabled] @root_dir = config[:root_dir] @profile_dir = config[:profile_dir] @cpu = config[:cpu] @memory = config[:memory] @min_percent = config[:min_percent] @min_profile_time = config[:min_profile_time] @output = config[:output] @output = @output.to_s.to_sym if @enabled @output_dir = "#{@root_dir}/#{@profile_dir}" unless Dir.exist? @output_dir Dir.mkdir @output_dir end if @memory RubyProf.measure_mode = RubyProf::MEMORY end if @cpu RubyProf.measure_mode = RubyProf::WALL_TIME end end end def logger @logger ||= Logging.logger['Profile'] end def enabled? @enabled end def self.set_config(config = {}) @@config = DEFAULT_CONFIG.merge(config) end # # @return profile file residing in profiling dir # def full_file(file_name) @file_index += 1 File.join @output_dir, "#{DateTime.now.strftime '%Y%m%d_%H%M'}_#{'%04d' % @file_index}_#{file_name}" end def start return unless @enabled RubyProf.start @profile_start_time = Time.now end def end(file_name) return unless @enabled results = RubyProf.stop profile_start_time = @profile_start_time @profile_start_time = nil profile_end_time = Time.now diff = profile_end_time - profile_start_time if diff < @min_profile_time logger.info "skipping: too_short_time, file=#{file_name}, time=#{diff}s, min=#{@min_profile_time}s" return end # ensure name is safe file_name = file_name .gsub(/^.*(\\|\/)/, '') .gsub!(/[^0-9A-Za-z.\-]/, '_') base_name = full_file(file_name) # results.eliminate_methods!([/ProfileHelper/]) if @output == :graph File.open "#{base_name}-graph.html", 'w' do |file| logger.info "Saving: #{file.path}" RubyProf::GraphHtmlPrinter.new(results).print file, min_percent: @min_percent end elsif @output == :call_stack File.open "#{base_name}-stack.html", 'w' do |file| logger.info "Saving: #{file}" RubyProf::CallStackPrinter.new(results).print file, min_percent: @min_percent end elsif @profile == :flat File.open "#{base_name}-flat.txt", 'w' do |file| logger.info "Saving: #{file}" RubyProf::FlatPrinter.new(results).print file, min_percent: @min_percent end elsif @profile == :call_tree File.open "#{base_name}-tree.prof", 'w' do |file| logger.info "Saving: #{file}" RubyProf::CallTreePrinter.new(results).print file, min_percent: @min_percent end end end end RubyProfProfiler.set_config end
require 'protobuf/rpc/connectors/base' require 'protobuf/rpc/service_directory' module Protobuf module Rpc module Connectors class Zmq < Base RequestTimeout = Class.new(RuntimeError) ZmqRecoverableError = Class.new(RuntimeError) ## # Included Modules # include Protobuf::Rpc::Connectors::Common include Protobuf::Logger::LogMethods ## # Class Constants # CLIENT_RETRIES = (ENV['PB_CLIENT_RETRIES'] || 3) ## # Class Methods # def self.zmq_context @zmq_contexts ||= Hash.new { |hash, key| hash[key] = ZMQ::Context.new } @zmq_contexts[Process.pid] end ## # Instance methods # # Start the request/response cycle. We implement the Lazy Pirate # req/reply reliability pattern as laid out in the ZMQ Guide, Chapter 4. # # @see http://zguide.zeromq.org/php:chapter4#Client-side-Reliability-Lazy-Pirate-Pattern # def send_request setup_connection send_request_with_lazy_pirate unless error? end def log_signature @_log_signature ||= "[client-#{self.class}]" end private ## # Private Instance methods # def close_connection # The socket is automatically closed after every request. end # Create a socket connected to a server that can handle the current # service. The LINGER is set to 0 so we can close immediately in # the event of a timeout def create_socket socket = nil begin server_uri = lookup_server_uri socket = zmq_context.socket(::ZMQ::REQ) if socket # Make sure the context builds the socket socket.setsockopt(::ZMQ::LINGER, 0) log_debug { sign_message("Establishing connection: #{server_uri}") } zmq_error_check(socket.connect(server_uri), :socket_connect) log_debug { sign_message("Connection established to #{server_uri}") } if first_alive_load_balance? begin check_available_response = "" socket.setsockopt(::ZMQ::RCVTIMEO, 50) socket.setsockopt(::ZMQ::SNDTIMEO, 50) zmq_recoverable_error_check(socket.send_string(::Protobuf::Rpc::Zmq::CHECK_AVAILABLE_MESSAGE), :socket_send_string) zmq_recoverable_error_check(socket.recv_string(check_available_response), :socket_recv_string) if check_available_response == ::Protobuf::Rpc::Zmq::NO_WORKERS_AVAILABLE zmq_recoverable_error_check(socket.close, :socket_close) end rescue ZmqRecoverableError socket = nil # couldn't make a connection and need to try again end end end end while socket.try(:socket).nil? socket end # Method to determine error state, must be used with Connector API. # def error? !! @error end # Lookup a server uri for the requested service in the service # directory. If the service directory is not running, default # to the host and port in the options # def lookup_server_uri 5.times do service_directory.all_listings_for(service).each do |listing| host = listing.try(:address) port = listing.try(:port) return "tcp://#{host}:#{port}" if host_alive?(host) end host = options[:host] port = options[:port] return "tcp://#{host}:#{port}" if host_alive?(host) end raise "Host not found for service #{service}" end def host_alive?(host) return true unless ping_port_enabled? socket = TCPSocket.new(host, ping_port.to_i) true rescue false ensure socket.close rescue nil end # Trying a number of times, attempt to get a response from the server. # If we haven't received a legitimate response in the CLIENT_RETRIES number # of retries, fail the request. # def send_request_with_lazy_pirate attempt = 0 timeout = options[:timeout].to_f begin attempt += 1 send_request_with_timeout(timeout, attempt) parse_response rescue RequestTimeout retry if attempt < CLIENT_RETRIES fail(:RPC_FAILED, "The server repeatedly failed to respond within #{timeout} seconds") end end def send_request_with_timeout(timeout, attempt = 0) socket = create_socket poller = ::ZMQ::Poller.new poller.register_readable(socket) log_debug { sign_message("Sending Request (attempt #{attempt}, #{socket})") } zmq_error_check(socket.send_string(@request_data), :socket_send_string) log_debug { sign_message("Waiting #{timeout} seconds for response (attempt #{attempt}, #{socket})") } if poller.poll(timeout * 1000) == 1 zmq_error_check(socket.recv_string(@response_data = ""), :socket_recv_string) log_debug { sign_message("Response received (attempt #{attempt}, #{socket})") } else log_debug { sign_message("Timed out waiting for response (attempt #{attempt}, #{socket})") } raise RequestTimeout end ensure log_debug { sign_message("Closing Socket") } zmq_error_check(socket.close, :socket_close) if socket log_debug { sign_message("Socket closed") } end # The service we're attempting to connect to # def service options[:service] end # Alias for ::Protobuf::Rpc::ServiceDirectory.instance def service_directory ::Protobuf::Rpc::ServiceDirectory.instance end # Return the ZMQ Context to use for this process. # If the context does not exist, create it, then register # an exit block to ensure the context is terminated correctly. # def zmq_context self.class.zmq_context end def zmq_error_check(return_code, source) unless ::ZMQ::Util.resultcode_ok?(return_code || -1) raise <<-ERROR Last ZMQ API call to #{source} failed with "#{::ZMQ::Util.error_string}". #{caller(1).join($/)} ERROR end end def zmq_recoverable_error_check(return_code, source) unless ::ZMQ::Util.resultcode_ok?(return_code || -1) raise ZmqRecoverableError, <<-ERROR Last ZMQ API call to #{source} failed with "#{::ZMQ::Util.error_string}". #{caller(1).join($/)} ERROR end end end end end end add back a sleep and no linger on host_live require 'protobuf/rpc/connectors/base' require 'protobuf/rpc/service_directory' module Protobuf module Rpc module Connectors class Zmq < Base RequestTimeout = Class.new(RuntimeError) ZmqRecoverableError = Class.new(RuntimeError) ## # Included Modules # include Protobuf::Rpc::Connectors::Common include Protobuf::Logger::LogMethods ## # Class Constants # CLIENT_RETRIES = (ENV['PB_CLIENT_RETRIES'] || 3) ## # Class Methods # def self.zmq_context @zmq_contexts ||= Hash.new { |hash, key| hash[key] = ZMQ::Context.new } @zmq_contexts[Process.pid] end ## # Instance methods # # Start the request/response cycle. We implement the Lazy Pirate # req/reply reliability pattern as laid out in the ZMQ Guide, Chapter 4. # # @see http://zguide.zeromq.org/php:chapter4#Client-side-Reliability-Lazy-Pirate-Pattern # def send_request setup_connection send_request_with_lazy_pirate unless error? end def log_signature @_log_signature ||= "[client-#{self.class}]" end private ## # Private Instance methods # def close_connection # The socket is automatically closed after every request. end # Create a socket connected to a server that can handle the current # service. The LINGER is set to 0 so we can close immediately in # the event of a timeout def create_socket socket = nil begin server_uri = lookup_server_uri socket = zmq_context.socket(::ZMQ::REQ) if socket # Make sure the context builds the socket socket.setsockopt(::ZMQ::LINGER, 0) log_debug { sign_message("Establishing connection: #{server_uri}") } zmq_error_check(socket.connect(server_uri), :socket_connect) log_debug { sign_message("Connection established to #{server_uri}") } if first_alive_load_balance? begin check_available_response = "" socket.setsockopt(::ZMQ::RCVTIMEO, 50) socket.setsockopt(::ZMQ::SNDTIMEO, 50) zmq_recoverable_error_check(socket.send_string(::Protobuf::Rpc::Zmq::CHECK_AVAILABLE_MESSAGE), :socket_send_string) zmq_recoverable_error_check(socket.recv_string(check_available_response), :socket_recv_string) if check_available_response == ::Protobuf::Rpc::Zmq::NO_WORKERS_AVAILABLE zmq_recoverable_error_check(socket.close, :socket_close) end rescue ZmqRecoverableError socket = nil # couldn't make a connection and need to try again end end end end while socket.try(:socket).nil? socket end # Method to determine error state, must be used with Connector API. # def error? !! @error end # Lookup a server uri for the requested service in the service # directory. If the service directory is not running, default # to the host and port in the options # def lookup_server_uri 10.times do service_directory.all_listings_for(service).each do |listing| host = listing.try(:address) port = listing.try(:port) return "tcp://#{host}:#{port}" if host_alive?(host) end host = options[:host] port = options[:port] return "tcp://#{host}:#{port}" if host_alive?(host) sleep(1.0/60.0) end raise "Host not found for service #{service}" end def host_alive?(host) return true unless ping_port_enabled? socket = TCPSocket.new(host, ping_port.to_i) linger = [1,0].pack('ii') socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_LINGER, linger) true rescue false ensure socket.close rescue nil end # Trying a number of times, attempt to get a response from the server. # If we haven't received a legitimate response in the CLIENT_RETRIES number # of retries, fail the request. # def send_request_with_lazy_pirate attempt = 0 timeout = options[:timeout].to_f begin attempt += 1 send_request_with_timeout(timeout, attempt) parse_response rescue RequestTimeout retry if attempt < CLIENT_RETRIES fail(:RPC_FAILED, "The server repeatedly failed to respond within #{timeout} seconds") end end def send_request_with_timeout(timeout, attempt = 0) socket = create_socket poller = ::ZMQ::Poller.new poller.register_readable(socket) log_debug { sign_message("Sending Request (attempt #{attempt}, #{socket})") } zmq_error_check(socket.send_string(@request_data), :socket_send_string) log_debug { sign_message("Waiting #{timeout} seconds for response (attempt #{attempt}, #{socket})") } if poller.poll(timeout * 1000) == 1 zmq_error_check(socket.recv_string(@response_data = ""), :socket_recv_string) log_debug { sign_message("Response received (attempt #{attempt}, #{socket})") } else log_debug { sign_message("Timed out waiting for response (attempt #{attempt}, #{socket})") } raise RequestTimeout end ensure log_debug { sign_message("Closing Socket") } zmq_error_check(socket.close, :socket_close) if socket log_debug { sign_message("Socket closed") } end # The service we're attempting to connect to # def service options[:service] end # Alias for ::Protobuf::Rpc::ServiceDirectory.instance def service_directory ::Protobuf::Rpc::ServiceDirectory.instance end # Return the ZMQ Context to use for this process. # If the context does not exist, create it, then register # an exit block to ensure the context is terminated correctly. # def zmq_context self.class.zmq_context end def zmq_error_check(return_code, source) unless ::ZMQ::Util.resultcode_ok?(return_code || -1) raise <<-ERROR Last ZMQ API call to #{source} failed with "#{::ZMQ::Util.error_string}". #{caller(1).join($/)} ERROR end end def zmq_recoverable_error_check(return_code, source) unless ::ZMQ::Util.resultcode_ok?(return_code || -1) raise ZmqRecoverableError, <<-ERROR Last ZMQ API call to #{source} failed with "#{::ZMQ::Util.error_string}". #{caller(1).join($/)} ERROR end end end end end end
module PunchblockConsole class Commands def initialize(client, call_id, queue) # :nodoc: @client, @call_id, @queue = client, call_id, queue end def accept # :nodoc: write Command::Accept.new end def answer # :nodoc: write Command::Answer.new end def hangup # :nodoc: write Command::Hangup.new end def reject(reason = nil) # :nodoc: write Command::Reject.new(:reason => reason) end def redirect(dest) # :nodoc: write Command::Redirect.new(:to => dest) end def record(options = {}) write Component::Record.new(options) end def say(string) output string, :text end def output(string, type = :text) # :nodoc: component = Component::Output.new(type => string) write component component.complete_event.resource end def agi(command, params = {}) component = Component::Asterisk::AGI::Command.new :name => command, :params => params write component puts component.complete_event.resource end def write(command) # :nodoc: @client.execute_command command, :call_id => @call_id, :async => false end end end Fix commands to use new punchblock complete event API module PunchblockConsole class Commands def initialize(client, call_id, queue) # :nodoc: @client, @call_id, @queue = client, call_id, queue end def accept # :nodoc: write Command::Accept.new end def answer # :nodoc: write Command::Answer.new end def hangup # :nodoc: write Command::Hangup.new end def reject(reason = nil) # :nodoc: write Command::Reject.new(:reason => reason) end def redirect(dest) # :nodoc: write Command::Redirect.new(:to => dest) end def record(options = {}) write Component::Record.new(options) end def say(string) output string, :text end def output(string, type = :text) # :nodoc: component = Component::Output.new(type => string) write component component.complete_event end def agi(command, params = {}) component = Component::Asterisk::AGI::Command.new :name => command, :params => params write component component.complete_event end def write(command) # :nodoc: @client.execute_command command, :call_id => @call_id, :async => false end end end
# # Copyright (c) 2014, Arista Networks, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # Neither the name of Arista Networks nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARISTA NETWORKS # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR # BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN # IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # encoding: utf-8 require 'puppet_x/eos/utils/helpers' Puppet::Type.newtype(:eos_staticroute) do @doc = <<-EOS Configure static routes in EOS. Example: eos_static_route { '192.168.99.0/24/10.0.0.1': } eos_static_route { '192.168.99.0/24/10.0.0.1': ensure => absent, } eos_static_route { '192.168.10.0/24/Ethernet1': route_name => 'Edge10', distance => 3, } EOS ensurable # Parameters newparam(:name, namevar: true) do @doc = <<-EOS A composite string consisting of <prefix>/<masklen>/<next_hop>. (namevar) prefix - IP destination subnet prefix masklen - Number of mask bits to apply to the destination next_hop - Next_hop IP address or interface name EOS validate do |value| if value.is_a? String then super(value) else fail "value #{value.inspect} is invalid, must be a String." end end end # Properties (state management) newproperty(:route_name) do @doc = <<-EOS The name assigned to the static route EOS validate do |value| unless value.is_a? String fail "value #{value.inspect} is invalid, must be a String." end end end newproperty(:distance) do @doc = <<-EOS Administrative distance of the route. Valid values are 1-255. EOS munge { |value| Integer(value) } validate do |value| unless value.to_i.between?(1, 255) fail "value #{value.inspect} is invalid, must be an integer from 1-255." end end end newproperty(:tag) do @doc = <<-EOS Route tag (0-255) EOS munge { |value| Integer(value) } validate do |value| unless value.to_i.between?(0, 255) fail "value #{value.inspect} is invalid, must be an integer from 0-255." end end end end Fix type name in documentation example. # # Copyright (c) 2014, Arista Networks, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # Neither the name of Arista Networks nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARISTA NETWORKS # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR # BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN # IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # encoding: utf-8 require 'puppet_x/eos/utils/helpers' Puppet::Type.newtype(:eos_staticroute) do @doc = <<-EOS Configure static routes in EOS. Example: eos_staticroute { '192.168.99.0/24/10.0.0.1': } eos_staticroute { '192.168.99.0/24/10.0.0.1': ensure => absent, } eos_staticroute { '192.168.10.0/24/Ethernet1': route_name => 'Edge10', distance => 3, } EOS ensurable # Parameters newparam(:name, namevar: true) do @doc = <<-EOS A composite string consisting of <prefix>/<masklen>/<next_hop>. (namevar) prefix - IP destination subnet prefix masklen - Number of mask bits to apply to the destination next_hop - Next_hop IP address or interface name EOS validate do |value| if value.is_a? String then super(value) else fail "value #{value.inspect} is invalid, must be a String." end end end # Properties (state management) newproperty(:route_name) do @doc = <<-EOS The name assigned to the static route EOS validate do |value| unless value.is_a? String fail "value #{value.inspect} is invalid, must be a String." end end end newproperty(:distance) do @doc = <<-EOS Administrative distance of the route. Valid values are 1-255. EOS munge { |value| Integer(value) } validate do |value| unless value.to_i.between?(1, 255) fail "value #{value.inspect} is invalid, must be an integer from 1-255." end end end newproperty(:tag) do @doc = <<-EOS Route tag (0-255) EOS munge { |value| Integer(value) } validate do |value| unless value.to_i.between?(0, 255) fail "value #{value.inspect} is invalid, must be an integer from 0-255." end end end end
class Page attr_accessor :filename, :permalink, :title, :topic, :body, :target end class IndexPage < Page def initialize(filename) @filename = filename if @filename == "index" @permalink = @filename else @permalink = filename.split(".index")[0] end @topic = @permalink @target = "#{@permalink}.html" end def template IO.read("design/template.index.html") end end class ContentPage < Page attr_accessor :pub_date def initialize(filename) @filename = filename @topic, @permalink = @filename.split(":", 2) @target = "#{@permalink}.html" end def template IO.read("design/template.html") end end def escape_htmlspecialchars(content) # see: http://php.net/htmlspecialchars replaces = { "&" => "&amp;", "\"" => "&quot;", "'" => "&apos;", "<" => "&lt;", ">" => "&gt;" } replaces.each { |key, value| content.gsub!(key, value) } content end def anchor_footerlinks(footer) footer.gsub!(/^(\[\d+\]:) (.*)/, '\1 <a href="\2">\2</a>') end def main # First, make sure that the required files are present all_files = (Dir.entries(".") - [".", "..", "design", ".git"]).reject { |file| /\.html$/ =~ file } if not all_files.include? "index" puts "error: index file not found; aborting" exit 1 end ["template.index.html", "template.html"].each { |file| if not Dir.entries("design").include? file puts "error: design/#{file} file not found; aborting" exit 1 end } index_files = ["index"] + all_files.select { |file| /\.index$/ =~ file } content_files = all_files - index_files index_pages = index_files.map { |file| IndexPage.new(file) } content_pages = content_files.map { |file| ContentPage.new(file) } topics = index_files.map { |file| file.split(".index")[0] } # Next, look for stray files (content_files.reject { |file| topics.include? (file.split(":", 2)[0]) }) .each { |stray_file| puts "warning: #{stray_file} is a stray file; ignored" } # First, fill in all the page attributes (index_pages + content_pages).each { |page| page.content = escape_htmlspecialchars(IO.read file) page.title, rest = content.split("\n\n", 2) begin # Optional footer page.body, partial_footer = rest.split("\n\n[1]: ", 2) page.footer = "\n\n[1]: #{partial_footer}" if partial_footer rescue end anchor_footerlinks page.footer if page.footer sidebar = topics.map { |topic| "<li><a href=\"#{topic}\">#{topic}/</a></li>" }.join("\n") } # Compute the indexfill for indexes flist = content_files.select { |file| file.start_with? "#{permalink}:" } indexfill = flist.map { |file| file.split("#{permalink}:")[1] }.map { |link| "<li><a href=\"#{link}\">#{link}</a></li>" }.join("\n") if flist (index_pages + content_pages.each { |page| template_vars = ["permalink", "title", "body", "sidebar"] ["footer", "indexfill"].each { |optional_field| if eval(page.optional_field) template_vars = template_vars + [optional_field] else template.gsub!("\{% #{optional_field} %\}", "") end } template_vars.each { |template_var| template.gsub!("\{% #{template_var} %\}", eval(template_var)) } File.open(target, mode="w") { |targetio| nbytes = targetio.write(template) puts "[GEN] #{target} (#{nbytes} bytes out)" } } end main add :index_fill to IndexPage and compute it class Page attr_accessor :filename, :permalink, :title, :topic, :body, :target end class IndexPage < Page attr_accessor :index_fill def initialize(filename) @filename = filename if @filename == "index" @permalink = @filename else @permalink = filename.split(".index")[0] end @topic = @permalink @target = "#{@permalink}.html" end def template IO.read("design/template.index.html") end end class ContentPage < Page attr_accessor :pub_date def initialize(filename) @filename = filename @topic, @permalink = @filename.split(":", 2) @target = "#{@permalink}.html" end def template IO.read("design/template.html") end end def escape_htmlspecialchars(content) # see: http://php.net/htmlspecialchars replaces = { "&" => "&amp;", "\"" => "&quot;", "'" => "&apos;", "<" => "&lt;", ">" => "&gt;" } replaces.each { |key, value| content.gsub!(key, value) } content end def anchor_footerlinks(footer) footer.gsub!(/^(\[\d+\]:) (.*)/, '\1 <a href="\2">\2</a>') end def main # First, make sure that the required files are present all_files = (Dir.entries(".") - [".", "..", "design", ".git"]).reject { |file| /\.html$/ =~ file } if not all_files.include? "index" puts "error: index file not found; aborting" exit 1 end ["template.index.html", "template.html"].each { |file| if not Dir.entries("design").include? file puts "error: design/#{file} file not found; aborting" exit 1 end } index_files = ["index"] + all_files.select { |file| /\.index$/ =~ file } content_files = all_files - index_files index_pages = index_files.map { |file| IndexPage.new(file) } content_pages = content_files.map { |file| ContentPage.new(file) } topics = index_files.map { |file| file.split(".index")[0] } # Next, look for stray files (content_files.reject { |file| topics.include? (file.split(":", 2)[0]) }) .each { |stray_file| puts "warning: #{stray_file} is a stray file; ignored" } # First, fill in all the page attributes (index_pages + content_pages).each { |page| page.content = escape_htmlspecialchars(IO.read file) page.title, rest = content.split("\n\n", 2) begin # Optional footer page.body, partial_footer = rest.split("\n\n[1]: ", 2) page.footer = "\n\n[1]: #{partial_footer}" if partial_footer rescue end anchor_footerlinks page.footer if page.footer sidebar = topics.map { |topic| "<li><a href=\"#{topic}\">#{topic}/</a></li>" }.join("\n") } # Compute the indexfill for indexes flist = content_files.select { |file| file.start_with? "#{permalink}:" } topics.each { |topic| topic_index = index_pages.select { |page| page.topic == topic }[0] # there is only one topic_index.indexfill = content_pages.select { |page| page.topic == topic } indexfill = flist.map { |file| file.split("#{permalink}:")[1] }.map { |link| "<li><a href=\"#{link}\">#{link}</a></li>" }.join("\n") if flist (index_pages + content_pages.each { |page| template_vars = ["permalink", "title", "body", "sidebar"] ["footer", "indexfill"].each { |optional_field| if eval(page.optional_field) template_vars = template_vars + [optional_field] else template.gsub!("\{% #{optional_field} %\}", "") end } template_vars.each { |template_var| template.gsub!("\{% #{template_var} %\}", eval(template_var)) } File.open(target, mode="w") { |targetio| nbytes = targetio.write(template) puts "[GEN] #{target} (#{nbytes} bytes out)" } } end main
[Add] FirebaseAppCheck (8.1.0-beta) Pod::Spec.new do |s| s.name = 'FirebaseAppCheck' s.version = '8.1.0-beta' s.summary = 'Firebase App Check SDK.' s.description = <<-DESC Firebase SDK for anti-abuse compatibility. DESC s.homepage = 'https://firebase.google.com' s.license = { :type => 'Apache', :file => 'LICENSE' } s.authors = 'Google, Inc.' s.source = { :git => 'https://github.com/firebase/firebase-ios-sdk.git', :tag => 'CocoaPods-8.1.0.nightly' } s.social_media_url = 'https://twitter.com/Firebase' ios_deployment_target = '11.0' osx_deployment_target = '10.15' tvos_deployment_target = '11.0' s.ios.deployment_target = ios_deployment_target s.osx.deployment_target = osx_deployment_target s.tvos.deployment_target = tvos_deployment_target s.cocoapods_version = '>= 1.4.0' s.prefix_header_file = false base_dir = "FirebaseAppCheck/" s.source_files = [ base_dir + 'Sources/**/*.[mh]', 'FirebaseCore/Sources/Private/*.h', ] s.public_header_files = base_dir + 'Sources/Public/FirebaseAppCheck/*.h' s.framework = 'DeviceCheck' s.dependency 'FirebaseCore', '~> 8.0' s.dependency 'PromisesObjC', '~> 1.2' s.dependency 'GoogleUtilities/Environment', '~> 7.4' s.pod_target_xcconfig = { 'GCC_C_LANGUAGE_STANDARD' => 'c99', 'HEADER_SEARCH_PATHS' => '"${PODS_TARGET_SRCROOT}"' } s.test_spec 'unit' do |unit_tests| unit_tests.platforms = { :ios => ios_deployment_target, :osx => osx_deployment_target, :tvos => tvos_deployment_target } unit_tests.source_files = [ base_dir + 'Tests/Unit/**/*.[mh]', base_dir + 'Tests/Utils/**/*.[mh]', 'SharedTestUtilities/AppCheckFake/*', 'SharedTestUtilities/Date/*', 'SharedTestUtilities/URLSession/*', ] unit_tests.resources = base_dir + 'Tests/Fixture/**/*' unit_tests.dependency 'OCMock' unit_tests.requires_app_host = true end s.test_spec 'integration' do |integration_tests| integration_tests.platforms = { :ios => ios_deployment_target, :osx => osx_deployment_target, :tvos => tvos_deployment_target } integration_tests.source_files = [ base_dir + 'Tests/Integration/**/*.[mh]', base_dir + 'Tests/Integration/**/*.[mh]', ] integration_tests.resources = base_dir + 'Tests/Fixture/**/*' integration_tests.requires_app_host = true end s.test_spec 'swift-unit' do |swift_unit_tests| swift_unit_tests.platforms = { :ios => ios_deployment_target, :osx => osx_deployment_target, :tvos => tvos_deployment_target } swift_unit_tests.source_files = [ base_dir + 'Tests/Unit/Swift/**/*.swift', base_dir + 'Tests/Unit/Swift/**/*.h', ] end end
[Add] FirebaseAppCheck (8.2.0-beta) Pod::Spec.new do |s| s.name = 'FirebaseAppCheck' s.version = '8.2.0-beta' s.summary = 'Firebase App Check SDK.' s.description = <<-DESC Firebase SDK for anti-abuse compatibility. DESC s.homepage = 'https://firebase.google.com' s.license = { :type => 'Apache', :file => 'LICENSE' } s.authors = 'Google, Inc.' s.source = { :git => 'https://github.com/firebase/firebase-ios-sdk.git', :tag => 'CocoaPods-8.3.0.nightly' } s.social_media_url = 'https://twitter.com/Firebase' ios_deployment_target = '11.0' osx_deployment_target = '10.15' tvos_deployment_target = '11.0' s.ios.deployment_target = ios_deployment_target s.osx.deployment_target = osx_deployment_target s.tvos.deployment_target = tvos_deployment_target s.cocoapods_version = '>= 1.4.0' s.prefix_header_file = false base_dir = "FirebaseAppCheck/" s.source_files = [ base_dir + 'Sources/**/*.[mh]', 'FirebaseCore/Sources/Private/*.h', ] s.public_header_files = base_dir + 'Sources/Public/FirebaseAppCheck/*.h' s.framework = 'DeviceCheck' s.dependency 'FirebaseCore', '~> 8.0' s.dependency 'PromisesObjC', '~> 1.2' s.dependency 'GoogleUtilities/Environment', '~> 7.4' s.pod_target_xcconfig = { 'GCC_C_LANGUAGE_STANDARD' => 'c99', 'HEADER_SEARCH_PATHS' => '"${PODS_TARGET_SRCROOT}"' } s.test_spec 'unit' do |unit_tests| unit_tests.platforms = { :ios => ios_deployment_target, :osx => osx_deployment_target, :tvos => tvos_deployment_target } unit_tests.source_files = [ base_dir + 'Tests/Unit/**/*.[mh]', base_dir + 'Tests/Utils/**/*.[mh]', 'SharedTestUtilities/AppCheckFake/*', 'SharedTestUtilities/Date/*', 'SharedTestUtilities/URLSession/*', ] unit_tests.resources = base_dir + 'Tests/Fixture/**/*' unit_tests.dependency 'OCMock' unit_tests.requires_app_host = true end s.test_spec 'integration' do |integration_tests| integration_tests.platforms = { :ios => ios_deployment_target, :osx => osx_deployment_target, :tvos => tvos_deployment_target } integration_tests.source_files = [ base_dir + 'Tests/Integration/**/*.[mh]', base_dir + 'Tests/Integration/**/*.[mh]', ] integration_tests.resources = base_dir + 'Tests/Fixture/**/*' integration_tests.requires_app_host = true end s.test_spec 'swift-unit' do |swift_unit_tests| swift_unit_tests.platforms = { :ios => ios_deployment_target, :osx => osx_deployment_target, :tvos => tvos_deployment_target } swift_unit_tests.source_files = [ base_dir + 'Tests/Unit/Swift/**/*.swift', base_dir + 'Tests/Unit/Swift/**/*.h', ] end end
[Add] FirebaseAppCheck (8.2.0-beta) Pod::Spec.new do |s| s.name = 'FirebaseAppCheck' s.version = '8.2.0-beta' s.summary = 'Firebase App Check SDK.' s.description = <<-DESC Firebase SDK for anti-abuse compatibility. DESC s.homepage = 'https://firebase.google.com' s.license = { :type => 'Apache', :file => 'LICENSE' } s.authors = 'Google, Inc.' s.source = { :git => 'https://github.com/firebase/firebase-ios-sdk.git', :tag => 'CocoaPods-8.3.0.nightly' } s.social_media_url = 'https://twitter.com/Firebase' ios_deployment_target = '11.0' osx_deployment_target = '10.15' tvos_deployment_target = '11.0' s.ios.deployment_target = ios_deployment_target s.osx.deployment_target = osx_deployment_target s.tvos.deployment_target = tvos_deployment_target s.cocoapods_version = '>= 1.4.0' s.prefix_header_file = false base_dir = "FirebaseAppCheck/" s.source_files = [ base_dir + 'Sources/**/*.[mh]', 'FirebaseCore/Sources/Private/*.h', ] s.public_header_files = base_dir + 'Sources/Public/FirebaseAppCheck/*.h' s.framework = 'DeviceCheck' s.dependency 'FirebaseCore', '~> 8.0' s.dependency 'PromisesObjC', '~> 1.2' s.dependency 'GoogleUtilities/Environment', '~> 7.4' s.pod_target_xcconfig = { 'GCC_C_LANGUAGE_STANDARD' => 'c99', 'HEADER_SEARCH_PATHS' => '"${PODS_TARGET_SRCROOT}"' } s.test_spec 'unit' do |unit_tests| unit_tests.platforms = { :ios => ios_deployment_target, :osx => osx_deployment_target, :tvos => tvos_deployment_target } unit_tests.source_files = [ base_dir + 'Tests/Unit/**/*.[mh]', base_dir + 'Tests/Utils/**/*.[mh]', 'SharedTestUtilities/AppCheckFake/*', 'SharedTestUtilities/Date/*', 'SharedTestUtilities/URLSession/*', ] unit_tests.resources = base_dir + 'Tests/Fixture/**/*' unit_tests.dependency 'OCMock' unit_tests.requires_app_host = true end s.test_spec 'integration' do |integration_tests| integration_tests.platforms = { :ios => ios_deployment_target, :osx => osx_deployment_target, :tvos => tvos_deployment_target } integration_tests.source_files = [ base_dir + 'Tests/Integration/**/*.[mh]', base_dir + 'Tests/Integration/**/*.[mh]', ] integration_tests.resources = base_dir + 'Tests/Fixture/**/*' integration_tests.requires_app_host = true end s.test_spec 'swift-unit' do |swift_unit_tests| swift_unit_tests.platforms = { :ios => ios_deployment_target, :osx => osx_deployment_target, :tvos => tvos_deployment_target } swift_unit_tests.source_files = [ base_dir + 'Tests/Unit/Swift/**/*.swift', base_dir + 'Tests/Unit/Swift/**/*.h', ] end end
# Apache 2.0 License # # Copyright (c) 2018 Sebastian Katzer, appPlant GmbH # # 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. module SKI # Execute SQL command on the remote database. class DatabaseTask < BaseTask # The shell command to invoke pqdb_sql.out PQDB = '. profiles/%s.prof && exe/pqdb_sql.out -s -x %s'.freeze # Execute the SQL command on the remote database. # # @param [ SKI::Planet ] planet The planet where to execute the task. # # @return [ Void ] def exec(planet) connect(planet) do |ssh| log "Executing SQL command on #{ssh.host}" do cmd = format(PQDB, planet.user, planet.db) pqdb(ssh, cmd) { |out, ok| result(planet, out, ok) } end end end protected # Well formatted SQL command to execute on the remote server. # # @return [ String ] def command (cmd = super)[-1] == ';' ? cmd : "#{cmd};" end private # Execute the SQL command on the remote database and yields the code # block with the captured result. # # @param [ SSH::Session ] ssh The SSH session that is connected to # the remote host. # @param [ String ] pqdb_cmd The shell command to invoke pqdb_sql. # # @return [ SKI::Result ] def pqdb(ssh, pqdb_cmd, &block) io, ok = ssh.open_channel.popen2e(pqdb_cmd) io.puts(command) io.puts('exit') block&.call(io.gets(nil), ok) ensure io&.close(false) end end end Ignore stdout from user profile # Apache 2.0 License # # Copyright (c) 2018 Sebastian Katzer, appPlant GmbH # # 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. module SKI # Execute SQL command on the remote database. class DatabaseTask < BaseTask # The shell command to invoke pqdb_sql.out PQDB = '. profiles/%s.prof > /dev/null && exe/pqdb_sql.out -s -x %s'.freeze # Execute the SQL command on the remote database. # # @param [ SKI::Planet ] planet The planet where to execute the task. # # @return [ Void ] def exec(planet) connect(planet) do |ssh| log "Executing SQL command on #{ssh.host}" do cmd = format(PQDB, planet.user, planet.db) pqdb(ssh, cmd) { |out, ok| result(planet, out, ok) } end end end protected # Well formatted SQL command to execute on the remote server. # # @return [ String ] def command (cmd = super)[-1] == ';' ? cmd : "#{cmd};" end private # Execute the SQL command on the remote database and yields the code # block with the captured result. # # @param [ SSH::Session ] ssh The SSH session that is connected to # the remote host. # @param [ String ] pqdb_cmd The shell command to invoke pqdb_sql. # # @return [ SKI::Result ] def pqdb(ssh, pqdb_cmd, &block) io, ok = ssh.open_channel.popen2e(pqdb_cmd) io.puts(command) io.puts('exit') block&.call(io.gets(nil), ok) ensure io&.close(false) end end end
require 'amqp' module QueueingRabbit module Client class AMQP include QueueingRabbit::Serializer include QueueingRabbit::Logging extend QueueingRabbit::Logging extend QueueingRabbit::Client::Callbacks attr_reader :connection, :exchange_name, :exchange_options define_callback :on_tcp_failure do |_| fatal "unable to establish TCP connection to broker" EM.stop end define_callback :on_tcp_loss do |c, _| info "re-establishing TCP connection to broker" c.reconnect(false, 1) end define_callback :on_tcp_recovery do info "TCP connection to broker is back and running" end define_callback :on_channel_error do |ch, channel_close| EM.stop fatal "channel error occured: #{channel_close.reply_text}" end def self.connection_options {:timeout => QueueingRabbit.tcp_timeout, :heartbeat => QueueingRabbit.heartbeat, :on_tcp_connection_failure => self.callback(:on_tcp_failure)} end def self.connect self.run_event_machine self.new(::AMQP.connect(QueueingRabbit.amqp_uri), QueueingRabbit.amqp_exchange_name, QueueingRabbit.amqp_exchange_options) end def self.run_event_machine return if EM.reactor_running? @event_machine_thread = Thread.new do EM.run do QueueingRabbit.trigger_event(:event_machine_started) end end end def self.join_event_machine_thread @event_machine_thread.join if @event_machine_thread end def disconnect info "closing AMQP broker connection..." connection.close do yield if block_given? EM.stop if EM.reactor_running? end end def define_queue(channel, queue_name, options={}) routing_keys = [*options.delete(:routing_keys)] + [queue_name] channel.queue(queue_name.to_s, options) do |queue| routing_keys.each do |key| queue.bind(exchange(channel), :routing_key => key.to_s) end end end def listen_queue(channel, queue_name, options={}, &block) define_queue(channel, queue_name, options). subscribe(:ack => true) do |metadata, payload| begin process_message(deserialize(payload), &block) metadata.ack rescue JSON::JSONError => e error "JSON parser error occured: #{e.message}" debug e end end end def process_message(arguments) begin yield arguments rescue => e error "unexpected error #{e.class} occured: #{e.message}" debug e end end def open_channel(options={}) ::AMQP::Channel.new(connection, ::AMQP::Channel.next_channel_id, options) do |c, open_ok| c.on_error(&self.class.callback(:on_channel_error)) yield c, open_ok end end def define_exchange(channel, options={}) channel.direct(exchange_name, exchange_options.merge(options)) end alias_method :exchange, :define_exchange def enqueue(channel, routing_key, payload) exchange(channel).publish(serialize(payload), :key => routing_key.to_s, :persistent => true) end alias_method :publish, :enqueue def queue_size(queue) raise NotImplementedError end private def setup_callbacks connection.on_tcp_connection_loss(&self.class.callback(:on_tcp_loss)) connection.on_recovery(&self.class.callback(:on_tcp_recovery)) end def initialize(connection, exchange_name, exchange_options = {}) @connection = connection @exchange_name = exchange_name @exchange_options = exchange_options setup_callbacks end end end end Block control thread for 0.5 sec while starting EM in a separate thread. require 'amqp' module QueueingRabbit module Client class AMQP include QueueingRabbit::Serializer include QueueingRabbit::Logging extend QueueingRabbit::Logging extend QueueingRabbit::Client::Callbacks attr_reader :connection, :exchange_name, :exchange_options define_callback :on_tcp_failure do |_| fatal "unable to establish TCP connection to broker" EM.stop end define_callback :on_tcp_loss do |c, _| info "re-establishing TCP connection to broker" c.reconnect(false, 1) end define_callback :on_tcp_recovery do info "TCP connection to broker is back and running" end define_callback :on_channel_error do |ch, channel_close| EM.stop fatal "channel error occured: #{channel_close.reply_text}" end def self.connection_options {:timeout => QueueingRabbit.tcp_timeout, :heartbeat => QueueingRabbit.heartbeat, :on_tcp_connection_failure => self.callback(:on_tcp_failure)} end def self.connect self.run_event_machine self.new(::AMQP.connect(QueueingRabbit.amqp_uri), QueueingRabbit.amqp_exchange_name, QueueingRabbit.amqp_exchange_options) end def self.run_event_machine return if EM.reactor_running? @event_machine_thread = Thread.new do EM.run do QueueingRabbit.trigger_event(:event_machine_started) end end # Block the control process while EM is starting up sleep 0.5 end def self.join_event_machine_thread @event_machine_thread.join if @event_machine_thread end def disconnect info "closing AMQP broker connection..." connection.close do yield if block_given? EM.stop if EM.reactor_running? end end def define_queue(channel, queue_name, options={}) routing_keys = [*options.delete(:routing_keys)] + [queue_name] channel.queue(queue_name.to_s, options) do |queue| routing_keys.each do |key| queue.bind(exchange(channel), :routing_key => key.to_s) end end end def listen_queue(channel, queue_name, options={}, &block) define_queue(channel, queue_name, options). subscribe(:ack => true) do |metadata, payload| begin process_message(deserialize(payload), &block) metadata.ack rescue JSON::JSONError => e error "JSON parser error occured: #{e.message}" debug e end end end def process_message(arguments) begin yield arguments rescue => e error "unexpected error #{e.class} occured: #{e.message}" debug e end end def open_channel(options={}) ::AMQP::Channel.new(connection, ::AMQP::Channel.next_channel_id, options) do |c, open_ok| c.on_error(&self.class.callback(:on_channel_error)) yield c, open_ok end end def define_exchange(channel, options={}) channel.direct(exchange_name, exchange_options.merge(options)) end alias_method :exchange, :define_exchange def enqueue(channel, routing_key, payload) exchange(channel).publish(serialize(payload), :key => routing_key.to_s, :persistent => true) end alias_method :publish, :enqueue def queue_size(queue) raise NotImplementedError end private def setup_callbacks connection.on_tcp_connection_loss(&self.class.callback(:on_tcp_loss)) connection.on_recovery(&self.class.callback(:on_tcp_recovery)) end def initialize(connection, exchange_name, exchange_options = {}) @connection = connection @exchange_name = exchange_name @exchange_options = exchange_options setup_callbacks end end end end
require 'amqp' module QueueingRabbit module Client class AMQP include QueueingRabbit::Serializer include QueueingRabbit::Logging extend QueueingRabbit::Logging extend QueueingRabbit::Client::Callbacks attr_reader :connection, :exchange_name, :exchange_options define_callback :on_tcp_failure do |_| fatal "unable to establish TCP connection to broker" EM.stop end define_callback :on_tcp_loss do |c, _| info "re-establishing TCP connection to broker" c.reconnect(false, 1) end define_callback :on_tcp_recovery do info "TCP connection to broker is back and running" end define_callback :on_channel_error do |ch, channel_close| EM.stop fatal "channel error occured: #{channel_close.reply_text}" end def self.connection_options {:timeout => QueueingRabbit.tcp_timeout, :heartbeat => QueueingRabbit.heartbeat, :on_tcp_connection_failure => self.callback(:on_tcp_failure)} end def self.connect self.run_event_machine self.new(::AMQP.connect(QueueingRabbit.amqp_uri), QueueingRabbit.amqp_exchange_name, QueueingRabbit.amqp_exchange_options) end def self.run_event_machine return if EM.reactor_running? @event_machine_thread = Thread.new do EM.run do QueueingRabbit.trigger_event(:event_machine_started) end end end def self.join_event_machine_thread @event_machine_thread.join if @event_machine_thread end def disconnect info "closing AMQP broker connection..." connection.close do yield if block_given? EM.stop { exit } end end def define_queue(channel, queue_name, options={}) queue_name = queue_name.to_s routing_keys = [*options.delete(:routing_keys)] + [queue_name] channel.queue(queue_name.to_s, options) do |queue| routing_keys.each do |key| queue.bind(exchange(channel), routing_key: key.to_s) end end end def listen_queue(channel, queue_name, options={}, &block) define_queue(channel, queue_name, options).subscribe(ack: true) do |metadata, payload| begin process_message(deserialize(payload), &block) metadata.ack rescue JSON::JSONError => e error "JSON parser error occured: #{e.message}" debug e end end end def process_message(options) begin yield options rescue => e error "unexpected error #{e.class} occured: #{e.message}" debug e end end def open_channel(options={}) ::AMQP::Channel.new(connection, ::AMQP::Channel.next_channel_id, options) do |c, open_ok| c.on_error(&self.class.callback(:on_channel_error)) yield c, open_ok end end def define_exchange(channel, options={}) @exchange ||= channel.direct(exchange_name, exchange_options.merge(options)) end def exchange(*args) define_exchange(*args) end def enqueue(channel, routing_key, payload) exchange(channel).publish(serialize(payload), :key => routing_key.to_s, :persistent => true) end alias_method :publish, :enqueue private def setup_callbacks connection.on_tcp_connection_loss(&self.class.callback(:on_tcp_loss)) connection.on_recovery(&self.class.callback(:on_tcp_recovery)) end def initialize(connection, exchange_name, exchange_options) @connection = connection @exchange_name = exchange_name @exchange_options = exchange_options setup_callbacks end end end end Remove 1.9 Hash syntax to stay compatible with 1.8.7, acomplish a minor refactoring. require 'amqp' module QueueingRabbit module Client class AMQP include QueueingRabbit::Serializer include QueueingRabbit::Logging extend QueueingRabbit::Logging extend QueueingRabbit::Client::Callbacks attr_reader :connection, :exchange_name, :exchange_options define_callback :on_tcp_failure do |_| fatal "unable to establish TCP connection to broker" EM.stop end define_callback :on_tcp_loss do |c, _| info "re-establishing TCP connection to broker" c.reconnect(false, 1) end define_callback :on_tcp_recovery do info "TCP connection to broker is back and running" end define_callback :on_channel_error do |ch, channel_close| EM.stop fatal "channel error occured: #{channel_close.reply_text}" end def self.connection_options {:timeout => QueueingRabbit.tcp_timeout, :heartbeat => QueueingRabbit.heartbeat, :on_tcp_connection_failure => self.callback(:on_tcp_failure)} end def self.connect self.run_event_machine self.new(::AMQP.connect(QueueingRabbit.amqp_uri), QueueingRabbit.amqp_exchange_name, QueueingRabbit.amqp_exchange_options) end def self.run_event_machine return if EM.reactor_running? @event_machine_thread = Thread.new do EM.run do QueueingRabbit.trigger_event(:event_machine_started) end end end def self.join_event_machine_thread @event_machine_thread.join if @event_machine_thread end def disconnect info "closing AMQP broker connection..." connection.close do yield if block_given? EM.stop { exit } end end def define_queue(channel, queue_name, options={}) routing_keys = [*options.delete(:routing_keys)] + [queue_name] channel.queue(queue_name.to_s, options) do |queue| routing_keys.each do |key| queue.bind(exchange(channel), :routing_key => key.to_s) end end end def listen_queue(channel, queue_name, options={}, &block) define_queue(channel, queue_name, options) .subscribe(:ack => true) do |metadata, payload| begin process_message(deserialize(payload), &block) metadata.ack rescue JSON::JSONError => e error "JSON parser error occured: #{e.message}" debug e end end end def process_message(arguments) begin yield arguments rescue => e error "unexpected error #{e.class} occured: #{e.message}" debug e end end def open_channel(options={}) ::AMQP::Channel.new(connection, ::AMQP::Channel.next_channel_id, options) do |c, open_ok| c.on_error(&self.class.callback(:on_channel_error)) yield c, open_ok end end def define_exchange(channel, options={}) channel.direct(exchange_name, exchange_options.merge(options)) end alias_method :exchange, :define_exchange def enqueue(channel, routing_key, payload) exchange(channel).publish(serialize(payload), :key => routing_key.to_s, :persistent => true) end alias_method :publish, :enqueue private def setup_callbacks connection.on_tcp_connection_loss(&self.class.callback(:on_tcp_loss)) connection.on_recovery(&self.class.callback(:on_tcp_recovery)) end def initialize(connection, exchange_name, exchange_options) @connection = connection @exchange_name = exchange_name @exchange_options = exchange_options setup_callbacks end end end end
module RackWarden ### OMNIAUTH CODE ### # # class Identity extend Forwardable STORE=[] File.open('identities.yml', 'a').close attr_accessor :auth_hash, :user_id def_delegators :auth_hash, :uid, :provider, :info, :credentials, :extra, :[] def self.locate_or_new(identifier) # identifier should be auth_hash #puts "Identity.locate_or_new: #{identifier.class}" identity = (locate(identifier) || new(identifier)) end def self.new(auth_hash) #puts "Identity.new: #{auth_hash.class}" identity = super(auth_hash) if (auth_hash['uid'] && auth_hash['provider']) if identity #puts "Identity.new SUCCEEDED" (STORE << identity) && write else #puts "Identity.new FAILED" end identity end def self.write File.open('identities.yml', 'w') { |f| f.puts STORE.to_yaml } end def self.locate(identifier) # id or auth_hash #puts "Identity.locate: #{identifier.class} \"#{identifier}\"" auth_hash = (identifier.respond_to?(:uid) || identifier.is_a?(Hash)) ? identifier : {} uid = (auth_hash[:uid] || auth_hash['uid'] || auth_hash.uid || identifier) rescue identifier identity = STORE.find{|i| i.uid.to_s == uid.to_s} if identity && auth_hash['provider'] && auth_hash['uid'] identity.auth_hash = auth_hash end #puts "Identity.locate found: #{identity.class}" identity end ### For RackWarden def self.get(*args) locate(*args) end def id uid end def initialize(_auth_hash={}) @auth_hash = _auth_hash self end def name; info['name']; end def email; info['email']; end def username; name; end end # Identity Identity::STORE.replace(YAML.load_file('identities.yml') || []) ### END OMNIAUTH CODE ### end # RackWarden Add potential code for better Identity searches. module RackWarden ### OMNIAUTH CODE ### # # class Identity extend Forwardable STORE=[] File.open('identities.yml', 'a').close attr_accessor :auth_hash, :user_id def_delegators :auth_hash, :uid, :provider, :info, :credentials, :extra, :[] def self.locate_or_new(identifier) # identifier should be auth_hash #puts "Identity.locate_or_new: #{identifier.class}" identity = (locate(identifier) || new(identifier)) end def self.new(auth_hash) #puts "Identity.new: #{auth_hash.class}" identity = super(auth_hash) if (auth_hash['uid'] && auth_hash['provider']) if identity #puts "Identity.new SUCCEEDED" (STORE << identity) && write else #puts "Identity.new FAILED" end identity end def self.write File.open('identities.yml', 'w') { |f| f.puts STORE.to_yaml } end def self.locate(identifier) # id or auth_hash #puts "Identity.locate: #{identifier.class} \"#{identifier}\"" auth_hash = (identifier.respond_to?(:uid) || identifier.is_a?(Hash)) ? identifier : {} uid = (auth_hash[:uid] || auth_hash['uid'] || auth_hash.uid || identifier) rescue identifier identity = STORE.find{|i| i.uid.to_s == uid.to_s} if identity && auth_hash['provider'] && auth_hash['uid'] identity.auth_hash = auth_hash end #puts "Identity.locate found: #{identity.class}" identity end # def self.locate(identifier) # id or auth_hash or query hash # #puts "Identity.locate: #{identifier.class} \"#{identifier}\"" # auth_hash = (identifier.respond_to?(:uid) || identifier.is_a?(Hash)) ? identifier : {} # uid = (auth_hash[:uid] || auth_hash['uid'] || auth_hash.uid || identifier) rescue identifier # identity = STORE.find{|i| i.uid.to_s == uid.to_s || auth_hash.all?{|k,v| i[k].to_s == v.to_s}} # if identity && auth_hash['provider'] && auth_hash['uid'] # identity.auth_hash = auth_hash # end # #puts "Identity.locate found: #{identity.class}" # identity # end ### For RackWarden def self.get(*args) locate(*args) end def id uid end def initialize(_auth_hash={}) @auth_hash = _auth_hash self end def name; info['name']; end def email; info['email']; end def username; name; end end # Identity Identity::STORE.replace(YAML.load_file('identities.yml') || []) ### END OMNIAUTH CODE ### end # RackWarden
module RedisFailover # NodeManager manages a list of redis nodes. Upon startup, the NodeManager # will discover the current redis master and slaves. Each redis node is # monitored by a NodeWatcher instance. The NodeWatchers periodically # report the current state of the redis node it's watching to the # NodeManager via an asynchronous queue. The NodeManager processes the # state reports and reacts appropriately by handling stale/dead nodes, # and promoting a new redis master if it sees fit to do so. class NodeManager include Util # Number of seconds to wait before retrying bootstrap process. TIMEOUT = 3 # ZK Errors that the Node Manager cares about. ZK_ERRORS = [ ZK::Exceptions::LockAssertionFailedError, ZK::Exceptions::InterruptedSession, ZKDisconnectedError ].freeze # Errors that can happen during the node discovery process. NODE_DISCOVERY_ERRORS = [ InvalidNodeRoleError, NodeUnavailableError, NoMasterError, MultipleMastersError ].freeze # Creates a new instance. # # @param [Hash] options the options used to initialize the manager # @option options [String] :zkservers comma-separated ZK host:port pairs # @option options [String] :znode_path znode path override for redis nodes # @option options [String] :password password for redis nodes # @option options [Array<String>] :nodes the nodes to manage # @option options [String] :max_failures the max failures for a node def initialize(options) logger.info("Redis Node Manager v#{VERSION} starting (#{RUBY_DESCRIPTION})") @options = options @znode = @options[:znode_path] || Util::DEFAULT_ZNODE_PATH @manual_znode = ManualFailover::ZNODE_PATH @mutex = Mutex.new @shutdown = false @leader = false @master = nil @slaves = [] @unavailable = [] @lock_path = "#{@znode}_lock".freeze end # Starts the node manager. # # @note This method does not return until the manager terminates. def start return unless running? @queue = Queue.new setup_zk logger.info('Waiting to become master Node Manager ...') with_lock do @leader = true logger.info('Acquired master Node Manager lock') if discover_nodes initialize_path spawn_watchers handle_state_reports end end rescue *ZK_ERRORS => ex logger.error("ZK error while attempting to manage nodes: #{ex.inspect}") reset retry end # Notifies the manager of a state change. Used primarily by # {RedisFailover::NodeWatcher} to inform the manager of watched node states. # # @param [Node] node the node # @param [Symbol] state the state def notify_state(node, state) @queue << [node, state] end # Performs a reset of the manager. def reset @leader = false @watchers.each(&:shutdown) if @watchers @queue.clear @zk.close! if @zk @zk_lock = nil end # Initiates a graceful shutdown. def shutdown logger.info('Shutting down ...') @mutex.synchronize do @shutdown = true end end private # Configures the ZooKeeper client. def setup_zk @zk.close! if @zk @zk = ZK.new("#{@options[:zkservers]}#{@options[:chroot] || ''}") @zk.on_expired_session { notify_state(:zk_disconnected, nil) } @zk.register(@manual_znode) do |event| if event.node_created? || event.node_changed? perform_manual_failover end end @zk.on_connected { @zk.stat(@manual_znode, :watch => true) } @zk.stat(@manual_znode, :watch => true) end # Handles periodic state reports from {RedisFailover::NodeWatcher} instances. def handle_state_reports while running? && (state_report = @queue.pop) begin @mutex.synchronize do return unless running? @zk_lock.assert! node, state = state_report case state when :unavailable then handle_unavailable(node) when :available then handle_available(node) when :syncing then handle_syncing(node) when :zk_disconnected then raise ZKDisconnectedError else raise InvalidNodeStateError.new(node, state) end # flush current state write_state end rescue *ZK_ERRORS # fail hard if this is a ZK connection-related error raise rescue => ex logger.error("Error handling #{state_report.inspect}: #{ex.inspect}") logger.error(ex.backtrace.join("\n")) end end end # Handles an unavailable node. # # @param [Node] node the unavailable node def handle_unavailable(node) # no-op if we already know about this node return if @unavailable.include?(node) logger.info("Handling unavailable node: #{node}") @unavailable << node # find a new master if this node was a master if node == @master logger.info("Demoting currently unavailable master #{node}.") promote_new_master else @slaves.delete(node) end end # Handles an available node. # # @param [Node] node the available node def handle_available(node) reconcile(node) # no-op if we already know about this node return if @master == node || (@master && @slaves.include?(node)) logger.info("Handling available node: #{node}") if @master # master already exists, make a slave node.make_slave!(@master) @slaves << node else # no master exists, make this the new master promote_new_master(node) end @unavailable.delete(node) end # Handles a node that is currently syncing. # # @param [Node] node the syncing node def handle_syncing(node) reconcile(node) if node.syncing_with_master? && node.prohibits_stale_reads? logger.info("Node #{node} not ready yet, still syncing with master.") force_unavailable_slave(node) return end # otherwise, we can use this node handle_available(node) end # Handles a manual failover request to the given node. # # @param [Node] node the candidate node for failover def handle_manual_failover(node) # no-op if node to be failed over is already master return if @master == node logger.info("Handling manual failover") # make current master a slave, and promote new master @slaves << @master if @master @slaves.delete(node) promote_new_master(node) end # Promotes a new master. # # @param [Node] node the optional node to promote # @note if no node is specified, a random slave will be used def promote_new_master(node = nil) delete_path @master = nil # make a specific node or slave the new master candidate = node || @slaves.pop unless candidate logger.error('Failed to promote a new master, no candidate available.') return end redirect_slaves_to(candidate) candidate.make_master! @master = candidate create_path write_state logger.info("Successfully promoted #{candidate} to master.") end # Discovers the current master and slave nodes. # @return [Boolean] true if nodes successfully discovered, false otherwise def discover_nodes @mutex.synchronize do return false unless running? nodes = @options[:nodes].map { |opts| Node.new(opts) }.uniq if @master = find_existing_master logger.info("Using master #{@master} from existing znode config.") elsif @master = guess_master(nodes) logger.info("Guessed master #{@master} from known redis nodes.") end @slaves = nodes - [@master] logger.info("Managing master (#{@master}) and slaves " + "(#{@slaves.map(&:to_s).join(', ')})") # ensure that slaves are correctly pointing to this master redirect_slaves_to(@master) true end rescue *NODE_DISCOVERY_ERRORS => ex msg = <<-MSG.gsub(/\s+/, ' ') Failed to discover master node: #{ex.inspect} In order to ensure a safe startup, redis_failover requires that all redis nodes be accessible, and only a single node indicating that it's the master. In order to fix this, you can perform a manual failover via redis_failover, or manually fix the individual redis servers. This discovery process will retry in #{TIMEOUT}s. MSG logger.warn(msg) sleep(TIMEOUT) retry end # Seeds the initial node master from an existing znode config. def find_existing_master if data = @zk.get(@znode).first nodes = symbolize_keys(decode(data)) master = node_from(nodes[:master]) logger.info("Master from existing znode config: #{master || 'none'}") # Check for case where a node previously thought to be the master was # somehow manually reconfigured to be a slave outside of the node manager's # control. if master && master.slave? raise InvalidNodeRoleError.new(node, :master, :slave) end master end rescue ZK::Exceptions::NoNode # blank slate, no last known master nil end # Creates a Node instance from a string. # # @param [String] node_string a string representation of a node (e.g., host:port) # @return [Node] the Node representation def node_from(node_string) return if node_string.nil? host, port = node_string.split(':', 2) Node.new(:host => host, :port => port, :password => @options[:password]) end # Spawns the {RedisFailover::NodeWatcher} instances for each managed node. def spawn_watchers @watchers = [@master, @slaves, @unavailable].flatten.compact.map do |node| NodeWatcher.new(self, node, @options[:max_failures] || 3) end @watchers.each(&:watch) end # Searches for the master node. # # @param [Array<Node>] nodes the nodes to search # @return [Node] the found master node, nil if not found def guess_master(nodes) master_nodes = nodes.select { |node| node.master? } raise NoMasterError if master_nodes.empty? raise MultipleMastersError.new(master_nodes) if master_nodes.size > 1 master_nodes.first end # Redirects all slaves to the specified node. # # @param [Node] node the node to which slaves are redirected def redirect_slaves_to(node) @slaves.dup.each do |slave| begin slave.make_slave!(node) rescue NodeUnavailableError logger.info("Failed to redirect unreachable slave #{slave} to #{node}") force_unavailable_slave(slave) end end end # Forces a slave to be marked as unavailable. # # @param [Node] node the node to force as unavailable def force_unavailable_slave(node) @slaves.delete(node) @unavailable << node unless @unavailable.include?(node) end # It's possible that a newly available node may have been restarted # and completely lost its dynamically set run-time role by the node # manager. This method ensures that the node resumes its role as # determined by the manager. # # @param [Node] node the node to reconcile def reconcile(node) return if @master == node && node.master? return if @master && node.slave_of?(@master) logger.info("Reconciling node #{node}") if @master == node && !node.master? # we think the node is a master, but the node doesn't node.make_master! return end # verify that node is a slave for the current master if @master && !node.slave_of?(@master) node.make_slave!(@master) end end # @return [Hash] the set of current nodes grouped by category def current_nodes { :master => @master ? @master.to_s : nil, :slaves => @slaves.map(&:to_s), :unavailable => @unavailable.map(&:to_s) } end # Deletes the znode path containing the redis nodes. def delete_path @zk.delete(@znode) logger.info("Deleted ZooKeeper node #{@znode}") rescue ZK::Exceptions::NoNode => ex logger.info("Tried to delete missing znode: #{ex.inspect}") end # Creates the znode path containing the redis nodes. def create_path unless @zk.exists?(@znode) @zk.create(@znode, encode(current_nodes)) logger.info("Created ZooKeeper node #{@znode}") end rescue ZK::Exceptions::NodeExists # best effort end # Initializes the znode path containing the redis nodes. def initialize_path create_path write_state end # Writes the current redis nodes state to the znode path. def write_state create_path @zk.set(@znode, encode(current_nodes)) end # Executes a block wrapped in a ZK exclusive lock. def with_lock @zk_lock = @zk.locker(@lock_path) while running? && !@zk_lock.lock sleep(TIMEOUT) end if running? yield end ensure @zk_lock.unlock! if @zk_lock end # Perform a manual failover to a redis node. def perform_manual_failover @mutex.synchronize do return unless running? && @leader && @zk_lock @zk_lock.assert! new_master = @zk.get(@manual_znode, :watch => true).first return unless new_master && new_master.size > 0 logger.info("Received manual failover request for: #{new_master}") logger.info("Current nodes: #{current_nodes.inspect}") node = new_master == ManualFailover::ANY_SLAVE ? @slaves.shuffle.first : node_from(new_master) if node handle_manual_failover(node) else logger.error('Failed to perform manual failover, no candidate found.') end end rescue => ex logger.error("Error handling a manual failover: #{ex.inspect}") logger.error(ex.backtrace.join("\n")) ensure @zk.stat(@manual_znode, :watch => true) end # @return [Boolean] true if running, false otherwise def running? !@shutdown end end end fix typo module RedisFailover # NodeManager manages a list of redis nodes. Upon startup, the NodeManager # will discover the current redis master and slaves. Each redis node is # monitored by a NodeWatcher instance. The NodeWatchers periodically # report the current state of the redis node it's watching to the # NodeManager via an asynchronous queue. The NodeManager processes the # state reports and reacts appropriately by handling stale/dead nodes, # and promoting a new redis master if it sees fit to do so. class NodeManager include Util # Number of seconds to wait before retrying bootstrap process. TIMEOUT = 3 # ZK Errors that the Node Manager cares about. ZK_ERRORS = [ ZK::Exceptions::LockAssertionFailedError, ZK::Exceptions::InterruptedSession, ZKDisconnectedError ].freeze # Errors that can happen during the node discovery process. NODE_DISCOVERY_ERRORS = [ InvalidNodeRoleError, NodeUnavailableError, NoMasterError, MultipleMastersError ].freeze # Creates a new instance. # # @param [Hash] options the options used to initialize the manager # @option options [String] :zkservers comma-separated ZK host:port pairs # @option options [String] :znode_path znode path override for redis nodes # @option options [String] :password password for redis nodes # @option options [Array<String>] :nodes the nodes to manage # @option options [String] :max_failures the max failures for a node def initialize(options) logger.info("Redis Node Manager v#{VERSION} starting (#{RUBY_DESCRIPTION})") @options = options @znode = @options[:znode_path] || Util::DEFAULT_ZNODE_PATH @manual_znode = ManualFailover::ZNODE_PATH @mutex = Mutex.new @shutdown = false @leader = false @master = nil @slaves = [] @unavailable = [] @lock_path = "#{@znode}_lock".freeze end # Starts the node manager. # # @note This method does not return until the manager terminates. def start return unless running? @queue = Queue.new setup_zk logger.info('Waiting to become master Node Manager ...') with_lock do @leader = true logger.info('Acquired master Node Manager lock') if discover_nodes initialize_path spawn_watchers handle_state_reports end end rescue *ZK_ERRORS => ex logger.error("ZK error while attempting to manage nodes: #{ex.inspect}") reset retry end # Notifies the manager of a state change. Used primarily by # {RedisFailover::NodeWatcher} to inform the manager of watched node states. # # @param [Node] node the node # @param [Symbol] state the state def notify_state(node, state) @queue << [node, state] end # Performs a reset of the manager. def reset @leader = false @watchers.each(&:shutdown) if @watchers @queue.clear @zk.close! if @zk @zk_lock = nil end # Initiates a graceful shutdown. def shutdown logger.info('Shutting down ...') @mutex.synchronize do @shutdown = true end end private # Configures the ZooKeeper client. def setup_zk @zk.close! if @zk @zk = ZK.new("#{@options[:zkservers]}#{@options[:chroot] || ''}") @zk.on_expired_session { notify_state(:zk_disconnected, nil) } @zk.register(@manual_znode) do |event| if event.node_created? || event.node_changed? perform_manual_failover end end @zk.on_connected { @zk.stat(@manual_znode, :watch => true) } @zk.stat(@manual_znode, :watch => true) end # Handles periodic state reports from {RedisFailover::NodeWatcher} instances. def handle_state_reports while running? && (state_report = @queue.pop) begin @mutex.synchronize do return unless running? @zk_lock.assert! node, state = state_report case state when :unavailable then handle_unavailable(node) when :available then handle_available(node) when :syncing then handle_syncing(node) when :zk_disconnected then raise ZKDisconnectedError else raise InvalidNodeStateError.new(node, state) end # flush current state write_state end rescue *ZK_ERRORS # fail hard if this is a ZK connection-related error raise rescue => ex logger.error("Error handling #{state_report.inspect}: #{ex.inspect}") logger.error(ex.backtrace.join("\n")) end end end # Handles an unavailable node. # # @param [Node] node the unavailable node def handle_unavailable(node) # no-op if we already know about this node return if @unavailable.include?(node) logger.info("Handling unavailable node: #{node}") @unavailable << node # find a new master if this node was a master if node == @master logger.info("Demoting currently unavailable master #{node}.") promote_new_master else @slaves.delete(node) end end # Handles an available node. # # @param [Node] node the available node def handle_available(node) reconcile(node) # no-op if we already know about this node return if @master == node || (@master && @slaves.include?(node)) logger.info("Handling available node: #{node}") if @master # master already exists, make a slave node.make_slave!(@master) @slaves << node else # no master exists, make this the new master promote_new_master(node) end @unavailable.delete(node) end # Handles a node that is currently syncing. # # @param [Node] node the syncing node def handle_syncing(node) reconcile(node) if node.syncing_with_master? && node.prohibits_stale_reads? logger.info("Node #{node} not ready yet, still syncing with master.") force_unavailable_slave(node) return end # otherwise, we can use this node handle_available(node) end # Handles a manual failover request to the given node. # # @param [Node] node the candidate node for failover def handle_manual_failover(node) # no-op if node to be failed over is already master return if @master == node logger.info("Handling manual failover") # make current master a slave, and promote new master @slaves << @master if @master @slaves.delete(node) promote_new_master(node) end # Promotes a new master. # # @param [Node] node the optional node to promote # @note if no node is specified, a random slave will be used def promote_new_master(node = nil) delete_path @master = nil # make a specific node or slave the new master candidate = node || @slaves.pop unless candidate logger.error('Failed to promote a new master, no candidate available.') return end redirect_slaves_to(candidate) candidate.make_master! @master = candidate create_path write_state logger.info("Successfully promoted #{candidate} to master.") end # Discovers the current master and slave nodes. # @return [Boolean] true if nodes successfully discovered, false otherwise def discover_nodes @mutex.synchronize do return false unless running? nodes = @options[:nodes].map { |opts| Node.new(opts) }.uniq if @master = find_existing_master logger.info("Using master #{@master} from existing znode config.") elsif @master = guess_master(nodes) logger.info("Guessed master #{@master} from known redis nodes.") end @slaves = nodes - [@master] logger.info("Managing master (#{@master}) and slaves " + "(#{@slaves.map(&:to_s).join(', ')})") # ensure that slaves are correctly pointing to this master redirect_slaves_to(@master) true end rescue *NODE_DISCOVERY_ERRORS => ex msg = <<-MSG.gsub(/\s+/, ' ') Failed to discover master node: #{ex.inspect} In order to ensure a safe startup, redis_failover requires that all redis nodes be accessible, and only a single node indicating that it's the master. In order to fix this, you can perform a manual failover via redis_failover, or manually fix the individual redis servers. This discovery process will retry in #{TIMEOUT}s. MSG logger.warn(msg) sleep(TIMEOUT) retry end # Seeds the initial node master from an existing znode config. def find_existing_master if data = @zk.get(@znode).first nodes = symbolize_keys(decode(data)) master = node_from(nodes[:master]) logger.info("Master from existing znode config: #{master || 'none'}") # Check for case where a node previously thought to be the master was # somehow manually reconfigured to be a slave outside of the node manager's # control. if master && master.slave? raise InvalidNodeRoleError.new(master, :master, :slave) end master end rescue ZK::Exceptions::NoNode # blank slate, no last known master nil end # Creates a Node instance from a string. # # @param [String] node_string a string representation of a node (e.g., host:port) # @return [Node] the Node representation def node_from(node_string) return if node_string.nil? host, port = node_string.split(':', 2) Node.new(:host => host, :port => port, :password => @options[:password]) end # Spawns the {RedisFailover::NodeWatcher} instances for each managed node. def spawn_watchers @watchers = [@master, @slaves, @unavailable].flatten.compact.map do |node| NodeWatcher.new(self, node, @options[:max_failures] || 3) end @watchers.each(&:watch) end # Searches for the master node. # # @param [Array<Node>] nodes the nodes to search # @return [Node] the found master node, nil if not found def guess_master(nodes) master_nodes = nodes.select { |node| node.master? } raise NoMasterError if master_nodes.empty? raise MultipleMastersError.new(master_nodes) if master_nodes.size > 1 master_nodes.first end # Redirects all slaves to the specified node. # # @param [Node] node the node to which slaves are redirected def redirect_slaves_to(node) @slaves.dup.each do |slave| begin slave.make_slave!(node) rescue NodeUnavailableError logger.info("Failed to redirect unreachable slave #{slave} to #{node}") force_unavailable_slave(slave) end end end # Forces a slave to be marked as unavailable. # # @param [Node] node the node to force as unavailable def force_unavailable_slave(node) @slaves.delete(node) @unavailable << node unless @unavailable.include?(node) end # It's possible that a newly available node may have been restarted # and completely lost its dynamically set run-time role by the node # manager. This method ensures that the node resumes its role as # determined by the manager. # # @param [Node] node the node to reconcile def reconcile(node) return if @master == node && node.master? return if @master && node.slave_of?(@master) logger.info("Reconciling node #{node}") if @master == node && !node.master? # we think the node is a master, but the node doesn't node.make_master! return end # verify that node is a slave for the current master if @master && !node.slave_of?(@master) node.make_slave!(@master) end end # @return [Hash] the set of current nodes grouped by category def current_nodes { :master => @master ? @master.to_s : nil, :slaves => @slaves.map(&:to_s), :unavailable => @unavailable.map(&:to_s) } end # Deletes the znode path containing the redis nodes. def delete_path @zk.delete(@znode) logger.info("Deleted ZooKeeper node #{@znode}") rescue ZK::Exceptions::NoNode => ex logger.info("Tried to delete missing znode: #{ex.inspect}") end # Creates the znode path containing the redis nodes. def create_path unless @zk.exists?(@znode) @zk.create(@znode, encode(current_nodes)) logger.info("Created ZooKeeper node #{@znode}") end rescue ZK::Exceptions::NodeExists # best effort end # Initializes the znode path containing the redis nodes. def initialize_path create_path write_state end # Writes the current redis nodes state to the znode path. def write_state create_path @zk.set(@znode, encode(current_nodes)) end # Executes a block wrapped in a ZK exclusive lock. def with_lock @zk_lock = @zk.locker(@lock_path) while running? && !@zk_lock.lock sleep(TIMEOUT) end if running? yield end ensure @zk_lock.unlock! if @zk_lock end # Perform a manual failover to a redis node. def perform_manual_failover @mutex.synchronize do return unless running? && @leader && @zk_lock @zk_lock.assert! new_master = @zk.get(@manual_znode, :watch => true).first return unless new_master && new_master.size > 0 logger.info("Received manual failover request for: #{new_master}") logger.info("Current nodes: #{current_nodes.inspect}") node = new_master == ManualFailover::ANY_SLAVE ? @slaves.shuffle.first : node_from(new_master) if node handle_manual_failover(node) else logger.error('Failed to perform manual failover, no candidate found.') end end rescue => ex logger.error("Error handling a manual failover: #{ex.inspect}") logger.error(ex.backtrace.join("\n")) ensure @zk.stat(@manual_znode, :watch => true) end # @return [Boolean] true if running, false otherwise def running? !@shutdown end end end
module RedmineIRCGateway class Channel include Net::IRC::Constants def initialize(channel, prefix, users = []) @prefix = prefix @name = channel @owner_user = users.first end def talk(message) Command.send(message.content.to_sym).each do |r| yield r end rescue NoMethodError => e puts e yield [@owner_user, "Command Not Found"] rescue => e yield [@owner_user, "Command Error"] end def crawl Command.all.each { |i| yield i } end end end command をすべて downcase module RedmineIRCGateway class Channel include Net::IRC::Constants def initialize(channel, prefix, users = []) @prefix = prefix @name = channel @owner_user = users.first end def talk(message) Command.send(message.content.downcase.to_sym).each do |r| yield r end rescue NoMethodError => e puts e yield [@owner_user, "Command Not Found"] rescue => e yield [@owner_user, "Command Error"] end def crawl Command.all.each { |i| yield i } end end end
module SchemaAssociations VERSION = "0.1.1" end prepare to 1.1.2 release module SchemaAssociations VERSION = "0.1.2" end
up to page 30 implemented class Number < Struct.new(:value) def to_s value.to_s end def inspect "#{self}" end def reducible? false end end class Variable < Struct.new(:name) def to_s name.to_s end def inspect "#{self}" end def reducible? true end def reduce(environment) envrionment[name] end end class Add < Struct.new(:left, :right) def to_s "#{left} + #{right}" end def inspect "#{self}" end def reducible? true end def reduce(environment) if left.reducible? Add.new(left.reduce, right) elsif right.reducible? Add.new(left, right.reduce) else Number.new(left.value + right.value) end end end class Multiply < Struct.new(:left, :right) def to_s "#{left} * #{right}" end def inspect "#{self}" end def reducible? true end def reduce(environment) if left.reducible? Multiply.new(left.reduce, right) elsif right.reducible? Multiply.new(left, right.reduce) else Number.new(left.value * right.value) end end end class Machine < Struct.new(:expression, :environment) def run puts expression while expression.reducible? self.expression = expression.reduce(environment) puts expression end end end
#!/usr/bin/env ruby -KU # ============================================================================================= # Schemaform # A high-level database construction and programming layer. # # [Website] http://schemaform.org # [Copyright] Copyright 2004-2011 Chris Poirier # [License] Licensed 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. # ============================================================================================= # # comment module Schemaform class Schema # # Brings the database schema up to date. def upgrade(sequel, prefix = nil) layout = lay_out(sequel.database_type, prefix) sequel.transaction do layout.tables.each do |table| sequel.execute_ddl(table.to_create_sql) unless sequel.table_exists?(table.name.to_s) end end puts layout.to_create_sql exit end end # Schema end # Schemaform Removed a premature exit from last commit. #!/usr/bin/env ruby -KU # ============================================================================================= # Schemaform # A high-level database construction and programming layer. # # [Website] http://schemaform.org # [Copyright] Copyright 2004-2011 Chris Poirier # [License] Licensed 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. # ============================================================================================= # # comment module Schemaform class Schema # # Brings the database schema up to date. def upgrade(sequel, prefix = nil) layout = lay_out(sequel.database_type, prefix) sequel.transaction do layout.tables.each do |table| sequel.execute_ddl(table.to_create_sql) unless sequel.table_exists?(table.name.to_s) end end end end # Schema end # Schemaform
require 'colorize' module Seek module Ontologies class Synchronize def initialize Rails.logger.debug 'clearing caches' Rails.cache.clear end def synchronize_technology_types synchronize_types 'technology_type' end def synchronize_assay_types synchronize_types 'assay_type' end # private def synchronize_types(type) Assay.record_timestamps = false # check for label in ontology found_suggested_types = get_suggested_types_found_in_ontology(type) Rails.logger.info "matching suggested #{type.pluralize} found in ontology: #{found_suggested_types.map(&:label).join(', ')}" replace_suggested_types_with_ontology(found_suggested_types, type) update_assay_with_obselete_uris(type) Assay.record_timestamps = true nil end def update_assay_with_obselete_uris(type) assays_for_update = Assay.all.reject do |assay| assay.send("valid_#{type}_uri?") end # check all assay uri-s, for those that don't exist in ontology. This is unusual and uris shouldn't be removed # revert to top level uri - print warning Rails.logger.debug "#{assays_for_update.count} assays found where the #{type} no longer exists in the ontology".green disable_authorization_checks do assays_for_update.each do |assay| assay.send("use_default_#{type}_uri!") assay.save end end end def replace_suggested_types_with_ontology(found_suggested_types, type) label_hash = type_labels_and_uri(type) disable_authorization_checks do found_suggested_types.each do |suggested_type| new_ontology_uri = label_hash[suggested_type.label.downcase] assays = Assay.where("suggested_#{type}_id" => suggested_type.id) if type == 'assay_type' cannot_be_removed = assay_changes_class?(assays, new_ontology_uri) end if cannot_be_removed update_suggested_type(suggested_type) else update_assays_and_remove_suggested_type(assays, suggested_type, type, new_ontology_uri) end end end end def update_suggested_type(suggested_type) suggested_type.label = suggested_type.label + '2' Rails.logger.info "suggested label updated to #{suggested_type.label}" suggested_type.save end def update_assays_and_remove_suggested_type(assays, suggested_type, type, new_ontology_uri) assays.each do |assay| Rails.logger.info "updating assay: #{assay.id} with the new #{type} uri #{new_ontology_uri}".green assay.send("#{type}_uri=", new_ontology_uri) assay.save end Rails.logger.info "destroying suggested type #{suggested_type.id} with label #{suggested_type.label}".green suggested_type.destroy end # detected whether the new uri would lead to any of the assays changing between # modelling or experimental type def assay_changes_class?(assays, ontology_uri) assay_class = determine_assay_class_from_uri(ontology_uri) assays.find do |assay| assay.assay_class.key != assay_class.key end end def determine_assay_class_from_uri(uri) ontology_class = Seek::Ontologies::AssayTypeReader.instance.class_for_uri(uri) ontology_class.nil? ? AssayClass.for_type('modelling') : AssayClass.for_type('experimental') end def get_suggested_types_found_in_ontology(type) label_hash = type_labels_and_uri(type) get_types(type).select do |suggested_type| label_hash[suggested_type.label.downcase] end end def get_types(suffix) "suggested_#{suffix}".classify.constantize.all end def type_labels_and_uri(type) if type == 'assay_type' hash = Seek::Ontologies::AssayTypeReader.instance.class_hierarchy.hash_by_label hash.merge!(Seek::Ontologies::ModellingAnalysisTypeReader.instance.class_hierarchy.hash_by_label) else hash = Seek::Ontologies::TechnologyTypeReader.instance.class_hierarchy.hash_by_label end # remove_suggested Hash[hash.map do |key, value| [key, value.uri.to_s] end] end end end end a safer way to clear the caches and reset before doing an ontology resync avoids an error if the cache directory is missing, and also only clears what is necessary and state held in memory require 'colorize' module Seek module Ontologies class Synchronize def initialize clear_caches end def synchronize_technology_types synchronize_types 'technology_type' end def synchronize_assay_types synchronize_types 'assay_type' end # private def synchronize_types(type) Assay.record_timestamps = false # check for label in ontology found_suggested_types = get_suggested_types_found_in_ontology(type) Rails.logger.info "matching suggested #{type.pluralize} found in ontology: #{found_suggested_types.map(&:label).join(', ')}" replace_suggested_types_with_ontology(found_suggested_types, type) update_assay_with_obselete_uris(type) Assay.record_timestamps = true nil end def update_assay_with_obselete_uris(type) assays_for_update = Assay.all.reject do |assay| assay.send("valid_#{type}_uri?") end # check all assay uri-s, for those that don't exist in ontology. This is unusual and uris shouldn't be removed # revert to top level uri - print warning Rails.logger.debug "#{assays_for_update.count} assays found where the #{type} no longer exists in the ontology".green disable_authorization_checks do assays_for_update.each do |assay| assay.send("use_default_#{type}_uri!") assay.save end end end def replace_suggested_types_with_ontology(found_suggested_types, type) label_hash = type_labels_and_uri(type) disable_authorization_checks do found_suggested_types.each do |suggested_type| new_ontology_uri = label_hash[suggested_type.label.downcase] assays = Assay.where("suggested_#{type}_id" => suggested_type.id) if type == 'assay_type' cannot_be_removed = assay_changes_class?(assays, new_ontology_uri) end if cannot_be_removed update_suggested_type(suggested_type) else update_assays_and_remove_suggested_type(assays, suggested_type, type, new_ontology_uri) end end end end def update_suggested_type(suggested_type) suggested_type.label = suggested_type.label + '2' Rails.logger.info "suggested label updated to #{suggested_type.label}" suggested_type.save end def update_assays_and_remove_suggested_type(assays, suggested_type, type, new_ontology_uri) assays.each do |assay| Rails.logger.info "updating assay: #{assay.id} with the new #{type} uri #{new_ontology_uri}".green assay.send("#{type}_uri=", new_ontology_uri) assay.save end Rails.logger.info "destroying suggested type #{suggested_type.id} with label #{suggested_type.label}".green suggested_type.destroy end # detected whether the new uri would lead to any of the assays changing between # modelling or experimental type def assay_changes_class?(assays, ontology_uri) assay_class = determine_assay_class_from_uri(ontology_uri) assays.find do |assay| assay.assay_class.key != assay_class.key end end def determine_assay_class_from_uri(uri) ontology_class = Seek::Ontologies::AssayTypeReader.instance.class_for_uri(uri) ontology_class.nil? ? AssayClass.for_type('modelling') : AssayClass.for_type('experimental') end def get_suggested_types_found_in_ontology(type) label_hash = type_labels_and_uri(type) get_types(type).select do |suggested_type| label_hash[suggested_type.label.downcase] end end def get_types(suffix) "suggested_#{suffix}".classify.constantize.all end def type_labels_and_uri(type) if type == 'assay_type' hash = Seek::Ontologies::AssayTypeReader.instance.class_hierarchy.hash_by_label hash.merge!(Seek::Ontologies::ModellingAnalysisTypeReader.instance.class_hierarchy.hash_by_label) else hash = Seek::Ontologies::TechnologyTypeReader.instance.class_hierarchy.hash_by_label end # remove_suggested Hash[hash.map do |key, value| [key, value.uri.to_s] end] end def clear_caches Rails.logger.debug 'clearing caches' Seek::Ontologies::AssayTypeReader.instance.reset Seek::Ontologies::TechnologyTypeReader.instance.reset Seek::Ontologies::ModellingAnalysisTypeReader.instance.reset end end end end
# -*- coding: utf-8 -*- class BookmarkViewController < UIViewController attr_accessor :bookmark, :url, :short_url, :user_name, :on_modal def viewDidLoad super self.navigationItem.title = "ブックマーク" self.view.backgroundColor = UIColor.whiteColor self.backGestureEnabled = true self.navigationItem.backBarButtonItem = UIBarButtonItem.titled("戻る") self.configure_toolbar self.view << @bookmarkView = HBFav2::BookmarkView.new.tap do |v| v.frame = self.view.bounds v.backgroundColor = UIColor.whiteColor v.headerView.addGestureRecognizer(UITapGestureRecognizer.alloc.initWithTarget(self, action:'open_profile')) v.starView.addGestureRecognizer(UITapGestureRecognizer.alloc.initWithTarget(self, action:'open_stars')) v.titleButton.addTarget(self, action:'open_webview', forControlEvents:UIControlEventTouchUpInside) v.titleButton.addGestureRecognizer(UILongPressGestureRecognizer.alloc.initWithTarget(self, action:'on_action')) v.usersButton.addTarget(self, action:'open_bookmarks', forControlEvents:UIControlEventTouchUpInside) v.delegate = self end self.view << @indicator = UIActivityIndicatorView.gray ## clickable URL に悪影響を与えるので中止 # self.view.addGestureRecognizer(UITapGestureRecognizer.alloc.initWithTarget(self, action:'toggle_toolbar')) if self.on_modal == true UIBarButtonItem.stop.tap do |btn| btn.action = 'on_close' btn.target = self end self.navigationItem.leftBarButtonItem = UIBarButtonItem.alloc.initWithBarButtonSystemItem( UIBarButtonSystemItemStop, target:self, action:'on_close' ) end end def open_profile controller = TimelineViewController.new.tap do |c| c.user = bookmark.user c.content_type = :bookmark c.title = bookmark.user.name end self.navigationController.pushViewController(controller, animated:true) end def open_stars controller = StarsViewController.new.tap do |c| c.url = @bookmark.permalink @bookmarkView.starView.highlighted = true @bookmarkView.starView.backgroundColor = '#e5f0ff'.to_color end self.presentViewController( UINavigationController.alloc.initWithRootViewController(controller), animated:true, completion:nil ) end def open_webview controller = WebViewController.new controller.bookmark = @bookmark self.navigationController.pushViewController(controller, animated: true) end def open_bookmarks controller = BookmarksViewController.new.tap { |c| c.entry = @bookmark } self.presentViewController(HBFav2NavigationController.alloc.initWithRootViewController(controller), animated:true, completion:nil) end def viewWillAppear(animated) super ## 応急処置 UIApplication.sharedApplication.statusBarStyle = UIStatusBarStyleBlackOpaque UIApplication.sharedApplication.setStatusBarHidden(false, animated:animated) self.wantsFullScreenLayout = false self.navigationController.setToolbarHidden(false, animated:self.on_modal ? false : true) if self.bookmark.present? @bookmarkView.bookmark = self.bookmark elsif self.short_url and self.user_name @indicator.center = self.view.center @indicator.startAnimating ## FIXME: error handling GoogleAPI.sharedAPI.expand_url(self.short_url) do |response, long_url| if response.ok? and long_url BookmarkManager.sharedManager.get_bookmark(long_url, self.user_name) do |res, bm| @indicator.stopAnimating if bm self.bookmark = bm @bookmarkView.bookmark = bm end end end end end @bookmarkView.tap do |v| v.starView.highlighted = false v.starView.backgroundColor = UIColor.whiteColor end end def toggle_toolbar if @toolbar_visible @toolbar_visible = false self.navigationController.setToolbarHidden(true, animated:true) else @toolbar_visible = true self.navigationController.setToolbarHidden(false, animated:true) end end def viewWillDisappear(animated) super self.navigationController.toolbar.translucent = false end def configure_toolbar spacer = UIBarButtonItem.fixedspace spacer.width = self.view.size.width - 110 self.toolbarItems = [ spacer, UIBarButtonItem.alloc.initWithBarButtonSystemItem(UIBarButtonSystemItemCompose, target:self, action: 'on_bookmark'), UIBarButtonItem.flexiblespace, # BookmarkBarButtonItem.alloc.initWithTarget(self, action:'on_bookmark'), UIBarButtonItem.alloc.initWithBarButtonSystemItem(UIBarButtonSystemItemAction, target:self, action:'on_action'), ] end def on_bookmark open_hatena_bookmark_view end def open_hatena_bookmark_view controller = HTBHatenaBookmarkViewController.alloc.init controller.URL = @bookmark.link.nsurl self.presentViewController(controller, animated:true, completion:nil) end def on_action controller = URLActivityViewController.alloc.initWithDefaultActivities([ @bookmark.title, @bookmark.link.nsurl ]) self.presentViewController(controller, animated:true, completion:nil) end def attributedLabel(label, didSelectLinkWithURL:url) if url.scheme == 'bookmark' name = url.host controller = TimelineViewController.new.tap do |c| user = User.new({ :name => name }) c.user = user c.content_type = :bookmark c.title = user.name end return self.navigationController.pushViewController(controller, animated:true) end if url.scheme == 'twitter' name = url.host link = "http://twitter.com/#{name}" else link = url.absoluteString end bookmark = Bookmark.new( { :title => '', :link => link, :count => nil } ) controller = WebViewController.new controller.bookmark = bookmark self.navigationController.pushViewController(controller, animated:true) end def on_close self.dismissModalViewControllerAnimated(true, completion:nil) end def dealloc NSLog("dealloc: " + self.class.name) super end end ブックマーク見つからない時のエラー # -*- coding: utf-8 -*- class BookmarkViewController < UIViewController attr_accessor :bookmark, :url, :short_url, :user_name, :on_modal def viewDidLoad super self.navigationItem.title = "ブックマーク" self.view.backgroundColor = UIColor.whiteColor self.backGestureEnabled = true self.navigationItem.backBarButtonItem = UIBarButtonItem.titled("戻る") self.configure_toolbar self.view << @bookmarkView = HBFav2::BookmarkView.new.tap do |v| v.frame = self.view.bounds v.backgroundColor = UIColor.whiteColor v.headerView.addGestureRecognizer(UITapGestureRecognizer.alloc.initWithTarget(self, action:'open_profile')) v.starView.addGestureRecognizer(UITapGestureRecognizer.alloc.initWithTarget(self, action:'open_stars')) v.titleButton.addTarget(self, action:'open_webview', forControlEvents:UIControlEventTouchUpInside) v.titleButton.addGestureRecognizer(UILongPressGestureRecognizer.alloc.initWithTarget(self, action:'on_action')) v.usersButton.addTarget(self, action:'open_bookmarks', forControlEvents:UIControlEventTouchUpInside) v.delegate = self end self.view << @indicator = UIActivityIndicatorView.gray ## clickable URL に悪影響を与えるので中止 # self.view.addGestureRecognizer(UITapGestureRecognizer.alloc.initWithTarget(self, action:'toggle_toolbar')) if self.on_modal == true UIBarButtonItem.stop.tap do |btn| btn.action = 'on_close' btn.target = self end self.navigationItem.leftBarButtonItem = UIBarButtonItem.alloc.initWithBarButtonSystemItem( UIBarButtonSystemItemStop, target:self, action:'on_close' ) end end def open_profile controller = TimelineViewController.new.tap do |c| c.user = bookmark.user c.content_type = :bookmark c.title = bookmark.user.name end self.navigationController.pushViewController(controller, animated:true) end def open_stars controller = StarsViewController.new.tap do |c| c.url = @bookmark.permalink @bookmarkView.starView.highlighted = true @bookmarkView.starView.backgroundColor = '#e5f0ff'.to_color end self.presentViewController( UINavigationController.alloc.initWithRootViewController(controller), animated:true, completion:nil ) end def open_webview controller = WebViewController.new controller.bookmark = @bookmark self.navigationController.pushViewController(controller, animated: true) end def open_bookmarks controller = BookmarksViewController.new.tap { |c| c.entry = @bookmark } self.presentViewController(HBFav2NavigationController.alloc.initWithRootViewController(controller), animated:true, completion:nil) end def viewWillAppear(animated) super ## 応急処置 UIApplication.sharedApplication.statusBarStyle = UIStatusBarStyleBlackOpaque UIApplication.sharedApplication.setStatusBarHidden(false, animated:animated) self.wantsFullScreenLayout = false self.navigationController.setToolbarHidden(false, animated:self.on_modal ? false : true) if self.bookmark.present? @bookmarkView.bookmark = self.bookmark elsif self.short_url and self.user_name @indicator.center = self.view.center @indicator.startAnimating ## FIXME: error handling GoogleAPI.sharedAPI.expand_url(self.short_url) do |response, long_url| if response.ok? and long_url BookmarkManager.sharedManager.get_bookmark(long_url, self.user_name) do |res, bm| @indicator.stopAnimating if bm self.bookmark = bm @bookmarkView.bookmark = bm else App.alert("ブックマークが見つかりません。時間をおいて再度試行してください") end end end end end @bookmarkView.tap do |v| v.starView.highlighted = false v.starView.backgroundColor = UIColor.whiteColor end end def toggle_toolbar if @toolbar_visible @toolbar_visible = false self.navigationController.setToolbarHidden(true, animated:true) else @toolbar_visible = true self.navigationController.setToolbarHidden(false, animated:true) end end def viewWillDisappear(animated) super self.navigationController.toolbar.translucent = false end def configure_toolbar spacer = UIBarButtonItem.fixedspace spacer.width = self.view.size.width - 110 self.toolbarItems = [ spacer, UIBarButtonItem.alloc.initWithBarButtonSystemItem(UIBarButtonSystemItemCompose, target:self, action: 'on_bookmark'), UIBarButtonItem.flexiblespace, # BookmarkBarButtonItem.alloc.initWithTarget(self, action:'on_bookmark'), UIBarButtonItem.alloc.initWithBarButtonSystemItem(UIBarButtonSystemItemAction, target:self, action:'on_action'), ] end def on_bookmark open_hatena_bookmark_view end def open_hatena_bookmark_view controller = HTBHatenaBookmarkViewController.alloc.init controller.URL = @bookmark.link.nsurl self.presentViewController(controller, animated:true, completion:nil) end def on_action controller = URLActivityViewController.alloc.initWithDefaultActivities([ @bookmark.title, @bookmark.link.nsurl ]) self.presentViewController(controller, animated:true, completion:nil) end def attributedLabel(label, didSelectLinkWithURL:url) if url.scheme == 'bookmark' name = url.host controller = TimelineViewController.new.tap do |c| user = User.new({ :name => name }) c.user = user c.content_type = :bookmark c.title = user.name end return self.navigationController.pushViewController(controller, animated:true) end if url.scheme == 'twitter' name = url.host link = "http://twitter.com/#{name}" else link = url.absoluteString end bookmark = Bookmark.new( { :title => '', :link => link, :count => nil } ) controller = WebViewController.new controller.bookmark = bookmark self.navigationController.pushViewController(controller, animated:true) end def on_close self.dismissModalViewControllerAnimated(true, completion:nil) end def dealloc NSLog("dealloc: " + self.class.name) super end end
class Admin::DonorsController < Admin::ApplicationController before_action :set_donor, only: [:show, :edit, :update, :destroy] # GET /donors # GET /donors.json def index # @donors = Donor.all @donors = Donor.page(params[:page]).per(10) end # GET /donors/1 # GET /donors/1.json def show end # GET /donors/new def new @donor = Donor.new end # GET /donors/1/edit def edit end # POST /donors # POST /donors.json def create @donor = Donor.new(donor_params) respond_to do |format| if @donor.save format.html { redirect_to @donor, notice: 'Donor was successfully created.' } format.json { render :show, status: :created, location: @donor } else format.html { render :new } format.json { render json: @donor.errors, status: :unprocessable_entity } end end end # PATCH/PUT /donors/1 # PATCH/PUT /donors/1.json def update respond_to do |format| if @donor.update(donor_params) format.html { redirect_to @donor, notice: 'Donor was successfully updated.' } format.json { render :show, status: :ok, location: @donor } else format.html { render :edit } format.json { render json: @donor.errors, status: :unprocessable_entity } end end end # DELETE /donors/1 # DELETE /donors/1.json def destroy @donor.destroy respond_to do |format| format.html { redirect_to donors_url, notice: 'Donor was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_donor @donor = Donor.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def donor_params params.require(:donor).permit(:name, :email, :phone, :address, :wordsto, :identify) end end update class Admin::DonorsController < Admin::ApplicationController before_action :set_donor, only: [:show, :edit, :update, :destroy] layout 'admin' # GET /donors # GET /donors.json def index # @donors = Donor.all @donors = Donor.page(params[:page]).per(10) end # GET /donors/1 # GET /donors/1.json def show end # GET /donors/new def new @donor = Donor.new end # GET /donors/1/edit def edit end # POST /donors # POST /donors.json def create @donor = Donor.new(donor_params) respond_to do |format| if @donor.save format.html { redirect_to @donor, notice: 'Donor was successfully created.' } format.json { render :show, status: :created, location: @donor } else format.html { render :new } format.json { render json: @donor.errors, status: :unprocessable_entity } end end end # PATCH/PUT /donors/1 # PATCH/PUT /donors/1.json def update respond_to do |format| if @donor.update(donor_params) format.html { redirect_to @donor, notice: 'Donor was successfully updated.' } format.json { render :show, status: :ok, location: @donor } else format.html { render :edit } format.json { render json: @donor.errors, status: :unprocessable_entity } end end end # DELETE /donors/1 # DELETE /donors/1.json def destroy @donor.destroy respond_to do |format| format.html { redirect_to donors_url, notice: 'Donor was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_donor @donor = Donor.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def donor_params params.require(:donor).permit(:name, :email, :phone, :address, :wordsto, :identify) end end
# frozen_string_literal: true module Admin class ImagesController < Admin::AdminController before_action :find_image, only: %i[show edit update destroy] def index; end def show; end def new; end def edit; end def create @image = Image.create(image_params) respond_to do |format| format.json { render_image_json(@image) } end end def update @image.update(image_params) respond_to do |format| format.json { render action: :show } end end def destroy; end protected def localized_attributes %i[caption alternative] end def image_params params.require(:image).permit( :name, :description, :file, :crop_start_x, :crop_start_y, :crop_height, :crop_width, :locale, :crop_gravity_x, :crop_gravity_y, localized_attributes.index_with do |_a| I18n.available_locales end ) end def find_image @image = Image.find(params[:id]) end def render_image_json(image) if image.valid? render json: Admin::ImageResource.new(image) else render json: { status: "error", error: image.errors.first.full_message } end end end end Fix update image response # frozen_string_literal: true module Admin class ImagesController < Admin::AdminController before_action :find_image, only: %i[show edit update destroy] def index; end def show; end def new; end def edit; end def create @image = Image.create(image_params) respond_to do |format| format.json { render_image_json(@image) } end end def update @image.update(image_params) respond_to do |format| format.json { render_image_json(@image) } end end def destroy; end protected def localized_attributes %i[caption alternative] end def image_params params.require(:image).permit( :name, :description, :file, :crop_start_x, :crop_start_y, :crop_height, :crop_width, :locale, :crop_gravity_x, :crop_gravity_y, localized_attributes.index_with do |_a| I18n.available_locales end ) end def find_image @image = Image.find(params[:id]) end def render_image_json(image) if image.valid? render json: Admin::ImageResource.new(image) else render json: { status: "error", error: image.errors.first.full_message } end end end end
module SettingCrazy class SettingsProxy attr_reader :template def initialize(model, template) @model = model @template = template @namespaces = model.class._setting_namespaces # TODO: It would probably be a good idea to memoize the NamespacedSettingsProxies end def []=(key, value) if @namespaces && namespace = @namespaces[key.to_sym] return NamespacedSettingsProxy.new(@model, namespace).bulk_assign(value) end sv = setting_record(key) if sv.blank? build_value(key, value) else sv.update_attribute(:value, value) end end def [](key) if @namespaces && namespace = @namespaces[key.to_sym] return NamespacedSettingsProxy.new(@model, namespace) end sv = setting_record(key) if sv.blank? parent_value(key) || template_default_value(key) || nil else sv.value end end def bulk_assign(attributes) attributes.each do |(k,v)| self[k] = v end end def delete(key) @model.setting_values.delete(setting_record(key)) end def method_missing(method_name, *args, &block) if method_name =~ /=$/ attribute = method_name[0...-1] self[attribute] = args.first else self[method_name] end end def parent_settings return nil unless @model.class._inheritor.present? @model.class._inheritor.parent_settings_for(@model) end def each(&block) setting_values.each(&block) end def map(&block) setting_values.map(&block) end def inspect @model.reload unless @model.new_record? self.to_hash.inspect end def to_hash setting_values.inject({}) do |hash, sv| hash[sv.key] = sv.value hash end.symbolize_keys end protected def template_default_value(key) template.present? ? template.defaults[key] : nil end def parent_value(key) parent_settings.present? ? parent_settings[key] : nil end def setting_record(attribute) # Check valid template attrs if template.present? && !template.valid_option?(attribute) raise ActiveRecord::UnknownAttributeError end setting_values.select{|sv| sv.key.to_sym == attribute.to_sym }.last # When updating an existing setting_value, the new value comes after the existing value in the array. end def build_value(key, value) @model.setting_values.build(:key => key, :value => value) end def setting_values @model.setting_values end end end Reject empty strings from arrays before saving module SettingCrazy class SettingsProxy attr_reader :template def initialize(model, template) @model = model @template = template @namespaces = model.class._setting_namespaces # TODO: It would probably be a good idea to memoize the NamespacedSettingsProxies end def []=(key, value) value.reject!(&:blank?) if value.respond_to?(:reject!) if @namespaces && namespace = @namespaces[key.to_sym] return NamespacedSettingsProxy.new(@model, namespace).bulk_assign(value) end sv = setting_record(key) if sv.blank? build_value(key, value) else sv.update_attribute(:value, value) end end def [](key) if @namespaces && namespace = @namespaces[key.to_sym] return NamespacedSettingsProxy.new(@model, namespace) end sv = setting_record(key) if sv.blank? parent_value(key) || template_default_value(key) || nil else sv.value end end def bulk_assign(attributes) attributes.each do |(k,v)| self[k] = v end end def delete(key) @model.setting_values.delete(setting_record(key)) end def method_missing(method_name, *args, &block) if method_name =~ /=$/ attribute = method_name[0...-1] self[attribute] = args.first else self[method_name] end end def parent_settings return nil unless @model.class._inheritor.present? @model.class._inheritor.parent_settings_for(@model) end def each(&block) setting_values.each(&block) end def map(&block) setting_values.map(&block) end def inspect @model.reload unless @model.new_record? self.to_hash.inspect end def to_hash setting_values.inject({}) do |hash, sv| hash[sv.key] = sv.value hash end.symbolize_keys end protected def template_default_value(key) template.present? ? template.defaults[key] : nil end def parent_value(key) parent_settings.present? ? parent_settings[key] : nil end def setting_record(attribute) # Check valid template attrs if template.present? && !template.valid_option?(attribute) raise ActiveRecord::UnknownAttributeError end setting_values.select{|sv| sv.key.to_sym == attribute.to_sym }.last # When updating an existing setting_value, the new value comes after the existing value in the array. end def build_value(key, value) @model.setting_values.build(:key => key, :value => value) end def setting_values @model.setting_values end end end
class Admin::MasterController < ApplicationController layout 'admin' include Typus::Authentication include Typus::Format include Typus::Locale include Typus::Reloader if Typus::Configuration.options[:ssl] include SslRequirement ssl_required :index, :new, :create, :edit, :show, :update, :destroy, :toggle, :position, :relate, :unrelate end filter_parameter_logging :password before_filter :reload_config_et_roles before_filter :require_login before_filter :set_locale before_filter :set_resource before_filter :find_item, :only => [ :show, :edit, :update, :destroy, :toggle, :position, :relate, :unrelate ] before_filter :check_ownership_of_item, :only => [ :edit, :update, :destroy, :toggle, :position, :relate, :unrelate ] before_filter :check_if_user_can_perform_action_on_user, :only => [ :edit, :update, :toggle, :destroy ] before_filter :check_if_user_can_perform_action_on_resource before_filter :set_order, :only => [ :index ] before_filter :set_fields, :only => [ :index, :new, :edit, :create, :update, :show ] ## # This is the main index of the model. With filters, conditions # and more. # # By default application can respond_to html, csv and xml, but you # can add your formats. # def index @conditions, @joins = @resource[:class].build_conditions(params) check_ownership_of_items if @resource[:class].typus_options_for(:only_user_items) respond_to do |format| format.html { generate_html } @resource[:class].typus_export_formats.each do |f| format.send(f) { send("generate_#{f}") } end end rescue Exception => error error_handler(error) end def new item_params = params.dup %w( controller action resource resource_id back_to selected ).each do |param| item_params.delete(param) end @item = @resource[:class].new(item_params.symbolize_keys) select_template :new end ## # Create new items. There's an special case when we create an # item from another item. In this case, after the item is # created we also create the relationship between these items. # def create @item = @resource[:class].new(params[:item]) if @item.attributes.include?(Typus.user_fk) @item.attributes = { Typus.user_fk => session[:typus_user_id] } end if @item.valid? create_with_back_to and return if params[:back_to] @item.save flash[:success] = _("{{model}} successfully created.", :model => @resource[:class].human_name) if @resource[:class].typus_options_for(:index_after_save) redirect_to :action => 'index' else redirect_to :action => @resource[:class].typus_options_for(:default_action_on_item), :id => @item.id end else select_template :new end end def edit item_params = params.dup %w( action controller model model_id back_to id resource resource_id ).each { |p| item_params.delete(p) } # We assign the params passed trough the url @item.attributes = item_params @previous, @next = @item.previous_and_next(item_params) select_template :edit end def show @previous, @next = @item.previous_and_next respond_to do |format| format.html { select_template :show } format.xml { render :xml => @item } end end def update if @item.update_attributes(params[:item]) flash[:success] = _("{{model}} successfully updated.", :model => @resource[:class].human_name) path = if @resource[:class].typus_options_for(:index_after_save) params[:back_to] ? "#{params[:back_to]}##{@resource[:self]}" : { :action => 'index' } else { :action => @resource[:class].typus_options_for(:default_action_on_item), :id => @item.id } end redirect_to path else @previous, @next = @item.previous_and_next select_template :edit end end def destroy @item.destroy flash[:success] = _("{{model}} successfully removed.", :model => @resource[:class].human_name) redirect_to :back rescue Exception => error error_handler(error, params.merge(:action => 'index', :id => nil)) end def toggle if @resource[:class].typus_options_for(:toggle) @item.toggle!(params[:field]) flash[:success] = _("{{model}} {{attribute}} changed.", :model => @resource[:class].human_name, :attribute => params[:field].humanize.downcase) else flash[:notice] = _("Toggle is disabled.") end redirect_to :back end ## # Change item position. This only works if acts_as_list is # installed. We can then move items: # # params[:go] = 'move_to_top' # # Available positions are move_to_top, move_higher, move_lower, # move_to_bottom. # def position @item.send(params[:go]) flash[:success] = _("Record moved {{to}}.", :to => params[:go].gsub(/move_/, '').humanize.downcase) redirect_to :back end ## # Relate a model object to another, this action is used only by the # has_and_belongs_to_many relationships. # def relate resource_class = params[:related][:model].constantize resource_tableized = params[:related][:model].tableize @item.send(resource_tableized) << resource_class.find(params[:related][:id]) flash[:success] = _("{{model_a}} related to {{model_b}}.", :model_a => resource_class.human_name, :model_b => @resource[:class].human_name) redirect_to :action => @resource[:class].typus_options_for(:default_action_on_item), :id => @item.id, :anchor => resource_tableized end ## # Remove relationship between models. # def unrelate resource_class = params[:resource].classify.constantize resource = resource_class.find(params[:resource_id]) case params[:association] when 'has_and_belongs_to_many' @item.send(resource_class.table_name).delete(resource) message = "{{model_a}} unrelated from {{model_b}}." when 'has_many', 'has_one' resource.destroy message = "{{model_a}} removed from {{model_b}}." end flash[:success] = _(message, :model_a => resource_class.human_name, :model_b => @resource[:class].human_name) redirect_to :controller => @resource[:self], :action => @resource[:class].typus_options_for(:default_action_on_item), :id => @item.id, :anchor => resource_class.table_name end private def set_resource resource = params[:controller].split('/').last @resource = { :self => resource, :class => resource.classify.constantize } rescue Exception => error error_handler(error) end ## # Find model when performing an edit, update, destroy, relate, # unrelate ... # def find_item @item = @resource[:class].find(params[:id]) end ## # If item is owned by another user, we only can perform a # show action on the item. Updated item is also blocked. # # before_filter :check_ownership_of_item, :only => [ :edit, :update, :destroy ] # def check_ownership_of_item # If current_user is a root user, by-pass. return if @current_user.is_root? # If the current model doesn't include a key which relates it with the # current_user, by-pass. return unless @item.respond_to?(Typus.user_fk) # If item is owned by the user ... unless @item.send(Typus.user_fk) == session[:typus_user_id] flash[:notice] = _("Record owned by another user.") redirect_to :action => 'show', :id => @item.id end end def check_ownership_of_items # If current_user is a root user, by-pass. return if @current_user.is_root? # If current user is not root and @resource has a foreign_key which # is related to the logged user (Typus.user_fk) we only show the user # related items. if @resource[:class].columns.map { |u| u.name }.include?(Typus.user_fk) condition = { Typus.user_fk => @current_user } @conditions = @resource[:class].merge_conditions(@conditions, condition) end end def set_fields @fields = case params[:action] when 'index' @resource[:class].typus_fields_for(:list) when 'new', 'edit', 'create', 'update' @resource[:class].typus_fields_for(:form) else @resource[:class].typus_fields_for(params[:action]) end end def set_order params[:sort_order] ||= 'desc' @order = params[:order_by] ? "#{@resource[:class].table_name}.#{params[:order_by]} #{params[:sort_order]}" : @resource[:class].typus_order_by end def select_template(template, resource = @resource[:self]) folder = (File.exist?("app/views/admin/#{resource}/#{template}.html.erb")) ? resource : 'resources' render "admin/#{folder}/#{template}" end ## # When <tt>params[:back_to]</tt> is defined this action is used. # # - <tt>has_and_belongs_to_many</tt> relationships. # - <tt>has_many</tt> relationships (polymorphic ones). # def create_with_back_to if params[:resource] && params[:resource_id] resource_class = params[:resource].classify.constantize resource_id = params[:resource_id] resource = resource_class.find(resource_id) association = @resource[:class].reflect_on_association(params[:resource].to_sym).macro rescue :polymorphic else association = :has_many end case association when :belongs_to @item.save when :has_and_belongs_to_many @item.save @item.send(params[:resource]) << resource when :has_many @item.save message = _("{{model}} successfully created.", :model => @resource[:class].human_name) path = "#{params[:back_to]}?#{params[:selected]}=#{@item.id}" when :polymorphic resource.send(@item.class.name.tableize).create(params[:item]) end flash[:success] = message || _("{{model_a}} successfully assigned to {{model_b}}.", :model_a => @item.class, :model_b => resource_class.name) redirect_to path || "#{params[:back_to]}##{@resource[:self]}" end def error_handler(error, path = admin_dashboard_path) raise error unless Rails.env.production? flash[:error] = "#{error.message} (#{@resource[:class]})" redirect_to path end end Fixed redirection path. class Admin::MasterController < ApplicationController layout 'admin' include Typus::Authentication include Typus::Format include Typus::Locale include Typus::Reloader if Typus::Configuration.options[:ssl] include SslRequirement ssl_required :index, :new, :create, :edit, :show, :update, :destroy, :toggle, :position, :relate, :unrelate end filter_parameter_logging :password before_filter :reload_config_et_roles before_filter :require_login before_filter :set_locale before_filter :set_resource before_filter :find_item, :only => [ :show, :edit, :update, :destroy, :toggle, :position, :relate, :unrelate ] before_filter :check_ownership_of_item, :only => [ :edit, :update, :destroy, :toggle, :position, :relate, :unrelate ] before_filter :check_if_user_can_perform_action_on_user, :only => [ :edit, :update, :toggle, :destroy ] before_filter :check_if_user_can_perform_action_on_resource before_filter :set_order, :only => [ :index ] before_filter :set_fields, :only => [ :index, :new, :edit, :create, :update, :show ] ## # This is the main index of the model. With filters, conditions # and more. # # By default application can respond_to html, csv and xml, but you # can add your formats. # def index @conditions, @joins = @resource[:class].build_conditions(params) check_ownership_of_items if @resource[:class].typus_options_for(:only_user_items) respond_to do |format| format.html { generate_html } @resource[:class].typus_export_formats.each do |f| format.send(f) { send("generate_#{f}") } end end rescue Exception => error error_handler(error) end def new item_params = params.dup %w( controller action resource resource_id back_to selected ).each do |param| item_params.delete(param) end @item = @resource[:class].new(item_params.symbolize_keys) select_template :new end ## # Create new items. There's an special case when we create an # item from another item. In this case, after the item is # created we also create the relationship between these items. # def create @item = @resource[:class].new(params[:item]) if @item.attributes.include?(Typus.user_fk) @item.attributes = { Typus.user_fk => session[:typus_user_id] } end if @item.valid? create_with_back_to and return if params[:back_to] @item.save flash[:success] = _("{{model}} successfully created.", :model => @resource[:class].human_name) if @resource[:class].typus_options_for(:index_after_save) redirect_to :action => 'index' else redirect_to :action => @resource[:class].typus_options_for(:default_action_on_item), :id => @item.id end else select_template :new end end def edit item_params = params.dup %w( action controller model model_id back_to id resource resource_id ).each { |p| item_params.delete(p) } # We assign the params passed trough the url @item.attributes = item_params @previous, @next = @item.previous_and_next(item_params) select_template :edit end def show @previous, @next = @item.previous_and_next respond_to do |format| format.html { select_template :show } format.xml { render :xml => @item } end end def update if @item.update_attributes(params[:item]) flash[:success] = _("{{model}} successfully updated.", :model => @resource[:class].human_name) path = if @resource[:class].typus_options_for(:index_after_save) params[:back_to] ? "#{params[:back_to]}##{@resource[:self]}" : { :action => 'index' } else { :action => @resource[:class].typus_options_for(:default_action_on_item), :id => @item.id } end redirect_to path else @previous, @next = @item.previous_and_next select_template :edit end end def destroy @item.destroy flash[:success] = _("{{model}} successfully removed.", :model => @resource[:class].human_name) redirect_to :back rescue Exception => error error_handler(error, params.merge(:action => 'index', :id => nil)) end def toggle if @resource[:class].typus_options_for(:toggle) @item.toggle!(params[:field]) flash[:success] = _("{{model}} {{attribute}} changed.", :model => @resource[:class].human_name, :attribute => params[:field].humanize.downcase) else flash[:notice] = _("Toggle is disabled.") end redirect_to :back end ## # Change item position. This only works if acts_as_list is # installed. We can then move items: # # params[:go] = 'move_to_top' # # Available positions are move_to_top, move_higher, move_lower, # move_to_bottom. # def position @item.send(params[:go]) flash[:success] = _("Record moved {{to}}.", :to => params[:go].gsub(/move_/, '').humanize.downcase) redirect_to :back end ## # Relate a model object to another, this action is used only by the # has_and_belongs_to_many relationships. # def relate resource_class = params[:related][:model].constantize resource_tableized = params[:related][:model].tableize @item.send(resource_tableized) << resource_class.find(params[:related][:id]) flash[:success] = _("{{model_a}} related to {{model_b}}.", :model_a => resource_class.human_name, :model_b => @resource[:class].human_name) redirect_to :action => @resource[:class].typus_options_for(:default_action_on_item), :id => @item.id, :anchor => resource_tableized end ## # Remove relationship between models. # def unrelate resource_class = params[:resource].classify.constantize resource = resource_class.find(params[:resource_id]) case params[:association] when 'has_and_belongs_to_many' @item.send(resource_class.table_name).delete(resource) message = "{{model_a}} unrelated from {{model_b}}." when 'has_many', 'has_one' resource.destroy message = "{{model_a}} removed from {{model_b}}." end flash[:success] = _(message, :model_a => resource_class.human_name, :model_b => @resource[:class].human_name) redirect_to :controller => @resource[:self], :action => @resource[:class].typus_options_for(:default_action_on_item), :id => @item.id, :anchor => resource_class.table_name end private def set_resource resource = params[:controller].split('/').last @resource = { :self => resource, :class => resource.classify.constantize } rescue Exception => error error_handler(error) end ## # Find model when performing an edit, update, destroy, relate, # unrelate ... # def find_item @item = @resource[:class].find(params[:id]) end ## # If item is owned by another user, we only can perform a # show action on the item. Updated item is also blocked. # # before_filter :check_ownership_of_item, :only => [ :edit, :update, :destroy ] # def check_ownership_of_item # If current_user is a root user, by-pass. return if @current_user.is_root? # If the current model doesn't include a key which relates it with the # current_user, by-pass. return unless @item.respond_to?(Typus.user_fk) # If item is owned by the user ... unless @item.send(Typus.user_fk) == session[:typus_user_id] flash[:notice] = _("Record owned by another user.") redirect_to :action => 'show', :id => @item.id end end def check_ownership_of_items # If current_user is a root user, by-pass. return if @current_user.is_root? # If current user is not root and @resource has a foreign_key which # is related to the logged user (Typus.user_fk) we only show the user # related items. if @resource[:class].columns.map { |u| u.name }.include?(Typus.user_fk) condition = { Typus.user_fk => @current_user } @conditions = @resource[:class].merge_conditions(@conditions, condition) end end def set_fields @fields = case params[:action] when 'index' @resource[:class].typus_fields_for(:list) when 'new', 'edit', 'create', 'update' @resource[:class].typus_fields_for(:form) else @resource[:class].typus_fields_for(params[:action]) end end def set_order params[:sort_order] ||= 'desc' @order = params[:order_by] ? "#{@resource[:class].table_name}.#{params[:order_by]} #{params[:sort_order]}" : @resource[:class].typus_order_by end def select_template(template, resource = @resource[:self]) folder = (File.exist?("app/views/admin/#{resource}/#{template}.html.erb")) ? resource : 'resources' render "admin/#{folder}/#{template}" end ## # When <tt>params[:back_to]</tt> is defined this action is used. # # - <tt>has_and_belongs_to_many</tt> relationships. # - <tt>has_many</tt> relationships (polymorphic ones). # def create_with_back_to if params[:resource] && params[:resource_id] resource_class = params[:resource].classify.constantize resource_id = params[:resource_id] resource = resource_class.find(resource_id) association = @resource[:class].reflect_on_association(params[:resource].to_sym).macro rescue :polymorphic else association = :has_many end case association when :belongs_to @item.save when :has_and_belongs_to_many @item.save @item.send(params[:resource]) << resource when :has_many @item.save message = _("{{model}} successfully created.", :model => @resource[:class].human_name) path = "#{params[:back_to]}?#{params[:selected]}=#{@item.id}" when :polymorphic resource.send(@item.class.name.tableize).create(params[:item]) path = "#{params[:back_to]}##{@resource[:self]}" end flash[:success] = message || _("{{model_a}} successfully assigned to {{model_b}}.", :model_a => @item.class, :model_b => resource_class.name) redirect_to path || params[:back_to] end def error_handler(error, path = admin_dashboard_path) raise error unless Rails.env.production? flash[:error] = "#{error.message} (#{@resource[:class]})" redirect_to path end end
require 'sfn' require 'sparkle_formation' require 'pathname' module Sfn module CommandModule # Template handling helper methods module Template # cloudformation directories that should be ignored TEMPLATE_IGNORE_DIRECTORIES = %w(components dynamics registry) module InstanceMethods # Load the template file # # @param args [Symbol] options (:allow_missing) # @return [Hash] loaded template def load_template_file(*args) unless(config[:template]) set_paths_and_discover_file! unless(File.exists?(config[:file].to_s)) unless(args.include?(:allow_missing)) ui.fatal "Invalid formation file path provided: #{config[:file]}" raise IOError.new "Failed to locate file: #{config[:file]}" end end end if(config[:template]) config[:template] elsif(config[:file]) if(config[:processing]) sf = SparkleFormation.compile(config[:file], :sparkle) if(sf.nested? && !sf.isolated_nests?) raise TypeError.new('Template does not contain isolated stack nesting! Sfn does not support mixed mixed resources within root stack!') end run_callbacks_for(:stack, :stack_name => arguments.first, :stack_sparkle => sf) if(sf.nested? && config[:apply_nesting]) if(config[:apply_nesting] == true) config[:apply_nesting] = :deep end case config[:apply_nesting].to_sym when :deep process_nested_stack_deep(sf) when :shallow process_nested_stack_shallow(sf) else raise ArgumentError.new "Unknown nesting style requested: #{config[:apply_nesting].inspect}!" end else sf.dump.merge('sfn_nested_stack' => !!sf.nested?) end else template = _from_json(File.read(config[:file])) run_callbacks_for(:stack, :stack_name => arguments.first, :stack_hash => template) template end else raise ArgumentError.new 'Failed to locate template for processing!' end end # Processes template using the original shallow workflow # # @param sf [SparkleFormation] stack # @return [Hash] dumped stack def process_nested_stack_shallow(sf) sf.apply_nesting(:shallow) do |stack_name, stack_definition, resource| run_callbacks_for(:stack, :stack_name => stack_name, :stack_hash => stack) run_callbacks_for(:stack, stack_name, stack_definition) bucket = provider.connection.api_for(:storage).buckets.get( config[:nesting_bucket] ) if(config[:print_only]) resource['Properties']['TemplateURL'] = "http://example.com/bucket/#{name_args.first}_#{stack_name}.json" else resource['Properties'].delete('Stack') unless(bucket) raise "Failed to locate configured bucket for stack template storage (#{bucket})!" end file = bucket.files.build file.name = "#{name_args.first}_#{stack_name}.json" file.content_type = 'text/json' file.body = MultiJson.dump(Sfn::Utils::StackParameterScrubber.scrub!(stack_definition)) file.save url = URI.parse(file.url) resource['Properties']['TemplateURL'] = "#{url.scheme}://#{url.host}#{url.path}" end end end # Processes template using new deep workflow # # @param sf [SparkleFormation] stack # @return [Hash] dumped stack def process_nested_stack_deep(sf) sf.apply_nesting(:deep) do |stack_name, stack, resource| run_callbacks_for(:stack, :stack_name => stack_name, :stack_sparkle => stack) stack_definition = stack.compile.dump! stack_resource = resource._dump bucket = provider.connection.api_for(:storage).buckets.get( config[:nesting_bucket] ) params = Hash[ stack_definition.fetch('Parameters', {}).map do |k,v| next if stack_resource['Properties'].fetch('Parameters', {}).keys.include?(k) [k,v] end.compact ] result = Smash.new('Parameters' => populate_parameters!('Parameters' => params).merge(stack_resource['Properties'].fetch('Parameters', {}))) if(config[:print_only]) result.merge!( 'TemplateURL' => "http://example.com/bucket/#{name_args.first}_#{stack_name}.json" ) else resource.properties.delete!(:stack) unless(bucket) raise "Failed to locate configured bucket for stack template storage (#{bucket})!" end file = bucket.files.build file.name = "#{name_args.first}_#{stack_name}.json" file.content_type = 'text/json' file.body = MultiJson.dump(Sfn::Utils::StackParameterScrubber.scrub!(stack_definition)) file.save url = URI.parse(file.url) result.merge!( 'TemplateURL' => "#{url.scheme}://#{url.host}#{url.path}" ) end result.each do |k,v| resource.properties.set!(k, v) end end end # Apply template translation # # @param template [Hash] # @return [Hash] def translate_template(template) if(klass_name = config[:translate]) klass = SparkleFormation::Translation.const_get(camel(klass_name)) args = { :parameters => config.fetch(:options, :parameters, Smash.new) } if(chunk_size = config[:translate_chunk_size]) args.merge!( :options => { :serialization_chunk_size => chunk_size } ) end translator = klass.new(template, args) translator.translate! template = translator.translated ui.info "#{ui.color('Translation applied:', :bold)} #{ui.color(klass_name, :yellow)}" end template end # Set SparkleFormation paths and locate tempate # # @return [TrueClass] def set_paths_and_discover_file! if(config[:base_directory]) SparkleFormation.sparkle_path = config[:base_directory] end if(!config[:file] && config[:file_path_prompt]) root = File.expand_path( config.fetch(:base_directory, File.join(Dir.pwd, 'cloudformation') ) ).split('/') bucket = root.pop root = root.join('/') directory = File.join(root, bucket) config[:file] = prompt_for_file(directory, :directories_name => 'Collections', :files_name => 'Templates', :ignore_directories => TEMPLATE_IGNORE_DIRECTORIES ) else unless(Pathname(config[:file].to_s).absolute?) base_dir = config[:base_directory].to_s file = config[:file].to_s pwd = Dir.pwd config[:file] = [ File.join(base_dir, file), File.join(pwd, file), File.join(pwd, 'cloudformation', file) ].detect do |file_path| File.file?(file_path) end end end true end end module ClassMethods end # Load methods into class and define options # # @param klass [Class] def self.included(klass) klass.class_eval do extend Sfn::CommandModule::Template::ClassMethods include Sfn::CommandModule::Template::InstanceMethods include Sfn::Utils::PathSelector end end end end end Update naming to be consistent for type require 'sfn' require 'sparkle_formation' require 'pathname' module Sfn module CommandModule # Template handling helper methods module Template # cloudformation directories that should be ignored TEMPLATE_IGNORE_DIRECTORIES = %w(components dynamics registry) module InstanceMethods # Load the template file # # @param args [Symbol] options (:allow_missing) # @return [Hash] loaded template def load_template_file(*args) unless(config[:template]) set_paths_and_discover_file! unless(File.exists?(config[:file].to_s)) unless(args.include?(:allow_missing)) ui.fatal "Invalid formation file path provided: #{config[:file]}" raise IOError.new "Failed to locate file: #{config[:file]}" end end end if(config[:template]) config[:template] elsif(config[:file]) if(config[:processing]) sf = SparkleFormation.compile(config[:file], :sparkle) if(sf.nested? && !sf.isolated_nests?) raise TypeError.new('Template does not contain isolated stack nesting! Sfn does not support mixed mixed resources within root stack!') end run_callbacks_for(:stack, :stack_name => arguments.first, :sparkle_stack => sf) if(sf.nested? && config[:apply_nesting]) if(config[:apply_nesting] == true) config[:apply_nesting] = :deep end case config[:apply_nesting].to_sym when :deep process_nested_stack_deep(sf) when :shallow process_nested_stack_shallow(sf) else raise ArgumentError.new "Unknown nesting style requested: #{config[:apply_nesting].inspect}!" end else sf.dump.merge('sfn_nested_stack' => !!sf.nested?) end else template = _from_json(File.read(config[:file])) run_callbacks_for(:stack, :stack_name => arguments.first, :hash_stack => template) template end else raise ArgumentError.new 'Failed to locate template for processing!' end end # Processes template using the original shallow workflow # # @param sf [SparkleFormation] stack # @return [Hash] dumped stack def process_nested_stack_shallow(sf) sf.apply_nesting(:shallow) do |stack_name, stack_definition, resource| run_callbacks_for(:stack, :stack_name => stack_name, :hash_stack => stack) run_callbacks_for(:stack, stack_name, stack_definition) bucket = provider.connection.api_for(:storage).buckets.get( config[:nesting_bucket] ) if(config[:print_only]) resource['Properties']['TemplateURL'] = "http://example.com/bucket/#{name_args.first}_#{stack_name}.json" else resource['Properties'].delete('Stack') unless(bucket) raise "Failed to locate configured bucket for stack template storage (#{bucket})!" end file = bucket.files.build file.name = "#{name_args.first}_#{stack_name}.json" file.content_type = 'text/json' file.body = MultiJson.dump(Sfn::Utils::StackParameterScrubber.scrub!(stack_definition)) file.save url = URI.parse(file.url) resource['Properties']['TemplateURL'] = "#{url.scheme}://#{url.host}#{url.path}" end end end # Processes template using new deep workflow # # @param sf [SparkleFormation] stack # @return [Hash] dumped stack def process_nested_stack_deep(sf) sf.apply_nesting(:deep) do |stack_name, stack, resource| run_callbacks_for(:stack, :stack_name => stack_name, :sparkle_stack => stack) stack_definition = stack.compile.dump! stack_resource = resource._dump bucket = provider.connection.api_for(:storage).buckets.get( config[:nesting_bucket] ) params = Hash[ stack_definition.fetch('Parameters', {}).map do |k,v| next if stack_resource['Properties'].fetch('Parameters', {}).keys.include?(k) [k,v] end.compact ] result = Smash.new('Parameters' => populate_parameters!('Parameters' => params).merge(stack_resource['Properties'].fetch('Parameters', {}))) if(config[:print_only]) result.merge!( 'TemplateURL' => "http://example.com/bucket/#{name_args.first}_#{stack_name}.json" ) else resource.properties.delete!(:stack) unless(bucket) raise "Failed to locate configured bucket for stack template storage (#{bucket})!" end file = bucket.files.build file.name = "#{name_args.first}_#{stack_name}.json" file.content_type = 'text/json' file.body = MultiJson.dump(Sfn::Utils::StackParameterScrubber.scrub!(stack_definition)) file.save url = URI.parse(file.url) result.merge!( 'TemplateURL' => "#{url.scheme}://#{url.host}#{url.path}" ) end result.each do |k,v| resource.properties.set!(k, v) end end end # Apply template translation # # @param template [Hash] # @return [Hash] def translate_template(template) if(klass_name = config[:translate]) klass = SparkleFormation::Translation.const_get(camel(klass_name)) args = { :parameters => config.fetch(:options, :parameters, Smash.new) } if(chunk_size = config[:translate_chunk_size]) args.merge!( :options => { :serialization_chunk_size => chunk_size } ) end translator = klass.new(template, args) translator.translate! template = translator.translated ui.info "#{ui.color('Translation applied:', :bold)} #{ui.color(klass_name, :yellow)}" end template end # Set SparkleFormation paths and locate tempate # # @return [TrueClass] def set_paths_and_discover_file! if(config[:base_directory]) SparkleFormation.sparkle_path = config[:base_directory] end if(!config[:file] && config[:file_path_prompt]) root = File.expand_path( config.fetch(:base_directory, File.join(Dir.pwd, 'cloudformation') ) ).split('/') bucket = root.pop root = root.join('/') directory = File.join(root, bucket) config[:file] = prompt_for_file(directory, :directories_name => 'Collections', :files_name => 'Templates', :ignore_directories => TEMPLATE_IGNORE_DIRECTORIES ) else unless(Pathname(config[:file].to_s).absolute?) base_dir = config[:base_directory].to_s file = config[:file].to_s pwd = Dir.pwd config[:file] = [ File.join(base_dir, file), File.join(pwd, file), File.join(pwd, 'cloudformation', file) ].detect do |file_path| File.file?(file_path) end end end true end end module ClassMethods end # Load methods into class and define options # # @param klass [Class] def self.included(klass) klass.class_eval do extend Sfn::CommandModule::Template::ClassMethods include Sfn::CommandModule::Template::InstanceMethods include Sfn::Utils::PathSelector end end end end end
require 'sfn' require 'sparkle_formation' require 'pathname' module Sfn module CommandModule # Template handling helper methods module Template # cloudformation directories that should be ignored TEMPLATE_IGNORE_DIRECTORIES = %w(components dynamics registry) module InstanceMethods # Load the template file # # @param args [Symbol] options (:allow_missing) # @return [Hash] loaded template def load_template_file(*args) unless(config[:template]) set_paths_and_discover_file! unless(File.exists?(config[:file].to_s)) unless(args.include?(:allow_missing)) ui.fatal "Invalid formation file path provided: #{config[:file]}" raise IOError.new "Failed to locate file: #{config[:file]}" end end end if(config[:template]) config[:template] elsif(config[:file]) if(config[:processing]) sf = SparkleFormation.compile(config[:file], :sparkle) if(sf.nested? && !sf.isolated_nests?) raise TypeError.new('Template does not contain isolated stack nesting! Sfn does not support mixed mixed resources within root stack!') end if(sf.nested? && config[:apply_nesting]) if(config[:apply_nesting] == true) config[:apply_nesting] = :deep end case config[:apply_nesting].to_sym when :shallow process_nested_stack_shallow(sf) when :deep process_nested_stack_deep(sf) else raise ArgumentError.new "Unknown nesting style requested: #{config[:apply_nesting].inspect}!" end else sf.dump.merge('sfn_nested_stack' => !!sf.nested?) end else _from_json(File.read(config[:file])) end else raise ArgumentError.new 'Failed to locate template for processing!' end end # Processes template using the original shallow workflow # # @param sf [SparkleFormation] stack # @return [Hash] dumped stack def process_nested_stack_shallow(sf) sf.apply_nesting(:shallow) do |stack_name, stack_definition| bucket = provider.connection.api_for(:storage).buckets.get( config[:nesting_bucket] ) if(config[:print_only]) "http://example.com/bucket/#{name_args.first}_#{stack_name}.json" else unless(bucket) raise "Failed to locate configured bucket for stack template storage (#{bucket})!" end file = bucket.files.build file.name = "#{name_args.first}_#{stack_name}.json" file.content_type = 'text/json' file.body = MultiJson.dump(Sfn::Utils::StackParameterScrubber.scrub!(stack_definition)) file.save url = URI.parse(file.url) "#{url.scheme}://#{url.host}#{url.path}" end end end # Processes template using the deep workflow # # @param sf [SparkleFormation] tack # @return [Hash] dumped stack def process_nested_stack_deep(sf) end def stack_processors(stack) config.fetch(: end # Apply template translation # # @param template [Hash] # @return [Hash] def translate_template(template) if(klass_name = config[:translate]) klass = SparkleFormation::Translation.const_get(camel(klass_name)) args = { :parameters => config.fetch(:options, :parameters, Smash.new) } if(chunk_size = config[:translate_chunk_size]) args.merge!( :options => { :serialization_chunk_size => chunk_size } ) end translator = klass.new(template, args) translator.translate! template = translator.translated ui.info "#{ui.color('Translation applied:', :bold)} #{ui.color(klass_name, :yellow)}" end template end # Set SparkleFormation paths and locate tempate # # @return [TrueClass] def set_paths_and_discover_file! if(config[:base_directory]) SparkleFormation.sparkle_path = config[:base_directory] end if(!config[:file] && config[:file_path_prompt]) root = File.expand_path( config.fetch(:base_directory, File.join(Dir.pwd, 'cloudformation') ) ).split('/') bucket = root.pop root = root.join('/') directory = File.join(root, bucket) config[:file] = prompt_for_file(directory, :directories_name => 'Collections', :files_name => 'Templates', :ignore_directories => TEMPLATE_IGNORE_DIRECTORIES ) else unless(Pathname(config[:file].to_s).absolute?) base_dir = config[:base_directory].to_s file = config[:file].to_s pwd = Dir.pwd config[:file] = [ File.join(base_dir, file), File.join(pwd, file), File.join(pwd, 'cloudformation', file) ].detect do |file_path| File.file?(file_path) end end end true end end module ClassMethods end # Load methods into class and define options # # @param klass [Class] def self.included(klass) klass.class_eval do extend Sfn::CommandModule::Template::ClassMethods include Sfn::CommandModule::Template::InstanceMethods include Sfn::Utils::PathSelector end end end end end Add support for deep nest processing require 'sfn' require 'sparkle_formation' require 'pathname' module Sfn module CommandModule # Template handling helper methods module Template # cloudformation directories that should be ignored TEMPLATE_IGNORE_DIRECTORIES = %w(components dynamics registry) module InstanceMethods # Load the template file # # @param args [Symbol] options (:allow_missing) # @return [Hash] loaded template def load_template_file(*args) unless(config[:template]) set_paths_and_discover_file! unless(File.exists?(config[:file].to_s)) unless(args.include?(:allow_missing)) ui.fatal "Invalid formation file path provided: #{config[:file]}" raise IOError.new "Failed to locate file: #{config[:file]}" end end end if(config[:template]) config[:template] elsif(config[:file]) if(config[:processing]) sf = SparkleFormation.compile(config[:file], :sparkle) if(sf.nested? && !sf.isolated_nests?) raise TypeError.new('Template does not contain isolated stack nesting! Sfn does not support mixed mixed resources within root stack!') end if(sf.nested? && config[:apply_nesting]) if(config[:apply_nesting] == true) config[:apply_nesting] = :deep end case config[:apply_nesting].to_sym when :deep process_nested_stack_deep(sf) when :shallow process_nested_stack_shallow(sf) else raise ArgumentError.new "Unknown nesting style requested: #{config[:apply_nesting].inspect}!" end else sf.dump.merge('sfn_nested_stack' => !!sf.nested?) end else _from_json(File.read(config[:file])) end else raise ArgumentError.new 'Failed to locate template for processing!' end end # Processes template using the original shallow workflow # # @param sf [SparkleFormation] stack # @return [Hash] dumped stack def process_nested_stack_shallow(sf) sf.apply_nesting(:shallow) do |stack_name, stack_definition| bucket = provider.connection.api_for(:storage).buckets.get( config[:nesting_bucket] ) if(config[:print_only]) "http://example.com/bucket/#{name_args.first}_#{stack_name}.json" else unless(bucket) raise "Failed to locate configured bucket for stack template storage (#{bucket})!" end file = bucket.files.build file.name = "#{name_args.first}_#{stack_name}.json" file.content_type = 'text/json' file.body = MultiJson.dump(Sfn::Utils::StackParameterScrubber.scrub!(stack_definition)) file.save url = URI.parse(file.url) "#{url.scheme}://#{url.host}#{url.path}" end end end # Processes template using new deep workflow # # @param sf [SparkleFormation] stack # @return [Hash] dumped stack def process_nested_stack_deep(sf) sf.apply_nesting(:deep) do |stack_name, stack_definition, stack_resource| bucket = provider.connection.api_for(:storage).buckets.get( config[:nesting_bucket] ) params = Hash[ stack_definition['Parameters'].map do |k,v| next if stack_resource['Properties'].fetch('Parameters', {}).keys.include?(k) [k,v] end.compact ] result = Smash.new('Parameters' => populate_parameters!('Parameters' => params).merge(stack_resource['Properties'].fetch('Parameters', {}))) if(config[:print_only]) result.merge( 'TemplateURL' => "http://example.com/bucket/#{name_args.first}_#{stack_name}.json" ) else unless(bucket) raise "Failed to locate configured bucket for stack template storage (#{bucket})!" end file = bucket.files.build file.name = "#{name_args.first}_#{stack_name}.json" file.content_type = 'text/json' file.body = MultiJson.dump(Sfn::Utils::StackParameterScrubber.scrub!(stack_definition)) file.save url = URI.parse(file.url) result.merge( 'TemplateURL' => "#{url.scheme}://#{url.host}#{url.path}" ) end end end # pre and post processors? def stack_processors(stack) config.fetch end # Apply template translation # # @param template [Hash] # @return [Hash] def translate_template(template) if(klass_name = config[:translate]) klass = SparkleFormation::Translation.const_get(camel(klass_name)) args = { :parameters => config.fetch(:options, :parameters, Smash.new) } if(chunk_size = config[:translate_chunk_size]) args.merge!( :options => { :serialization_chunk_size => chunk_size } ) end translator = klass.new(template, args) translator.translate! template = translator.translated ui.info "#{ui.color('Translation applied:', :bold)} #{ui.color(klass_name, :yellow)}" end template end # Set SparkleFormation paths and locate tempate # # @return [TrueClass] def set_paths_and_discover_file! if(config[:base_directory]) SparkleFormation.sparkle_path = config[:base_directory] end if(!config[:file] && config[:file_path_prompt]) root = File.expand_path( config.fetch(:base_directory, File.join(Dir.pwd, 'cloudformation') ) ).split('/') bucket = root.pop root = root.join('/') directory = File.join(root, bucket) config[:file] = prompt_for_file(directory, :directories_name => 'Collections', :files_name => 'Templates', :ignore_directories => TEMPLATE_IGNORE_DIRECTORIES ) else unless(Pathname(config[:file].to_s).absolute?) base_dir = config[:base_directory].to_s file = config[:file].to_s pwd = Dir.pwd config[:file] = [ File.join(base_dir, file), File.join(pwd, file), File.join(pwd, 'cloudformation', file) ].detect do |file_path| File.file?(file_path) end end end true end end module ClassMethods end # Load methods into class and define options # # @param klass [Class] def self.included(klass) klass.class_eval do extend Sfn::CommandModule::Template::ClassMethods include Sfn::CommandModule::Template::InstanceMethods include Sfn::Utils::PathSelector end end end end end
module SimpleFlashHelper VERSION = "0.3.0" end version bump module SimpleFlashHelper VERSION = "0.4.0" end
require 'rake' require 'rake/tasklib' require 'rake/sprocketstask' module Sinatra module AssetPipeline class Task < Rake::TaskLib def initialize(app) namespace :assets do desc "Precompile assets" task :precompile do environment = app.sprockets manifest = Sprockets::Manifest.new(environment.index, app.assets_path) manifest.compile(app.assets_precompile) end desc "Clean assets" task :clean do FileUtils.rm_rf(app.assets_path) end end end def self.define!(app) self.new app end end end end Refactor app to use a more descriptive name require 'rake' require 'rake/tasklib' require 'rake/sprocketstask' module Sinatra module AssetPipeline class Task < Rake::TaskLib def initialize(app_klass) namespace :assets do desc "Precompile assets" task :precompile do environment = app_klass.sprockets manifest = Sprockets::Manifest.new(environment.index, app_klass.assets_path) manifest.compile(app_klass.assets_precompile) end desc "Clean assets" task :clean do FileUtils.rm_rf(app_klass.assets_path) end end end def self.define!(app_klass) self.new app_klass end end end end
require 'dl/import' require 'skype/communication/protocol' class Skype module Communication # Utilises the Windows API to send and receive Window Messages to/from Skype. # # This protocol is only available on Windows and Cygwin. class Windows include Skype::Communication::Protocol def initialize # Get the message id's for the Skype Control messages @api_discover_message_id = Win32::RegisterWindowMessage('SkypeControlAPIDiscover') @api_attach_message_id = Win32::RegisterWindowMessage('SkypeControlAPIAttach') puts "#{@api_discover_message_id} #{@api_attach_message_id}" end module Win32 extend DL::Importer dlload 'user32' typealias('HWND', 'void *') typealias('LPCTSTR', 'unsigned char *') typealias('UINT', 'unsigned int') extern 'UINT RegisterWindowMessage(LPCTSTR)' end end end end Basic attempt at Win32 via DL I like this approach better in general, but it's still not working. require 'dl/import' require 'skype/communication/protocol' class Skype module Communication # Utilises the Windows API to send and receive Window Messages to/from Skype. # # This protocol is only available on Windows and Cygwin. class Windows include Skype::Communication::Protocol def initialize # Get the message id's for the Skype Control messages @api_discover_message_id = Win32::RegisterWindowMessage('SkypeControlAPIDiscover') @api_attach_message_id = Win32::RegisterWindowMessage('SkypeControlAPIAttach') @window = Win32::CreateWindowEx(0, DL::NULL, DL::NULL, Win32::WS_OVERLAPPEDWINDOW, 0, 0, 200, 200, 0, DL::NULL, DL::NULL) puts "#{@window}" end module Win32 extend DL::Importer dlload 'user32' # @see http://msdn.microsoft.com/en-us/library/windows/desktop/aa383751.aspx typealias('HWND', 'int') typealias('HANDLE', 'int') # Handles are actually void*, but don't point to anything. The pointer is semantic. typealias('HMENU', 'HANDLE') typealias('HINSTANCE', 'HANDLE') typealias('LPVOID', 'void *') typealias('DWORD', 'unsigned long') typealias('LPCTSTR', 'unsigned char *') typealias('UINT', 'unsigned int') # Window handle to broadcast to all windows HWND_BROADCAST = 0xffff HWND_MESSAGE = -3 # CreateWindow Use Default Value CW_USEDEFAULT = 0x80000000 # Window Style constants. This is only a subset. # @see http://msdn.microsoft.com/en-us/library/windows/desktop/ms632600.aspx WS_BORDER = 0x00800000 WS_CAPTION = 0x00C00000 WS_DISABLED = 0x08000000 WS_OVERLAPPED = 0x00000000 WS_POPUP = 0x80000000 WS_SIZEBOX = 0x00040000 WS_SYSMENU = 0x00080000 WS_THICKFRAME = 0x00040000 WS_MAXIMIZEBOX = 0x00010000 WS_MINIMIZEBOX = 0x00020000 WS_OVERLAPPEDWINDOW = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX WS_POPUPWINDOW = WS_POPUP | WS_BORDER | WS_SYSMENU extern 'UINT RegisterWindowMessage(LPCTSTR)' extern 'HWND CreateWindowEx(DWORD, LPCTSTR, LPCTSTR, DWORD, int, int, int, int, HWND, HMENU, HINSTANCE)' end end end end
class SlimKeyfy::Console::Translate attr_reader :original_file_path, :bak_path def initialize(options={}) @extension = options[:ext] @transformer = transformer @original_file_path = options[:input] @no_backup = options.fetch(:no_backup, false) @bak_path = SlimKeyfy::Slimutils::MFileUtils.backup(@original_file_path) @content = self.class.join_multiline( SlimKeyfy::Slimutils::FileReader.read(@bak_path).split("\n") ) @file_path = SlimKeyfy::Slimutils::MFileUtils.create_new_file(@original_file_path) @key_base = generate_key_base @yaml_processor = create_yaml_processor(options) @new_content = [] @changes = false end def transformer if @extension == "slim" SlimKeyfy::Transformer::SlimTransformer elsif @extension == "rb" SlimKeyfy::Transformer::ControllerTransformer else puts "Unknown extension type!" exit end end def create_yaml_processor(options) SlimKeyfy::Slimutils::YamlProcessor.new(options[:locale], @key_base, options.fetch(:yaml_output, nil)) end def generate_key_base SlimKeyfy::Slimutils::BaseKeyGenerator.generate_key_base_from_path(@original_file_path, @extension) end def stream_mode @content.each_with_index do |old_line, idx| word = SlimKeyfy::Transformer::Word.new(old_line, @key_base, @extension) new_line, translations = @transformer.new(word, @yaml_processor).transform if translations_are_invalid?(translations) @yaml_processor.delete_translations(translations) update_with(idx, old_line) else process_new_line(idx, old_line, new_line, translations) @changes = true end end SlimKeyfy::Slimutils::FileWriter.write(@file_path, @new_content.join("\n")) finalize! end def process_new_line(idx, old_line, new_line, translations) SlimKeyfy::Console::Printer.difference(old_line, new_line, translations) case SlimKeyfy::Console::IOAction.choose("Changes wanted?") when "y" then update_with(idx, new_line) when "n" then update_with(idx, old_line) @yaml_processor.delete_translations(translations) when "x" then update_with(idx, SlimKeyfy::Console::Printer.tag(old_line, translations, comment_tag)) @yaml_processor.delete_translations(translations) when "a" then SlimKeyfy::Slimutils::MFileUtils.restore(@bak_path, @original_file_path) puts "Aborted!" exit end end def finalize! if @changes if SlimKeyfy::Console::IOAction.yes_or_no?("Do you like to review your changes?") SlimKeyfy::Console::Printer.unix_diff(@bak_path, @original_file_path) end if SlimKeyfy::Console::IOAction.yes_or_no?("Do you like to save your changes?") @yaml_processor.store! puts "Saved! at #{@original_file_path}" SlimKeyfy::Slimutils::MFileUtils.rm(@bak_path) if @no_backup else SlimKeyfy::Slimutils::MFileUtils.restore(@bak_path, @original_file_path) puts "Restored!" end else SlimKeyfy::Slimutils::MFileUtils.restore(@bak_path, @original_file_path) puts "Nothing was changed!" end end def update_with(idx, line) @new_content[idx] = line end def translations_are_invalid?(translations) translations.nil? or translations.empty? end def comment_tag @transformer.slim? ? "//" : "#" end def self.join_multiline( strings_array ) result = [] joining_str = '' indent_length = 0 long_str_start = /^[ ]+\|/ long_str_indent = /^[ ]+/ long_str_indent_with_vertical_bar = /^[ ]+\|/ strings_array.each do |str| if joining_str.empty? if str[long_str_start] joining_str = str indent_length = str[long_str_start].length else result << str end #multiline string continues with spaces elsif ( str[long_str_indent] && str[long_str_indent].length.to_i >= indent_length ) joining_str << str.gsub( long_str_indent, ' ' ) #muliline string continues with spaces and vertical bar with same indentation elsif str[long_str_indent_with_vertical_bar] && str[long_str_indent_with_vertical_bar].length.to_i == indent_length joining_str << str.gsub( long_str_indent_with_vertical_bar, ' ' ) #multiline string ends else result << joining_str joining_str = '' indent_length = 0 redo end end result end end redo doesn't needed since the next line in well formed slim can only be nex tag and not start of multiline string class SlimKeyfy::Console::Translate attr_reader :original_file_path, :bak_path def initialize(options={}) @extension = options[:ext] @transformer = transformer @original_file_path = options[:input] @no_backup = options.fetch(:no_backup, false) @bak_path = SlimKeyfy::Slimutils::MFileUtils.backup(@original_file_path) @content = self.class.join_multiline( SlimKeyfy::Slimutils::FileReader.read(@bak_path).split("\n") ) @file_path = SlimKeyfy::Slimutils::MFileUtils.create_new_file(@original_file_path) @key_base = generate_key_base @yaml_processor = create_yaml_processor(options) @new_content = [] @changes = false end def transformer if @extension == "slim" SlimKeyfy::Transformer::SlimTransformer elsif @extension == "rb" SlimKeyfy::Transformer::ControllerTransformer else puts "Unknown extension type!" exit end end def create_yaml_processor(options) SlimKeyfy::Slimutils::YamlProcessor.new(options[:locale], @key_base, options.fetch(:yaml_output, nil)) end def generate_key_base SlimKeyfy::Slimutils::BaseKeyGenerator.generate_key_base_from_path(@original_file_path, @extension) end def stream_mode @content.each_with_index do |old_line, idx| word = SlimKeyfy::Transformer::Word.new(old_line, @key_base, @extension) new_line, translations = @transformer.new(word, @yaml_processor).transform if translations_are_invalid?(translations) @yaml_processor.delete_translations(translations) update_with(idx, old_line) else process_new_line(idx, old_line, new_line, translations) @changes = true end end SlimKeyfy::Slimutils::FileWriter.write(@file_path, @new_content.join("\n")) finalize! end def process_new_line(idx, old_line, new_line, translations) SlimKeyfy::Console::Printer.difference(old_line, new_line, translations) case SlimKeyfy::Console::IOAction.choose("Changes wanted?") when "y" then update_with(idx, new_line) when "n" then update_with(idx, old_line) @yaml_processor.delete_translations(translations) when "x" then update_with(idx, SlimKeyfy::Console::Printer.tag(old_line, translations, comment_tag)) @yaml_processor.delete_translations(translations) when "a" then SlimKeyfy::Slimutils::MFileUtils.restore(@bak_path, @original_file_path) puts "Aborted!" exit end end def finalize! if @changes if SlimKeyfy::Console::IOAction.yes_or_no?("Do you like to review your changes?") SlimKeyfy::Console::Printer.unix_diff(@bak_path, @original_file_path) end if SlimKeyfy::Console::IOAction.yes_or_no?("Do you like to save your changes?") @yaml_processor.store! puts "Saved! at #{@original_file_path}" SlimKeyfy::Slimutils::MFileUtils.rm(@bak_path) if @no_backup else SlimKeyfy::Slimutils::MFileUtils.restore(@bak_path, @original_file_path) puts "Restored!" end else SlimKeyfy::Slimutils::MFileUtils.restore(@bak_path, @original_file_path) puts "Nothing was changed!" end end def update_with(idx, line) @new_content[idx] = line end def translations_are_invalid?(translations) translations.nil? or translations.empty? end def comment_tag @transformer.slim? ? "//" : "#" end def self.join_multiline( strings_array ) result = [] joining_str = '' indent_length = 0 long_str_start = /^[ ]+\|/ long_str_indent = /^[ ]+/ long_str_indent_with_vertical_bar = /^[ ]+\|/ strings_array.each do |str| if joining_str.empty? if str[long_str_start] joining_str = str indent_length = str[long_str_start].length else result << str end #multiline string continues with spaces elsif ( str[long_str_indent] && str[long_str_indent].length.to_i >= indent_length ) joining_str << str.gsub( long_str_indent, ' ' ) #muliline string continues with spaces and vertical bar with same indentation elsif str[long_str_indent_with_vertical_bar] && str[long_str_indent_with_vertical_bar].length.to_i == indent_length joining_str << str.gsub( long_str_indent_with_vertical_bar, ' ' ) #multiline string ends else result << joining_str joining_str = '' indent_length = 0 end end result end end
class Admin::ThemesController < Admin::BaseController @@theme_export_path = RAILS_PATH + 'tmp/export' cattr_accessor :theme_export_path before_filter :find_theme, :only => [:preview_for, :export, :change_to, :show, :destroy] def preview_for send_file((@theme.preview.exist? ? @theme.preview : RAILS_PATH + 'public/images/mephisto/preview.png').to_s, :type => 'image/png', :disposition => 'inline') end def export theme_site_path = temp_theme_path_for(params[:id]) theme_zip_path = theme_site_path + "#{params[:id]}.zip" theme_zip_path.unlink if theme_zip_path.exist? @theme.export_as_zip params[:id], :to => theme_site_path theme_zip_path.exist? ? send_file(theme_zip_path.to_s, :stream => false) : raise("Error sending #{theme_zip_path.to_s} file") ensure theme_site_path.rmtree end def change_to site.change_theme_to @theme flash[:notice] = "Your theme has now been changed to '#{params[:id]}'" sweep_cache redirect_to :controller => 'design', :action => 'index' end def rollback site.rollback flash[:notice] = "Your theme has been rolled back" sweep_cache redirect_to :controller => 'design', :action => 'index' end def import return unless request.post? unless params[:theme] && params[:theme].size > 0 && params[:theme].content_type.strip == 'application/zip' flash.now[:error] = "Invalid theme upload." return end filename = params[:theme].original_filename filename.gsub!(/(^.*(\\|\/))|(\.zip$)/, '') filename.gsub!(/[^\w\.\-]/, '_') begin theme_site_path = temp_theme_path_for(filename) zip_file = theme_site_path + "temp.zip" File.open(zip_file, 'wb') { |f| f << params[:theme].read } site.import_theme zip_file, filename flash[:notice] = "The '#{filename}' theme has been imported." redirect_to :action => 'index' ensure theme_site_path.rmtree end end def destroy if @theme.current? flash[:error] = "Cannot delete the current theme" else @index = site.themes.index(@theme) @theme.path.rmtree flash[:notice] = "The '#{params[:id]}' theme was deleted." end respond_to do |format| format.html { redirect_to :action => 'index' } format.js end end protected def find_theme show_404 unless @theme = params[:id] == 'current' ? site.theme : site.themes[params[:id]] end def temp_theme_path_for(prefix) returning theme_export_path + "site-#{site.id}/#{prefix}#{Time.now.utc.to_i.to_s.split('').sort_by { rand }}" do |path| FileUtils.mkdir_p path unless path.exist? end end def sweep_cache site.expire_cached_pages self, "Expired all referenced pages" end alias authorized? admin? end add more compatible zip content types for themes git-svn-id: 4158f9403e16ea83fe8a6e07a45f1f3b56a747ab@2278 567b1171-46fb-0310-a4c9-b4bef9110e78 class Admin::ThemesController < Admin::BaseController @@theme_export_path = RAILS_PATH + 'tmp/export' @@theme_content_types = %w(application/zip multipart/x-zip application/x-zip-compressed) cattr_accessor :theme_export_path, :theme_content_types before_filter :find_theme, :only => [:preview_for, :export, :change_to, :show, :destroy] def preview_for send_file((@theme.preview.exist? ? @theme.preview : RAILS_PATH + 'public/images/mephisto/preview.png').to_s, :type => 'image/png', :disposition => 'inline') end def export theme_site_path = temp_theme_path_for(params[:id]) theme_zip_path = theme_site_path + "#{params[:id]}.zip" theme_zip_path.unlink if theme_zip_path.exist? @theme.export_as_zip params[:id], :to => theme_site_path theme_zip_path.exist? ? send_file(theme_zip_path.to_s, :stream => false) : raise("Error sending #{theme_zip_path.to_s} file") ensure theme_site_path.rmtree end def change_to site.change_theme_to @theme flash[:notice] = "Your theme has now been changed to '#{params[:id]}'" sweep_cache redirect_to :controller => 'design', :action => 'index' end def rollback site.rollback flash[:notice] = "Your theme has been rolled back" sweep_cache redirect_to :controller => 'design', :action => 'index' end def import return unless request.post? unless params[:theme] && params[:theme].size > 0 && theme_content_types.include?(params[:theme].content_type.strip) flash.now[:error] = "Invalid theme upload." return end filename = params[:theme].original_filename filename.gsub!(/(^.*(\\|\/))|(\.zip$)/, '') filename.gsub!(/[^\w\.\-]/, '_') begin theme_site_path = temp_theme_path_for(filename) zip_file = theme_site_path + "temp.zip" File.open(zip_file, 'wb') { |f| f << params[:theme].read } site.import_theme zip_file, filename flash[:notice] = "The '#{filename}' theme has been imported." redirect_to :action => 'index' ensure theme_site_path.rmtree end end def destroy if @theme.current? flash[:error] = "Cannot delete the current theme" else @index = site.themes.index(@theme) @theme.path.rmtree flash[:notice] = "The '#{params[:id]}' theme was deleted." end respond_to do |format| format.html { redirect_to :action => 'index' } format.js end end protected def find_theme show_404 unless @theme = params[:id] == 'current' ? site.theme : site.themes[params[:id]] end def temp_theme_path_for(prefix) returning theme_export_path + "site-#{site.id}/#{prefix}#{Time.now.utc.to_i.to_s.split('').sort_by { rand }}" do |path| FileUtils.mkdir_p path unless path.exist? end end def sweep_cache site.expire_cached_pages self, "Expired all referenced pages" end alias authorized? admin? end
module Snapshot class DependencyChecker def self.check_dependencies self.check_xcode_select self.check_xctool self.check_for_automation_subfolder self.check_simctl end def self.check_xcode_select unless `xcode-select -v`.include?"xcode-select version " Helper.log.fatal '#############################################################' Helper.log.fatal "# You have to install the Xcode commdand line tools to use snapshot" Helper.log.fatal "# Install the latest version of Xcode from the AppStore" Helper.log.fatal "# Run xcode-select --install to install the developer tools" Helper.log.fatal '#############################################################' raise "Run 'xcode-select --install' and start snapshot again" end end def self.check_simulators Helper.log.debug "Found #{Simulators.available_devices.count} simulators." if $verbose if Simulators.available_devices.count < 1 Helper.log.fatal '#############################################################' Helper.log.fatal "# You have to add new simulators using Xcode" Helper.log.fatal "# You can let snapshot create new simulators: 'snapshot reset_simulators'" Helper.log.fatal "# Manually: Xcode => Window => Devices" Helper.log.fatal "# Please run `instruments -s` to verify your xcode path" Helper.log.fatal '#############################################################' raise "Create the new simulators and run this script again" end end def self.xctool_installed? return `which xctool`.length > 1 end def self.check_xctool if not self.xctool_installed? Helper.log.info '#############################################################' Helper.log.info "# xctool is recommended to build the apps" Helper.log.info "# Install it using 'brew install xctool'" Helper.log.info "# Falling back to xcode build instead " Helper.log.info '#############################################################' end end def self.check_for_automation_subfolder if File.directory?"./Automation" or File.exists?"./Automation" raise "Seems like you have an 'Automation' folder in the current directory. You need to delete/rename it!".red end end def self.check_simctl unless `xcrun simctl`.include?"openurl" raise "Could not find `xcrun simctl`. Make sure you have the latest version of Xcode and Mac OS installed.".red end end end end Fixed spelling module Snapshot class DependencyChecker def self.check_dependencies self.check_xcode_select self.check_xctool self.check_for_automation_subfolder self.check_simctl end def self.check_xcode_select unless `xcode-select -v`.include?"xcode-select version " Helper.log.fatal '#############################################################' Helper.log.fatal "# You have to install the Xcode commdand line tools to use snapshot" Helper.log.fatal "# Install the latest version of Xcode from the AppStore" Helper.log.fatal "# Run xcode-select --install to install the developer tools" Helper.log.fatal '#############################################################' raise "Run 'xcode-select --install' and start snapshot again" end end def self.check_simulators Helper.log.debug "Found #{Simulators.available_devices.count} simulators." if $verbose if Simulators.available_devices.count < 1 Helper.log.fatal '#############################################################' Helper.log.fatal "# You have to add new simulators using Xcode" Helper.log.fatal "# You can let snapshot create new simulators: 'snapshot reset_simulators'" Helper.log.fatal "# Manually: Xcode => Window => Devices" Helper.log.fatal "# Please run `instruments -s` to verify your xcode path" Helper.log.fatal '#############################################################' raise "Create the new simulators and run this script again" end end def self.xctool_installed? return `which xctool`.length > 1 end def self.check_xctool if not self.xctool_installed? Helper.log.info '#############################################################' Helper.log.info "# xctool is recommended to build the apps" Helper.log.info "# Install it using 'brew install xctool'" Helper.log.info "# Falling back to xcodebuild instead " Helper.log.info '#############################################################' end end def self.check_for_automation_subfolder if File.directory?"./Automation" or File.exists?"./Automation" raise "Seems like you have an 'Automation' folder in the current directory. You need to delete/rename it!".red end end def self.check_simctl unless `xcrun simctl`.include?"openurl" raise "Could not find `xcrun simctl`. Make sure you have the latest version of Xcode and Mac OS installed.".red end end end end
class RegistrationsController < ApplicationController respond_to :html def new @event = Event.find params.require(:event_id) registration = Registration.new end def create @event = Event.find params.require(:event_id) @registration = @event.registrations.create params.require(:registration).permit(:email, :name) params.require(:registration).require(:checkboxes).each do |access_level, periods| periods.each do |period, checked| if checked = "on" then access = @registration.accesses.build access_level_id: access_level, period_id: period access.save end end end respond_with @registration end end show event after registration class RegistrationsController < ApplicationController respond_to :html def new @event = Event.find params.require(:event_id) registration = Registration.new end def create @event = Event.find params.require(:event_id) @registration = @event.registrations.create params.require(:registration).permit(:email, :name) params.require(:registration).require(:checkboxes).each do |access_level, periods| periods.each do |period, checked| if checked = "on" then access = @registration.accesses.build access_level_id: access_level, period_id: period access.save end end end respond_with @event end end
require "spec_helper" module RubyEventStore module RSpec ::RSpec.describe Publish do let(:matchers) { Object.new.tap { |o| o.extend(Matchers) } } let(:event_store) do RubyEventStore::Client.new( repository: RubyEventStore::InMemoryRepository.new, mapper: RubyEventStore::Mappers::PipelineMapper.new( RubyEventStore::Mappers::Pipeline.new(to_domain_event: Transformations::IdentityMap.new) ) ) end def matcher(*expected) Publish.new(*expected, failure_message_formatter: RSpec.default_formatter.publish) end specify do expect { expect { true }.to matcher }.to raise_error("You have to set the event store instance with `in`, e.g. `expect { ... }.to publish(an_event(MyEvent)).in(event_store)`") end specify do expect { true }.not_to matcher.in(event_store) end specify do expect { event_store.publish(FooEvent.new) }.to matcher.in(event_store) end specify do expect { event_store.publish(FooEvent.new, stream_name: 'Foo$1') }.to matcher.in(event_store).in_stream('Foo$1') end specify do expect { event_store.publish(FooEvent.new, stream_name: 'Foo$1') }.not_to matcher.in(event_store).in_stream('Bar$1') end specify do expect { event_store.publish(FooEvent.new) }.not_to matcher(matchers.an_event(BarEvent)).in(event_store) end specify do expect { event_store.publish(FooEvent.new) }.to matcher(matchers.an_event(FooEvent)).in(event_store) end specify do expect { event_store.publish(FooEvent.new, stream_name: "Foo$1") }.to matcher(matchers.an_event(FooEvent)).in(event_store).in_stream("Foo$1") end specify do expect { event_store.publish(FooEvent.new) }.not_to matcher(matchers.an_event(FooEvent)).in(event_store).in_stream("Foo$1") end specify do event_store.publish(FooEvent.new) event_store.publish(FooEvent.new) event_store.publish(FooEvent.new) expect { event_store.publish(BarEvent.new) }.to matcher(matchers.an_event(BarEvent)).in(event_store) expect { event_store.publish(BarEvent.new) }.not_to matcher(matchers.an_event(FooEvent)).in(event_store) end specify do foo_event = FooEvent.new bar_event = BarEvent.new expect { event_store.publish(foo_event, stream_name: "Foo$1") event_store.publish(bar_event, stream_name: "Bar$1") }.to matcher(matchers.an_event(FooEvent), matchers.an_event(BarEvent)).in(event_store) end specify do foo_event = FooEvent.new bar_event = BarEvent.new event_store.publish(foo_event) expect { event_store.publish(bar_event) }.not_to matcher(matchers.an_event(FooEvent)).in(event_store) end specify do expect { true }.not_to matcher.in(event_store) end specify do matcher_ = matcher.in(event_store) matcher_.matches?(Proc.new { }) expect(matcher_.failure_message_when_negated.to_s).to eq(<<~EOS.strip) expected block not to have published any events EOS end specify do matcher_ = matcher.in(event_store) matcher_.matches?(Proc.new { }) expect(matcher_.failure_message.to_s).to eq(<<~EOS.strip) expected block to have published any events EOS end specify do matcher_ = matcher(actual = matchers.an_event(FooEvent)).in(event_store) matcher_.matches?(Proc.new { }) expect(matcher_.failure_message.to_s).to eq(<<~EOS) expected block to have published: #{[actual].inspect} but published: [] EOS end specify do matcher_ = matcher(actual = matchers.an_event(FooEvent)).in_stream('foo').in(event_store) matcher_.matches?(Proc.new { }) expect(matcher_.failure_message.to_s).to eq(<<~EOS) expected block to have published: #{[actual].inspect} in stream foo but published: [] EOS end specify do foo_event = FooEvent.new matcher_ = matcher(actual = matchers.an_event(FooEvent)).in(event_store) matcher_.matches?(Proc.new { event_store.publish(foo_event) }) expect(matcher_.failure_message_when_negated.to_s).to eq(<<~EOS) expected block not to have published: #{[actual].inspect} but published: #{[foo_event].inspect} EOS end specify do foo_event = FooEvent.new matcher_ = matcher(actual = matchers.an_event(FooEvent)).in_stream('foo').in(event_store) matcher_.matches?(Proc.new { event_store.publish(foo_event, stream_name: 'foo') }) expect(matcher_.failure_message_when_negated.to_s).to eq(<<~EOS) expected block not to have published: #{[actual].inspect} in stream foo but published: #{[foo_event].inspect} EOS end specify do matcher_ = matcher expect(matcher_.description).to eq("publish events") end specify do expect { event_store.publish(FooEvent.new) event_store.publish(FooEvent.new) }.to matcher(matchers.an_event(FooEvent)).in(event_store).exactly(2).times end specify do expect { event_store.publish(FooEvent.new) event_store.publish(FooEvent.new) }.not_to matcher(matchers.an_event(FooEvent)).in(event_store).exactly(3).times end specify do expect do expect { event_store.publish(FooEvent.new) }.to matcher(matchers.an_event(FooEvent), matchers.an_event(FooEvent)).in(event_store).exactly(3).times end.to raise_error(NotSupported) end specify do expect do expect { }.to matcher(matchers.an_event(FooEvent), matchers.an_event(FooEvent)).in(event_store).exactly(3).times end.to raise_error(NotSupported) end specify do expect { event_store.publish(FooEvent.new) }.to matcher(matchers.an_event(FooEvent)).once.in(event_store) end specify do expect do event_store.publish(FooEvent.new) event_store.publish(BarEvent.new) event_store.publish(BazEvent.new) end.not_to matcher( matchers.an_event(FooEvent), matchers.an_event(BarEvent) ).strict.in(event_store) end specify do expect do event_store.publish(FooEvent.new) event_store.publish(BarEvent.new) end.to matcher( matchers.an_event(FooEvent), matchers.an_event(BarEvent) ).strict.in(event_store) end end end end Kill mutant, missing failure test for Publish#once require "spec_helper" module RubyEventStore module RSpec ::RSpec.describe Publish do let(:matchers) { Object.new.tap { |o| o.extend(Matchers) } } let(:event_store) do RubyEventStore::Client.new( repository: RubyEventStore::InMemoryRepository.new, mapper: RubyEventStore::Mappers::PipelineMapper.new( RubyEventStore::Mappers::Pipeline.new(to_domain_event: Transformations::IdentityMap.new) ) ) end def matcher(*expected) Publish.new(*expected, failure_message_formatter: RSpec.default_formatter.publish) end specify do expect { expect { true }.to matcher }.to raise_error("You have to set the event store instance with `in`, e.g. `expect { ... }.to publish(an_event(MyEvent)).in(event_store)`") end specify do expect { true }.not_to matcher.in(event_store) end specify do expect { event_store.publish(FooEvent.new) }.to matcher.in(event_store) end specify do expect { event_store.publish(FooEvent.new, stream_name: 'Foo$1') }.to matcher.in(event_store).in_stream('Foo$1') end specify do expect { event_store.publish(FooEvent.new, stream_name: 'Foo$1') }.not_to matcher.in(event_store).in_stream('Bar$1') end specify do expect { event_store.publish(FooEvent.new) }.not_to matcher(matchers.an_event(BarEvent)).in(event_store) end specify do expect { event_store.publish(FooEvent.new) }.to matcher(matchers.an_event(FooEvent)).in(event_store) end specify do expect { event_store.publish(FooEvent.new, stream_name: "Foo$1") }.to matcher(matchers.an_event(FooEvent)).in(event_store).in_stream("Foo$1") end specify do expect { event_store.publish(FooEvent.new) }.not_to matcher(matchers.an_event(FooEvent)).in(event_store).in_stream("Foo$1") end specify do event_store.publish(FooEvent.new) event_store.publish(FooEvent.new) event_store.publish(FooEvent.new) expect { event_store.publish(BarEvent.new) }.to matcher(matchers.an_event(BarEvent)).in(event_store) expect { event_store.publish(BarEvent.new) }.not_to matcher(matchers.an_event(FooEvent)).in(event_store) end specify do foo_event = FooEvent.new bar_event = BarEvent.new expect { event_store.publish(foo_event, stream_name: "Foo$1") event_store.publish(bar_event, stream_name: "Bar$1") }.to matcher(matchers.an_event(FooEvent), matchers.an_event(BarEvent)).in(event_store) end specify do foo_event = FooEvent.new bar_event = BarEvent.new event_store.publish(foo_event) expect { event_store.publish(bar_event) }.not_to matcher(matchers.an_event(FooEvent)).in(event_store) end specify do expect { true }.not_to matcher.in(event_store) end specify do matcher_ = matcher.in(event_store) matcher_.matches?(Proc.new { }) expect(matcher_.failure_message_when_negated.to_s).to eq(<<~EOS.strip) expected block not to have published any events EOS end specify do matcher_ = matcher.in(event_store) matcher_.matches?(Proc.new { }) expect(matcher_.failure_message.to_s).to eq(<<~EOS.strip) expected block to have published any events EOS end specify do matcher_ = matcher(actual = matchers.an_event(FooEvent)).in(event_store) matcher_.matches?(Proc.new { }) expect(matcher_.failure_message.to_s).to eq(<<~EOS) expected block to have published: #{[actual].inspect} but published: [] EOS end specify do matcher_ = matcher(actual = matchers.an_event(FooEvent)).in_stream('foo').in(event_store) matcher_.matches?(Proc.new { }) expect(matcher_.failure_message.to_s).to eq(<<~EOS) expected block to have published: #{[actual].inspect} in stream foo but published: [] EOS end specify do foo_event = FooEvent.new matcher_ = matcher(actual = matchers.an_event(FooEvent)).in(event_store) matcher_.matches?(Proc.new { event_store.publish(foo_event) }) expect(matcher_.failure_message_when_negated.to_s).to eq(<<~EOS) expected block not to have published: #{[actual].inspect} but published: #{[foo_event].inspect} EOS end specify do foo_event = FooEvent.new matcher_ = matcher(actual = matchers.an_event(FooEvent)).in_stream('foo').in(event_store) matcher_.matches?(Proc.new { event_store.publish(foo_event, stream_name: 'foo') }) expect(matcher_.failure_message_when_negated.to_s).to eq(<<~EOS) expected block not to have published: #{[actual].inspect} in stream foo but published: #{[foo_event].inspect} EOS end specify do matcher_ = matcher expect(matcher_.description).to eq("publish events") end specify do expect { event_store.publish(FooEvent.new) event_store.publish(FooEvent.new) }.to matcher(matchers.an_event(FooEvent)).in(event_store).exactly(2).times end specify do expect { event_store.publish(FooEvent.new) event_store.publish(FooEvent.new) }.not_to matcher(matchers.an_event(FooEvent)).in(event_store).exactly(3).times end specify do expect do expect { event_store.publish(FooEvent.new) }.to matcher(matchers.an_event(FooEvent), matchers.an_event(FooEvent)).in(event_store).exactly(3).times end.to raise_error(NotSupported) end specify do expect do expect { }.to matcher(matchers.an_event(FooEvent), matchers.an_event(FooEvent)).in(event_store).exactly(3).times end.to raise_error(NotSupported) end specify do expect { event_store.publish(FooEvent.new) }.to matcher(matchers.an_event(FooEvent)).once.in(event_store) end specify do expect { event_store.publish(FooEvent.new) event_store.publish(FooEvent.new) }.not_to matcher(matchers.an_event(FooEvent)).once.in(event_store) end specify do expect do event_store.publish(FooEvent.new) event_store.publish(BarEvent.new) event_store.publish(BazEvent.new) end.not_to matcher( matchers.an_event(FooEvent), matchers.an_event(BarEvent) ).strict.in(event_store) end specify do expect do event_store.publish(FooEvent.new) event_store.publish(BarEvent.new) end.to matcher( matchers.an_event(FooEvent), matchers.an_event(BarEvent) ).strict.in(event_store) end end end end
class Admin::TweetsController < Admin::AdminController before_filter :load_tweet, :only => :review # list either unreviewed def index # boilerplate I don't fully understand @group_name = params[:group_name] || @default_group.name @politicians = Politician.active.joins(:groups).where({:groups => {:name => @group_name}}).all @tweets = DeletedTweet.where(:politician_id => @politicians) # filter to relevant subset of deleted tweets @tweets = @tweets.where :reviewed => params[:reviewed], :approved => params[:approved] per_page = params[:per_page] ? params[:per_page].to_i : nil per_page ||= Tweet.per_page per_page = 200 if per_page > 200 @tweets = @tweets.includes(:politician => [:party]).paginate(:page => params[:page], :per_page => per_page) end # approve or unapprove a tweet, mark it as reviewed either way def review approved = (params[:commit] == "Approve") review_message = (params[:review_message] || "").strip if !@tweet.reviewed? and approved and review_message.blank? flash[:review_message] = "You need to add a note about why you're approving this tweet." redirect_to params[:return_to] return false end @tweet.approved = approved @tweet.reviewed = true @tweet.reviewed_at = Time.now if review_message.any? @tweet.review_message = review_message end @tweet.save! expire_action :controller => '/tweets', :action => :index redirect_to params[:return_to] end # filters def load_tweet unless params[:id] and (@tweet = DeletedTweet.find(params[:id])) render :nothing => true, :status => :not_found return false end end end Show unreviewed tweets oldest to newest class Admin::TweetsController < Admin::AdminController before_filter :load_tweet, :only => :review # list either unreviewed def index # boilerplate I don't fully understand @group_name = params[:group_name] || @default_group.name @politicians = Politician.active.joins(:groups).where({:groups => {:name => @group_name}}).all @tweets = DeletedTweet.where(:politician_id => @politicians) # filter to relevant subset of deleted tweets @tweets = @tweets.where :reviewed => params[:reviewed], :approved => params[:approved] # show unreviewed tweets oldest to newest if !params[:reviewed] @tweets = @tweets.reorder "modified ASC" end per_page = params[:per_page] ? params[:per_page].to_i : nil per_page ||= Tweet.per_page per_page = 200 if per_page > 200 @tweets = @tweets.includes(:politician => [:party]).paginate(:page => params[:page], :per_page => per_page) end # approve or unapprove a tweet, mark it as reviewed either way def review approved = (params[:commit] == "Approve") review_message = (params[:review_message] || "").strip if !@tweet.reviewed? and approved and review_message.blank? flash[:review_message] = "You need to add a note about why you're approving this tweet." redirect_to params[:return_to] return false end @tweet.approved = approved @tweet.reviewed = true @tweet.reviewed_at = Time.now if review_message.any? @tweet.review_message = review_message end @tweet.save! expire_action :controller => '/tweets', :action => :index redirect_to params[:return_to] end # filters def load_tweet unless params[:id] and (@tweet = DeletedTweet.find(params[:id])) render :nothing => true, :status => :not_found return false end end end
class SettingsValidationWrapper class DataPathsValidator < ActiveModel::Validator def defaults(key) [Settings.paths[key], PathsInitializer::DEFAULT_PATHS[key]] end def set_directory(key) setting, fallback = defaults(key) PathsInitializer.prepare(setting, fallback) end def failure_condition_met?(key) setting, _fallback = defaults(key) setting.nil? && !File.directory?(set_directory(key)) end def validate(record) PathsInitializer::DEFAULT_PATHS.each do |key, _default_value| dir = set_directory(key) if failure_condition_met?(key) record.errors["yml__paths__#{key}".to_sym] = "Implicitly set data directory path '#{dir}' is not a directory." elsif !Settings.paths[key].is_a?(String) record.errors["yml__paths__#{key}".to_sym] = 'Is not a String value.' elsif !File.directory?(dir) record.errors["yml__paths__#{key}".to_sym] = 'Is not a directory.' end end end end include ActiveModel::Validations include SettingsValidationWrapper::Validators # We assume that deployment is done on a linux machine that has 'nproc'. # Counting processors is different on other machines. For them, we would need # to use a gem. NPROC_PATH = `which nproc` NPROC_AVAILABLE = NPROC_PATH.present? && File.executable?(NPROC_PATH) PRESENCE = %i(yml__name yml__OMS yml__OMS_qualifier yml__action_mailer__delivery_method yml__action_mailer__smtp_settings__address yml__allow_unconfirmed_access_for_days yml__max_read_filesize yml__max_combined_diff_size yml__ontology_parse_timeout yml__footer yml__exception_notifier__email_prefix yml__exception_notifier__sender_address yml__exception_notifier__exception_recipients yml__paths__data yml__git__verify_url yml__git__default_branch yml__git__push_priority__commits yml__git__push_priority__changed_files_per_commit yml__git__fallbacks__committer_name yml__git__fallbacks__committer_email yml__allowed_iri_schemes yml__external_repository_name yml__formality_levels yml__license_models yml__ontology_types yml__tasks yml__hets__version_minimum_version yml__hets__version_minimum_revision yml__hets__stack_size yml__hets__cmd_line_options yml__hets__server_options yml__hets__env__LANG initializers__fqdn) PRESENCE_IN_PRODUCTION = %i(yml__hets__executable_path yml__hets__instances_count) BOOLEAN = %i(yml__exception_notifier__enabled yml__display_head_commit yml__display_symbols_tab yml__format_selection yml__action_mailer__perform_deliveries yml__action_mailer__raise_delivery_errors yml__action_mailer__smtp_settings__enable_starttls_auto initializers__consider_all_requests_local) FIXNUM = %i(yml__hets__instances_count yml__action_mailer__smtp_settings__port yml__allow_unconfirmed_access_for_days yml__git__push_priority__commits yml__git__push_priority__changed_files_per_commit yml__access_token__expiration_minutes yml__hets__time_between_updates yml__hets__version_minimum_revision) FLOAT = %i(yml__hets__version_minimum_version) STRING = %i(yml__name yml__OMS yml__OMS_qualifier yml__email yml__action_mailer__smtp_settings__address yml__exception_notifier__email_prefix yml__exception_notifier__sender_address yml__paths__data yml__git__verify_url yml__git__default_branch yml__git__fallbacks__committer_name yml__git__fallbacks__committer_email yml__external_repository_name) ARRAY = %i(yml__footer yml__exception_notifier__exception_recipients yml__allowed_iri_schemes yml__formality_levels yml__license_models yml__ontology_types yml__tasks yml__hets__cmd_line_options yml__hets__server_options) DIRECTORY_PRODUCTION = %i(yml__paths__data) ELEMENT_PRESENT = %i(yml__allowed_iri_schemes yml__hets__cmd_line_options yml__hets__server_options) attr_reader :cp_keys validates :cp_keys, executable: true, if: :in_production? validates_with DataPathsValidator, if: :in_production? validates_presence_of *PRESENCE validates_presence_of *PRESENCE_IN_PRODUCTION, if: :in_production? BOOLEAN.each do |field| validates field, class: {in: [TrueClass, FalseClass]} end FIXNUM.each { |field| validates field, class: {in: [Fixnum]} } FLOAT.each { |field| validates field, class: {in: [Float]} } STRING.each { |field| validates field, class: {in: [String]} } ARRAY.each { |field| validates field, class: {in: [Array]} } DIRECTORY_PRODUCTION.each do |field| validates field, directory: true, if: :in_production? end ELEMENT_PRESENT.each { |field| validates field, elements_are_present: true } validates :initializers__secret_token, presence: true, length: {minimum: 64}, if: :in_production? validates :yml__email, email_host: {hostname: ->(record) { record.initializers__fqdn }}, if: :in_production? validates :yml__exception_notifier__exception_recipients, elements_are_email: true validates :yml__action_mailer__delivery_method, inclusion: {in: %i(sendmail smtp file test)} validates :yml__allow_unconfirmed_access_for_days, numericality: {greater_than_or_equal_to: 0} validates :yml__max_read_filesize, numericality: {greater_than: 1024} validates :yml__max_combined_diff_size, numericality: {greater_than: 2048} validates :yml__ontology_parse_timeout, numericality: {greater_than: 0} validates :yml__git__verify_url, format: URI.regexp validates :yml__git__push_priority__commits, numericality: {greater_than_or_equal_to: 1} validates :yml__git__push_priority__changed_files_per_commit, numericality: {greater_than_or_equal_to: 1} validates :yml__access_token__expiration_minutes, numericality: {greater_than_or_equal_to: 1} validates :yml__footer, elements_have_keys: {keys: %i(text)} validates :yml__formality_levels, elements_have_keys: {keys: %i(name description)} validates :yml__license_models, elements_have_keys: {keys: %i(name url)} validates :yml__ontology_types, elements_have_keys: {keys: %i(name description documentation)} validates :yml__tasks, elements_have_keys: {keys: %i(name description)} validates :initializers__log_level, inclusion: {in: %i(fatal error warn info debug)} validates :yml__hets__executable_path, executable: true, if: :in_production? if NPROC_AVAILABLE validates :yml__hets__instances_count, numericality: {greater_than: 0, less_than_or_equal_to: `nproc`.to_i}, if: :in_production? else validates :yml__hets__instances_count, numericality: {greater_than: 0}, if: :in_production? end validates :yml__hets__time_between_updates, numericality: {greater_than_or_equal_to: 1} validates :yml__asynchronous_execution__log_level, inclusion: {in: %w(UNKNOWN FATAL ERROR WARN INFO DEBUG)} def self.base(first_portion) case first_portion when 'yml' Settings when 'initializers' Ontohub::Application.config else :error end end def self.get_value(object, key_chain) key_chain.each do |key| if object.respond_to?(key) object = object.send(key) else # The nil value shall be caught by the presence validators. return nil end end object end def initialize # Define a value for the cp_keys location. # This must be defined in two places. Make sure this value is synchronized # with AuthorizedKeysManager.cp_keys_executable. @cp_keys = Pathname.new(Settings.paths.data).join('.ssh', 'cp_keys').to_s end def cp_keys=(_path) # Noop - the value is supposed to be hard-coded. # The validations require the existence of a setter, though. end protected def in_production? Rails.env.production? end # We use '__' as a separator. It will be replaced by a dot. # This uses the fact that our settings-keys never have two consecutive # underscores. # yml__git__verify_url maps to Settings.git.verify_url. # initializers__git__verify_url maps to @config.git.verify_url. def method_missing(method_name, *_args) portions = method_name.to_s.split('__') object = base(portions[0]) key_chain = portions[1..-1] if object == :error || key_chain.blank? raise NoMethodError, "undefined method `#{method_name}' for #{self}:#{self.class}" end get_value(object, key_chain) end protected def in_production? Rails.env.production? end # We use '__' as a separator. It will be replaced by a dot. # This uses the fact that our settings-keys never have two consecutive # underscores. # yml__git__verify_url maps to Settings.git.verify_url. # initializers__git__verify_url maps to @config.git.verify_url. def method_missing(method_name, *_args) portions = method_name.to_s.split('__') object = self.class.base(portions[0]) key_chain = portions[1..-1] if object == :error || key_chain.blank? raise NoMethodError, "undefined method `#{method_name}' for #{self}:#{self.class}" end self.class.get_value(object, key_chain) end end Correct comment. class SettingsValidationWrapper class DataPathsValidator < ActiveModel::Validator def defaults(key) [Settings.paths[key], PathsInitializer::DEFAULT_PATHS[key]] end def set_directory(key) setting, fallback = defaults(key) PathsInitializer.prepare(setting, fallback) end def failure_condition_met?(key) setting, _fallback = defaults(key) setting.nil? && !File.directory?(set_directory(key)) end def validate(record) PathsInitializer::DEFAULT_PATHS.each do |key, _default_value| dir = set_directory(key) if failure_condition_met?(key) record.errors["yml__paths__#{key}".to_sym] = "Implicitly set data directory path '#{dir}' is not a directory." elsif !Settings.paths[key].is_a?(String) record.errors["yml__paths__#{key}".to_sym] = 'Is not a String value.' elsif !File.directory?(dir) record.errors["yml__paths__#{key}".to_sym] = 'Is not a directory.' end end end end include ActiveModel::Validations include SettingsValidationWrapper::Validators # We assume that deployment is done on a linux machine that has 'nproc'. # Counting processors is different on other machines. For them, we would need # to use a gem. NPROC_PATH = `which nproc` NPROC_AVAILABLE = NPROC_PATH.present? && File.executable?(NPROC_PATH) PRESENCE = %i(yml__name yml__OMS yml__OMS_qualifier yml__action_mailer__delivery_method yml__action_mailer__smtp_settings__address yml__allow_unconfirmed_access_for_days yml__max_read_filesize yml__max_combined_diff_size yml__ontology_parse_timeout yml__footer yml__exception_notifier__email_prefix yml__exception_notifier__sender_address yml__exception_notifier__exception_recipients yml__paths__data yml__git__verify_url yml__git__default_branch yml__git__push_priority__commits yml__git__push_priority__changed_files_per_commit yml__git__fallbacks__committer_name yml__git__fallbacks__committer_email yml__allowed_iri_schemes yml__external_repository_name yml__formality_levels yml__license_models yml__ontology_types yml__tasks yml__hets__version_minimum_version yml__hets__version_minimum_revision yml__hets__stack_size yml__hets__cmd_line_options yml__hets__server_options yml__hets__env__LANG initializers__fqdn) PRESENCE_IN_PRODUCTION = %i(yml__hets__executable_path yml__hets__instances_count) BOOLEAN = %i(yml__exception_notifier__enabled yml__display_head_commit yml__display_symbols_tab yml__format_selection yml__action_mailer__perform_deliveries yml__action_mailer__raise_delivery_errors yml__action_mailer__smtp_settings__enable_starttls_auto initializers__consider_all_requests_local) FIXNUM = %i(yml__hets__instances_count yml__action_mailer__smtp_settings__port yml__allow_unconfirmed_access_for_days yml__git__push_priority__commits yml__git__push_priority__changed_files_per_commit yml__access_token__expiration_minutes yml__hets__time_between_updates yml__hets__version_minimum_revision) FLOAT = %i(yml__hets__version_minimum_version) STRING = %i(yml__name yml__OMS yml__OMS_qualifier yml__email yml__action_mailer__smtp_settings__address yml__exception_notifier__email_prefix yml__exception_notifier__sender_address yml__paths__data yml__git__verify_url yml__git__default_branch yml__git__fallbacks__committer_name yml__git__fallbacks__committer_email yml__external_repository_name) ARRAY = %i(yml__footer yml__exception_notifier__exception_recipients yml__allowed_iri_schemes yml__formality_levels yml__license_models yml__ontology_types yml__tasks yml__hets__cmd_line_options yml__hets__server_options) DIRECTORY_PRODUCTION = %i(yml__paths__data) ELEMENT_PRESENT = %i(yml__allowed_iri_schemes yml__hets__cmd_line_options yml__hets__server_options) attr_reader :cp_keys validates :cp_keys, executable: true, if: :in_production? validates_with DataPathsValidator, if: :in_production? validates_presence_of *PRESENCE validates_presence_of *PRESENCE_IN_PRODUCTION, if: :in_production? BOOLEAN.each do |field| validates field, class: {in: [TrueClass, FalseClass]} end FIXNUM.each { |field| validates field, class: {in: [Fixnum]} } FLOAT.each { |field| validates field, class: {in: [Float]} } STRING.each { |field| validates field, class: {in: [String]} } ARRAY.each { |field| validates field, class: {in: [Array]} } DIRECTORY_PRODUCTION.each do |field| validates field, directory: true, if: :in_production? end ELEMENT_PRESENT.each { |field| validates field, elements_are_present: true } validates :initializers__secret_token, presence: true, length: {minimum: 64}, if: :in_production? validates :yml__email, email_host: {hostname: ->(record) { record.initializers__fqdn }}, if: :in_production? validates :yml__exception_notifier__exception_recipients, elements_are_email: true validates :yml__action_mailer__delivery_method, inclusion: {in: %i(sendmail smtp file test)} validates :yml__allow_unconfirmed_access_for_days, numericality: {greater_than_or_equal_to: 0} validates :yml__max_read_filesize, numericality: {greater_than: 1024} validates :yml__max_combined_diff_size, numericality: {greater_than: 2048} validates :yml__ontology_parse_timeout, numericality: {greater_than: 0} validates :yml__git__verify_url, format: URI.regexp validates :yml__git__push_priority__commits, numericality: {greater_than_or_equal_to: 1} validates :yml__git__push_priority__changed_files_per_commit, numericality: {greater_than_or_equal_to: 1} validates :yml__access_token__expiration_minutes, numericality: {greater_than_or_equal_to: 1} validates :yml__footer, elements_have_keys: {keys: %i(text)} validates :yml__formality_levels, elements_have_keys: {keys: %i(name description)} validates :yml__license_models, elements_have_keys: {keys: %i(name url)} validates :yml__ontology_types, elements_have_keys: {keys: %i(name description documentation)} validates :yml__tasks, elements_have_keys: {keys: %i(name description)} validates :initializers__log_level, inclusion: {in: %i(fatal error warn info debug)} validates :yml__hets__executable_path, executable: true, if: :in_production? if NPROC_AVAILABLE validates :yml__hets__instances_count, numericality: {greater_than: 0, less_than_or_equal_to: `nproc`.to_i}, if: :in_production? else validates :yml__hets__instances_count, numericality: {greater_than: 0}, if: :in_production? end validates :yml__hets__time_between_updates, numericality: {greater_than_or_equal_to: 1} validates :yml__asynchronous_execution__log_level, inclusion: {in: %w(UNKNOWN FATAL ERROR WARN INFO DEBUG)} def self.base(first_portion) case first_portion when 'yml' Settings when 'initializers' Ontohub::Application.config else :error end end def self.get_value(object, key_chain) key_chain.each do |key| if object.respond_to?(key) object = object.send(key) else # The nil value shall be caught by the presence validators. return nil end end object end def initialize # Define a value for the cp_keys location. # This must be defined in two places. Make sure this value is synchronized # with AuthorizedKeysManager.cp_keys_executable. @cp_keys = Pathname.new(Settings.paths.data).join('.ssh', 'cp_keys').to_s end def cp_keys=(_path) # No-Op - the value is supposed to be hard-coded. # The validations require the existence of a setter, though. end protected def in_production? Rails.env.production? end # We use '__' as a separator. It will be replaced by a dot. # This uses the fact that our settings-keys never have two consecutive # underscores. # yml__git__verify_url maps to Settings.git.verify_url. # initializers__git__verify_url maps to @config.git.verify_url. def method_missing(method_name, *_args) portions = method_name.to_s.split('__') object = base(portions[0]) key_chain = portions[1..-1] if object == :error || key_chain.blank? raise NoMethodError, "undefined method `#{method_name}' for #{self}:#{self.class}" end get_value(object, key_chain) end protected def in_production? Rails.env.production? end # We use '__' as a separator. It will be replaced by a dot. # This uses the fact that our settings-keys never have two consecutive # underscores. # yml__git__verify_url maps to Settings.git.verify_url. # initializers__git__verify_url maps to @config.git.verify_url. def method_missing(method_name, *_args) portions = method_name.to_s.split('__') object = self.class.base(portions[0]) key_chain = portions[1..-1] if object == :error || key_chain.blank? raise NoMethodError, "undefined method `#{method_name}' for #{self}:#{self.class}" end self.class.get_value(object, key_chain) end end
require 'social_net/byte/errors/response_error' require 'social_net/byte/errors/unknown_user' require 'active_support' require 'active_support/core_ext' module SocialNet module Byte module Api class Request def initialize(attrs = {}) @host = 'api.byte.co' @username = attrs[:username] @endpoint = attrs.fetch :endpoint, "/account/id/#{@username}/posts" @block = attrs.fetch :block, -> (request) {add_access_token_and_cursor! request} @next_page = attrs[:next_page] if attrs[:next_page] @method = attrs.fetch :method, :get end def run print "#{as_curl}\n" case response = run_http_request when Net::HTTPOK JSON response.body else raise Errors::ResponseError, response end end private def run_http_request Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http| http.request http_request end end def http_request http_class = "Net::HTTP::#{@method.capitalize}".constantize @http_request ||= http_class.new(uri.request_uri).tap do |request| @block.call request end end def uri @uri ||= URI::HTTPS.build host: @host, path: @endpoint, query: query end def add_access_token_and_cursor!(request) request.add_field 'Authorization', SocialNet::Byte.configuration.access_token end def query {}.tap do |query| query.merge! cursor: @next_page if @next_page end.to_param end def as_curl 'curl'.tap do |curl| curl << " -X #{http_request.method}" http_request.each_header do |name, value| curl << %Q{ -H "#{name}: #{value}"} end curl << %Q{ -d '#{http_request.body}'} if http_request.body curl << %Q{ "#{@uri.to_s}"} end end end end end end Add rate limit protection require 'social_net/byte/errors/response_error' require 'social_net/byte/errors/unknown_user' require 'active_support' require 'active_support/core_ext' module SocialNet module Byte module Api class Request def initialize(attrs = {}) @host = 'api.byte.co' @username = attrs[:username] @endpoint = attrs.fetch :endpoint, "/account/id/#{@username}/posts" @block = attrs.fetch :block, -> (request) {add_access_token_and_cursor! request} @next_page = attrs[:next_page] if attrs[:next_page] @method = attrs.fetch :method, :get end def run print "#{as_curl}\n" case response = run_http_request when Net::HTTPOK rate_limit_reset response.header["x-ratelimit-remaining"].to_i JSON response.body else raise Errors::ResponseError, response end end private def run_http_request Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http| http.request http_request end end def http_request http_class = "Net::HTTP::#{@method.capitalize}".constantize @http_request ||= http_class.new(uri.request_uri).tap do |request| @block.call request end end def uri @uri ||= URI::HTTPS.build host: @host, path: @endpoint, query: query end def add_access_token_and_cursor!(request) request.add_field 'Authorization', SocialNet::Byte.configuration.access_token end def query {}.tap do |query| query.merge! cursor: @next_page if @next_page end.to_param end def rate_limit_reset(number_of_tries) puts number_of_tries if number_of_tries == 1 puts "Sleeping 20 seconds to reset the rate limit" sleep 20 end end def as_curl 'curl'.tap do |curl| curl << " -X #{http_request.method}" http_request.each_header do |name, value| curl << %Q{ -H "#{name}: #{value}"} end curl << %Q{ -d '#{http_request.body}'} if http_request.body curl << %Q{ "#{@uri.to_s}"} end end end end end end
module Api # A controller that contains all of the helper methods and shared logic for # all API endpoints. class AbstractController < ApplicationController # This error is thrown when you try to use a non-JSON request body on an # endpoint that requires JSON. class OnlyJson < Exception; end; CONSENT_REQUIRED = "all device users must agree to terms of service." NOT_JSON = "That request was not valid JSON. Consider checking the request"\ " body with a JSON validator.." respond_to :json before_action :check_fbos_version before_action :set_default_stuff before_action :authenticate_user! skip_before_action :verify_authenticity_token after_action :skip_set_cookies_header rescue_from(ActionController::RoutingError) { sorry "Not found", 404 } rescue_from(User::AlreadyVerified) { sorry "Already verified.", 409 } rescue_from(JWT::VerificationError) { |e| auth_err } rescue_from(ActionDispatch::Http::Parameters::ParseError) { sorry NOT_JSON, 422 } rescue_from(ActiveRecord::ValueTooLong) do sorry "Please use reasonable lengths on string inputs", 422 end rescue_from Errors::Forbidden do |exc| sorry "You can't perform that action. #{exc.message}", 403 end rescue_from OnlyJson do |e| sorry "This is a JSON API. Please use _valid_ JSON.", 422 end rescue_from Errors::NoBot do |exc| sorry "You need to register a device first.", 422 end rescue_from ActiveRecord::RecordNotFound do |exc| sorry "Document not found.", 404 end rescue_from ActiveRecord::RecordInvalid do |exc| render json: {error: exc.message}, status: 422 end rescue_from Errors::LegalConsent do |exc| render json: {error: CONSENT_REQUIRED}, status: 451 end rescue_from ActiveModel::RangeError do |_| sorry "One of those numbers was too big/small. " + "If you need larger numbers, let us know.", 422 end def default_serializer_options {root: false, user: current_user} end private def clean_expired_farm_events FarmEvents::CleanExpired.run!(device: current_device) end # Rails 5 params are no longer simple hashes. This was for security reasons. # Our API does not do things the "Rails way" (we use Mutations for input # sanitation) so we can ignore this and grab the raw input. def raw_json @raw_json ||= JSON.parse(request.body.read).tap{ |x| symbolize(x) } rescue JSON::ParserError raise OnlyJson end # PROBLEM: We want to deep_symbolize_keys! on all JSON inputs, but what if # the user POSTs an Array? It will crash because [] does not respond_to # deep_symbolize_keys! This is the workaround. I could probably use a # refinement. def symbolize(x) x.is_a?(Array) ? x.map(&:deep_symbolize_keys!) : x.deep_symbolize_keys! end REQ_ID = "X-Farmbot-Rpc-Id" def set_default_stuff request.format = "json" id = request.headers[REQ_ID] || SecureRandom.uuid response.headers[REQ_ID] = id # # IMPORTANT: We need to hoist X-Farmbot-Rpc-Id to a global so that it is # # accessible for use with auto_sync. Transport.current.set_current_request_id(response.headers[REQ_ID]) end # Disable cookies. This is an API! def skip_set_cookies_header reset_session end def current_device if @current_device @current_device else @current_device = (current_user.try(:device) || no_device) Device.current = @current_device # Mutable state eww @current_device end end def no_device raise Errors::NoBot end def authenticate_user! # All possible information that could be needed for any of the 3 auth # strategies. context = { jwt: request.headers["Authorization"], user: current_user } # Returns a symbol representing the appropriate auth strategy, or nil if # unknown. strategy = Auth::DetermineAuthStrategy.run!(context) case strategy when :jwt sign_in(Auth::FromJWT.run!(context).require_consent!) when :already_connected # Probably provided a cookie. # 9 times out of 10, it's a unit test. # Our cookie system works, we just don't use it. current_user.require_consent! return true else auth_err end mark_as_seen rescue Mutations::ValidationException => e errors = e.errors.message.merge(strategy: strategy) render json: {error: errors}, status: 401 end def auth_err sorry("You failed to authenticate with the API. Ensure that you " \ " provide a JSON Web Token in the `Authorization:` header." , 401) end def sorry(msg, status) render json: { error: msg }, status: status end def mutate(outcome, options = {}) if outcome.success? render options.merge(json: outcome.result) else Rollbar.info("Mutation error", errors: outcome.errors.message_list.join(" "), user: current_user.try(:email) || "No User") render options.merge(json: outcome.errors.message, status: 422) end end def bad_version render json: {error: "Upgrade to latest FarmBot OS"}, status: 426 end EXPECTED_VER = Gem::Version::new GlobalConfig.dump["MINIMUM_FBOS_VERSION"] # Try to extract FarmBot OS version from user agent. def fbos_version when_farmbot_os do Gem::Version::new(pretty_ua.upcase.split("/").last.split(" ").first) || CalculateUpgrade::NULL end || CalculateUpgrade::NOT_FBOS end # This is how we lock old versions of FBOS out of the API: def check_fbos_version when_farmbot_os do bad_version unless fbos_version >= EXPECTED_VER end end # Format the user agent header in a way that is easier for us to parse. def pretty_ua # "FARMBOTOS/3.1.0 (RPI3) RPI3 ()" (request.user_agent || "FARMBOTOS/0.0.0 (RPI3) RPI3 ()").upcase end # Conditionally execute a block when the request was made by a FarmBot def when_farmbot_os yield if pretty_ua.include?("FARMBOTOS") end # Devices have a `last_saw_api` field to assist users with debugging. # We update this column every time an FBOS device talks to the API. def mark_as_seen(bot = (current_user && current_user.device)) when_farmbot_os do v = fbos_version.to_s bot.update_attributes!(last_saw_api: Time.now, fbos_version: v) if bot end end end end Updates to fbos_version() helper module Api # A controller that contains all of the helper methods and shared logic for # all API endpoints. class AbstractController < ApplicationController # This error is thrown when you try to use a non-JSON request body on an # endpoint that requires JSON. class OnlyJson < Exception; end; CONSENT_REQUIRED = \ "all device users must agree to terms of service." NOT_JSON = "That request was not valid JSON. Consider checking the"\ " request body with a JSON validator.." FARMBOT_UA_STRING = "FARMBOTOS" NO_UA_FOUND = FARMBOT_UA_STRING + "/0.0.0 (RPI3) RPI3 (MISSING)" respond_to :json before_action :check_fbos_version before_action :set_default_stuff before_action :authenticate_user! skip_before_action :verify_authenticity_token after_action :skip_set_cookies_header rescue_from(ActionController::RoutingError) { sorry "Not found", 404 } rescue_from(User::AlreadyVerified) { sorry "Already verified.", 409 } rescue_from(JWT::VerificationError) { |e| auth_err } rescue_from(ActionDispatch::Http::Parameters::ParseError) { sorry NOT_JSON, 422 } rescue_from(ActiveRecord::ValueTooLong) do sorry "Please use reasonable lengths on string inputs", 422 end rescue_from Errors::Forbidden do |exc| sorry "You can't perform that action. #{exc.message}", 403 end rescue_from OnlyJson do |e| sorry "This is a JSON API. Please use _valid_ JSON.", 422 end rescue_from Errors::NoBot do |exc| sorry "You need to register a device first.", 422 end rescue_from ActiveRecord::RecordNotFound do |exc| sorry "Document not found.", 404 end rescue_from ActiveRecord::RecordInvalid do |exc| render json: {error: exc.message}, status: 422 end rescue_from Errors::LegalConsent do |exc| render json: {error: CONSENT_REQUIRED}, status: 451 end rescue_from ActiveModel::RangeError do |_| sorry "One of those numbers was too big/small. " + "If you need larger numbers, let us know.", 422 end def default_serializer_options {root: false, user: current_user} end private def clean_expired_farm_events FarmEvents::CleanExpired.run!(device: current_device) end # Rails 5 params are no longer simple hashes. This was for security reasons. # Our API does not do things the "Rails way" (we use Mutations for input # sanitation) so we can ignore this and grab the raw input. def raw_json @raw_json ||= JSON.parse(request.body.read).tap{ |x| symbolize(x) } rescue JSON::ParserError raise OnlyJson end # PROBLEM: We want to deep_symbolize_keys! on all JSON inputs, but what if # the user POSTs an Array? It will crash because [] does not respond_to # deep_symbolize_keys! This is the workaround. I could probably use a # refinement. def symbolize(x) x.is_a?(Array) ? x.map(&:deep_symbolize_keys!) : x.deep_symbolize_keys! end REQ_ID = "X-Farmbot-Rpc-Id" def set_default_stuff request.format = "json" id = request.headers[REQ_ID] || SecureRandom.uuid response.headers[REQ_ID] = id # # IMPORTANT: We need to hoist X-Farmbot-Rpc-Id to a global so that it is # # accessible for use with auto_sync. Transport.current.set_current_request_id(response.headers[REQ_ID]) end # Disable cookies. This is an API! def skip_set_cookies_header reset_session end def current_device if @current_device @current_device else @current_device = (current_user.try(:device) || no_device) Device.current = @current_device # Mutable state eww @current_device end end def no_device raise Errors::NoBot end def authenticate_user! # All possible information that could be needed for any of the 3 auth # strategies. context = { jwt: request.headers["Authorization"], user: current_user } # Returns a symbol representing the appropriate auth strategy, or nil if # unknown. strategy = Auth::DetermineAuthStrategy.run!(context) case strategy when :jwt sign_in(Auth::FromJWT.run!(context).require_consent!) when :already_connected # Probably provided a cookie. # 9 times out of 10, it's a unit test. # Our cookie system works, we just don't use it. current_user.require_consent! return true else auth_err end mark_as_seen rescue Mutations::ValidationException => e errors = e.errors.message.merge(strategy: strategy) render json: {error: errors}, status: 401 end def auth_err sorry("You failed to authenticate with the API. Ensure that you " \ " provide a JSON Web Token in the `Authorization:` header." , 401) end def sorry(msg, status) render json: { error: msg }, status: status end def mutate(outcome, options = {}) if outcome.success? render options.merge(json: outcome.result) else Rollbar.info("Mutation error", errors: outcome.errors.message_list.join(" "), user: current_user.try(:email) || "No User") render options.merge(json: outcome.errors.message, status: 422) end end def bad_version render json: {error: "Upgrade to latest FarmBot OS"}, status: 426 end EXPECTED_VER = Gem::Version::new GlobalConfig.dump["MINIMUM_FBOS_VERSION"] # Try to extract FarmBot OS version from user agent. def fbos_version ua = (request.user_agent || NO_UA_FOUND).upcase # Attempt 1: # The device is using an HTTP client that does not provide a user-agent. # We will assume this is an old FBOS version and set it to 0.0.0 return CalculateUpgrade::NULL if ua == NO_UA_FOUND # Attempt 2: # If the user agent was missing, we would have returned by now. # If the UA includes FARMBOT_UA_STRING at this point, it's safe to # assume we have a have a non-legacy FBOS client. return Gem::Version::new(ua[10, 5]) if ua.include?(FARMBOT_UA_STRING) # Attempt 3: # Pass CalculateUpgrade::NOT_FBOS if all other attempts fail. return CalculateUpgrade::NOT_FBOS end # This is how we lock old versions of FBOS out of the API: def check_fbos_version when_farmbot_os do bad_version unless fbos_version >= EXPECTED_VER end end # Format the user agent header in a way that is easier for us to parse. def pretty_ua # "FARMBOTOS/3.1.0 (RPI3) RPI3 ()" # If there is no user-agent present, we assume it is a _very_ old version # of FBOS. (request.user_agent || NO_UA_FOUND).upcase end # Conditionally execute a block when the request was made by a FarmBot def when_farmbot_os yield if pretty_ua.include?(FARMBOT_UA_STRING) end # Devices have a `last_saw_api` field to assist users with debugging. # We update this column every time an FBOS device talks to the API. def mark_as_seen(bot = (current_user && current_user.device)) when_farmbot_os do if bot v = fbos_version bot.last_saw_api = Time.now bot.fbos_version = v.to_s if v != CalculateUpgrade::NULL bot.save! end end end end end
class Shoes module Swt class TextBlockFitter attr_reader :parent def initialize(text_block, current_position) @text_block = text_block @dsl = @text_block.dsl @parent = @dsl.parent @current_position = current_position end # Fitting text works by using either 1 or 2 layouts # # If the text fits in the height and width available, we use one layout. # # -------------------------- # | button | text layout 1 | # -------------------------- # # If if the text doesn't fit into that space, then we'll break it into # two different layouts. # # -------------------------- # | button | text layout 1 | # -------------------------- # | text layout 2 goes here| # | in space | # -------------------------- # ^ # # When flowing, the position for the next element gets set to the end of # the text in the second layout (shown as ^ in the diagram). # # Stacks properly move to the next whole line as you'd expect. # def fit_it_in width, height = available_space if no_space_in_first_layout?(width) return fit_with_empty_first_layout(height) end layout = generate_layout(width, @dsl.text) if fits_in_one_layout?(layout, height) fit_as_one_layout(layout) else fit_as_two_layouts(layout, height, width) end end def no_space_in_first_layout?(width) width <= 0 end def fits_in_one_layout?(layout, height) return true if height == :unbounded || layout.line_count == 1 layout.get_bounds.height <= height end def fit_as_one_layout(layout) [FittedTextLayout.new(layout, @dsl.element_left, @dsl.element_top)] end def fit_as_two_layouts(layout, height, width) first_text, second_text = split_text(layout, height) first_layout = generate_layout(width, first_text) if second_text.empty? fit_as_one_layout(first_layout) else generate_two_layouts(first_layout, first_text, second_text, height) end end def fit_with_empty_first_layout(height) # Although we purposefully empty it out, still need the first layout layout = generate_layout(1, @dsl.text) layout.text = "" height += ::Shoes::Slot::NEXT_ELEMENT_ON_NEXT_LINE_OFFSET.y return generate_two_layouts(layout, "", @dsl.text, height) end def generate_two_layouts(first_layout, first_text, second_text, height) first_height = first_height(first_layout, first_text, height) second_layout = generate_second_layout(second_text) [ FittedTextLayout.new(first_layout, @dsl.element_left, @dsl.element_top), FittedTextLayout.new(second_layout, parent.absolute_left + @dsl.margin_left, @dsl.element_top + first_height) ] end def generate_second_layout(second_text) generate_layout(@dsl.containing_width, second_text) end def available_space width = @dsl.desired_width height = next_line_start - @dsl.absolute_top - 1 height = :unbounded if on_new_line? [width, height] end def next_line_start @current_position.next_line_start end def on_new_line? next_line_start <= @dsl.absolute_top end def generate_layout(width, text) @text_block.generate_layout(width, text) end def split_text(layout, height) ending_offset = 0 height_so_far = 0 offsets = layout.line_offsets offsets[0...-1].each_with_index do |_, i| height_so_far += layout.line_metrics(i).height break if height_so_far > height ending_offset = offsets[i+1] end [layout.text[0...ending_offset], layout.text[ending_offset..-1]] end # If first text is empty, height may be smaller than an actual line in # the current font. Take our pre-existing allowed height instead. def first_height(first_layout, first_text, height) first_height = first_layout.get_bounds.height first_height = height if first_text.empty? first_height end end end end Minor code-style cleanups class Shoes module Swt class TextBlockFitter attr_reader :parent def initialize(text_block, current_position) @text_block = text_block @dsl = @text_block.dsl @parent = @dsl.parent @current_position = current_position end # Fitting text works by using either 1 or 2 layouts # # If the text fits in the height and width available, we use one layout. # # -------------------------- # | button | text layout 1 | # -------------------------- # # If if the text doesn't fit into that space, then we'll break it into # two different layouts. # # -------------------------- # | button | text layout 1 | # -------------------------- # | text layout 2 goes here| # | in space | # -------------------------- # ^ # # When flowing, the position for the next element gets set to the end of # the text in the second layout (shown as ^ in the diagram). # # Stacks properly move to the next whole line as you'd expect. # def fit_it_in width, height = available_space return fit_as_empty_first_layout(height) if no_space_in_first_layout?(width) layout = generate_layout(width, @dsl.text) if fits_in_one_layout?(layout, height) fit_as_one_layout(layout) else fit_as_two_layouts(layout, height, width) end end def no_space_in_first_layout?(width) width <= 0 end def fits_in_one_layout?(layout, height) return true if height == :unbounded || layout.line_count == 1 layout.get_bounds.height <= height end def fit_as_one_layout(layout) [FittedTextLayout.new(layout, @dsl.element_left, @dsl.element_top)] end def fit_as_two_layouts(layout, height, width) first_text, second_text = split_text(layout, height) first_layout = generate_layout(width, first_text) if second_text.empty? fit_as_one_layout(first_layout) else generate_two_layouts(first_layout, first_text, second_text, height) end end def fit_as_empty_first_layout(height) # Although we purposefully empty it out, still need the first layout layout = generate_layout(1, @dsl.text) layout.text = "" height += ::Shoes::Slot::NEXT_ELEMENT_ON_NEXT_LINE_OFFSET.y generate_two_layouts(layout, "", @dsl.text, height) end def generate_two_layouts(first_layout, first_text, second_text, height) first_height = first_height(first_layout, first_text, height) second_layout = generate_second_layout(second_text) [ FittedTextLayout.new(first_layout, @dsl.element_left, @dsl.element_top), FittedTextLayout.new(second_layout, parent.absolute_left + @dsl.margin_left, @dsl.element_top + first_height) ] end def generate_second_layout(second_text) generate_layout(@dsl.containing_width, second_text) end def available_space width = @dsl.desired_width height = next_line_start - @dsl.absolute_top - 1 height = :unbounded if on_new_line? [width, height] end def next_line_start @current_position.next_line_start end def on_new_line? next_line_start <= @dsl.absolute_top end def generate_layout(width, text) @text_block.generate_layout(width, text) end def split_text(layout, height) ending_offset = 0 height_so_far = 0 offsets = layout.line_offsets offsets[0...-1].each_with_index do |_, i| height_so_far += layout.line_metrics(i).height break if height_so_far > height ending_offset = offsets[i+1] end [layout.text[0...ending_offset], layout.text[ending_offset..-1]] end # If first text is empty, height may be smaller than an actual line in # the current font. Take our pre-existing allowed height instead. def first_height(first_layout, first_text, height) first_height = first_layout.get_bounds.height first_height = height if first_text.empty? first_height end end end end
# Scripting API handlers for MarkUs module Api # This is the parent class of all API controllers. Shared functionality of # all API controllers should go here. class MainApiController < ActionController::Base include ActionPolicy::Controller, SessionHandler authorize :user, through: :current_user rescue_from ActionPolicy::Unauthorized, with: :user_not_authorized before_action :check_format, :authenticate skip_before_action :verify_authenticity_token # Unless overridden by a subclass, all routes are 404's by default def index render 'shared/http_status', locals: {code: '404', message: HttpStatusHelper::ERROR_CODE['message']['404']}, status: 404 end def show render 'shared/http_status', locals: {code: '404', message: HttpStatusHelper::ERROR_CODE['message']['404'] }, status: 404 end def create render 'shared/http_status', locals: {code: '404', message: HttpStatusHelper::ERROR_CODE['message']['404'] }, status: 404 end def update render 'shared/http_status', locals: {code: '404', message: HttpStatusHelper::ERROR_CODE['message']['404'] }, status: 404 end def destroy render 'shared/http_status', locals: {code: '404', message: HttpStatusHelper::ERROR_CODE['message']['404'] }, status: 404 end private # Auth handler for the MarkUs API. It uses the Authorization HTTP header to # determine the user who issued the request. With the Authorization # HTTP header comes a Base 64 encoded MD5 digest of the user's private key. # Note that remote authentication is not supported. API key must be used. def authenticate auth_token = parse_auth_token(request.headers['HTTP_AUTHORIZATION']) # pretend resource not found if missing or authentication is invalid if auth_token.nil? render 'shared/http_status', locals: { code: '403', message: HttpStatusHelper::ERROR_CODE['message']['403'] }, status: 403 return end # Find user by api_key_md5 @current_user = User.find_by_api_key(auth_token) if @current_user.nil? # Key/username does not exist, return 403 error render 'shared/http_status', locals: {code: '403', message: HttpStatusHelper::ERROR_CODE['message']['403']}, status: 403 return end # Student's aren't allowed yet if @current_user.student? # API is available for TAs, Admins and TestServers only render 'shared/http_status', locals: {code: '403', message: HttpStatusHelper::ERROR_CODE['message']['403']}, status: 403 end end # Make sure that the passed format is either xml or json # If no format is provided, default to XML def check_format # This allows us to support content negotiation if request.headers['HTTP_ACCEPT'].nil? || request.format == '*/*' request.format = 'xml' end request_format = request.format.symbol if request_format != :xml && request_format != :json # 406 is the default status code when the format is not support head :not_acceptable end end # Helper method for parsing the authentication token def parse_auth_token(token) return nil if token.nil? if token =~ /MarkUsAuth ([^\s,]+)/ $1 # return matched part else nil end end # Helper method for filtering, limit, offset # Ignores default_scope order, always order by id to be consistent # # Renders an error message and returns false if the filters are malformed def get_collection(collection) collection.order('id') .where(params[:filter]&.split(',')&.map { |filter| filter.split(':') }&.to_h) .offset(params[:offset]&.to_i) .limit(params[:limit]&.to_i) .load rescue StandardError render 'shared/http_status', locals: { code: '422', message: 'Invalid or malformed parameter values' }, status: 422 false end # Helper method handling which fields to render, given the provided default # fields and those present in params[:fields] def fields_to_render(default_fields) fields = [] # params[:fields] will match the following format: # argument,argument,argument... unless params[:fields].blank? filtered_fields = /(\w+,{0,1})+/.match(params[:fields]) unless filtered_fields.nil? filtered_fields.to_s.split(',').each do |field| field = field.to_sym fields << field if default_fields.include?(field) end end end fields = default_fields if fields.empty? fields end # Checks that the symbols provided in the array aren't blank in the params def has_missing_params?(required_params) required_params.each do |param| return true if params[param].blank? end false end def user_not_authorized render 'shared/http_status', locals: { code: '403', message: HttpStatusHelper::ERROR_CODE['message']['403'] }, status: 403 end end end # end Api module api: remove support for limit and offset params # Scripting API handlers for MarkUs module Api # This is the parent class of all API controllers. Shared functionality of # all API controllers should go here. class MainApiController < ActionController::Base include ActionPolicy::Controller, SessionHandler authorize :user, through: :current_user rescue_from ActionPolicy::Unauthorized, with: :user_not_authorized before_action :check_format, :authenticate skip_before_action :verify_authenticity_token # Unless overridden by a subclass, all routes are 404's by default def index render 'shared/http_status', locals: {code: '404', message: HttpStatusHelper::ERROR_CODE['message']['404']}, status: 404 end def show render 'shared/http_status', locals: {code: '404', message: HttpStatusHelper::ERROR_CODE['message']['404'] }, status: 404 end def create render 'shared/http_status', locals: {code: '404', message: HttpStatusHelper::ERROR_CODE['message']['404'] }, status: 404 end def update render 'shared/http_status', locals: {code: '404', message: HttpStatusHelper::ERROR_CODE['message']['404'] }, status: 404 end def destroy render 'shared/http_status', locals: {code: '404', message: HttpStatusHelper::ERROR_CODE['message']['404'] }, status: 404 end private # Auth handler for the MarkUs API. It uses the Authorization HTTP header to # determine the user who issued the request. With the Authorization # HTTP header comes a Base 64 encoded MD5 digest of the user's private key. # Note that remote authentication is not supported. API key must be used. def authenticate auth_token = parse_auth_token(request.headers['HTTP_AUTHORIZATION']) # pretend resource not found if missing or authentication is invalid if auth_token.nil? render 'shared/http_status', locals: { code: '403', message: HttpStatusHelper::ERROR_CODE['message']['403'] }, status: 403 return end # Find user by api_key_md5 @current_user = User.find_by_api_key(auth_token) if @current_user.nil? # Key/username does not exist, return 403 error render 'shared/http_status', locals: {code: '403', message: HttpStatusHelper::ERROR_CODE['message']['403']}, status: 403 return end # Student's aren't allowed yet if @current_user.student? # API is available for TAs, Admins and TestServers only render 'shared/http_status', locals: {code: '403', message: HttpStatusHelper::ERROR_CODE['message']['403']}, status: 403 end end # Make sure that the passed format is either xml or json # If no format is provided, default to XML def check_format # This allows us to support content negotiation if request.headers['HTTP_ACCEPT'].nil? || request.format == '*/*' request.format = 'xml' end request_format = request.format.symbol if request_format != :xml && request_format != :json # 406 is the default status code when the format is not support head :not_acceptable end end # Helper method for parsing the authentication token def parse_auth_token(token) return nil if token.nil? if token =~ /MarkUsAuth ([^\s,]+)/ $1 # return matched part else nil end end # Helper method for filtering, limit, offset # Ignores default_scope order, always order by id to be consistent # # Renders an error message and returns false if the filters are malformed def get_collection(collection) collection.order('id') .where(params[:filter]&.split(',')&.map { |filter| filter.split(':') }&.to_h) .load rescue StandardError render 'shared/http_status', locals: { code: '422', message: 'Invalid or malformed parameter values' }, status: 422 false end # Helper method handling which fields to render, given the provided default # fields and those present in params[:fields] def fields_to_render(default_fields) fields = [] # params[:fields] will match the following format: # argument,argument,argument... unless params[:fields].blank? filtered_fields = /(\w+,{0,1})+/.match(params[:fields]) unless filtered_fields.nil? filtered_fields.to_s.split(',').each do |field| field = field.to_sym fields << field if default_fields.include?(field) end end end fields = default_fields if fields.empty? fields end # Checks that the symbols provided in the array aren't blank in the params def has_missing_params?(required_params) required_params.each do |param| return true if params[param].blank? end false end def user_not_authorized render 'shared/http_status', locals: { code: '403', message: HttpStatusHelper::ERROR_CODE['message']['403'] }, status: 403 end end end # end Api module
module Api class TomatoesController < BaseController before_action :authenticate_user! def index @tomatoes = current_user.tomatoes.order_by([[:created_at, :desc]]).page params[:page] render json: Presenter::Tomatoes.new(@tomatoes) end def show @tomato = current_user.tomatoes.find(params[:id]) render json: Presenter::Tomato.new(@tomato) end def create @tomato = current_user.tomatoes.build(resource_params) if @tomato.save render status: :created, json: Presenter::Tomato.new(@tomato), location: api_tomato_url(@tomato) else render status: :unprocessable_entity, json: @tomato.errors end end def update @tomato = current_user.tomatoes.find(params[:id]) if @tomato.update_attributes(resource_params) render json: Presenter::Tomato.new(@tomato), location: api_tomato_url(@tomato) else render status: :unprocessable_entity, json: @tomato.errors end end def destroy @tomato = current_user.tomatoes.find(params[:id]) @tomato.destroy head :no_content end private def resource_params params.require(:tomato).permit(:tag_list) end end end DRY controller module Api class TomatoesController < BaseController before_action :authenticate_user! before_action :find_tomato, only: [:show, :update, :destroy] def index @tomatoes = current_user.tomatoes.order_by([[:created_at, :desc]]).page params[:page] render json: Presenter::Tomatoes.new(@tomatoes) end def show render json: Presenter::Tomato.new(@tomato) end def create @tomato = current_user.tomatoes.build(resource_params) if @tomato.save render status: :created, json: Presenter::Tomato.new(@tomato), location: api_tomato_url(@tomato) else render status: :unprocessable_entity, json: @tomato.errors end end def update if @tomato.update_attributes(resource_params) render json: Presenter::Tomato.new(@tomato), location: api_tomato_url(@tomato) else render status: :unprocessable_entity, json: @tomato.errors end end def destroy @tomato.destroy head :no_content end private def find_tomato @tomato = current_user.tomatoes.find(params[:id]) end def resource_params params.require(:tomato).permit(:tag_list) end end end
require 'sucker_punch' require 'fileutils' require 'open3' module SinatraDeployer class DeployJob include SuckerPunch::Job WORKSPACE = ENV['DEPLOYER_WORKSPACE'] || '/etc/nginx/sites-enabled' DEPLOYER_HOST = ENV['DEPLOYER_HOST'] || '127.0.0.1.xip.io' NGINX_SITES_ENABLED_DIR = ENV['NGINX_SITES_ENABLED_DIR'] || '/etc/nginx/sites-enabled' def perform(repository:, branch:, callback_url:) puts "RUNNING ASYNC === #{repository} == #{branch} == #{callback_url}" git_basename = repository.split('/').last project = File.basename(git_basename,File.extname(git_basename)) @deployment_alias = "#{project}-#{branch}" @project_dir = "#{WORKSPACE}/#{project}/#{branch}" puts "Creating #{@project_dir} if it doesn't exist already" FileUtils.mkdir_p @project_dir Dir.chdir @project_dir #TODO: No error conditions are handled in the following methods. if fetch_repository(repository, branch) && dockerup && add_nginx_config callback(callback_url, :success) else callback(callback_url, :failure) end end private def fetch_repository(repository, branch) puts "Cloning #{repository}:#{branch}" system("git clone --branch=#{branch} --depth=1 #{repository} .") end def dockerup puts "Running docker container #{@deployment_alias}" system("docker build -t #{@deployment_alias} .") && system("docker run -P --name=#{@deployment_alias} #{@deployment_alias}") end def add_nginx_config puts "Adding nginx config at #{NGINX_SITES_ENABLED_DIR}/#{@deployment_alias}" Dir.chdir(NGINX_SITES_ENABLED_DIR) do return false if File.exists?(@deployment_alias) contents <<-EOM server{ listen 80; server_name #{@deployment_alias}.#{DEPLOYER_HOST}; # host error and access log access_log /var/log/nginx/#{@deployment_alias}.access.log; error_log /var/log/nginx/#{@deployment_alias}.error.log; location / { proxy_pass http://#{get_docker_host}; } } EOM File.open(@deployment_alias, 'w') do |file| file << contents end end end def get_docker_host host = "" Open3.popen3("docker inspect --format '{{ .NetworkSettings.IPAddress }}' #{@deployment_alias}") do |i, o| output = o.read host = output.chomp end Open3.popen3("docker port #{@deployment_alias}") do |i, o| output = o.read port = output.split(':').last.chomp host += ":#{port}" end host end end end Remove docker container after running require 'sucker_punch' require 'fileutils' require 'open3' module SinatraDeployer class DeployJob include SuckerPunch::Job WORKSPACE = ENV['DEPLOYER_WORKSPACE'] || '/etc/nginx/sites-enabled' DEPLOYER_HOST = ENV['DEPLOYER_HOST'] || '127.0.0.1.xip.io' NGINX_SITES_ENABLED_DIR = ENV['NGINX_SITES_ENABLED_DIR'] || '/etc/nginx/sites-enabled' def perform(repository:, branch:, callback_url:) puts "RUNNING ASYNC === #{repository} == #{branch} == #{callback_url}" git_basename = repository.split('/').last project = File.basename(git_basename,File.extname(git_basename)) @deployment_alias = "#{project}-#{branch}" @project_dir = "#{WORKSPACE}/#{project}/#{branch}" puts "Creating #{@project_dir} if it doesn't exist already" FileUtils.mkdir_p @project_dir Dir.chdir @project_dir #TODO: No error conditions are handled in the following methods. if fetch_repository(repository, branch) && dockerup && add_nginx_config #callback(callback_url, :success) else #callback(callback_url, :failure) end end private def fetch_repository(repository, branch) puts "Cloning #{repository}:#{branch}" system("git clone --branch=#{branch} --depth=1 #{repository} .") end def dockerup puts "Running docker container #{@deployment_alias}" system("docker build -t #{@deployment_alias} .") && system("docker run -rm -P -d --name=#{@deployment_alias} #{@deployment_alias}") end def add_nginx_config puts "Adding nginx config at #{NGINX_SITES_ENABLED_DIR}/#{@deployment_alias}" Dir.chdir(NGINX_SITES_ENABLED_DIR) do return false if File.exists?(@deployment_alias) contents <<-EOM server{ listen 80; server_name #{@deployment_alias}.#{DEPLOYER_HOST}; # host error and access log access_log /var/log/nginx/#{@deployment_alias}.access.log; error_log /var/log/nginx/#{@deployment_alias}.error.log; location / { proxy_pass http://#{get_docker_host}; } } EOM File.open(@deployment_alias, 'w') do |file| file << contents end end end def get_docker_host host = "" Open3.popen3("docker inspect --format '{{ .NetworkSettings.IPAddress }}' #{@deployment_alias}") do |i, o| output = o.read host = output.chomp end Open3.popen3("docker port #{@deployment_alias}") do |i, o| output = o.read port = output.split(':').last.chomp host += ":#{port}" end host end end end
require "open-uri" class Api::V1::HooksController < ActionController::API def create # get amazon message type and topic amz_message_type = request.headers['x-amz-sns-message-type'] amz_sns_topic = request.headers['x-amz-sns-topic-arn'] #return unless !amz_sns_topic.nil? && #amz_sns_topic.to_s.downcase == 'arn:aws:sns:us-west-2:867544872691:User_Data_Updates' request_body = JSON.parse request.body.read # if this is the first time confirmation of subscription, then confirm it if amz_message_type.to_s.downcase == 'subscriptionconfirmation' send_subscription_confirmation request_body render plain: "ok" and return end if amz_message_type == "Notification" or request_body["Type"] == "Notification" if request_body['Subject'] == "Amazon SES Email Receipt Notification" process_email_notification(request_body["Message"]) render plain: "ok" and return end if request_body["Message"] == "Successfully validated SNS topic for Amazon SES event publishing." render plain: "ok" and return else process_event_notification(request_body) render plain: "ok" and return end end #process_notification(request_body) render plain: "ok" and return end private def process_email_notification(message) json_message = JSON.parse(message) json_message["receipt"] json_message["mail"]["headers"].map{|o| {o["name"]=> o["value"]}} json_message["receipt"]["action"] #=> {"type"=>"S3", # "topicArn"=>"xxxx", # "bucketName"=>"xxxx-incoming-mails", # "objectKeyPrefix"=>"mail", # "objectKey"=>"mail/xxxxx"} action = json_message["receipt"]["action"] file = AWS_CLIENT.get_object( bucket: action["bucketName"], key: action["objectKey"] ) mail = Mail.read_from_string(file.body.read) from = mail.from to = mail.to recipients = mail.recipients # ["messages+aaa@hermessenger.com"] de aqui sale el app y el mensaje! message = EmailReplyParser.parse_reply( mail.text_part.body.to_s).gsub("\n", "<br/>").force_encoding(Encoding::UTF_8) # mail.parts.last.body.to_s ) recipient_parts = URLcrypt.decode(recipients.first.split("@").first.split("+").last) app_id, conversation_id = recipient_parts.split("+") app = App.find(app_id) conversation = app.conversations.find(conversation_id) messageId = json_message["mail"]["messageId"] opts = { from: app.app_users.joins(:user).where(["users.email =?", from.first]).first, message: message, email_message_id: mail.message_id } conversation.add_message(opts) end def process_event_notification(request_body) message = parse_body_message(request_body["Message"]) track_message_for(message["eventType"].downcase, message) end def parse_body_message(body) JSON.parse(body) end def track_message_for(track_type, m) SnsReceiverJob.perform_later(track_type, m, request.remote_ip) end def send_subscription_confirmation(request_body) subscribe_url = request_body['SubscribeURL'] return nil unless !subscribe_url.to_s.empty? && !subscribe_url.nil? open subscribe_url end end reminder comment require "open-uri" class Api::V1::HooksController < ActionController::API def create # get amazon message type and topic amz_message_type = request.headers['x-amz-sns-message-type'] amz_sns_topic = request.headers['x-amz-sns-topic-arn'] #return unless !amz_sns_topic.nil? && #amz_sns_topic.to_s.downcase == 'arn:aws:sns:us-west-2:867544872691:User_Data_Updates' request_body = JSON.parse request.body.read # if this is the first time confirmation of subscription, then confirm it if amz_message_type.to_s.downcase == 'subscriptionconfirmation' send_subscription_confirmation request_body render plain: "ok" and return end if amz_message_type == "Notification" or request_body["Type"] == "Notification" if request_body['Subject'] == "Amazon SES Email Receipt Notification" process_email_notification(request_body["Message"]) render plain: "ok" and return end if request_body["Message"] == "Successfully validated SNS topic for Amazon SES event publishing." render plain: "ok" and return else process_event_notification(request_body) render plain: "ok" and return end end #process_notification(request_body) render plain: "ok" and return end private #TODO: add some tests mdfk! def process_email_notification(message) json_message = JSON.parse(message) json_message["receipt"] json_message["mail"]["headers"].map{|o| {o["name"]=> o["value"]}} json_message["receipt"]["action"] #=> {"type"=>"S3", # "topicArn"=>"xxxx", # "bucketName"=>"xxxx-incoming-mails", # "objectKeyPrefix"=>"mail", # "objectKey"=>"mail/xxxxx"} action = json_message["receipt"]["action"] file = AWS_CLIENT.get_object( bucket: action["bucketName"], key: action["objectKey"] ) mail = Mail.read_from_string(file.body.read) from = mail.from to = mail.to recipients = mail.recipients # ["messages+aaa@hermessenger.com"] de aqui sale el app y el mensaje! message = EmailReplyParser.parse_reply( mail.text_part.body.to_s).gsub("\n", "<br/>").force_encoding(Encoding::UTF_8) # mail.parts.last.body.to_s ) recipient_parts = URLcrypt.decode(recipients.first.split("@").first.split("+").last) app_id, conversation_id = recipient_parts.split("+") app = App.find(app_id) conversation = app.conversations.find(conversation_id) messageId = json_message["mail"]["messageId"] opts = { from: app.app_users.joins(:user).where(["users.email =?", from.first]).first, message: message, email_message_id: mail.message_id } conversation.add_message(opts) end def process_event_notification(request_body) message = parse_body_message(request_body["Message"]) track_message_for(message["eventType"].downcase, message) end def parse_body_message(body) JSON.parse(body) end def track_message_for(track_type, m) SnsReceiverJob.perform_later(track_type, m, request.remote_ip) end def send_subscription_confirmation(request_body) subscribe_url = request_body['SubscribeURL'] return nil unless !subscribe_url.to_s.empty? && !subscribe_url.nil? open subscribe_url end end
class Api::V1::PostsController < Api::ApiController before_action :login_required, except: [:index, :show] before_action :find_post, only: [:show, :update] resource_description do description 'Viewing and editing posts' end api :GET, '/posts', 'Load all posts optionally filtered by subject' param :q, String, required: false, desc: 'Subject search term' def index queryset = Post.order(Arel.sql('LOWER(subject) asc')) queryset = queryset.where('LOWER(subject) LIKE ?', "%#{params[:q].downcase}%") if params[:q].present? posts = paginate queryset, per_page: 25 posts = posts.select { |post| post.visible_to?(current_user) } render json: {results: posts.as_json(min: true)} end api :GET, '/posts/:id', 'Load a single post as a JSON resource' param :id, :number, required: true, desc: "Post ID" error 403, "Post is not visible to the user" error 404, "Post not found" def show render json: @post.as_json(include: [:character, :icon, :content]) end api :PATCH, '/posts/:id', 'Update a single post. Currently only supports saving the private note for an author.' header 'Authorization', 'Authorization token for a user in the format "Authorization" : "Bearer [token]"', required: true param :id, :number, required: true, desc: "Post ID" param :private_note, String, required: true, desc: "Author's private notes about this post" error 403, "Post is not visible to the user" error 404, "Post not found" error 422, "Invalid parameters provided" def update author = @post.author_for(current_user) unless author.present? access_denied return end unless author.update(private_note: params[:private_note]) error = {message: 'Post could not be updated.'} render json: {errors: [error]}, status: :unprocessable_entity return end render json: {private_note: helpers.sanitize_written_content(params[:private_note])} end api :POST, '/posts/reorder', 'Update the order of posts. This is an unstable feature, and may be moved or renamed; it should not be trusted.' error 401, "You must be logged in" error 403, "Board is not editable by the user" error 404, "Post IDs could not be found" error 422, "Invalid parameters provided" param :ordered_post_ids, Array, allow_blank: false param :section_id, :number, required: false def reorder section_id = params[:section_id] ? params[:section_id].to_i : nil post_ids = params[:ordered_post_ids].map(&:to_i).uniq posts = Post.where(id: post_ids) posts_count = posts.count unless posts_count == post_ids.count missing_posts = post_ids - posts.pluck(:id) error = {message: "Some posts could not be found: #{missing_posts * ', '}"} render json: {errors: [error]}, status: :not_found and return end boards = Board.where(id: posts.select(:board_id).distinct.pluck(:board_id)) unless boards.count == 1 error = {message: 'Posts must be from one board'} render json: {errors: [error]}, status: :unprocessable_entity and return end board = boards.first access_denied and return unless board.editable_by?(current_user) post_section_ids = posts.select(:section_id).distinct.pluck(:section_id) unless post_section_ids == [section_id] && (section_id.nil? || BoardSection.where(id: section_id, board_id: board.id).exists?) error = {message: 'Posts must be from one specified section in the board, or no section'} render json: {errors: [error]}, status: :unprocessable_entity and return end Post.transaction do posts = posts.sort_by {|post| post_ids.index(post.id) } posts.each_with_index do |post, index| next if post.section_order == index post.update(section_order: index) end other_posts = Post.where(board_id: board.id, section_id: section_id).where.not(id: post_ids).ordered_in_section other_posts.each_with_index do |post, i| index = i + posts_count next if post.section_order == index post.update(section_order: index) end end posts = Post.where(board_id: board.id, section_id: section_id) render json: {post_ids: posts.ordered_in_section.pluck(:id)} end private def find_post return unless (@post = find_object(Post)) access_denied unless @post.visible_to?(current_user) end end Make api posts#index use visible_to scope class Api::V1::PostsController < Api::ApiController before_action :login_required, except: [:index, :show] before_action :find_post, only: [:show, :update] resource_description do description 'Viewing and editing posts' end api :GET, '/posts', 'Load all posts optionally filtered by subject' param :q, String, required: false, desc: 'Subject search term' def index queryset = Post.order(Arel.sql('LOWER(subject) asc')) queryset = queryset.where('LOWER(subject) LIKE ?', "%#{params[:q].downcase}%") if params[:q].present? posts = paginate queryset, per_page: 25 posts = posts.visible_to(current_user) render json: {results: posts.as_json(min: true)} end api :GET, '/posts/:id', 'Load a single post as a JSON resource' param :id, :number, required: true, desc: "Post ID" error 403, "Post is not visible to the user" error 404, "Post not found" def show render json: @post.as_json(include: [:character, :icon, :content]) end api :PATCH, '/posts/:id', 'Update a single post. Currently only supports saving the private note for an author.' header 'Authorization', 'Authorization token for a user in the format "Authorization" : "Bearer [token]"', required: true param :id, :number, required: true, desc: "Post ID" param :private_note, String, required: true, desc: "Author's private notes about this post" error 403, "Post is not visible to the user" error 404, "Post not found" error 422, "Invalid parameters provided" def update author = @post.author_for(current_user) unless author.present? access_denied return end unless author.update(private_note: params[:private_note]) error = {message: 'Post could not be updated.'} render json: {errors: [error]}, status: :unprocessable_entity return end render json: {private_note: helpers.sanitize_written_content(params[:private_note])} end api :POST, '/posts/reorder', 'Update the order of posts. This is an unstable feature, and may be moved or renamed; it should not be trusted.' error 401, "You must be logged in" error 403, "Board is not editable by the user" error 404, "Post IDs could not be found" error 422, "Invalid parameters provided" param :ordered_post_ids, Array, allow_blank: false param :section_id, :number, required: false def reorder section_id = params[:section_id] ? params[:section_id].to_i : nil post_ids = params[:ordered_post_ids].map(&:to_i).uniq posts = Post.where(id: post_ids) posts_count = posts.count unless posts_count == post_ids.count missing_posts = post_ids - posts.pluck(:id) error = {message: "Some posts could not be found: #{missing_posts * ', '}"} render json: {errors: [error]}, status: :not_found and return end boards = Board.where(id: posts.select(:board_id).distinct.pluck(:board_id)) unless boards.count == 1 error = {message: 'Posts must be from one board'} render json: {errors: [error]}, status: :unprocessable_entity and return end board = boards.first access_denied and return unless board.editable_by?(current_user) post_section_ids = posts.select(:section_id).distinct.pluck(:section_id) unless post_section_ids == [section_id] && (section_id.nil? || BoardSection.where(id: section_id, board_id: board.id).exists?) error = {message: 'Posts must be from one specified section in the board, or no section'} render json: {errors: [error]}, status: :unprocessable_entity and return end Post.transaction do posts = posts.sort_by {|post| post_ids.index(post.id) } posts.each_with_index do |post, index| next if post.section_order == index post.update(section_order: index) end other_posts = Post.where(board_id: board.id, section_id: section_id).where.not(id: post_ids).ordered_in_section other_posts.each_with_index do |post, i| index = i + posts_count next if post.section_order == index post.update(section_order: index) end end posts = Post.where(board_id: board.id, section_id: section_id) render json: {post_ids: posts.ordered_in_section.pluck(:id)} end private def find_post return unless (@post = find_object(Post)) access_denied unless @post.visible_to?(current_user) end end
Basic start on the Windows communication protocol require 'Win32API' require 'skype/communication/protocol' class Skype module Communication # Utilises the Windows API to send and receive Window Messages to/from Skype. # # This protocol is only available on Windows and Cygwin. class Windows include Skype::Communication::Protocol def initialize # Setup Win32 API calls @send_message = Win32API.new("user32", "SendMessage", %w{L L L L}, 'L') @register_window_message = Win32API.new("user32", "RegisterWindowMessage", %w{P}, 'I') # Get the message id's for the Skype Control messages @api_discover_message_id = register_window_message('SkypeControlAPIDiscover') @api_attach_message_id = register_window_message('SkypeControlAPIAttach') end private # Ruby handle to the Win32API function SendMessage. # # @see http://msdn.microsoft.com/en-us/library/windows/desktop/ms644950.aspx # @api win32 # @param [Integer] window_handle # @param [Integer] message_id # @param [Integer] wParam # @param [Integer] lParam # @return [Integer] def send_message(window_handle, message_id, wParam, lParam) @send_message.Call(window_handle, message_id, wParam, lParam) end # Ruby handle to the Win32API function RegisterWindowMessage. # # @see http://msdn.microsoft.com/en-us/library/windows/desktop/ms644947.aspx # @api win32 # @param [String] message_name # @return [Integer] def register_window_message(message_name) @register_window_message.Call(message_name) end end end end
class Api::V1::PostsController < Api::V1::BaseController def index authenticate_request! offset = params[:offset] || 0 posts = Post.where(user: @current_user.following).order('created_at DESC').limit(20).offset(offset) last_date = posts[-1].created_at first_date = posts[0].created_at @current_user.following.each { |user| user.reposts.where(created_at: last_date..first_date).each { |post| posts << post } } posts = posts.map { |post| Api::V1::PostSerializer.new(post) } render(json: posts.to_json) end def find search = params[:content] posts = Post.all.where("content LIKE :query", query: "%#{search}%") posts = posts.map { |post| Api::V1::PostSerializer.new(post) } render(json: posts.to_json) end def show post = Post.find(params[:id]) render(json: Api::V1::PostSerializer.new(post).to_json) end def like authenticate_request! if !Post.like?(@current_user.id, params[:id]) post = Post.find_by(id: params[:id]) post.like(@current_user.id) render nothing: true, :status => :ok else render :json => { :errors => 'Like realtion already exists' } end end def unlike authenticate_request! if Post.like?(@current_user.id, params[:id]) post = Post.find_by(id: params[:id]) post.unlike(@current_user.id) render nothing: true, :status => :ok else render :json => { :errors => 'Like realtion does not exists' } end end def create authenticate_request! params = post_params params["user_id"] = @current_user.id @post = Post.new(params) if @post.save render json: Api::V1::PostSerializer.new(@post).to_json, :status => :created else render :json => { :errors => @post.errors.messages }, :status => :bad_request end end # def update # @user = User.update(params[:id], user_params) # if @user.save # render :nothing => true, :status => :created # else # render :json => { :errors => @user.errors.messages }, :status => :bad_request # end # end def repost authenticate_request! user_id = @current_user.id Post.find_by(id: params[:id]).repost(user_id) render nothing: true, :status => :ok end def unrepost authenticate_request! user_id = @current_user.id Post.find_by(id: params[:id]).unrepost(user_id) render nothing: true, :status => :ok end private def post_params params.require(:post).permit(:content, :image_url, :mood_id) end end :bug: Add personnal posts in index class Api::V1::PostsController < Api::V1::BaseController def index authenticate_request! offset = params[:offset] || 0 users = @current_user.following users.unshift(@current_user) posts = Post.where(user: @current_user.following).order('created_at DESC').limit(20).offset(offset) last_date = posts[-1].created_at first_date = posts[0].created_at @current_user.following.each { |user| user.reposts.where(created_at: last_date..first_date).each { |post| posts << post } } posts = posts.map { |post| Api::V1::PostSerializer.new(post) } render(json: posts.to_json) end def find search = params[:content] posts = Post.all.where("content LIKE :query", query: "%#{search}%") posts = posts.map { |post| Api::V1::PostSerializer.new(post) } render(json: posts.to_json) end def show post = Post.find(params[:id]) render(json: Api::V1::PostSerializer.new(post).to_json) end def like authenticate_request! if !Post.like?(@current_user.id, params[:id]) post = Post.find_by(id: params[:id]) post.like(@current_user.id) render nothing: true, :status => :ok else render :json => { :errors => 'Like realtion already exists' } end end def unlike authenticate_request! if Post.like?(@current_user.id, params[:id]) post = Post.find_by(id: params[:id]) post.unlike(@current_user.id) render nothing: true, :status => :ok else render :json => { :errors => 'Like realtion does not exists' } end end def create authenticate_request! params = post_params params["user_id"] = @current_user.id @post = Post.new(params) if @post.save render json: Api::V1::PostSerializer.new(@post).to_json, :status => :created else render :json => { :errors => @post.errors.messages }, :status => :bad_request end end # def update # @user = User.update(params[:id], user_params) # if @user.save # render :nothing => true, :status => :created # else # render :json => { :errors => @user.errors.messages }, :status => :bad_request # end # end def repost authenticate_request! user_id = @current_user.id Post.find_by(id: params[:id]).repost(user_id) render nothing: true, :status => :ok end def unrepost authenticate_request! user_id = @current_user.id Post.find_by(id: params[:id]).unrepost(user_id) render nothing: true, :status => :ok end private def post_params params.require(:post).permit(:content, :image_url, :mood_id) end end
require 'net/http' require 'json' require 'httparty' class SlackSidekiq class << self # def configure(options={}) # @@webhook_url = options[:webhook_url] # end def configure(webhook_url) @@webhook_url = webhook_url end def post text = 'hello' attachments = [ { "fallback" => "Required plain-text summary of the attachment.", "color" => "#36a64f", "pretext" => "Optional text that appears above the attachment block", "author_name" => "Bobby Tables", "author_link" => "http://flickr.com/bobby/", "author_icon" => "http://flickr.com/icons/bobby.jpg", "title" => "Slack API Documentation", "title_link" => "https://api.slack.com/", "text" => "Optional text that appears within the attachment", "fields" => [ { "title" => "Priority", "value" => "High", "short" => false } ], "image_url" => "http://my-website.com/path/to/image.jpg", "thumb_url" => "http://example.com/path/to/thumb.png" } ] body = {text: text, attachments: attachments}.to_json HTTParty.post(@@webhook_url, body: body, attachments: attachments) end end end better shade of green require 'net/http' require 'json' require 'httparty' class SlackSidekiq class << self # def configure(options={}) # @@webhook_url = options[:webhook_url] # end def configure(webhook_url) @@webhook_url = webhook_url end def post text = 'hello' attachments = [ { "fallback" => "Required plain-text summary of the attachment.", "color" => "#00ff66", "title" => "Sidekiq Batch Completed", "text" => "Optional text that appears within the attachment", "fields" => [ { "title" => "Priority", "value" => "High", "short" => false } ], "image_url" => "http://my-website.com/path/to/image.jpg", "thumb_url" => "http://example.com/path/to/thumb.png" } ] body = {attachments: attachments}.to_json HTTParty.post(@@webhook_url, body: body) end end end
class Api::V1::StoreController < Api::V1::ApiController require 'digest/md5' require 'net/http' require 'uri' skip_before_action :authenticate_member! def create error_store = ErrorStore::Error.new(request).create! rescue ErrorStore::MissingCredentials => e _not_allowed! e.message end # if error_data # ErrorStore.save_to_database(error_data) # else # _not_allowed! 'The data sent is not valid' # end # subscriber = current_site.subscribers.create_with(name: "Name for subscriber").find_or_create_by!(email: error_params["user"]["email"], website_id: current_site.id) # if error_params["stacktrace"].blank? # checksum = Digest::MD5.hexdigest(error_params["platform"] + error_params["culprit"] + error_params["message"]) # elsif !error_params["exception"].blank? # checksum = Digest::MD5.hexdigest(error_params["exception"].to_s) # else # checksum = Digest::MD5.hexdigest(error_params["stacktrace"].to_s) # end # groupedissue = GroupedIssue.find_by_data_and_website_id(checksum,current_site.id) # if groupedissue.nil? # @group = GroupedIssue.create_with( # issue_logger: error_params["logger"], # view: error_params["request"].to_s.gsub('=>', ':'), # status: 3,platform: error_params["platform"], # message: error_params["message"], # times_seen: 1, # first_seen: Time.now, # last_seen: Time.now # ) # else # groupedissue.update_attributes( # :times_seen => groupedissue.times_seen + 1, # :last_seen => Time.now # ) # end # @group = GroupedIssue.create_with( # issue_logger: error_params["logger"], # view: error_params["request"].to_s.gsub('=>', ':'), # status: 3,platform: error_params["platform"], # message: error_params["message"] # ).find_or_create_by(data: checksum, website_id: current_site.id) # if error_params.has_key?("stacktrace") # stacktrace = error_params["stacktrace"] # elsif error_params.has_key?("exception") # stacktrace = error_params["exception"]["values"].first["stacktrace"] # end # source_code = open_url_content(stacktrace) # @error = Issue.create_with( # description: stacktracke["frames"].to_s.gsub('=>', ':'), # page_title: error_params["extra"]["title"], # platform: error_params["platform"], # group_id: @group.id # # stacktracke["frames"].to_s.gsub(/=>|\./, ":") # ).find_or_create_by(data: source_code, subscriber_id: subscriber.id) # message = Message.create(content: error_params["message"], issue_id: @error.id) # end # def open_url_content(stacktrace) # nr = 0 # content = [] # stacktrace["frames"].each do |frame| # nr +=1 # content.push({"content_#{nr}" => Net::HTTP.get(URI.parse(frame["filename"]))}) # # content += "," if nr > 0 # end # content.to_s.gsub('=>', ':') # end private end call class method create! on store_controller class Api::V1::StoreController < Api::V1::ApiController require 'digest/md5' require 'net/http' require 'uri' skip_before_action :authenticate_member! def create error_store = ErrorStore::Error.create!(request) rescue ErrorStore::MissingCredentials => e _not_allowed! e.message end # if error_data # ErrorStore.save_to_database(error_data) # else # _not_allowed! 'The data sent is not valid' # end # subscriber = current_site.subscribers.create_with(name: "Name for subscriber").find_or_create_by!(email: error_params["user"]["email"], website_id: current_site.id) # if error_params["stacktrace"].blank? # checksum = Digest::MD5.hexdigest(error_params["platform"] + error_params["culprit"] + error_params["message"]) # elsif !error_params["exception"].blank? # checksum = Digest::MD5.hexdigest(error_params["exception"].to_s) # else # checksum = Digest::MD5.hexdigest(error_params["stacktrace"].to_s) # end # groupedissue = GroupedIssue.find_by_data_and_website_id(checksum,current_site.id) # if groupedissue.nil? # @group = GroupedIssue.create_with( # issue_logger: error_params["logger"], # view: error_params["request"].to_s.gsub('=>', ':'), # status: 3,platform: error_params["platform"], # message: error_params["message"], # times_seen: 1, # first_seen: Time.now, # last_seen: Time.now # ) # else # groupedissue.update_attributes( # :times_seen => groupedissue.times_seen + 1, # :last_seen => Time.now # ) # end # @group = GroupedIssue.create_with( # issue_logger: error_params["logger"], # view: error_params["request"].to_s.gsub('=>', ':'), # status: 3,platform: error_params["platform"], # message: error_params["message"] # ).find_or_create_by(data: checksum, website_id: current_site.id) # if error_params.has_key?("stacktrace") # stacktrace = error_params["stacktrace"] # elsif error_params.has_key?("exception") # stacktrace = error_params["exception"]["values"].first["stacktrace"] # end # source_code = open_url_content(stacktrace) # @error = Issue.create_with( # description: stacktracke["frames"].to_s.gsub('=>', ':'), # page_title: error_params["extra"]["title"], # platform: error_params["platform"], # group_id: @group.id # # stacktracke["frames"].to_s.gsub(/=>|\./, ":") # ).find_or_create_by(data: source_code, subscriber_id: subscriber.id) # message = Message.create(content: error_params["message"], issue_id: @error.id) # end # def open_url_content(stacktrace) # nr = 0 # content = [] # stacktrace["frames"].each do |frame| # nr +=1 # content.push({"content_#{nr}" => Net::HTTP.get(URI.parse(frame["filename"]))}) # # content += "," if nr > 0 # end # content.to_s.gsub('=>', ':') # end private end
# coding: utf-8 module UIAutoMonkey module CommandHelper require 'open3' def is_simulator deviceinfo = instruments_deviceinfo(device) if deviceinfo.include? "Simulator" true else false end end def shell(cmds) puts "Shell: #{cmds.inspect}" Open3.popen3(*cmds) do |stdin, stdout, stderr| stdin.close return stdout.read end end # def run_process(cmds) # puts "Run: #{cmds.inspect}" # Kernel.system(cmds[0], *cmds[1..-1]) # end def relaunch_app(device,app) if is_simulator `xcrun simctl launch #{device} #{app} >/dev/null 2>&1 &` else `idevicedebug -u #{device} run #{app} >/dev/null 2>&1 &` end end def run_process(cmds) puts "Run: #{cmds.inspect}" device = cmds[2] app = cmds[-7] Open3.popen3(*cmds) do |stdin, stdout, stderr, thread| @tmpline = "" stdin.close app_hang_monitor_thread = Thread.start{ sleep 30 while true current_line = @tmpline sleep 30 after_sleep_line = @tmpline if current_line == after_sleep_line puts "WARN: no response in log, trigger re-launch action." relaunch_app(device, app) end end } instruments_stderr_thread = Thread.start{ stderr.each do |line| puts line end } stdout.each do |line| @tmpline = line.strip puts @tmpline if @tmpline =~ /MonkeyTest finish/ || @tmpline =~ /Script was stopped by the user/ app_hang_monitor_thread.kill end end app_hang_monitor_thread.kill instruments_stderr_thread.kill end end def kill_all(process_name, signal=nil) signal = signal ? "-#{signal}" : '' # puts "killall #{signal} #{process_name}" Kernel.system("killall #{signal} '#{process_name}' >/dev/null 2>&1") end def xcode_path @xcode_path ||= shell(%w(xcode-select -print-path)).strip end end end xcode7通过instruments -s devices查看设备没有Simulator关键字,兼容xcode7 # coding: utf-8 module UIAutoMonkey module CommandHelper require 'open3' def instruments_deviceinfo(device) `"instruments" -s devices | grep "#{device}"`.strip end def is_simulator deviceinfo = instruments_deviceinfo(device) if deviceinfo.include? "-" true else false end end def shell(cmds) puts "Shell: #{cmds.inspect}" Open3.popen3(*cmds) do |stdin, stdout, stderr| stdin.close return stdout.read end end # def run_process(cmds) # puts "Run: #{cmds.inspect}" # Kernel.system(cmds[0], *cmds[1..-1]) # end def relaunch_app(device,app) if is_simulator `xcrun simctl launch #{device} #{app} >/dev/null 2>&1 &` else `idevicedebug -u #{device} run #{app} >/dev/null 2>&1 &` end end def run_process(cmds) puts "Run: #{cmds.inspect}" device = cmds[2] app = cmds[-7] Open3.popen3(*cmds) do |stdin, stdout, stderr, thread| @tmpline = "" stdin.close app_hang_monitor_thread = Thread.start{ sleep 30 while true current_line = @tmpline sleep 30 after_sleep_line = @tmpline if current_line == after_sleep_line puts "WARN: no response in log, trigger re-launch action." relaunch_app(device, app) end end } instruments_stderr_thread = Thread.start{ stderr.each do |line| puts line end } stdout.each do |line| @tmpline = line.strip puts @tmpline if @tmpline =~ /MonkeyTest finish/ || @tmpline =~ /Script was stopped by the user/ app_hang_monitor_thread.kill end end app_hang_monitor_thread.kill instruments_stderr_thread.kill end end def kill_all(process_name, signal=nil) signal = signal ? "-#{signal}" : '' # puts "killall #{signal} #{process_name}" Kernel.system("killall #{signal} '#{process_name}' >/dev/null 2>&1") end def xcode_path @xcode_path ||= shell(%w(xcode-select -print-path)).strip end end end
module Api module V2 class PrintController < ApiController include PaasS3 before_action :set_up_s3_bucket def index @result = filter_by(/^UK-Trade-Tariff-/).sort_by(&:date).reverse render_result end def chapters @result = filter_by(%r{^chapters/}).sort_by(&:id) render_result end def latest @result = filter_by(/^UK-Trade-Tariff-/).max_by(&:date) render_result end private def set_up_s3_bucket @bucket = initialize_s3 end def printed_pdf(obj) pdf = Print.new pdf.id = obj.key pdf.url = url(obj.key) pdf.date = obj.last_modified pdf end def url(pdf_file_path) initialize_s3(pdf_file_path) @s3_obj.public_url end def render_result @result = [@result] unless @result.is_a?(Array) render json: Api::V2::PrintSerializer.new(@result).serializable_hash end def filter_by(filter) @bucket.objects.select { |f| f.key =~ filter } .map { |obj| printed_pdf(obj) } end end end end [api v2] Fix pdf api to return valid latest pdf links module Api module V2 class PrintController < ApiController include PaasS3 before_action :set_up_s3_bucket def index @result = filter_by(/UK-Trade-Tariff-/).sort_by(&:date).reverse render_result end def chapters @result = filter_by(%r{^chapters/}).sort_by(&:id) render_result end def latest @result = filter_by(/UK-Trade-Tariff-latest/).max_by(&:date) render_result end private def set_up_s3_bucket @bucket = initialize_s3 end def printed_pdf(obj) pdf = Print.new pdf.id = obj.key pdf.url = url(obj.key) pdf.date = obj.last_modified pdf end def url(pdf_file_path) initialize_s3(pdf_file_path) @s3_obj.public_url end def render_result @result = [@result] unless @result.is_a?(Array) render json: Api::V2::PrintSerializer.new(@result).serializable_hash end def filter_by(filter) @bucket.objects.select { |f| f.key =~ filter } .map { |obj| printed_pdf(obj) } end end end end
module Spaceship module Tunes # Represents an editable version of an iTunes Connect Application # This can either be the live or the edit version retrieved via the app class AppVersion < TunesBase # @return (Spaceship::Tunes::Application) A reference to the application # this version is for attr_accessor :application # @return (String) The version number of this version attr_accessor :version # @return (String) The copyright information of this app attr_accessor :copyright # @return (Spaceship::Tunes::AppStatus) What's the current status of this app # e.g. Waiting for Review, Ready for Sale, ... attr_reader :app_status # @return (Bool) Is that the version that's currently available in the App Store? attr_accessor :is_live # Categories (e.g. MZGenre.Business) attr_accessor :primary_category attr_accessor :primary_first_sub_category attr_accessor :primary_second_sub_category attr_accessor :secondary_category attr_accessor :secondary_first_sub_category attr_accessor :secondary_second_sub_category # @return (String) App Status (e.g. 'readyForSale'). You should use `app_status` instead attr_accessor :raw_status # @return (Bool) attr_accessor :can_reject_version # @return (Bool) attr_accessor :can_prepare_for_upload # @return (Bool) attr_accessor :can_send_version_live # @return (Bool) Should the app automatically be released once it's approved? attr_accessor :release_on_approval # @return (Bool) attr_accessor :can_beta_test # @return (Bool) Does the binary contain a watch binary? attr_accessor :supports_apple_watch # @return (String) URL to the full resolution 1024x1024 app icon attr_accessor :app_icon_url # @return (String) Name of the original file attr_accessor :app_icon_original_name # @return (String) URL to the full resolution 1024x1024 app icon attr_accessor :watch_app_icon_url # @return (String) Name of the original file attr_accessor :watch_app_icon_original_name # @return (Integer) a unqiue ID for this version generated by iTunes Connect attr_accessor :version_id #### # App Review Information #### # @return (String) App Review Information First Name attr_accessor :review_first_name # @return (String) App Review Information Last Name attr_accessor :review_last_name # @return (String) App Review Information Phone Number attr_accessor :review_phone_number # @return (String) App Review Information Email Address attr_accessor :review_email # @return (String) App Review Information Demo Account User Name attr_accessor :review_demo_user # @return (String) App Review Information Demo Account Password attr_accessor :review_demo_password # @return (String) App Review Information Notes attr_accessor :review_notes #### # Localized values #### # @return (Array) Raw access the all available languages. You shouldn't use it probbaly attr_accessor :languages # @return (Hash) A hash representing the app name in all languages attr_reader :name # @return (Hash) A hash representing the keywords in all languages attr_reader :keywords # @return (Hash) A hash representing the description in all languages attr_reader :description # @return (Hash) The changelog attr_reader :release_notes # @return (Hash) A hash representing the keywords in all languages attr_reader :privacy_url # @return (Hash) A hash representing the keywords in all languages attr_reader :support_url # @return (Hash) A hash representing the keywords in all languages attr_reader :marketing_url # @return (Hash) Represents the screenshots of this app version (read-only) attr_reader :screenshots attr_mapping({ 'canBetaTest' => :can_beta_test, 'canPrepareForUpload' => :can_prepare_for_upload, 'canRejectVersion' => :can_reject_version, 'canSendVersionLive' => :can_send_version_live, 'copyright.value' => :copyright, 'details.value' => :languages, 'largeAppIcon.value.originalFileName' => :app_icon_original_name, 'largeAppIcon.value.url' => :app_icon_url, 'primaryCategory.value' => :primary_category, 'primaryFirstSubCategory.value' => :primary_first_sub_category, 'primarySecondSubCategory.value' => :primary_second_sub_category, 'releaseOnApproval.value' => :release_on_approval, 'secondaryCategory.value' => :secondary_category, 'secondaryFirstSubCategory.value' => :secondary_first_sub_category, 'secondarySecondSubCategory.value' => :secondary_second_sub_category, 'status' => :raw_status, 'supportsAppleWatch' => :supports_apple_watch, 'versionId' => :version_id, 'version.value' => :version, 'watchAppIcon.value.originalFileName' => :watch_app_icon_original_name, 'watchAppIcon.value.url' => :watch_app_icon_url, # App Review Information 'appReviewInfo.firstName.value' => :review_first_name, 'appReviewInfo.lastName.value' => :review_last_name, 'appReviewInfo.phoneNumber.value' => :review_phone_number, 'appReviewInfo.emailAddress.value' => :review_email, 'appReviewInfo.reviewNotes.value' => :review_notes, 'appReviewInfo.userName.value' => :review_demo_user, 'appReviewInfo.password.value' => :review_demo_password }) class << self # Create a new object based on a hash. # This is used to create a new object based on the server response. def factory(attrs) obj = self.new(attrs) obj.unfold_languages return obj end # @param application (Spaceship::Tunes::Application) The app this version is for # @param app_id (String) The unique Apple ID of this app # @param is_live (Boolean) Is that the version that's live in the App Store? def find(application, app_id, is_live = false) attrs = client.app_version(app_id, is_live) attrs.merge!(application: application) attrs.merge!(is_live: is_live) return self.factory(attrs) end end # @return (Bool) Is that version currently available in the App Store? # rubocop:disable Style/PredicateName def is_live? is_live end # rubocop:enable Style/PredicateName # Call this method to make sure the given languages are available for this app # You should call this method before accessing the name, description and other localized values # This will create the new language if it's not available yet and do nothing if everything's there # def create_languages!(languages) # raise "Please pass an array" unless languages.kind_of?Array # copy_from = self.languages.first # languages.each do |language| # # First, see if it's already available # found = self.languages.find do |local| # local['language'] == language # end # unless found # new_language = copy_from.dup # new_language['language'] = language # [:description, :releaseNotes, :keywords].each do |key| # new_language[key.to_s]['value'] = nil # end # self.languages << new_language # unfold_languages # # Now we need to set a useless `pageLanguageValue` value because iTC says so, after adding a new version # self.languages.each do |current| # current['pageLanguageValue'] = current['language'] # end # end # end # languages # end # Push all changes that were made back to iTunes Connect def save! client.update_app_version!(application.apple_id, is_live?, raw_data) end # @return (String) An URL to this specific resource. You can enter this URL into your browser def url "https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/#{self.application.apple_id}/" + (self.is_live? ? "cur" : "") end # Private methods def setup # Properly parse the AppStatus status = raw_data['status'] @app_status = Tunes::AppStatus.get_from_string(status) # Setup the screenshots @screenshots = {} raw_data['details']['value'].each do |row| # Now that's one language right here @screenshots[row['language']] = setup_screenshots(row) end end # Prefill name, keywords, etc... def unfold_languages { name: :name, keywords: :keywords, description: :description, privacyURL: :privacy_url, supportURL: :support_url, marketingURL: :marketing_url, releaseNotes: :release_notes }.each do |json, attribute| instance_variable_set("@#{attribute}".to_sym, LanguageItem.new(json, languages)) end end # These methods takes care of properly parsing values that # are not returned in the right format, e.g. boolean as string def release_on_approval super == 'true' end def supports_apple_watch !super.nil? end def primary_category=(value) value = "MZGenre.#{value}" unless value.include? "MZGenre" super(value) end def primary_first_sub_category=(value) value = "MZGenre.#{value}" unless value.include? "MZGenre" super(value) end def primary_second_sub_category=(value) value = "MZGenre.#{value}" unless value.include? "MZGenre" super(value) end def secondary_category=(value) value = "MZGenre.#{value}" unless value.include? "MZGenre" super(value) end def secondary_first_sub_category=(value) value = "MZGenre.#{value}" unless value.include? "MZGenre" super(value) end def secondary_second_sub_category=(value) value = "MZGenre.#{value}" unless value.include? "MZGenre" super(value) end private # generates the nested data structure to represent screenshots def setup_screenshots(row) screenshots = row.fetch('screenshots', {}).fetch('value', nil) return [] unless screenshots result = [] screenshots.each do |device_type, value| value['value'].each do |screenshot| screenshot = screenshot['value'] result << Tunes::AppScreenshot.new({ url: screenshot['url'], thumbnail_url: screenshot['thumbNailUrl'], sort_order: screenshot['sortOrder'], original_file_name: screenshot['originalFileName'], device_type: device_type, language: row['language'] }) end end return result end end end end Added analytics interface to app version module Spaceship module Tunes # Represents an editable version of an iTunes Connect Application # This can either be the live or the edit version retrieved via the app class AppVersion < TunesBase # @return (Spaceship::Tunes::Application) A reference to the application # this version is for attr_accessor :application # @return (String) The version number of this version attr_accessor :version # @return (String) The copyright information of this app attr_accessor :copyright # @return (Spaceship::Tunes::AppStatus) What's the current status of this app # e.g. Waiting for Review, Ready for Sale, ... attr_reader :app_status # @return (Bool) Is that the version that's currently available in the App Store? attr_accessor :is_live # Categories (e.g. MZGenre.Business) attr_accessor :primary_category attr_accessor :primary_first_sub_category attr_accessor :primary_second_sub_category attr_accessor :secondary_category attr_accessor :secondary_first_sub_category attr_accessor :secondary_second_sub_category # @return (String) App Status (e.g. 'readyForSale'). You should use `app_status` instead attr_accessor :raw_status # @return (Bool) attr_accessor :can_reject_version # @return (Bool) attr_accessor :can_prepare_for_upload # @return (Bool) attr_accessor :can_send_version_live # @return (Bool) Should the app automatically be released once it's approved? attr_accessor :release_on_approval # @return (Bool) attr_accessor :can_beta_test # @return (Bool) Does the binary contain a watch binary? attr_accessor :supports_apple_watch # @return (String) URL to the full resolution 1024x1024 app icon attr_accessor :app_icon_url # @return (String) Name of the original file attr_accessor :app_icon_original_name # @return (String) URL to the full resolution 1024x1024 app icon attr_accessor :watch_app_icon_url # @return (String) Name of the original file attr_accessor :watch_app_icon_original_name # @return (Integer) a unqiue ID for this version generated by iTunes Connect attr_accessor :version_id #### # App Review Information #### # @return (String) App Review Information First Name attr_accessor :review_first_name # @return (String) App Review Information Last Name attr_accessor :review_last_name # @return (String) App Review Information Phone Number attr_accessor :review_phone_number # @return (String) App Review Information Email Address attr_accessor :review_email # @return (String) App Review Information Demo Account User Name attr_accessor :review_demo_user # @return (String) App Review Information Demo Account Password attr_accessor :review_demo_password # @return (String) App Review Information Notes attr_accessor :review_notes #### # Localized values #### # @return (Array) Raw access the all available languages. You shouldn't use it probbaly attr_accessor :languages # @return (Hash) A hash representing the app name in all languages attr_reader :name # @return (Hash) A hash representing the keywords in all languages attr_reader :keywords # @return (Hash) A hash representing the description in all languages attr_reader :description # @return (Hash) The changelog attr_reader :release_notes # @return (Hash) A hash representing the keywords in all languages attr_reader :privacy_url # @return (Hash) A hash representing the keywords in all languages attr_reader :support_url # @return (Hash) A hash representing the keywords in all languages attr_reader :marketing_url # @return (Hash) Represents the screenshots of this app version (read-only) attr_reader :screenshots attr_mapping({ 'canBetaTest' => :can_beta_test, 'canPrepareForUpload' => :can_prepare_for_upload, 'canRejectVersion' => :can_reject_version, 'canSendVersionLive' => :can_send_version_live, 'copyright.value' => :copyright, 'details.value' => :languages, 'largeAppIcon.value.originalFileName' => :app_icon_original_name, 'largeAppIcon.value.url' => :app_icon_url, 'primaryCategory.value' => :primary_category, 'primaryFirstSubCategory.value' => :primary_first_sub_category, 'primarySecondSubCategory.value' => :primary_second_sub_category, 'releaseOnApproval.value' => :release_on_approval, 'secondaryCategory.value' => :secondary_category, 'secondaryFirstSubCategory.value' => :secondary_first_sub_category, 'secondarySecondSubCategory.value' => :secondary_second_sub_category, 'status' => :raw_status, 'supportsAppleWatch' => :supports_apple_watch, 'versionId' => :version_id, 'version.value' => :version, 'watchAppIcon.value.originalFileName' => :watch_app_icon_original_name, 'watchAppIcon.value.url' => :watch_app_icon_url, # App Review Information 'appReviewInfo.firstName.value' => :review_first_name, 'appReviewInfo.lastName.value' => :review_last_name, 'appReviewInfo.phoneNumber.value' => :review_phone_number, 'appReviewInfo.emailAddress.value' => :review_email, 'appReviewInfo.reviewNotes.value' => :review_notes, 'appReviewInfo.userName.value' => :review_demo_user, 'appReviewInfo.password.value' => :review_demo_password }) class << self # Create a new object based on a hash. # This is used to create a new object based on the server response. def factory(attrs) obj = self.new(attrs) obj.unfold_languages return obj end # @param application (Spaceship::Tunes::Application) The app this version is for # @param app_id (String) The unique Apple ID of this app # @param is_live (Boolean) Is that the version that's live in the App Store? def find(application, app_id, is_live = false) attrs = client.app_version(app_id, is_live) attrs.merge!(application: application) attrs.merge!(is_live: is_live) return self.factory(attrs) end def analytics return client.app_analytics end end # @return (Bool) Is that version currently available in the App Store? # rubocop:disable Style/PredicateName def is_live? is_live end # rubocop:enable Style/PredicateName # Call this method to make sure the given languages are available for this app # You should call this method before accessing the name, description and other localized values # This will create the new language if it's not available yet and do nothing if everything's there # def create_languages!(languages) # raise "Please pass an array" unless languages.kind_of?Array # copy_from = self.languages.first # languages.each do |language| # # First, see if it's already available # found = self.languages.find do |local| # local['language'] == language # end # unless found # new_language = copy_from.dup # new_language['language'] = language # [:description, :releaseNotes, :keywords].each do |key| # new_language[key.to_s]['value'] = nil # end # self.languages << new_language # unfold_languages # # Now we need to set a useless `pageLanguageValue` value because iTC says so, after adding a new version # self.languages.each do |current| # current['pageLanguageValue'] = current['language'] # end # end # end # languages # end # Push all changes that were made back to iTunes Connect def save! client.update_app_version!(application.apple_id, is_live?, raw_data) end # @return (String) An URL to this specific resource. You can enter this URL into your browser def url "https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/#{self.application.apple_id}/" + (self.is_live? ? "cur" : "") end # Private methods def setup # Properly parse the AppStatus status = raw_data['status'] @app_status = Tunes::AppStatus.get_from_string(status) # Setup the screenshots @screenshots = {} raw_data['details']['value'].each do |row| # Now that's one language right here @screenshots[row['language']] = setup_screenshots(row) end end # Prefill name, keywords, etc... def unfold_languages { name: :name, keywords: :keywords, description: :description, privacyURL: :privacy_url, supportURL: :support_url, marketingURL: :marketing_url, releaseNotes: :release_notes }.each do |json, attribute| instance_variable_set("@#{attribute}".to_sym, LanguageItem.new(json, languages)) end end # These methods takes care of properly parsing values that # are not returned in the right format, e.g. boolean as string def release_on_approval super == 'true' end def supports_apple_watch !super.nil? end def primary_category=(value) value = "MZGenre.#{value}" unless value.include? "MZGenre" super(value) end def primary_first_sub_category=(value) value = "MZGenre.#{value}" unless value.include? "MZGenre" super(value) end def primary_second_sub_category=(value) value = "MZGenre.#{value}" unless value.include? "MZGenre" super(value) end def secondary_category=(value) value = "MZGenre.#{value}" unless value.include? "MZGenre" super(value) end def secondary_first_sub_category=(value) value = "MZGenre.#{value}" unless value.include? "MZGenre" super(value) end def secondary_second_sub_category=(value) value = "MZGenre.#{value}" unless value.include? "MZGenre" super(value) end private # generates the nested data structure to represent screenshots def setup_screenshots(row) screenshots = row.fetch('screenshots', {}).fetch('value', nil) return [] unless screenshots result = [] screenshots.each do |device_type, value| value['value'].each do |screenshot| screenshot = screenshot['value'] result << Tunes::AppScreenshot.new({ url: screenshot['url'], thumbnail_url: screenshot['thumbNailUrl'], sort_order: screenshot['sortOrder'], original_file_name: screenshot['originalFileName'], device_type: device_type, language: row['language'] }) end end return result end end end end
module CreatesCommit extend ActiveSupport::Concern def create_commit(service, success_path:, failure_path:, failure_view: nil, success_notice: nil) set_commit_variables base_branch = @mr_target_branch unless initial_commit? commit_params = @commit_params.merge( base_project: @mr_target_project, base_branch: base_branch, target_branch: @mr_source_branch ) result = service.new( @mr_source_project, current_user, commit_params).execute if result[:status] == :success update_flash_notice(success_notice) respond_to do |format| format.html { redirect_to final_success_path(success_path) } format.json { render json: { message: "success", filePath: final_success_path(success_path) } } end else flash[:alert] = result[:message] respond_to do |format| format.html do if failure_view render failure_view else redirect_to failure_path end end format.json { render json: { message: "failed", filePath: failure_path } } end end end def authorize_edit_tree! return if can_collaborate_with_project? access_denied! end private def update_flash_notice(success_notice) flash[:notice] = success_notice || "Your changes have been successfully committed." if create_merge_request? if merge_request_exists? flash[:notice] = nil else target = different_project? ? "project" : "branch" flash[:notice] << " You can now submit a merge request to get this change into the original #{target}." end end end def final_success_path(success_path) return success_path unless create_merge_request? merge_request_exists? ? existing_merge_request_path : new_merge_request_path end def new_merge_request_path new_namespace_project_merge_request_path( @mr_source_project.namespace, @mr_source_project, merge_request: { source_project_id: @mr_source_project.id, target_project_id: @mr_target_project.id, source_branch: @mr_source_branch, target_branch: @mr_target_branch } ) end def existing_merge_request_path namespace_project_merge_request_path(@mr_target_project.namespace, @mr_target_project, @merge_request) end def merge_request_exists? return @merge_request if defined?(@merge_request) @merge_request = MergeRequestsFinder.new(current_user, project_id: @mr_target_project.id).execute.opened. find_by(source_branch: @mr_source_branch, target_branch: @mr_target_branch, source_project_id: @mr_source_project) end def different_project? @mr_source_project != @mr_target_project end def create_merge_request? params[:create_merge_request].present? end # TODO: We should really clean this up def set_commit_variables if can?(current_user, :push_code, @project) # Edit file in this project @tree_edit_project = @project @mr_source_project = @project if @project.forked? # Merge request from this project to fork origin @mr_target_project = @project.forked_from_project @mr_target_branch = @mr_target_project.repository.root_ref else # Merge request to this project @mr_target_project = @project @mr_target_branch = @ref || @target_branch end else # Edit file in fork @tree_edit_project = current_user.fork_of(@project) # Merge request from fork to this project @mr_source_project = @tree_edit_project @mr_target_project = @project @mr_target_branch = @ref || @target_branch end @mr_source_branch = guess_mr_source_branch end def initial_commit? @mr_target_branch.nil? || !@mr_target_project.repository.branch_exists?(@mr_target_branch) end def guess_mr_source_branch # XXX: Happens when viewing a commit without a branch. In this case, # @target_branch would be the default branch for @mr_source_project, # however we want a generated new branch here. Thus we can't use # @target_branch, but should pass nil to indicate that we want a new # branch instead of @target_branch. return if create_merge_request? && @mr_source_project.repository.branch_exists?(@target_branch) @target_branch end end Detect if we really want a new merge request properly module CreatesCommit extend ActiveSupport::Concern def create_commit(service, success_path:, failure_path:, failure_view: nil, success_notice: nil) set_commit_variables base_branch = @mr_target_branch unless initial_commit? commit_params = @commit_params.merge( base_project: @mr_target_project, base_branch: base_branch, target_branch: @mr_source_branch ) result = service.new( @mr_source_project, current_user, commit_params).execute if result[:status] == :success update_flash_notice(success_notice) respond_to do |format| format.html { redirect_to final_success_path(success_path) } format.json { render json: { message: "success", filePath: final_success_path(success_path) } } end else flash[:alert] = result[:message] respond_to do |format| format.html do if failure_view render failure_view else redirect_to failure_path end end format.json { render json: { message: "failed", filePath: failure_path } } end end end def authorize_edit_tree! return if can_collaborate_with_project? access_denied! end private def update_flash_notice(success_notice) flash[:notice] = success_notice || "Your changes have been successfully committed." if create_merge_request? if merge_request_exists? flash[:notice] = nil else target = different_project? ? "project" : "branch" flash[:notice] << " You can now submit a merge request to get this change into the original #{target}." end end end def final_success_path(success_path) return success_path unless create_merge_request? merge_request_exists? ? existing_merge_request_path : new_merge_request_path end def new_merge_request_path new_namespace_project_merge_request_path( @mr_source_project.namespace, @mr_source_project, merge_request: { source_project_id: @mr_source_project.id, target_project_id: @mr_target_project.id, source_branch: @mr_source_branch, target_branch: @mr_target_branch } ) end def existing_merge_request_path namespace_project_merge_request_path(@mr_target_project.namespace, @mr_target_project, @merge_request) end def merge_request_exists? return @merge_request if defined?(@merge_request) @merge_request = MergeRequestsFinder.new(current_user, project_id: @mr_target_project.id).execute.opened. find_by(source_branch: @mr_source_branch, target_branch: @mr_target_branch, source_project_id: @mr_source_project) end def different_project? @mr_source_project != @mr_target_project end def create_merge_request? # XXX: Even if the field is set, if we're checking the same branch # as the target branch, we don't want to create a merge request. params[:create_merge_request].present? && @ref != @target_branch end # TODO: We should really clean this up def set_commit_variables if can?(current_user, :push_code, @project) # Edit file in this project @tree_edit_project = @project @mr_source_project = @project if @project.forked? # Merge request from this project to fork origin @mr_target_project = @project.forked_from_project @mr_target_branch = @mr_target_project.repository.root_ref else # Merge request to this project @mr_target_project = @project @mr_target_branch = @ref || @target_branch end else # Edit file in fork @tree_edit_project = current_user.fork_of(@project) # Merge request from fork to this project @mr_source_project = @tree_edit_project @mr_target_project = @project @mr_target_branch = @ref || @target_branch end @mr_source_branch = guess_mr_source_branch end def initial_commit? @mr_target_branch.nil? || !@mr_target_project.repository.branch_exists?(@mr_target_branch) end def guess_mr_source_branch # XXX: Happens when viewing a commit without a branch. In this case, # @target_branch would be the default branch for @mr_source_project, # however we want a generated new branch here. Thus we can't use # @target_branch, but should pass nil to indicate that we want a new # branch instead of @target_branch. return if create_merge_request? && # XXX: Don't understand why rubocop prefers this indention @mr_source_project.repository.branch_exists?(@target_branch) @target_branch end end
module SortablePosts extend ActiveSupport::Concern private def map_sort_key(key, default) map = {id: "id", id_desc: "id DESC", topic_id: "topic_id", topic_id_desc: "topic_id DESC", user_id: "user_id", user_id_desc: "user_id DESC", remote_created_at: "remote_created_at", remote_created_at_desc: "remote_created_at_desc", remote_id: "remote_id", remote_id_desc: "remote_id DESC"} map[key.try(:to_sym)] || map[default.to_sym] end end fix typo module SortablePosts extend ActiveSupport::Concern private def map_sort_key(key, default) map = {id: "id", id_desc: "id DESC", topic_id: "topic_id", topic_id_desc: "topic_id DESC", user_id: "user_id", user_id_desc: "user_id DESC", remote_created_at: "remote_created_at", remote_created_at_desc: "remote_created_at DESC", remote_id: "remote_id", remote_id_desc: "remote_id DESC"} map[key.try(:to_sym)] || map[default.to_sym] end end
class DataObjectsController < ApplicationController #User admin methods will need to be rewritten in move to other codebase def index @data_objects = get_allowed_data_objects @group_type_options = options_for_group_type @group_by_options = [] if params[:view_options] @selected_type = params[:view_options][:group_type] if params[:view_options][:group_by] unless (@selected_by = params[:view_options][:group_by]).blank? @data_objects = @selected_type.classify.constantize.find(@selected_by).data_objects end end @group_by_options = options_for_group_by(@selected_type) end @data_types = @data_objects.group_by &:data_type end def show @data_object = DataObject.find(params[:id]) @data_type = @data_object.data_type end def new @data_object = DataObject.build({:data_type_id => params[:data_type_id]}) @data_type = DataType.find(params[:data_type_id]) end def create @data_object = DataObject.new(params[:data_object]) @data_object.data_type_id = params[:data_object][:data_type_id] if @data_object.save flash[:notice] = "Successfully created data object." redirect_to data_objects_path else render :action => 'new' end end def edit @data_object = DataObject.find(params[:id]) @data_type = @data_object.data_type end def update @data_object = DataObject.find(params[:id]) if @data_object.update_attributes(params[:data_object]) flash[:notice] = "Successfully updated data object." redirect_to @data_object else render :action => 'edit' end end def destroy @data_object = DataObject.find(params[:id]) @data_object.destroy flash[:notice] = "Successfully destroyed data object." redirect_to data_objects_url end # have to define a more elaborate sort method that will make # Object 2 appear before Object 10, for example # def view_all # @data_objects = DataObject.find(:all, :order => :data_type_id) # end private # Returns all the data objects that the user is permitted to administer def get_allowed_data_objects unless (@loc_groups = current_user.loc_groups_to_admin(@department)).empty? return @loc_groups.map{|lg| DataObject.by_location_group(lg)}.flatten end return @department.data_objects if current_user.is_admin_of?(@department) flash[:error] = "You do not have the permissions necessary to view any data objects." redirect_to access_denied_path end def options_for_group_type options = [["Location","locations"],["Location Group","loc_groups"]] if current_user.is_admin_of?(@department) options.push(["Data type", "data_types"], ["Department", "departments"]) end end def options_for_group_by(group_type) return [] if group_type == "departments" @options = @department.send(group_type) if group_type == "locations" || group_type == "loc_groups" @options.reject!{|opt| !current_user.permission_list.include?(opt.admin_permission)} end @options.map{|t| [t.name, t.id]} << [] end end Stupid merge class DataObjectsController < ApplicationController #User admin methods will need to be rewritten in move to other codebase def index @data_objects = get_allowed_data_objects @group_type_options = options_for_group_type @group_by_options = [] if params[:view_options] @selected_type = params[:view_options][:group_type] if params[:view_options][:group_by] unless (@selected_by = params[:view_options][:group_by]).blank? @data_objects = @selected_type.classify.constantize.find(@selected_by).data_objects end end @group_by_options = options_for_group_by(@selected_type) end @data_types = @data_objects.group_by &:data_type end def show @data_object = DataObject.find(params[:id]) @data_type = @data_object.data_type end def new @data_object = DataObject.build({:data_type_id => params[:data_type_id]}) @data_type = DataType.find(params[:data_type_id]) end def create @data_object = DataObject.new(params[:data_object]) @data_object.data_type_id = params[:data_object][:data_type_id] if @data_object.save flash[:notice] = "Successfully created data object." redirect_to data_objects_path else render :action => 'new' end end def edit @data_object = DataObject.find(params[:id]) @data_type = @data_object.data_type end def update @data_object = DataObject.find(params[:id]) if @data_object.update_attributes(params[:data_object]) flash[:notice] = "Successfully updated data object." redirect_to @data_object else render :action => 'edit' end end def destroy @data_object = DataObject.find(params[:id]) @data_object.destroy flash[:notice] = "Successfully destroyed data object." redirect_to data_objects_url end # have to define a more elaborate sort method that will make # Object 2 appear before Object 10, for example # def view_all # @data_objects = DataObject.find(:all, :order => :data_type_id) # end private # Returns all the data objects that the user is permitted to administer def get_allowed_data_objects unless (@loc_groups = current_user.loc_groups_to_admin(@department)).empty? return @loc_groups.map{|lg| DataObject.by_location_group(lg)}.flatten end return @department.data_objects if current_user.is_admin_of?(@department) flash[:error] = "You do not have the permissions necessary to view any data objects." redirect_to access_denied_path end def options_for_group_type options = [["Location","locations"],["Location Group","loc_groups"]] if current_user.is_admin_of?(@department) options.push(["Data type", "data_types"], ["Department", "departments"]) end end def options_for_group_by(group_type) return [] if group_type == "departments" @options = @department.send(group_type) if group_type == "locations" || group_type == "loc_groups" @options.reject!{|opt| !current_user.permission_list.include?(opt.admin_permission)} end @options.map{|t| [t.name, t.id]} << [] end end
class Editor::PostsController < Editor::ApplicationController def index @posts = posts.preload(:category).order(:public_id => :desc).page(params[:page]).per(50) end def show @post = posts.find_by!(public_id: params[:id]) end def new @post = posts.build end def create @post = posts.build(post_params) if @post.save redirect_to [:editor, @post], notice: '記事が作成されました。' else render :new end end def edit @post = posts.find_by!(public_id: params[:id]) end def update @post = posts.find_by!(public_id: params[:id]) if @post.update(post_params) redirect_to [:editor, @post], notice: '記事が更新されました。' else render :edit end end def destroy @post = posts.find_by!(public_id: params[:id]) @post.destroy redirect_to editor_posts_url, notice: '記事が削除されました。' end def preview @post = posts.find_by!(public_id: params[:id]) @pages = if params[:all] @post.pages else Kaminari.paginate_array(@post.pages).page(params[:page]).per(1) end render template: 'posts/show', layout: 'preview' end private def posts current_site.posts end def post_params params.require(:post).permit( :title, :body, :category_id, :thumbnail, :published_at, :credits_attributes => [ :id, :participant_id, :credit_role_id, :_destroy ] ) end end Fix `all=true` pagination for editor/posts#show This is a part of 270eaac8 class Editor::PostsController < Editor::ApplicationController def index @posts = posts.preload(:category).order(:public_id => :desc).page(params[:page]).per(50) end def show @post = posts.find_by!(public_id: params[:id]) end def new @post = posts.build end def create @post = posts.build(post_params) if @post.save redirect_to [:editor, @post], notice: '記事が作成されました。' else render :new end end def edit @post = posts.find_by!(public_id: params[:id]) end def update @post = posts.find_by!(public_id: params[:id]) if @post.update(post_params) redirect_to [:editor, @post], notice: '記事が更新されました。' else render :edit end end def destroy @post = posts.find_by!(public_id: params[:id]) @post.destroy redirect_to editor_posts_url, notice: '記事が削除されました。' end def preview @post = posts.find_by!(public_id: params[:id]) @pages = if params[:all] Kaminari.paginate_array(@post.pages).page(1).per(@post.pages.size) else Kaminari.paginate_array(@post.pages).page(params[:page]).per(1) end render template: 'posts/show', layout: 'preview' end private def posts current_site.posts end def post_params params.require(:post).permit( :title, :body, :category_id, :thumbnail, :published_at, :credits_attributes => [ :id, :participant_id, :credit_role_id, :_destroy ] ) end end
class Epp::SessionsController < EppController skip_authorization_check only: [:hello, :login, :logout] def hello render_epp_response('greeting') end # rubocop: disable Metrics/PerceivedComplexity # rubocop: disable Metrics/CyclomaticComplexity # rubocop: disable Metrics/MethodLength # rubocop: disable Metrics/AbcSize def login success = true @api_user = ApiUser.find_by(login_params) if request.ip == ENV['webclient_ip'] && !Rails.env.test? client_md5 = Certificate.parse_md_from_string(request.env['HTTP_SSL_CLIENT_CERT']) server_md5 = Certificate.parse_md_from_string(File.read(ENV['cert_path'])) if client_md5 != server_md5 @msg = 'Authentication error; server closing connection (certificate is not valid)' success = false end end if request.ip != ENV['webclient_ip'] && @api_user unless @api_user.api_pki_ok?(request.env['HTTP_SSL_CLIENT_CERT'], request.env['HTTP_SSL_CLIENT_S_DN_CN']) @msg = 'Authentication error; server closing connection (certificate is not valid)' success = false end end if success && !@api_user @msg = 'Authentication error; server closing connection (API user not found)' success = false end if success && !@api_user.try(:active) @msg = 'Authentication error; server closing connection (API user is not active)' success = false end if success && !ip_white? @msg = 'Authentication error; server closing connection (IP is not whitelisted)' success = false end if success && !connection_limit_ok? @msg = 'Authentication error; server closing connection (connection limit reached)' success = false end if success if parsed_frame.css('newPW').first unless @api_user.update(password: parsed_frame.css('newPW').first.text) response.headers['X-EPP-Returncode'] = '2200' handle_errors(@api_user) and return end end epp_session[:api_user_id] = @api_user.id epp_session.update_column(:registrar_id, @api_user.registrar_id) render_epp_response('login_success') else response.headers['X-EPP-Returncode'] = '2200' render_epp_response('login_fail') end end # rubocop: enable Metrics/MethodLength # rubocop: enable Metrics/AbcSize # rubocop: enable Metrics/PerceivedComplexity # rubocop: enable Metrics/CyclomaticComplexity def ip_white? return true if request.ip == ENV['webclient_ip'] if @api_user return false unless @api_user.registrar.api_ip_white?(request.ip) end true end def connection_limit_ok? return true if Rails.env.test? c = EppSession.where( 'registrar_id = ? AND updated_at >= ?', @api_user.registrar_id, Time.zone.now - 5.minutes ).count return false if c >= 4 true end def logout @api_user = current_user # cache current_user for logging epp_session.destroy response.headers['X-EPP-Returncode'] = '1500' render_epp_response('logout') end ### HELPER METHODS ### def login_params ph = params_hash['epp']['command']['login'] { username: ph[:clID], password: ph[:pw] } end def parsed_frame @parsed_frame ||= Nokogiri::XML(request.params[:raw_frame]).remove_namespaces! end end Ignore webclient ip in development mode #2765 class Epp::SessionsController < EppController skip_authorization_check only: [:hello, :login, :logout] def hello render_epp_response('greeting') end # rubocop: disable Metrics/PerceivedComplexity # rubocop: disable Metrics/CyclomaticComplexity # rubocop: disable Metrics/MethodLength # rubocop: disable Metrics/AbcSize def login success = true @api_user = ApiUser.find_by(login_params) if request.ip == ENV['webclient_ip'] && (!Rails.env.test? || !Rails.env.development?) client_md5 = Certificate.parse_md_from_string(request.env['HTTP_SSL_CLIENT_CERT']) server_md5 = Certificate.parse_md_from_string(File.read(ENV['cert_path'])) if client_md5 != server_md5 @msg = 'Authentication error; server closing connection (certificate is not valid)' success = false end end if request.ip != ENV['webclient_ip'] && @api_user unless @api_user.api_pki_ok?(request.env['HTTP_SSL_CLIENT_CERT'], request.env['HTTP_SSL_CLIENT_S_DN_CN']) @msg = 'Authentication error; server closing connection (certificate is not valid)' success = false end end if success && !@api_user @msg = 'Authentication error; server closing connection (API user not found)' success = false end if success && !@api_user.try(:active) @msg = 'Authentication error; server closing connection (API user is not active)' success = false end if success && !ip_white? @msg = 'Authentication error; server closing connection (IP is not whitelisted)' success = false end if success && !connection_limit_ok? @msg = 'Authentication error; server closing connection (connection limit reached)' success = false end if success if parsed_frame.css('newPW').first unless @api_user.update(password: parsed_frame.css('newPW').first.text) response.headers['X-EPP-Returncode'] = '2200' handle_errors(@api_user) and return end end epp_session[:api_user_id] = @api_user.id epp_session.update_column(:registrar_id, @api_user.registrar_id) render_epp_response('login_success') else response.headers['X-EPP-Returncode'] = '2200' render_epp_response('login_fail') end end # rubocop: enable Metrics/MethodLength # rubocop: enable Metrics/AbcSize # rubocop: enable Metrics/PerceivedComplexity # rubocop: enable Metrics/CyclomaticComplexity def ip_white? return true if request.ip == ENV['webclient_ip'] if @api_user return false unless @api_user.registrar.api_ip_white?(request.ip) end true end def connection_limit_ok? return true if Rails.env.test? c = EppSession.where( 'registrar_id = ? AND updated_at >= ?', @api_user.registrar_id, Time.zone.now - 5.minutes ).count return false if c >= 4 true end def logout @api_user = current_user # cache current_user for logging epp_session.destroy response.headers['X-EPP-Returncode'] = '1500' render_epp_response('logout') end ### HELPER METHODS ### def login_params ph = params_hash['epp']['command']['login'] { username: ph[:clID], password: ph[:pw] } end def parsed_frame @parsed_frame ||= Nokogiri::XML(request.params[:raw_frame]).remove_namespaces! end end
class HuntStreetsController < ApplicationController def new @hunts = Hunt.all # @hunts = current_user.hunts @streets = Street.all end def create params[:ids].each do |street_id| @hunt_street = HuntStreet.create({ hunt_id: params[:hunt_id], street_id: street_id }) render nothing: true end end end completed street user capture class HuntStreetsController < ApplicationController def new @hunts = current_user.hunts @streets = Street.all end def create params[:ids].each do |street_id| @hunt_street = HuntStreet.create({ hunt_id: params[:hunt_id], street_id: street_id }) render nothing: true end end end
module Jarvis class SyncsController < ApplicationController def create # This is where we'll create users from the Brain Brain.create_user(params[:user]) end def update # This is where we'll update users from the Brain Brain.update_user(params[:user_id], params[:update]) end def destroy # This is where we'll destroy users from the Brain Brain.destroy_user(params[:user_id]) end end end Initialize the class in sync module Jarvis class SyncsController < ApplicationController @@brain = Brain.new(Rails.application.config.api_token) def create # This is where we'll create users from the @brain @@brain.create_user(params[:user]) end def update # This is where we'll update users from the @brain @@brain.update_user(params[:user_id], params[:update]) end def destroy # This is where we'll destroy users from the @brain @@brain.destroy_user(params[:user_id]) end end end
require "rexml/document" class MiqAeClassController < ApplicationController include MiqAeClassHelper include AutomateTreeHelper include Mixins::GenericSessionMixin before_action :check_privileges before_action :get_session_data after_action :cleanup_action after_action :set_session_data MIQ_AE_COPY_ACTIONS = %w(miq_ae_class_copy miq_ae_instance_copy miq_ae_method_copy).freeze # GET /automation_classes # GET /automation_classes.xml def index redirect_to :action => 'explorer' end def change_tab # resetting flash array so messages don't get displayed when tab is changed @flash_array = [] @explorer = true @record = @ae_class = MiqAeClass.find(from_cid(x_node.split('-').last)) @sb[:active_tab] = params[:tab_id] render :update do |page| page << javascript_prologue page.replace("flash_msg_div", :partial => "layouts/flash_msg") page << javascript_reload_toolbars page << "miqSparkle(false);" end end AE_X_BUTTON_ALLOWED_ACTIONS = { 'instance_fields_edit' => :edit_instance, 'method_inputs_edit' => :edit_mehod, 'miq_ae_class_copy' => :copy_objects, 'miq_ae_class_edit' => :edit_class, 'miq_ae_class_delete' => :deleteclasses, 'miq_ae_class_new' => :new, 'miq_ae_domain_delete' => :delete_domain, 'miq_ae_domain_edit' => :edit_domain, 'miq_ae_domain_lock' => :domain_lock, 'miq_ae_domain_unlock' => :domain_unlock, 'miq_ae_git_refresh' => :git_refresh, 'miq_ae_domain_new' => :new_domain, 'miq_ae_domain_priority_edit' => :domains_priority_edit, 'miq_ae_field_edit' => :edit_fields, 'miq_ae_field_seq' => :fields_seq_edit, 'miq_ae_instance_copy' => :copy_objects, 'miq_ae_instance_delete' => :deleteinstances, 'miq_ae_instance_edit' => :edit_instance, 'miq_ae_instance_new' => :new_instance, 'miq_ae_item_edit' => :edit_item, 'miq_ae_method_copy' => :copy_objects, 'miq_ae_method_delete' => :deletemethods, 'miq_ae_method_edit' => :edit_method, 'miq_ae_method_new' => :new_method, 'miq_ae_namespace_delete' => :delete_ns, 'miq_ae_namespace_edit' => :edit_ns, 'miq_ae_namespace_new' => :new_ns, }.freeze def x_button generic_x_button(AE_X_BUTTON_ALLOWED_ACTIONS) end def explorer @trees = [] @sb[:action] = nil @explorer = true # don't need right bottom cell @breadcrumbs = [] bc_name = _("Explorer") bc_name += _(" (filtered)") if @filters && (!@filters[:tags].blank? || !@filters[:cats].blank?) drop_breadcrumb(:name => bc_name, :url => "/miq_ae_class/explorer") @lastaction = "replace_right_cell" build_accordions_and_trees @right_cell_text ||= _("Datastore") render :layout => "application" end def set_right_cell_text(id, rec = nil) nodes = id.split('-') case nodes[0] when "root" txt = _("Datastore") @sb[:namespace_path] = "" when "aec" txt = ui_lookup(:model => "MiqAeClass") @sb[:namespace_path] = rec.fqname when "aei" txt = ui_lookup(:model => "MiqAeInstance") updated_by = rec.updated_by ? _(" by %{user}") % {:user => rec.updated_by} : "" @sb[:namespace_path] = rec.fqname @right_cell_text = _("%{model} [%{name} - Updated %{time}%{update}]") % { :model => txt, :name => get_rec_name(rec), :time => format_timezone(rec.updated_on, Time.zone, "gtl"), :update => updated_by } when "aem" txt = ui_lookup(:model => "MiqAeMethod") updated_by = rec.updated_by ? _(" by %{user}") % {:user => rec.updated_by} : "" @sb[:namespace_path] = rec.fqname @right_cell_text = _("%{model} [%{name} - Updated %{time}%{update}]") % { :model => txt, :name => get_rec_name(rec), :time => format_timezone(rec.updated_on, Time.zone, "gtl"), :update => updated_by } when "aen" txt = ui_lookup(:model => rec.domain? ? "MiqAeDomain" : "MiqAeNamespace") @sb[:namespace_path] = rec.fqname end @sb[:namespace_path].gsub!(%r{\/}, " / ") if @sb[:namespace_path] @right_cell_text = "#{txt} #{_("\"%s\"") % get_rec_name(rec)}" unless %w(root aei aem).include?(nodes[0]) end def expand_toggle render :update do |page| page << javascript_prologue if @sb[:squash_state] @sb[:squash_state] = false page << javascript_show("inputs_div") page << "$('#exp_collapse_img i').attr('class','fa fa-angle-up fa-lg')" page << "$('#exp_collapse_img').prop('title', 'Hide Input Parameters');" page << "$('#exp_collapse_img').prop('alt', 'Hide Input Parameters');" else @sb[:squash_state] = true page << javascript_hide("inputs_div") page << "$('#exp_collapse_img i').attr('class','fa fa-angle-down fa-lg')" page << "$('#exp_collapse_img').prop('title', 'Show Input Parameters');" page << "$('#exp_collapse_img').prop('alt', 'Show Input Parameters');" end end end def get_node_info(node, _show_list = true) id = valid_active_node(node).split('-') @sb[:row_selected] = nil if params[:action] == "tree_select" case id[0] when "aec" get_class_node_info(id) when "aei" get_instance_node_info(id) when "aem" get_method_node_info(id) when "aen" @record = MiqAeNamespace.find(from_cid(id[1])) # need to set record as Domain record if it's a domain, editable_domains, enabled_domains, # visible domains methods returns list of Domains, need this for toolbars to hide/disable correct records. @record = MiqAeDomain.find(from_cid(id[1])) if @record.domain? @version_message = domain_version_message(@record) if @record.domain? if @record.nil? set_root_node else @records = [] # Add Namespaces under a namespace details = @record.ae_namespaces @records += details.sort_by { |d| [d.display_name.to_s, d.name.to_s] } # Add classes under a namespace details_cls = @record.ae_classes unless details_cls.nil? @records += details_cls.sort_by { |d| [d.display_name.to_s, d.name.to_s] } end @combo_xml = build_type_options @dtype_combo_xml = build_dtype_options @sb[:active_tab] = "details" set_right_cell_text(x_node, @record) end else @grid_data = User.current_tenant.visible_domains add_all_domains_version_message(@grid_data) @record = nil @right_cell_text = _("Datastore") @sb[:active_tab] = "namespaces" set_right_cell_text(x_node) end x_history_add_item(:id => x_node, :text => @right_cell_text) end def domain_version_message(domain) version = domain.version available_version = domain.available_version return if version.nil? || available_version.nil? if version != available_version _("%{name} domain: Current version - %{version}, Available version - %{available_version}") % {:name => domain.name, :version => version, :available_version => available_version} end end def add_all_domains_version_message(domains) @version_messages = domains.collect { |dom| domain_version_message(dom) }.compact end # Tree node selected in explorer def tree_select @explorer = true @lastaction = "explorer" self.x_active_tree = params[:tree] if params[:tree] self.x_node = params[:id] @sb[:action] = nil replace_right_cell end # Check for parent nodes missing from ae tree and return them if any def open_parent_nodes(record) nodes = record.fqname.split("/") parents = [] nodes.each_with_index do |_, i| if i == nodes.length - 1 selected_node = x_node.split("-") parents.push(record.ae_class) if %w(aei aem).include?(selected_node[0]) self.x_node = "#{selected_node[0]}-#{to_cid(record.id)}" parents.push(record) else ns = MiqAeNamespace.find_by(:fqname => nodes[0..i].join("/")) parents.push(ns) if ns end end build_and_add_nodes(parents) end def build_and_add_nodes(parents) existing_node = find_existing_node(parents) return nil if existing_node.nil? children = tree_add_child_nodes(existing_node) # set x_node after building tree nodes so parent node of new nodes can be selected in the tree. unless params[:action] == "x_show" self.x_node = if @record.kind_of?(MiqAeClass) "aen-#{to_cid(@record.namespace_id)}" else "aec-#{to_cid(@record.class_id)}" end end {:key => existing_node, :nodes => children} end def find_existing_node(parents) existing_node = nil # Go up thru the parents and find the highest level unopened, mark all as opened along the way unless parents.empty? || # Skip if no parents or parent already open x_tree[:open_nodes].include?(x_build_node_id(parents.last)) parents.reverse_each do |p| p_node = x_build_node_id(p) if x_tree[:open_nodes].include?(p_node) return p_node else x_tree[:open_nodes].push(p_node) existing_node = p_node end end end existing_node end def replace_right_cell(options = {}) @explorer = true replace_trees = options[:replace_trees] # FIXME: is the following line needed? # replace_trees = @replace_trees if @replace_trees #get_node_info might set this nodes = x_node.split('-') @in_a_form = @in_a_form_fields = @in_a_form_props = false if params[:button] == "cancel" || (%w(save add).include?(params[:button]) && replace_trees) add_nodes = open_parent_nodes(@record) if params[:button] == "copy" || params[:action] == "x_show" get_node_info(x_node) if !@in_a_form && !@angular_form && @button != "reset" c_tb = build_toolbar(center_toolbar_filename) unless @in_a_form h_tb = build_toolbar("x_history_tb") presenter = ExplorerPresenter.new( :active_tree => x_active_tree, :right_cell_text => @right_cell_text, :remove_nodes => add_nodes, # remove any existing nodes before adding child nodes to avoid duplication :add_nodes => add_nodes, ) reload_trees_by_presenter(presenter, :ae => build_ae_tree) unless replace_trees.blank? if @sb[:action] == "miq_ae_field_seq" presenter.update(:class_fields_div, r[:partial => "fields_seq_form"]) elsif @sb[:action] == "miq_ae_domain_priority_edit" presenter.update(:ns_list_div, r[:partial => "domains_priority_form"]) elsif MIQ_AE_COPY_ACTIONS.include?(@sb[:action]) presenter.update(:main_div, r[:partial => "copy_objects_form"]) else if @sb[:action] == "miq_ae_class_edit" @sb[:active_tab] = 'props' else @sb[:active_tab] ||= 'instances' end presenter.update(:main_div, r[:partial => 'all_tabs']) end presenter.replace('flash_msg_div', r[:partial => "layouts/flash_msg"]) if @flash_array if @in_a_form && !@angular_form action_url = create_action_url(nodes.first) # incase it was hidden for summary screen, and incase there were no records on show_list presenter.show(:paging_div, :form_buttons_div) presenter.update(:form_buttons_div, r[ :partial => "layouts/x_edit_buttons", :locals => { :record_id => @edit[:rec_id], :action_url => action_url, :copy_button => action_url == "copy_objects", :multi_record => @sb[:action] == "miq_ae_domain_priority_edit", :serialize => @sb[:active_tab] == 'methods', } ]) else # incase it was hidden for summary screen, and incase there were no records on show_list presenter.hide(:paging_div, :form_buttons_div) end presenter[:lock_sidebar] = @in_a_form && @edit if @record.kind_of?(MiqAeMethod) && !@in_a_form && !@angular_form presenter.set_visibility(!@record.inputs.blank?, :params_div) end presenter[:clear_gtl_list_grid] = @gtl_type && @gtl_type != 'list' # Rebuild the toolbars presenter.reload_toolbars(:history => h_tb) if c_tb.present? presenter.show(:toolbar) presenter.reload_toolbars(:center => c_tb) else presenter.hide(:toolbar) end presenter[:record_id] = determine_record_id_for_presenter presenter[:osf_node] = x_node presenter.show_miq_buttons if @changed render :json => presenter.for_render end def build_type_options MiqAeField.available_aetypes.collect { |t| [t.titleize, t, {"data-icon" => ae_field_fonticon(t)}] } end def build_dtype_options MiqAeField.available_datatypes_for_ui.collect { |t| [t.titleize, t, {"data-icon" => ae_field_fonticon(t)}] } end def class_and_glyph(cls) case cls.to_s.split("::").last when "MiqAeClass" cls = "aec" glyphicon = "ff ff-class" when "MiqAeNamespace" cls = "aen" glyphicon = "pficon pficon-folder-open" when "MiqAeInstance" cls = "aei" glyphicon = "fa fa-file-text-o" when "MiqAeField" cls = "Field" glyphicon = "ff ff-field" when "MiqAeMethod" cls = "aem" glyphicon = "ff ff-method" end [cls, glyphicon] end def build_details_grid(view, mode = true) xml = REXML::Document.load("") xml << REXML::XMLDecl.new(1.0, "UTF-8") # Create root element root = xml.add_element("rows") # Build the header row head = root.add_element("head") header = "" head.add_element("column", "type" => "ch", "width" => 25, "align" => "center") # Checkbox column new_column = head.add_element("column", "width" => "30", "align" => "left", "sort" => "na") new_column.add_attribute("type", 'ro') new_column.text = header new_column = head.add_element("column", "width" => "*", "align" => "left", "sort" => "na") new_column.add_attribute("type", 'ro') new_column.text = header # passing in mode, don't need to sort records for namaspace node, it will be passed in sorted order, need to show Namesaces first and then Classes records = if mode view.sort_by { |v| [v.display_name.to_s, v.name.to_s] } else view end records.each do |kids| cls, glyphicon = class_and_glyph(kids.class) rec_name = get_rec_name(kids) if rec_name rec_name = rec_name.gsub(/\n/, "\\n") rec_name = rec_name.gsub(/\t/, "\\t") rec_name = rec_name.tr('"', "'") rec_name = ERB::Util.html_escape(rec_name) rec_name = rec_name.gsub(/\\/, "&#92;") end srow = root.add_element("row", "id" => "#{cls}-#{to_cid(kids.id)}", "style" => "border-bottom: 1px solid #CCCCCC;color:black; text-align: center") srow.add_element("cell").text = "0" # Checkbox column unchecked srow.add_element("cell", "image" => "blank.png", "title" => cls.to_s, "style" => "border-bottom: 1px solid #CCCCCC;text-align: left;height:28px;").text = REXML::CData.new("<i class='#{glyphicon}' alt='#{cls}' title='#{cls}'></i>") srow.add_element("cell", "image" => "blank.png", "title" => rec_name.to_s, "style" => "border-bottom: 1px solid #CCCCCC;text-align: left;height:28px;").text = rec_name end xml.to_s end def edit_item item = find_checked_items @sb[:row_selected] = item[0] if @sb[:row_selected].split('-')[0] == "aec" edit_class else edit_ns end end def edit_class assert_privileges("miq_ae_class_edit") if params[:pressed] == "miq_ae_item_edit" # came from Namespace details screen id = @sb[:row_selected].split('-') @ae_class = find_record_with_rbac(MiqAeClass, from_cid(id[1])) else @ae_class = find_record_with_rbac(MiqAeClass, params[:id]) end set_form_vars # have to get name and set node info, to load multiple tabs correctly # rec_name = get_rec_name(@ae_class) # get_node_info("aec-#{to_cid(@ae_class.id)}") @in_a_form = true @in_a_form_props = true session[:changed] = @changed = false replace_right_cell end def edit_fields assert_privileges("miq_ae_field_edit") if params[:pressed] == "miq_ae_item_edit" # came from Namespace details screen id = @sb[:row_selected].split('-') @ae_class = find_record_with_rbac(MiqAeClass, from_cid(id[1])) else @ae_class = find_record_with_rbac(MiqAeClass, params[:id]) end fields_set_form_vars @in_a_form = true @in_a_form_fields = true session[:changed] = @changed = false replace_right_cell end def edit_domain assert_privileges("miq_ae_domain_edit") edit_domain_or_namespace end def edit_ns assert_privileges("miq_ae_namespace_edit") edit_domain_or_namespace end def edit_instance assert_privileges("miq_ae_instance_edit") obj = find_checked_items if !obj.blank? @sb[:row_selected] = obj[0] id = @sb[:row_selected].split('-') else id = x_node.split('-') end initial_setup_for_instances_form_vars(from_cid(id[1])) set_instances_form_vars @in_a_form = true session[:changed] = @changed = false replace_right_cell end def edit_method assert_privileges("miq_ae_method_edit") obj = find_checked_items if !obj.blank? @sb[:row_selected] = obj[0] id = @sb[:row_selected].split('-') else id = x_node.split('-') end @ae_method = find_record_with_rbac(MiqAeMethod, from_cid(id[1])) if @ae_method.location == "playbook" angular_form_specific_data else set_method_form_vars @in_a_form = true end session[:changed] = @changed = false replace_right_cell end # Set form variables for edit def set_instances_form_vars session[:inst_data] = {} @edit = { :ae_inst_id => @ae_inst.id, :ae_class_id => @ae_class.id, :rec_id => @ae_inst.id || nil, :key => "aeinst_edit__#{@ae_inst.id || "new"}", :new => {} } @edit[:new][:ae_inst] = {} instance_column_names.each do |fld| @edit[:new][:ae_inst][fld] = @ae_inst.send(fld) end @edit[:new][:ae_values] = @ae_values.collect do |ae_value| value_column_names.each_with_object({}) do |fld, hash| hash[fld] = ae_value.send(fld) end end @edit[:new][:ae_fields] = @ae_class.ae_fields.collect do |ae_field| field_column_names.each_with_object({}) do |fld, hash| hash[fld] = ae_field.send(fld) end end @edit[:current] = copy_hash(@edit[:new]) @right_cell_text = if @edit[:rec_id].nil? _("Adding a new %{model}") % {:model => ui_lookup(:model => "MiqAeInstance")} else _("Editing %{model} \"%{name}\"") % {:model => ui_lookup(:model => "MiqAeInstance"), :name => @ae_inst.name} end session[:edit] = @edit end # AJAX driven routine to check for changes in ANY field on the form def form_instance_field_changed return unless load_edit("aeinst_edit__#{params[:id]}", "replace_cell__explorer") get_instances_form_vars javascript_miq_button_visibility(@edit[:current] != @edit[:new]) end def update_instance assert_privileges("miq_ae_instance_edit") return unless load_edit("aeinst_edit__#{params[:id]}", "replace_cell__explorer") get_instances_form_vars @changed = (@edit[:new] != @edit[:current]) case params[:button] when "cancel" session[:edit] = nil # clean out the saved info add_flash(_("Edit of %{model} \"%{name}\" was cancelled by the user") % {:model => ui_lookup(:model => "MiqAeInstance"), :name => @ae_inst.name}) @in_a_form = false replace_right_cell when "save" if @edit[:new][:ae_inst]["name"].blank? add_flash(_("Name is required"), :error) end if @flash_array javascript_flash return end set_instances_record_vars(@ae_inst) # Set the instance record variables, but don't save # Update the @ae_inst.ae_values directly because of update bug in RAILS # When saving a parent, the childrens updates are not getting saved set_instances_value_vars(@ae_values, @ae_inst) # Set the instance record variables, but don't save begin MiqAeInstance.transaction do @ae_inst.ae_values.each { |v| v.value = nil if v.value == "" } @ae_inst.save! end rescue => bang add_flash(_("Error during 'save': %{error_message}") % {:error_message => bang.message}, :error) @in_a_form = true javascript_flash else AuditEvent.success(build_saved_audit(@ae_class, @edit)) session[:edit] = nil # clean out the saved info @in_a_form = false add_flash(_("%{model} \"%{name}\" was saved") % {:model => ui_lookup(:model => "MiqAeInstance"), :name => @ae_inst.name}) replace_right_cell(:replace_trees => [:ae]) return end when "reset" set_instances_form_vars add_flash(_("All changes have been reset"), :warning) @in_a_form = true @button = "reset" replace_right_cell end end def create_instance assert_privileges("miq_ae_instance_new") case params[:button] when "cancel" session[:edit] = nil # clean out the saved info add_flash(_("Add of new %{model} was cancelled by the user") % {:model => ui_lookup(:model => "MiqAeInstance")}) @in_a_form = false replace_right_cell when "add" return unless load_edit("aeinst_edit__new", "replace_cell__explorer") get_instances_form_vars if @edit[:new][:ae_inst]["name"].blank? add_flash(_("Name is required"), :error) end if @flash_array javascript_flash return end add_aeinst = MiqAeInstance.new set_instances_record_vars(add_aeinst) # Set the instance record variables, but don't save set_instances_value_vars(@ae_values) # Set the instance value record variables, but don't save begin MiqAeInstance.transaction do add_aeinst.ae_values = @ae_values add_aeinst.ae_values.each { |v| v.value = nil if v.value == "" } add_aeinst.save! end rescue => bang @in_a_form = true render_flash(_("Error during 'add': %{message}") % {:message => bang.message}, :error) else AuditEvent.success(build_created_audit(add_aeinst, @edit)) add_flash(_("%{model} \"%{name}\" was added") % {:model => ui_lookup(:model => "MiqAeInstance"), :name => add_aeinst.name}) @in_a_form = false replace_right_cell(:replace_trees => [:ae]) return end end end # Set form variables for edit def set_form_vars @in_a_form_props = true session[:field_data] = {} @edit = {} session[:edit] = {} @edit[:ae_class_id] = @ae_class.id @edit[:new] = {} @edit[:current] = {} @edit[:new_field] = {} @edit[:rec_id] = @ae_class.id || nil @edit[:key] = "aeclass_edit__#{@ae_class.id || "new"}" @edit[:new][:name] = @ae_class.name @edit[:new][:display_name] = @ae_class.display_name @edit[:new][:description] = @ae_class.description @edit[:new][:namespace] = @ae_class.namespace @edit[:new][:inherits] = @ae_class.inherits @edit[:inherits_from] = MiqAeClass.all.collect { |c| [c.fqname, c.fqname] } @edit[:current] = @edit[:new].dup @right_cell_text = if @edit[:rec_id].nil? _("Adding a new %{model}") % {:model => ui_lookup(:model => "Class")} else _("Editing %{model} \"%{name}\"") % {:model => ui_lookup(:model => "Class"), :name => @ae_class.name} end session[:edit] = @edit @in_a_form = true end # Set form variables for edit def fields_set_form_vars @in_a_form_fields = true session[:field_data] = {} @edit = { :ae_class_id => @ae_class.id, :rec_id => @ae_class.id, :new_field => {}, :key => "aefields_edit__#{@ae_class.id || "new"}", :fields_to_delete => [] } @edit[:new] = { :datatypes => build_dtype_options, # setting dtype combo for adding a new field :aetypes => build_type_options # setting aetype combo for adding a new field } @edit[:new][:fields] = @ae_class.ae_fields.sort_by { |a| [a.priority.to_i] }.collect do |fld| field_attributes.each_with_object({}) do |column, hash| hash[column] = fld.send(column) end end # combo to show existing fields @combo_xml = build_type_options # passing in fields because that's how many combo boxes we need @dtype_combo_xml = build_dtype_options @edit[:current] = copy_hash(@edit[:new]) @right_cell_text = if @edit[:rec_id].nil? _("Adding a new %{model}") % {:model => ui_lookup(:model => "Class Schema")} else _("Editing %{model} \"%{name}\"") % {:model => ui_lookup(:model => "Class Schema"), :name => @ae_class.name} end session[:edit] = @edit end # Set form variables for edit def set_method_form_vars session[:field_data] = {} @ae_class = ae_class_for_instance_or_method(@ae_method) @edit = {} session[:edit] = {} @edit[:ae_method_id] = @ae_method.id @edit[:fields_to_delete] = [] @edit[:new] = {} @edit[:new_field] = {} @edit[:ae_class_id] = @ae_class.id @edit[:rec_id] = @ae_method.id || nil @edit[:key] = "aemethod_edit__#{@ae_method.id || "new"}" @sb[:form_vars_set] = true @sb[:squash_state] ||= true @edit[:new][:name] = @ae_method.name @edit[:new][:display_name] = @ae_method.display_name @edit[:new][:scope] = "instance" @edit[:new][:language] = "ruby" @edit[:new][:available_locations] = MiqAeMethod.available_locations unless @ae_method.id @edit[:new][:available_expression_objects] = MiqAeMethod.available_expression_objects.sort @edit[:new][:location] = @ae_method.location if @edit[:new][:location] == "expression" expr_hash = YAML.load(@ae_method.data) if expr_hash[:db] && expr_hash[:expression] @edit[:new][:expression] = expr_hash[:expression] expression_setup(expr_hash[:db]) end else @edit[:new][:data] = @ae_method.data.to_s end @edit[:new][:data] = @ae_method.data.to_s @edit[:default_verify_status] = @edit[:new][:location] == "inline" && @edit[:new][:data] && @edit[:new][:data] != "" @edit[:new][:fields] = @ae_method.inputs.collect do |input| method_input_column_names.each_with_object({}) do |column, hash| hash[column] = input.send(column) end end @edit[:new][:available_datatypes] = MiqAeField.available_datatypes_for_ui @edit[:current] = copy_hash(@edit[:new]) @right_cell_text = if @edit[:rec_id].nil? _("Adding a new %{model}") % {:model => ui_lookup(:model => "MiqAeMethod")} else _("Editing %{model} \"%{name}\"") % {:model => ui_lookup(:model => "MiqAeMethod"), :name => @ae_method.name} end session[:log_depot_default_verify_status] = false session[:edit] = @edit session[:changed] = @changed = false end def expression_setup(db) @edit[:expression_method] = true @edit[:new][:exp_object] = db if params[:exp_object] || params[:cls_exp_object] session[:adv_search] = nil @edit[@expkey] = @edit[:new][@expkey] = nil end adv_search_build(db) end def expression_cleanup @edit[:expression_method] = false end def ae_class_for_instance_or_method(record) record.id ? record.ae_class : MiqAeClass.find(from_cid(x_node.split("-").last)) end def validate_method_data return unless load_edit("aemethod_edit__#{params[:id]}", "replace_cell__explorer") @edit[:new][:data] = params[:cls_method_data] if params[:cls_method_data] @edit[:new][:data] = params[:method_data] if params[:method_data] res = MiqAeMethod.validate_syntax(@edit[:new][:data]) line = 0 if !res add_flash(_("Data validated successfully")) else res.each do |err| line = err[0] if line.zero? add_flash(_("Error on line %{line_num}: %{err_txt}") % {:line_num => err[0], :err_txt => err[1]}, :error) end end render :update do |page| page << javascript_prologue page << "if (miqDomElementExists('cls_method_data')){" page << "var ta = document.getElementById('cls_method_data');" page << "} else {" page << "var ta = document.getElementById('method_data');" page << "}" page.replace("flash_msg_div", :partial => "layouts/flash_msg") page << "var lineHeight = ta.clientHeight / ta.rows;" page << "ta.scrollTop = (#{line.to_i}-1) * lineHeight;" if line > 0 if @sb[:row_selected] page << "$('#cls_method_data_lines').scrollTop(ta.scrollTop);" page << "$('#cls_method_data').scrollTop(ta.scrollTop);" else page << "$('#method_data_lines').scrollTop(ta.scrollTop);" page << "$('#method_data').scrollTop(ta.scrollTop);" end end end end # AJAX driven routine to check for changes in ANY field on the form def form_field_changed return unless load_edit("aeclass_edit__#{params[:id]}", "replace_cell__explorer") get_form_vars javascript_miq_button_visibility(@edit[:new] != @edit[:current]) end # AJAX driven routine to check for changes in ANY field on the form def fields_form_field_changed return unless load_edit("aefields_edit__#{params[:id]}", "replace_cell__explorer") fields_get_form_vars @changed = (@edit[:new] != @edit[:current]) render :update do |page| page << javascript_prologue unless %w(up down).include?(params[:button]) if params[:field_datatype] == "password" page << javascript_hide("field_default_value") page << javascript_show("field_password_value") page << "$('#field_password_value').val('');" session[:field_data][:default_value] = @edit[:new_field][:default_value] = '' elsif params[:field_datatype] page << javascript_hide("field_password_value") page << javascript_show("field_default_value") page << "$('#field_default_value').val('');" session[:field_data][:default_value] = @edit[:new_field][:default_value] = '' end params.keys.each do |field| next unless field.to_s.starts_with?("fields_datatype") f = field.split('fields_datatype') def_field = "fields_default_value_" << f[1].to_s pwd_field = "fields_password_value_" << f[1].to_s if @edit[:new][:fields][f[1].to_i]['datatype'] == "password" page << javascript_hide(def_field) page << javascript_show(pwd_field) page << "$('##{pwd_field}').val('');" else page << javascript_hide(pwd_field) page << javascript_show(def_field) page << "$('##{def_field}').val('');" end @edit[:new][:fields][f[1].to_i]['default_value'] = nil end end page << javascript_for_miq_button_visibility_changed(@changed) end end # AJAX driven routine to check for changes in ANY field on the form def form_method_field_changed if !@sb[:form_vars_set] # workaround to prevent an error that happens when IE sends a transaction form form even after save button is clicked when there is text_area in the form head :ok else return unless load_edit("aemethod_edit__#{params[:id]}", "replace_cell__explorer") get_method_form_vars if @edit[:new][:location] == 'expression' @edit[:new][:exp_object] ||= @edit[:new][:available_expression_objects].first exp_object = params[:cls_exp_object] || params[:exp_object] || @edit[:new][:exp_object] expression_setup(exp_object) if exp_object else expression_cleanup end if row_selected_in_grid? @refresh_div = "class_methods_div" @refresh_partial = "class_methods" @field_name = "cls_method" else @refresh_div = "method_inputs_div" @refresh_partial = "method_inputs" @field_name = "method" end if @edit[:current][:location] == "inline" && @edit[:current][:data] @edit[:method_prev_data] = @edit[:current][:data] end @edit[:new][:data] = if @edit[:new][:location] == "inline" && !params[:cls_method_data] && !params[:method_data] && !params[:transOne] if !@edit[:method_prev_data] MiqAeMethod.default_method_text else @edit[:method_prev_data] end elsif params[:cls_method_location] || params[:method_location] # reset data if location is changed '' end @changed = (@edit[:new] != @edit[:current]) @edit[:default_verify_status] = @edit[:new][:location] == "inline" && @edit[:new][:data] && @edit[:new][:data] != "" angular_form_specific_data if @edit[:new][:location] == "playbook" render :update do |page| page << javascript_prologue page.replace_html('form_div', :partial => 'method_form', :locals => {:prefix => ""}) if @edit[:new][:location] == 'expression' if @edit[:new][:location] == "playbook" page.replace_html(@refresh_div, :partial => 'angular_method_form') page << javascript_hide("form_buttons_div") elsif @refresh_div && (params[:cls_method_location] || params[:exp_object] || params[:cls_exp_object]) page.replace_html(@refresh_div, :partial => @refresh_partial) end if params[:cls_field_datatype] if session[:field_data][:datatype] == "password" page << javascript_hide("cls_field_default_value") page << javascript_show("cls_field_password_value") page << "$('#cls_field_password_value').val('');" else page << javascript_hide("cls_field_password_value") page << javascript_show("cls_field_default_value") page << "$('#cls_field_default_value').val('');" end end if params[:method_field_datatype] if session[:field_data][:datatype] == "password" page << javascript_hide("method_field_default_value") page << javascript_show("method_field_password_value") page << "$('#method_field_password_value').val('');" else page << javascript_hide("method_field_password_value") page << javascript_show("method_field_default_value") page << "$('#method_field_default_value').val('');" end end params.keys.each do |field| if field.to_s.starts_with?("cls_fields_datatype_") f = field.split('cls_fields_datatype_') def_field = "cls_fields_value_" << f[1].to_s pwd_field = "cls_fields_password_value_" << f[1].to_s elsif field.to_s.starts_with?("fields_datatype_") f = field.split('fields_datatype_') def_field = "fields_value_" << f[1].to_s pwd_field = "fields_password_value_" << f[1].to_s end next unless f if @edit[:new][:fields][f[1].to_i]['datatype'] == "password" page << javascript_hide(def_field) page << javascript_show(pwd_field) page << "$('##{pwd_field}').val('');" else page << javascript_hide(pwd_field) page << javascript_show(def_field) page << "$('##{def_field}').val('');" end @edit[:new][:fields][f[1].to_i]['default_value'] = nil end if @edit[:default_verify_status] != session[:log_depot_default_verify_status] session[:log_depot_default_verify_status] = @edit[:default_verify_status] page << if @edit[:default_verify_status] "miqValidateButtons('show', 'default_');" else "miqValidateButtons('hide', 'default_');" end end page << javascript_for_miq_button_visibility_changed(@changed) page << "miqSparkle(false)" end end end def method_form_fields method = params[:id] == "new" ? MiqAeMethod.new : MiqAeMethod.find(params[:id]) data = method.data ? YAML.load(method.data) : {} method_hash = { :name => method.name, :display_name => method.display_name, :namespace_path => @sb[:namespace_path], :class_id => method.id ? method.class_id : MiqAeClass.find(from_cid(x_node.split("-").last)).id, :location => 'playbook', :language => 'ruby', :scope => "instance", :available_datatypes => MiqAeField.available_datatypes_for_ui, :config_info => { :repository_id => data[:repository_id] || '', :playbook_id => data[:playbook_id] || '', :credential_id => data[:credential_id] || '', :network_credential_id => data[:network_credential_id] || '', :cloud_credential_id => data[:cloud_credential_id] || '', :verbosity => data[:verbosity], :become_enabled => data[:become_enabled] || false, :extra_vars => method.inputs } } render :json => method_hash end # AJAX driven routine to check for changes in ANY field on the form def form_ns_field_changed return unless load_edit("aens_edit__#{params[:id]}", "replace_cell__explorer") get_ns_form_vars @changed = (@edit[:new] != @edit[:current]) render :update do |page| page << javascript_prologue page << javascript_for_miq_button_visibility(@changed) end end def update assert_privileges("miq_ae_class_edit") return unless load_edit("aeclass_edit__#{params[:id]}", "replace_cell__explorer") get_form_vars @changed = (@edit[:new] != @edit[:current]) case params[:button] when "cancel" session[:edit] = nil # clean out the saved info add_flash(_("Edit of %{model} \"%{name}\" was cancelled by the user") % {:model => ui_lookup(:model => "MiqAeClass"), :name => @ae_class.name}) @in_a_form = false replace_right_cell when "save" ae_class = find_record_with_rbac(MiqAeClass, params[:id]) set_record_vars(ae_class) # Set the record variables, but don't save begin MiqAeClass.transaction do ae_class.save! end rescue => bang add_flash(_("Error during 'save': %{error_message}") % {:error_message => bang.message}, :error) session[:changed] = @changed @changed = true javascript_flash else add_flash(_("%{model} \"%{name}\" was saved") % {:model => ui_lookup(:model => "MiqAeClass"), :name => ae_class.fqname}) AuditEvent.success(build_saved_audit(ae_class, @edit)) session[:edit] = nil # clean out the saved info @in_a_form = false replace_right_cell(:replace_trees => [:ae]) return end when "reset" set_form_vars session[:changed] = @changed = false add_flash(_("All changes have been reset"), :warning) @button = "reset" replace_right_cell else @changed = session[:changed] = (@edit[:new] != @edit[:current]) replace_right_cell(:replace_trees => [:ae]) end end def update_fields return unless load_edit("aefields_edit__#{params[:id]}", "replace_cell__explorer") fields_get_form_vars @changed = (@edit[:new] != @edit[:current]) case params[:button] when "cancel" session[:edit] = nil # clean out the saved info add_flash(_("Edit of schema for %{model} \"%{name}\" was cancelled by the user") % {:model => ui_lookup(:model => "MiqAeClass"), :name => @ae_class.name}) @in_a_form = false replace_right_cell when "save" ae_class = find_record_with_rbac(MiqAeClass, params[:id]) begin MiqAeClass.transaction do set_field_vars(ae_class) ae_class.ae_fields.destroy(MiqAeField.where(:id => @edit[:fields_to_delete])) ae_class.ae_fields.each { |fld| fld.default_value = nil if fld.default_value == "" } ae_class.save! end # end of transaction rescue => bang add_flash(_("Error during 'save': %{error_message}") % {:error_message => bang.message}, :error) session[:changed] = @changed = true javascript_flash else add_flash(_("Schema for %{model} \"%{name}\" was saved") % {:model => ui_lookup(:model => "MiqAeClass"), :name => ae_class.name}) AuditEvent.success(build_saved_audit(ae_class, @edit)) session[:edit] = nil # clean out the saved info @in_a_form = false replace_right_cell(:replace_trees => [:ae]) return end when "reset" fields_set_form_vars session[:changed] = @changed = false add_flash(_("All changes have been reset"), :warning) @button = "reset" @in_a_form = true replace_right_cell else @changed = session[:changed] = (@edit[:new] != @edit[:current]) replace_right_cell(:replace_trees => [:ae]) end end def update_ns assert_privileges("miq_ae_namespace_edit") return unless load_edit("aens_edit__#{params[:id]}", "replace_cell__explorer") get_ns_form_vars @changed = (@edit[:new] != @edit[:current]) case params[:button] when "cancel" session[:edit] = nil # clean out the saved info add_flash(_("Edit of %{model} \"%{name}\" was cancelled by the user") % {:model => ui_lookup(:model => @edit[:typ]), :name => @ae_ns.name}) @in_a_form = false replace_right_cell when "save" ae_ns = find_record_with_rbac(@edit[:typ].constantize, params[:id]) ns_set_record_vars(ae_ns) # Set the record variables, but don't save begin ae_ns.save! rescue => bang add_flash(_("Error during 'save': %{message}") % {:message => bang.message}, :error) session[:changed] = @changed @changed = true javascript_flash else add_flash(_("%{model} \"%{name}\" was saved") % {:model => ui_lookup(:model => @edit[:typ]), :name => get_record_display_name(ae_ns)}) AuditEvent.success(build_saved_audit(ae_ns, @edit)) session[:edit] = nil # clean out the saved info @in_a_form = false replace_right_cell(:replace_trees => [:ae]) end when "reset" ns_set_form_vars session[:changed] = @changed = false add_flash(_("All changes have been reset"), :warning) @button = "reset" replace_right_cell else @changed = session[:changed] = (@edit[:new] != @edit[:current]) replace_right_cell(:replace_trees => [:ae]) end end def add_update_method assert_privileges("miq_ae_method_edit") case params[:button] when "cancel" if params[:id] && params[:id] != "new" method = find_record_with_rbac(MiqAeMethod, params[:id]) add_flash(_("Edit of %{model} \"%{name}\" was cancelled by the user") % {:model => ui_lookup(:model => "MiqAeMethod"), :name => method.name}) else add_flash(_("Add of %{model} was cancelled by the user") % {:model => ui_lookup(:model => "MiqAeMethod")}) end replace_right_cell when "add", "save" method = params[:id] != "new" ? find_record_with_rbac(MiqAeMethod, params[:id]) : MiqAeMethod.new method.name = params["name"] method.display_name = params["display_name"] method.location = params["location"] method.language = params["language"] method.scope = params["scope"] method.class_id = params[:class_id] method.data = YAML.dump(set_playbook_data) begin MiqAeMethod.transaction do to_save, to_delete = playbook_inputs(method) method.inputs.destroy(MiqAeField.where(:id => to_delete)) method.inputs = to_save method.save! end rescue => bang add_flash(_("Error during 'save': %{error_message}") % {:error_message => bang.message}, :error) javascript_flash else old_method_attributes = method.attributes.clone add_flash(_("%{model} \"%{name}\" was saved") % {:model => ui_lookup(:model => "MiqAeMethod"), :name => method.name}) AuditEvent.success(build_saved_audit_hash_angular(old_method_attributes, method, params[:button] == "add")) replace_right_cell(:replace_trees => [:ae]) return end end end def update_method assert_privileges("miq_ae_method_edit") return unless load_edit("aemethod_edit__#{params[:id]}", "replace_cell__explorer") get_method_form_vars @changed = (@edit[:new] != @edit[:current]) case params[:button] when "cancel" session[:edit] = nil # clean out the saved info add_flash(_("Edit of %{model} \"%{name}\" was cancelled by the user") % {:model => ui_lookup(:model => "MiqAeMethod"), :name => @ae_method.name}) @sb[:form_vars_set] = false @in_a_form = false replace_right_cell when "save" # dont allow save if expression has not been added or existing one has been removed validate_expression("save") if @edit[:new][:location] == 'expression' return if flash_errors? ae_method = find_record_with_rbac(MiqAeMethod, params[:id]) set_method_record_vars(ae_method) # Set the record variables, but don't save begin MiqAeMethod.transaction do set_input_vars(ae_method) ae_method.inputs.destroy(MiqAeField.where(:id => @edit[:fields_to_delete])) ae_method.inputs.each { |fld| fld.default_value = nil if fld.default_value == "" } ae_method.save! end rescue => bang add_flash(_("Error during 'save': %{error_message}") % {:error_message => bang.message}, :error) session[:changed] = @changed @changed = true javascript_flash else add_flash(_("%{model} \"%{name}\" was saved") % {:model => ui_lookup(:model => "MiqAeMethod"), :name => ae_method.name}) AuditEvent.success(build_saved_audit(ae_method, @edit)) session[:edit] = nil # clean out the saved info @sb[:form_vars_set] = false @in_a_form = false replace_right_cell(:replace_trees => [:ae]) return end when "reset" set_method_form_vars session[:changed] = @changed = false @in_a_form = true add_flash(_("All changes have been reset"), :warning) @button = "reset" replace_right_cell else @changed = session[:changed] = (@edit[:new] != @edit[:current]) replace_right_cell end end def new assert_privileges("miq_ae_class_new") @ae_class = MiqAeClass.new set_form_vars @in_a_form = true replace_right_cell end def new_instance assert_privileges("miq_ae_instance_new") initial_setup_for_instances_form_vars(nil) set_instances_form_vars @in_a_form = true replace_right_cell end def new_method assert_privileges("miq_ae_method_new") @ae_method = MiqAeMethod.new set_method_form_vars @in_a_form = true replace_right_cell end def create assert_privileges("miq_ae_class_new") return unless load_edit("aeclass_edit__new", "replace_cell__explorer") get_form_vars @in_a_form = true case params[:button] when "cancel" add_flash(_("Add of new %{record} was cancelled by the user") % {:record => ui_lookup(:model => "MiqAeClass")}) @in_a_form = false replace_right_cell(:replace_trees => [:ae]) when "add" add_aeclass = MiqAeClass.new set_record_vars(add_aeclass) # Set the record variables, but don't save begin MiqAeClass.transaction do add_aeclass.save! end rescue => bang add_flash(_("Error during 'add': %{error_message}") % {:error_message => bang.message}, :error) @in_a_form = true render :update do |page| page << javascript_prologue page.replace("flash_msg", :partial => "layouts/flash_msg") end else add_flash(_("%{model} \"%{name}\" was added") % {:model => ui_lookup(:model => "MiqAeClass"), :name => add_aeclass.fqname}) @in_a_form = false replace_right_cell(:replace_trees => [:ae]) end else @changed = session[:changed] = (@edit[:new] != @edit[:current]) replace_right_cell(:replace_trees => [:ae]) end end def data_for_expression {:db => @edit[:new][:exp_object], :expression => @edit[:new][:expression]}.to_yaml end def create_method assert_privileges("miq_ae_method_new") @in_a_form = true case params[:button] when "cancel" add_flash(_("Add of new %{record} was cancelled by the user") % {:record => ui_lookup(:model => "MiqAeMethod")}) @sb[:form_vars_set] = false @in_a_form = false replace_right_cell when "add" return unless load_edit("aemethod_edit__new", "replace_cell__explorer") get_method_form_vars # dont allow add if expression has not been added or existing one has been removed validate_expression("add") if @edit[:new][:location] == 'expression' return if flash_errors? add_aemethod = MiqAeMethod.new set_method_record_vars(add_aemethod) # Set the record variables, but don't save begin MiqAeMethod.transaction do add_aemethod.save! set_field_vars(add_aemethod) add_aemethod.save! end rescue => bang add_flash(_("Error during 'add': %{error_message}") % {:error_message => bang.message}, :error) @in_a_form = true javascript_flash else add_flash(_("%{model} \"%{name}\" was added") % {:model => ui_lookup(:model => "MiqAeMethod"), :name => add_aemethod.name}) @sb[:form_vars_set] = false @in_a_form = false replace_right_cell(:replace_trees => [:ae]) end else @changed = session[:changed] = (@edit[:new] != @edit[:current]) @sb[:form_vars_set] = false replace_right_cell(:replace_trees => [:ae]) end end def create_ns assert_privileges("miq_ae_namespace_new") return unless load_edit("aens_edit__new", "replace_cell__explorer") get_ns_form_vars case params[:button] when "cancel" add_flash(_("Add of new %{record} was cancelled by the user") % {:record => ui_lookup(:model => @edit[:typ])}) @in_a_form = false replace_right_cell when "add" add_ae_ns = if @edit[:typ] == "MiqAeDomain" current_tenant.ae_domains.new else MiqAeNamespace.new(:parent_id => from_cid(x_node.split('-')[1])) end ns_set_record_vars(add_ae_ns) # Set the record variables, but don't save if add_ae_ns.valid? && !flash_errors? && add_ae_ns.save add_flash(_("%{model} \"%{name}\" was added") % {:model => ui_lookup(:model => add_ae_ns.class.name), :name => get_record_display_name(add_ae_ns)}) @in_a_form = false replace_right_cell(:replace_trees => [:ae]) else add_ae_ns.errors.each do |field, msg| add_flash("#{field.to_s.capitalize} #{msg}", :error) end javascript_flash end else @changed = session[:changed] = (@edit[:new] != @edit[:current]) replace_right_cell end end # AJAX driven routine to select a classification entry def field_select fields_get_form_vars @combo_xml = build_type_options @dtype_combo_xml = build_dtype_options session[:field_data] = {} @edit[:new_field][:substitute] = session[:field_data][:substitute] = true @changed = (@edit[:new] != @edit[:current]) render :update do |page| page << javascript_prologue page.replace("class_fields_div", :partial => "class_fields") page << javascript_for_miq_button_visibility(@changed) page << "miqSparkle(false);" end end # AJAX driven routine to select a classification entry def field_accept fields_get_form_vars @changed = (@edit[:new] != @edit[:current]) @combo_xml = build_type_options @dtype_combo_xml = build_dtype_options render :update do |page| page << javascript_prologue page.replace("class_fields_div", :partial => "class_fields") page << javascript_for_miq_button_visibility(@changed) page << "miqSparkle(false);" end end # AJAX driven routine to delete a classification entry def field_delete fields_get_form_vars @combo_xml = build_type_options @dtype_combo_xml = build_dtype_options if params.key?(:id) && @edit[:fields_to_delete].exclude?(params[:id]) @edit[:fields_to_delete].push(params[:id]) end @edit[:new][:fields].delete_at(params[:arr_id].to_i) @changed = (@edit[:new] != @edit[:current]) render :update do |page| page << javascript_prologue page.replace("class_fields_div", :partial => "class_fields") page << javascript_for_miq_button_visibility(@changed) page << "miqSparkle(false);" end end # AJAX driven routine to select a classification entry def field_method_select get_method_form_vars @refresh_div = "inputs_div" @refresh_partial = "inputs" @changed = (@edit[:new] != @edit[:current]) @in_a_form = true render :update do |page| page << javascript_prologue page.replace_html(@refresh_div, :partial => @refresh_partial) if row_selected_in_grid? page << javascript_show("class_methods_div") page << javascript_focus('cls_field_name') else page << javascript_show("method_inputs_div") page << javascript_focus('field_name') end page << javascript_for_miq_button_visibility(@changed) page << javascript_show("inputs_div") page << "miqSparkle(false);" end end # AJAX driven routine to select a classification entry def field_method_accept get_method_form_vars @refresh_div = "inputs_div" @refresh_partial = "inputs" session[:field_data] = {} @changed = (@edit[:new] != @edit[:current]) @in_a_form = true render :update do |page| page << javascript_prologue page.replace_html(@refresh_div, :partial => @refresh_partial) if row_selected_in_grid? page << javascript_show("class_methods_div") else page << javascript_show("method_inputs_div") end page << javascript_for_miq_button_visibility(@changed) page << javascript_show("inputs_div") page << "miqSparkle(false);" end end # AJAX driven routine to delete a classification entry def field_method_delete get_method_form_vars @refresh_div = "inputs_div" @refresh_partial = "inputs" if params.key?(:id) && @edit[:fields_to_delete].exclude?(params[:id]) @edit[:fields_to_delete].push(params[:id]) end @edit[:new][:fields].delete_at(params[:arr_id].to_i) @changed = (@edit[:new] != @edit[:current]) render :update do |page| page << javascript_prologue page.replace_html(@refresh_div, :partial => @refresh_partial) if row_selected_in_grid? page << javascript_show("class_methods_div") else page << javascript_show("method_inputs_div") end page << javascript_for_miq_button_visibility(@changed) page << javascript_show("inputs_div") page << "miqSparkle(false);" end end def handle_up_down_buttons(hash_key, field_name) case params[:button] when 'up' move_selected_fields_up(@edit[:new][hash_key], params[:seq_fields], field_name) when 'down' move_selected_fields_down(@edit[:new][hash_key], params[:seq_fields], field_name) end end # Get variables from user edit form def fields_seq_field_changed return unless load_edit("fields_edit__seq", "replace_cell__explorer") unless handle_up_down_buttons(:fields_list, _('Fields')) render_flash return end render :update do |page| page << javascript_prologue page.replace('column_lists', :partial => 'fields_seq_form') @changed = (@edit[:new] != @edit[:current]) page << javascript_for_miq_button_visibility(@changed) if @changed page << "miqsparkle(false);" end end def fields_seq_edit assert_privileges("miq_ae_field_seq") case params[:button] when "cancel" @sb[:action] = session[:edit] = nil # clean out the saved info add_flash(_("Edit of Class Schema Sequence was cancelled by the user")) @in_a_form = false replace_right_cell when "save" return unless load_edit("fields_edit__seq", "replace_cell__explorer") ae_class = MiqAeClass.find(@edit[:ae_class_id]) indexed_ae_fields = ae_class.ae_fields.index_by(&:name) @edit[:new][:fields_list].each_with_index do |f, i| fname = f.split('(').last.split(')').first # leave display name and parenthesis out indexed_ae_fields[fname].try(:priority=, i + 1) end unless ae_class.save flash_validation_errors(ae_class) @in_a_form = true @changed = true javascript_flash return end AuditEvent.success(build_saved_audit(ae_class, @edit)) add_flash(_("Class Schema Sequence was saved")) @sb[:action] = @edit = session[:edit] = nil # clean out the saved info @in_a_form = false replace_right_cell when "reset", nil # Reset or first time in id = params[:id] ? params[:id] : from_cid(@edit[:ae_class_id]) @in_a_form = true fields_seq_edit_screen(id) if params[:button] == "reset" add_flash(_("All changes have been reset"), :warning) end replace_right_cell end end def priority_form_field_changed return unless load_edit(params[:id], "replace_cell__explorer") @in_a_form = true unless handle_up_down_buttons(:domain_order, _('Domains')) render_flash return end render :update do |page| page << javascript_prologue page.replace('domains_list', :partial => 'domains_priority_form', :locals => {:action => "domains_priority_edit"}) @changed = (@edit[:new] != @edit[:current]) page << javascript_for_miq_button_visibility(@changed) if @changed page << "miqsparkle(false);" end end def domains_priority_edit assert_privileges("miq_ae_domain_priority_edit") case params[:button] when "cancel" @sb[:action] = @in_a_form = @edit = session[:edit] = nil # clean out the saved info add_flash(_("Edit of Priority Order was cancelled by the user")) replace_right_cell when "save" return unless load_edit("priority__edit", "replace_cell__explorer") domains = @edit[:new][:domain_order].reverse!.collect do |domain| MiqAeDomain.find_by(:name => domain.split(' (Locked)').first).id end current_tenant.reset_domain_priority_by_ordered_ids(domains) add_flash(_("Priority Order was saved")) @sb[:action] = @in_a_form = @edit = session[:edit] = nil # clean out the saved info replace_right_cell(:replace_trees => [:ae]) when "reset", nil # Reset or first time in priority_edit_screen add_flash(_("All changes have been reset"), :warning) if params[:button] == "reset" session[:changed] = @changed = false replace_right_cell end end def objects_to_copy ids = find_checked_items if ids items_without_prefix = [] ids.each do |item| values = item.split("-") # remove any namespaces that were selected in grid items_without_prefix.push(values.last) unless values.first == "aen" end items_without_prefix else [params[:id]] end end def copy_objects ids = objects_to_copy if ids.blank? add_flash(_("Copy does not apply to selected %{model}") % {:model => ui_lookup(:model => "MiqAeNamespace")}, :error) @sb[:action] = session[:edit] = nil @in_a_form = false replace_right_cell return end case params[:button] when "cancel" copy_cancel when "copy" copy_save when "reset", nil # Reset or first time in action = params[:pressed] || @sb[:action] klass = case action when "miq_ae_class_copy" MiqAeClass when "miq_ae_instance_copy" MiqAeInstance when "miq_ae_method_copy" MiqAeMethod end copy_reset(klass, ids, action) end end def form_copy_objects_field_changed return unless load_edit("copy_objects__#{params[:id]}", "replace_cell__explorer") copy_objects_get_form_vars build_ae_tree(:automate, :automate_tree) @changed = (@edit[:new] != @edit[:current]) @changed = @edit[:new][:override_source] if @edit[:new][:namespace].nil? render :update do |page| page << javascript_prologue page.replace("flash_msg_div", :partial => "layouts/flash_msg") page.replace("form_div", :partial => "copy_objects_form") if params[:domain] || params[:override_source] page << javascript_for_miq_button_visibility(@changed) end end def ae_tree_select_toggle @edit = session[:edit] self.x_active_tree = :ae_tree at_tree_select_toggle(:namespace) if params[:button] == 'submit' x_node_set(@edit[:active_id], :automate_tree) @edit[:namespace] = @edit[:new][:namespace] end session[:edit] = @edit end def ae_tree_select @edit = session[:edit] at_tree_select(:namespace) session[:edit] = @edit end def x_show typ, id = params[:id].split("-") @record = TreeBuilder.get_model_for_prefix(typ).constantize.find(from_cid(id)) tree_select end def refresh_git_domain if params[:button] == "save" git_based_domain_import_service.import(params[:git_repo_id], params[:git_branch_or_tag], current_tenant.id) add_flash(_("Successfully refreshed!"), :info) else add_flash(_("Git based refresh canceled"), :info) end session[:edit] = nil @in_a_form = false replace_right_cell(:replace_trees => [:ae]) end private def playbook_inputs(method) existing_inputs = method.inputs new_inputs = params[:extra_vars] inputs_to_save = [] inputs_to_delete = [] new_inputs.each do |i, input| field = input.length == 4 ? MiqAeField.find_by(:id => input.last) : MiqAeField.new field.name = input[0] field.default_value = input[1] == "" ? nil : input[1] field.datatype = input[2] field.priority = i inputs_to_save.push(field) end existing_inputs.each do |existing_input| inputs_to_delete.push(existing_input.id) unless inputs_to_save.any? { |i| i.id == existing_input.id } end return inputs_to_save, inputs_to_delete end def set_playbook_data data = { :repository_id => params['repository_id'], :playbook_id => params['playbook_id'], :credential_id => params['credential_id'], :become_enabled => params['become_enabled'], :verbosity => params['verbosity'], } data[:network_credential_id] = params['network_credential_id'] if params['network_credential_id'] data[:cloud_credential_id] = params['cloud_credential_id'] if params['cloud_credential_id'] data end def angular_form_specific_data @record = @ae_method @ae_class = ae_class_for_instance_or_method(@ae_method) @current_region = MiqRegion.my_region.region @angular_form = true end def validate_expression(task) if @edit[@expkey][:expression]["???"] == "???" add_flash(_("Error during '%{task}': Expression element is required") % {:task => _(task)}, :error) @in_a_form = true javascript_flash end end def features [ApplicationController::Feature.new_with_hash(:role => "miq_ae_class_explorer", :role_any => true, :name => :ae, :accord_name => "datastores", :title => _("Datastore"))] end def initial_setup_for_instances_form_vars(ae_inst_id) @ae_inst = ae_inst_id ? MiqAeInstance.find(ae_inst_id) : MiqAeInstance.new @ae_class = ae_class_for_instance_or_method(@ae_inst) @ae_values = @ae_class.ae_fields.sort_by { |a| [a.priority.to_i] }.collect do |fld| MiqAeValue.find_or_initialize_by(:field_id => fld.id.to_s, :instance_id => @ae_inst.id.to_s) end end def instance_column_names %w(name description display_name) end def field_column_names %w(aetype collect datatype default_value display_name name on_entry on_error on_exit substitute) end def value_column_names %w(collect display_name on_entry on_error on_exit max_retries max_time value) end def method_input_column_names %w(datatype default_value id name priority) end def copy_objects_get_form_vars %w(domain override_existing override_source namespace new_name).each do |field| fld = field.to_sym if %w(override_existing override_source).include?(field) @edit[:new][fld] = params[fld] == "1" if params[fld] @edit[:new][:namespace] = nil if @edit[:new][:override_source] else @edit[:new][fld] = params[fld] if params[fld] if fld == :domain && params[fld] # save domain in sandbox, treebuilder doesnt have access to @edit @sb[:domain_id] = params[fld] @edit[:new][:namespace] = nil @edit[:new][:new_name] = nil end end end end def copy_save assert_privileges(@sb[:action]) return unless load_edit("copy_objects__#{params[:id]}", "replace_cell__explorer") begin @record = @edit[:typ].find(@edit[:rec_id]) domain = MiqAeDomain.find(@edit[:new][:domain]) @edit[:new][:new_name] = nil if @edit[:new][:new_name] == @edit[:old_name] options = { :ids => @edit[:selected_items].keys, :domain => domain.name, :namespace => @edit[:new][:namespace], :overwrite_location => @edit[:new][:override_existing], :new_name => @edit[:new][:new_name], :fqname => @edit[:fqname] } res = @edit[:typ].copy(options) rescue => bang render_flash(_("Error during '%{record} copy': %{error_message}") % {:record => ui_lookup(:model => @edit[:typ].to_s), :error_message => bang.message}, :error) return end model = @edit[:selected_items].count > 1 ? :models : :model add_flash(_("Copy selected %{record} was saved") % {:record => ui_lookup(model => @edit[:typ].to_s)}) @record = res.kind_of?(Array) ? @edit[:typ].find(res.first) : res self.x_node = "#{TreeBuilder.get_prefix_for_model(@edit[:typ])}-#{to_cid(@record.id)}" @in_a_form = @changed = session[:changed] = false @sb[:action] = @edit = session[:edit] = nil replace_right_cell end def copy_reset(typ, ids, button_pressed) assert_privileges(button_pressed) @changed = session[:changed] = @in_a_form = true copy_objects_edit_screen(typ, ids, button_pressed) if params[:button] == "reset" add_flash(_("All changes have been reset"), :warning) end build_ae_tree(:automate, :automate_tree) replace_right_cell end def copy_cancel assert_privileges(@sb[:action]) @record = session[:edit][:typ].find_by(:id => session[:edit][:rec_id]) model = @edit[:selected_items].count > 1 ? :models : :model @sb[:action] = session[:edit] = nil # clean out the saved info add_flash(_("Copy %{record} was cancelled by the user") % {:record => ui_lookup(model => @edit[:typ].to_s)}) @in_a_form = false replace_right_cell end def copy_objects_edit_screen(typ, ids, button_pressed) domains = {} selected_items = {} ids.each_with_index do |id, i| record = find_record_with_rbac(typ, from_cid(id)) selected_items[record.id] = record.display_name.blank? ? record.name : "#{record.display_name} (#{record.name})" @record = record if i.zero? end current_tenant.editable_domains.collect { |domain| domains[domain.id] = domain_display_name(domain) } initialize_copy_edit_vars(typ, button_pressed, domains, selected_items) @sb[:domain_id] = domains.first.first @edit[:current] = copy_hash(@edit[:new]) model = @edit[:selected_items].count > 1 ? :models : :model @right_cell_text = _("Copy %{model}") % {:model => ui_lookup(model => typ.to_s)} session[:edit] = @edit end def initialize_copy_edit_vars(typ, button_pressed, domains, selected_items) @edit = { :typ => typ, :action => button_pressed, :domain_name => @record.domain.name, :domain_id => @record.domain.id, :old_name => @record.name, :fqname => @record.fqname, :rec_id => from_cid(@record.id), :key => "copy_objects__#{from_cid(@record.id)}", :domains => domains, :selected_items => selected_items, :namespaces => {} } @edit[:new] = { :domain => domains.first.first, :override_source => true, :namespace => nil, :new_name => nil, :override_existing => false } end def create_action_url(node) if @sb[:action] == "miq_ae_domain_priority_edit" 'domains_priority_edit' elsif @sb[:action] == 'miq_ae_field_seq' 'fields_seq_edit' elsif MIQ_AE_COPY_ACTIONS.include?(@sb[:action]) 'copy_objects' else prefix = @edit[:rec_id].nil? ? 'create' : 'update' if node == 'aec' suffix_hash = { 'instances' => '_instance', 'methods' => '_method', 'props' => '', 'schema' => '_fields' } suffix = suffix_hash[@sb[:active_tab]] else suffix_hash = { 'root' => '_ns', 'aei' => '_instance', 'aem' => '_method', 'aen' => @edit.key?(:ae_class_id) ? '' : '_ns' } suffix = suffix_hash[node] end prefix + suffix end end def get_rec_name(rec) column = rec.display_name.blank? ? :name : :display_name if rec.kind_of?(MiqAeNamespace) && rec.domain? editable_domain = editable_domain?(rec) enabled_domain = rec.enabled unless editable_domain && enabled_domain return add_read_only_suffix(rec.send(column), editable_domain?(rec), enabled_domain) end end rec.send(column) end # Delete all selected or single displayed aeclasses(s) def deleteclasses assert_privileges("miq_ae_class_delete") delete_namespaces_or_classes end # Common aeclasses button handler routines def process_aeclasses(aeclasses, task) process_elements(aeclasses, MiqAeClass, task) end # Delete all selected or single displayed aeclasses(s) def deleteinstances assert_privileges("miq_ae_instance_delete") aeinstances = [] @sb[:row_selected] = find_checked_items if @sb[:row_selected] @sb[:row_selected].each do |items| item = items.split('-') item = find_id_with_rbac(MiqAeInstance, from_cid(item[1])) aeinstances.push(from_cid(item[1])) end else node = x_node.split('-') aeinstances.push(from_cid(node[1])) inst = find_record_with_rbac(MiqAeInstance, from_cid(node[1])) self.x_node = "aec-#{to_cid(inst.class_id)}" end process_aeinstances(aeinstances, "destroy") unless aeinstances.empty? replace_right_cell(:replace_trees => [:ae]) end # Common aeclasses button handler routines def process_aeinstances(aeinstances, task) process_elements(aeinstances, MiqAeInstance, task) end # Delete all selected or single displayed aeclasses(s) def deletemethods assert_privileges("miq_ae_method_delete") aemethods = [] @sb[:row_selected] = find_checked_items if @sb[:row_selected] @sb[:row_selected].each do |items| item = items.split('-') item = find_id_with_rbac(MiqAeMethod, from_cid(item[1])) aemethods.push(from_cid(item[1])) end else node = x_node.split('-') aemethods.push(from_cid(node[1])) inst = find_record_with_rbac(MiqAeMethod, from_cid(node[1])) self.x_node = "aec-#{to_cid(inst.class_id)}" end process_aemethods(aemethods, "destroy") unless aemethods.empty? replace_right_cell(:replace_trees => [:ae]) end # Common aeclasses button handler routines def process_aemethods(aemethods, task) process_elements(aemethods, MiqAeMethod, task) end def delete_domain assert_privileges("miq_ae_domain_delete") aedomains = [] git_domains = [] if params[:id] aedomains.push(params[:id]) self.x_node = "root" else selected = find_checked_items selected_ids = selected.map { |x| from_cid(x.split('-')[1]) } # TODO: replace with RBAC safe method #14665 is merged domains = MiqAeDomain.where(:id => selected_ids) domains.each do |domain| if domain.editable_properties? domain.git_enabled? ? git_domains.push(domain) : aedomains.push(domain.id) else add_flash(_("Read Only %{model} \"%{name}\" cannot be deleted") % {:model => ui_lookup(:model => "MiqAeDomain"), :name => get_record_display_name(domain)}, :error) end end end process_elements(aedomains, MiqAeDomain, 'destroy') unless aedomains.empty? git_domains.each do |domain| process_element_destroy_via_queue(domain, domain.class, domain.name) end replace_right_cell(:replace_trees => [:ae]) end # Delete all selected or single displayed aeclasses(s) def delete_ns assert_privileges("miq_ae_namespace_delete") delete_namespaces_or_classes end def delete_namespaces_or_classes selected = find_checked_items ae_ns = [] ae_cs = [] node = x_node.split('-') if params[:id] && params[:miq_grid_checks].blank? && node.first == "aen" ae_ns.push(params[:id]) ns = find_record_with_rbac(MiqAeNamespace, from_cid(node[1])) self.x_node = ns.parent_id ? "aen-#{to_cid(ns.parent_id)}" : "root" elsif selected ae_ns, ae_cs = items_to_delete(selected) else ae_cs.push(from_cid(node[1])) cls = find_record_with_rbac(MiqAeClass, from_cid(node[1])) self.x_node = "aen-#{to_cid(cls.namespace_id)}" end process_ae_ns(ae_ns, "destroy") unless ae_ns.empty? process_aeclasses(ae_cs, "destroy") unless ae_cs.empty? replace_right_cell(:replace_trees => [:ae]) end def items_to_delete(selected) ns_list = [] cs_list = [] selected.each do |items| item = items.split('-') if item[0] == "aen" record = find_record_with_rbac(MiqAeNamespace, from_cid(item[1])) if (record.domain? && record.editable_properties?) || record.editable? ns_list.push(from_cid(item[1])) else add_flash(_("\"%{field}\" %{model} cannot be deleted") % {:model => ui_lookup(:model => "MiqAeDomain"), :field => get_record_display_name(record)}, :error) end else cs_list.push(from_cid(item[1])) end end return ns_list, cs_list end # Common aeclasses button handler routines def process_ae_ns(ae_ns, task) process_elements(ae_ns, MiqAeNamespace, task) end # Get variables from edit form def get_form_vars @ae_class = MiqAeClass.find_by(:id => from_cid(@edit[:ae_class_id])) # for class add tab @edit[:new][:name] = params[:name].blank? ? nil : params[:name] if params[:name] @edit[:new][:description] = params[:description].blank? ? nil : params[:description] if params[:description] @edit[:new][:display_name] = params[:display_name].blank? ? nil : params[:display_name] if params[:display_name] @edit[:new][:namespace] = params[:namespace] if params[:namespace] @edit[:new][:inherits] = params[:inherits_from] if params[:inherits_from] # for class edit tab @edit[:new][:name] = params[:cls_name].blank? ? nil : params[:cls_name] if params[:cls_name] @edit[:new][:description] = params[:cls_description].blank? ? nil : params[:cls_description] if params[:cls_description] @edit[:new][:display_name] = params[:cls_display_name].blank? ? nil : params[:cls_display_name] if params[:cls_display_name] @edit[:new][:namespace] = params[:cls_namespace] if params[:cls_namespace] @edit[:new][:inherits] = params[:cls_inherits_from] if params[:cls_inherits_from] end # Common routine to find checked items on a page (checkbox ids are "check_xxx" where xxx is the item id or index) def find_checked_items(_prefix = nil) # AE can't use ApplicationController#find_checked_items because that one expects non-prefixed ids params[:miq_grid_checks].split(",") unless params[:miq_grid_checks].blank? end def field_attributes %w(aetype class_id collect datatype default_value description display_name id max_retries max_time message name on_entry on_error on_exit priority substitute) end def row_selected_in_grid? @sb[:row_selected] || x_node.split('-').first == "aec" end helper_method :row_selected_in_grid? # Get variables from edit form def fields_get_form_vars @ae_class = MiqAeClass.find_by(:id => from_cid(@edit[:ae_class_id])) @in_a_form = true @in_a_form_fields = true if params[:item].blank? && !%w(accept save).include?(params[:button]) && params["action"] != "field_delete" field_data = session[:field_data] new_field = @edit[:new_field] field_attributes.each do |field| field_name = "field_#{field}".to_sym field_sym = field.to_sym if field == "substitute" field_data[field_sym] = new_field[field_sym] = params[field_name] == "1" if params[field_name] elsif params[field_name] field_data[field_sym] = new_field[field_sym] = params[field_name] end end field_data[:default_value] = new_field[:default_value] = params[:field_password_value] if params[:field_password_value] new_field[:priority] = 1 @edit[:new][:fields].each_with_index do |flds, i| if i == @edit[:new][:fields].length - 1 new_field[:priority] = flds['priority'].nil? ? 1 : flds['priority'].to_i + 1 end end new_field[:class_id] = @ae_class.id @edit[:new][:fields].each_with_index do |fld, i| field_attributes.each do |field| field_name = "fields_#{field}_#{i}" if field == "substitute" fld[field] = params[field_name] == "1" if params[field_name] elsif %w(aetype datatype).include?(field) var_name = "fields_#{field}#{i}" fld[field] = params[var_name.to_sym] if params[var_name.to_sym] elsif field == "default_value" fld[field] = params[field_name] if params[field_name] fld[field] = params["fields_password_value_#{i}".to_sym] if params["fields_password_value_#{i}".to_sym] elsif params[field_name] fld[field] = params[field_name] end end end elsif params[:button] == "accept" if session[:field_data][:name].blank? || session[:field_data][:aetype].blank? field = session[:field_data][:name].blank? ? "Name" : "Type" field += " and Type" if field == "Name" && session[:field_data][:aetype].blank? add_flash(_("%{field} is required") % {:field => field}, :error) return end new_fields = {} field_attributes.each do |field_attribute| new_fields[field_attribute] = @edit[:new_field][field_attribute.to_sym] end @edit[:new][:fields].push(new_fields) @edit[:new_field] = session[:field_data] = {} end end def method_form_vars_process_fields(prefix = '') @edit[:new][:fields].each_with_index do |field, i| method_input_column_names.each do |column| field[column] = params["#{prefix}fields_#{column}_#{i}".to_sym] if params["#{prefix}fields_#{column}_#{i}".to_sym] next unless column == 'default_value' field[column] = params["#{prefix}fields_value_#{i}".to_sym] if params["#{prefix}fields_value_#{i}".to_sym] field[column] = params["#{prefix}fields_password_value_#{i}".to_sym] if params["#{prefix}fields_password_value_#{i}".to_sym] end end end # Get variables from edit form def get_method_form_vars @ae_method = @edit[:ae_method_id] ? MiqAeMethod.find(from_cid(@edit[:ae_method_id])) : MiqAeMethod.new @in_a_form = true if params[:item].blank? && params[:button] != "accept" && params["action"] != "field_delete" # for method_inputs view @edit[:new][:name] = params[:method_name].blank? ? nil : params[:method_name] if params[:method_name] @edit[:new][:display_name] = params[:method_display_name].blank? ? nil : params[:method_display_name] if params[:method_display_name] @edit[:new][:location] = params[:method_location] if params[:method_location] @edit[:new][:location] ||= "inline" @edit[:new][:data] = params[:method_data] if params[:method_data] method_form_vars_process_fields session[:field_data][:name] = @edit[:new_field][:name] = params[:field_name] if params[:field_name] session[:field_data][:datatype] = @edit[:new_field][:datatype] = params[:field_datatype] if params[:field_datatype] session[:field_data][:default_value] = @edit[:new_field][:default_value] = params[:field_default_value] if params[:field_default_value] session[:field_data][:default_value] = @edit[:new_field][:default_value] = params[:field_password_value] if params[:field_password_value] # for class_methods view @edit[:new][:name] = params[:cls_method_name].blank? ? nil : params[:cls_method_name] if params[:cls_method_name] @edit[:new][:display_name] = params[:cls_method_display_name].blank? ? nil : params[:cls_method_display_name] if params[:cls_method_display_name] @edit[:new][:location] = params[:cls_method_location] if params[:cls_method_location] @edit[:new][:location] ||= "inline" @edit[:new][:data] = params[:cls_method_data] if params[:cls_method_data] @edit[:new][:data] += "..." if params[:transOne] && params[:transOne] == "1" # Update the new data to simulate a change method_form_vars_process_fields('cls_') session[:field_data][:name] = @edit[:new_field][:name] = params[:cls_field_name] if params[:cls_field_name] session[:field_data][:datatype] = @edit[:new_field][:datatype] = params[:cls_field_datatype] if params[:cls_field_datatype] session[:field_data][:default_value] = @edit[:new_field][:default_value] = params[:cls_field_default_value] if params[:cls_field_default_value] session[:field_data][:default_value] = @edit[:new_field][:default_value] = params[:cls_field_password_value] if params[:cls_field_password_value] @edit[:new_field][:method_id] = @ae_method.id session[:field_data] ||= {} elsif params[:button] == "accept" if @edit[:new_field].blank? || @edit[:new_field][:name].nil? || @edit[:new_field][:name] == "" add_flash(_("Name is required"), :error) return end new_field = {} new_field['name'] = @edit[:new_field][:name] new_field['datatype'] = @edit[:new_field][:datatype] new_field['default_value'] = @edit[:new_field][:default_value] new_field['method_id'] = @ae_method.id @edit[:new][:fields].push(new_field) @edit[:new_field] = { :name => '', :default_value => '', :datatype => 'string' } elsif params[:add] == 'new' session[:fields_data] = { :name => '', :default_value => '', :datatype => 'string' } end end # Get variables from edit form def get_ns_form_vars @ae_ns = @edit[:typ].constantize.find_by(:id => from_cid(@edit[:ae_ns_id])) @edit[:new][:enabled] = params[:ns_enabled] == '1' if params[:ns_enabled] [:ns_name, :ns_description].each do |field| next unless params[field] @edit[:new][field] = params[field].blank? ? nil : params[field] end @in_a_form = true end def get_instances_form_vars_for(prefix = nil) instance_column_names.each do |key| @edit[:new][:ae_inst][key] = params["#{prefix}inst_#{key}"].blank? ? nil : params["#{prefix}inst_#{key}"] if params["#{prefix}inst_#{key}"] end @ae_class.ae_fields.sort_by { |a| [a.priority.to_i] }.each_with_index do |_fld, i| %w(value collect on_entry on_exit on_error max_retries max_time).each do |key| @edit[:new][:ae_values][i][key] = params["#{prefix}inst_#{key}_#{i}".to_sym] if params["#{prefix}inst_#{key}_#{i}".to_sym] end @edit[:new][:ae_values][i]["value"] = params["#{prefix}inst_password_value_#{i}".to_sym] if params["#{prefix}inst_password_value_#{i}".to_sym] end end # Get variables from edit form def get_instances_form_vars # resetting inst/class/values from id stored in @edit. @ae_inst = @edit[:ae_inst_id] ? MiqAeInstance.find(@edit[:ae_inst_id]) : MiqAeInstance.new @ae_class = MiqAeClass.find(from_cid(@edit[:ae_class_id])) @ae_values = @ae_class.ae_fields.sort_by { |a| a.priority.to_i }.collect do |fld| MiqAeValue.find_or_initialize_by(:field_id => fld.id.to_s, :instance_id => @ae_inst.id.to_s) end if x_node.split('-').first == "aei" # for instance_fields view get_instances_form_vars_for else # for class_instances view get_instances_form_vars_for("cls_") end end # Set record variables to new values def set_record_vars(miqaeclass) miqaeclass.name = @edit[:new][:name].strip unless @edit[:new][:name].blank? miqaeclass.display_name = @edit[:new][:display_name] miqaeclass.description = @edit[:new][:description] miqaeclass.inherits = @edit[:new][:inherits] ns = x_node.split("-") if ns.first == "aen" && !miqaeclass.namespace_id rec = MiqAeNamespace.find(from_cid(ns[1])) miqaeclass.namespace_id = rec.id.to_s # miqaeclass.namespace = rec.name end end # Set record variables to new values def set_method_record_vars(miqaemethod) miqaemethod.name = @edit[:new][:name].strip unless @edit[:new][:name].blank? miqaemethod.display_name = @edit[:new][:display_name] miqaemethod.scope = @edit[:new][:scope] miqaemethod.location = @edit[:new][:location] miqaemethod.language = @edit[:new][:language] miqaemethod.data = if @edit[:new][:location] == 'expression' data_for_expression else @edit[:new][:data] end miqaemethod.class_id = from_cid(@edit[:ae_class_id]) end # Set record variables to new values def ns_set_record_vars(miqaens) miqaens.name = @edit[:new][:ns_name].strip unless @edit[:new][:ns_name].blank? miqaens.description = @edit[:new][:ns_description] miqaens.enabled = @edit[:new][:enabled] if miqaens.domain? end # Set record variables to new values def set_field_vars(parent = nil) fields = parent_fields(parent) highest_priority = fields.count @edit[:new][:fields].each_with_index do |fld, i| if fld["id"].nil? new_field = MiqAeField.new highest_priority += 1 new_field.priority = highest_priority if @ae_method new_field.method_id = @ae_method.id else new_field.class_id = @ae_class.id end else new_field = parent.nil? ? MiqAeField.find(fld["id"]) : fields.detect { |f| f.id == fld["id"] } end field_attributes.each do |attr| if attr == "substitute" || @edit[:new][:fields][i][attr] new_field.send("#{attr}=", @edit[:new][:fields][i][attr]) end end if new_field.new_record? || parent.nil? raise StandardError, new_field.errors.full_messages[0] unless fields.push(new_field) end end reset_field_priority(fields) end alias_method :set_input_vars, :set_field_vars def parent_fields(parent) return [] unless parent parent.class == MiqAeClass ? parent.ae_fields : parent.inputs end def reset_field_priority(fields) # reset priority to be in order 1..3 i = 0 fields.sort_by { |a| [a.priority.to_i] }.each do |fld| if !@edit[:fields_to_delete].include?(fld.id.to_s) || fld.id.blank? i += 1 fld.priority = i end end fields end # Set record variables to new values def set_instances_record_vars(miqaeinst) instance_column_names.each do |attr| miqaeinst.send("#{attr}=", @edit[:new][:ae_inst][attr].try(:strip)) end miqaeinst.class_id = from_cid(@edit[:ae_class_id]) end # Set record variables to new values def set_instances_value_vars(vals, ae_instance = nil) original_values = ae_instance ? ae_instance.ae_values : [] vals.each_with_index do |v, i| original = original_values.detect { |ov| ov.id == v.id } unless original_values.empty? if original v = original elsif ae_instance ae_instance.ae_values << v end value_column_names.each do |attr| v.send("#{attr}=", @edit[:new][:ae_values][i][attr]) if @edit[:new][:ae_values][i][attr] end end end def fields_seq_edit_screen(id) @edit = {} @edit[:new] = {} @edit[:current] = {} @ae_class = MiqAeClass.find_by(:id => from_cid(id)) @edit[:rec_id] = @ae_class.try(:id) @edit[:ae_class_id] = @ae_class.id @edit[:new][:fields] = @ae_class.ae_fields.to_a.deep_clone @edit[:new][:fields_list] = @edit[:new][:fields] .sort_by { |f| f.priority.to_i } .collect { |f| f.display_name ? "#{f.display_name} (#{f.name})" : "(#{f.name})" } @edit[:key] = "fields_edit__seq" @edit[:current] = copy_hash(@edit[:new]) @right_cell_text = _("Edit of Class Schema Sequence '%{name}'") % {:name => @ae_class.name} session[:edit] = @edit end def move_selected_fields_up(available_fields, selected_fields, display_name) if no_items_selected?(selected_fields) add_flash(_("No %{name} were selected to move up") % {:name => display_name}, :error) return false end consecutive, first_idx, last_idx = selected_consecutive?(available_fields, selected_fields) @selected = selected_fields if consecutive if first_idx > 0 available_fields[first_idx..last_idx].reverse_each do |field| pulled = available_fields.delete(field) available_fields.insert(first_idx - 1, pulled) end end return true end add_flash(_("Select only one or consecutive %{name} to move up") % {:name => display_name}, :error) false end def move_selected_fields_down(available_fields, selected_fields, display_name) if no_items_selected?(selected_fields) add_flash(_("No %{name} were selected to move down") % {:name => display_name}, :error) return false end consecutive, first_idx, last_idx = selected_consecutive?(available_fields, selected_fields) @selected = selected_fields if consecutive if last_idx < available_fields.length - 1 insert_idx = last_idx + 1 # Insert before the element after the last one insert_idx = -1 if last_idx == available_fields.length - 2 # Insert at end if 1 away from end available_fields[first_idx..last_idx].each do |field| pulled = available_fields.delete(field) available_fields.insert(insert_idx, pulled) end end return true end add_flash(_("Select only one or consecutive %{name} to move down") % {:name => display_name}, :error) false end def no_items_selected?(field_name) !field_name || field_name.empty? || field_name[0] == "" end def selected_consecutive?(available_fields, selected_fields) first_idx = last_idx = 0 available_fields.each_with_index do |nf, idx| first_idx = idx if nf == selected_fields.first if nf == selected_fields.last last_idx = idx break end end if last_idx - first_idx + 1 > selected_fields.length return [false, first_idx, last_idx] else return [true, first_idx, last_idx] end end def edit_domain_or_namespace obj = find_checked_items obj = [x_node] if obj.nil? && params[:id] typ = params[:pressed] == "miq_ae_domain_edit" ? MiqAeDomain : MiqAeNamespace @ae_ns = find_record_with_rbac(typ, from_cid(obj[0].split('-')[1])) if @ae_ns.domain? && !@ae_ns.editable_properties? add_flash(_("Read Only %{model} \"%{name}\" cannot be edited") % {:model => ui_lookup(:model => "MiqAeDomain"), :name => get_record_display_name(@ae_ns)}, :error) else ns_set_form_vars @in_a_form = true session[:changed] = @changed = false end replace_right_cell end def new_ns assert_privileges("miq_ae_namespace_new") new_domain_or_namespace(MiqAeNamespace) end def new_domain assert_privileges("miq_ae_domain_new") new_domain_or_namespace(MiqAeDomain) end def new_domain_or_namespace(klass) parent_id = x_node == "root" ? nil : from_cid(x_node.split("-").last) @ae_ns = klass.new(:parent_id => parent_id) ns_set_form_vars @in_a_form = true replace_right_cell end # Set form variables for edit def ns_set_form_vars session[:field_data] = session[:edit] = {} @edit = { :ae_ns_id => @ae_ns.id, :typ => @ae_ns.domain? ? "MiqAeDomain" : "MiqAeNamespace", :key => "aens_edit__#{@ae_ns.id || "new"}", :rec_id => @ae_ns.id || nil } @edit[:new] = { :ns_name => @ae_ns.name, :ns_description => @ae_ns.description } # set these field for a new domain or when existing record is a domain @edit[:new][:enabled] = @ae_ns.enabled if @ae_ns.domain? @edit[:current] = @edit[:new].dup @right_cell_text = ns_right_cell_text session[:edit] = @edit end def ns_right_cell_text model = ui_lookup(:model => @edit[:typ]) name_for_msg = if @edit[:rec_id].nil? _("Adding a new %{model}") % {:model => model} else _("Editing %{model} \"%{name}\"") % {:model => model, :name => @ae_ns.name} end name_for_msg end def ordered_domains_for_priority_edit_screen User.current_tenant.sequenceable_domains.collect(&:name) end def priority_edit_screen @in_a_form = true @edit = { :key => "priority__edit", :new => {:domain_order => ordered_domains_for_priority_edit_screen} } @edit[:current] = copy_hash(@edit[:new]) session[:edit] = @edit end def domain_toggle(locked) assert_privileges("miq_ae_domain_#{locked ? 'lock' : 'unlock'}") action = locked ? _("Locked") : _("Unlocked") if params[:id].nil? add_flash(_("No %{model} were selected to be marked as %{action}") % {:model => ui_lookup(:model => "MiqAeDomain"), :action => action}, :error) javascript_flash end domain_toggle_lock(params[:id], locked) unless flash_errors? add_flash(_("The selected %{model} were marked as %{action}") % {:model => ui_lookup(:model => "MiqAeDomain"), :action => action}, :info, true) end replace_right_cell(:replace_trees => [:ae]) end def domain_lock domain_toggle(true) end def domain_unlock domain_toggle(false) end def domain_toggle_lock(domain_id, lock) domain = MiqAeDomain.find(domain_id) lock ? domain.lock_contents! : domain.unlock_contents! end def git_refresh @in_a_form = true @explorer = true session[:changed] = true git_repo = MiqAeDomain.find(params[:id]).git_repository git_based_domain_import_service.refresh(git_repo.id) git_repo.reload @branch_names = git_repo.git_branches.collect(&:name) @tag_names = git_repo.git_tags.collect(&:name) @git_repo_id = git_repo.id @right_cell_text = _("Refreshing branch/tag for Git-based Domain") h_tb = build_toolbar("x_history_tb") presenter = ExplorerPresenter.new( :active_tree => x_active_tree, :right_cell_text => @right_cell_text, :remove_nodes => nil, :add_nodes => nil, ) update_partial_div = :main_div update_partial = "git_domain_refresh" presenter.update(update_partial_div, r[:partial => update_partial]) action_url = "refresh_git_domain" presenter.show(:paging_div, :form_buttons_div) presenter.update(:form_buttons_div, r[ :partial => "layouts/x_edit_buttons", :locals => { :record_id => git_repo.id, :action_url => action_url, :serialize => true, :no_reset => true } ]) presenter.reload_toolbars(:history => h_tb) presenter.show(:toolbar) render :json => presenter.for_render end def git_based_domain_import_service @git_based_domain_import_service ||= GitBasedDomainImportService.new end def get_instance_node_info(id) begin @record = MiqAeInstance.find(from_cid(id[1])) rescue ActiveRecord::RecordNotFound set_root_node return end @ae_class = @record.ae_class @sb[:active_tab] = "instances" domain_overrides set_right_cell_text(x_node, @record) end def get_method_node_info(id) begin @record = @ae_method = MiqAeMethod.find(from_cid(id[1])) rescue ActiveRecord::RecordNotFound set_root_node return end @ae_class = @record.ae_class @sb[:squash_state] = true @sb[:active_tab] = "methods" if @record.location == 'expression' hash = YAML.load(@record.data) @expression = hash[:expression] ? MiqExpression.new(hash[:expression]).to_human : "" elsif @record.location == "playbook" fetch_playbook_details end domain_overrides set_right_cell_text(x_node, @record) end def fetch_playbook_details @playbook_details = {} data = YAML.load(@record.data) @playbook_details[:repository] = fetch_name_from_object(ManageIQ::Providers::EmbeddedAnsible::AutomationManager::ConfigurationScriptSource, data[:repository_id]) @playbook_details[:playbook] = fetch_name_from_object(ManageIQ::Providers::EmbeddedAnsible::AutomationManager::Playbook, data[:playbook_id]) @playbook_details[:machine_credential] = fetch_name_from_object(ManageIQ::Providers::EmbeddedAnsible::AutomationManager::MachineCredential, data[:credential_id]) @playbook_details[:network_credential] = fetch_name_from_object(ManageIQ::Providers::EmbeddedAnsible::AutomationManager::NetworkCredential, data[:network_credential_id]) if data[:network_credential_id] @playbook_details[:cloud_credential] = fetch_name_from_object(ManageIQ::Providers::EmbeddedAnsible::AutomationManager::CloudCredential, data[:cloud_credential_id]) if data[:cloud_credential_id] @playbook_details[:verbosity] = data[:verbosity] @playbook_details[:become_enabled] = data[:become_enabled] == 'true' ? _("Yes") : _("No") @playbook_details end def get_class_node_info(id) @sb[:active_tab] = "instances" if !@in_a_form && !params[:button] && !params[:pressed] begin @record = @ae_class = MiqAeClass.find(from_cid(id[1])) rescue ActiveRecord::RecordNotFound set_root_node return end @combo_xml = build_type_options # passing fields because that's how many combo boxes we need @dtype_combo_xml = build_dtype_options @grid_methods_list_xml = build_details_grid(@record.ae_methods) domain_overrides set_right_cell_text(x_node, @record) end def domain_overrides @domain_overrides = {} typ, = x_node.split('-') overrides = TreeBuilder.get_model_for_prefix(typ).constantize.get_homonymic_across_domains(current_user, @record.fqname) overrides.each do |obj| display_name, id = domain_display_name_using_name(obj, @record.domain.name) @domain_overrides[display_name] = id end end def title _("Datastore") end def session_key_prefix "miq_ae_class" end def get_session_data super @edit = session[:edit] end def flash_validation_errors(am_obj) am_obj.errors.each do |field, msg| add_flash("#{field.to_s.capitalize} #{msg}", :error) end end menu_section :automate def process_element_destroy_via_queue(element, klass, name) return unless element.respond_to?(:destroy) audit = {:event => "#{klass.name.downcase}_record_delete", :message => "[#{name}] Record deleted", :target_id => element.id, :target_class => klass.base_class.name, :userid => session[:userid]} model_name = ui_lookup(:model => klass.name) # Lookup friendly model name in dictionary record_name = get_record_display_name(element) begin git_based_domain_import_service.destroy_domain(element.id) AuditEvent.success(audit) add_flash(_("%{model} \"%{name}\": Delete successful") % {:model => model_name, :name => record_name}) rescue => bang add_flash(_("%{model} \"%{name}\": Error during delete: %{error_msg}") % {:model => model_name, :name => record_name, :error_msg => bang.message}, :error) end end end Replaced YAML.load with YAML.safe_load to address Hakiri warning. https://www.pivotaltracker.com/story/show/149747321 require "rexml/document" class MiqAeClassController < ApplicationController include MiqAeClassHelper include AutomateTreeHelper include Mixins::GenericSessionMixin before_action :check_privileges before_action :get_session_data after_action :cleanup_action after_action :set_session_data MIQ_AE_COPY_ACTIONS = %w(miq_ae_class_copy miq_ae_instance_copy miq_ae_method_copy).freeze # GET /automation_classes # GET /automation_classes.xml def index redirect_to :action => 'explorer' end def change_tab # resetting flash array so messages don't get displayed when tab is changed @flash_array = [] @explorer = true @record = @ae_class = MiqAeClass.find(from_cid(x_node.split('-').last)) @sb[:active_tab] = params[:tab_id] render :update do |page| page << javascript_prologue page.replace("flash_msg_div", :partial => "layouts/flash_msg") page << javascript_reload_toolbars page << "miqSparkle(false);" end end AE_X_BUTTON_ALLOWED_ACTIONS = { 'instance_fields_edit' => :edit_instance, 'method_inputs_edit' => :edit_mehod, 'miq_ae_class_copy' => :copy_objects, 'miq_ae_class_edit' => :edit_class, 'miq_ae_class_delete' => :deleteclasses, 'miq_ae_class_new' => :new, 'miq_ae_domain_delete' => :delete_domain, 'miq_ae_domain_edit' => :edit_domain, 'miq_ae_domain_lock' => :domain_lock, 'miq_ae_domain_unlock' => :domain_unlock, 'miq_ae_git_refresh' => :git_refresh, 'miq_ae_domain_new' => :new_domain, 'miq_ae_domain_priority_edit' => :domains_priority_edit, 'miq_ae_field_edit' => :edit_fields, 'miq_ae_field_seq' => :fields_seq_edit, 'miq_ae_instance_copy' => :copy_objects, 'miq_ae_instance_delete' => :deleteinstances, 'miq_ae_instance_edit' => :edit_instance, 'miq_ae_instance_new' => :new_instance, 'miq_ae_item_edit' => :edit_item, 'miq_ae_method_copy' => :copy_objects, 'miq_ae_method_delete' => :deletemethods, 'miq_ae_method_edit' => :edit_method, 'miq_ae_method_new' => :new_method, 'miq_ae_namespace_delete' => :delete_ns, 'miq_ae_namespace_edit' => :edit_ns, 'miq_ae_namespace_new' => :new_ns, }.freeze def x_button generic_x_button(AE_X_BUTTON_ALLOWED_ACTIONS) end def explorer @trees = [] @sb[:action] = nil @explorer = true # don't need right bottom cell @breadcrumbs = [] bc_name = _("Explorer") bc_name += _(" (filtered)") if @filters && (!@filters[:tags].blank? || !@filters[:cats].blank?) drop_breadcrumb(:name => bc_name, :url => "/miq_ae_class/explorer") @lastaction = "replace_right_cell" build_accordions_and_trees @right_cell_text ||= _("Datastore") render :layout => "application" end def set_right_cell_text(id, rec = nil) nodes = id.split('-') case nodes[0] when "root" txt = _("Datastore") @sb[:namespace_path] = "" when "aec" txt = ui_lookup(:model => "MiqAeClass") @sb[:namespace_path] = rec.fqname when "aei" txt = ui_lookup(:model => "MiqAeInstance") updated_by = rec.updated_by ? _(" by %{user}") % {:user => rec.updated_by} : "" @sb[:namespace_path] = rec.fqname @right_cell_text = _("%{model} [%{name} - Updated %{time}%{update}]") % { :model => txt, :name => get_rec_name(rec), :time => format_timezone(rec.updated_on, Time.zone, "gtl"), :update => updated_by } when "aem" txt = ui_lookup(:model => "MiqAeMethod") updated_by = rec.updated_by ? _(" by %{user}") % {:user => rec.updated_by} : "" @sb[:namespace_path] = rec.fqname @right_cell_text = _("%{model} [%{name} - Updated %{time}%{update}]") % { :model => txt, :name => get_rec_name(rec), :time => format_timezone(rec.updated_on, Time.zone, "gtl"), :update => updated_by } when "aen" txt = ui_lookup(:model => rec.domain? ? "MiqAeDomain" : "MiqAeNamespace") @sb[:namespace_path] = rec.fqname end @sb[:namespace_path].gsub!(%r{\/}, " / ") if @sb[:namespace_path] @right_cell_text = "#{txt} #{_("\"%s\"") % get_rec_name(rec)}" unless %w(root aei aem).include?(nodes[0]) end def expand_toggle render :update do |page| page << javascript_prologue if @sb[:squash_state] @sb[:squash_state] = false page << javascript_show("inputs_div") page << "$('#exp_collapse_img i').attr('class','fa fa-angle-up fa-lg')" page << "$('#exp_collapse_img').prop('title', 'Hide Input Parameters');" page << "$('#exp_collapse_img').prop('alt', 'Hide Input Parameters');" else @sb[:squash_state] = true page << javascript_hide("inputs_div") page << "$('#exp_collapse_img i').attr('class','fa fa-angle-down fa-lg')" page << "$('#exp_collapse_img').prop('title', 'Show Input Parameters');" page << "$('#exp_collapse_img').prop('alt', 'Show Input Parameters');" end end end def get_node_info(node, _show_list = true) id = valid_active_node(node).split('-') @sb[:row_selected] = nil if params[:action] == "tree_select" case id[0] when "aec" get_class_node_info(id) when "aei" get_instance_node_info(id) when "aem" get_method_node_info(id) when "aen" @record = MiqAeNamespace.find(from_cid(id[1])) # need to set record as Domain record if it's a domain, editable_domains, enabled_domains, # visible domains methods returns list of Domains, need this for toolbars to hide/disable correct records. @record = MiqAeDomain.find(from_cid(id[1])) if @record.domain? @version_message = domain_version_message(@record) if @record.domain? if @record.nil? set_root_node else @records = [] # Add Namespaces under a namespace details = @record.ae_namespaces @records += details.sort_by { |d| [d.display_name.to_s, d.name.to_s] } # Add classes under a namespace details_cls = @record.ae_classes unless details_cls.nil? @records += details_cls.sort_by { |d| [d.display_name.to_s, d.name.to_s] } end @combo_xml = build_type_options @dtype_combo_xml = build_dtype_options @sb[:active_tab] = "details" set_right_cell_text(x_node, @record) end else @grid_data = User.current_tenant.visible_domains add_all_domains_version_message(@grid_data) @record = nil @right_cell_text = _("Datastore") @sb[:active_tab] = "namespaces" set_right_cell_text(x_node) end x_history_add_item(:id => x_node, :text => @right_cell_text) end def domain_version_message(domain) version = domain.version available_version = domain.available_version return if version.nil? || available_version.nil? if version != available_version _("%{name} domain: Current version - %{version}, Available version - %{available_version}") % {:name => domain.name, :version => version, :available_version => available_version} end end def add_all_domains_version_message(domains) @version_messages = domains.collect { |dom| domain_version_message(dom) }.compact end # Tree node selected in explorer def tree_select @explorer = true @lastaction = "explorer" self.x_active_tree = params[:tree] if params[:tree] self.x_node = params[:id] @sb[:action] = nil replace_right_cell end # Check for parent nodes missing from ae tree and return them if any def open_parent_nodes(record) nodes = record.fqname.split("/") parents = [] nodes.each_with_index do |_, i| if i == nodes.length - 1 selected_node = x_node.split("-") parents.push(record.ae_class) if %w(aei aem).include?(selected_node[0]) self.x_node = "#{selected_node[0]}-#{to_cid(record.id)}" parents.push(record) else ns = MiqAeNamespace.find_by(:fqname => nodes[0..i].join("/")) parents.push(ns) if ns end end build_and_add_nodes(parents) end def build_and_add_nodes(parents) existing_node = find_existing_node(parents) return nil if existing_node.nil? children = tree_add_child_nodes(existing_node) # set x_node after building tree nodes so parent node of new nodes can be selected in the tree. unless params[:action] == "x_show" self.x_node = if @record.kind_of?(MiqAeClass) "aen-#{to_cid(@record.namespace_id)}" else "aec-#{to_cid(@record.class_id)}" end end {:key => existing_node, :nodes => children} end def find_existing_node(parents) existing_node = nil # Go up thru the parents and find the highest level unopened, mark all as opened along the way unless parents.empty? || # Skip if no parents or parent already open x_tree[:open_nodes].include?(x_build_node_id(parents.last)) parents.reverse_each do |p| p_node = x_build_node_id(p) if x_tree[:open_nodes].include?(p_node) return p_node else x_tree[:open_nodes].push(p_node) existing_node = p_node end end end existing_node end def replace_right_cell(options = {}) @explorer = true replace_trees = options[:replace_trees] # FIXME: is the following line needed? # replace_trees = @replace_trees if @replace_trees #get_node_info might set this nodes = x_node.split('-') @in_a_form = @in_a_form_fields = @in_a_form_props = false if params[:button] == "cancel" || (%w(save add).include?(params[:button]) && replace_trees) add_nodes = open_parent_nodes(@record) if params[:button] == "copy" || params[:action] == "x_show" get_node_info(x_node) if !@in_a_form && !@angular_form && @button != "reset" c_tb = build_toolbar(center_toolbar_filename) unless @in_a_form h_tb = build_toolbar("x_history_tb") presenter = ExplorerPresenter.new( :active_tree => x_active_tree, :right_cell_text => @right_cell_text, :remove_nodes => add_nodes, # remove any existing nodes before adding child nodes to avoid duplication :add_nodes => add_nodes, ) reload_trees_by_presenter(presenter, :ae => build_ae_tree) unless replace_trees.blank? if @sb[:action] == "miq_ae_field_seq" presenter.update(:class_fields_div, r[:partial => "fields_seq_form"]) elsif @sb[:action] == "miq_ae_domain_priority_edit" presenter.update(:ns_list_div, r[:partial => "domains_priority_form"]) elsif MIQ_AE_COPY_ACTIONS.include?(@sb[:action]) presenter.update(:main_div, r[:partial => "copy_objects_form"]) else if @sb[:action] == "miq_ae_class_edit" @sb[:active_tab] = 'props' else @sb[:active_tab] ||= 'instances' end presenter.update(:main_div, r[:partial => 'all_tabs']) end presenter.replace('flash_msg_div', r[:partial => "layouts/flash_msg"]) if @flash_array if @in_a_form && !@angular_form action_url = create_action_url(nodes.first) # incase it was hidden for summary screen, and incase there were no records on show_list presenter.show(:paging_div, :form_buttons_div) presenter.update(:form_buttons_div, r[ :partial => "layouts/x_edit_buttons", :locals => { :record_id => @edit[:rec_id], :action_url => action_url, :copy_button => action_url == "copy_objects", :multi_record => @sb[:action] == "miq_ae_domain_priority_edit", :serialize => @sb[:active_tab] == 'methods', } ]) else # incase it was hidden for summary screen, and incase there were no records on show_list presenter.hide(:paging_div, :form_buttons_div) end presenter[:lock_sidebar] = @in_a_form && @edit if @record.kind_of?(MiqAeMethod) && !@in_a_form && !@angular_form presenter.set_visibility(!@record.inputs.blank?, :params_div) end presenter[:clear_gtl_list_grid] = @gtl_type && @gtl_type != 'list' # Rebuild the toolbars presenter.reload_toolbars(:history => h_tb) if c_tb.present? presenter.show(:toolbar) presenter.reload_toolbars(:center => c_tb) else presenter.hide(:toolbar) end presenter[:record_id] = determine_record_id_for_presenter presenter[:osf_node] = x_node presenter.show_miq_buttons if @changed render :json => presenter.for_render end def build_type_options MiqAeField.available_aetypes.collect { |t| [t.titleize, t, {"data-icon" => ae_field_fonticon(t)}] } end def build_dtype_options MiqAeField.available_datatypes_for_ui.collect { |t| [t.titleize, t, {"data-icon" => ae_field_fonticon(t)}] } end def class_and_glyph(cls) case cls.to_s.split("::").last when "MiqAeClass" cls = "aec" glyphicon = "ff ff-class" when "MiqAeNamespace" cls = "aen" glyphicon = "pficon pficon-folder-open" when "MiqAeInstance" cls = "aei" glyphicon = "fa fa-file-text-o" when "MiqAeField" cls = "Field" glyphicon = "ff ff-field" when "MiqAeMethod" cls = "aem" glyphicon = "ff ff-method" end [cls, glyphicon] end def build_details_grid(view, mode = true) xml = REXML::Document.load("") xml << REXML::XMLDecl.new(1.0, "UTF-8") # Create root element root = xml.add_element("rows") # Build the header row head = root.add_element("head") header = "" head.add_element("column", "type" => "ch", "width" => 25, "align" => "center") # Checkbox column new_column = head.add_element("column", "width" => "30", "align" => "left", "sort" => "na") new_column.add_attribute("type", 'ro') new_column.text = header new_column = head.add_element("column", "width" => "*", "align" => "left", "sort" => "na") new_column.add_attribute("type", 'ro') new_column.text = header # passing in mode, don't need to sort records for namaspace node, it will be passed in sorted order, need to show Namesaces first and then Classes records = if mode view.sort_by { |v| [v.display_name.to_s, v.name.to_s] } else view end records.each do |kids| cls, glyphicon = class_and_glyph(kids.class) rec_name = get_rec_name(kids) if rec_name rec_name = rec_name.gsub(/\n/, "\\n") rec_name = rec_name.gsub(/\t/, "\\t") rec_name = rec_name.tr('"', "'") rec_name = ERB::Util.html_escape(rec_name) rec_name = rec_name.gsub(/\\/, "&#92;") end srow = root.add_element("row", "id" => "#{cls}-#{to_cid(kids.id)}", "style" => "border-bottom: 1px solid #CCCCCC;color:black; text-align: center") srow.add_element("cell").text = "0" # Checkbox column unchecked srow.add_element("cell", "image" => "blank.png", "title" => cls.to_s, "style" => "border-bottom: 1px solid #CCCCCC;text-align: left;height:28px;").text = REXML::CData.new("<i class='#{glyphicon}' alt='#{cls}' title='#{cls}'></i>") srow.add_element("cell", "image" => "blank.png", "title" => rec_name.to_s, "style" => "border-bottom: 1px solid #CCCCCC;text-align: left;height:28px;").text = rec_name end xml.to_s end def edit_item item = find_checked_items @sb[:row_selected] = item[0] if @sb[:row_selected].split('-')[0] == "aec" edit_class else edit_ns end end def edit_class assert_privileges("miq_ae_class_edit") if params[:pressed] == "miq_ae_item_edit" # came from Namespace details screen id = @sb[:row_selected].split('-') @ae_class = find_record_with_rbac(MiqAeClass, from_cid(id[1])) else @ae_class = find_record_with_rbac(MiqAeClass, params[:id]) end set_form_vars # have to get name and set node info, to load multiple tabs correctly # rec_name = get_rec_name(@ae_class) # get_node_info("aec-#{to_cid(@ae_class.id)}") @in_a_form = true @in_a_form_props = true session[:changed] = @changed = false replace_right_cell end def edit_fields assert_privileges("miq_ae_field_edit") if params[:pressed] == "miq_ae_item_edit" # came from Namespace details screen id = @sb[:row_selected].split('-') @ae_class = find_record_with_rbac(MiqAeClass, from_cid(id[1])) else @ae_class = find_record_with_rbac(MiqAeClass, params[:id]) end fields_set_form_vars @in_a_form = true @in_a_form_fields = true session[:changed] = @changed = false replace_right_cell end def edit_domain assert_privileges("miq_ae_domain_edit") edit_domain_or_namespace end def edit_ns assert_privileges("miq_ae_namespace_edit") edit_domain_or_namespace end def edit_instance assert_privileges("miq_ae_instance_edit") obj = find_checked_items if !obj.blank? @sb[:row_selected] = obj[0] id = @sb[:row_selected].split('-') else id = x_node.split('-') end initial_setup_for_instances_form_vars(from_cid(id[1])) set_instances_form_vars @in_a_form = true session[:changed] = @changed = false replace_right_cell end def edit_method assert_privileges("miq_ae_method_edit") obj = find_checked_items if !obj.blank? @sb[:row_selected] = obj[0] id = @sb[:row_selected].split('-') else id = x_node.split('-') end @ae_method = find_record_with_rbac(MiqAeMethod, from_cid(id[1])) if @ae_method.location == "playbook" angular_form_specific_data else set_method_form_vars @in_a_form = true end session[:changed] = @changed = false replace_right_cell end # Set form variables for edit def set_instances_form_vars session[:inst_data] = {} @edit = { :ae_inst_id => @ae_inst.id, :ae_class_id => @ae_class.id, :rec_id => @ae_inst.id || nil, :key => "aeinst_edit__#{@ae_inst.id || "new"}", :new => {} } @edit[:new][:ae_inst] = {} instance_column_names.each do |fld| @edit[:new][:ae_inst][fld] = @ae_inst.send(fld) end @edit[:new][:ae_values] = @ae_values.collect do |ae_value| value_column_names.each_with_object({}) do |fld, hash| hash[fld] = ae_value.send(fld) end end @edit[:new][:ae_fields] = @ae_class.ae_fields.collect do |ae_field| field_column_names.each_with_object({}) do |fld, hash| hash[fld] = ae_field.send(fld) end end @edit[:current] = copy_hash(@edit[:new]) @right_cell_text = if @edit[:rec_id].nil? _("Adding a new %{model}") % {:model => ui_lookup(:model => "MiqAeInstance")} else _("Editing %{model} \"%{name}\"") % {:model => ui_lookup(:model => "MiqAeInstance"), :name => @ae_inst.name} end session[:edit] = @edit end # AJAX driven routine to check for changes in ANY field on the form def form_instance_field_changed return unless load_edit("aeinst_edit__#{params[:id]}", "replace_cell__explorer") get_instances_form_vars javascript_miq_button_visibility(@edit[:current] != @edit[:new]) end def update_instance assert_privileges("miq_ae_instance_edit") return unless load_edit("aeinst_edit__#{params[:id]}", "replace_cell__explorer") get_instances_form_vars @changed = (@edit[:new] != @edit[:current]) case params[:button] when "cancel" session[:edit] = nil # clean out the saved info add_flash(_("Edit of %{model} \"%{name}\" was cancelled by the user") % {:model => ui_lookup(:model => "MiqAeInstance"), :name => @ae_inst.name}) @in_a_form = false replace_right_cell when "save" if @edit[:new][:ae_inst]["name"].blank? add_flash(_("Name is required"), :error) end if @flash_array javascript_flash return end set_instances_record_vars(@ae_inst) # Set the instance record variables, but don't save # Update the @ae_inst.ae_values directly because of update bug in RAILS # When saving a parent, the childrens updates are not getting saved set_instances_value_vars(@ae_values, @ae_inst) # Set the instance record variables, but don't save begin MiqAeInstance.transaction do @ae_inst.ae_values.each { |v| v.value = nil if v.value == "" } @ae_inst.save! end rescue => bang add_flash(_("Error during 'save': %{error_message}") % {:error_message => bang.message}, :error) @in_a_form = true javascript_flash else AuditEvent.success(build_saved_audit(@ae_class, @edit)) session[:edit] = nil # clean out the saved info @in_a_form = false add_flash(_("%{model} \"%{name}\" was saved") % {:model => ui_lookup(:model => "MiqAeInstance"), :name => @ae_inst.name}) replace_right_cell(:replace_trees => [:ae]) return end when "reset" set_instances_form_vars add_flash(_("All changes have been reset"), :warning) @in_a_form = true @button = "reset" replace_right_cell end end def create_instance assert_privileges("miq_ae_instance_new") case params[:button] when "cancel" session[:edit] = nil # clean out the saved info add_flash(_("Add of new %{model} was cancelled by the user") % {:model => ui_lookup(:model => "MiqAeInstance")}) @in_a_form = false replace_right_cell when "add" return unless load_edit("aeinst_edit__new", "replace_cell__explorer") get_instances_form_vars if @edit[:new][:ae_inst]["name"].blank? add_flash(_("Name is required"), :error) end if @flash_array javascript_flash return end add_aeinst = MiqAeInstance.new set_instances_record_vars(add_aeinst) # Set the instance record variables, but don't save set_instances_value_vars(@ae_values) # Set the instance value record variables, but don't save begin MiqAeInstance.transaction do add_aeinst.ae_values = @ae_values add_aeinst.ae_values.each { |v| v.value = nil if v.value == "" } add_aeinst.save! end rescue => bang @in_a_form = true render_flash(_("Error during 'add': %{message}") % {:message => bang.message}, :error) else AuditEvent.success(build_created_audit(add_aeinst, @edit)) add_flash(_("%{model} \"%{name}\" was added") % {:model => ui_lookup(:model => "MiqAeInstance"), :name => add_aeinst.name}) @in_a_form = false replace_right_cell(:replace_trees => [:ae]) return end end end # Set form variables for edit def set_form_vars @in_a_form_props = true session[:field_data] = {} @edit = {} session[:edit] = {} @edit[:ae_class_id] = @ae_class.id @edit[:new] = {} @edit[:current] = {} @edit[:new_field] = {} @edit[:rec_id] = @ae_class.id || nil @edit[:key] = "aeclass_edit__#{@ae_class.id || "new"}" @edit[:new][:name] = @ae_class.name @edit[:new][:display_name] = @ae_class.display_name @edit[:new][:description] = @ae_class.description @edit[:new][:namespace] = @ae_class.namespace @edit[:new][:inherits] = @ae_class.inherits @edit[:inherits_from] = MiqAeClass.all.collect { |c| [c.fqname, c.fqname] } @edit[:current] = @edit[:new].dup @right_cell_text = if @edit[:rec_id].nil? _("Adding a new %{model}") % {:model => ui_lookup(:model => "Class")} else _("Editing %{model} \"%{name}\"") % {:model => ui_lookup(:model => "Class"), :name => @ae_class.name} end session[:edit] = @edit @in_a_form = true end # Set form variables for edit def fields_set_form_vars @in_a_form_fields = true session[:field_data] = {} @edit = { :ae_class_id => @ae_class.id, :rec_id => @ae_class.id, :new_field => {}, :key => "aefields_edit__#{@ae_class.id || "new"}", :fields_to_delete => [] } @edit[:new] = { :datatypes => build_dtype_options, # setting dtype combo for adding a new field :aetypes => build_type_options # setting aetype combo for adding a new field } @edit[:new][:fields] = @ae_class.ae_fields.sort_by { |a| [a.priority.to_i] }.collect do |fld| field_attributes.each_with_object({}) do |column, hash| hash[column] = fld.send(column) end end # combo to show existing fields @combo_xml = build_type_options # passing in fields because that's how many combo boxes we need @dtype_combo_xml = build_dtype_options @edit[:current] = copy_hash(@edit[:new]) @right_cell_text = if @edit[:rec_id].nil? _("Adding a new %{model}") % {:model => ui_lookup(:model => "Class Schema")} else _("Editing %{model} \"%{name}\"") % {:model => ui_lookup(:model => "Class Schema"), :name => @ae_class.name} end session[:edit] = @edit end # Set form variables for edit def set_method_form_vars session[:field_data] = {} @ae_class = ae_class_for_instance_or_method(@ae_method) @edit = {} session[:edit] = {} @edit[:ae_method_id] = @ae_method.id @edit[:fields_to_delete] = [] @edit[:new] = {} @edit[:new_field] = {} @edit[:ae_class_id] = @ae_class.id @edit[:rec_id] = @ae_method.id || nil @edit[:key] = "aemethod_edit__#{@ae_method.id || "new"}" @sb[:form_vars_set] = true @sb[:squash_state] ||= true @edit[:new][:name] = @ae_method.name @edit[:new][:display_name] = @ae_method.display_name @edit[:new][:scope] = "instance" @edit[:new][:language] = "ruby" @edit[:new][:available_locations] = MiqAeMethod.available_locations unless @ae_method.id @edit[:new][:available_expression_objects] = MiqAeMethod.available_expression_objects.sort @edit[:new][:location] = @ae_method.location if @edit[:new][:location] == "expression" expr_hash = YAML.load(@ae_method.data) if expr_hash[:db] && expr_hash[:expression] @edit[:new][:expression] = expr_hash[:expression] expression_setup(expr_hash[:db]) end else @edit[:new][:data] = @ae_method.data.to_s end @edit[:new][:data] = @ae_method.data.to_s @edit[:default_verify_status] = @edit[:new][:location] == "inline" && @edit[:new][:data] && @edit[:new][:data] != "" @edit[:new][:fields] = @ae_method.inputs.collect do |input| method_input_column_names.each_with_object({}) do |column, hash| hash[column] = input.send(column) end end @edit[:new][:available_datatypes] = MiqAeField.available_datatypes_for_ui @edit[:current] = copy_hash(@edit[:new]) @right_cell_text = if @edit[:rec_id].nil? _("Adding a new %{model}") % {:model => ui_lookup(:model => "MiqAeMethod")} else _("Editing %{model} \"%{name}\"") % {:model => ui_lookup(:model => "MiqAeMethod"), :name => @ae_method.name} end session[:log_depot_default_verify_status] = false session[:edit] = @edit session[:changed] = @changed = false end def expression_setup(db) @edit[:expression_method] = true @edit[:new][:exp_object] = db if params[:exp_object] || params[:cls_exp_object] session[:adv_search] = nil @edit[@expkey] = @edit[:new][@expkey] = nil end adv_search_build(db) end def expression_cleanup @edit[:expression_method] = false end def ae_class_for_instance_or_method(record) record.id ? record.ae_class : MiqAeClass.find(from_cid(x_node.split("-").last)) end def validate_method_data return unless load_edit("aemethod_edit__#{params[:id]}", "replace_cell__explorer") @edit[:new][:data] = params[:cls_method_data] if params[:cls_method_data] @edit[:new][:data] = params[:method_data] if params[:method_data] res = MiqAeMethod.validate_syntax(@edit[:new][:data]) line = 0 if !res add_flash(_("Data validated successfully")) else res.each do |err| line = err[0] if line.zero? add_flash(_("Error on line %{line_num}: %{err_txt}") % {:line_num => err[0], :err_txt => err[1]}, :error) end end render :update do |page| page << javascript_prologue page << "if (miqDomElementExists('cls_method_data')){" page << "var ta = document.getElementById('cls_method_data');" page << "} else {" page << "var ta = document.getElementById('method_data');" page << "}" page.replace("flash_msg_div", :partial => "layouts/flash_msg") page << "var lineHeight = ta.clientHeight / ta.rows;" page << "ta.scrollTop = (#{line.to_i}-1) * lineHeight;" if line > 0 if @sb[:row_selected] page << "$('#cls_method_data_lines').scrollTop(ta.scrollTop);" page << "$('#cls_method_data').scrollTop(ta.scrollTop);" else page << "$('#method_data_lines').scrollTop(ta.scrollTop);" page << "$('#method_data').scrollTop(ta.scrollTop);" end end end end # AJAX driven routine to check for changes in ANY field on the form def form_field_changed return unless load_edit("aeclass_edit__#{params[:id]}", "replace_cell__explorer") get_form_vars javascript_miq_button_visibility(@edit[:new] != @edit[:current]) end # AJAX driven routine to check for changes in ANY field on the form def fields_form_field_changed return unless load_edit("aefields_edit__#{params[:id]}", "replace_cell__explorer") fields_get_form_vars @changed = (@edit[:new] != @edit[:current]) render :update do |page| page << javascript_prologue unless %w(up down).include?(params[:button]) if params[:field_datatype] == "password" page << javascript_hide("field_default_value") page << javascript_show("field_password_value") page << "$('#field_password_value').val('');" session[:field_data][:default_value] = @edit[:new_field][:default_value] = '' elsif params[:field_datatype] page << javascript_hide("field_password_value") page << javascript_show("field_default_value") page << "$('#field_default_value').val('');" session[:field_data][:default_value] = @edit[:new_field][:default_value] = '' end params.keys.each do |field| next unless field.to_s.starts_with?("fields_datatype") f = field.split('fields_datatype') def_field = "fields_default_value_" << f[1].to_s pwd_field = "fields_password_value_" << f[1].to_s if @edit[:new][:fields][f[1].to_i]['datatype'] == "password" page << javascript_hide(def_field) page << javascript_show(pwd_field) page << "$('##{pwd_field}').val('');" else page << javascript_hide(pwd_field) page << javascript_show(def_field) page << "$('##{def_field}').val('');" end @edit[:new][:fields][f[1].to_i]['default_value'] = nil end end page << javascript_for_miq_button_visibility_changed(@changed) end end # AJAX driven routine to check for changes in ANY field on the form def form_method_field_changed if !@sb[:form_vars_set] # workaround to prevent an error that happens when IE sends a transaction form form even after save button is clicked when there is text_area in the form head :ok else return unless load_edit("aemethod_edit__#{params[:id]}", "replace_cell__explorer") get_method_form_vars if @edit[:new][:location] == 'expression' @edit[:new][:exp_object] ||= @edit[:new][:available_expression_objects].first exp_object = params[:cls_exp_object] || params[:exp_object] || @edit[:new][:exp_object] expression_setup(exp_object) if exp_object else expression_cleanup end if row_selected_in_grid? @refresh_div = "class_methods_div" @refresh_partial = "class_methods" @field_name = "cls_method" else @refresh_div = "method_inputs_div" @refresh_partial = "method_inputs" @field_name = "method" end if @edit[:current][:location] == "inline" && @edit[:current][:data] @edit[:method_prev_data] = @edit[:current][:data] end @edit[:new][:data] = if @edit[:new][:location] == "inline" && !params[:cls_method_data] && !params[:method_data] && !params[:transOne] if !@edit[:method_prev_data] MiqAeMethod.default_method_text else @edit[:method_prev_data] end elsif params[:cls_method_location] || params[:method_location] # reset data if location is changed '' end @changed = (@edit[:new] != @edit[:current]) @edit[:default_verify_status] = @edit[:new][:location] == "inline" && @edit[:new][:data] && @edit[:new][:data] != "" angular_form_specific_data if @edit[:new][:location] == "playbook" render :update do |page| page << javascript_prologue page.replace_html('form_div', :partial => 'method_form', :locals => {:prefix => ""}) if @edit[:new][:location] == 'expression' if @edit[:new][:location] == "playbook" page.replace_html(@refresh_div, :partial => 'angular_method_form') page << javascript_hide("form_buttons_div") elsif @refresh_div && (params[:cls_method_location] || params[:exp_object] || params[:cls_exp_object]) page.replace_html(@refresh_div, :partial => @refresh_partial) end if params[:cls_field_datatype] if session[:field_data][:datatype] == "password" page << javascript_hide("cls_field_default_value") page << javascript_show("cls_field_password_value") page << "$('#cls_field_password_value').val('');" else page << javascript_hide("cls_field_password_value") page << javascript_show("cls_field_default_value") page << "$('#cls_field_default_value').val('');" end end if params[:method_field_datatype] if session[:field_data][:datatype] == "password" page << javascript_hide("method_field_default_value") page << javascript_show("method_field_password_value") page << "$('#method_field_password_value').val('');" else page << javascript_hide("method_field_password_value") page << javascript_show("method_field_default_value") page << "$('#method_field_default_value').val('');" end end params.keys.each do |field| if field.to_s.starts_with?("cls_fields_datatype_") f = field.split('cls_fields_datatype_') def_field = "cls_fields_value_" << f[1].to_s pwd_field = "cls_fields_password_value_" << f[1].to_s elsif field.to_s.starts_with?("fields_datatype_") f = field.split('fields_datatype_') def_field = "fields_value_" << f[1].to_s pwd_field = "fields_password_value_" << f[1].to_s end next unless f if @edit[:new][:fields][f[1].to_i]['datatype'] == "password" page << javascript_hide(def_field) page << javascript_show(pwd_field) page << "$('##{pwd_field}').val('');" else page << javascript_hide(pwd_field) page << javascript_show(def_field) page << "$('##{def_field}').val('');" end @edit[:new][:fields][f[1].to_i]['default_value'] = nil end if @edit[:default_verify_status] != session[:log_depot_default_verify_status] session[:log_depot_default_verify_status] = @edit[:default_verify_status] page << if @edit[:default_verify_status] "miqValidateButtons('show', 'default_');" else "miqValidateButtons('hide', 'default_');" end end page << javascript_for_miq_button_visibility_changed(@changed) page << "miqSparkle(false)" end end end def method_form_fields method = params[:id] == "new" ? MiqAeMethod.new : MiqAeMethod.find(params[:id]) whitelist_symbols = [:repository_id, :playbook_id, :credential_id, :network_credential_id, :cloud_credential_id, :verbosity, :become_enabled] data = method.data ? YAML.safe_load(method.data, [Symbol], whitelist_symbols, false, nil) : {} method_hash = { :name => method.name, :display_name => method.display_name, :namespace_path => @sb[:namespace_path], :class_id => method.id ? method.class_id : MiqAeClass.find(from_cid(x_node.split("-").last)).id, :location => 'playbook', :language => 'ruby', :scope => "instance", :available_datatypes => MiqAeField.available_datatypes_for_ui, :config_info => { :repository_id => data[:repository_id] || '', :playbook_id => data[:playbook_id] || '', :credential_id => data[:credential_id] || '', :network_credential_id => data[:network_credential_id] || '', :cloud_credential_id => data[:cloud_credential_id] || '', :verbosity => data[:verbosity], :become_enabled => data[:become_enabled] || false, :extra_vars => method.inputs } } render :json => method_hash end # AJAX driven routine to check for changes in ANY field on the form def form_ns_field_changed return unless load_edit("aens_edit__#{params[:id]}", "replace_cell__explorer") get_ns_form_vars @changed = (@edit[:new] != @edit[:current]) render :update do |page| page << javascript_prologue page << javascript_for_miq_button_visibility(@changed) end end def update assert_privileges("miq_ae_class_edit") return unless load_edit("aeclass_edit__#{params[:id]}", "replace_cell__explorer") get_form_vars @changed = (@edit[:new] != @edit[:current]) case params[:button] when "cancel" session[:edit] = nil # clean out the saved info add_flash(_("Edit of %{model} \"%{name}\" was cancelled by the user") % {:model => ui_lookup(:model => "MiqAeClass"), :name => @ae_class.name}) @in_a_form = false replace_right_cell when "save" ae_class = find_record_with_rbac(MiqAeClass, params[:id]) set_record_vars(ae_class) # Set the record variables, but don't save begin MiqAeClass.transaction do ae_class.save! end rescue => bang add_flash(_("Error during 'save': %{error_message}") % {:error_message => bang.message}, :error) session[:changed] = @changed @changed = true javascript_flash else add_flash(_("%{model} \"%{name}\" was saved") % {:model => ui_lookup(:model => "MiqAeClass"), :name => ae_class.fqname}) AuditEvent.success(build_saved_audit(ae_class, @edit)) session[:edit] = nil # clean out the saved info @in_a_form = false replace_right_cell(:replace_trees => [:ae]) return end when "reset" set_form_vars session[:changed] = @changed = false add_flash(_("All changes have been reset"), :warning) @button = "reset" replace_right_cell else @changed = session[:changed] = (@edit[:new] != @edit[:current]) replace_right_cell(:replace_trees => [:ae]) end end def update_fields return unless load_edit("aefields_edit__#{params[:id]}", "replace_cell__explorer") fields_get_form_vars @changed = (@edit[:new] != @edit[:current]) case params[:button] when "cancel" session[:edit] = nil # clean out the saved info add_flash(_("Edit of schema for %{model} \"%{name}\" was cancelled by the user") % {:model => ui_lookup(:model => "MiqAeClass"), :name => @ae_class.name}) @in_a_form = false replace_right_cell when "save" ae_class = find_record_with_rbac(MiqAeClass, params[:id]) begin MiqAeClass.transaction do set_field_vars(ae_class) ae_class.ae_fields.destroy(MiqAeField.where(:id => @edit[:fields_to_delete])) ae_class.ae_fields.each { |fld| fld.default_value = nil if fld.default_value == "" } ae_class.save! end # end of transaction rescue => bang add_flash(_("Error during 'save': %{error_message}") % {:error_message => bang.message}, :error) session[:changed] = @changed = true javascript_flash else add_flash(_("Schema for %{model} \"%{name}\" was saved") % {:model => ui_lookup(:model => "MiqAeClass"), :name => ae_class.name}) AuditEvent.success(build_saved_audit(ae_class, @edit)) session[:edit] = nil # clean out the saved info @in_a_form = false replace_right_cell(:replace_trees => [:ae]) return end when "reset" fields_set_form_vars session[:changed] = @changed = false add_flash(_("All changes have been reset"), :warning) @button = "reset" @in_a_form = true replace_right_cell else @changed = session[:changed] = (@edit[:new] != @edit[:current]) replace_right_cell(:replace_trees => [:ae]) end end def update_ns assert_privileges("miq_ae_namespace_edit") return unless load_edit("aens_edit__#{params[:id]}", "replace_cell__explorer") get_ns_form_vars @changed = (@edit[:new] != @edit[:current]) case params[:button] when "cancel" session[:edit] = nil # clean out the saved info add_flash(_("Edit of %{model} \"%{name}\" was cancelled by the user") % {:model => ui_lookup(:model => @edit[:typ]), :name => @ae_ns.name}) @in_a_form = false replace_right_cell when "save" ae_ns = find_record_with_rbac(@edit[:typ].constantize, params[:id]) ns_set_record_vars(ae_ns) # Set the record variables, but don't save begin ae_ns.save! rescue => bang add_flash(_("Error during 'save': %{message}") % {:message => bang.message}, :error) session[:changed] = @changed @changed = true javascript_flash else add_flash(_("%{model} \"%{name}\" was saved") % {:model => ui_lookup(:model => @edit[:typ]), :name => get_record_display_name(ae_ns)}) AuditEvent.success(build_saved_audit(ae_ns, @edit)) session[:edit] = nil # clean out the saved info @in_a_form = false replace_right_cell(:replace_trees => [:ae]) end when "reset" ns_set_form_vars session[:changed] = @changed = false add_flash(_("All changes have been reset"), :warning) @button = "reset" replace_right_cell else @changed = session[:changed] = (@edit[:new] != @edit[:current]) replace_right_cell(:replace_trees => [:ae]) end end def add_update_method assert_privileges("miq_ae_method_edit") case params[:button] when "cancel" if params[:id] && params[:id] != "new" method = find_record_with_rbac(MiqAeMethod, params[:id]) add_flash(_("Edit of %{model} \"%{name}\" was cancelled by the user") % {:model => ui_lookup(:model => "MiqAeMethod"), :name => method.name}) else add_flash(_("Add of %{model} was cancelled by the user") % {:model => ui_lookup(:model => "MiqAeMethod")}) end replace_right_cell when "add", "save" method = params[:id] != "new" ? find_record_with_rbac(MiqAeMethod, params[:id]) : MiqAeMethod.new method.name = params["name"] method.display_name = params["display_name"] method.location = params["location"] method.language = params["language"] method.scope = params["scope"] method.class_id = params[:class_id] method.data = YAML.dump(set_playbook_data) begin MiqAeMethod.transaction do to_save, to_delete = playbook_inputs(method) method.inputs.destroy(MiqAeField.where(:id => to_delete)) method.inputs = to_save method.save! end rescue => bang add_flash(_("Error during 'save': %{error_message}") % {:error_message => bang.message}, :error) javascript_flash else old_method_attributes = method.attributes.clone add_flash(_("%{model} \"%{name}\" was saved") % {:model => ui_lookup(:model => "MiqAeMethod"), :name => method.name}) AuditEvent.success(build_saved_audit_hash_angular(old_method_attributes, method, params[:button] == "add")) replace_right_cell(:replace_trees => [:ae]) return end end end def update_method assert_privileges("miq_ae_method_edit") return unless load_edit("aemethod_edit__#{params[:id]}", "replace_cell__explorer") get_method_form_vars @changed = (@edit[:new] != @edit[:current]) case params[:button] when "cancel" session[:edit] = nil # clean out the saved info add_flash(_("Edit of %{model} \"%{name}\" was cancelled by the user") % {:model => ui_lookup(:model => "MiqAeMethod"), :name => @ae_method.name}) @sb[:form_vars_set] = false @in_a_form = false replace_right_cell when "save" # dont allow save if expression has not been added or existing one has been removed validate_expression("save") if @edit[:new][:location] == 'expression' return if flash_errors? ae_method = find_record_with_rbac(MiqAeMethod, params[:id]) set_method_record_vars(ae_method) # Set the record variables, but don't save begin MiqAeMethod.transaction do set_input_vars(ae_method) ae_method.inputs.destroy(MiqAeField.where(:id => @edit[:fields_to_delete])) ae_method.inputs.each { |fld| fld.default_value = nil if fld.default_value == "" } ae_method.save! end rescue => bang add_flash(_("Error during 'save': %{error_message}") % {:error_message => bang.message}, :error) session[:changed] = @changed @changed = true javascript_flash else add_flash(_("%{model} \"%{name}\" was saved") % {:model => ui_lookup(:model => "MiqAeMethod"), :name => ae_method.name}) AuditEvent.success(build_saved_audit(ae_method, @edit)) session[:edit] = nil # clean out the saved info @sb[:form_vars_set] = false @in_a_form = false replace_right_cell(:replace_trees => [:ae]) return end when "reset" set_method_form_vars session[:changed] = @changed = false @in_a_form = true add_flash(_("All changes have been reset"), :warning) @button = "reset" replace_right_cell else @changed = session[:changed] = (@edit[:new] != @edit[:current]) replace_right_cell end end def new assert_privileges("miq_ae_class_new") @ae_class = MiqAeClass.new set_form_vars @in_a_form = true replace_right_cell end def new_instance assert_privileges("miq_ae_instance_new") initial_setup_for_instances_form_vars(nil) set_instances_form_vars @in_a_form = true replace_right_cell end def new_method assert_privileges("miq_ae_method_new") @ae_method = MiqAeMethod.new set_method_form_vars @in_a_form = true replace_right_cell end def create assert_privileges("miq_ae_class_new") return unless load_edit("aeclass_edit__new", "replace_cell__explorer") get_form_vars @in_a_form = true case params[:button] when "cancel" add_flash(_("Add of new %{record} was cancelled by the user") % {:record => ui_lookup(:model => "MiqAeClass")}) @in_a_form = false replace_right_cell(:replace_trees => [:ae]) when "add" add_aeclass = MiqAeClass.new set_record_vars(add_aeclass) # Set the record variables, but don't save begin MiqAeClass.transaction do add_aeclass.save! end rescue => bang add_flash(_("Error during 'add': %{error_message}") % {:error_message => bang.message}, :error) @in_a_form = true render :update do |page| page << javascript_prologue page.replace("flash_msg", :partial => "layouts/flash_msg") end else add_flash(_("%{model} \"%{name}\" was added") % {:model => ui_lookup(:model => "MiqAeClass"), :name => add_aeclass.fqname}) @in_a_form = false replace_right_cell(:replace_trees => [:ae]) end else @changed = session[:changed] = (@edit[:new] != @edit[:current]) replace_right_cell(:replace_trees => [:ae]) end end def data_for_expression {:db => @edit[:new][:exp_object], :expression => @edit[:new][:expression]}.to_yaml end def create_method assert_privileges("miq_ae_method_new") @in_a_form = true case params[:button] when "cancel" add_flash(_("Add of new %{record} was cancelled by the user") % {:record => ui_lookup(:model => "MiqAeMethod")}) @sb[:form_vars_set] = false @in_a_form = false replace_right_cell when "add" return unless load_edit("aemethod_edit__new", "replace_cell__explorer") get_method_form_vars # dont allow add if expression has not been added or existing one has been removed validate_expression("add") if @edit[:new][:location] == 'expression' return if flash_errors? add_aemethod = MiqAeMethod.new set_method_record_vars(add_aemethod) # Set the record variables, but don't save begin MiqAeMethod.transaction do add_aemethod.save! set_field_vars(add_aemethod) add_aemethod.save! end rescue => bang add_flash(_("Error during 'add': %{error_message}") % {:error_message => bang.message}, :error) @in_a_form = true javascript_flash else add_flash(_("%{model} \"%{name}\" was added") % {:model => ui_lookup(:model => "MiqAeMethod"), :name => add_aemethod.name}) @sb[:form_vars_set] = false @in_a_form = false replace_right_cell(:replace_trees => [:ae]) end else @changed = session[:changed] = (@edit[:new] != @edit[:current]) @sb[:form_vars_set] = false replace_right_cell(:replace_trees => [:ae]) end end def create_ns assert_privileges("miq_ae_namespace_new") return unless load_edit("aens_edit__new", "replace_cell__explorer") get_ns_form_vars case params[:button] when "cancel" add_flash(_("Add of new %{record} was cancelled by the user") % {:record => ui_lookup(:model => @edit[:typ])}) @in_a_form = false replace_right_cell when "add" add_ae_ns = if @edit[:typ] == "MiqAeDomain" current_tenant.ae_domains.new else MiqAeNamespace.new(:parent_id => from_cid(x_node.split('-')[1])) end ns_set_record_vars(add_ae_ns) # Set the record variables, but don't save if add_ae_ns.valid? && !flash_errors? && add_ae_ns.save add_flash(_("%{model} \"%{name}\" was added") % {:model => ui_lookup(:model => add_ae_ns.class.name), :name => get_record_display_name(add_ae_ns)}) @in_a_form = false replace_right_cell(:replace_trees => [:ae]) else add_ae_ns.errors.each do |field, msg| add_flash("#{field.to_s.capitalize} #{msg}", :error) end javascript_flash end else @changed = session[:changed] = (@edit[:new] != @edit[:current]) replace_right_cell end end # AJAX driven routine to select a classification entry def field_select fields_get_form_vars @combo_xml = build_type_options @dtype_combo_xml = build_dtype_options session[:field_data] = {} @edit[:new_field][:substitute] = session[:field_data][:substitute] = true @changed = (@edit[:new] != @edit[:current]) render :update do |page| page << javascript_prologue page.replace("class_fields_div", :partial => "class_fields") page << javascript_for_miq_button_visibility(@changed) page << "miqSparkle(false);" end end # AJAX driven routine to select a classification entry def field_accept fields_get_form_vars @changed = (@edit[:new] != @edit[:current]) @combo_xml = build_type_options @dtype_combo_xml = build_dtype_options render :update do |page| page << javascript_prologue page.replace("class_fields_div", :partial => "class_fields") page << javascript_for_miq_button_visibility(@changed) page << "miqSparkle(false);" end end # AJAX driven routine to delete a classification entry def field_delete fields_get_form_vars @combo_xml = build_type_options @dtype_combo_xml = build_dtype_options if params.key?(:id) && @edit[:fields_to_delete].exclude?(params[:id]) @edit[:fields_to_delete].push(params[:id]) end @edit[:new][:fields].delete_at(params[:arr_id].to_i) @changed = (@edit[:new] != @edit[:current]) render :update do |page| page << javascript_prologue page.replace("class_fields_div", :partial => "class_fields") page << javascript_for_miq_button_visibility(@changed) page << "miqSparkle(false);" end end # AJAX driven routine to select a classification entry def field_method_select get_method_form_vars @refresh_div = "inputs_div" @refresh_partial = "inputs" @changed = (@edit[:new] != @edit[:current]) @in_a_form = true render :update do |page| page << javascript_prologue page.replace_html(@refresh_div, :partial => @refresh_partial) if row_selected_in_grid? page << javascript_show("class_methods_div") page << javascript_focus('cls_field_name') else page << javascript_show("method_inputs_div") page << javascript_focus('field_name') end page << javascript_for_miq_button_visibility(@changed) page << javascript_show("inputs_div") page << "miqSparkle(false);" end end # AJAX driven routine to select a classification entry def field_method_accept get_method_form_vars @refresh_div = "inputs_div" @refresh_partial = "inputs" session[:field_data] = {} @changed = (@edit[:new] != @edit[:current]) @in_a_form = true render :update do |page| page << javascript_prologue page.replace_html(@refresh_div, :partial => @refresh_partial) if row_selected_in_grid? page << javascript_show("class_methods_div") else page << javascript_show("method_inputs_div") end page << javascript_for_miq_button_visibility(@changed) page << javascript_show("inputs_div") page << "miqSparkle(false);" end end # AJAX driven routine to delete a classification entry def field_method_delete get_method_form_vars @refresh_div = "inputs_div" @refresh_partial = "inputs" if params.key?(:id) && @edit[:fields_to_delete].exclude?(params[:id]) @edit[:fields_to_delete].push(params[:id]) end @edit[:new][:fields].delete_at(params[:arr_id].to_i) @changed = (@edit[:new] != @edit[:current]) render :update do |page| page << javascript_prologue page.replace_html(@refresh_div, :partial => @refresh_partial) if row_selected_in_grid? page << javascript_show("class_methods_div") else page << javascript_show("method_inputs_div") end page << javascript_for_miq_button_visibility(@changed) page << javascript_show("inputs_div") page << "miqSparkle(false);" end end def handle_up_down_buttons(hash_key, field_name) case params[:button] when 'up' move_selected_fields_up(@edit[:new][hash_key], params[:seq_fields], field_name) when 'down' move_selected_fields_down(@edit[:new][hash_key], params[:seq_fields], field_name) end end # Get variables from user edit form def fields_seq_field_changed return unless load_edit("fields_edit__seq", "replace_cell__explorer") unless handle_up_down_buttons(:fields_list, _('Fields')) render_flash return end render :update do |page| page << javascript_prologue page.replace('column_lists', :partial => 'fields_seq_form') @changed = (@edit[:new] != @edit[:current]) page << javascript_for_miq_button_visibility(@changed) if @changed page << "miqsparkle(false);" end end def fields_seq_edit assert_privileges("miq_ae_field_seq") case params[:button] when "cancel" @sb[:action] = session[:edit] = nil # clean out the saved info add_flash(_("Edit of Class Schema Sequence was cancelled by the user")) @in_a_form = false replace_right_cell when "save" return unless load_edit("fields_edit__seq", "replace_cell__explorer") ae_class = MiqAeClass.find(@edit[:ae_class_id]) indexed_ae_fields = ae_class.ae_fields.index_by(&:name) @edit[:new][:fields_list].each_with_index do |f, i| fname = f.split('(').last.split(')').first # leave display name and parenthesis out indexed_ae_fields[fname].try(:priority=, i + 1) end unless ae_class.save flash_validation_errors(ae_class) @in_a_form = true @changed = true javascript_flash return end AuditEvent.success(build_saved_audit(ae_class, @edit)) add_flash(_("Class Schema Sequence was saved")) @sb[:action] = @edit = session[:edit] = nil # clean out the saved info @in_a_form = false replace_right_cell when "reset", nil # Reset or first time in id = params[:id] ? params[:id] : from_cid(@edit[:ae_class_id]) @in_a_form = true fields_seq_edit_screen(id) if params[:button] == "reset" add_flash(_("All changes have been reset"), :warning) end replace_right_cell end end def priority_form_field_changed return unless load_edit(params[:id], "replace_cell__explorer") @in_a_form = true unless handle_up_down_buttons(:domain_order, _('Domains')) render_flash return end render :update do |page| page << javascript_prologue page.replace('domains_list', :partial => 'domains_priority_form', :locals => {:action => "domains_priority_edit"}) @changed = (@edit[:new] != @edit[:current]) page << javascript_for_miq_button_visibility(@changed) if @changed page << "miqsparkle(false);" end end def domains_priority_edit assert_privileges("miq_ae_domain_priority_edit") case params[:button] when "cancel" @sb[:action] = @in_a_form = @edit = session[:edit] = nil # clean out the saved info add_flash(_("Edit of Priority Order was cancelled by the user")) replace_right_cell when "save" return unless load_edit("priority__edit", "replace_cell__explorer") domains = @edit[:new][:domain_order].reverse!.collect do |domain| MiqAeDomain.find_by(:name => domain.split(' (Locked)').first).id end current_tenant.reset_domain_priority_by_ordered_ids(domains) add_flash(_("Priority Order was saved")) @sb[:action] = @in_a_form = @edit = session[:edit] = nil # clean out the saved info replace_right_cell(:replace_trees => [:ae]) when "reset", nil # Reset or first time in priority_edit_screen add_flash(_("All changes have been reset"), :warning) if params[:button] == "reset" session[:changed] = @changed = false replace_right_cell end end def objects_to_copy ids = find_checked_items if ids items_without_prefix = [] ids.each do |item| values = item.split("-") # remove any namespaces that were selected in grid items_without_prefix.push(values.last) unless values.first == "aen" end items_without_prefix else [params[:id]] end end def copy_objects ids = objects_to_copy if ids.blank? add_flash(_("Copy does not apply to selected %{model}") % {:model => ui_lookup(:model => "MiqAeNamespace")}, :error) @sb[:action] = session[:edit] = nil @in_a_form = false replace_right_cell return end case params[:button] when "cancel" copy_cancel when "copy" copy_save when "reset", nil # Reset or first time in action = params[:pressed] || @sb[:action] klass = case action when "miq_ae_class_copy" MiqAeClass when "miq_ae_instance_copy" MiqAeInstance when "miq_ae_method_copy" MiqAeMethod end copy_reset(klass, ids, action) end end def form_copy_objects_field_changed return unless load_edit("copy_objects__#{params[:id]}", "replace_cell__explorer") copy_objects_get_form_vars build_ae_tree(:automate, :automate_tree) @changed = (@edit[:new] != @edit[:current]) @changed = @edit[:new][:override_source] if @edit[:new][:namespace].nil? render :update do |page| page << javascript_prologue page.replace("flash_msg_div", :partial => "layouts/flash_msg") page.replace("form_div", :partial => "copy_objects_form") if params[:domain] || params[:override_source] page << javascript_for_miq_button_visibility(@changed) end end def ae_tree_select_toggle @edit = session[:edit] self.x_active_tree = :ae_tree at_tree_select_toggle(:namespace) if params[:button] == 'submit' x_node_set(@edit[:active_id], :automate_tree) @edit[:namespace] = @edit[:new][:namespace] end session[:edit] = @edit end def ae_tree_select @edit = session[:edit] at_tree_select(:namespace) session[:edit] = @edit end def x_show typ, id = params[:id].split("-") @record = TreeBuilder.get_model_for_prefix(typ).constantize.find(from_cid(id)) tree_select end def refresh_git_domain if params[:button] == "save" git_based_domain_import_service.import(params[:git_repo_id], params[:git_branch_or_tag], current_tenant.id) add_flash(_("Successfully refreshed!"), :info) else add_flash(_("Git based refresh canceled"), :info) end session[:edit] = nil @in_a_form = false replace_right_cell(:replace_trees => [:ae]) end private def playbook_inputs(method) existing_inputs = method.inputs new_inputs = params[:extra_vars] inputs_to_save = [] inputs_to_delete = [] new_inputs.each do |i, input| field = input.length == 4 ? MiqAeField.find_by(:id => input.last) : MiqAeField.new field.name = input[0] field.default_value = input[1] == "" ? nil : input[1] field.datatype = input[2] field.priority = i inputs_to_save.push(field) end existing_inputs.each do |existing_input| inputs_to_delete.push(existing_input.id) unless inputs_to_save.any? { |i| i.id == existing_input.id } end return inputs_to_save, inputs_to_delete end def set_playbook_data data = { :repository_id => params['repository_id'], :playbook_id => params['playbook_id'], :credential_id => params['credential_id'], :become_enabled => params['become_enabled'], :verbosity => params['verbosity'], } data[:network_credential_id] = params['network_credential_id'] if params['network_credential_id'] data[:cloud_credential_id] = params['cloud_credential_id'] if params['cloud_credential_id'] data end def angular_form_specific_data @record = @ae_method @ae_class = ae_class_for_instance_or_method(@ae_method) @current_region = MiqRegion.my_region.region @angular_form = true end def validate_expression(task) if @edit[@expkey][:expression]["???"] == "???" add_flash(_("Error during '%{task}': Expression element is required") % {:task => _(task)}, :error) @in_a_form = true javascript_flash end end def features [ApplicationController::Feature.new_with_hash(:role => "miq_ae_class_explorer", :role_any => true, :name => :ae, :accord_name => "datastores", :title => _("Datastore"))] end def initial_setup_for_instances_form_vars(ae_inst_id) @ae_inst = ae_inst_id ? MiqAeInstance.find(ae_inst_id) : MiqAeInstance.new @ae_class = ae_class_for_instance_or_method(@ae_inst) @ae_values = @ae_class.ae_fields.sort_by { |a| [a.priority.to_i] }.collect do |fld| MiqAeValue.find_or_initialize_by(:field_id => fld.id.to_s, :instance_id => @ae_inst.id.to_s) end end def instance_column_names %w(name description display_name) end def field_column_names %w(aetype collect datatype default_value display_name name on_entry on_error on_exit substitute) end def value_column_names %w(collect display_name on_entry on_error on_exit max_retries max_time value) end def method_input_column_names %w(datatype default_value id name priority) end def copy_objects_get_form_vars %w(domain override_existing override_source namespace new_name).each do |field| fld = field.to_sym if %w(override_existing override_source).include?(field) @edit[:new][fld] = params[fld] == "1" if params[fld] @edit[:new][:namespace] = nil if @edit[:new][:override_source] else @edit[:new][fld] = params[fld] if params[fld] if fld == :domain && params[fld] # save domain in sandbox, treebuilder doesnt have access to @edit @sb[:domain_id] = params[fld] @edit[:new][:namespace] = nil @edit[:new][:new_name] = nil end end end end def copy_save assert_privileges(@sb[:action]) return unless load_edit("copy_objects__#{params[:id]}", "replace_cell__explorer") begin @record = @edit[:typ].find(@edit[:rec_id]) domain = MiqAeDomain.find(@edit[:new][:domain]) @edit[:new][:new_name] = nil if @edit[:new][:new_name] == @edit[:old_name] options = { :ids => @edit[:selected_items].keys, :domain => domain.name, :namespace => @edit[:new][:namespace], :overwrite_location => @edit[:new][:override_existing], :new_name => @edit[:new][:new_name], :fqname => @edit[:fqname] } res = @edit[:typ].copy(options) rescue => bang render_flash(_("Error during '%{record} copy': %{error_message}") % {:record => ui_lookup(:model => @edit[:typ].to_s), :error_message => bang.message}, :error) return end model = @edit[:selected_items].count > 1 ? :models : :model add_flash(_("Copy selected %{record} was saved") % {:record => ui_lookup(model => @edit[:typ].to_s)}) @record = res.kind_of?(Array) ? @edit[:typ].find(res.first) : res self.x_node = "#{TreeBuilder.get_prefix_for_model(@edit[:typ])}-#{to_cid(@record.id)}" @in_a_form = @changed = session[:changed] = false @sb[:action] = @edit = session[:edit] = nil replace_right_cell end def copy_reset(typ, ids, button_pressed) assert_privileges(button_pressed) @changed = session[:changed] = @in_a_form = true copy_objects_edit_screen(typ, ids, button_pressed) if params[:button] == "reset" add_flash(_("All changes have been reset"), :warning) end build_ae_tree(:automate, :automate_tree) replace_right_cell end def copy_cancel assert_privileges(@sb[:action]) @record = session[:edit][:typ].find_by(:id => session[:edit][:rec_id]) model = @edit[:selected_items].count > 1 ? :models : :model @sb[:action] = session[:edit] = nil # clean out the saved info add_flash(_("Copy %{record} was cancelled by the user") % {:record => ui_lookup(model => @edit[:typ].to_s)}) @in_a_form = false replace_right_cell end def copy_objects_edit_screen(typ, ids, button_pressed) domains = {} selected_items = {} ids.each_with_index do |id, i| record = find_record_with_rbac(typ, from_cid(id)) selected_items[record.id] = record.display_name.blank? ? record.name : "#{record.display_name} (#{record.name})" @record = record if i.zero? end current_tenant.editable_domains.collect { |domain| domains[domain.id] = domain_display_name(domain) } initialize_copy_edit_vars(typ, button_pressed, domains, selected_items) @sb[:domain_id] = domains.first.first @edit[:current] = copy_hash(@edit[:new]) model = @edit[:selected_items].count > 1 ? :models : :model @right_cell_text = _("Copy %{model}") % {:model => ui_lookup(model => typ.to_s)} session[:edit] = @edit end def initialize_copy_edit_vars(typ, button_pressed, domains, selected_items) @edit = { :typ => typ, :action => button_pressed, :domain_name => @record.domain.name, :domain_id => @record.domain.id, :old_name => @record.name, :fqname => @record.fqname, :rec_id => from_cid(@record.id), :key => "copy_objects__#{from_cid(@record.id)}", :domains => domains, :selected_items => selected_items, :namespaces => {} } @edit[:new] = { :domain => domains.first.first, :override_source => true, :namespace => nil, :new_name => nil, :override_existing => false } end def create_action_url(node) if @sb[:action] == "miq_ae_domain_priority_edit" 'domains_priority_edit' elsif @sb[:action] == 'miq_ae_field_seq' 'fields_seq_edit' elsif MIQ_AE_COPY_ACTIONS.include?(@sb[:action]) 'copy_objects' else prefix = @edit[:rec_id].nil? ? 'create' : 'update' if node == 'aec' suffix_hash = { 'instances' => '_instance', 'methods' => '_method', 'props' => '', 'schema' => '_fields' } suffix = suffix_hash[@sb[:active_tab]] else suffix_hash = { 'root' => '_ns', 'aei' => '_instance', 'aem' => '_method', 'aen' => @edit.key?(:ae_class_id) ? '' : '_ns' } suffix = suffix_hash[node] end prefix + suffix end end def get_rec_name(rec) column = rec.display_name.blank? ? :name : :display_name if rec.kind_of?(MiqAeNamespace) && rec.domain? editable_domain = editable_domain?(rec) enabled_domain = rec.enabled unless editable_domain && enabled_domain return add_read_only_suffix(rec.send(column), editable_domain?(rec), enabled_domain) end end rec.send(column) end # Delete all selected or single displayed aeclasses(s) def deleteclasses assert_privileges("miq_ae_class_delete") delete_namespaces_or_classes end # Common aeclasses button handler routines def process_aeclasses(aeclasses, task) process_elements(aeclasses, MiqAeClass, task) end # Delete all selected or single displayed aeclasses(s) def deleteinstances assert_privileges("miq_ae_instance_delete") aeinstances = [] @sb[:row_selected] = find_checked_items if @sb[:row_selected] @sb[:row_selected].each do |items| item = items.split('-') item = find_id_with_rbac(MiqAeInstance, from_cid(item[1])) aeinstances.push(from_cid(item[1])) end else node = x_node.split('-') aeinstances.push(from_cid(node[1])) inst = find_record_with_rbac(MiqAeInstance, from_cid(node[1])) self.x_node = "aec-#{to_cid(inst.class_id)}" end process_aeinstances(aeinstances, "destroy") unless aeinstances.empty? replace_right_cell(:replace_trees => [:ae]) end # Common aeclasses button handler routines def process_aeinstances(aeinstances, task) process_elements(aeinstances, MiqAeInstance, task) end # Delete all selected or single displayed aeclasses(s) def deletemethods assert_privileges("miq_ae_method_delete") aemethods = [] @sb[:row_selected] = find_checked_items if @sb[:row_selected] @sb[:row_selected].each do |items| item = items.split('-') item = find_id_with_rbac(MiqAeMethod, from_cid(item[1])) aemethods.push(from_cid(item[1])) end else node = x_node.split('-') aemethods.push(from_cid(node[1])) inst = find_record_with_rbac(MiqAeMethod, from_cid(node[1])) self.x_node = "aec-#{to_cid(inst.class_id)}" end process_aemethods(aemethods, "destroy") unless aemethods.empty? replace_right_cell(:replace_trees => [:ae]) end # Common aeclasses button handler routines def process_aemethods(aemethods, task) process_elements(aemethods, MiqAeMethod, task) end def delete_domain assert_privileges("miq_ae_domain_delete") aedomains = [] git_domains = [] if params[:id] aedomains.push(params[:id]) self.x_node = "root" else selected = find_checked_items selected_ids = selected.map { |x| from_cid(x.split('-')[1]) } # TODO: replace with RBAC safe method #14665 is merged domains = MiqAeDomain.where(:id => selected_ids) domains.each do |domain| if domain.editable_properties? domain.git_enabled? ? git_domains.push(domain) : aedomains.push(domain.id) else add_flash(_("Read Only %{model} \"%{name}\" cannot be deleted") % {:model => ui_lookup(:model => "MiqAeDomain"), :name => get_record_display_name(domain)}, :error) end end end process_elements(aedomains, MiqAeDomain, 'destroy') unless aedomains.empty? git_domains.each do |domain| process_element_destroy_via_queue(domain, domain.class, domain.name) end replace_right_cell(:replace_trees => [:ae]) end # Delete all selected or single displayed aeclasses(s) def delete_ns assert_privileges("miq_ae_namespace_delete") delete_namespaces_or_classes end def delete_namespaces_or_classes selected = find_checked_items ae_ns = [] ae_cs = [] node = x_node.split('-') if params[:id] && params[:miq_grid_checks].blank? && node.first == "aen" ae_ns.push(params[:id]) ns = find_record_with_rbac(MiqAeNamespace, from_cid(node[1])) self.x_node = ns.parent_id ? "aen-#{to_cid(ns.parent_id)}" : "root" elsif selected ae_ns, ae_cs = items_to_delete(selected) else ae_cs.push(from_cid(node[1])) cls = find_record_with_rbac(MiqAeClass, from_cid(node[1])) self.x_node = "aen-#{to_cid(cls.namespace_id)}" end process_ae_ns(ae_ns, "destroy") unless ae_ns.empty? process_aeclasses(ae_cs, "destroy") unless ae_cs.empty? replace_right_cell(:replace_trees => [:ae]) end def items_to_delete(selected) ns_list = [] cs_list = [] selected.each do |items| item = items.split('-') if item[0] == "aen" record = find_record_with_rbac(MiqAeNamespace, from_cid(item[1])) if (record.domain? && record.editable_properties?) || record.editable? ns_list.push(from_cid(item[1])) else add_flash(_("\"%{field}\" %{model} cannot be deleted") % {:model => ui_lookup(:model => "MiqAeDomain"), :field => get_record_display_name(record)}, :error) end else cs_list.push(from_cid(item[1])) end end return ns_list, cs_list end # Common aeclasses button handler routines def process_ae_ns(ae_ns, task) process_elements(ae_ns, MiqAeNamespace, task) end # Get variables from edit form def get_form_vars @ae_class = MiqAeClass.find_by(:id => from_cid(@edit[:ae_class_id])) # for class add tab @edit[:new][:name] = params[:name].blank? ? nil : params[:name] if params[:name] @edit[:new][:description] = params[:description].blank? ? nil : params[:description] if params[:description] @edit[:new][:display_name] = params[:display_name].blank? ? nil : params[:display_name] if params[:display_name] @edit[:new][:namespace] = params[:namespace] if params[:namespace] @edit[:new][:inherits] = params[:inherits_from] if params[:inherits_from] # for class edit tab @edit[:new][:name] = params[:cls_name].blank? ? nil : params[:cls_name] if params[:cls_name] @edit[:new][:description] = params[:cls_description].blank? ? nil : params[:cls_description] if params[:cls_description] @edit[:new][:display_name] = params[:cls_display_name].blank? ? nil : params[:cls_display_name] if params[:cls_display_name] @edit[:new][:namespace] = params[:cls_namespace] if params[:cls_namespace] @edit[:new][:inherits] = params[:cls_inherits_from] if params[:cls_inherits_from] end # Common routine to find checked items on a page (checkbox ids are "check_xxx" where xxx is the item id or index) def find_checked_items(_prefix = nil) # AE can't use ApplicationController#find_checked_items because that one expects non-prefixed ids params[:miq_grid_checks].split(",") unless params[:miq_grid_checks].blank? end def field_attributes %w(aetype class_id collect datatype default_value description display_name id max_retries max_time message name on_entry on_error on_exit priority substitute) end def row_selected_in_grid? @sb[:row_selected] || x_node.split('-').first == "aec" end helper_method :row_selected_in_grid? # Get variables from edit form def fields_get_form_vars @ae_class = MiqAeClass.find_by(:id => from_cid(@edit[:ae_class_id])) @in_a_form = true @in_a_form_fields = true if params[:item].blank? && !%w(accept save).include?(params[:button]) && params["action"] != "field_delete" field_data = session[:field_data] new_field = @edit[:new_field] field_attributes.each do |field| field_name = "field_#{field}".to_sym field_sym = field.to_sym if field == "substitute" field_data[field_sym] = new_field[field_sym] = params[field_name] == "1" if params[field_name] elsif params[field_name] field_data[field_sym] = new_field[field_sym] = params[field_name] end end field_data[:default_value] = new_field[:default_value] = params[:field_password_value] if params[:field_password_value] new_field[:priority] = 1 @edit[:new][:fields].each_with_index do |flds, i| if i == @edit[:new][:fields].length - 1 new_field[:priority] = flds['priority'].nil? ? 1 : flds['priority'].to_i + 1 end end new_field[:class_id] = @ae_class.id @edit[:new][:fields].each_with_index do |fld, i| field_attributes.each do |field| field_name = "fields_#{field}_#{i}" if field == "substitute" fld[field] = params[field_name] == "1" if params[field_name] elsif %w(aetype datatype).include?(field) var_name = "fields_#{field}#{i}" fld[field] = params[var_name.to_sym] if params[var_name.to_sym] elsif field == "default_value" fld[field] = params[field_name] if params[field_name] fld[field] = params["fields_password_value_#{i}".to_sym] if params["fields_password_value_#{i}".to_sym] elsif params[field_name] fld[field] = params[field_name] end end end elsif params[:button] == "accept" if session[:field_data][:name].blank? || session[:field_data][:aetype].blank? field = session[:field_data][:name].blank? ? "Name" : "Type" field += " and Type" if field == "Name" && session[:field_data][:aetype].blank? add_flash(_("%{field} is required") % {:field => field}, :error) return end new_fields = {} field_attributes.each do |field_attribute| new_fields[field_attribute] = @edit[:new_field][field_attribute.to_sym] end @edit[:new][:fields].push(new_fields) @edit[:new_field] = session[:field_data] = {} end end def method_form_vars_process_fields(prefix = '') @edit[:new][:fields].each_with_index do |field, i| method_input_column_names.each do |column| field[column] = params["#{prefix}fields_#{column}_#{i}".to_sym] if params["#{prefix}fields_#{column}_#{i}".to_sym] next unless column == 'default_value' field[column] = params["#{prefix}fields_value_#{i}".to_sym] if params["#{prefix}fields_value_#{i}".to_sym] field[column] = params["#{prefix}fields_password_value_#{i}".to_sym] if params["#{prefix}fields_password_value_#{i}".to_sym] end end end # Get variables from edit form def get_method_form_vars @ae_method = @edit[:ae_method_id] ? MiqAeMethod.find(from_cid(@edit[:ae_method_id])) : MiqAeMethod.new @in_a_form = true if params[:item].blank? && params[:button] != "accept" && params["action"] != "field_delete" # for method_inputs view @edit[:new][:name] = params[:method_name].blank? ? nil : params[:method_name] if params[:method_name] @edit[:new][:display_name] = params[:method_display_name].blank? ? nil : params[:method_display_name] if params[:method_display_name] @edit[:new][:location] = params[:method_location] if params[:method_location] @edit[:new][:location] ||= "inline" @edit[:new][:data] = params[:method_data] if params[:method_data] method_form_vars_process_fields session[:field_data][:name] = @edit[:new_field][:name] = params[:field_name] if params[:field_name] session[:field_data][:datatype] = @edit[:new_field][:datatype] = params[:field_datatype] if params[:field_datatype] session[:field_data][:default_value] = @edit[:new_field][:default_value] = params[:field_default_value] if params[:field_default_value] session[:field_data][:default_value] = @edit[:new_field][:default_value] = params[:field_password_value] if params[:field_password_value] # for class_methods view @edit[:new][:name] = params[:cls_method_name].blank? ? nil : params[:cls_method_name] if params[:cls_method_name] @edit[:new][:display_name] = params[:cls_method_display_name].blank? ? nil : params[:cls_method_display_name] if params[:cls_method_display_name] @edit[:new][:location] = params[:cls_method_location] if params[:cls_method_location] @edit[:new][:location] ||= "inline" @edit[:new][:data] = params[:cls_method_data] if params[:cls_method_data] @edit[:new][:data] += "..." if params[:transOne] && params[:transOne] == "1" # Update the new data to simulate a change method_form_vars_process_fields('cls_') session[:field_data][:name] = @edit[:new_field][:name] = params[:cls_field_name] if params[:cls_field_name] session[:field_data][:datatype] = @edit[:new_field][:datatype] = params[:cls_field_datatype] if params[:cls_field_datatype] session[:field_data][:default_value] = @edit[:new_field][:default_value] = params[:cls_field_default_value] if params[:cls_field_default_value] session[:field_data][:default_value] = @edit[:new_field][:default_value] = params[:cls_field_password_value] if params[:cls_field_password_value] @edit[:new_field][:method_id] = @ae_method.id session[:field_data] ||= {} elsif params[:button] == "accept" if @edit[:new_field].blank? || @edit[:new_field][:name].nil? || @edit[:new_field][:name] == "" add_flash(_("Name is required"), :error) return end new_field = {} new_field['name'] = @edit[:new_field][:name] new_field['datatype'] = @edit[:new_field][:datatype] new_field['default_value'] = @edit[:new_field][:default_value] new_field['method_id'] = @ae_method.id @edit[:new][:fields].push(new_field) @edit[:new_field] = { :name => '', :default_value => '', :datatype => 'string' } elsif params[:add] == 'new' session[:fields_data] = { :name => '', :default_value => '', :datatype => 'string' } end end # Get variables from edit form def get_ns_form_vars @ae_ns = @edit[:typ].constantize.find_by(:id => from_cid(@edit[:ae_ns_id])) @edit[:new][:enabled] = params[:ns_enabled] == '1' if params[:ns_enabled] [:ns_name, :ns_description].each do |field| next unless params[field] @edit[:new][field] = params[field].blank? ? nil : params[field] end @in_a_form = true end def get_instances_form_vars_for(prefix = nil) instance_column_names.each do |key| @edit[:new][:ae_inst][key] = params["#{prefix}inst_#{key}"].blank? ? nil : params["#{prefix}inst_#{key}"] if params["#{prefix}inst_#{key}"] end @ae_class.ae_fields.sort_by { |a| [a.priority.to_i] }.each_with_index do |_fld, i| %w(value collect on_entry on_exit on_error max_retries max_time).each do |key| @edit[:new][:ae_values][i][key] = params["#{prefix}inst_#{key}_#{i}".to_sym] if params["#{prefix}inst_#{key}_#{i}".to_sym] end @edit[:new][:ae_values][i]["value"] = params["#{prefix}inst_password_value_#{i}".to_sym] if params["#{prefix}inst_password_value_#{i}".to_sym] end end # Get variables from edit form def get_instances_form_vars # resetting inst/class/values from id stored in @edit. @ae_inst = @edit[:ae_inst_id] ? MiqAeInstance.find(@edit[:ae_inst_id]) : MiqAeInstance.new @ae_class = MiqAeClass.find(from_cid(@edit[:ae_class_id])) @ae_values = @ae_class.ae_fields.sort_by { |a| a.priority.to_i }.collect do |fld| MiqAeValue.find_or_initialize_by(:field_id => fld.id.to_s, :instance_id => @ae_inst.id.to_s) end if x_node.split('-').first == "aei" # for instance_fields view get_instances_form_vars_for else # for class_instances view get_instances_form_vars_for("cls_") end end # Set record variables to new values def set_record_vars(miqaeclass) miqaeclass.name = @edit[:new][:name].strip unless @edit[:new][:name].blank? miqaeclass.display_name = @edit[:new][:display_name] miqaeclass.description = @edit[:new][:description] miqaeclass.inherits = @edit[:new][:inherits] ns = x_node.split("-") if ns.first == "aen" && !miqaeclass.namespace_id rec = MiqAeNamespace.find(from_cid(ns[1])) miqaeclass.namespace_id = rec.id.to_s # miqaeclass.namespace = rec.name end end # Set record variables to new values def set_method_record_vars(miqaemethod) miqaemethod.name = @edit[:new][:name].strip unless @edit[:new][:name].blank? miqaemethod.display_name = @edit[:new][:display_name] miqaemethod.scope = @edit[:new][:scope] miqaemethod.location = @edit[:new][:location] miqaemethod.language = @edit[:new][:language] miqaemethod.data = if @edit[:new][:location] == 'expression' data_for_expression else @edit[:new][:data] end miqaemethod.class_id = from_cid(@edit[:ae_class_id]) end # Set record variables to new values def ns_set_record_vars(miqaens) miqaens.name = @edit[:new][:ns_name].strip unless @edit[:new][:ns_name].blank? miqaens.description = @edit[:new][:ns_description] miqaens.enabled = @edit[:new][:enabled] if miqaens.domain? end # Set record variables to new values def set_field_vars(parent = nil) fields = parent_fields(parent) highest_priority = fields.count @edit[:new][:fields].each_with_index do |fld, i| if fld["id"].nil? new_field = MiqAeField.new highest_priority += 1 new_field.priority = highest_priority if @ae_method new_field.method_id = @ae_method.id else new_field.class_id = @ae_class.id end else new_field = parent.nil? ? MiqAeField.find(fld["id"]) : fields.detect { |f| f.id == fld["id"] } end field_attributes.each do |attr| if attr == "substitute" || @edit[:new][:fields][i][attr] new_field.send("#{attr}=", @edit[:new][:fields][i][attr]) end end if new_field.new_record? || parent.nil? raise StandardError, new_field.errors.full_messages[0] unless fields.push(new_field) end end reset_field_priority(fields) end alias_method :set_input_vars, :set_field_vars def parent_fields(parent) return [] unless parent parent.class == MiqAeClass ? parent.ae_fields : parent.inputs end def reset_field_priority(fields) # reset priority to be in order 1..3 i = 0 fields.sort_by { |a| [a.priority.to_i] }.each do |fld| if !@edit[:fields_to_delete].include?(fld.id.to_s) || fld.id.blank? i += 1 fld.priority = i end end fields end # Set record variables to new values def set_instances_record_vars(miqaeinst) instance_column_names.each do |attr| miqaeinst.send("#{attr}=", @edit[:new][:ae_inst][attr].try(:strip)) end miqaeinst.class_id = from_cid(@edit[:ae_class_id]) end # Set record variables to new values def set_instances_value_vars(vals, ae_instance = nil) original_values = ae_instance ? ae_instance.ae_values : [] vals.each_with_index do |v, i| original = original_values.detect { |ov| ov.id == v.id } unless original_values.empty? if original v = original elsif ae_instance ae_instance.ae_values << v end value_column_names.each do |attr| v.send("#{attr}=", @edit[:new][:ae_values][i][attr]) if @edit[:new][:ae_values][i][attr] end end end def fields_seq_edit_screen(id) @edit = {} @edit[:new] = {} @edit[:current] = {} @ae_class = MiqAeClass.find_by(:id => from_cid(id)) @edit[:rec_id] = @ae_class.try(:id) @edit[:ae_class_id] = @ae_class.id @edit[:new][:fields] = @ae_class.ae_fields.to_a.deep_clone @edit[:new][:fields_list] = @edit[:new][:fields] .sort_by { |f| f.priority.to_i } .collect { |f| f.display_name ? "#{f.display_name} (#{f.name})" : "(#{f.name})" } @edit[:key] = "fields_edit__seq" @edit[:current] = copy_hash(@edit[:new]) @right_cell_text = _("Edit of Class Schema Sequence '%{name}'") % {:name => @ae_class.name} session[:edit] = @edit end def move_selected_fields_up(available_fields, selected_fields, display_name) if no_items_selected?(selected_fields) add_flash(_("No %{name} were selected to move up") % {:name => display_name}, :error) return false end consecutive, first_idx, last_idx = selected_consecutive?(available_fields, selected_fields) @selected = selected_fields if consecutive if first_idx > 0 available_fields[first_idx..last_idx].reverse_each do |field| pulled = available_fields.delete(field) available_fields.insert(first_idx - 1, pulled) end end return true end add_flash(_("Select only one or consecutive %{name} to move up") % {:name => display_name}, :error) false end def move_selected_fields_down(available_fields, selected_fields, display_name) if no_items_selected?(selected_fields) add_flash(_("No %{name} were selected to move down") % {:name => display_name}, :error) return false end consecutive, first_idx, last_idx = selected_consecutive?(available_fields, selected_fields) @selected = selected_fields if consecutive if last_idx < available_fields.length - 1 insert_idx = last_idx + 1 # Insert before the element after the last one insert_idx = -1 if last_idx == available_fields.length - 2 # Insert at end if 1 away from end available_fields[first_idx..last_idx].each do |field| pulled = available_fields.delete(field) available_fields.insert(insert_idx, pulled) end end return true end add_flash(_("Select only one or consecutive %{name} to move down") % {:name => display_name}, :error) false end def no_items_selected?(field_name) !field_name || field_name.empty? || field_name[0] == "" end def selected_consecutive?(available_fields, selected_fields) first_idx = last_idx = 0 available_fields.each_with_index do |nf, idx| first_idx = idx if nf == selected_fields.first if nf == selected_fields.last last_idx = idx break end end if last_idx - first_idx + 1 > selected_fields.length return [false, first_idx, last_idx] else return [true, first_idx, last_idx] end end def edit_domain_or_namespace obj = find_checked_items obj = [x_node] if obj.nil? && params[:id] typ = params[:pressed] == "miq_ae_domain_edit" ? MiqAeDomain : MiqAeNamespace @ae_ns = find_record_with_rbac(typ, from_cid(obj[0].split('-')[1])) if @ae_ns.domain? && !@ae_ns.editable_properties? add_flash(_("Read Only %{model} \"%{name}\" cannot be edited") % {:model => ui_lookup(:model => "MiqAeDomain"), :name => get_record_display_name(@ae_ns)}, :error) else ns_set_form_vars @in_a_form = true session[:changed] = @changed = false end replace_right_cell end def new_ns assert_privileges("miq_ae_namespace_new") new_domain_or_namespace(MiqAeNamespace) end def new_domain assert_privileges("miq_ae_domain_new") new_domain_or_namespace(MiqAeDomain) end def new_domain_or_namespace(klass) parent_id = x_node == "root" ? nil : from_cid(x_node.split("-").last) @ae_ns = klass.new(:parent_id => parent_id) ns_set_form_vars @in_a_form = true replace_right_cell end # Set form variables for edit def ns_set_form_vars session[:field_data] = session[:edit] = {} @edit = { :ae_ns_id => @ae_ns.id, :typ => @ae_ns.domain? ? "MiqAeDomain" : "MiqAeNamespace", :key => "aens_edit__#{@ae_ns.id || "new"}", :rec_id => @ae_ns.id || nil } @edit[:new] = { :ns_name => @ae_ns.name, :ns_description => @ae_ns.description } # set these field for a new domain or when existing record is a domain @edit[:new][:enabled] = @ae_ns.enabled if @ae_ns.domain? @edit[:current] = @edit[:new].dup @right_cell_text = ns_right_cell_text session[:edit] = @edit end def ns_right_cell_text model = ui_lookup(:model => @edit[:typ]) name_for_msg = if @edit[:rec_id].nil? _("Adding a new %{model}") % {:model => model} else _("Editing %{model} \"%{name}\"") % {:model => model, :name => @ae_ns.name} end name_for_msg end def ordered_domains_for_priority_edit_screen User.current_tenant.sequenceable_domains.collect(&:name) end def priority_edit_screen @in_a_form = true @edit = { :key => "priority__edit", :new => {:domain_order => ordered_domains_for_priority_edit_screen} } @edit[:current] = copy_hash(@edit[:new]) session[:edit] = @edit end def domain_toggle(locked) assert_privileges("miq_ae_domain_#{locked ? 'lock' : 'unlock'}") action = locked ? _("Locked") : _("Unlocked") if params[:id].nil? add_flash(_("No %{model} were selected to be marked as %{action}") % {:model => ui_lookup(:model => "MiqAeDomain"), :action => action}, :error) javascript_flash end domain_toggle_lock(params[:id], locked) unless flash_errors? add_flash(_("The selected %{model} were marked as %{action}") % {:model => ui_lookup(:model => "MiqAeDomain"), :action => action}, :info, true) end replace_right_cell(:replace_trees => [:ae]) end def domain_lock domain_toggle(true) end def domain_unlock domain_toggle(false) end def domain_toggle_lock(domain_id, lock) domain = MiqAeDomain.find(domain_id) lock ? domain.lock_contents! : domain.unlock_contents! end def git_refresh @in_a_form = true @explorer = true session[:changed] = true git_repo = MiqAeDomain.find(params[:id]).git_repository git_based_domain_import_service.refresh(git_repo.id) git_repo.reload @branch_names = git_repo.git_branches.collect(&:name) @tag_names = git_repo.git_tags.collect(&:name) @git_repo_id = git_repo.id @right_cell_text = _("Refreshing branch/tag for Git-based Domain") h_tb = build_toolbar("x_history_tb") presenter = ExplorerPresenter.new( :active_tree => x_active_tree, :right_cell_text => @right_cell_text, :remove_nodes => nil, :add_nodes => nil, ) update_partial_div = :main_div update_partial = "git_domain_refresh" presenter.update(update_partial_div, r[:partial => update_partial]) action_url = "refresh_git_domain" presenter.show(:paging_div, :form_buttons_div) presenter.update(:form_buttons_div, r[ :partial => "layouts/x_edit_buttons", :locals => { :record_id => git_repo.id, :action_url => action_url, :serialize => true, :no_reset => true } ]) presenter.reload_toolbars(:history => h_tb) presenter.show(:toolbar) render :json => presenter.for_render end def git_based_domain_import_service @git_based_domain_import_service ||= GitBasedDomainImportService.new end def get_instance_node_info(id) begin @record = MiqAeInstance.find(from_cid(id[1])) rescue ActiveRecord::RecordNotFound set_root_node return end @ae_class = @record.ae_class @sb[:active_tab] = "instances" domain_overrides set_right_cell_text(x_node, @record) end def get_method_node_info(id) begin @record = @ae_method = MiqAeMethod.find(from_cid(id[1])) rescue ActiveRecord::RecordNotFound set_root_node return end @ae_class = @record.ae_class @sb[:squash_state] = true @sb[:active_tab] = "methods" if @record.location == 'expression' hash = YAML.load(@record.data) @expression = hash[:expression] ? MiqExpression.new(hash[:expression]).to_human : "" elsif @record.location == "playbook" fetch_playbook_details end domain_overrides set_right_cell_text(x_node, @record) end def fetch_playbook_details @playbook_details = {} data = YAML.load(@record.data) @playbook_details[:repository] = fetch_name_from_object(ManageIQ::Providers::EmbeddedAnsible::AutomationManager::ConfigurationScriptSource, data[:repository_id]) @playbook_details[:playbook] = fetch_name_from_object(ManageIQ::Providers::EmbeddedAnsible::AutomationManager::Playbook, data[:playbook_id]) @playbook_details[:machine_credential] = fetch_name_from_object(ManageIQ::Providers::EmbeddedAnsible::AutomationManager::MachineCredential, data[:credential_id]) @playbook_details[:network_credential] = fetch_name_from_object(ManageIQ::Providers::EmbeddedAnsible::AutomationManager::NetworkCredential, data[:network_credential_id]) if data[:network_credential_id] @playbook_details[:cloud_credential] = fetch_name_from_object(ManageIQ::Providers::EmbeddedAnsible::AutomationManager::CloudCredential, data[:cloud_credential_id]) if data[:cloud_credential_id] @playbook_details[:verbosity] = data[:verbosity] @playbook_details[:become_enabled] = data[:become_enabled] == 'true' ? _("Yes") : _("No") @playbook_details end def get_class_node_info(id) @sb[:active_tab] = "instances" if !@in_a_form && !params[:button] && !params[:pressed] begin @record = @ae_class = MiqAeClass.find(from_cid(id[1])) rescue ActiveRecord::RecordNotFound set_root_node return end @combo_xml = build_type_options # passing fields because that's how many combo boxes we need @dtype_combo_xml = build_dtype_options @grid_methods_list_xml = build_details_grid(@record.ae_methods) domain_overrides set_right_cell_text(x_node, @record) end def domain_overrides @domain_overrides = {} typ, = x_node.split('-') overrides = TreeBuilder.get_model_for_prefix(typ).constantize.get_homonymic_across_domains(current_user, @record.fqname) overrides.each do |obj| display_name, id = domain_display_name_using_name(obj, @record.domain.name) @domain_overrides[display_name] = id end end def title _("Datastore") end def session_key_prefix "miq_ae_class" end def get_session_data super @edit = session[:edit] end def flash_validation_errors(am_obj) am_obj.errors.each do |field, msg| add_flash("#{field.to_s.capitalize} #{msg}", :error) end end menu_section :automate def process_element_destroy_via_queue(element, klass, name) return unless element.respond_to?(:destroy) audit = {:event => "#{klass.name.downcase}_record_delete", :message => "[#{name}] Record deleted", :target_id => element.id, :target_class => klass.base_class.name, :userid => session[:userid]} model_name = ui_lookup(:model => klass.name) # Lookup friendly model name in dictionary record_name = get_record_display_name(element) begin git_based_domain_import_service.destroy_domain(element.id) AuditEvent.success(audit) add_flash(_("%{model} \"%{name}\": Delete successful") % {:model => model_name, :name => record_name}) rescue => bang add_flash(_("%{model} \"%{name}\": Error during delete: %{error_msg}") % {:model => model_name, :name => record_name, :error_msg => bang.message}, :error) end end end
module Mixins module PlaybookOptions def playbook_options_field_changed @edit = session[:edit] @edit[:new][:inventory_type] = params[:inventory_type] if params[:inventory_type] playbook_box_edit render :update do |page| page << javascript_prologue if @edit[:new][:button_type] == 'ansible_playbook' page << javascript_show('playbook_div') page << if @edit[:new][:inventory_type] == "manual" javascript_show('manual_inventory_div') else javascript_hide('manual_inventory_div') end else page << javascript_hide('playbook_div') end @changed = session[:changed] = (@edit[:new] != @edit[:current]) page << javascript_for_miq_button_visibility(@changed) page << "miqSparkle(false);" end end def dialog_for_service_template(service_template) service_template.resource_actions.each do |ra| d = Dialog.where(:id => ra.dialog_id).first @edit[:new][:dialog_id] = d.id if d end end def playbook_box_edit if params[:inventory_manual] || params[:inventory_localhost] || params[:inventory_event_target] update_playbook_variables(params) end if params[:service_template_id] @edit[:new][:service_template_id] = params[:service_template_id].to_i service_template = ServiceTemplate.find_by(:id => @edit[:new][:service_template_id]) dialog_for_service_template(service_template) if service_template end @edit[:new][:hosts] = params[:hosts] if params[:hosts] end def update_playbook_variables(params) @edit[:new][:inventory_type] = params[:inventory_manual] if params[:inventory_manual] @edit[:new][:inventory_type] = params[:inventory_localhost] if params[:inventory_localhost] @edit[:new][:inventory_type] = params[:inventory_event_target] if params[:inventory_event_target] @edit[:new][:hosts] = '' if params[:inventory_localhost] || params[:inventory_event_target] end def clear_playbook_variables @edit[:new][:service_template_id] = nil @edit[:new][:inventory_type] = 'localhost' @edit[:new][:hosts] = '' end def initialize_playbook_variables @edit[:new][:service_template_id] = nil @edit[:new][:inventory_type] = "localhost" @edit[:new][:hosts] = '' end end end Clear the request field when switching the button type from Ansible to default module Mixins module PlaybookOptions def playbook_options_field_changed @edit = session[:edit] @edit[:new][:inventory_type] = params[:inventory_type] if params[:inventory_type] playbook_box_edit render :update do |page| page << javascript_prologue if @edit[:new][:button_type] == 'ansible_playbook' page << javascript_show('playbook_div') page << if @edit[:new][:inventory_type] == "manual" javascript_show('manual_inventory_div') else javascript_hide('manual_inventory_div') end else page << javascript_hide('playbook_div') end @changed = session[:changed] = (@edit[:new] != @edit[:current]) page << javascript_for_miq_button_visibility(@changed) page << "miqSparkle(false);" end end def dialog_for_service_template(service_template) service_template.resource_actions.each do |ra| d = Dialog.where(:id => ra.dialog_id).first @edit[:new][:dialog_id] = d.id if d end end def playbook_box_edit if params[:inventory_manual] || params[:inventory_localhost] || params[:inventory_event_target] update_playbook_variables(params) end if params[:service_template_id] @edit[:new][:service_template_id] = params[:service_template_id].to_i service_template = ServiceTemplate.find_by(:id => @edit[:new][:service_template_id]) dialog_for_service_template(service_template) if service_template end @edit[:new][:hosts] = params[:hosts] if params[:hosts] end def update_playbook_variables(params) @edit[:new][:inventory_type] = params[:inventory_manual] if params[:inventory_manual] @edit[:new][:inventory_type] = params[:inventory_localhost] if params[:inventory_localhost] @edit[:new][:inventory_type] = params[:inventory_event_target] if params[:inventory_event_target] @edit[:new][:hosts] = '' if params[:inventory_localhost] || params[:inventory_event_target] end def clear_playbook_variables @edit[:new][:service_template_id] = nil @edit[:new][:inventory_type] = 'localhost' @edit[:new][:hosts] = '' @edit[:new][:object_request] = nil end def initialize_playbook_variables @edit[:new][:service_template_id] = nil @edit[:new][:inventory_type] = "localhost" @edit[:new][:hosts] = '' end end end
#!/usr/bin/env ruby require_relative 'assert_system' require_relative 'dir_get_args' require_relative 'dockerhub' require_relative 'image_builder' class InnerMain def initialize @src_dir = ENV['SRC_DIR'] @args = dir_get_args(@src_dir) end def run t1 = Time.now validate_image_data_triple Dockerhub.login builder = ImageBuilder.new(@src_dir, @args) builder.build_and_test_image Dockerhub.push_image(image_name) Dockerhub.logout trigger_dependent_repos t2 = Time.now print_date_time(t1, t2) end private include AssertSystem include DirGetArgs def print_date_time(t1, t2) banner assert_system 'date' hms = Time.at(t2 - t1).utc.strftime("%H:%M:%S") print_to STDOUT, "took #{hms}", "\n" end def validate_image_data_triple banner if validated? print_to STDOUT, triple.inspect, 'OK' else print_to STDERR, *triple_diagnostic(triples_url) if running_on_travis? exit false end end end def triple { "from" => from, "image_name" => image_name, "test_framework" => test_framework? } end def image_name @args[:image_name] end def from @args[:from] end def test_framework? @args[:test_framework] end # - - - - - - - - - - - - - - - - - def validated? triple = triples.find { |_,args| args['image_name'] == image_name } if triple.nil? return false end triple = triple[1] triple['from'] == from && triple['test_framework'] == test_framework? end def triples @triples ||= curled_triples end def curled_triples assert_system "curl --silent -O #{triples_url}" JSON.parse(IO.read("./#{triples_filename}")) end def triples_url "https://raw.githubusercontent.com/cyber-dojo-languages/images_info/master/#{triples_filename}" end def triples_filename 'images_info.json' end def triple_diagnostic(url) [ '', url, 'does not contain an entry for:', '', "#{quoted('...dir...')}: {", " #{quoted('from')}: #{quoted(from)},", " #{quoted('image_name')}: #{quoted(image_name)},", " #{quoted('test_framework')}: #{quoted(test_framework?)}", '},', '' ] end def quoted(s) '"' + s.to_s + '"' end # - - - - - - - - - - - - - - - - - def trigger_dependent_repos banner repos = dependent_repos print_to STDOUT, "dependent repos: #{repos.size}" if running_on_travis? travis_trigger(repos) else local_list(repos) end banner_end end def travis_trigger(repos) if repos.size == 0 return end assert_system "travis login --skip-completion-check --github-token ${GITHUB_TOKEN}" token = assert_backtick('travis token --org').strip repos.each do |repo_name| puts " #{cdl}/#{repo_name}" output = assert_backtick "./app/trigger.sh #{token} #{cdl} #{repo_name}" print_to STDOUT, output print_to STDOUT, "\n", '- - - - - - - - -' end end def local_list(repos) print_to STDOUT, 'skipped (not running on Travis)' repos.each do |repo_name| puts " #{cdl}/#{repo_name}" end end def dependent_repos triples.keys.select { |key| triples[key]['from'] == image_name } end def cdl 'cyber-dojo-languages' end # - - - - - - - - - - - - - - - - - def banner title = caller_locations(1,1)[0].label print_to STDOUT, '', banner_line, title end def banner_end print_to STDOUT, 'OK', banner_line end def banner_line '-' * 42 end # - - - - - - - - - - - - - - - - - def running_on_travis? ENV['TRAVIS'] == 'true' end end InnerMain.new.run logout of travis after getting token #!/usr/bin/env ruby require_relative 'assert_system' require_relative 'dir_get_args' require_relative 'dockerhub' require_relative 'image_builder' class InnerMain def initialize @src_dir = ENV['SRC_DIR'] @args = dir_get_args(@src_dir) end def run t1 = Time.now validate_image_data_triple Dockerhub.login builder = ImageBuilder.new(@src_dir, @args) builder.build_and_test_image Dockerhub.push_image(image_name) Dockerhub.logout trigger_dependent_repos t2 = Time.now print_date_time(t1, t2) end private include AssertSystem include DirGetArgs def print_date_time(t1, t2) banner assert_system 'date' hms = Time.at(t2 - t1).utc.strftime("%H:%M:%S") print_to STDOUT, "took #{hms}", "\n" end def validate_image_data_triple banner if validated? print_to STDOUT, triple.inspect, 'OK' else print_to STDERR, *triple_diagnostic(triples_url) if running_on_travis? exit false end end end def triple { "from" => from, "image_name" => image_name, "test_framework" => test_framework? } end def image_name @args[:image_name] end def from @args[:from] end def test_framework? @args[:test_framework] end # - - - - - - - - - - - - - - - - - def validated? triple = triples.find { |_,args| args['image_name'] == image_name } if triple.nil? return false end triple = triple[1] triple['from'] == from && triple['test_framework'] == test_framework? end def triples @triples ||= curled_triples end def curled_triples assert_system "curl --silent -O #{triples_url}" JSON.parse(IO.read("./#{triples_filename}")) end def triples_url "https://raw.githubusercontent.com/cyber-dojo-languages/images_info/master/#{triples_filename}" end def triples_filename 'images_info.json' end def triple_diagnostic(url) [ '', url, 'does not contain an entry for:', '', "#{quoted('...dir...')}: {", " #{quoted('from')}: #{quoted(from)},", " #{quoted('image_name')}: #{quoted(image_name)},", " #{quoted('test_framework')}: #{quoted(test_framework?)}", '},', '' ] end def quoted(s) '"' + s.to_s + '"' end # - - - - - - - - - - - - - - - - - def trigger_dependent_repos banner repos = dependent_repos print_to STDOUT, "dependent repos: #{repos.size}" if running_on_travis? travis_trigger(repos) else local_list(repos) end banner_end end def travis_trigger(repos) if repos.size == 0 return end assert_system "travis login --skip-completion-check --github-token ${GITHUB_TOKEN}" token = assert_backtick('travis token --org').strip assert_system 'travis logout' repos.each do |repo_name| puts " #{cdl}/#{repo_name}" output = assert_backtick "./app/trigger.sh #{token} #{cdl} #{repo_name}" print_to STDOUT, output print_to STDOUT, "\n", '- - - - - - - - -' end end def local_list(repos) print_to STDOUT, 'skipped (not running on Travis)' repos.each do |repo_name| puts " #{cdl}/#{repo_name}" end end def dependent_repos triples.keys.select { |key| triples[key]['from'] == image_name } end def cdl 'cyber-dojo-languages' end # - - - - - - - - - - - - - - - - - def banner title = caller_locations(1,1)[0].label print_to STDOUT, '', banner_line, title end def banner_end print_to STDOUT, 'OK', banner_line end def banner_line '-' * 42 end # - - - - - - - - - - - - - - - - - def running_on_travis? ENV['TRAVIS'] == 'true' end end InnerMain.new.run
class ModelImagesController < ApplicationController before_filter :check_model_specified before_filter :find_model_images, :only=>[:index] before_filter :find_model_image_auth,:only=>[:show,:select,:edit,:update,:destroy] def new @model_image = ModelImage.new end def create unless params[:model_image].blank? || params[:model_image][:image_file].blank? file_specified = true @model_image = ModelImage.new params[:model_image] @model_image.model_id = params[:model_id] @model_image.content_type = params[:model_image][:image_file].content_type @model_image.original_filename = params[:model_image][:image_file].original_filename else file_specified = false end respond_to do |format| if file_specified && @model_image.save if @model_image.model.model_image_id.nil? @model_instance.update_attribute(:model_image_id,@model_image.id) end flash[:notice] = 'Image was successfully uploaded' format.html {redirect_to params[:return_to]} else @model_image = ModelImage.new unless file_specified flash.now[:error]= "You haven't specified the filename. Please choose the image file to upload." else flash.now[:error] = "The image format is unreadable. Please try again or select a different image." end format.html { render :action => 'new'} end end end def show params[:size] ||='200x200' if params[:size]=='large' size = ModelImage::LARGE_SIZE else size = params[:size] end size = size[0..-($1.length.to_i + 2)] if size =~ /[0-9]+x[0-9]+\.([a-z0-9]+)/ # trim file extension size = filter_size size id = params[:id].to_i if !cache_exists?(id, size) # look in file system cache before attempting db access # resize (keeping image side ratio), encode and cache the picture @model_image.operate do |image| Rails.logger.info "resizing to #{size}" image.resize size, :upsample=>true @image_binary = image.image.to_blob end # cache data cache_data!(@model_image, @image_binary, size) end respond_to do |format| format.html do send_file(full_cache_path(id, size), :type => 'image/jpeg', :disposition => 'inline') end format.xml do @cache_file=full_cache_path(id, size) @type='image/jpeg' end end end def filter_size size max_size=1500 matches = size.match /([0-9]+)x([0-9]+).*/ if matches width = matches[1].to_i height = matches[2].to_i width = max_size if width>max_size height = max_size if height>max_size return "#{width}x#{height}" else return "100x100" end end def index respond_to do |format| format.html end end def destroy model = @model_image.model @model_image.destroy respond_to do |format| format.html { redirect_to model_model_images_url model.id} end end def select if @model_image.select! @model_image.save respond_to do |format| flash[:notice]= 'Model image was successfully updated.' format.html { redirect_to model_model_image_url @model_instance.id} end else respond_to do |format| flash[:error] = 'Image was already selected.' format.html { redirect_to url_for(@model_instance)} end end end private def check_model_specified @image_for = 'Model' @image_for_id = params[:model_id] begin @model_instance = Model.find(@image_for_id) rescue ActiveRecord::RecordNotFound flash[:error] = "Could not find the #{@image_for.downcase} for this image." redirect_to(root_path) return false end end def find_model_images if @model_instance.can_view? current_user @model_images = ModelImage.find(:all,:conditions=>{:model_id=>@image_for_id}) else flash[:error] = "You can only view images for models you can access" redirect_to root_path end end def find_model_image_auth action = translate_action(action_name) unless is_auth?(@model_instance,action) flash[:error] = "You can only #{action} images for models you can access" redirect_to root_path return false end begin @model_image = ModelImage.find params[:id],:conditions => { :model_id => @image_for_id} rescue ActiveRecord::RecordNotFound flash[:error] = "Image not found or belongs to a different model." redirect_to root_path return false end end # caches data (where size = #{size}x#{size}) def cache_data!(image, image_binary, size=nil) FileUtils.mkdir_p(cache_path(image, size)) File.open(full_cache_path(image, size), "wb+") { |f| f.write(image_binary) } end def cache_path(image, size=nil, include_local_name=false) id = image.kind_of?(Integer) ? image : image.id rtn = "#{RAILS_ROOT}/tmp/model_images" rtn = "#{rtn}/#{size}" if size rtn = "#{rtn}/#{id}.#{ModelImage.image_storage_format}" if include_local_name return rtn end def full_cache_path(image, size=nil) cache_path(image, size, true) end def cache_exists?(image, size=nil) File.exists?(full_cache_path(image, size)) end end handle model image size where only the width is specified class ModelImagesController < ApplicationController before_filter :check_model_specified before_filter :find_model_images, :only=>[:index] before_filter :find_model_image_auth,:only=>[:show,:select,:edit,:update,:destroy] def new @model_image = ModelImage.new end def create unless params[:model_image].blank? || params[:model_image][:image_file].blank? file_specified = true @model_image = ModelImage.new params[:model_image] @model_image.model_id = params[:model_id] @model_image.content_type = params[:model_image][:image_file].content_type @model_image.original_filename = params[:model_image][:image_file].original_filename else file_specified = false end respond_to do |format| if file_specified && @model_image.save if @model_image.model.model_image_id.nil? @model_instance.update_attribute(:model_image_id,@model_image.id) end flash[:notice] = 'Image was successfully uploaded' format.html {redirect_to params[:return_to]} else @model_image = ModelImage.new unless file_specified flash.now[:error]= "You haven't specified the filename. Please choose the image file to upload." else flash.now[:error] = "The image format is unreadable. Please try again or select a different image." end format.html { render :action => 'new'} end end end def show params[:size] ||='200x200' if params[:size]=='large' size = ModelImage::LARGE_SIZE else size = params[:size] end size = size[0..-($1.length.to_i + 2)] if size =~ /[0-9]+x[0-9]+\.([a-z0-9]+)/ # trim file extension size = filter_size size id = params[:id].to_i if !cache_exists?(id, size) # look in file system cache before attempting db access # resize (keeping image side ratio), encode and cache the picture @model_image.operate do |image| Rails.logger.info "resizing to #{size}" image.resize size, :upsample=>true @image_binary = image.image.to_blob end # cache data cache_data!(@model_image, @image_binary, size) end respond_to do |format| format.html do send_file(full_cache_path(id, size), :type => 'image/jpeg', :disposition => 'inline') end format.xml do @cache_file=full_cache_path(id, size) @type='image/jpeg' end end end def filter_size size max_size=1500 matches = size.match /([0-9]+)x([0-9]+).*/ if matches width = matches[1].to_i height = matches[2].to_i width = max_size if width>max_size height = max_size if height>max_size return "#{width}x#{height}" else matches = size.match /([0-9]+)/ if matches width=matches[1].to_i width = max_size if width>max_size return "#{width}" else return "900" end end end def index respond_to do |format| format.html end end def destroy model = @model_image.model @model_image.destroy respond_to do |format| format.html { redirect_to model_model_images_url model.id} end end def select if @model_image.select! @model_image.save respond_to do |format| flash[:notice]= 'Model image was successfully updated.' format.html { redirect_to model_model_image_url @model_instance.id} end else respond_to do |format| flash[:error] = 'Image was already selected.' format.html { redirect_to url_for(@model_instance)} end end end private def check_model_specified @image_for = 'Model' @image_for_id = params[:model_id] begin @model_instance = Model.find(@image_for_id) rescue ActiveRecord::RecordNotFound flash[:error] = "Could not find the #{@image_for.downcase} for this image." redirect_to(root_path) return false end end def find_model_images if @model_instance.can_view? current_user @model_images = ModelImage.find(:all,:conditions=>{:model_id=>@image_for_id}) else flash[:error] = "You can only view images for models you can access" redirect_to root_path end end def find_model_image_auth action = translate_action(action_name) unless is_auth?(@model_instance,action) flash[:error] = "You can only #{action} images for models you can access" redirect_to root_path return false end begin @model_image = ModelImage.find params[:id],:conditions => { :model_id => @image_for_id} rescue ActiveRecord::RecordNotFound flash[:error] = "Image not found or belongs to a different model." redirect_to root_path return false end end # caches data (where size = #{size}x#{size}) def cache_data!(image, image_binary, size=nil) FileUtils.mkdir_p(cache_path(image, size)) File.open(full_cache_path(image, size), "wb+") { |f| f.write(image_binary) } end def cache_path(image, size=nil, include_local_name=false) id = image.kind_of?(Integer) ? image : image.id rtn = "#{RAILS_ROOT}/tmp/model_images" rtn = "#{rtn}/#{size}" if size rtn = "#{rtn}/#{id}.#{ModelImage.image_storage_format}" if include_local_name return rtn end def full_cache_path(image, size=nil) cache_path(image, size, true) end def cache_exists?(image, size=nil) File.exists?(full_cache_path(image, size)) end end
#encoding: utf-8 class ObservationsController < ApplicationController caches_page :tile_points WIDGET_CACHE_EXPIRATION = 15.minutes caches_action :index, :by_login, :project, :expires_in => WIDGET_CACHE_EXPIRATION, :cache_path => Proc.new {|c| c.params.merge(:locale => I18n.locale)}, :if => Proc.new {|c| c.session.blank? && # make sure they're logged out c.request.format && # make sure format corresponds to a known mime type (c.request.format.geojson? || c.request.format.widget? || c.request.format.kml?) && c.request.url.size < 250} caches_action :of, :expires_in => 1.day, :cache_path => Proc.new {|c| c.params.merge(:locale => I18n.locale)}, :if => Proc.new {|c| c.request.format != :html } cache_sweeper :observation_sweeper, :only => [:create, :update, :destroy] rescue_from ::AbstractController::ActionNotFound do unless @selected_user = User.find_by_login(params[:action]) return render_404 end by_login end doorkeeper_for :create, :update, :destroy, :if => lambda { authenticate_with_oauth? } before_filter :load_user_by_login, :only => [:by_login, :by_login_all] before_filter :return_here, :only => [:index, :by_login, :show, :id_please, :import, :add_from_list, :new, :project] before_filter :authenticate_user!, :unless => lambda { authenticated_with_oauth? }, :except => [:explore, :index, :of, :show, :by_login, :id_please, :tile_points, :nearby, :widget, :project] before_filter :load_observation, :only => [:show, :edit, :edit_photos, :update_photos, :destroy, :fields] before_filter :require_owner, :only => [:edit, :edit_photos, :update_photos, :destroy] before_filter :curator_required, :only => [:curation] before_filter :load_photo_identities, :only => [:new, :new_batch, :show, :new_batch_csv,:edit, :update, :edit_batch, :create, :import, :import_photos, :new_from_list] before_filter :photo_identities_required, :only => [:import_photos] after_filter :refresh_lists_for_batch, :only => [:create, :update] MOBILIZED = [:add_from_list, :nearby, :add_nearby, :project, :by_login, :index, :show] before_filter :unmobilized, :except => MOBILIZED before_filter :mobilized, :only => MOBILIZED before_filter :load_prefs, :only => [:index, :project, :by_login] ORDER_BY_FIELDS = %w"created_at observed_on species_guess" REJECTED_FEED_PARAMS = %w"page view filters_open partial" REJECTED_KML_FEED_PARAMS = REJECTED_FEED_PARAMS + %w"swlat swlng nelat nelng" DISPLAY_ORDER_BY_FIELDS = { 'created_at' => 'date added', 'observations.id' => 'date added', 'id' => 'date added', 'observed_on' => 'date observed', 'species_guess' => 'species name' } PARTIALS = %w(cached_component observation_component observation mini) EDIT_PARTIALS = %w(add_photos) PHOTO_SYNC_ATTRS = [:description, :species_guess, :taxon_id, :observed_on, :observed_on_string, :latitude, :longitude, :place_guess] # GET /observations # GET /observations.xml def index search_params, find_options = get_search_params(params) search_params = site_search_params(search_params) if search_params[:q].blank? @observations = if perform_caching cache_params = params.reject{|k,v| %w(controller action format partial).include?(k.to_s)} cache_params[:page] ||= 1 cache_params[:site_name] ||= SITE_NAME if CONFIG.site_only_observations cache_params[:bounds] ||= CONFIG.bounds if CONFIG.bounds cache_key = "obs_index_#{Digest::MD5.hexdigest(cache_params.to_s)}" Rails.cache.fetch(cache_key, :expires_in => 5.minutes) do get_paginated_observations(search_params, find_options).to_a end else get_paginated_observations(search_params, find_options) end else @observations = search_observations(search_params, find_options) end respond_to do |format| format.html do @iconic_taxa ||= [] if (partial = params[:partial]) && PARTIALS.include?(partial) pagination_headers_for(@observations) return render_observations_partial(partial) end end format.json do render_observations_to_json end format.mobile format.geojson do render :json => @observations.to_geojson(:except => [ :geom, :latitude, :longitude, :map_scale, :num_identification_agreements, :num_identification_disagreements, :delta, :location_is_exact]) end format.atom do @updated_at = Observation.first(:order => 'updated_at DESC').updated_at end format.dwc format.csv do render_observations_to_csv end format.kml do render_observations_to_kml( :snippet => "#{CONFIG.site_name} Feed for Everyone", :description => "#{CONFIG.site_name} Feed for Everyone", :name => "#{CONFIG.site_name} Feed for Everyone" ) end format.widget do if params[:markup_only]=='true' render :js => render_to_string(:partial => "widget.html.erb", :locals => { :show_user => true, :target => params[:target], :default_image => params[:default_image], :silence => params[:silence] }) else render :js => render_to_string(:partial => "widget.js.erb", :locals => { :show_user => true }) end end end end def of if request.format == :html redirect_to observations_path(:taxon_id => params[:id]) return end unless @taxon = Taxon.find_by_id(params[:id].to_i) render_404 && return end @observations = Observation.of(@taxon).all( :include => [:user, :taxon, :iconic_taxon, :observation_photos => [:photo]], :order => "observations.id desc", :limit => 500).sort_by{|o| [o.quality_grade == "research" ? 1 : 0, o.id]} respond_to do |format| format.json do render :json => @observations.to_json( :methods => [:user_login, :iconic_taxon_name, :obs_image_url], :include => {:user => {:only => :login}, :taxon => {}, :iconic_taxon => {}}) end format.geojson do render :json => @observations.to_geojson(:except => [ :geom, :latitude, :longitude, :map_scale, :num_identification_agreements, :num_identification_disagreements, :delta, :location_is_exact]) end end end # GET /observations/1 # GET /observations/1.xml def show if request.format == :html && params[:partial] == "cached_component" && fragment_exist?(@observation.component_cache_key(:for_owner => @observation.user_id == current_user.try(:id))) return render(:partial => params[:partial], :object => @observation, :layout => false) end @previous = @observation.user.observations.first(:conditions => ["id < ?", @observation.id], :order => "id DESC") @prev = @previous @next = @observation.user.observations.first(:conditions => ["id > ?", @observation.id], :order => "id ASC") @quality_metrics = @observation.quality_metrics.all(:include => :user) if logged_in? @user_quality_metrics = @observation.quality_metrics.select{|qm| qm.user_id == current_user.id} @project_invitations = @observation.project_invitations.limit(100).to_a @project_invitations_by_project_id = @project_invitations.index_by(&:project_id) end respond_to do |format| format.html do # always display the time in the zone in which is was observed Time.zone = @observation.user.time_zone @identifications = @observation.identifications.includes(:user, :taxon => :photos) @current_identifications = @identifications.select{|o| o.current?} @owners_identification = @current_identifications.detect do |ident| ident.user_id == @observation.user_id end if logged_in? @viewers_identification = @current_identifications.detect do |ident| ident.user_id == current_user.id end end @current_identifications_by_taxon = @current_identifications.select do |ident| ident.user_id != ident.observation.user_id end.group_by{|i| i.taxon} @current_identifications_by_taxon = @current_identifications_by_taxon.sort_by do |row| row.last.size end.reverse if logged_in? # Make sure the viewer's ID is first in its group @current_identifications_by_taxon.each_with_index do |pair, i| if pair.last.map(&:user_id).include?(current_user.id) pair.last.delete(@viewers_identification) identifications = [@viewers_identification] + pair.last @current_identifications_by_taxon[i] = [pair.first, identifications] end end @projects = Project.all( :joins => [:project_users], :limit => 1000, :conditions => ["project_users.user_id = ?", current_user] ).sort_by{|p| p.title.downcase} end @places = @observation.places @project_observations = @observation.project_observations.limit(100).to_a @project_observations_by_project_id = @project_observations.index_by(&:project_id) @comments_and_identifications = (@observation.comments.all + @identifications).sort_by{|r| r.created_at} @photos = @observation.observation_photos.sort_by do |op| op.position || @observation.observation_photos.size + op.id.to_i end.map{|op| op.photo} if @observation.observed_on @day_observations = Observation.by(@observation.user).on(@observation.observed_on). includes(:photos). paginate(:page => 1, :per_page => 14) end if logged_in? @subscription = @observation.update_subscriptions.first(:conditions => {:user_id => current_user}) end @observation_links = @observation.observation_links.sort_by{|ol| ol.href} @posts = @observation.posts.published.limit(50) if @observation.taxon unless @places.blank? @listed_taxon = ListedTaxon. where("taxon_id = ? AND place_id IN (?) AND establishment_means IS NOT NULL", @observation.taxon_id, @places). includes(:place).first @conservation_status = ConservationStatus. where(:taxon_id => @observation.taxon).where("place_id IN (?)", @places). where("iucn >= ?", Taxon::IUCN_NEAR_THREATENED). includes(:place).first end @conservation_status ||= ConservationStatus.where(:taxon_id => @observation.taxon).where("place_id IS NULL"). where("iucn >= ?", Taxon::IUCN_NEAR_THREATENED).first end @observer_provider_authorizations = @observation.user.provider_authorizations if params[:partial] return render(:partial => params[:partial], :object => @observation, :layout => false) end end format.mobile format.xml { render :xml => @observation } format.json do render :json => @observation.to_json( :viewer => current_user, :methods => [:user_login, :iconic_taxon_name], :include => { :observation_field_values => {}, :project_observations => { :include => { :project => { :only => [:id, :title, :description], :methods => [:icon_url] } } }, :observation_photos => { :include => { :photo => { :methods => [:license_code, :attribution], :except => [:original_url, :file_processing, :file_file_size, :file_content_type, :file_file_name, :mobile, :metadata, :user_id, :native_realname, :native_photo_id] } } } }) end format.atom do cache end end end # GET /observations/new # GET /observations/new.xml # An attempt at creating a simple new page for batch add def new @observation = Observation.new(:user => current_user) @observation.id_please = params[:id_please] @observation.time_zone = current_user.time_zone if params[:copy] && (copy_obs = Observation.find_by_id(params[:copy])) && copy_obs.user_id == current_user.id %w(observed_on_string time_zone place_guess geoprivacy map_scale positional_accuracy).each do |a| @observation.send("#{a}=", copy_obs.send(a)) end @observation.latitude = copy_obs.private_latitude || copy_obs.latitude @observation.longitude = copy_obs.private_longitude || copy_obs.longitude copy_obs.observation_photos.each do |op| @observation.observation_photos.build(:photo => op.photo) end copy_obs.observation_field_values.each do |ofv| @observation.observation_field_values.build(:observation_field => ofv.observation_field, :value => ofv.value) end end @taxon = Taxon.find_by_id(params[:taxon_id].to_i) unless params[:taxon_id].blank? unless params[:taxon_name].blank? @taxon ||= TaxonName.first(:conditions => [ "lower(name) = ?", params[:taxon_name].to_s.strip.gsub(/[\s_]+/, ' ').downcase] ).try(:taxon) end if !params[:project_id].blank? @project = if params[:project_id].to_i == 0 Project.includes(:project_observation_fields => :observation_field).find(params[:project_id]) else Project.includes(:project_observation_fields => :observation_field).find_by_id(params[:project_id].to_i) end if @project @project_curators = @project.project_users.where("role IN (?)", [ProjectUser::MANAGER, ProjectUser::CURATOR]) if @place = @project.place @place_geometry = PlaceGeometry.without_geom.first(:conditions => {:place_id => @place}) end @tracking_code = params[:tracking_code] if @project.tracking_code_allowed?(params[:tracking_code]) @kml_assets = @project.project_assets.select{|pa| pa.asset_file_name =~ /\.km[lz]$/} end end if params[:facebook_photo_id] begin sync_facebook_photo rescue Koala::Facebook::APIError => e raise e unless e.message =~ /OAuthException/ redirect_to ProviderAuthorization::AUTH_URLS['facebook'] return end end sync_flickr_photo if params[:flickr_photo_id] && current_user.flickr_identity sync_picasa_photo if params[:picasa_photo_id] && current_user.picasa_identity sync_local_photo if params[:local_photo_id] @welcome = params[:welcome] # this should happen AFTER photo syncing so params can override attrs # from the photo [:latitude, :longitude, :place_guess, :location_is_exact, :map_scale, :positional_accuracy, :positioning_device, :positioning_method, :observed_on_string].each do |obs_attr| next if params[obs_attr].blank? # sync_photo indicates that the user clicked sync photo, so presumably they'd # like the photo attrs to override the URL # invite links are the other case, in which URL params *should* override the # photo attrs b/c the person who made the invite link chose a taxon or something if params[:sync_photo] @observation.send("#{obs_attr}=", params[obs_attr]) if @observation.send(obs_attr).blank? else @observation.send("#{obs_attr}=", params[obs_attr]) end end if @taxon @observation.taxon = @taxon @observation.species_guess = if @taxon.common_name @taxon.common_name.name else @taxon.name end elsif !params[:taxon_name].blank? @observation.species_guess = params[:taxon_name] end @observation_fields = ObservationField. includes(:observation_field_values => :observation). where("observations.user_id = ?", current_user). limit(10). order("observation_field_values.id DESC") respond_to do |format| format.html do @observations = [@observation] @sharing_authorizations = current_user.provider_authorizations.select do |pa| pa.provider_name == "facebook" || (pa.provider_name == "twitter" && !pa.secret.blank?) end end format.json { render :json => @observation } end end # def quickadd # if params[:txt] # pieces = txt.split(/\sat\s|\son\s|\sin\s/) # @observation = Observation.new(:species_guess => pieces.first) # @observation.place_guess = pieces.last if pieces.size > 1 # if pieces.size > 2 # @observation.observed_on_string = pieces[1..-2].join(' ') # end # @observation.user = self.current_user # end # respond_to do |format| # if @observation.save # flash[:notice] = "Your observation was saved." # format.html { redirect_to :action => @user.login } # format.xml { render :xml => @observation, :status => :created, # :location => @observation } # format.js { render } # else # format.html { render :action => "new" } # format.xml { render :xml => @observation.errors, # :status => :unprocessable_entity } # format.js { render :json => @observation.errors, # :status => :unprocessable_entity } # end # end # end # GET /observations/1/edit def edit # Only the owner should be able to see this. unless current_user.id == @observation.user_id or current_user.is_admin? redirect_to observation_path(@observation) return end # Make sure user is editing the REAL coordinates if @observation.coordinates_obscured? @observation.latitude = @observation.private_latitude @observation.longitude = @observation.private_longitude end if params[:facebook_photo_id] begin sync_facebook_photo rescue Koala::Facebook::APIError => e raise e unless e.message =~ /OAuthException/ redirect_to ProviderAuthorization::AUTH_URLS['facebook'] return end end sync_flickr_photo if params[:flickr_photo_id] sync_picasa_photo if params[:picasa_photo_id] sync_local_photo if params[:local_photo_id] @observation_fields = ObservationField. includes(:observation_field_values => {:observation => :user}). where("users.id = ?", current_user). limit(10). order("observation_field_values.id DESC") if @observation.quality_metrics.detect{|qm| qm.user_id == @observation.user_id && qm.metric == QualityMetric::WILD && !qm.agree?} @observation.captive = true end if params[:partial] && EDIT_PARTIALS.include?(params[:partial]) return render(:partial => params[:partial], :object => @observation, :layout => false) end end # POST /observations # POST /observations.xml def create # Handle the case of a single obs params[:observations] = [['0', params[:observation]]] if params[:observation] if params[:observations].blank? && params[:observation].blank? respond_to do |format| format.html do flash[:error] = t(:no_observations_submitted) redirect_to new_observation_path end format.json { render :status => :unprocessable_entity, :json => "No observations submitted!" } end return end @observations = params[:observations].map do |fieldset_index, observation| next unless observation observation.delete('fieldset_index') if observation[:fieldset_index] o = Observation.new(observation) o.user = current_user o.user_agent = request.user_agent if doorkeeper_token && (a = doorkeeper_token.application) o.oauth_application = a.becomes(OauthApplication) end # Get photos Photo.descendent_classes.each do |klass| klass_key = klass.to_s.underscore.pluralize.to_sym if params[klass_key] && params[klass_key][fieldset_index] o.photos << retrieve_photos(params[klass_key][fieldset_index], :user => current_user, :photo_class => klass) end if params["#{klass_key}_to_sync"] && params["#{klass_key}_to_sync"][fieldset_index] if photo = o.photos.compact.last photo_o = photo.to_observation PHOTO_SYNC_ATTRS.each do |a| o.send("#{a}=", photo_o.send(a)) end end end end o end current_user.observations << @observations if request.format != :json && !params[:accept_terms] && params[:project_id] && !current_user.project_users.find_by_project_id(params[:project_id]) flash[:error] = t(:but_we_didnt_add_this_observation_to_the_x_project, :project => Project.find_by_id(params[:project_id]).title) else create_project_observations end update_user_account # check for errors errors = false @observations.each { |obs| errors = true unless obs.valid? } respond_to do |format| format.html do unless errors flash[:notice] = params[:success_msg] || t(:observations_saved) if params[:commit] == "Save and add another" o = @observations.first redirect_to :action => 'new', :latitude => o.coordinates_obscured? ? o.private_latitude : o.latitude, :longitude => o.coordinates_obscured? ? o.private_longitude : o.longitude, :place_guess => o.place_guess, :observed_on_string => o.observed_on_string, :location_is_exact => o.location_is_exact, :map_scale => o.map_scale, :positional_accuracy => o.positional_accuracy, :positioning_method => o.positioning_method, :positioning_device => o.positioning_device, :project_id => params[:project_id] elsif @observations.size == 1 redirect_to observation_path(@observations.first) else redirect_to :action => self.current_user.login end else if @observations.size == 1 render :action => 'new' else render :action => 'edit_batch' end end end format.json do if errors json = if @observations.size == 1 && is_iphone_app_2? {:error => @observations.map{|o| o.errors.full_messages}.flatten.uniq.compact.to_sentence} else {:errors => @observations.map{|o| o.errors.full_messages}} end render :json => json, :status => :unprocessable_entity else if @observations.size == 1 && is_iphone_app_2? render :json => @observations[0].to_json( :viewer => current_user, :methods => [:user_login, :iconic_taxon_name], :include => { :taxon => Taxon.default_json_options, :observation_field_values => {} } ) else render :json => @observations.to_json(:viewer => current_user, :methods => [:user_login, :iconic_taxon_name]) end end end end end # PUT /observations/1 # PUT /observations/1.xml def update observation_user = current_user unless params[:admin_action].nil? || !current_user.is_admin? observation_user = Observation.find(params[:id]).user end # Handle the case of a single obs if params[:observation] params[:observations] = [[params[:id], params[:observation]]] elsif params[:id] && params[:observations] params[:observations] = [[params[:id], params[:observations][0]]] end if params[:observations].blank? && params[:observation].blank? respond_to do |format| format.html do flash[:error] = t(:no_observations_submitted) redirect_to new_observation_path end format.json { render :status => :unprocessable_entity, :json => "No observations submitted!" } end return end @observations = Observation.all( :conditions => [ "id IN (?) AND user_id = ?", params[:observations].map{|k,v| k}, observation_user ] ) # Make sure there's no evil going on unique_user_ids = @observations.map(&:user_id).uniq if unique_user_ids.size > 1 || unique_user_ids.first != observation_user.id && !current_user.has_role?(:admin) flash[:error] = t(:you_dont_have_permission_to_edit_that_observation) return redirect_to(@observation || observations_path) end # Convert the params to a hash keyed by ID. Yes, it's weird hashed_params = Hash[*params[:observations].to_a.flatten] errors = false extra_msg = nil @observations.each do |observation| # Update the flickr photos # Note: this ignore photos thing is a total hack and should only be # included if you are updating observations but aren't including flickr # fields, e.g. when removing something from ID please if !params[:ignore_photos] && !is_mobile_app? # Get photos updated_photos = [] old_photo_ids = observation.photo_ids Photo.descendent_classes.each do |klass| klass_key = klass.to_s.underscore.pluralize.to_sym if params[klass_key] && params[klass_key][observation.id.to_s] updated_photos += retrieve_photos(params[klass_key][observation.id.to_s], :user => current_user, :photo_class => klass, :sync => true) end end if updated_photos.empty? observation.photos.clear else observation.photos = updated_photos end # Destroy old photos. ObservationPhotos seem to get removed by magic doomed_photo_ids = (old_photo_ids - observation.photo_ids).compact unless doomed_photo_ids.blank? Photo.delay.destroy_orphans(doomed_photo_ids) end end unless observation.update_attributes(hashed_params[observation.id.to_s]) errors = true end if !errors && params[:project_id] && !observation.project_observations.where(:project_id => params[:project_id]).exists? if @project ||= Project.find(params[:project_id]) project_observation = ProjectObservation.create(:project => @project, :observation => observation) extra_msg = if project_observation.valid? "Successfully added to #{@project.title}" else "Failed to add to #{@project.title}: #{project_observation.errors.full_messages.to_sentence}" end end end end respond_to do |format| if errors format.html do if @observations.size == 1 @observation = @observations.first render :action => 'edit' else render :action => 'edit_batch' end end format.xml { render :xml => @observations.collect(&:errors), :status => :unprocessable_entity } format.json do render :status => :unprocessable_entity, :json => { :error => @observations.map{|o| o.errors.full_messages.to_sentence}.to_sentence, :errors => @observations.collect(&:errors) } end elsif @observations.empty? msg = if params[:id] t(:that_observation_no_longer_exists) else t(:those_observations_no_longer_exist) end format.html do flash[:error] = msg redirect_back_or_default(observations_by_login_path(current_user.login)) end format.json { render :json => {:error => msg}, :status => :gone } else format.html do flash[:notice] = "#{t(:observations_was_successfully_updated)} #{extra_msg}" if @observations.size == 1 redirect_to observation_path(@observations.first) else redirect_to observations_by_login_path(observation_user.login) end end format.xml { head :ok } format.js { render :json => @observations } format.json do if @observations.size == 1 && is_iphone_app_2? render :json => @observations[0].to_json( :methods => [:user_login, :iconic_taxon_name], :include => { :taxon => Taxon.default_json_options, :observation_field_values => {}, :project_observations => { :include => { :project => { :only => [:id, :title, :description], :methods => [:icon_url] } } }, :observation_photos => { :except => [:file_processing, :file_file_size, :file_content_type, :file_file_name, :user_id, :native_realname, :mobile, :native_photo_id], :include => { :photo => {} } } }) else render :json => @observations.to_json(:methods => [:user_login, :iconic_taxon_name]) end end end end end def edit_photos @observation_photos = @observation.observation_photos if @observation_photos.blank? flash[:error] = t(:that_observation_doesnt_have_any_photos) return redirect_to edit_observation_path(@observation) end end def update_photos @observation_photos = ObservationPhoto.all(:conditions => [ "id IN (?)", params[:observation_photos].map{|k,v| k}]) @observation_photos.each do |op| next unless @observation.observation_photo_ids.include?(op.id) op.update_attributes(params[:observation_photos][op.id.to_s]) end flash[:notice] = t(:photos_updated) redirect_to edit_observation_path(@observation) end # DELETE /observations/1 # DELETE /observations/1.xml def destroy @observation.destroy respond_to do |format| format.html do flash[:notice] = t(:observation_was_deleted) redirect_to(observations_by_login_path(current_user.login)) end format.xml { head :ok } format.json { head :ok } end end ## Custom actions ############################################################ def curation @flags = Flag.paginate(:page => params[:page], :include => :user, :conditions => "resolved = false AND flaggable_type = 'Observation'") end def new_batch @step = 1 @observations = [] if params[:batch] params[:batch][:taxa].each_line do |taxon_name_str| next if taxon_name_str.strip.blank? latitude = params[:batch][:latitude] longitude = params[:batch][:longitude] if latitude.nil? && longitude.nil? && params[:batch][:place_guess] places = Ym4r::GmPlugin::Geocoding.get(params[:batch][:place_guess]) unless places.empty? latitude = places.first.latitude longitude = places.first.longitude end end @observations << Observation.new( :user => current_user, :species_guess => taxon_name_str, :taxon => Taxon.single_taxon_for_name(taxon_name_str.strip), :place_guess => params[:batch][:place_guess], :longitude => longitude, :latitude => latitude, :map_scale => params[:batch][:map_scale], :positional_accuracy => params[:batch][:positional_accuracy], :positioning_method => params[:batch][:positioning_method], :positioning_device => params[:batch][:positioning_device], :location_is_exact => params[:batch][:location_is_exact], :observed_on_string => params[:batch][:observed_on_string], :time_zone => current_user.time_zone) end @step = 2 end end def new_batch_csv if params[:upload].blank? || params[:upload] && params[:upload][:datafile].blank? flash[:error] = t(:you_must_select_a_csv_file_to_upload) return redirect_to :action => "import" end @observations = [] @hasInvalid = false csv = params[:upload][:datafile].read max_rows = 100 row_num = 0 @rows = [] begin CSV.parse(csv) do |row| next if row.blank? row = row.map do |item| if item.blank? nil else begin item.to_s.encode('UTF-8').strip rescue Encoding::UndefinedConversionError => e problem = e.message[/"(.+)" from/, 1] begin item.to_s.gsub(problem, '').encode('UTF-8').strip rescue Encoding::UndefinedConversionError => e # If there's more than one encoding issue, just bail '' end end end end obs = Observation.new( :user => current_user, :species_guess => row[0], :observed_on_string => row[1], :description => row[2], :place_guess => row[3], :time_zone => current_user.time_zone, :latitude => row[4], :longitude => row[5] ) obs.set_taxon_from_species_guess if obs.georeferenced? obs.location_is_exact = true elsif row[3] places = Ym4r::GmPlugin::Geocoding.get(row[3]) unless row[3].blank? unless places.blank? obs.latitude = places.first.latitude obs.longitude = places.first.longitude obs.location_is_exact = false end end obs.tag_list = row[6] @hasInvalid ||= !obs.valid? @observations << obs @rows << row row_num += 1 if row_num >= max_rows flash[:notice] = t(:too_many_observations_csv, :max_rows => max_rows) break end end rescue CSV::MalformedCSVError => e flash[:error] = <<-EOT Your CSV had a formatting problem. Try removing any strange characters and unclosed quotes, and if the problem persists, please <a href="mailto:#{CONFIG.help_email}">email us</a> the file and we'll figure out the problem. EOT redirect_to :action => 'import' return end end # Edit a batch of observations def edit_batch observation_ids = params[:o].is_a?(String) ? params[:o].split(',') : [] @observations = Observation.all( :conditions => [ "id in (?) AND user_id = ?", observation_ids, current_user]) @observations.map do |o| if o.coordinates_obscured? o.latitude = o.private_latitude o.longitude = o.private_longitude end o end end def delete_batch @observations = Observation.all( :conditions => [ "id in (?) AND user_id = ?", params[:o].split(','), current_user]) @observations.each do |observation| observation.destroy if observation.user == current_user end respond_to do |format| format.html do flash[:notice] = t(:observations_deleted) redirect_to observations_by_login_path(current_user.login) end format.js { render :text => "Observations deleted.", :status => 200 } end end # Import observations from external sources def import end def import_photos photos = Photo.descendent_classes.map do |klass| retrieve_photos(params[klass.to_s.underscore.pluralize.to_sym], :user => current_user, :photo_class => klass) end.flatten.compact @observations = photos.map{|p| p.to_observation} @observation_photos = ObservationPhoto.includes(:photo, :observation). where("photos.native_photo_id IN (?)", photos.map(&:native_photo_id)) @step = 2 render :template => 'observations/new_batch' rescue Timeout::Error => e flash[:error] = t(:sorry_that_photo_provider_isnt_responding) Rails.logger.error "[ERROR #{Time.now}] Timeout: #{e}" redirect_to :action => "import" end def add_from_list @order = params[:order] || "alphabetical" if @list = List.find_by_id(params[:id]) @cache_key = {:controller => "observations", :action => "add_from_list", :id => @list.id, :order => @order} unless fragment_exist?(@cache_key) @listed_taxa = @list.listed_taxa.order_by(@order).paginate(:include => {:taxon => [:photos, :taxon_names]}, :page => 1, :per_page => 1000) @listed_taxa_alphabetical = @listed_taxa.sort! {|a,b| a.taxon.default_name.name <=> b.taxon.default_name.name} @listed_taxa = @listed_taxa_alphabetical if @order == ListedTaxon::ALPHABETICAL_ORDER @taxon_ids_by_name = {} ancestor_ids = @listed_taxa.map {|lt| lt.taxon_ancestor_ids.to_s.split('/')}.flatten.uniq @orders = Taxon.all(:conditions => ["rank = 'order' AND id IN (?)", ancestor_ids], :order => "ancestry") @families = Taxon.all(:conditions => ["rank = 'family' AND id IN (?)", ancestor_ids], :order => "ancestry") end end @user_lists = current_user.lists.all(:limit => 100) respond_to do |format| format.html format.mobile { render "add_from_list.html.erb" } format.js do if fragment_exist?(@cache_key) render read_fragment(@cache_key) else render :partial => 'add_from_list.html.erb' end end end end def new_from_list @taxa = Taxon.all(:conditions => ["id in (?)", params[:taxa]], :include => :taxon_names) if @taxa.blank? flash[:error] = t(:no_taxa_selected) return redirect_to :action => :add_from_list end @observations = @taxa.map do |taxon| current_user.observations.build(:taxon => taxon, :species_guess => taxon.default_name.name, :time_zone => current_user.time_zone) end @step = 2 render :new_batch end # gets observations by user login def by_login search_params, find_options = get_search_params(params) search_params.update(:user_id => @selected_user.id) if search_params[:q].blank? get_paginated_observations(search_params, find_options) else search_observations(search_params, find_options) end respond_to do |format| format.html do @observer_provider_authorizations = @selected_user.provider_authorizations if logged_in? && @selected_user.id == current_user.id @project_users = current_user.project_users.all(:include => :project, :order => "projects.title") if @proj_obs_errors = Rails.cache.read("proj_obs_errors_#{current_user.id}") @project = Project.find_by_id(@proj_obs_errors[:project_id]) @proj_obs_errors_obs = current_user.observations.all(:conditions => ["id IN (?)", @proj_obs_errors[:errors].keys], :include => [:photos, :taxon]) Rails.cache.delete("proj_obs_errors_#{current_user.id}") end end if (partial = params[:partial]) && PARTIALS.include?(partial) return render_observations_partial(partial) end end format.mobile format.json do render_observations_to_json end format.kml do render_observations_to_kml( :snippet => "#{CONFIG.site_name} Feed for User: #{@selected_user.login}", :description => "#{CONFIG.site_name} Feed for User: #{@selected_user.login}", :name => "#{CONFIG.site_name} Feed for User: #{@selected_user.login}" ) end format.atom format.csv do render_observations_to_csv(:show_private => logged_in? && @selected_user.id == current_user.id) end format.widget do if params[:markup_only]=='true' render :js => render_to_string(:partial => "widget.html.erb", :locals => { :show_user => false, :target => params[:target], :default_image => params[:default_image], :silence => params[:silence] }) else render :js => render_to_string(:partial => "widget.js.erb") end end end end def by_login_all if @selected_user.id != current_user.id flash[:error] = t(:you_dont_have_permission_to_do_that) redirect_back_or_default(root_url) return end path_for_csv = private_page_cache_path("observations/#{@selected_user.login}.all.csv") delayed_csv(path_for_csv, @selected_user) end # shows observations in need of an ID def id_please params[:order_by] ||= "created_at" params[:order] ||= "desc" search_params, find_options = get_search_params(params) search_params = site_search_params(search_params) find_options.update( :per_page => 10, :include => [ :user, {:taxon => [:taxon_names]}, :tags, :photos, {:identifications => [{:taxon => [:taxon_names]}, :user]}, {:comments => [:user]} ] ) if search_params[:has] search_params[:has] = (search_params[:has].split(',') + ['id_please']).flatten.uniq else search_params[:has] = 'id_please' end if search_params[:q].blank? get_paginated_observations(search_params, find_options) else search_observations(search_params, find_options) end @top_identifiers = User.all(:order => "identifications_count DESC", :limit => 5) end # Renders observation components as form fields for inclusion in # observation-picking form widgets def selector search_params, find_options = get_search_params(params) @observations = Observation.latest.query(search_params).paginate(find_options) respond_to do |format| format.html { render :layout => false, :partial => 'selector'} # format.js end end def tile_points # Project tile coordinates into lat/lon using a Spherical Merc projection merc = SPHERICAL_MERCATOR tile_size = 256 x, y, zoom = params[:x].to_i, params[:y].to_i, params[:zoom].to_i swlng, swlat = merc.from_pixel_to_ll([x * tile_size, (y+1) * tile_size], zoom) nelng, nelat = merc.from_pixel_to_ll([(x+1) * tile_size, y * tile_size], zoom) @observations = Observation.in_bounding_box(swlat, swlng, nelat, nelng).all( :select => "id, species_guess, latitude, longitude, user_id, description, private_latitude, private_longitude, time_observed_at", :include => [:user, :photos], :limit => 500, :order => "id DESC") respond_to do |format| format.json do render :json => @observations.to_json( :only => [:id, :species_guess, :latitude, :longitude], :include => { :user => {:only => :login} }, :methods => [:image_url, :short_description]) end end end def widget @project = Project.find_by_id(params[:project_id].to_i) if params[:project_id] @place = Place.find_by_id(params[:place_id].to_i) if params[:place_id] @taxon = Taxon.find_by_id(params[:taxon_id].to_i) if params[:taxon_id] @order_by = params[:order_by] || "observed_on" @order = params[:order] || "desc" @limit = params[:limit] || 5 @limit = @limit.to_i if %w"logo-small.gif logo-small.png logo-small-white.png none".include?(params[:logo]) @logo = params[:logo] end @logo ||= "logo-small.gif" @layout = params[:layout] || "large" url_params = { :format => "widget", :limit => @limit, :order => @order, :order_by => @order_by, :layout => @layout, } @widget_url = if @place observations_url(url_params.merge(:place_id => @place.id)) elsif @taxon observations_url(url_params.merge(:taxon_id => @taxon.id)) elsif @project project_observations_url(@project.id, url_params) elsif logged_in? observations_by_login_feed_url(current_user.login, url_params) end respond_to do |format| format.html end end def nearby @lat = params[:latitude].to_f @lon = params[:longitude].to_f if @lat && @lon @latrads = @lat * (Math::PI / 180) @lonrads = @lon * (Math::PI / 180) @observations = Observation.search(:geo => [latrads,lonrads], :page => params[:page], :without => {:observed_on => 0}, :order => "@geodist asc, observed_on desc") rescue [] end @observations ||= Observation.latest.paginate(:page => params[:page]) request.format = :mobile respond_to do |format| format.mobile end end def add_nearby @observation = current_user.observations.build(:time_zone => current_user.time_zone) request.format = :mobile respond_to do |format| format.mobile end end def project @project = Project.find(params[:id]) rescue nil unless @project flash[:error] = t(:that_project_doesnt_exist) redirect_to request.env["HTTP_REFERER"] || projects_path return end unless request.format == :mobile search_params, find_options = get_search_params(params) search_params[:projects] = @project.id if search_params[:q].blank? get_paginated_observations(search_params, find_options) else search_observations(search_params, find_options) end end @project_observations = @project.project_observations.all( :conditions => ["observation_id IN (?)", @observations], :include => [{:curator_identification => [:taxon, :user]}]) @project_observations_by_observation_id = @project_observations.index_by(&:observation_id) @kml_assets = @project.project_assets.select{|pa| pa.asset_file_name =~ /\.km[lz]$/} respond_to do |format| format.html do if (partial = params[:partial]) && PARTIALS.include?(partial) return render_observations_partial(partial) end end format.json do render_observations_to_json end format.atom do @updated_at = Observation.first(:order => 'updated_at DESC').updated_at render :action => "index" end format.csv do render :text => ProjectObservation.to_csv(@project_observations, :user => current_user) end format.kml do render_observations_to_kml( :snippet => "#{@project.title.html_safe} Observations", :description => "Observations feed for the #{CONFIG.site_name} project '#{@project.title.html_safe}'", :name => "#{@project.title.html_safe} Observations" ) end format.widget do if params[:markup_only] == 'true' render :js => render_to_string(:partial => "widget.html.erb", :locals => { :show_user => true, :target => params[:target], :default_image => params[:default_image], :silence => params[:silence] }) else render :js => render_to_string(:partial => "widget.js.erb", :locals => { :show_user => true }) end end format.mobile end end def project_all @project = Project.find(params[:id]) rescue nil unless @project flash[:error] = t(:that_project_doesnt_exist) redirect_to request.env["HTTP_REFERER"] || projects_path return end unless @project.curated_by?(current_user) flash[:error] = t(:only_project_curators_can_do_that) redirect_to request.env["HTTP_REFERER"] || @project return end path_for_csv = private_page_cache_path("observations/project/#{@project.slug}.all.csv") delayed_csv(path_for_csv, @project) end def identotron @observation = Observation.find_by_id((params[:observation] || params[:observation_id]).to_i) @taxon = Taxon.find_by_id(params[:taxon].to_i) @q = params[:q] unless params[:q].blank? if @observation @places = @observation.places.try(:reverse) if @observation.taxon && @observation.taxon.species_or_lower? @taxon ||= @observation.taxon.genus else @taxon ||= @observation.taxon end if @taxon && @places @place = @places.reverse.detect {|p| p.taxa.self_and_descendants_of(@taxon).exists?} end end @place ||= (Place.find(params[:place_id]) rescue nil) || @places.try(:last) @default_taxa = @taxon ? @taxon.ancestors : Taxon::ICONIC_TAXA @taxon ||= Taxon::LIFE @default_taxa = [@default_taxa, @taxon].flatten.compact end def fields @project = Project.find(params[:project_id]) rescue nil @observation_fields = if @project @project.observation_fields elsif params[:observation_fields] ObservationField.where("id IN (?)", params[:observation_fields]) else @observation_fields = ObservationField. includes(:observation_field_values => {:observation => :user}). where("users.id = ?", current_user). limit(10). order("observation_field_values.id DESC") end render :layout => false end def photo @observations = [] unless params[:files].blank? params[:files].each_with_index do |file, i| lp = LocalPhoto.new(:file => file, :user => current_user) o = lp.to_observation if params[:observations] && obs_params = params[:observations][i] obs_params.each do |k,v| o.send("#{k}=", v) unless v.blank? end end o.save @observations << o end end respond_to do |format| format.json do render_observations_to_json(:include => { :taxon => { :only => [:name, :id, :rank, :rank_level, :is_iconic], :methods => [:default_name, :image_url, :iconic_taxon_name, :conservation_status_name], :include => { :iconic_taxon => { :only => [:id, :name] }, :taxon_names => { :only => [:id, :name, :lexicon] } } } }) end end end def stats @headless = @footless = true search_params, find_options = get_search_params(params) @stats_adequately_scoped = stats_adequately_scoped? end def taxon_stats search_params, find_options = get_search_params(params, :skip_order => true, :skip_pagination => true) scope = Observation.query(search_params).scoped scope = scope.where("1 = 2") unless stats_adequately_scoped? taxon_counts_scope = scope. joins(:taxon). where("taxa.rank_level <= ?", Taxon::SPECIES_LEVEL) taxon_counts_sql = <<-SQL SELECT o.taxon_id, count(*) AS count_all FROM (#{taxon_counts_scope.to_sql}) AS o GROUP BY o.taxon_id ORDER BY count_all desc LIMIT 5 SQL @taxon_counts = ActiveRecord::Base.connection.execute(taxon_counts_sql) @taxa = Taxon.where("id in (?)", @taxon_counts.map{|r| r['taxon_id']}).includes({:taxon_photos => :photo}, :taxon_names) @taxa_by_taxon_id = @taxa.index_by(&:id) rank_counts_sql = <<-SQL SELECT o.rank_name, count(*) AS count_all FROM (#{scope.joins(:taxon).select("DISTINCT ON (taxa.id) taxa.rank AS rank_name").to_sql}) AS o GROUP BY o.rank_name SQL @rank_counts = ActiveRecord::Base.connection.execute(rank_counts_sql) respond_to do |format| format.json do render :json => { :total => @rank_counts.map{|r| r['count_all'].to_i}.sum, :taxon_counts => @taxon_counts.map{|row| { :id => row['taxon_id'], :count => row['count_all'], :taxon => @taxa_by_taxon_id[row['taxon_id'].to_i].as_json( :methods => [:default_name, :image_url, :iconic_taxon_name, :conservation_status_name], :only => [:id, :name, :rank, :rank_level] ) } }, :rank_counts => @rank_counts.inject({}) {|memo,row| memo[row['rank_name']] = row['count_all'] memo } } end end end def user_stats search_params, find_options = get_search_params(params, :skip_order => true, :skip_pagination => true) scope = Observation.query(search_params).scoped scope = scope.where("1 = 2") unless stats_adequately_scoped? user_counts_sql = <<-SQL SELECT o.user_id, count(*) AS count_all FROM (#{scope.to_sql}) AS o GROUP BY o.user_id ORDER BY count_all desc LIMIT 5 SQL @user_counts = ActiveRecord::Base.connection.execute(user_counts_sql) user_taxon_counts_sql = <<-SQL SELECT o.user_id, count(*) AS count_all FROM (#{scope.select("DISTINCT ON (observations.taxon_id) observations.user_id").joins(:taxon).where("taxa.rank_level <= ?", Taxon::SPECIES_LEVEL).to_sql}) AS o GROUP BY o.user_id ORDER BY count_all desc LIMIT 5 SQL @user_taxon_counts = ActiveRecord::Base.connection.execute(user_taxon_counts_sql) @users = User.where("id in (?)", [@user_counts.map{|r| r['user_id']}, @user_taxon_counts.map{|r| r['user_id']}].flatten.uniq) @users_by_id = @users.index_by(&:id) respond_to do |format| format.json do render :json => { :total => scope.select("DISTINCT observations.user_id").count, :most_observations => @user_counts.map{|row| { :id => row['user_id'], :count => row['count_all'], :user => @users_by_id[row['user_id'].to_i].as_json( :only => [:id, :name, :login], :methods => [:user_icon_url] ) } }, :most_species => @user_taxon_counts.map{|row| { :id => row['user_id'], :count => row['count_all'], :user => @users_by_id[row['user_id'].to_i].as_json( :only => [:id, :name, :login], :methods => [:user_icon_url] ) } } } end end end ## Protected / private actions ############################################### private def stats_adequately_scoped? if params[:d1] && params[:d2] d1 = (Date.parse(params[:d1]) rescue Date.today) d2 = (Date.parse(params[:d2]) rescue Date.today) return false if d2 - d1 > 366 end !(params[:d1].blank? && params[:projects].blank? && params[:place_id].blank? && params[:user_id].blank?) end def retrieve_photos(photo_list = nil, options = {}) return [] if photo_list.blank? photo_list = photo_list.values if photo_list.is_a?(Hash) photo_list = [photo_list] unless photo_list.is_a?(Array) photo_class = options[:photo_class] || Photo # simple algorithm, # 1. create an array to be passed back to the observation obj # 2. check to see if that photo's data has already been stored # 3. if yes # retrieve Photo obj and put in array # if no # create Photo obj and put in array # 4. return array photos = [] native_photo_ids = photo_list.map{|p| p.to_s}.uniq existing = photo_class.includes(:user).where("native_photo_id IN (?)", native_photo_ids).index_by{|p| p.native_photo_id} photo_list.uniq.each do |photo_id| if (photo = existing[photo_id]) || options[:sync] api_response = photo_class.get_api_response(photo_id, :user => current_user) end # Sync existing if called for if photo photo.user ||= options[:user] if options[:sync] # sync the photo URLs b/c they change when photos become private photo.api_response = api_response # set to make sure user validation works photo.sync photo.save if photo.changed? end end # Create a new one if one doesn't already exist unless photo photo = if photo_class == LocalPhoto LocalPhoto.new(:file => photo_id, :user => current_user) unless photo_id.blank? else api_response ||= photo_class.get_api_response(photo_id, :user => current_user) if api_response photo_class.new_from_api_response(api_response, :user => current_user) end end end if photo.blank? Rails.logger.error "[ERROR #{Time.now}] Failed to get photo for photo_class: #{photo_class}, photo_id: #{photo_id}" elsif photo.valid? photos << photo else Rails.logger.error "[ERROR #{Time.now}] #{current_user} tried to save an observation with an invalid photo (#{photo}): #{photo.errors.full_messages.to_sentence}" end end photos end # Processes params for observation requests. Designed for use with # will_paginate and standard observations query API def get_search_params(params, options = {}) # The original params is important for things like pagination, so we # leave it untouched. search_params = params.clone @swlat = search_params[:swlat] unless search_params[:swlat].blank? @swlng = search_params[:swlng] unless search_params[:swlng].blank? @nelat = search_params[:nelat] unless search_params[:nelat].blank? @nelng = search_params[:nelng] unless search_params[:nelng].blank? unless search_params[:place_id].blank? @place = begin Place.find(search_params[:place_id]) rescue ActiveRecord::RecordNotFound nil end end @q = search_params[:q].to_s unless search_params[:q].blank? if Observation::SPHINX_FIELD_NAMES.include?(search_params[:search_on]) @search_on = search_params[:search_on] end find_options = { :include => [:user, {:taxon => [:taxon_names]}, :taggings, {:observation_photos => :photo}], :page => search_params[:page] } unless options[:skip_pagination] find_options[:page] = 1 if find_options[:page].to_i == 0 find_options[:per_page] = @prefs["per_page"] if @prefs if !search_params[:per_page].blank? find_options.update(:per_page => search_params[:per_page]) elsif !search_params[:limit].blank? find_options.update(:per_page => search_params[:limit]) end if find_options[:per_page] && find_options[:per_page].to_i > 200 find_options[:per_page] = 200 end find_options[:per_page] = 30 if find_options[:per_page].to_i == 0 end if find_options[:limit] && find_options[:limit].to_i > 200 find_options[:limit] = 200 end unless request.format && request.format.html? find_options[:include] = [{:taxon => :taxon_names}, {:observation_photos => :photo}, :user] end # iconic_taxa if search_params[:iconic_taxa] # split a string of names if search_params[:iconic_taxa].is_a? String search_params[:iconic_taxa] = search_params[:iconic_taxa].split(',') end # resolve taxa entered by name search_params[:iconic_taxa] = search_params[:iconic_taxa].map do |it| it = it.last if it.is_a?(Array) if it.to_i == 0 Taxon::ICONIC_TAXA_BY_NAME[it] else Taxon::ICONIC_TAXA_BY_ID[it] end end @iconic_taxa = search_params[:iconic_taxa] end # taxon unless search_params[:taxon_id].blank? @observations_taxon_id = search_params[:taxon_id] @observations_taxon = Taxon.find_by_id(@observations_taxon_id.to_i) end unless search_params[:taxon_name].blank? @observations_taxon_name = search_params[:taxon_name].to_s taxon_name_conditions = ["taxon_names.name = ?", @observations_taxon_name] includes = nil unless @iconic_taxa.blank? taxon_name_conditions[0] += " AND taxa.iconic_taxon_id IN (?)" taxon_name_conditions << @iconic_taxa includes = :taxon end begin @observations_taxon = TaxonName.first(:include => includes, :conditions => taxon_name_conditions).try(:taxon) rescue ActiveRecord::StatementInvalid => e raise e unless e.message =~ /invalid byte sequence/ taxon_name_conditions[1] = @observations_taxon_name.encode('UTF-8') @observations_taxon = TaxonName.first(:include => includes, :conditions => taxon_name_conditions).try(:taxon) end end search_params[:taxon] = @observations_taxon if search_params[:has] if search_params[:has].is_a?(String) search_params[:has] = search_params[:has].split(',') end @id_please = true if search_params[:has].include?('id_please') @with_photos = true if search_params[:has].include?('photos') end @quality_grade = search_params[:quality_grade] @identifications = search_params[:identifications] @out_of_range = search_params[:out_of_range] @license = search_params[:license] @photo_license = search_params[:photo_license] unless options[:skip_order] search_params[:order_by] = "created_at" if search_params[:order_by] == "observations.id" if ORDER_BY_FIELDS.include?(search_params[:order_by].to_s) @order_by = search_params[:order_by] @order = if %w(asc desc).include?(search_params[:order].to_s.downcase) search_params[:order] else 'desc' end else @order_by = "observations.id" @order = "desc" end search_params[:order_by] = "#{@order_by} #{@order}" end # date date_pieces = [search_params[:year], search_params[:month], search_params[:day]] unless date_pieces.map{|d| d.blank? ? nil : d}.compact.blank? search_params[:on] = date_pieces.join('-') end if search_params[:on].to_s =~ /^\d{4}/ @observed_on = search_params[:on] @observed_on_year, @observed_on_month, @observed_on_day = @observed_on.split('-').map{|d| d.to_i} end @observed_on_year ||= search_params[:year].to_i unless search_params[:year].blank? @observed_on_month ||= search_params[:month].to_i unless search_params[:month].blank? @observed_on_day ||= search_params[:day].to_i unless search_params[:day].blank? # observation fields ofv_params = search_params.select{|k,v| k =~ /^field\:/} unless ofv_params.blank? @ofv_params = {} ofv_params.each do |k,v| @ofv_params[k] = { :normalized_name => ObservationField.normalize_name(k), :value => v } end observation_fields = ObservationField.where("lower(name) IN (?)", @ofv_params.map{|k,v| v[:normalized_name]}) @ofv_params.each do |k,v| v[:observation_field] = observation_fields.detect do |of| v[:normalized_name] == ObservationField.normalize_name(of.name) end end @ofv_params.delete_if{|k,v| v[:observation_field].blank?} search_params[:ofv_params] = @ofv_params end @site = params[:site] unless params[:site].blank? @user = User.find_by_id(params[:user_id]) unless params[:user_id].blank? @projects = Project.where("id IN (?)", params[:projects]) unless params[:projects].blank? @filters_open = !@q.nil? || !@observations_taxon_id.blank? || !@observations_taxon_name.blank? || !@iconic_taxa.blank? || @id_please == true || !@with_photos.blank? || !@identifications.blank? || !@quality_grade.blank? || !@out_of_range.blank? || !@observed_on.blank? || !@place.blank? || !@ofv_params.blank? @filters_open = search_params[:filters_open] == 'true' if search_params.has_key?(:filters_open) [search_params, find_options] end # Either make a plain db query and return a WillPaginate collection or make # a Sphinx call if there were query terms specified. def get_paginated_observations(search_params, find_options) if @q @observations = if @search_on find_options[:conditions] = update_conditions( find_options[:conditions], @search_on.to_sym => @q ) Observation.query(search_params).search(find_options).compact else Observation.query(search_params).search(@q, find_options).compact end end if @observations.blank? @observations = Observation.query(search_params).includes(:observation_photos => :photo).paginate(find_options) end @observations rescue ThinkingSphinx::ConnectionError Rails.logger.error "[ERROR #{Time.now}] ThinkingSphinx::ConnectionError, hitting the db" find_options.delete(:class) find_options.delete(:classes) find_options.delete(:raise_on_stale) @observations = if @q Observation.query(search_params).all( :conditions => ["species_guess LIKE ?", "%#{@q}%"]).paginate(find_options) else Observation.query(search_params).paginate(find_options) end end def search_observations(search_params, find_options) sphinx_options = find_options.dup sphinx_options[:with] = {} if sphinx_options[:page] && sphinx_options[:page].to_i > 50 if request.format && request.format.html? flash.now[:notice] = t(:heads_up_observation_search_can_only_load) end sphinx_options[:page] = 50 find_options[:page] = 50 end if search_params[:has] # id please if search_params[:has].include?('id_please') sphinx_options[:with][:has_id_please] = true end # has photos if search_params[:has].include?('photos') sphinx_options[:with][:has_photos] = true end # geo if search_params[:has].include?('geo') sphinx_options[:with][:has_geo] = true end end # Bounding box or near point if (!search_params[:swlat].blank? && !search_params[:swlng].blank? && !search_params[:nelat].blank? && !search_params[:nelng].blank?) swlatrads = search_params[:swlat].to_f * (Math::PI / 180) swlngrads = search_params[:swlng].to_f * (Math::PI / 180) nelatrads = search_params[:nelat].to_f * (Math::PI / 180) nelngrads = search_params[:nelng].to_f * (Math::PI / 180) # The box straddles the 180th meridian... # This is a very stupid solution that just chooses the biggest of the # two sides straddling the meridian and queries in that. Sphinx doesn't # seem to support multiple queries on the same attribute, so we can't do # the OR clause we do in the equivalent named scope. Grr. -kueda # 2009-04-10 if swlngrads > 0 && nelngrads < 0 lngrange = swlngrads.abs > nelngrads ? swlngrads..Math::PI : -Math::PI..nelngrads sphinx_options[:with][:longitude] = lngrange # sphinx_options[:with][:longitude] = swlngrads..Math::PI # sphinx_options[:with] = {:longitude => -Math::PI..nelngrads} else sphinx_options[:with][:longitude] = swlngrads..nelngrads end sphinx_options[:with][:latitude] = swlatrads..nelatrads elsif search_params[:lat] && search_params[:lng] latrads = search_params[:lat].to_f * (Math::PI / 180) lngrads = search_params[:lng].to_f * (Math::PI / 180) sphinx_options[:geo] = [latrads, lngrads] sphinx_options[:order] = "@geodist asc" end # identifications case search_params[:identifications] when 'most_agree' sphinx_options[:with][:identifications_most_agree] = true when 'some_agree' sphinx_options[:with][:identifications_some_agree] = true when 'most_disagree' sphinx_options[:with][:identifications_most_disagree] = true end # Taxon ID unless search_params[:taxon_id].blank? sphinx_options[:with][:taxon_id] = search_params[:taxon_id] end # Iconic taxa unless search_params[:iconic_taxa].blank? sphinx_options[:with][:iconic_taxon_id] = \ search_params[:iconic_taxa].map do |iconic_taxon| iconic_taxon.nil? ? nil : iconic_taxon.id end end # User ID unless search_params[:user_id].blank? sphinx_options[:with][:user_id] = search_params[:user_id] end # User login unless search_params[:user].blank? sphinx_options[:with][:user] = search_params[:user] end # Ordering unless search_params[:order_by].blank? # observations.id is a more efficient sql clause, but it's not the name of a field in sphinx search_params[:order_by].gsub!(/observations\.id/, 'created_at') if !sphinx_options[:order].blank? sphinx_options[:order] += ", #{search_params[:order_by]}" sphinx_options[:sort_mode] = :extended elsif search_params[:order_by] =~ /\sdesc|asc/i sphinx_options[:order] = search_params[:order_by].split.first.to_sym sphinx_options[:sort_mode] = search_params[:order_by].split.last.downcase.to_sym else sphinx_options[:order] = search_params[:order_by].to_sym end end unless search_params[:projects].blank? sphinx_options[:with][:projects] = if search_params[:projects].is_a?(String) && search_params[:projects].index(',') search_params[:projects].split(',') else [search_params[:projects]].flatten end end unless search_params[:ofv_params].blank? ofs = search_params[:ofv_params].map do |k,v| v[:observation_field].blank? ? nil : v[:observation_field].id end.compact sphinx_options[:with][:observation_fields] = ofs unless ofs.blank? end # Sanitize query q = sanitize_sphinx_query(@q) # Field-specific searches obs_ids = if @search_on sphinx_options[:conditions] ||= {} # not sure why sphinx chokes on slashes when searching on attributes... sphinx_options[:conditions][@search_on.to_sym] = q.gsub(/\//, '') Observation.search_for_ids(find_options.merge(sphinx_options)) else Observation.search_for_ids(q, find_options.merge(sphinx_options)) end @observations = Observation.where("observations.id in (?)", obs_ids). order_by(search_params[:order_by]). includes(find_options[:include]).scoped # lame hacks unless search_params[:ofv_params].blank? search_params[:ofv_params].each do |k,v| next unless of = v[:observation_field] next if v[:value].blank? v[:observation_field].blank? ? nil : v[:observation_field].id @observations = @observations.has_observation_field(of.id, v[:value]) end end if CONFIG.site_only_observations && params[:site].blank? @observations = @observations.where("observations.uri LIKE ?", "#{root_url}%") end @observations = WillPaginate::Collection.create(obs_ids.current_page, obs_ids.per_page, obs_ids.total_entries) do |pager| pager.replace(@observations.to_a) end begin @observations.total_entries rescue ThinkingSphinx::SphinxError, Riddle::OutOfBoundsError => e Rails.logger.error "[ERROR #{Time.now}] Failed sphinx search: #{e}" @observations = WillPaginate::Collection.new(1,30, 0) end @observations rescue ThinkingSphinx::ConnectionError Rails.logger.error "[ERROR #{Time.now}] Failed to connect to sphinx, falling back to db" get_paginated_observations(search_params, find_options) end # Refresh lists affected by taxon changes in a batch of new/edited # observations. Note that if you don't set @skip_refresh_lists on the records # in @observations before this is called, this won't do anything def refresh_lists_for_batch return true if @observations.blank? taxa = @observations.select(&:skip_refresh_lists).map(&:taxon).uniq.compact return true if taxa.blank? List.delay.refresh_for_user(current_user, :taxa => taxa.map(&:id)) true end # Tries to create a new observation from the specified Facebook photo ID and # update the existing @observation with the new properties, without saving def sync_facebook_photo fb = current_user.facebook_api if fb fbp_json = FacebookPhoto.get_api_response(params[:facebook_photo_id], :user => current_user) @facebook_photo = FacebookPhoto.new_from_api_response(fbp_json) else @facebook_photo = nil end if @facebook_photo && @facebook_photo.owned_by?(current_user) @facebook_observation = @facebook_photo.to_observation sync_attrs = [:description] # facebook strips exif metadata so we can't get geo or observed_on :-/ #, :species_guess, :taxon_id, :observed_on, :observed_on_string, :latitude, :longitude, :place_guess] unless params[:facebook_sync_attrs].blank? sync_attrs = sync_attrs & params[:facebook_sync_attrs] end sync_attrs.each do |sync_attr| # merge facebook_observation with existing observation @observation[sync_attr] ||= @facebook_observation[sync_attr] end unless @observation.observation_photos.detect {|op| op.photo.native_photo_id == @facebook_photo.native_photo_id} @observation.observation_photos.build(:photo => @facebook_photo) end unless @observation.new_record? flash.now[:notice] = t(:preview_of_synced_observation, :url => url_for) end else flash.now[:error] = t(:sorry_we_didnt_find_that_photo) end end # Tries to create a new observation from the specified Flickr photo ID and # update the existing @observation with the new properties, without saving def sync_flickr_photo flickr = get_flickraw begin fp = flickr.photos.getInfo(:photo_id => params[:flickr_photo_id]) @flickr_photo = FlickrPhoto.new_from_flickraw(fp, :user => current_user) rescue FlickRaw::FailedResponse => e Rails.logger.debug "[DEBUG] FlickRaw failed to find photo " + "#{params[:flickr_photo_id]}: #{e}\n#{e.backtrace.join("\n")}" @flickr_photo = nil rescue Timeout::Error => e flash.now[:error] = t(:sorry_flickr_isnt_responding_at_the_moment) Rails.logger.error "[ERROR #{Time.now}] Timeout: #{e}" Airbrake.notify(e, :request => request, :session => session) return end if fp && @flickr_photo && @flickr_photo.valid? @flickr_observation = @flickr_photo.to_observation sync_attrs = %w(description species_guess taxon_id observed_on observed_on_string latitude longitude place_guess map_scale) unless params[:flickr_sync_attrs].blank? sync_attrs = sync_attrs & params[:flickr_sync_attrs] end sync_attrs.each do |sync_attr| # merge flickr_observation with existing observation val = @flickr_observation.send(sync_attr) @observation.send("#{sync_attr}=", val) unless val.blank? end # Note: the following is sort of a hacky alternative to build(). We # need to append a new photo object without saving it, but build() won't # work here b/c Photo and its descedents use STI, and type is a # protected attributes that can't be mass-assigned. unless @observation.observation_photos.detect {|op| op.photo.native_photo_id == @flickr_photo.native_photo_id} @observation.observation_photos.build(:photo => @flickr_photo) end unless @observation.new_record? flash.now[:notice] = t(:preview_of_synced_observation, :url => url_for) end if (@existing_photo = Photo.find_by_native_photo_id(@flickr_photo.native_photo_id)) && (@existing_photo_observation = @existing_photo.observations.first) && @existing_photo_observation.id != @observation.id msg = t(:heads_up_this_photo_is_already_associated_with, :url => url_for(@existing_photo_observation)) flash.now[:notice] = flash.now[:notice].blank? ? msg : "#{flash.now[:notice]}<br/>#{msg}" end else flash.now[:error] = t(:sorry_we_didnt_find_that_photo) end end def sync_picasa_photo begin api_response = PicasaPhoto.get_api_response(params[:picasa_photo_id], :user => current_user) rescue Timeout::Error => e flash.now[:error] = t(:sorry_picasa_isnt_responding_at_the_moment) Rails.logger.error "[ERROR #{Time.now}] Timeout: #{e}" Airbrake.notify(e, :request => request, :session => session) return end unless api_response Rails.logger.debug "[DEBUG] Failed to find Picasa photo for #{params[:picasa_photo_id]}" return end @picasa_photo = PicasaPhoto.new_from_api_response(api_response, :user => current_user) if @picasa_photo && @picasa_photo.valid? @picasa_observation = @picasa_photo.to_observation sync_attrs = PHOTO_SYNC_ATTRS unless params[:picasa_sync_attrs].blank? sync_attrs = sync_attrs & params[:picasa_sync_attrs] end sync_attrs.each do |sync_attr| @observation.send("#{sync_attr}=", @picasa_observation.send(sync_attr)) end unless @observation.observation_photos.detect {|op| op.photo.native_photo_id == @picasa_photo.native_photo_id} @observation.observation_photos.build(:photo => @picasa_photo) end flash.now[:notice] = t(:preview_of_synced_observation, :url => url_for) else flash.now[:error] = t(:sorry_we_didnt_find_that_photo) end end def sync_local_photo unless @local_photo = Photo.find_by_id(params[:local_photo_id]) flash.now[:error] = t(:that_photo_doesnt_exist) return end if @local_photo.metadata.blank? flash.now[:error] = t(:sorry_we_dont_have_any_metadata_for_that_photo) return end o = @local_photo.to_observation PHOTO_SYNC_ATTRS.each do |sync_attr| @observation.send("#{sync_attr}=", o.send(sync_attr)) end unless @observation.observation_photos.detect {|op| op.photo_id == @local_photo.id} @observation.observation_photos.build(:photo => @local_photo) end unless @observation.new_record? flash.now[:notice] = t(:preview_of_synced_observation, :url => url_for) end if @existing_photo_observation = @local_photo.observations.where("observations.id != ?", @observation).first msg = t(:heads_up_this_photo_is_already_associated_with, :url => url_for(@existing_photo_observation)) flash.now[:notice] = flash.now[:notice].blank? ? msg : "#{flash.now[:notice]}<br/>#{msg}" end end def load_photo_identities unless logged_in? @photo_identity_urls = [] @photo_identities = [] return true end @photo_identities = Photo.descendent_classes.map do |klass| assoc_name = klass.to_s.underscore.split('_').first + "_identity" current_user.send(assoc_name) if current_user.respond_to?(assoc_name) end.compact reference_photo = @observation.try(:observation_photos).try(:first).try(:photo) reference_photo ||= @observations.try(:first).try(:observation_photos).try(:first).try(:photo) reference_photo ||= current_user.photos.order("id ASC").last if reference_photo assoc_name = reference_photo.class.to_s.underscore.split('_').first + "_identity" @default_photo_identity = current_user.send(assoc_name) if current_user.respond_to?(assoc_name) end if params[:facebook_photo_id] if @default_photo_identity = @photo_identities.detect{|pi| pi.to_s =~ /facebook/i} @default_photo_source = 'facebook' end elsif params[:flickr_photo_id] if @default_photo_identity = @photo_identities.detect{|pi| pi.to_s =~ /flickr/i} @default_photo_source = 'flickr' end end @default_photo_identity ||= @photo_identities.first @default_photo_source ||= if @default_photo_identity && @default_photo_identity.class.name =~ /Identity/ @default_photo_identity.class.name.underscore.humanize.downcase.split.first elsif @default_photo_identity "facebook" end @default_photo_identity_url = nil @photo_identity_urls = @photo_identities.map do |identity| provider_name = if identity.is_a?(ProviderAuthorization) identity.provider_name else identity.class.to_s.underscore.split('_').first # e.g. FlickrIdentity=>'flickr' end url = "/#{provider_name.downcase}/photo_fields?context=user" @default_photo_identity_url = url if identity == @default_photo_identity "{title: '#{provider_name.capitalize}', url: '#{url}'}" end @photo_sources = @photo_identities.inject({}) do |memo, ident| if ident.respond_to?(:source_options) memo[ident.class.name.underscore.humanize.downcase.split.first] = ident.source_options else memo[:facebook] = { :title => 'Facebook', :url => '/facebook/photo_fields', :contexts => [ ["Your photos", 'user'] ] } end memo end end def load_observation render_404 unless @observation = Observation.find_by_id(params[:id] || params[:observation_id], :include => [ :photos, {:taxon => [:taxon_names]}, :identifications ] ) end def require_owner unless logged_in? && current_user.id == @observation.user_id msg = t(:you_dont_have_permission_to_do_that) respond_to do |format| format.html do flash[:error] = msg return redirect_to @observation end format.json do return render :json => {:error => msg} end end end end def render_observations_to_json(options = {}) if (partial = params[:partial]) && PARTIALS.include?(partial) data = @observations.map do |observation| item = { :instance => observation, :extra => { :taxon => observation.taxon, :iconic_taxon => observation.iconic_taxon, :user => {:login => observation.user.login} } } item[:html] = view_context.render_in_format(:html, :partial => partial, :object => observation) item end render :json => data else opts = options opts[:methods] ||= [] opts[:methods] += [:short_description, :user_login, :iconic_taxon_name, :tag_list] opts[:methods].uniq! opts[:include] ||= {} if @ofv_params opts[:include][:observation_field_values] ||= { :except => [:observation_field_id], :include => { :observation_field => { :only => [:id, :datatype, :name] } } } end opts[:include][:taxon] ||= { :only => [:id, :name, :rank, :ancestry] } opts[:include][:iconic_taxon] ||= {:only => [:id, :name, :rank, :rank_level, :ancestry]} opts[:include][:user] ||= {:only => :login} opts[:include][:photos] ||= { :methods => [:license_code, :attribution], :except => [:original_url, :file_processing, :file_file_size, :file_content_type, :file_file_name, :mobile, :metadata] } pagination_headers_for(@observations) if @observations.respond_to?(:scoped) @observations = @observations.includes({:observation_photos => :photo}, :photos, :iconic_taxon) end render :json => @observations.to_json(opts) end end def render_observations_to_csv(options = {}) first = %w(scientific_name datetime description place_guess latitude longitude tag_list common_name url image_url user_login) only = (first + Observation::CSV_COLUMNS).uniq except = %w(map_scale timeframe iconic_taxon_id delta geom user_agent cached_tag_list) unless options[:show_private] == true except += %w(private_latitude private_longitude private_positional_accuracy) end only = only - except unless @ofv_params.blank? only += @ofv_params.map{|k,v| "field:#{v[:normalized_name]}"} if @observations.respond_to?(:scoped) @observations = @observations.includes(:observation_field_values => :observation_field) end end @observations = @observations.includes(:tags) if @observations.respond_to?(:scoped) render :text => @observations.to_csv(:only => only.map{|c| c.to_sym}) end def render_observations_to_kml(options = {}) @net_hash = options if params[:kml_type] == "network_link" @net_hash = { :id => "AllObs", :link_id =>"AllObs", :snippet => "#{CONFIG.site_name} Feed for Everyone", :description => "#{CONFIG.site_name} Feed for Everyone", :name => "#{CONFIG.site_name} Feed for Everyone", :href => "#{root_url}#{request.fullpath}".gsub(/kml_type=network_link/, '') } render :layout => false, :action => 'network_link' return end render :layout => false, :action => "index" end # create project observations if a project was specified and project allows # auto-joining def create_project_observations return unless params[:project_id] @project = Project.find_by_id(params[:project_id]) @project ||= Project.find(params[:project_id]) rescue nil return unless @project @project_user = current_user.project_users.find_or_create_by_project_id(@project.id) return unless @project_user && @project_user.valid? tracking_code = params[:tracking_code] if @project.tracking_code_allowed?(params[:tracking_code]) errors = [] @observations.each do |observation| next if observation.new_record? po = @project.project_observations.build(:observation => observation, :tracking_code => tracking_code) unless po.save errors = (errors + po.errors.full_messages).uniq end end if !errors.blank? if request.format.html? flash[:error] = t(:your_observations_couldnt_be_added_to_that_project, :errors => errors.to_sentence) else Rails.logger.error "[ERROR #{Time.now}] Failed to add #{@observations.size} obs to #{@project}: #{errors.to_sentence}" end end end def update_user_account current_user.update_attributes(params[:user]) unless params[:user].blank? end def render_observations_partial(partial) if @observations.empty? render(:text => '') else render(:partial => partial, :collection => @observations, :layout => false) end end def load_prefs @prefs = current_preferences if request.format && request.format.html? @view = params[:view] || current_user.try(:preferred_observations_view) || 'map' end end def site_search_params(search_params = {}) if CONFIG.site_only_observations && params[:site].blank? search_params[:site] ||= FakeView.root_url @site ||= search_params[:site] end if (site_bounds = CONFIG.bounds) && params[:swlat].nil? search_params[:nelat] ||= site_bounds['nelat'] search_params[:nelng] ||= site_bounds['nelng'] search_params[:swlat] ||= site_bounds['swlat'] search_params[:swlng] ||= site_bounds['swlng'] @nelat ||= site_bounds['nelat'] @nelng ||= site_bounds['nelng'] @swlat ||= site_bounds['swlat'] @swlng ||= site_bounds['swlng'] end search_params end def delayed_csv(path_for_csv, parent, options = {}) if parent.observations.count < 50 Observation.generate_csv_for(parent, :path => path_for_csv) render :file => path_for_csv else cache_key = Observation.generate_csv_for_cache_key(parent) job_id = Rails.cache.read(cache_key) job = Delayed::Job.find_by_id(job_id) if job # Still working elsif File.exists? path_for_csv render :file => path_for_csv return else # no job id, no job, let's get this party started Rails.cache.delete(cache_key) job = Observation.delay.generate_csv_for(parent, :path => path_for_csv, :user => current_user) Rails.cache.write(cache_key, job.id, :expires_in => 1.hour) end prevent_caching render :status => :accepted, :text => "This file takes a little while to generate. It should be ready shortly at #{request.url}" end end end Possible bugfix. #encoding: utf-8 class ObservationsController < ApplicationController caches_page :tile_points WIDGET_CACHE_EXPIRATION = 15.minutes caches_action :index, :by_login, :project, :expires_in => WIDGET_CACHE_EXPIRATION, :cache_path => Proc.new {|c| c.params.merge(:locale => I18n.locale)}, :if => Proc.new {|c| c.session.blank? && # make sure they're logged out c.request.format && # make sure format corresponds to a known mime type (c.request.format.geojson? || c.request.format.widget? || c.request.format.kml?) && c.request.url.size < 250} caches_action :of, :expires_in => 1.day, :cache_path => Proc.new {|c| c.params.merge(:locale => I18n.locale)}, :if => Proc.new {|c| c.request.format != :html } cache_sweeper :observation_sweeper, :only => [:create, :update, :destroy] rescue_from ::AbstractController::ActionNotFound do unless @selected_user = User.find_by_login(params[:action]) return render_404 end by_login end doorkeeper_for :create, :update, :destroy, :if => lambda { authenticate_with_oauth? } before_filter :load_user_by_login, :only => [:by_login, :by_login_all] before_filter :return_here, :only => [:index, :by_login, :show, :id_please, :import, :add_from_list, :new, :project] before_filter :authenticate_user!, :unless => lambda { authenticated_with_oauth? }, :except => [:explore, :index, :of, :show, :by_login, :id_please, :tile_points, :nearby, :widget, :project] before_filter :load_observation, :only => [:show, :edit, :edit_photos, :update_photos, :destroy, :fields] before_filter :require_owner, :only => [:edit, :edit_photos, :update_photos, :destroy] before_filter :curator_required, :only => [:curation] before_filter :load_photo_identities, :only => [:new, :new_batch, :show, :new_batch_csv,:edit, :update, :edit_batch, :create, :import, :import_photos, :new_from_list] before_filter :photo_identities_required, :only => [:import_photos] after_filter :refresh_lists_for_batch, :only => [:create, :update] MOBILIZED = [:add_from_list, :nearby, :add_nearby, :project, :by_login, :index, :show] before_filter :unmobilized, :except => MOBILIZED before_filter :mobilized, :only => MOBILIZED before_filter :load_prefs, :only => [:index, :project, :by_login] ORDER_BY_FIELDS = %w"created_at observed_on species_guess" REJECTED_FEED_PARAMS = %w"page view filters_open partial" REJECTED_KML_FEED_PARAMS = REJECTED_FEED_PARAMS + %w"swlat swlng nelat nelng" DISPLAY_ORDER_BY_FIELDS = { 'created_at' => 'date added', 'observations.id' => 'date added', 'id' => 'date added', 'observed_on' => 'date observed', 'species_guess' => 'species name' } PARTIALS = %w(cached_component observation_component observation mini) EDIT_PARTIALS = %w(add_photos) PHOTO_SYNC_ATTRS = [:description, :species_guess, :taxon_id, :observed_on, :observed_on_string, :latitude, :longitude, :place_guess] # GET /observations # GET /observations.xml def index search_params, find_options = get_search_params(params) search_params = site_search_params(search_params) if search_params[:q].blank? @observations = if perform_caching cache_params = params.reject{|k,v| %w(controller action format partial).include?(k.to_s)} cache_params[:page] ||= 1 cache_params[:site_name] ||= SITE_NAME if CONFIG.site_only_observations cache_params[:bounds] ||= CONFIG.bounds if CONFIG.bounds cache_key = "obs_index_#{Digest::MD5.hexdigest(cache_params.to_s)}" Rails.cache.fetch(cache_key, :expires_in => 5.minutes) do get_paginated_observations(search_params, find_options).to_a end else get_paginated_observations(search_params, find_options) end else @observations = search_observations(search_params, find_options) end respond_to do |format| format.html do @iconic_taxa ||= [] if (partial = params[:partial]) && PARTIALS.include?(partial) pagination_headers_for(@observations) return render_observations_partial(partial) end end format.json do render_observations_to_json end format.mobile format.geojson do render :json => @observations.to_geojson(:except => [ :geom, :latitude, :longitude, :map_scale, :num_identification_agreements, :num_identification_disagreements, :delta, :location_is_exact]) end format.atom do @updated_at = Observation.first(:order => 'updated_at DESC').updated_at end format.dwc format.csv do render_observations_to_csv end format.kml do render_observations_to_kml( :snippet => "#{CONFIG.site_name} Feed for Everyone", :description => "#{CONFIG.site_name} Feed for Everyone", :name => "#{CONFIG.site_name} Feed for Everyone" ) end format.widget do if params[:markup_only]=='true' render :js => render_to_string(:partial => "widget.html.erb", :locals => { :show_user => true, :target => params[:target], :default_image => params[:default_image], :silence => params[:silence] }) else render :js => render_to_string(:partial => "widget.js.erb", :locals => { :show_user => true }) end end end end def of if request.format == :html redirect_to observations_path(:taxon_id => params[:id]) return end unless @taxon = Taxon.find_by_id(params[:id].to_i) render_404 && return end @observations = Observation.of(@taxon).all( :include => [:user, :taxon, :iconic_taxon, :observation_photos => [:photo]], :order => "observations.id desc", :limit => 500).sort_by{|o| [o.quality_grade == "research" ? 1 : 0, o.id]} respond_to do |format| format.json do render :json => @observations.to_json( :methods => [:user_login, :iconic_taxon_name, :obs_image_url], :include => {:user => {:only => :login}, :taxon => {}, :iconic_taxon => {}}) end format.geojson do render :json => @observations.to_geojson(:except => [ :geom, :latitude, :longitude, :map_scale, :num_identification_agreements, :num_identification_disagreements, :delta, :location_is_exact]) end end end # GET /observations/1 # GET /observations/1.xml def show if request.format == :html && params[:partial] == "cached_component" && fragment_exist?(@observation.component_cache_key(:for_owner => @observation.user_id == current_user.try(:id))) return render(:partial => params[:partial], :object => @observation, :layout => false) end @previous = @observation.user.observations.first(:conditions => ["id < ?", @observation.id], :order => "id DESC") @prev = @previous @next = @observation.user.observations.first(:conditions => ["id > ?", @observation.id], :order => "id ASC") @quality_metrics = @observation.quality_metrics.all(:include => :user) if logged_in? @user_quality_metrics = @observation.quality_metrics.select{|qm| qm.user_id == current_user.id} @project_invitations = @observation.project_invitations.limit(100).to_a @project_invitations_by_project_id = @project_invitations.index_by(&:project_id) end respond_to do |format| format.html do # always display the time in the zone in which is was observed Time.zone = @observation.user.time_zone @identifications = @observation.identifications.includes(:user, :taxon => :photos) @current_identifications = @identifications.select{|o| o.current?} @owners_identification = @current_identifications.detect do |ident| ident.user_id == @observation.user_id end if logged_in? @viewers_identification = @current_identifications.detect do |ident| ident.user_id == current_user.id end end @current_identifications_by_taxon = @current_identifications.select do |ident| ident.user_id != ident.observation.user_id end.group_by{|i| i.taxon} @current_identifications_by_taxon = @current_identifications_by_taxon.sort_by do |row| row.last.size end.reverse if logged_in? # Make sure the viewer's ID is first in its group @current_identifications_by_taxon.each_with_index do |pair, i| if pair.last.map(&:user_id).include?(current_user.id) pair.last.delete(@viewers_identification) identifications = [@viewers_identification] + pair.last @current_identifications_by_taxon[i] = [pair.first, identifications] end end @projects = Project.all( :joins => [:project_users], :limit => 1000, :conditions => ["project_users.user_id = ?", current_user] ).sort_by{|p| p.title.downcase} end @places = @observation.places @project_observations = @observation.project_observations.limit(100).to_a @project_observations_by_project_id = @project_observations.index_by(&:project_id) @comments_and_identifications = (@observation.comments.all + @identifications).sort_by{|r| r.created_at} @photos = @observation.observation_photos.sort_by do |op| op.position || @observation.observation_photos.size + op.id.to_i end.map{|op| op.photo} if @observation.observed_on @day_observations = Observation.by(@observation.user).on(@observation.observed_on). includes(:photos). paginate(:page => 1, :per_page => 14) end if logged_in? @subscription = @observation.update_subscriptions.first(:conditions => {:user_id => current_user}) end @observation_links = @observation.observation_links.sort_by{|ol| ol.href} @posts = @observation.posts.published.limit(50) if @observation.taxon unless @places.blank? @listed_taxon = ListedTaxon. where("taxon_id = ? AND place_id IN (?) AND establishment_means IS NOT NULL", @observation.taxon_id, @places). includes(:place).first @conservation_status = ConservationStatus. where(:taxon_id => @observation.taxon).where("place_id IN (?)", @places). where("iucn >= ?", Taxon::IUCN_NEAR_THREATENED). includes(:place).first end @conservation_status ||= ConservationStatus.where(:taxon_id => @observation.taxon).where("place_id IS NULL"). where("iucn >= ?", Taxon::IUCN_NEAR_THREATENED).first end @observer_provider_authorizations = @observation.user.provider_authorizations if params[:partial] return render(:partial => params[:partial], :object => @observation, :layout => false) end end format.mobile format.xml { render :xml => @observation } format.json do render :json => @observation.to_json( :viewer => current_user, :methods => [:user_login, :iconic_taxon_name], :include => { :observation_field_values => {}, :project_observations => { :include => { :project => { :only => [:id, :title, :description], :methods => [:icon_url] } } }, :observation_photos => { :include => { :photo => { :methods => [:license_code, :attribution], :except => [:original_url, :file_processing, :file_file_size, :file_content_type, :file_file_name, :mobile, :metadata, :user_id, :native_realname, :native_photo_id] } } } }) end format.atom do cache end end end # GET /observations/new # GET /observations/new.xml # An attempt at creating a simple new page for batch add def new @observation = Observation.new(:user => current_user) @observation.id_please = params[:id_please] @observation.time_zone = current_user.time_zone if params[:copy] && (copy_obs = Observation.find_by_id(params[:copy])) && copy_obs.user_id == current_user.id %w(observed_on_string time_zone place_guess geoprivacy map_scale positional_accuracy).each do |a| @observation.send("#{a}=", copy_obs.send(a)) end @observation.latitude = copy_obs.private_latitude || copy_obs.latitude @observation.longitude = copy_obs.private_longitude || copy_obs.longitude copy_obs.observation_photos.each do |op| @observation.observation_photos.build(:photo => op.photo) end copy_obs.observation_field_values.each do |ofv| @observation.observation_field_values.build(:observation_field => ofv.observation_field, :value => ofv.value) end end @taxon = Taxon.find_by_id(params[:taxon_id].to_i) unless params[:taxon_id].blank? unless params[:taxon_name].blank? @taxon ||= TaxonName.first(:conditions => [ "lower(name) = ?", params[:taxon_name].to_s.strip.gsub(/[\s_]+/, ' ').downcase] ).try(:taxon) end if !params[:project_id].blank? @project = if params[:project_id].to_i == 0 Project.includes(:project_observation_fields => :observation_field).find(params[:project_id]) else Project.includes(:project_observation_fields => :observation_field).find_by_id(params[:project_id].to_i) end if @project @project_curators = @project.project_users.where("role IN (?)", [ProjectUser::MANAGER, ProjectUser::CURATOR]) if @place = @project.place @place_geometry = PlaceGeometry.without_geom.first(:conditions => {:place_id => @place}) end @tracking_code = params[:tracking_code] if @project.tracking_code_allowed?(params[:tracking_code]) @kml_assets = @project.project_assets.select{|pa| pa.asset_file_name =~ /\.km[lz]$/} end end if params[:facebook_photo_id] begin sync_facebook_photo rescue Koala::Facebook::APIError => e raise e unless e.message =~ /OAuthException/ redirect_to ProviderAuthorization::AUTH_URLS['facebook'] return end end sync_flickr_photo if params[:flickr_photo_id] && current_user.flickr_identity sync_picasa_photo if params[:picasa_photo_id] && current_user.picasa_identity sync_local_photo if params[:local_photo_id] @welcome = params[:welcome] # this should happen AFTER photo syncing so params can override attrs # from the photo [:latitude, :longitude, :place_guess, :location_is_exact, :map_scale, :positional_accuracy, :positioning_device, :positioning_method, :observed_on_string].each do |obs_attr| next if params[obs_attr].blank? # sync_photo indicates that the user clicked sync photo, so presumably they'd # like the photo attrs to override the URL # invite links are the other case, in which URL params *should* override the # photo attrs b/c the person who made the invite link chose a taxon or something if params[:sync_photo] @observation.send("#{obs_attr}=", params[obs_attr]) if @observation.send(obs_attr).blank? else @observation.send("#{obs_attr}=", params[obs_attr]) end end if @taxon @observation.taxon = @taxon @observation.species_guess = if @taxon.common_name @taxon.common_name.name else @taxon.name end elsif !params[:taxon_name].blank? @observation.species_guess = params[:taxon_name] end @observation_fields = ObservationField. includes(:observation_field_values => :observation). where("observations.user_id = ?", current_user). limit(10). order("observation_field_values.id DESC") respond_to do |format| format.html do @observations = [@observation] @sharing_authorizations = current_user.provider_authorizations.select do |pa| pa.provider_name == "facebook" || (pa.provider_name == "twitter" && !pa.secret.blank?) end end format.json { render :json => @observation } end end # def quickadd # if params[:txt] # pieces = txt.split(/\sat\s|\son\s|\sin\s/) # @observation = Observation.new(:species_guess => pieces.first) # @observation.place_guess = pieces.last if pieces.size > 1 # if pieces.size > 2 # @observation.observed_on_string = pieces[1..-2].join(' ') # end # @observation.user = self.current_user # end # respond_to do |format| # if @observation.save # flash[:notice] = "Your observation was saved." # format.html { redirect_to :action => @user.login } # format.xml { render :xml => @observation, :status => :created, # :location => @observation } # format.js { render } # else # format.html { render :action => "new" } # format.xml { render :xml => @observation.errors, # :status => :unprocessable_entity } # format.js { render :json => @observation.errors, # :status => :unprocessable_entity } # end # end # end # GET /observations/1/edit def edit # Only the owner should be able to see this. unless current_user.id == @observation.user_id or current_user.is_admin? redirect_to observation_path(@observation) return end # Make sure user is editing the REAL coordinates if @observation.coordinates_obscured? @observation.latitude = @observation.private_latitude @observation.longitude = @observation.private_longitude end if params[:facebook_photo_id] begin sync_facebook_photo rescue Koala::Facebook::APIError => e raise e unless e.message =~ /OAuthException/ redirect_to ProviderAuthorization::AUTH_URLS['facebook'] return end end sync_flickr_photo if params[:flickr_photo_id] sync_picasa_photo if params[:picasa_photo_id] sync_local_photo if params[:local_photo_id] @observation_fields = ObservationField. includes(:observation_field_values => {:observation => :user}). where("users.id = ?", current_user). limit(10). order("observation_field_values.id DESC") if @observation.quality_metrics.detect{|qm| qm.user_id == @observation.user_id && qm.metric == QualityMetric::WILD && !qm.agree?} @observation.captive = true end if params[:partial] && EDIT_PARTIALS.include?(params[:partial]) return render(:partial => params[:partial], :object => @observation, :layout => false) end end # POST /observations # POST /observations.xml def create # Handle the case of a single obs params[:observations] = [['0', params[:observation]]] if params[:observation] if params[:observations].blank? && params[:observation].blank? respond_to do |format| format.html do flash[:error] = t(:no_observations_submitted) redirect_to new_observation_path end format.json { render :status => :unprocessable_entity, :json => "No observations submitted!" } end return end @observations = params[:observations].map do |fieldset_index, observation| next if observation.blank? observation.delete('fieldset_index') if observation[:fieldset_index] o = Observation.new(observation) o.user = current_user o.user_agent = request.user_agent if doorkeeper_token && (a = doorkeeper_token.application) o.oauth_application = a.becomes(OauthApplication) end # Get photos Photo.descendent_classes.each do |klass| klass_key = klass.to_s.underscore.pluralize.to_sym if params[klass_key] && params[klass_key][fieldset_index] o.photos << retrieve_photos(params[klass_key][fieldset_index], :user => current_user, :photo_class => klass) end if params["#{klass_key}_to_sync"] && params["#{klass_key}_to_sync"][fieldset_index] if photo = o.photos.compact.last photo_o = photo.to_observation PHOTO_SYNC_ATTRS.each do |a| o.send("#{a}=", photo_o.send(a)) end end end end o end current_user.observations << @observations if request.format != :json && !params[:accept_terms] && params[:project_id] && !current_user.project_users.find_by_project_id(params[:project_id]) flash[:error] = t(:but_we_didnt_add_this_observation_to_the_x_project, :project => Project.find_by_id(params[:project_id]).title) else create_project_observations end update_user_account # check for errors errors = false @observations.each { |obs| errors = true unless obs.valid? } respond_to do |format| format.html do unless errors flash[:notice] = params[:success_msg] || t(:observations_saved) if params[:commit] == "Save and add another" o = @observations.first redirect_to :action => 'new', :latitude => o.coordinates_obscured? ? o.private_latitude : o.latitude, :longitude => o.coordinates_obscured? ? o.private_longitude : o.longitude, :place_guess => o.place_guess, :observed_on_string => o.observed_on_string, :location_is_exact => o.location_is_exact, :map_scale => o.map_scale, :positional_accuracy => o.positional_accuracy, :positioning_method => o.positioning_method, :positioning_device => o.positioning_device, :project_id => params[:project_id] elsif @observations.size == 1 redirect_to observation_path(@observations.first) else redirect_to :action => self.current_user.login end else if @observations.size == 1 render :action => 'new' else render :action => 'edit_batch' end end end format.json do if errors json = if @observations.size == 1 && is_iphone_app_2? {:error => @observations.map{|o| o.errors.full_messages}.flatten.uniq.compact.to_sentence} else {:errors => @observations.map{|o| o.errors.full_messages}} end render :json => json, :status => :unprocessable_entity else if @observations.size == 1 && is_iphone_app_2? render :json => @observations[0].to_json( :viewer => current_user, :methods => [:user_login, :iconic_taxon_name], :include => { :taxon => Taxon.default_json_options, :observation_field_values => {} } ) else render :json => @observations.to_json(:viewer => current_user, :methods => [:user_login, :iconic_taxon_name]) end end end end end # PUT /observations/1 # PUT /observations/1.xml def update observation_user = current_user unless params[:admin_action].nil? || !current_user.is_admin? observation_user = Observation.find(params[:id]).user end # Handle the case of a single obs if params[:observation] params[:observations] = [[params[:id], params[:observation]]] elsif params[:id] && params[:observations] params[:observations] = [[params[:id], params[:observations][0]]] end if params[:observations].blank? && params[:observation].blank? respond_to do |format| format.html do flash[:error] = t(:no_observations_submitted) redirect_to new_observation_path end format.json { render :status => :unprocessable_entity, :json => "No observations submitted!" } end return end @observations = Observation.all( :conditions => [ "id IN (?) AND user_id = ?", params[:observations].map{|k,v| k}, observation_user ] ) # Make sure there's no evil going on unique_user_ids = @observations.map(&:user_id).uniq if unique_user_ids.size > 1 || unique_user_ids.first != observation_user.id && !current_user.has_role?(:admin) flash[:error] = t(:you_dont_have_permission_to_edit_that_observation) return redirect_to(@observation || observations_path) end # Convert the params to a hash keyed by ID. Yes, it's weird hashed_params = Hash[*params[:observations].to_a.flatten] errors = false extra_msg = nil @observations.each do |observation| # Update the flickr photos # Note: this ignore photos thing is a total hack and should only be # included if you are updating observations but aren't including flickr # fields, e.g. when removing something from ID please if !params[:ignore_photos] && !is_mobile_app? # Get photos updated_photos = [] old_photo_ids = observation.photo_ids Photo.descendent_classes.each do |klass| klass_key = klass.to_s.underscore.pluralize.to_sym if params[klass_key] && params[klass_key][observation.id.to_s] updated_photos += retrieve_photos(params[klass_key][observation.id.to_s], :user => current_user, :photo_class => klass, :sync => true) end end if updated_photos.empty? observation.photos.clear else observation.photos = updated_photos end # Destroy old photos. ObservationPhotos seem to get removed by magic doomed_photo_ids = (old_photo_ids - observation.photo_ids).compact unless doomed_photo_ids.blank? Photo.delay.destroy_orphans(doomed_photo_ids) end end unless observation.update_attributes(hashed_params[observation.id.to_s]) errors = true end if !errors && params[:project_id] && !observation.project_observations.where(:project_id => params[:project_id]).exists? if @project ||= Project.find(params[:project_id]) project_observation = ProjectObservation.create(:project => @project, :observation => observation) extra_msg = if project_observation.valid? "Successfully added to #{@project.title}" else "Failed to add to #{@project.title}: #{project_observation.errors.full_messages.to_sentence}" end end end end respond_to do |format| if errors format.html do if @observations.size == 1 @observation = @observations.first render :action => 'edit' else render :action => 'edit_batch' end end format.xml { render :xml => @observations.collect(&:errors), :status => :unprocessable_entity } format.json do render :status => :unprocessable_entity, :json => { :error => @observations.map{|o| o.errors.full_messages.to_sentence}.to_sentence, :errors => @observations.collect(&:errors) } end elsif @observations.empty? msg = if params[:id] t(:that_observation_no_longer_exists) else t(:those_observations_no_longer_exist) end format.html do flash[:error] = msg redirect_back_or_default(observations_by_login_path(current_user.login)) end format.json { render :json => {:error => msg}, :status => :gone } else format.html do flash[:notice] = "#{t(:observations_was_successfully_updated)} #{extra_msg}" if @observations.size == 1 redirect_to observation_path(@observations.first) else redirect_to observations_by_login_path(observation_user.login) end end format.xml { head :ok } format.js { render :json => @observations } format.json do if @observations.size == 1 && is_iphone_app_2? render :json => @observations[0].to_json( :methods => [:user_login, :iconic_taxon_name], :include => { :taxon => Taxon.default_json_options, :observation_field_values => {}, :project_observations => { :include => { :project => { :only => [:id, :title, :description], :methods => [:icon_url] } } }, :observation_photos => { :except => [:file_processing, :file_file_size, :file_content_type, :file_file_name, :user_id, :native_realname, :mobile, :native_photo_id], :include => { :photo => {} } } }) else render :json => @observations.to_json(:methods => [:user_login, :iconic_taxon_name]) end end end end end def edit_photos @observation_photos = @observation.observation_photos if @observation_photos.blank? flash[:error] = t(:that_observation_doesnt_have_any_photos) return redirect_to edit_observation_path(@observation) end end def update_photos @observation_photos = ObservationPhoto.all(:conditions => [ "id IN (?)", params[:observation_photos].map{|k,v| k}]) @observation_photos.each do |op| next unless @observation.observation_photo_ids.include?(op.id) op.update_attributes(params[:observation_photos][op.id.to_s]) end flash[:notice] = t(:photos_updated) redirect_to edit_observation_path(@observation) end # DELETE /observations/1 # DELETE /observations/1.xml def destroy @observation.destroy respond_to do |format| format.html do flash[:notice] = t(:observation_was_deleted) redirect_to(observations_by_login_path(current_user.login)) end format.xml { head :ok } format.json { head :ok } end end ## Custom actions ############################################################ def curation @flags = Flag.paginate(:page => params[:page], :include => :user, :conditions => "resolved = false AND flaggable_type = 'Observation'") end def new_batch @step = 1 @observations = [] if params[:batch] params[:batch][:taxa].each_line do |taxon_name_str| next if taxon_name_str.strip.blank? latitude = params[:batch][:latitude] longitude = params[:batch][:longitude] if latitude.nil? && longitude.nil? && params[:batch][:place_guess] places = Ym4r::GmPlugin::Geocoding.get(params[:batch][:place_guess]) unless places.empty? latitude = places.first.latitude longitude = places.first.longitude end end @observations << Observation.new( :user => current_user, :species_guess => taxon_name_str, :taxon => Taxon.single_taxon_for_name(taxon_name_str.strip), :place_guess => params[:batch][:place_guess], :longitude => longitude, :latitude => latitude, :map_scale => params[:batch][:map_scale], :positional_accuracy => params[:batch][:positional_accuracy], :positioning_method => params[:batch][:positioning_method], :positioning_device => params[:batch][:positioning_device], :location_is_exact => params[:batch][:location_is_exact], :observed_on_string => params[:batch][:observed_on_string], :time_zone => current_user.time_zone) end @step = 2 end end def new_batch_csv if params[:upload].blank? || params[:upload] && params[:upload][:datafile].blank? flash[:error] = t(:you_must_select_a_csv_file_to_upload) return redirect_to :action => "import" end @observations = [] @hasInvalid = false csv = params[:upload][:datafile].read max_rows = 100 row_num = 0 @rows = [] begin CSV.parse(csv) do |row| next if row.blank? row = row.map do |item| if item.blank? nil else begin item.to_s.encode('UTF-8').strip rescue Encoding::UndefinedConversionError => e problem = e.message[/"(.+)" from/, 1] begin item.to_s.gsub(problem, '').encode('UTF-8').strip rescue Encoding::UndefinedConversionError => e # If there's more than one encoding issue, just bail '' end end end end obs = Observation.new( :user => current_user, :species_guess => row[0], :observed_on_string => row[1], :description => row[2], :place_guess => row[3], :time_zone => current_user.time_zone, :latitude => row[4], :longitude => row[5] ) obs.set_taxon_from_species_guess if obs.georeferenced? obs.location_is_exact = true elsif row[3] places = Ym4r::GmPlugin::Geocoding.get(row[3]) unless row[3].blank? unless places.blank? obs.latitude = places.first.latitude obs.longitude = places.first.longitude obs.location_is_exact = false end end obs.tag_list = row[6] @hasInvalid ||= !obs.valid? @observations << obs @rows << row row_num += 1 if row_num >= max_rows flash[:notice] = t(:too_many_observations_csv, :max_rows => max_rows) break end end rescue CSV::MalformedCSVError => e flash[:error] = <<-EOT Your CSV had a formatting problem. Try removing any strange characters and unclosed quotes, and if the problem persists, please <a href="mailto:#{CONFIG.help_email}">email us</a> the file and we'll figure out the problem. EOT redirect_to :action => 'import' return end end # Edit a batch of observations def edit_batch observation_ids = params[:o].is_a?(String) ? params[:o].split(',') : [] @observations = Observation.all( :conditions => [ "id in (?) AND user_id = ?", observation_ids, current_user]) @observations.map do |o| if o.coordinates_obscured? o.latitude = o.private_latitude o.longitude = o.private_longitude end o end end def delete_batch @observations = Observation.all( :conditions => [ "id in (?) AND user_id = ?", params[:o].split(','), current_user]) @observations.each do |observation| observation.destroy if observation.user == current_user end respond_to do |format| format.html do flash[:notice] = t(:observations_deleted) redirect_to observations_by_login_path(current_user.login) end format.js { render :text => "Observations deleted.", :status => 200 } end end # Import observations from external sources def import end def import_photos photos = Photo.descendent_classes.map do |klass| retrieve_photos(params[klass.to_s.underscore.pluralize.to_sym], :user => current_user, :photo_class => klass) end.flatten.compact @observations = photos.map{|p| p.to_observation} @observation_photos = ObservationPhoto.includes(:photo, :observation). where("photos.native_photo_id IN (?)", photos.map(&:native_photo_id)) @step = 2 render :template => 'observations/new_batch' rescue Timeout::Error => e flash[:error] = t(:sorry_that_photo_provider_isnt_responding) Rails.logger.error "[ERROR #{Time.now}] Timeout: #{e}" redirect_to :action => "import" end def add_from_list @order = params[:order] || "alphabetical" if @list = List.find_by_id(params[:id]) @cache_key = {:controller => "observations", :action => "add_from_list", :id => @list.id, :order => @order} unless fragment_exist?(@cache_key) @listed_taxa = @list.listed_taxa.order_by(@order).paginate(:include => {:taxon => [:photos, :taxon_names]}, :page => 1, :per_page => 1000) @listed_taxa_alphabetical = @listed_taxa.sort! {|a,b| a.taxon.default_name.name <=> b.taxon.default_name.name} @listed_taxa = @listed_taxa_alphabetical if @order == ListedTaxon::ALPHABETICAL_ORDER @taxon_ids_by_name = {} ancestor_ids = @listed_taxa.map {|lt| lt.taxon_ancestor_ids.to_s.split('/')}.flatten.uniq @orders = Taxon.all(:conditions => ["rank = 'order' AND id IN (?)", ancestor_ids], :order => "ancestry") @families = Taxon.all(:conditions => ["rank = 'family' AND id IN (?)", ancestor_ids], :order => "ancestry") end end @user_lists = current_user.lists.all(:limit => 100) respond_to do |format| format.html format.mobile { render "add_from_list.html.erb" } format.js do if fragment_exist?(@cache_key) render read_fragment(@cache_key) else render :partial => 'add_from_list.html.erb' end end end end def new_from_list @taxa = Taxon.all(:conditions => ["id in (?)", params[:taxa]], :include => :taxon_names) if @taxa.blank? flash[:error] = t(:no_taxa_selected) return redirect_to :action => :add_from_list end @observations = @taxa.map do |taxon| current_user.observations.build(:taxon => taxon, :species_guess => taxon.default_name.name, :time_zone => current_user.time_zone) end @step = 2 render :new_batch end # gets observations by user login def by_login search_params, find_options = get_search_params(params) search_params.update(:user_id => @selected_user.id) if search_params[:q].blank? get_paginated_observations(search_params, find_options) else search_observations(search_params, find_options) end respond_to do |format| format.html do @observer_provider_authorizations = @selected_user.provider_authorizations if logged_in? && @selected_user.id == current_user.id @project_users = current_user.project_users.all(:include => :project, :order => "projects.title") if @proj_obs_errors = Rails.cache.read("proj_obs_errors_#{current_user.id}") @project = Project.find_by_id(@proj_obs_errors[:project_id]) @proj_obs_errors_obs = current_user.observations.all(:conditions => ["id IN (?)", @proj_obs_errors[:errors].keys], :include => [:photos, :taxon]) Rails.cache.delete("proj_obs_errors_#{current_user.id}") end end if (partial = params[:partial]) && PARTIALS.include?(partial) return render_observations_partial(partial) end end format.mobile format.json do render_observations_to_json end format.kml do render_observations_to_kml( :snippet => "#{CONFIG.site_name} Feed for User: #{@selected_user.login}", :description => "#{CONFIG.site_name} Feed for User: #{@selected_user.login}", :name => "#{CONFIG.site_name} Feed for User: #{@selected_user.login}" ) end format.atom format.csv do render_observations_to_csv(:show_private => logged_in? && @selected_user.id == current_user.id) end format.widget do if params[:markup_only]=='true' render :js => render_to_string(:partial => "widget.html.erb", :locals => { :show_user => false, :target => params[:target], :default_image => params[:default_image], :silence => params[:silence] }) else render :js => render_to_string(:partial => "widget.js.erb") end end end end def by_login_all if @selected_user.id != current_user.id flash[:error] = t(:you_dont_have_permission_to_do_that) redirect_back_or_default(root_url) return end path_for_csv = private_page_cache_path("observations/#{@selected_user.login}.all.csv") delayed_csv(path_for_csv, @selected_user) end # shows observations in need of an ID def id_please params[:order_by] ||= "created_at" params[:order] ||= "desc" search_params, find_options = get_search_params(params) search_params = site_search_params(search_params) find_options.update( :per_page => 10, :include => [ :user, {:taxon => [:taxon_names]}, :tags, :photos, {:identifications => [{:taxon => [:taxon_names]}, :user]}, {:comments => [:user]} ] ) if search_params[:has] search_params[:has] = (search_params[:has].split(',') + ['id_please']).flatten.uniq else search_params[:has] = 'id_please' end if search_params[:q].blank? get_paginated_observations(search_params, find_options) else search_observations(search_params, find_options) end @top_identifiers = User.all(:order => "identifications_count DESC", :limit => 5) end # Renders observation components as form fields for inclusion in # observation-picking form widgets def selector search_params, find_options = get_search_params(params) @observations = Observation.latest.query(search_params).paginate(find_options) respond_to do |format| format.html { render :layout => false, :partial => 'selector'} # format.js end end def tile_points # Project tile coordinates into lat/lon using a Spherical Merc projection merc = SPHERICAL_MERCATOR tile_size = 256 x, y, zoom = params[:x].to_i, params[:y].to_i, params[:zoom].to_i swlng, swlat = merc.from_pixel_to_ll([x * tile_size, (y+1) * tile_size], zoom) nelng, nelat = merc.from_pixel_to_ll([(x+1) * tile_size, y * tile_size], zoom) @observations = Observation.in_bounding_box(swlat, swlng, nelat, nelng).all( :select => "id, species_guess, latitude, longitude, user_id, description, private_latitude, private_longitude, time_observed_at", :include => [:user, :photos], :limit => 500, :order => "id DESC") respond_to do |format| format.json do render :json => @observations.to_json( :only => [:id, :species_guess, :latitude, :longitude], :include => { :user => {:only => :login} }, :methods => [:image_url, :short_description]) end end end def widget @project = Project.find_by_id(params[:project_id].to_i) if params[:project_id] @place = Place.find_by_id(params[:place_id].to_i) if params[:place_id] @taxon = Taxon.find_by_id(params[:taxon_id].to_i) if params[:taxon_id] @order_by = params[:order_by] || "observed_on" @order = params[:order] || "desc" @limit = params[:limit] || 5 @limit = @limit.to_i if %w"logo-small.gif logo-small.png logo-small-white.png none".include?(params[:logo]) @logo = params[:logo] end @logo ||= "logo-small.gif" @layout = params[:layout] || "large" url_params = { :format => "widget", :limit => @limit, :order => @order, :order_by => @order_by, :layout => @layout, } @widget_url = if @place observations_url(url_params.merge(:place_id => @place.id)) elsif @taxon observations_url(url_params.merge(:taxon_id => @taxon.id)) elsif @project project_observations_url(@project.id, url_params) elsif logged_in? observations_by_login_feed_url(current_user.login, url_params) end respond_to do |format| format.html end end def nearby @lat = params[:latitude].to_f @lon = params[:longitude].to_f if @lat && @lon @latrads = @lat * (Math::PI / 180) @lonrads = @lon * (Math::PI / 180) @observations = Observation.search(:geo => [latrads,lonrads], :page => params[:page], :without => {:observed_on => 0}, :order => "@geodist asc, observed_on desc") rescue [] end @observations ||= Observation.latest.paginate(:page => params[:page]) request.format = :mobile respond_to do |format| format.mobile end end def add_nearby @observation = current_user.observations.build(:time_zone => current_user.time_zone) request.format = :mobile respond_to do |format| format.mobile end end def project @project = Project.find(params[:id]) rescue nil unless @project flash[:error] = t(:that_project_doesnt_exist) redirect_to request.env["HTTP_REFERER"] || projects_path return end unless request.format == :mobile search_params, find_options = get_search_params(params) search_params[:projects] = @project.id if search_params[:q].blank? get_paginated_observations(search_params, find_options) else search_observations(search_params, find_options) end end @project_observations = @project.project_observations.all( :conditions => ["observation_id IN (?)", @observations], :include => [{:curator_identification => [:taxon, :user]}]) @project_observations_by_observation_id = @project_observations.index_by(&:observation_id) @kml_assets = @project.project_assets.select{|pa| pa.asset_file_name =~ /\.km[lz]$/} respond_to do |format| format.html do if (partial = params[:partial]) && PARTIALS.include?(partial) return render_observations_partial(partial) end end format.json do render_observations_to_json end format.atom do @updated_at = Observation.first(:order => 'updated_at DESC').updated_at render :action => "index" end format.csv do render :text => ProjectObservation.to_csv(@project_observations, :user => current_user) end format.kml do render_observations_to_kml( :snippet => "#{@project.title.html_safe} Observations", :description => "Observations feed for the #{CONFIG.site_name} project '#{@project.title.html_safe}'", :name => "#{@project.title.html_safe} Observations" ) end format.widget do if params[:markup_only] == 'true' render :js => render_to_string(:partial => "widget.html.erb", :locals => { :show_user => true, :target => params[:target], :default_image => params[:default_image], :silence => params[:silence] }) else render :js => render_to_string(:partial => "widget.js.erb", :locals => { :show_user => true }) end end format.mobile end end def project_all @project = Project.find(params[:id]) rescue nil unless @project flash[:error] = t(:that_project_doesnt_exist) redirect_to request.env["HTTP_REFERER"] || projects_path return end unless @project.curated_by?(current_user) flash[:error] = t(:only_project_curators_can_do_that) redirect_to request.env["HTTP_REFERER"] || @project return end path_for_csv = private_page_cache_path("observations/project/#{@project.slug}.all.csv") delayed_csv(path_for_csv, @project) end def identotron @observation = Observation.find_by_id((params[:observation] || params[:observation_id]).to_i) @taxon = Taxon.find_by_id(params[:taxon].to_i) @q = params[:q] unless params[:q].blank? if @observation @places = @observation.places.try(:reverse) if @observation.taxon && @observation.taxon.species_or_lower? @taxon ||= @observation.taxon.genus else @taxon ||= @observation.taxon end if @taxon && @places @place = @places.reverse.detect {|p| p.taxa.self_and_descendants_of(@taxon).exists?} end end @place ||= (Place.find(params[:place_id]) rescue nil) || @places.try(:last) @default_taxa = @taxon ? @taxon.ancestors : Taxon::ICONIC_TAXA @taxon ||= Taxon::LIFE @default_taxa = [@default_taxa, @taxon].flatten.compact end def fields @project = Project.find(params[:project_id]) rescue nil @observation_fields = if @project @project.observation_fields elsif params[:observation_fields] ObservationField.where("id IN (?)", params[:observation_fields]) else @observation_fields = ObservationField. includes(:observation_field_values => {:observation => :user}). where("users.id = ?", current_user). limit(10). order("observation_field_values.id DESC") end render :layout => false end def photo @observations = [] unless params[:files].blank? params[:files].each_with_index do |file, i| lp = LocalPhoto.new(:file => file, :user => current_user) o = lp.to_observation if params[:observations] && obs_params = params[:observations][i] obs_params.each do |k,v| o.send("#{k}=", v) unless v.blank? end end o.save @observations << o end end respond_to do |format| format.json do render_observations_to_json(:include => { :taxon => { :only => [:name, :id, :rank, :rank_level, :is_iconic], :methods => [:default_name, :image_url, :iconic_taxon_name, :conservation_status_name], :include => { :iconic_taxon => { :only => [:id, :name] }, :taxon_names => { :only => [:id, :name, :lexicon] } } } }) end end end def stats @headless = @footless = true search_params, find_options = get_search_params(params) @stats_adequately_scoped = stats_adequately_scoped? end def taxon_stats search_params, find_options = get_search_params(params, :skip_order => true, :skip_pagination => true) scope = Observation.query(search_params).scoped scope = scope.where("1 = 2") unless stats_adequately_scoped? taxon_counts_scope = scope. joins(:taxon). where("taxa.rank_level <= ?", Taxon::SPECIES_LEVEL) taxon_counts_sql = <<-SQL SELECT o.taxon_id, count(*) AS count_all FROM (#{taxon_counts_scope.to_sql}) AS o GROUP BY o.taxon_id ORDER BY count_all desc LIMIT 5 SQL @taxon_counts = ActiveRecord::Base.connection.execute(taxon_counts_sql) @taxa = Taxon.where("id in (?)", @taxon_counts.map{|r| r['taxon_id']}).includes({:taxon_photos => :photo}, :taxon_names) @taxa_by_taxon_id = @taxa.index_by(&:id) rank_counts_sql = <<-SQL SELECT o.rank_name, count(*) AS count_all FROM (#{scope.joins(:taxon).select("DISTINCT ON (taxa.id) taxa.rank AS rank_name").to_sql}) AS o GROUP BY o.rank_name SQL @rank_counts = ActiveRecord::Base.connection.execute(rank_counts_sql) respond_to do |format| format.json do render :json => { :total => @rank_counts.map{|r| r['count_all'].to_i}.sum, :taxon_counts => @taxon_counts.map{|row| { :id => row['taxon_id'], :count => row['count_all'], :taxon => @taxa_by_taxon_id[row['taxon_id'].to_i].as_json( :methods => [:default_name, :image_url, :iconic_taxon_name, :conservation_status_name], :only => [:id, :name, :rank, :rank_level] ) } }, :rank_counts => @rank_counts.inject({}) {|memo,row| memo[row['rank_name']] = row['count_all'] memo } } end end end def user_stats search_params, find_options = get_search_params(params, :skip_order => true, :skip_pagination => true) scope = Observation.query(search_params).scoped scope = scope.where("1 = 2") unless stats_adequately_scoped? user_counts_sql = <<-SQL SELECT o.user_id, count(*) AS count_all FROM (#{scope.to_sql}) AS o GROUP BY o.user_id ORDER BY count_all desc LIMIT 5 SQL @user_counts = ActiveRecord::Base.connection.execute(user_counts_sql) user_taxon_counts_sql = <<-SQL SELECT o.user_id, count(*) AS count_all FROM (#{scope.select("DISTINCT ON (observations.taxon_id) observations.user_id").joins(:taxon).where("taxa.rank_level <= ?", Taxon::SPECIES_LEVEL).to_sql}) AS o GROUP BY o.user_id ORDER BY count_all desc LIMIT 5 SQL @user_taxon_counts = ActiveRecord::Base.connection.execute(user_taxon_counts_sql) @users = User.where("id in (?)", [@user_counts.map{|r| r['user_id']}, @user_taxon_counts.map{|r| r['user_id']}].flatten.uniq) @users_by_id = @users.index_by(&:id) respond_to do |format| format.json do render :json => { :total => scope.select("DISTINCT observations.user_id").count, :most_observations => @user_counts.map{|row| { :id => row['user_id'], :count => row['count_all'], :user => @users_by_id[row['user_id'].to_i].as_json( :only => [:id, :name, :login], :methods => [:user_icon_url] ) } }, :most_species => @user_taxon_counts.map{|row| { :id => row['user_id'], :count => row['count_all'], :user => @users_by_id[row['user_id'].to_i].as_json( :only => [:id, :name, :login], :methods => [:user_icon_url] ) } } } end end end ## Protected / private actions ############################################### private def stats_adequately_scoped? if params[:d1] && params[:d2] d1 = (Date.parse(params[:d1]) rescue Date.today) d2 = (Date.parse(params[:d2]) rescue Date.today) return false if d2 - d1 > 366 end !(params[:d1].blank? && params[:projects].blank? && params[:place_id].blank? && params[:user_id].blank?) end def retrieve_photos(photo_list = nil, options = {}) return [] if photo_list.blank? photo_list = photo_list.values if photo_list.is_a?(Hash) photo_list = [photo_list] unless photo_list.is_a?(Array) photo_class = options[:photo_class] || Photo # simple algorithm, # 1. create an array to be passed back to the observation obj # 2. check to see if that photo's data has already been stored # 3. if yes # retrieve Photo obj and put in array # if no # create Photo obj and put in array # 4. return array photos = [] native_photo_ids = photo_list.map{|p| p.to_s}.uniq existing = photo_class.includes(:user).where("native_photo_id IN (?)", native_photo_ids).index_by{|p| p.native_photo_id} photo_list.uniq.each do |photo_id| if (photo = existing[photo_id]) || options[:sync] api_response = photo_class.get_api_response(photo_id, :user => current_user) end # Sync existing if called for if photo photo.user ||= options[:user] if options[:sync] # sync the photo URLs b/c they change when photos become private photo.api_response = api_response # set to make sure user validation works photo.sync photo.save if photo.changed? end end # Create a new one if one doesn't already exist unless photo photo = if photo_class == LocalPhoto LocalPhoto.new(:file => photo_id, :user => current_user) unless photo_id.blank? else api_response ||= photo_class.get_api_response(photo_id, :user => current_user) if api_response photo_class.new_from_api_response(api_response, :user => current_user) end end end if photo.blank? Rails.logger.error "[ERROR #{Time.now}] Failed to get photo for photo_class: #{photo_class}, photo_id: #{photo_id}" elsif photo.valid? photos << photo else Rails.logger.error "[ERROR #{Time.now}] #{current_user} tried to save an observation with an invalid photo (#{photo}): #{photo.errors.full_messages.to_sentence}" end end photos end # Processes params for observation requests. Designed for use with # will_paginate and standard observations query API def get_search_params(params, options = {}) # The original params is important for things like pagination, so we # leave it untouched. search_params = params.clone @swlat = search_params[:swlat] unless search_params[:swlat].blank? @swlng = search_params[:swlng] unless search_params[:swlng].blank? @nelat = search_params[:nelat] unless search_params[:nelat].blank? @nelng = search_params[:nelng] unless search_params[:nelng].blank? unless search_params[:place_id].blank? @place = begin Place.find(search_params[:place_id]) rescue ActiveRecord::RecordNotFound nil end end @q = search_params[:q].to_s unless search_params[:q].blank? if Observation::SPHINX_FIELD_NAMES.include?(search_params[:search_on]) @search_on = search_params[:search_on] end find_options = { :include => [:user, {:taxon => [:taxon_names]}, :taggings, {:observation_photos => :photo}], :page => search_params[:page] } unless options[:skip_pagination] find_options[:page] = 1 if find_options[:page].to_i == 0 find_options[:per_page] = @prefs["per_page"] if @prefs if !search_params[:per_page].blank? find_options.update(:per_page => search_params[:per_page]) elsif !search_params[:limit].blank? find_options.update(:per_page => search_params[:limit]) end if find_options[:per_page] && find_options[:per_page].to_i > 200 find_options[:per_page] = 200 end find_options[:per_page] = 30 if find_options[:per_page].to_i == 0 end if find_options[:limit] && find_options[:limit].to_i > 200 find_options[:limit] = 200 end unless request.format && request.format.html? find_options[:include] = [{:taxon => :taxon_names}, {:observation_photos => :photo}, :user] end # iconic_taxa if search_params[:iconic_taxa] # split a string of names if search_params[:iconic_taxa].is_a? String search_params[:iconic_taxa] = search_params[:iconic_taxa].split(',') end # resolve taxa entered by name search_params[:iconic_taxa] = search_params[:iconic_taxa].map do |it| it = it.last if it.is_a?(Array) if it.to_i == 0 Taxon::ICONIC_TAXA_BY_NAME[it] else Taxon::ICONIC_TAXA_BY_ID[it] end end @iconic_taxa = search_params[:iconic_taxa] end # taxon unless search_params[:taxon_id].blank? @observations_taxon_id = search_params[:taxon_id] @observations_taxon = Taxon.find_by_id(@observations_taxon_id.to_i) end unless search_params[:taxon_name].blank? @observations_taxon_name = search_params[:taxon_name].to_s taxon_name_conditions = ["taxon_names.name = ?", @observations_taxon_name] includes = nil unless @iconic_taxa.blank? taxon_name_conditions[0] += " AND taxa.iconic_taxon_id IN (?)" taxon_name_conditions << @iconic_taxa includes = :taxon end begin @observations_taxon = TaxonName.first(:include => includes, :conditions => taxon_name_conditions).try(:taxon) rescue ActiveRecord::StatementInvalid => e raise e unless e.message =~ /invalid byte sequence/ taxon_name_conditions[1] = @observations_taxon_name.encode('UTF-8') @observations_taxon = TaxonName.first(:include => includes, :conditions => taxon_name_conditions).try(:taxon) end end search_params[:taxon] = @observations_taxon if search_params[:has] if search_params[:has].is_a?(String) search_params[:has] = search_params[:has].split(',') end @id_please = true if search_params[:has].include?('id_please') @with_photos = true if search_params[:has].include?('photos') end @quality_grade = search_params[:quality_grade] @identifications = search_params[:identifications] @out_of_range = search_params[:out_of_range] @license = search_params[:license] @photo_license = search_params[:photo_license] unless options[:skip_order] search_params[:order_by] = "created_at" if search_params[:order_by] == "observations.id" if ORDER_BY_FIELDS.include?(search_params[:order_by].to_s) @order_by = search_params[:order_by] @order = if %w(asc desc).include?(search_params[:order].to_s.downcase) search_params[:order] else 'desc' end else @order_by = "observations.id" @order = "desc" end search_params[:order_by] = "#{@order_by} #{@order}" end # date date_pieces = [search_params[:year], search_params[:month], search_params[:day]] unless date_pieces.map{|d| d.blank? ? nil : d}.compact.blank? search_params[:on] = date_pieces.join('-') end if search_params[:on].to_s =~ /^\d{4}/ @observed_on = search_params[:on] @observed_on_year, @observed_on_month, @observed_on_day = @observed_on.split('-').map{|d| d.to_i} end @observed_on_year ||= search_params[:year].to_i unless search_params[:year].blank? @observed_on_month ||= search_params[:month].to_i unless search_params[:month].blank? @observed_on_day ||= search_params[:day].to_i unless search_params[:day].blank? # observation fields ofv_params = search_params.select{|k,v| k =~ /^field\:/} unless ofv_params.blank? @ofv_params = {} ofv_params.each do |k,v| @ofv_params[k] = { :normalized_name => ObservationField.normalize_name(k), :value => v } end observation_fields = ObservationField.where("lower(name) IN (?)", @ofv_params.map{|k,v| v[:normalized_name]}) @ofv_params.each do |k,v| v[:observation_field] = observation_fields.detect do |of| v[:normalized_name] == ObservationField.normalize_name(of.name) end end @ofv_params.delete_if{|k,v| v[:observation_field].blank?} search_params[:ofv_params] = @ofv_params end @site = params[:site] unless params[:site].blank? @user = User.find_by_id(params[:user_id]) unless params[:user_id].blank? @projects = Project.where("id IN (?)", params[:projects]) unless params[:projects].blank? @filters_open = !@q.nil? || !@observations_taxon_id.blank? || !@observations_taxon_name.blank? || !@iconic_taxa.blank? || @id_please == true || !@with_photos.blank? || !@identifications.blank? || !@quality_grade.blank? || !@out_of_range.blank? || !@observed_on.blank? || !@place.blank? || !@ofv_params.blank? @filters_open = search_params[:filters_open] == 'true' if search_params.has_key?(:filters_open) [search_params, find_options] end # Either make a plain db query and return a WillPaginate collection or make # a Sphinx call if there were query terms specified. def get_paginated_observations(search_params, find_options) if @q @observations = if @search_on find_options[:conditions] = update_conditions( find_options[:conditions], @search_on.to_sym => @q ) Observation.query(search_params).search(find_options).compact else Observation.query(search_params).search(@q, find_options).compact end end if @observations.blank? @observations = Observation.query(search_params).includes(:observation_photos => :photo).paginate(find_options) end @observations rescue ThinkingSphinx::ConnectionError Rails.logger.error "[ERROR #{Time.now}] ThinkingSphinx::ConnectionError, hitting the db" find_options.delete(:class) find_options.delete(:classes) find_options.delete(:raise_on_stale) @observations = if @q Observation.query(search_params).all( :conditions => ["species_guess LIKE ?", "%#{@q}%"]).paginate(find_options) else Observation.query(search_params).paginate(find_options) end end def search_observations(search_params, find_options) sphinx_options = find_options.dup sphinx_options[:with] = {} if sphinx_options[:page] && sphinx_options[:page].to_i > 50 if request.format && request.format.html? flash.now[:notice] = t(:heads_up_observation_search_can_only_load) end sphinx_options[:page] = 50 find_options[:page] = 50 end if search_params[:has] # id please if search_params[:has].include?('id_please') sphinx_options[:with][:has_id_please] = true end # has photos if search_params[:has].include?('photos') sphinx_options[:with][:has_photos] = true end # geo if search_params[:has].include?('geo') sphinx_options[:with][:has_geo] = true end end # Bounding box or near point if (!search_params[:swlat].blank? && !search_params[:swlng].blank? && !search_params[:nelat].blank? && !search_params[:nelng].blank?) swlatrads = search_params[:swlat].to_f * (Math::PI / 180) swlngrads = search_params[:swlng].to_f * (Math::PI / 180) nelatrads = search_params[:nelat].to_f * (Math::PI / 180) nelngrads = search_params[:nelng].to_f * (Math::PI / 180) # The box straddles the 180th meridian... # This is a very stupid solution that just chooses the biggest of the # two sides straddling the meridian and queries in that. Sphinx doesn't # seem to support multiple queries on the same attribute, so we can't do # the OR clause we do in the equivalent named scope. Grr. -kueda # 2009-04-10 if swlngrads > 0 && nelngrads < 0 lngrange = swlngrads.abs > nelngrads ? swlngrads..Math::PI : -Math::PI..nelngrads sphinx_options[:with][:longitude] = lngrange # sphinx_options[:with][:longitude] = swlngrads..Math::PI # sphinx_options[:with] = {:longitude => -Math::PI..nelngrads} else sphinx_options[:with][:longitude] = swlngrads..nelngrads end sphinx_options[:with][:latitude] = swlatrads..nelatrads elsif search_params[:lat] && search_params[:lng] latrads = search_params[:lat].to_f * (Math::PI / 180) lngrads = search_params[:lng].to_f * (Math::PI / 180) sphinx_options[:geo] = [latrads, lngrads] sphinx_options[:order] = "@geodist asc" end # identifications case search_params[:identifications] when 'most_agree' sphinx_options[:with][:identifications_most_agree] = true when 'some_agree' sphinx_options[:with][:identifications_some_agree] = true when 'most_disagree' sphinx_options[:with][:identifications_most_disagree] = true end # Taxon ID unless search_params[:taxon_id].blank? sphinx_options[:with][:taxon_id] = search_params[:taxon_id] end # Iconic taxa unless search_params[:iconic_taxa].blank? sphinx_options[:with][:iconic_taxon_id] = \ search_params[:iconic_taxa].map do |iconic_taxon| iconic_taxon.nil? ? nil : iconic_taxon.id end end # User ID unless search_params[:user_id].blank? sphinx_options[:with][:user_id] = search_params[:user_id] end # User login unless search_params[:user].blank? sphinx_options[:with][:user] = search_params[:user] end # Ordering unless search_params[:order_by].blank? # observations.id is a more efficient sql clause, but it's not the name of a field in sphinx search_params[:order_by].gsub!(/observations\.id/, 'created_at') if !sphinx_options[:order].blank? sphinx_options[:order] += ", #{search_params[:order_by]}" sphinx_options[:sort_mode] = :extended elsif search_params[:order_by] =~ /\sdesc|asc/i sphinx_options[:order] = search_params[:order_by].split.first.to_sym sphinx_options[:sort_mode] = search_params[:order_by].split.last.downcase.to_sym else sphinx_options[:order] = search_params[:order_by].to_sym end end unless search_params[:projects].blank? sphinx_options[:with][:projects] = if search_params[:projects].is_a?(String) && search_params[:projects].index(',') search_params[:projects].split(',') else [search_params[:projects]].flatten end end unless search_params[:ofv_params].blank? ofs = search_params[:ofv_params].map do |k,v| v[:observation_field].blank? ? nil : v[:observation_field].id end.compact sphinx_options[:with][:observation_fields] = ofs unless ofs.blank? end # Sanitize query q = sanitize_sphinx_query(@q) # Field-specific searches obs_ids = if @search_on sphinx_options[:conditions] ||= {} # not sure why sphinx chokes on slashes when searching on attributes... sphinx_options[:conditions][@search_on.to_sym] = q.gsub(/\//, '') Observation.search_for_ids(find_options.merge(sphinx_options)) else Observation.search_for_ids(q, find_options.merge(sphinx_options)) end @observations = Observation.where("observations.id in (?)", obs_ids). order_by(search_params[:order_by]). includes(find_options[:include]).scoped # lame hacks unless search_params[:ofv_params].blank? search_params[:ofv_params].each do |k,v| next unless of = v[:observation_field] next if v[:value].blank? v[:observation_field].blank? ? nil : v[:observation_field].id @observations = @observations.has_observation_field(of.id, v[:value]) end end if CONFIG.site_only_observations && params[:site].blank? @observations = @observations.where("observations.uri LIKE ?", "#{root_url}%") end @observations = WillPaginate::Collection.create(obs_ids.current_page, obs_ids.per_page, obs_ids.total_entries) do |pager| pager.replace(@observations.to_a) end begin @observations.total_entries rescue ThinkingSphinx::SphinxError, Riddle::OutOfBoundsError => e Rails.logger.error "[ERROR #{Time.now}] Failed sphinx search: #{e}" @observations = WillPaginate::Collection.new(1,30, 0) end @observations rescue ThinkingSphinx::ConnectionError Rails.logger.error "[ERROR #{Time.now}] Failed to connect to sphinx, falling back to db" get_paginated_observations(search_params, find_options) end # Refresh lists affected by taxon changes in a batch of new/edited # observations. Note that if you don't set @skip_refresh_lists on the records # in @observations before this is called, this won't do anything def refresh_lists_for_batch return true if @observations.blank? taxa = @observations.select(&:skip_refresh_lists).map(&:taxon).uniq.compact return true if taxa.blank? List.delay.refresh_for_user(current_user, :taxa => taxa.map(&:id)) true end # Tries to create a new observation from the specified Facebook photo ID and # update the existing @observation with the new properties, without saving def sync_facebook_photo fb = current_user.facebook_api if fb fbp_json = FacebookPhoto.get_api_response(params[:facebook_photo_id], :user => current_user) @facebook_photo = FacebookPhoto.new_from_api_response(fbp_json) else @facebook_photo = nil end if @facebook_photo && @facebook_photo.owned_by?(current_user) @facebook_observation = @facebook_photo.to_observation sync_attrs = [:description] # facebook strips exif metadata so we can't get geo or observed_on :-/ #, :species_guess, :taxon_id, :observed_on, :observed_on_string, :latitude, :longitude, :place_guess] unless params[:facebook_sync_attrs].blank? sync_attrs = sync_attrs & params[:facebook_sync_attrs] end sync_attrs.each do |sync_attr| # merge facebook_observation with existing observation @observation[sync_attr] ||= @facebook_observation[sync_attr] end unless @observation.observation_photos.detect {|op| op.photo.native_photo_id == @facebook_photo.native_photo_id} @observation.observation_photos.build(:photo => @facebook_photo) end unless @observation.new_record? flash.now[:notice] = t(:preview_of_synced_observation, :url => url_for) end else flash.now[:error] = t(:sorry_we_didnt_find_that_photo) end end # Tries to create a new observation from the specified Flickr photo ID and # update the existing @observation with the new properties, without saving def sync_flickr_photo flickr = get_flickraw begin fp = flickr.photos.getInfo(:photo_id => params[:flickr_photo_id]) @flickr_photo = FlickrPhoto.new_from_flickraw(fp, :user => current_user) rescue FlickRaw::FailedResponse => e Rails.logger.debug "[DEBUG] FlickRaw failed to find photo " + "#{params[:flickr_photo_id]}: #{e}\n#{e.backtrace.join("\n")}" @flickr_photo = nil rescue Timeout::Error => e flash.now[:error] = t(:sorry_flickr_isnt_responding_at_the_moment) Rails.logger.error "[ERROR #{Time.now}] Timeout: #{e}" Airbrake.notify(e, :request => request, :session => session) return end if fp && @flickr_photo && @flickr_photo.valid? @flickr_observation = @flickr_photo.to_observation sync_attrs = %w(description species_guess taxon_id observed_on observed_on_string latitude longitude place_guess map_scale) unless params[:flickr_sync_attrs].blank? sync_attrs = sync_attrs & params[:flickr_sync_attrs] end sync_attrs.each do |sync_attr| # merge flickr_observation with existing observation val = @flickr_observation.send(sync_attr) @observation.send("#{sync_attr}=", val) unless val.blank? end # Note: the following is sort of a hacky alternative to build(). We # need to append a new photo object without saving it, but build() won't # work here b/c Photo and its descedents use STI, and type is a # protected attributes that can't be mass-assigned. unless @observation.observation_photos.detect {|op| op.photo.native_photo_id == @flickr_photo.native_photo_id} @observation.observation_photos.build(:photo => @flickr_photo) end unless @observation.new_record? flash.now[:notice] = t(:preview_of_synced_observation, :url => url_for) end if (@existing_photo = Photo.find_by_native_photo_id(@flickr_photo.native_photo_id)) && (@existing_photo_observation = @existing_photo.observations.first) && @existing_photo_observation.id != @observation.id msg = t(:heads_up_this_photo_is_already_associated_with, :url => url_for(@existing_photo_observation)) flash.now[:notice] = flash.now[:notice].blank? ? msg : "#{flash.now[:notice]}<br/>#{msg}" end else flash.now[:error] = t(:sorry_we_didnt_find_that_photo) end end def sync_picasa_photo begin api_response = PicasaPhoto.get_api_response(params[:picasa_photo_id], :user => current_user) rescue Timeout::Error => e flash.now[:error] = t(:sorry_picasa_isnt_responding_at_the_moment) Rails.logger.error "[ERROR #{Time.now}] Timeout: #{e}" Airbrake.notify(e, :request => request, :session => session) return end unless api_response Rails.logger.debug "[DEBUG] Failed to find Picasa photo for #{params[:picasa_photo_id]}" return end @picasa_photo = PicasaPhoto.new_from_api_response(api_response, :user => current_user) if @picasa_photo && @picasa_photo.valid? @picasa_observation = @picasa_photo.to_observation sync_attrs = PHOTO_SYNC_ATTRS unless params[:picasa_sync_attrs].blank? sync_attrs = sync_attrs & params[:picasa_sync_attrs] end sync_attrs.each do |sync_attr| @observation.send("#{sync_attr}=", @picasa_observation.send(sync_attr)) end unless @observation.observation_photos.detect {|op| op.photo.native_photo_id == @picasa_photo.native_photo_id} @observation.observation_photos.build(:photo => @picasa_photo) end flash.now[:notice] = t(:preview_of_synced_observation, :url => url_for) else flash.now[:error] = t(:sorry_we_didnt_find_that_photo) end end def sync_local_photo unless @local_photo = Photo.find_by_id(params[:local_photo_id]) flash.now[:error] = t(:that_photo_doesnt_exist) return end if @local_photo.metadata.blank? flash.now[:error] = t(:sorry_we_dont_have_any_metadata_for_that_photo) return end o = @local_photo.to_observation PHOTO_SYNC_ATTRS.each do |sync_attr| @observation.send("#{sync_attr}=", o.send(sync_attr)) end unless @observation.observation_photos.detect {|op| op.photo_id == @local_photo.id} @observation.observation_photos.build(:photo => @local_photo) end unless @observation.new_record? flash.now[:notice] = t(:preview_of_synced_observation, :url => url_for) end if @existing_photo_observation = @local_photo.observations.where("observations.id != ?", @observation).first msg = t(:heads_up_this_photo_is_already_associated_with, :url => url_for(@existing_photo_observation)) flash.now[:notice] = flash.now[:notice].blank? ? msg : "#{flash.now[:notice]}<br/>#{msg}" end end def load_photo_identities unless logged_in? @photo_identity_urls = [] @photo_identities = [] return true end @photo_identities = Photo.descendent_classes.map do |klass| assoc_name = klass.to_s.underscore.split('_').first + "_identity" current_user.send(assoc_name) if current_user.respond_to?(assoc_name) end.compact reference_photo = @observation.try(:observation_photos).try(:first).try(:photo) reference_photo ||= @observations.try(:first).try(:observation_photos).try(:first).try(:photo) reference_photo ||= current_user.photos.order("id ASC").last if reference_photo assoc_name = reference_photo.class.to_s.underscore.split('_').first + "_identity" @default_photo_identity = current_user.send(assoc_name) if current_user.respond_to?(assoc_name) end if params[:facebook_photo_id] if @default_photo_identity = @photo_identities.detect{|pi| pi.to_s =~ /facebook/i} @default_photo_source = 'facebook' end elsif params[:flickr_photo_id] if @default_photo_identity = @photo_identities.detect{|pi| pi.to_s =~ /flickr/i} @default_photo_source = 'flickr' end end @default_photo_identity ||= @photo_identities.first @default_photo_source ||= if @default_photo_identity && @default_photo_identity.class.name =~ /Identity/ @default_photo_identity.class.name.underscore.humanize.downcase.split.first elsif @default_photo_identity "facebook" end @default_photo_identity_url = nil @photo_identity_urls = @photo_identities.map do |identity| provider_name = if identity.is_a?(ProviderAuthorization) identity.provider_name else identity.class.to_s.underscore.split('_').first # e.g. FlickrIdentity=>'flickr' end url = "/#{provider_name.downcase}/photo_fields?context=user" @default_photo_identity_url = url if identity == @default_photo_identity "{title: '#{provider_name.capitalize}', url: '#{url}'}" end @photo_sources = @photo_identities.inject({}) do |memo, ident| if ident.respond_to?(:source_options) memo[ident.class.name.underscore.humanize.downcase.split.first] = ident.source_options else memo[:facebook] = { :title => 'Facebook', :url => '/facebook/photo_fields', :contexts => [ ["Your photos", 'user'] ] } end memo end end def load_observation render_404 unless @observation = Observation.find_by_id(params[:id] || params[:observation_id], :include => [ :photos, {:taxon => [:taxon_names]}, :identifications ] ) end def require_owner unless logged_in? && current_user.id == @observation.user_id msg = t(:you_dont_have_permission_to_do_that) respond_to do |format| format.html do flash[:error] = msg return redirect_to @observation end format.json do return render :json => {:error => msg} end end end end def render_observations_to_json(options = {}) if (partial = params[:partial]) && PARTIALS.include?(partial) data = @observations.map do |observation| item = { :instance => observation, :extra => { :taxon => observation.taxon, :iconic_taxon => observation.iconic_taxon, :user => {:login => observation.user.login} } } item[:html] = view_context.render_in_format(:html, :partial => partial, :object => observation) item end render :json => data else opts = options opts[:methods] ||= [] opts[:methods] += [:short_description, :user_login, :iconic_taxon_name, :tag_list] opts[:methods].uniq! opts[:include] ||= {} if @ofv_params opts[:include][:observation_field_values] ||= { :except => [:observation_field_id], :include => { :observation_field => { :only => [:id, :datatype, :name] } } } end opts[:include][:taxon] ||= { :only => [:id, :name, :rank, :ancestry] } opts[:include][:iconic_taxon] ||= {:only => [:id, :name, :rank, :rank_level, :ancestry]} opts[:include][:user] ||= {:only => :login} opts[:include][:photos] ||= { :methods => [:license_code, :attribution], :except => [:original_url, :file_processing, :file_file_size, :file_content_type, :file_file_name, :mobile, :metadata] } pagination_headers_for(@observations) if @observations.respond_to?(:scoped) @observations = @observations.includes({:observation_photos => :photo}, :photos, :iconic_taxon) end render :json => @observations.to_json(opts) end end def render_observations_to_csv(options = {}) first = %w(scientific_name datetime description place_guess latitude longitude tag_list common_name url image_url user_login) only = (first + Observation::CSV_COLUMNS).uniq except = %w(map_scale timeframe iconic_taxon_id delta geom user_agent cached_tag_list) unless options[:show_private] == true except += %w(private_latitude private_longitude private_positional_accuracy) end only = only - except unless @ofv_params.blank? only += @ofv_params.map{|k,v| "field:#{v[:normalized_name]}"} if @observations.respond_to?(:scoped) @observations = @observations.includes(:observation_field_values => :observation_field) end end @observations = @observations.includes(:tags) if @observations.respond_to?(:scoped) render :text => @observations.to_csv(:only => only.map{|c| c.to_sym}) end def render_observations_to_kml(options = {}) @net_hash = options if params[:kml_type] == "network_link" @net_hash = { :id => "AllObs", :link_id =>"AllObs", :snippet => "#{CONFIG.site_name} Feed for Everyone", :description => "#{CONFIG.site_name} Feed for Everyone", :name => "#{CONFIG.site_name} Feed for Everyone", :href => "#{root_url}#{request.fullpath}".gsub(/kml_type=network_link/, '') } render :layout => false, :action => 'network_link' return end render :layout => false, :action => "index" end # create project observations if a project was specified and project allows # auto-joining def create_project_observations return unless params[:project_id] @project = Project.find_by_id(params[:project_id]) @project ||= Project.find(params[:project_id]) rescue nil return unless @project @project_user = current_user.project_users.find_or_create_by_project_id(@project.id) return unless @project_user && @project_user.valid? tracking_code = params[:tracking_code] if @project.tracking_code_allowed?(params[:tracking_code]) errors = [] @observations.each do |observation| next if observation.new_record? po = @project.project_observations.build(:observation => observation, :tracking_code => tracking_code) unless po.save errors = (errors + po.errors.full_messages).uniq end end if !errors.blank? if request.format.html? flash[:error] = t(:your_observations_couldnt_be_added_to_that_project, :errors => errors.to_sentence) else Rails.logger.error "[ERROR #{Time.now}] Failed to add #{@observations.size} obs to #{@project}: #{errors.to_sentence}" end end end def update_user_account current_user.update_attributes(params[:user]) unless params[:user].blank? end def render_observations_partial(partial) if @observations.empty? render(:text => '') else render(:partial => partial, :collection => @observations, :layout => false) end end def load_prefs @prefs = current_preferences if request.format && request.format.html? @view = params[:view] || current_user.try(:preferred_observations_view) || 'map' end end def site_search_params(search_params = {}) if CONFIG.site_only_observations && params[:site].blank? search_params[:site] ||= FakeView.root_url @site ||= search_params[:site] end if (site_bounds = CONFIG.bounds) && params[:swlat].nil? search_params[:nelat] ||= site_bounds['nelat'] search_params[:nelng] ||= site_bounds['nelng'] search_params[:swlat] ||= site_bounds['swlat'] search_params[:swlng] ||= site_bounds['swlng'] @nelat ||= site_bounds['nelat'] @nelng ||= site_bounds['nelng'] @swlat ||= site_bounds['swlat'] @swlng ||= site_bounds['swlng'] end search_params end def delayed_csv(path_for_csv, parent, options = {}) if parent.observations.count < 50 Observation.generate_csv_for(parent, :path => path_for_csv) render :file => path_for_csv else cache_key = Observation.generate_csv_for_cache_key(parent) job_id = Rails.cache.read(cache_key) job = Delayed::Job.find_by_id(job_id) if job # Still working elsif File.exists? path_for_csv render :file => path_for_csv return else # no job id, no job, let's get this party started Rails.cache.delete(cache_key) job = Observation.delay.generate_csv_for(parent, :path => path_for_csv, :user => current_user) Rails.cache.write(cache_key, job.id, :expires_in => 1.hour) end prevent_caching render :status => :accepted, :text => "This file takes a little while to generate. It should be ready shortly at #{request.url}" end end end
#encoding: utf-8 class ObservationsController < ApplicationController skip_before_action :verify_authenticity_token, only: :index, if: :json_request? protect_from_forgery unless: -> { request.format.widget? } #, except: [:stats, :user_stags, :taxa] before_filter :decide_if_skipping_preloading, only: [ :index ] before_filter :allow_external_iframes, only: [:stats, :user_stats, :taxa, :map] before_filter :allow_cors, only: [:index], 'if': -> { Rails.env.development? } WIDGET_CACHE_EXPIRATION = 15.minutes caches_action :of, :expires_in => 1.day, :cache_path => Proc.new {|c| c.params.merge(:locale => I18n.locale)}, :if => Proc.new {|c| c.request.format != :html } cache_sweeper :observation_sweeper, :only => [:create, :update, :destroy] rescue_from ::AbstractController::ActionNotFound do unless @selected_user = User.find_by_login(params[:action]) return render_404 end by_login end before_action :doorkeeper_authorize!, only: [ :create, :update, :destroy, :viewed_updates, :update_fields, :review ], if: lambda { authenticate_with_oauth? } before_filter :load_user_by_login, :only => [:by_login, :by_login_all] before_filter :return_here, :only => [:index, :by_login, :show, :import, :export, :add_from_list, :new, :project] before_filter :authenticate_user!, :unless => lambda { authenticated_with_oauth? }, :except => [:explore, :index, :of, :show, :by_login, :nearby, :widget, :project, :stats, :taxa, :taxon_stats, :user_stats, :community_taxon_summary, :map] load_only = [ :show, :edit, :edit_photos, :update_photos, :destroy, :fields, :viewed_updates, :community_taxon_summary, :update_fields, :review ] before_filter :load_observation, :only => load_only blocks_spam :only => load_only, :instance => :observation before_filter :require_owner, :only => [:edit, :edit_photos, :update_photos, :destroy] before_filter :curator_required, :only => [:curation, :accumulation, :phylogram] before_filter :load_photo_identities, :only => [:new, :new_batch, :show, :new_batch_csv,:edit, :update, :edit_batch, :create, :import, :import_photos, :import_sounds, :new_from_list] before_filter :load_sound_identities, :only => [:new, :new_batch, :show, :new_batch_csv,:edit, :update, :edit_batch, :create, :import, :import_photos, :import_sounds, :new_from_list] before_filter :photo_identities_required, :only => [:import_photos] after_filter :refresh_lists_for_batch, :only => [:create, :update] MOBILIZED = [:add_from_list, :nearby, :add_nearby, :project, :by_login, :index, :show] before_filter :unmobilized, :except => MOBILIZED before_filter :mobilized, :only => MOBILIZED before_filter :load_prefs, :only => [:index, :project, :by_login] ORDER_BY_FIELDS = %w"created_at observed_on project species_guess votes id" REJECTED_FEED_PARAMS = %w"page view filters_open partial action id locale" REJECTED_KML_FEED_PARAMS = REJECTED_FEED_PARAMS + %w"swlat swlng nelat nelng BBOX" MAP_GRID_PARAMS_TO_CONSIDER = REJECTED_KML_FEED_PARAMS + %w( order order_by taxon_id taxon_name projects user_id place_id utf8 d1 d2 ) DISPLAY_ORDER_BY_FIELDS = { 'created_at' => 'date added', 'observations.id' => 'date added', 'id' => 'date added', 'observed_on' => 'date observed', 'species_guess' => 'species name', 'project' => "date added to project", 'votes' => 'faves' } PARTIALS = %w(cached_component observation_component observation mini project_observation) EDIT_PARTIALS = %w(add_photos) PHOTO_SYNC_ATTRS = [:description, :species_guess, :taxon_id, :observed_on, :observed_on_string, :latitude, :longitude, :place_guess] # GET /observations # GET /observations.xml def index if !logged_in? && params[:page].to_i > 100 authenticate_user! return false end params = request.params showing_partial = (params[:partial] && PARTIALS.include?(params[:partial])) # the new default /observations doesn't need any observations # looked up now as it will use Angular/Node. This is for legacy # API methods, and HTML/views and partials if request.format.html? &&!request.format.mobile? && !showing_partial params = params else h = observations_index_search(params) params = h[:params] search_params = h[:search_params] @observations = h[:observations] end respond_to do |format| format.html do if showing_partial pagination_headers_for(@observations) return render_observations_partial(params[:partial]) end # one of the few things we do in Rails. Look up the taxon_name param unless params[:taxon_name].blank? sn = params[:taxon_name].to_s.strip.gsub(/[\s_]+/, ' ').downcase if t = TaxonName.where("lower(name) = ?", sn).first.try(:taxon) params[:taxon_id] = t.id end end render layout: "bootstrap", locals: { params: params } end format.json do Observation.preload_for_component(@observations, logged_in: logged_in?) Observation.preload_associations(@observations, :tags) render_observations_to_json end format.mobile format.geojson do render :json => @observations.to_geojson(:except => [ :geom, :latitude, :longitude, :map_scale, :num_identification_agreements, :num_identification_disagreements, :delta, :location_is_exact]) end format.atom do @updated_at = Observation.last.updated_at end format.dwc do Observation.preload_for_component(@observations, logged_in: logged_in?) Observation.preload_associations(@observations, [ :identifications ]) end format.csv do render_observations_to_csv end format.kml do render_observations_to_kml( :snippet => "#{CONFIG.site_name} Feed for Everyone", :description => "#{CONFIG.site_name} Feed for Everyone", :name => "#{CONFIG.site_name} Feed for Everyone" ) end format.widget do if params[:markup_only] == 'true' render :js => render_to_string(:partial => "widget.html.erb", :locals => { :show_user => true, :target => params[:target], :default_image => params[:default_image], :silence => params[:silence] }) else render :js => render_to_string(:partial => "widget.js.erb", :locals => { :show_user => true }) end end end end def of if request.format == :html redirect_to observations_path(:taxon_id => params[:id]) return end unless @taxon = Taxon.find_by_id(params[:id].to_i) render_404 && return end @observations = Observation.of(@taxon). includes([ :user, :iconic_taxon, { :taxon => :taxon_descriptions }, { :observation_photos => :photo } ]). order("observations.id desc"). limit(500).sort_by{|o| [o.quality_grade == "research" ? 1 : 0, o.id]} respond_to do |format| format.json do render :json => @observations.to_json( :methods => [ :user_login, :iconic_taxon_name, :obs_image_url], :include => [ { :user => { :only => :login } }, :taxon, :iconic_taxon ] ) end format.geojson do render :json => @observations.to_geojson(:except => [ :geom, :latitude, :longitude, :map_scale, :num_identification_agreements, :num_identification_disagreements, :delta, :location_is_exact]) end end end # GET /observations/1 # GET /observations/1.xml def show unless @skipping_preloading @quality_metrics = @observation.quality_metrics.includes(:user) if logged_in? @previous = Observation.page_of_results({ user_id: @observation.user.id, per_page: 1, max_id: @observation.id - 1, order_by: "id", order: "desc" }).first @prev = @previous @next = Observation.page_of_results({ user_id: @observation.user.id, per_page: 1, min_id: @observation.id + 1, order_by: "id", order: "asc" }).first @user_quality_metrics = @observation.quality_metrics.select{|qm| qm.user_id == current_user.id} @project_invitations = @observation.project_invitations.limit(100).to_a @project_invitations_by_project_id = @project_invitations.index_by(&:project_id) end @coordinates_viewable = @observation.coordinates_viewable_by?(current_user) end respond_to do |format| format.html do if params[:partial] == "cached_component" return render(partial: "cached_component", object: @observation, layout: false) end # always display the time in the zone in which is was observed Time.zone = @observation.user.time_zone @identifications = @observation.identifications.includes(:user, :taxon => :photos) @current_identifications = @identifications.select{|o| o.current?} @owners_identification = @current_identifications.detect do |ident| ident.user_id == @observation.user_id end @community_identification = if @observation.community_taxon Identification.new(:taxon => @observation.community_taxon, :observation => @observation) end if logged_in? @viewers_identification = @current_identifications.detect do |ident| ident.user_id == current_user.id end end @current_identifications_by_taxon = @current_identifications.select do |ident| ident.user_id != ident.observation.user_id end.group_by{|i| i.taxon} @sorted_current_identifications_by_taxon = @current_identifications_by_taxon.sort_by do |row| row.last.size end.reverse if logged_in? @projects = current_user.project_users.includes(:project).joins(:project).limit(1000).order("lower(projects.title)").map(&:project) @project_addition_allowed = @observation.user_id == current_user.id @project_addition_allowed ||= @observation.user.preferred_project_addition_by != User::PROJECT_ADDITION_BY_NONE end @places = @coordinates_viewable ? @observation.places : @observation.public_places @project_observations = @observation.project_observations.joins(:project).limit(100).to_a @project_observations_by_project_id = @project_observations.index_by(&:project_id) @comments_and_identifications = (@observation.comments.all + @identifications).sort_by{|r| r.created_at} @photos = @observation.observation_photos.includes(:photo => [:flags]).sort_by do |op| op.position || @observation.observation_photos.size + op.id.to_i end.map{|op| op.photo}.compact @flagged_photos = @photos.select{|p| p.flagged?} @sounds = @observation.sounds.all if @observation.observed_on @day_observations = Observation.by(@observation.user).on(@observation.observed_on) .includes([ :photos, :user ]) .paginate(:page => 1, :per_page => 14) end if logged_in? @subscription = @observation.update_subscriptions.where(user: current_user).first end @observation_links = @observation.observation_links.sort_by{|ol| ol.href} @posts = @observation.posts.published.limit(50) if @observation.taxon unless @places.blank? @listed_taxon = ListedTaxon. joins(:place). where([ "taxon_id = ? AND place_id IN (?) AND establishment_means IS NOT NULL", @observation.taxon_id, @places ]). order("establishment_means IN ('endemic', 'introduced') DESC, places.bbox_area ASC").first @conservation_status = ConservationStatus. where(:taxon_id => @observation.taxon).where("place_id IN (?)", @places). where("iucn >= ?", Taxon::IUCN_NEAR_THREATENED). includes(:place).first end @conservation_status ||= ConservationStatus.where(:taxon_id => @observation.taxon).where("place_id IS NULL"). where("iucn >= ?", Taxon::IUCN_NEAR_THREATENED).first end @observer_provider_authorizations = @observation.user.provider_authorizations @shareable_image_url = if !@photos.blank? && photo = @photos.detect{|p| p.medium_url =~ /^http/} FakeView.image_url(photo.best_url(:original)) else FakeView.iconic_taxon_image_url(@observation.taxon, :size => 200) end @shareable_title = if !@observation.species_guess.blank? @observation.species_guess elsif @observation.taxon if comname = FakeView.common_taxon_name( @observation.taxon, place: @site.try(:place) ).try(:name) "#{comname} (#{@observation.taxon.name})" else @observation.taxon.name end else I18n.t( "something" ) end @shareable_description = @observation.to_plain_s( no_place_guess: !@coordinates_viewable ) @shareable_description += ".\n\n#{@observation.description}" unless @observation.description.blank? if logged_in? user_viewed_updates end if params[:test] == "idcats" && logged_in? leading_taxon_ids = @identifications.select(&:leading?).map(&:taxon_id) if leading_taxon_ids.size > 0 sql = <<-SQL SELECT user_id, count(*) AS ident_count FROM identifications WHERE category = 'improving' AND taxon_id IN (#{leading_taxon_ids.join( "," )}) GROUP BY user_id HAVING count(*) > 0 ORDER BY count(*) DESC LIMIT 10 SQL @users_who_can_help = User.joins( "JOIN (#{sql}) AS ident_users ON ident_users.user_id = users.id" ).order("ident_count DESC").limit(10) elsif @observation.taxon && @observation.taxon.rank_level > Taxon::SPECIES_LEVEL sql = <<-SQL SELECT user_id, count(*) AS ident_count FROM identifications LEFT OUTER JOIN taxon_ancestors ta ON ta.taxon_id = identifications.taxon_id WHERE category = 'improving' AND ta.ancestor_taxon_id = #{@observation.taxon_id} GROUP BY user_id HAVING count(*) > 0 ORDER BY count(*) DESC LIMIT 10 SQL @users_who_can_help = User.joins( "JOIN (#{sql}) AS ident_users ON ident_users.user_id = users.id" ).order("ident_count DESC").limit(10) end end if params[:partial] return render(:partial => params[:partial], :object => @observation, :layout => false) end end format.mobile format.xml { render :xml => @observation } format.json do taxon_options = Taxon.default_json_options taxon_options[:methods] += [:iconic_taxon_name, :image_url, :common_name, :default_name] render :json => @observation.to_json( :viewer => current_user, :methods => [:user_login, :iconic_taxon_name, :captive_flag], :include => { :user => User.default_json_options, :observation_field_values => {:include => {:observation_field => {:only => [:name]}}}, :project_observations => { :include => { :project => { :only => [:id, :title, :description], :methods => [:icon_url] } } }, :observation_photos => { :include => { :photo => { :methods => [:license_code, :attribution], :except => [:original_url, :file_processing, :file_file_size, :file_content_type, :file_file_name, :mobile, :metadata, :user_id, :native_realname, :native_photo_id] } } }, :comments => { :include => { :user => { :only => [:name, :login, :id], :methods => [:user_icon_url] } } }, :taxon => taxon_options, :identifications => { :include => { :user => { :only => [:name, :login, :id], :methods => [:user_icon_url] }, :taxon => taxon_options } }, :faves => { :only => [:created_at], :include => { :user => { :only => [:name, :login, :id], :methods => [:user_icon_url] } } } }) end format.atom do cache end end end # GET /observations/new # GET /observations/new.xml # An attempt at creating a simple new page for batch add def new @observation = Observation.new(:user => current_user) @observation.time_zone = current_user.time_zone if params[:copy] && (copy_obs = Observation.find_by_id(params[:copy])) && copy_obs.user_id == current_user.id %w(observed_on_string time_zone place_guess geoprivacy map_scale positional_accuracy).each do |a| @observation.send("#{a}=", copy_obs.send(a)) end @observation.latitude = copy_obs.private_latitude || copy_obs.latitude @observation.longitude = copy_obs.private_longitude || copy_obs.longitude copy_obs.observation_photos.each do |op| @observation.observation_photos.build(:photo => op.photo) end copy_obs.observation_field_values.each do |ofv| @observation.observation_field_values.build(:observation_field => ofv.observation_field, :value => ofv.value) end end @taxon = Taxon.find_by_id(params[:taxon_id].to_i) unless params[:taxon_id].blank? unless params[:taxon_name].blank? @taxon ||= TaxonName.where("lower(name) = ?", params[:taxon_name].to_s.strip.gsub(/[\s_]+/, ' ').downcase). first.try(:taxon) end if !params[:project_id].blank? @project = if params[:project_id].to_i == 0 Project.includes(:project_observation_fields => :observation_field).find(params[:project_id]) else Project.includes(:project_observation_fields => :observation_field).find_by_id(params[:project_id].to_i) end if @project @place = @project.place @project_curators = @project.project_users.where("role IN (?)", [ProjectUser::MANAGER, ProjectUser::CURATOR]) @tracking_code = params[:tracking_code] if @project.tracking_code_allowed?(params[:tracking_code]) @kml_assets = @project.project_assets.select{|pa| pa.asset_file_name =~ /\.km[lz]$/} end end @place ||= Place.find(params[:place_id]) unless params[:place_id].blank? rescue nil if @place @place_geometry = PlaceGeometry.without_geom.where(place_id: @place).first end if params[:facebook_photo_id] begin sync_facebook_photo rescue Koala::Facebook::APIError => e raise e unless e.message =~ /OAuthException/ redirect_to ProviderAuthorization::AUTH_URLS['facebook'] return end end sync_flickr_photo if params[:flickr_photo_id] && current_user.flickr_identity sync_picasa_photo if params[:picasa_photo_id] && current_user.picasa_identity sync_local_photo if params[:local_photo_id] @welcome = params[:welcome] # this should happen AFTER photo syncing so params can override attrs # from the photo [:latitude, :longitude, :place_guess, :location_is_exact, :map_scale, :positional_accuracy, :positioning_device, :positioning_method, :observed_on_string].each do |obs_attr| next if params[obs_attr].blank? # sync_photo indicates that the user clicked sync photo, so presumably they'd # like the photo attrs to override the URL # invite links are the other case, in which URL params *should* override the # photo attrs b/c the person who made the invite link chose a taxon or something if params[:sync_photo] @observation.send("#{obs_attr}=", params[obs_attr]) if @observation.send(obs_attr).blank? else @observation.send("#{obs_attr}=", params[obs_attr]) end end if @taxon @observation.taxon = @taxon @observation.species_guess = if @taxon.common_name @taxon.common_name.name else @taxon.name end elsif !params[:taxon_name].blank? @observation.species_guess = params[:taxon_name] end @observation_fields = ObservationField.recently_used_by(current_user).limit(10) respond_to do |format| format.html do @observations = [@observation] end format.json { render :json => @observation } end end # GET /observations/1/edit def edit # Only the owner should be able to see this. unless current_user.id == @observation.user_id or current_user.is_admin? redirect_to observation_path(@observation) return end # Make sure user is editing the REAL coordinates if @observation.coordinates_obscured? @observation.latitude = @observation.private_latitude @observation.longitude = @observation.private_longitude @observation.place_guess = @observation.private_place_guess end if params[:facebook_photo_id] begin sync_facebook_photo rescue Koala::Facebook::APIError => e raise e unless e.message =~ /OAuthException/ redirect_to ProviderAuthorization::AUTH_URLS['facebook'] return end end sync_flickr_photo if params[:flickr_photo_id] sync_picasa_photo if params[:picasa_photo_id] sync_local_photo if params[:local_photo_id] @observation_fields = ObservationField.recently_used_by(current_user).limit(10) if @observation.quality_metrics.detect{|qm| qm.user_id == @observation.user_id && qm.metric == QualityMetric::WILD && !qm.agree?} @observation.captive_flag = true end if params[:interpolate_coordinates].yesish? @observation.interpolate_coordinates end respond_to do |format| format.html do if params[:partial] && EDIT_PARTIALS.include?(params[:partial]) return render(:partial => params[:partial], :object => @observation, :layout => false) end end end end # POST /observations # POST /observations.xml def create # Handle the case of a single obs params[:observations] = [['0', params[:observation]]] if params[:observation] if params[:observations].blank? && params[:observation].blank? respond_to do |format| format.html do flash[:error] = t(:no_observations_submitted) redirect_to new_observation_path end format.json { render :status => :unprocessable_entity, :json => "No observations submitted!" } end return end @observations = params[:observations].map do |fieldset_index, observation| next if observation.blank? observation.delete('fieldset_index') if observation[:fieldset_index] o = unless observation[:uuid].blank? current_user.observations.where( uuid: observation[:uuid] ).first end # when we add UUIDs to everything and either stop using strings or # ensure that everything is lowercase, we can stop doing this if o.blank? && !observation[:uuid].blank? o = current_user.observations.where( uuid: observation[:uuid].downcase ).first end o ||= Observation.new o.assign_attributes(observation_params(observation)) o.user = current_user o.user_agent = request.user_agent unless o.site_id o.site = @site || current_user.site o.site = o.site.becomes(Site) if o.site end if doorkeeper_token && (a = doorkeeper_token.application) o.oauth_application = a.becomes(OauthApplication) end # Get photos photos = [] Photo.subclasses.each do |klass| klass_key = klass.to_s.underscore.pluralize.to_sym if params[klass_key] && params[klass_key][fieldset_index] photos += retrieve_photos(params[klass_key][fieldset_index], :user => current_user, :photo_class => klass) end if params["#{klass_key}_to_sync"] && params["#{klass_key}_to_sync"][fieldset_index] if photo = photos.to_a.compact.last photo_o = photo.to_observation PHOTO_SYNC_ATTRS.each do |a| o.send("#{a}=", photo_o.send(a)) if o.send(a).blank? end end end end photo = photos.compact.last if o.new_record? && photo && photo.respond_to?(:to_observation) && !params[:uploader] && (o.observed_on_string.blank? || o.latitude.blank? || o.taxon.blank?) photo_o = photo.to_observation if o.observed_on_string.blank? o.observed_on_string = photo_o.observed_on_string o.observed_on = photo_o.observed_on o.time_observed_at = photo_o.time_observed_at end if o.latitude.blank? o.latitude = photo_o.latitude o.longitude = photo_o.longitude end o.taxon = photo_o.taxon if o.taxon.blank? o.species_guess = photo_o.species_guess if o.species_guess.blank? end o.photos = photos.map{ |p| p.new_record? && !p.is_a?(LocalPhoto) ? Photo.local_photo_from_remote_photo(p) : p } o.sounds << Sound.from_observation_params(params, fieldset_index, current_user) o end current_user.observations << @observations.compact create_project_observations update_user_account # check for errors errors = false if params[:uploader] @observations.compact.each { |obs| obs.errors.delete(:project_observations) errors = true if obs.errors.any? } else @observations.compact.each { |obs| errors = true unless obs.valid? } end respond_to do |format| format.html do unless errors flash[:notice] = params[:success_msg] || t(:observations_saved) if params[:commit] == t(:save_and_add_another) o = @observations.first redirect_to :action => 'new', :latitude => o.coordinates_obscured? ? o.private_latitude : o.latitude, :longitude => o.coordinates_obscured? ? o.private_longitude : o.longitude, :place_guess => o.place_guess, :observed_on_string => o.observed_on_string, :location_is_exact => o.location_is_exact, :map_scale => o.map_scale, :positional_accuracy => o.positional_accuracy, :positioning_method => o.positioning_method, :positioning_device => o.positioning_device, :project_id => params[:project_id] elsif @observations.size == 1 redirect_to observation_path(@observations.first) else redirect_to :action => self.current_user.login end else if @observations.size == 1 if @project @place = @project.place @project_curators = @project.project_users.where("role IN (?)", [ProjectUser::MANAGER, ProjectUser::CURATOR]) @tracking_code = params[:tracking_code] if @project.tracking_code_allowed?(params[:tracking_code]) @kml_assets = @project.project_assets.select{|pa| pa.asset_file_name =~ /\.km[lz]$/} end render :action => 'new' else render :action => 'edit_batch' end end end format.json do if errors json = if @observations.size == 1 && is_iphone_app_2? {:error => @observations.map{|o| o.errors.full_messages}.flatten.uniq.compact.to_sentence} else {:errors => @observations.map{|o| o.errors.full_messages}} end render :json => json, :status => :unprocessable_entity else Observation.refresh_es_index if @observations.size == 1 && is_iphone_app_2? render :json => @observations[0].to_json( :viewer => current_user, :methods => [:user_login, :iconic_taxon_name], :include => { :taxon => Taxon.default_json_options } ) else render :json => @observations.to_json(viewer: current_user, methods: [ :user_login, :iconic_taxon_name, :project_observations ]) end end end end end # PUT /observations/1 # PUT /observations/1.xml def update observation_user = current_user unless params[:admin_action].nil? || !current_user.is_admin? observation_user = Observation.find(params[:id]).user end # Handle the case of a single obs if params[:observation] params[:observations] = [[params[:id], params[:observation]]] elsif params[:id] && params[:observations] params[:observations] = [[params[:id], params[:observations][0]]] end if params[:observations].blank? && params[:observation].blank? respond_to do |format| format.html do flash[:error] = t(:no_observations_submitted) redirect_to new_observation_path end format.json { render :status => :unprocessable_entity, :json => "No observations submitted!" } end return end @observations = Observation.where(id: params[:observations].map{ |k,v| k }, user_id: observation_user) # Make sure there's no evil going on unique_user_ids = @observations.map(&:user_id).uniq more_than_one_observer = unique_user_ids.size > 1 admin_action = unique_user_ids.first != observation_user.id && current_user.has_role?(:admin) if !@observations.blank? && more_than_one_observer && !admin_action msg = t(:you_dont_have_permission_to_edit_that_observation) respond_to do |format| format.html do flash[:error] = msg redirect_to(@observation || observations_path) end format.json do render :status => :unprocessable_entity, :json => {:error => msg} end end return end # Convert the params to a hash keyed by ID. Yes, it's weird hashed_params = Hash[*params[:observations].to_a.flatten] errors = false extra_msg = nil @observations.each_with_index do |observation,i| fieldset_index = observation.id.to_s # Update the flickr photos # Note: this ignore photos thing is a total hack and should only be # included if you are updating observations but aren't including flickr # fields, e.g. when removing something from ID please if !params[:ignore_photos] && !is_mobile_app? # Get photos updated_photos = [] old_photo_ids = observation.photo_ids Photo.subclasses.each do |klass| klass_key = klass.to_s.underscore.pluralize.to_sym next if klass_key.blank? if params[klass_key] && params[klass_key][fieldset_index] updated_photos += retrieve_photos(params[klass_key][fieldset_index], :user => current_user, :photo_class => klass, :sync => true) end end if updated_photos.empty? observation.photos.clear else observation.photos = updated_photos.map{ |p| p.new_record? && !p.is_a?(LocalPhoto) ? Photo.local_photo_from_remote_photo(p) : p } end Photo.subclasses.each do |klass| klass_key = klass.to_s.underscore.pluralize.to_sym next unless params["#{klass_key}_to_sync"] && params["#{klass_key}_to_sync"][fieldset_index] next unless photo = observation.photos.last photo_o = photo.to_observation PHOTO_SYNC_ATTRS.each do |a| hashed_params[observation.id.to_s] ||= {} if hashed_params[observation.id.to_s][a].blank? && observation.send(a).blank? hashed_params[observation.id.to_s][a] = photo_o.send(a) end end end end # Kind of like :ignore_photos, but :editing_sounds makes it opt-in rather than opt-out # If editing sounds and no sound parameters are present, assign to an empty array # This way, sounds will be removed if params[:editing_sounds] params[:soundcloud_sounds] ||= {fieldset_index => []} params[:soundcloud_sounds][fieldset_index] ||= [] observation.sounds = Sound.from_observation_params(params, fieldset_index, current_user) end unless observation.update_attributes(observation_params(hashed_params[observation.id.to_s])) errors = true end if !errors && params[:project_id] && !observation.project_observations.where(:project_id => params[:project_id]).exists? if @project ||= Project.find(params[:project_id]) project_observation = ProjectObservation.create(:project => @project, :observation => observation) extra_msg = if project_observation.valid? "Successfully added to #{@project.title}" else "Failed to add to #{@project.title}: #{project_observation.errors.full_messages.to_sentence}" end end end end respond_to do |format| if errors format.html do if @observations.size == 1 @observation = @observations.first render :action => 'edit' else render :action => 'edit_batch' end end format.xml { render :xml => @observations.collect(&:errors), :status => :unprocessable_entity } format.json do render :status => :unprocessable_entity, :json => { :error => @observations.map{|o| o.errors.full_messages.to_sentence}.to_sentence, :errors => @observations.collect(&:errors) } end elsif @observations.empty? msg = if params[:id] t(:that_observation_no_longer_exists) else t(:those_observations_no_longer_exist) end format.html do flash[:error] = msg redirect_back_or_default(observations_by_login_path(current_user.login)) end format.json { render :json => {:error => msg}, :status => :gone } else format.html do flash[:notice] = "#{t(:observations_was_successfully_updated)} #{extra_msg}" if @observations.size == 1 redirect_to observation_path(@observations.first) else redirect_to observations_by_login_path(observation_user.login) end end format.xml { head :ok } format.js { render :json => @observations } format.json do Observation.refresh_es_index if @observations.size == 1 && is_iphone_app_2? render :json => @observations[0].to_json( viewer: current_user, methods: [:user_login, :iconic_taxon_name], include: { taxon: Taxon.default_json_options, observation_field_values: {}, project_observations: { include: { project: { only: [:id, :title, :description], methods: [:icon_url] } } }, observation_photos: { include: { photo: { methods: [:license_code, :attribution], except: [:original_url, :file_processing, :file_file_size, :file_content_type, :file_file_name, :mobile, :metadata, :user_id, :native_realname, :native_photo_id] } } }, } ) else render json: @observations.to_json( methods: [:user_login, :iconic_taxon_name], viewer: current_user ) end end end end end def edit_photos @observation_photos = @observation.observation_photos if @observation_photos.blank? flash[:error] = t(:that_observation_doesnt_have_any_photos) return redirect_to edit_observation_path(@observation) end end def update_photos @observation_photos = ObservationPhoto.where(id: params[:observation_photos].map{|k,v| k}) @observation_photos.each do |op| next unless @observation.observation_photo_ids.include?(op.id) op.update_attributes(params[:observation_photos][op.id.to_s]) end flash[:notice] = t(:photos_updated) redirect_to edit_observation_path(@observation) end # DELETE /observations/1 # DELETE /observations/1.xml def destroy @observation.destroy respond_to do |format| format.html do flash[:notice] = t(:observation_was_deleted) redirect_to(observations_by_login_path(current_user.login)) end format.xml { head :ok } format.json do Observation.refresh_es_index head :ok end end end ## Custom actions ############################################################ def curation @flags = Flag.where(resolved: false, flaggable_type: "Observation"). includes(:user, :flaggable). paginate(page: params[:page]) end def new_batch @step = 1 @observations = [] if params[:batch] params[:batch][:taxa].each_line do |taxon_name_str| next if taxon_name_str.strip.blank? latitude = params[:batch][:latitude] longitude = params[:batch][:longitude] @observations << Observation.new( :user => current_user, :species_guess => taxon_name_str, :taxon => Taxon.single_taxon_for_name(taxon_name_str.strip), :place_guess => params[:batch][:place_guess], :longitude => longitude, :latitude => latitude, :map_scale => params[:batch][:map_scale], :positional_accuracy => params[:batch][:positional_accuracy], :positioning_method => params[:batch][:positioning_method], :positioning_device => params[:batch][:positioning_device], :location_is_exact => params[:batch][:location_is_exact], :observed_on_string => params[:batch][:observed_on_string], :time_zone => current_user.time_zone) end @step = 2 end end def new_bulk_csv if params[:upload].blank? || params[:upload] && params[:upload][:datafile].blank? flash[:error] = "You must select a CSV file to upload." return redirect_to :action => "import" end unique_hash = { :class => 'BulkObservationFile', :user_id => current_user.id, :filename => params[:upload]['datafile'].original_filename, :project_id => params[:upload][:project_id] } # Copy to a temp directory path = private_page_cache_path(File.join( "bulk_observation_files", "#{unique_hash.to_s.parameterize}-#{Time.now}.csv" )) FileUtils.mkdir_p File.dirname(path), :mode => 0755 File.open(path, 'wb') { |f| f.write(params[:upload]['datafile'].read) } unless CONFIG.coordinate_systems.blank? || params[:upload][:coordinate_system].blank? if coordinate_system = CONFIG.coordinate_systems[params[:upload][:coordinate_system]] proj4 = coordinate_system.proj4 end end # Send the filename to a background processor bof = BulkObservationFile.new( path, current_user.id, project_id: params[:upload][:project_id], coord_system: proj4 ) Delayed::Job.enqueue( bof, priority: USER_PRIORITY, unique_hash: unique_hash ) # Notify the user that it's getting processed and return them to the upload screen. flash[:notice] = 'Observation file has been queued for import.' if params[:upload][:project_id].blank? redirect_to import_observations_path else project = Project.find(params[:upload][:project_id].to_i) redirect_to(project_path(project)) end end # Edit a batch of observations def edit_batch observation_ids = params[:o].is_a?(String) ? params[:o].split(',') : [] @observations = Observation.where("id in (?) AND user_id = ?", observation_ids, current_user). includes(:quality_metrics, {:observation_photos => :photo}, :taxon) @observations.map do |o| if o.coordinates_obscured? o.latitude = o.private_latitude o.longitude = o.private_longitude o.place_guess = o.private_place_guess end if qm = o.quality_metrics.detect{|qm| qm.user_id == o.user_id} o.captive_flag = qm.metric == QualityMetric::WILD && !qm.agree? ? 1 : 0 else o.captive_flag = "unknown" end o end end def delete_batch @observations = Observation.where(id: params[:o].split(','), user_id: current_user) @observations.each do |observation| observation.destroy if observation.user == current_user end respond_to do |format| format.html do flash[:notice] = t(:observations_deleted) redirect_to observations_by_login_path(current_user.login) end format.js { render :text => "Observations deleted.", :status => 200 } end end # Import observations from external sources def import if @default_photo_identity ||= @photo_identities.first provider_name = if @default_photo_identity.is_a?(ProviderAuthorization) @default_photo_identity.photo_source_name else @default_photo_identity.class.to_s.underscore.split('_').first end @default_photo_identity_url = "/#{provider_name.downcase}/photo_fields?context=user" end @project = Project.find(params[:project_id].to_i) if params[:project_id] if logged_in? @projects = current_user.project_users.joins(:project).includes(:project).order('lower(projects.title)').collect(&:project) @project_templates = {} @projects.each do |p| @project_templates[p.title] = p.observation_fields.order(:position) if @project && p.id == @project.id end end end def import_photos photos = Photo.subclasses.map do |klass| retrieve_photos(params[klass.to_s.underscore.pluralize.to_sym], :user => current_user, :photo_class => klass) end.flatten.compact @observations = photos.map{|p| p.to_observation} @observation_photos = ObservationPhoto.joins(:photo, :observation). where("photos.native_photo_id IN (?)", photos.map(&:native_photo_id)) @step = 2 render :template => 'observations/new_batch' rescue Timeout::Error => e flash[:error] = t(:sorry_that_photo_provider_isnt_responding) Rails.logger.error "[ERROR #{Time.now}] Timeout: #{e}" redirect_to :action => "import" end def import_sounds sounds = Sound.from_observation_params(params, 0, current_user) @observations = sounds.map{|s| s.to_observation} @step = 2 render :template => 'observations/new_batch' end def export if params[:flow_task_id] if @flow_task = ObservationsExportFlowTask.find_by_id(params[:flow_task_id]) output = @flow_task.outputs.first @export_url = output ? FakeView.uri_join(root_url, output.file.url).to_s : nil end end @recent_exports = ObservationsExportFlowTask. where(user_id: current_user).order(id: :desc).limit(20) @observation_fields = ObservationField.recently_used_by(current_user).limit(50).sort_by{|of| of.name.downcase} set_up_instance_variables(Observation.get_search_params(params, current_user: current_user, site: @site)) respond_to do |format| format.html end end def add_from_list @order = params[:order] || "alphabetical" if @list = List.find_by_id(params[:id]) @cache_key = {:controller => "observations", :action => "add_from_list", :id => @list.id, :order => @order} unless fragment_exist?(@cache_key) @listed_taxa = @list.listed_taxa.order_by(@order).includes( taxon: [:photos, { taxon_names: :place_taxon_names } ]).paginate(page: 1, per_page: 1000) @listed_taxa_alphabetical = @listed_taxa.to_a.sort! {|a,b| a.taxon.default_name.name <=> b.taxon.default_name.name} @listed_taxa = @listed_taxa_alphabetical if @order == ListedTaxon::ALPHABETICAL_ORDER @taxon_ids_by_name = {} ancestor_ids = @listed_taxa.map {|lt| lt.taxon.ancestry.to_s.split('/')}.flatten.uniq @orders = Taxon.where(rank: "order", id: ancestor_ids).order(:ancestry) @families = Taxon.where(rank: "family", id: ancestor_ids).order(:ancestry) end end @user_lists = current_user.lists.limit(100) respond_to do |format| format.html format.mobile { render "add_from_list.html.erb" } format.js do if fragment_exist?(@cache_key) render read_fragment(@cache_key) else render :partial => 'add_from_list.html.erb' end end end end def new_from_list @taxa = Taxon.where(id: params[:taxa]).includes(:taxon_names) if @taxa.blank? flash[:error] = t(:no_taxa_selected) return redirect_to :action => :add_from_list end @observations = @taxa.map do |taxon| current_user.observations.build(:taxon => taxon, :species_guess => taxon.default_name.name, :time_zone => current_user.time_zone) end @step = 2 render :new_batch end # gets observations by user login def by_login block_if_spammer(@selected_user) && return params.update(:user_id => @selected_user.id, :viewer => current_user, :filter_spam => (current_user.blank? || current_user != @selected_user) ) search_params = Observation.get_search_params(params, current_user: current_user) search_params = Observation.apply_pagination_options(search_params, user_preferences: @prefs) @observations = Observation.page_of_results(search_params) set_up_instance_variables(search_params) Observation.preload_for_component(@observations, logged_in: !!current_user) respond_to do |format| format.html do determine_if_map_should_be_shown(search_params) @observer_provider_authorizations = @selected_user.provider_authorizations if logged_in? && @selected_user.id == current_user.id @project_users = current_user.project_users.joins(:project).order("projects.title") if @proj_obs_errors = Rails.cache.read("proj_obs_errors_#{current_user.id}") @project = Project.find_by_id(@proj_obs_errors[:project_id]) @proj_obs_errors_obs = current_user.observations. where(id: @proj_obs_errors[:errors].keys).includes(:photos, :taxon) Rails.cache.delete("proj_obs_errors_#{current_user.id}") end end if (partial = params[:partial]) && PARTIALS.include?(partial) return render_observations_partial(partial) end end format.mobile format.json do if timestamp = Chronic.parse(params[:updated_since]) deleted_observation_ids = DeletedObservation.where("user_id = ? AND created_at >= ?", @selected_user, timestamp). select(:observation_id).limit(500).map(&:observation_id) response.headers['X-Deleted-Observations'] = deleted_observation_ids.join(',') end render_observations_to_json end format.kml do render_observations_to_kml( :snippet => "#{CONFIG.site_name} Feed for User: #{@selected_user.login}", :description => "#{CONFIG.site_name} Feed for User: #{@selected_user.login}", :name => "#{CONFIG.site_name} Feed for User: #{@selected_user.login}" ) end format.atom format.csv do render_observations_to_csv(:show_private => logged_in? && @selected_user.id == current_user.id) end format.widget do if params[:markup_only]=='true' render :js => render_to_string(:partial => "widget.html.erb", :locals => { :show_user => false, :target => params[:target], :default_image => params[:default_image], :silence => params[:silence] }) else render :js => render_to_string(:partial => "widget.js.erb") end end end end def by_login_all if @selected_user.id != current_user.id flash[:error] = t(:you_dont_have_permission_to_do_that) redirect_back_or_default(root_url) return end path_for_csv = private_page_cache_path("observations/#{@selected_user.login}.all.csv") delayed_csv(path_for_csv, @selected_user) end # Renders observation components as form fields for inclusion in # observation-picking form widgets def selector search_params = Observation.get_search_params(params, current_user: current_user) search_params = Observation.apply_pagination_options(search_params) @observations = Observation.latest.query(search_params).paginate( page: search_params[:page], per_page: search_params[:per_page]) Observation.preload_for_component(@observations, logged_in: !!current_user) respond_to do |format| format.html { render :layout => false, :partial => 'selector'} # format.js end end def widget @project = Project.find_by_id(params[:project_id].to_i) if params[:project_id] @place = Place.find_by_id(params[:place_id].to_i) if params[:place_id] @taxon = Taxon.find_by_id(params[:taxon_id].to_i) if params[:taxon_id] @order_by = params[:order_by] || "observed_on" @order = params[:order] || "desc" @limit = params[:limit] || 5 @limit = @limit.to_i if %w"logo-small.gif logo-small.png logo-small-white.png none".include?(params[:logo]) @logo = params[:logo] end @logo ||= "logo-small.gif" @layout = params[:layout] || "large" url_params = { :format => "widget", :limit => @limit, :order => @order, :order_by => @order_by, :layout => @layout, } @widget_url = if @place observations_url(url_params.merge(:place_id => @place.id)) elsif @taxon observations_url(url_params.merge(:taxon_id => @taxon.id)) elsif @project project_observations_url(@project.id, url_params) elsif logged_in? observations_by_login_feed_url(current_user.login, url_params) end if @widget_url @widget_url.gsub!('http:', '') end respond_to do |format| format.html end end def nearby @lat = params[:latitude].to_f @lon = params[:longitude].to_f if @lat && @lon @observations = Observation.elastic_paginate( page: params[:page], sort: { _geo_distance: { location: [ @lon, @lat ], unit: "km", order: "asc" } } ) end @observations ||= Observation.latest.paginate(:page => params[:page]) request.format = :mobile respond_to do |format| format.mobile end end def add_nearby @observation = current_user.observations.build(:time_zone => current_user.time_zone) request.format = :mobile respond_to do |format| format.mobile end end def project @project = Project.find(params[:id]) rescue nil unless @project flash[:error] = t(:that_project_doesnt_exist) redirect_to request.env["HTTP_REFERER"] || projects_path return end params[:projects] = @project.id search_params = Observation.get_search_params(params, current_user: current_user) search_params = Observation.apply_pagination_options(search_params, user_preferences: @prefs) search_params.delete(:id) @observations = Observation.page_of_results(search_params) set_up_instance_variables(search_params) Observation.preload_for_component(@observations, logged_in: !!current_user) @project_observations = @project.project_observations.where(observation: @observations.map(&:id)). includes([ { :curator_identification => [ :taxon, :user ] } ]) @project_observations_by_observation_id = @project_observations.index_by(&:observation_id) @kml_assets = @project.project_assets.select{|pa| pa.asset_file_name =~ /\.km[lz]$/} respond_to do |format| format.html do determine_if_map_should_be_shown(search_params) if (partial = params[:partial]) && PARTIALS.include?(partial) return render_observations_partial(partial) end end format.json do render_observations_to_json end format.atom do @updated_at = Observation.last.updated_at render :action => "index" end format.csv do pagination_headers_for(@observations) render :text => ProjectObservation.to_csv(@project_observations, :user => current_user) end format.kml do render_observations_to_kml( :snippet => "#{@project.title.html_safe} Observations", :description => "Observations feed for the #{CONFIG.site_name} project '#{@project.title.html_safe}'", :name => "#{@project.title.html_safe} Observations" ) end format.widget do if params[:markup_only] == 'true' render :js => render_to_string(:partial => "widget.html.erb", :locals => { :show_user => true, :target => params[:target], :default_image => params[:default_image], :silence => params[:silence] }) else render :js => render_to_string(:partial => "widget.js.erb", :locals => { :show_user => true }) end end format.mobile end end def project_all @project = Project.find(params[:id]) rescue nil unless @project flash[:error] = t(:that_project_doesnt_exist) redirect_to request.env["HTTP_REFERER"] || projects_path return end unless @project.curated_by?(current_user) flash[:error] = t(:only_project_curators_can_do_that) redirect_to request.env["HTTP_REFERER"] || @project return end path_for_csv = private_page_cache_path("observations/project/#{@project.slug}.all.csv") delayed_csv(path_for_csv, @project) end def identify render layout: "bootstrap" end def upload render layout: "basic" end def identotron @observation = Observation.find_by_id((params[:observation] || params[:observation_id]).to_i) @taxon = Taxon.find_by_id(params[:taxon].to_i) @q = params[:q] unless params[:q].blank? if @observation @places = if @observation.coordinates_viewable_by?( current_user ) @observation.places.try(:reverse) else @observation.public_places.try(:reverse) end if @observation.taxon && @observation.taxon.species_or_lower? @taxon ||= @observation.taxon.genus else @taxon ||= @observation.taxon end if @taxon && @places @place = @places.reverse.detect {|p| p.taxa.self_and_descendants_of(@taxon).exists?} end end @place ||= (Place.find(params[:place_id]) rescue nil) || @places.try(:last) @default_taxa = @taxon ? @taxon.ancestors : Taxon::ICONIC_TAXA @taxon ||= Taxon::LIFE @default_taxa = [@default_taxa, @taxon].flatten.compact @establishment_means = params[:establishment_means] if ListedTaxon::ESTABLISHMENT_MEANS.include?(params[:establishment_means]) respond_to do |format| format.html end end def fields @project = Project.find(params[:project_id]) rescue nil @observation_fields = if @project @project.observation_fields elsif params[:observation_fields] ObservationField.where("id IN (?)", params[:observation_fields]) else @observation_fields = ObservationField.recently_used_by(current_user).limit(10) end render :layout => false end def update_fields unless @observation.fields_addable_by?(current_user) respond_to do |format| msg = t(:you_dont_have_permission_to_do_that) format.html do flash[:error] = msg redirect_back_or_default @observation end format.json do render :status => 401, :json => {:error => msg} end end return end if params[:observation].blank? respond_to do |format| msg = t(:you_must_choose_an_observation_field) format.html do flash[:error] = msg redirect_back_or_default @observation end format.json do render :status => :unprocessable_entity, :json => {:error => msg} end end return end ofv_attrs = params[:observation][:observation_field_values_attributes] ofv_attrs.each do |k,v| ofv_attrs[k][:updater_user_id] = current_user.id end o = { :observation_field_values_attributes => ofv_attrs} respond_to do |format| if @observation.update_attributes(o) if !params[:project_id].blank? && @observation.user_id == current_user.id && (@project = Project.find(params[:project_id]) rescue nil) @project_observation = @observation.project_observations.create(project: @project, user: current_user) end format.html do flash[:notice] = I18n.t(:observations_was_successfully_updated) if @project_observation && !@project_observation.valid? flash[:notice] += I18n.t(:however_there_were_some_issues, :issues => @project_observation.errors.full_messages.to_sentence) end redirect_to @observation end format.json do render :json => @observation.to_json( :viewer => current_user, :include => { :observation_field_values => {:include => {:observation_field => {:only => [:name]}}} } ) end else msg = "Failed update observation: #{@observation.errors.full_messages.to_sentence}" format.html do flash[:error] = msg redirect_to @observation end format.json do render :status => :unprocessable_entity, :json => {:error => msg} end end end end def photo @observations = [] @errors = [] if params[:files].blank? respond_to do |format| format.json do render :status => :unprocessable_entity, :json => { :error => "You must include files to convert to observations." } end end return end params[:files].each_with_index do |file, i| lp = LocalPhoto.new(:file => file, :user => current_user) o = lp.to_observation if params[:observations] && obs_params = params[:observations][i] obs_params.each do |k,v| o.send("#{k}=", v) unless v.blank? end end o.site ||= @site || current_user.site if o.save @observations << o else @errors << o.errors end end respond_to do |format| format.json do unless @errors.blank? render :status => :unprocessable_entity, json: {errors: @errors.map{|e| e.full_messages.to_sentence}} return end render_observations_to_json(:include => { :taxon => { :only => [:name, :id, :rank, :rank_level, :is_iconic], :methods => [:default_name, :image_url, :iconic_taxon_name, :conservation_status_name], :include => { :iconic_taxon => { :only => [:id, :name] }, :taxon_names => { :only => [:id, :name, :lexicon] } } } }) end end end def stats @headless = @footless = true stats_adequately_scoped? respond_to do |format| format.html end end def taxa can_view_leaves = logged_in? && current_user.is_curator? params[:rank] = nil unless can_view_leaves params[:skip_order] = true search_params = Observation.get_search_params(params, current_user: current_user) if stats_adequately_scoped?(search_params) if Observation.able_to_use_elasticsearch?(search_params) if params[:rank] == "leaves" search_params.delete(:rank) end elastic_params = prepare_counts_elastic_query(search_params) # using 0 for the aggregation count to get all results distinct_taxa = Observation.elastic_search(elastic_params.merge(size: 0, aggregate: { species: { "taxon.id": 0 } })).response.aggregations @taxa = Taxon.where(id: distinct_taxa.species.buckets.map{ |b| b["key"] }) # if `leaves` were requested, remove any taxon in another's ancestry if params[:rank] == "leaves" ancestors = { } @taxa.each do |t| t.ancestor_ids.each do |aid| ancestors[aid] ||= 0 ancestors[aid] += 1 end end @taxa = @taxa.select{ |t| !ancestors[t.id] } end else oscope = Observation.query(search_params) if params[:rank] == "leaves" && can_view_leaves ancestor_ids_sql = <<-SQL SELECT DISTINCT regexp_split_to_table(ancestry, '/') AS ancestor_id FROM taxa JOIN ( #{oscope.to_sql} ) AS observations ON observations.taxon_id = taxa.id SQL sql = <<-SQL SELECT DISTINCT ON (taxa.id) taxa.* FROM taxa LEFT OUTER JOIN ( #{ancestor_ids_sql} ) AS ancestor_ids ON taxa.id::text = ancestor_ids.ancestor_id JOIN ( #{oscope.to_sql} ) AS observations ON observations.taxon_id = taxa.id WHERE ancestor_ids.ancestor_id IS NULL SQL @taxa = Taxon.find_by_sql(sql) else @taxa = Taxon.find_by_sql("SELECT DISTINCT ON (taxa.id) taxa.* from taxa INNER JOIN (#{oscope.to_sql}) as o ON o.taxon_id = taxa.id") end end # hack to test what this would look like @taxa = case params[:order] when "observations_count" @taxa.sort_by do |t| c = if search_params[:place] # this is a dumb hack. if i was smarter, i would have tried tp pull # this out of the sql with GROUP and COUNT, but I couldn't figure it # out --kueda 20150430 if lt = search_params[:place].listed_taxa.where(primary_listing: true, taxon_id: t.id).first lt.observations_count else # if there's no listed taxon assume it's been observed once 1 end else t.observations_count end c.to_i * -1 end when "name" @taxa.sort_by(&:name) else @taxa end else @taxa = [ ] end respond_to do |format| format.html do @headless = true ancestor_ids = @taxa.map{|t| t.ancestor_ids[1..-1]}.flatten.uniq ancestors = Taxon.where(id: ancestor_ids) taxa_to_arrange = (ancestors + @taxa).sort_by{|t| "#{t.ancestry}/#{t.id}"} @arranged_taxa = Taxon.arrange_nodes(taxa_to_arrange) @taxon_names_by_taxon_id = TaxonName. where(taxon_id: taxa_to_arrange.map(&:id).uniq). includes(:place_taxon_names). group_by(&:taxon_id) render :layout => "bootstrap" end format.csv do Taxon.preload_associations(@taxa, [ :ancestor_taxa, { taxon_names: :place_taxon_names }]) render :text => @taxa.to_csv( :only => [:id, :name, :rank, :rank_level, :ancestry, :is_active], :methods => [:common_name_string, :iconic_taxon_name, :taxonomic_kingdom_name, :taxonomic_phylum_name, :taxonomic_class_name, :taxonomic_order_name, :taxonomic_family_name, :taxonomic_genus_name, :taxonomic_species_name] ) end format.json do Taxon.preload_associations(@taxa, :taxon_descriptions) render :json => { :taxa => @taxa } end end end def taxon_stats params[:skip_order] = true search_params = Observation.get_search_params(params, current_user: current_user) if stats_adequately_scoped?(search_params) && request.format.json? if Observation.able_to_use_elasticsearch?(search_params) elastic_taxon_stats(search_params) else non_elastic_taxon_stats(search_params) end else @species_counts = [ ] @rank_counts = { } end @taxa = Taxon.where(id: @species_counts.map{ |r| r["taxon_id"] }). includes({ taxon_photos: :photo }, :taxon_names) @taxa_by_taxon_id = @taxa.index_by(&:id) @species_counts_json = @species_counts.map do |row| taxon = @taxa_by_taxon_id[row['taxon_id'].to_i] taxon.locale = I18n.locale { :count => row['count_all'], :taxon => taxon.as_json( :methods => [:default_name, :image_url, :iconic_taxon_name, :conservation_status_name], :only => [:id, :name, :rank, :rank_level] ) } end respond_to do |format| format.json do render :json => { :total => @total, :species_counts => @species_counts_json, :rank_counts => @rank_counts } end end end def user_stats params[:skip_order] = true search_params = Observation.get_search_params(params, current_user: current_user) limit = params[:limit].to_i limit = 500 if limit > 500 || limit <= 0 stats_adequately_scoped?(search_params) # all the HTML view needs to know is stats_adequately_scoped? if request.format.json? if Observation.able_to_use_elasticsearch?(search_params) elastic_user_stats(search_params, limit) else non_elastic_user_stats(search_params, limit) end @user_ids = @user_counts.map{ |c| c["user_id"] } | @user_taxon_counts.map{ |c| c["user_id"] } @users = User.where(id: @user_ids). select("id, login, name, icon_file_name, icon_updated_at, icon_content_type") @users_by_id = @users.index_by(&:id) else @user_counts = [ ] @user_taxon_counts = [ ] end respond_to do |format| format.html do @headless = true render layout: "bootstrap" end format.json do render :json => { :total => @total, :most_observations => @user_counts.map{|row| @users_by_id[row['user_id'].to_i].blank? ? nil : { :count => row['count_all'].to_i, :user => @users_by_id[row['user_id'].to_i].as_json( :only => [:id, :name, :login], :methods => [:user_icon_url] ) } }.compact, :most_species => @user_taxon_counts.map{|row| @users_by_id[row['user_id'].to_i].blank? ? nil : { :count => row['count_all'].to_i, :user => @users_by_id[row['user_id'].to_i].as_json( :only => [:id, :name, :login], :methods => [:user_icon_url] ) } }.compact } end end end def moimport if @api_key = params[:api_key] mot = MushroomObserverImportFlowTask.new @mo_user_id = mot.mo_user_id( @api_key ) @mo_user_name = mot.mo_user_name( @api_key ) @results = mot.get_results_xml( api_key: @api_key ).map{ |r| [r, mot.observation_from_result( r, skip_images: true )] } end respond_to do |format| format.html { render layout: "bootstrap" } end end private def observation_params(options = {}) p = options.blank? ? params : options p.permit( :captive_flag, :coordinate_system, :description, :force_quality_metrics, :geo_x, :geo_y, :geoprivacy, :iconic_taxon_id, :latitude, :license, :location_is_exact, :longitude, :make_license_default, :make_licenses_same, :map_scale, :oauth_application_id, :observed_on_string, :place_guess, :positional_accuracy, :positioning_device, :positioning_method, :prefers_community_taxon, :quality_grade, :species_guess, :tag_list, :taxon_id, :taxon_name, :time_zone, :uuid, :zic_time_zone, :site_id, observation_field_values_attributes: [ :_destroy, :id, :observation_field_id, :value ] ) end def user_obs_counts(scope, limit = 500) user_counts_sql = <<-SQL SELECT o.user_id, count(*) AS count_all FROM (#{scope.to_sql}) AS o GROUP BY o.user_id ORDER BY count_all desc LIMIT #{limit} SQL ActiveRecord::Base.connection.execute(user_counts_sql) end def user_taxon_counts(scope, limit = 500) unique_taxon_users_scope = scope. select("DISTINCT observations.taxon_id, observations.user_id"). joins(:taxon). where("taxa.rank_level <= ?", Taxon::SPECIES_LEVEL) user_taxon_counts_sql = <<-SQL SELECT o.user_id, count(*) AS count_all FROM (#{unique_taxon_users_scope.to_sql}) AS o GROUP BY o.user_id ORDER BY count_all desc LIMIT #{limit} SQL ActiveRecord::Base.connection.execute(user_taxon_counts_sql) end public def accumulation params[:order_by] = "observed_on" params[:order] = "asc" search_params = Observation.get_search_params(params, current_user: current_user) set_up_instance_variables(search_params) scope = Observation.query(search_params) scope = scope.where("1 = 2") unless stats_adequately_scoped?(search_params) scope = scope.joins(:taxon). select("observations.id, observations.user_id, observations.created_at, observations.observed_on, observations.time_observed_at, observations.time_zone, taxa.ancestry, taxon_id"). where("time_observed_at IS NOT NULL") rows = ActiveRecord::Base.connection.execute(scope.to_sql) row = rows.first @observations = rows.map do |row| { :id => row['id'].to_i, :user_id => row['user_id'].to_i, :created_at => DateTime.parse(row['created_at']), :observed_on => row['observed_on'] ? Date.parse(row['observed_on']) : nil, :time_observed_at => row['time_observed_at'] ? DateTime.parse(row['time_observed_at']).in_time_zone(row['time_zone']) : nil, :offset_hours => DateTime.parse(row['time_observed_at']).in_time_zone(row['time_zone']).utc_offset / 60 / 60, :ancestry => row['ancestry'], :taxon_id => row['taxon_id'] ? row['taxon_id'].to_i : nil } end respond_to do |format| format.html do @headless = true render :layout => "bootstrap" end format.json do render :json => { :observations => @observations } end end end def phylogram params[:skip_order] = true search_params = Observation.get_search_params(params, current_user: current_user) scope = Observation.query(search_params) scope = scope.where("1 = 2") unless stats_adequately_scoped?(search_params) ancestor_ids_sql = <<-SQL SELECT DISTINCT regexp_split_to_table(ancestry, '/') AS ancestor_id FROM taxa JOIN ( #{scope.to_sql} ) AS observations ON observations.taxon_id = taxa.id SQL sql = <<-SQL SELECT taxa.id, name, ancestry FROM taxa LEFT OUTER JOIN ( #{ancestor_ids_sql} ) AS ancestor_ids ON taxa.id::text = ancestor_ids.ancestor_id JOIN ( #{scope.to_sql} ) AS observations ON observations.taxon_id = taxa.id WHERE ancestor_ids.ancestor_id IS NULL SQL @taxa = ActiveRecord::Base.connection.execute(sql) respond_to do |format| format.html do @headless = true render :layout => "bootstrap" end format.json do render :json => { :taxa => @taxa } end end end def viewed_updates user_viewed_updates respond_to do |format| format.html { redirect_to @observation } format.json { head :no_content } end end def review user_reviewed respond_to do |format| format.html { redirect_to @observation } format.json do Observation.refresh_es_index head :no_content end end end def email_export unless flow_task = current_user.flow_tasks.find_by_id(params[:id]) render status: :unprocessable_entity, text: "Flow task doesn't exist" return end if flow_task.user_id != current_user.id render status: :unprocessable_entity, text: "You don't have permission to do that" return end if flow_task.outputs.exists? Emailer.observations_export_notification(flow_task).deliver_now render status: :ok, text: "" return elsif flow_task.error Emailer.observations_export_failed_notification(flow_task).deliver_now render status: :ok, text: "" return end flow_task.options = flow_task.options.merge(:email => true) if flow_task.save render status: :ok, text: "" else render status: :unprocessable_entity, text: flow_task.errors.full_messages.to_sentence end end def community_taxon_summary render :layout => false, :partial => "community_taxon_summary" end def map @taxa = [ ] @places = [ ] @user = User.find_by_id(params[:user_id]) @project = Project.find(params[:project_id]) rescue nil if params[:taxon_id] @taxa = [ Taxon.find_by_id(params[:taxon_id].to_i) ] elsif params[:taxon_ids] @taxa = Taxon.where(id: params[:taxon_ids]) end if params[:place_id] @places = [ Place.find_by_id(params[:place_id].to_i) ] elsif params[:place_ids] @places = Place.where(id: params[:place_ids]) end if params[:render_place_id] @render_place = Place.find_by_id(params[:render_place_id]) end if @taxa.length == 1 @taxon = @taxa.first @taxon_hash = { } common_name = view_context.common_taxon_name(@taxon).try(:name) rank_label = @taxon.rank ? t('ranks.#{ @taxon.rank.downcase }', default: @taxon.rank).capitalize : t(:unknown_rank) display_name = common_name || (rank_label + " " + @taxon.name) @taxon_hash[:display_label] = I18n.t(:observations_of_taxon, taxon_name: display_name) if @taxon.iconic_taxon @taxon_hash[:iconic_taxon_name] = @taxon.iconic_taxon.name end end @elastic_params = valid_map_params @default_color = params[:color] || (@taxa.empty? ? "heatmap" : nil) @map_style = (( params[:color] || @taxa.any? ) && params[:color] != "heatmap" ) ? "colored_heatmap" : "heatmap" @map_type = ( params[:type] == "map" ) ? "MAP" : "SATELLITE" @default_color = params[:heatmap_colors] if @map_style == "heatmap" @about_url = CONFIG.map_about_url ? CONFIG.map_about_url : view_context.wiki_page_url('help', anchor: 'mapsymbols') end ## Protected / private actions ############################################### private def user_viewed_updates return unless logged_in? obs_updates = UpdateAction.joins(:update_subscribers). where(resource: @observation). where("update_subscribers.subscriber_id = ?", current_user.id) UpdateAction.user_viewed_updates(obs_updates, current_user.id) end def user_reviewed return unless logged_in? review = ObservationReview.where(observation_id: @observation.id, user_id: current_user.id).first_or_create reviewed = if request.delete? false else params[:reviewed] === "false" ? false : true end review.update_attributes({ user_added: true, reviewed: reviewed }) review.observation.elastic_index! end def stats_adequately_scoped?(search_params = { }) # use the supplied search_params if available. Those will already have # tried to resolve and instances referred to by ID stats_params = search_params.blank? ? params : search_params if stats_params[:d1] d1 = (Date.parse(stats_params[:d1]) rescue Date.today) d2 = stats_params[:d2] ? (Date.parse(stats_params[:d2]) rescue Date.today) : Date.today return false if d2 - d1 > 366 end @stats_adequately_scoped = !( stats_params[:d1].blank? && stats_params[:projects].blank? && stats_params[:place_id].blank? && stats_params[:user_id].blank? && stats_params[:on].blank? && stats_params[:created_on].blank? && stats_params[:apply_project_rules_for].blank? ) end def retrieve_photos(photo_list = nil, options = {}) return [] if photo_list.blank? photo_list = photo_list.values if photo_list.is_a?(Hash) photo_list = [photo_list] unless photo_list.is_a?(Array) photo_class = options[:photo_class] || Photo # simple algorithm, # 1. create an array to be passed back to the observation obj # 2. check to see if that photo's data has already been stored # 3. if yes # retrieve Photo obj and put in array # if no # create Photo obj and put in array # 4. return array photos = [] native_photo_ids = photo_list.map{|p| p.to_s}.uniq # the photos may exist in their native photo_class, or cached # as a LocalPhoto, so lookup both and combine results existing = (LocalPhoto.where(subtype: photo_class, native_photo_id: native_photo_ids) + photo_class.includes(:user).where(native_photo_id: native_photo_ids)). index_by{|p| p.native_photo_id } photo_list.uniq.each do |photo_id| if (photo = existing[photo_id]) || options[:sync] api_response = begin photo_class.get_api_response(photo_id, :user => current_user) rescue JSON::ParserError => e Rails.logger.error "[ERROR #{Time.now}] Failed to parse JSON from Flickr: #{e}" next end end # Sync existing if called for if photo photo.user ||= options[:user] if options[:sync] # sync the photo URLs b/c they change when photos become private photo.api_response = api_response # set to make sure user validation works photo.sync photo.save if photo.changed? end end # Create a new one if one doesn't already exist unless photo photo = if photo_class == LocalPhoto if photo_id.is_a?(Fixnum) || photo_id.is_a?(String) LocalPhoto.find_by_id(photo_id) else LocalPhoto.new(:file => photo_id, :user => current_user) unless photo_id.blank? end else api_response ||= begin photo_class.get_api_response(photo_id, :user => current_user) rescue JSON::ParserError => e Rails.logger.error "[ERROR #{Time.now}] Failed to parse JSON from Flickr: #{e}" nil end if api_response photo_class.new_from_api_response(api_response, :user => current_user, :native_photo_id => photo_id) end end end if photo.blank? Rails.logger.error "[ERROR #{Time.now}] Failed to get photo for photo_class: #{photo_class}, photo_id: #{photo_id}" elsif photo.valid? || existing[photo_id] photos << photo else Rails.logger.error "[ERROR #{Time.now}] #{current_user} tried to save an observation with a new invalid photo (#{photo}): #{photo.errors.full_messages.to_sentence}" end end photos end def set_up_instance_variables(search_params) @swlat = search_params[:swlat] unless search_params[:swlat].blank? @swlng = search_params[:swlng] unless search_params[:swlng].blank? @nelat = search_params[:nelat] unless search_params[:nelat].blank? @nelng = search_params[:nelng] unless search_params[:nelng].blank? if search_params[:place].is_a?(Array) && search_params[:place].length == 1 search_params[:place] = search_params[:place].first end unless search_params[:place].blank? || search_params[:place].is_a?(Array) @place = search_params[:place] end @q = search_params[:q] unless search_params[:q].blank? @search_on = search_params[:search_on] @iconic_taxa = search_params[:iconic_taxa_instances] @observations_taxon_id = search_params[:observations_taxon_id] @observations_taxon = search_params[:observations_taxon] @observations_taxon_name = search_params[:taxon_name] @observations_taxon_ids = search_params[:taxon_ids] || search_params[:observations_taxon_ids] @observations_taxa = search_params[:observations_taxa] search_params[:has] ||= [ ] search_params[:has] << "photos" if search_params[:photos].yesish? search_params[:has] << "sounds" if search_params[:sounds].yesish? if search_params[:has] @id_please = true if search_params[:has].include?('id_please') @with_photos = true if search_params[:has].include?('photos') @with_sounds = true if search_params[:has].include?('sounds') @with_geo = true if search_params[:has].include?('geo') end @quality_grade = search_params[:quality_grade] @reviewed = search_params[:reviewed] @captive = search_params[:captive] @identifications = search_params[:identifications] @out_of_range = search_params[:out_of_range] @license = search_params[:license] @photo_license = search_params[:photo_license] @sound_license = search_params[:sound_license] @order_by = search_params[:order_by] @order = search_params[:order] @observed_on = search_params[:observed_on] @observed_on_year = search_params[:observed_on_year] @observed_on_month = [ search_params[:observed_on_month] ].flatten.first @observed_on_day = search_params[:observed_on_day] @ofv_params = search_params[:ofv_params] @site_uri = params[:site] unless params[:site].blank? @user = search_params[:user] @projects = search_params[:projects] @pcid = search_params[:pcid] @geoprivacy = search_params[:geoprivacy] unless search_params[:geoprivacy].blank? @rank = search_params[:rank] @hrank = search_params[:hrank] @lrank = search_params[:lrank] @verifiable = search_params[:verifiable] @threatened = search_params[:threatened] @introduced = search_params[:introduced] @popular = search_params[:popular] if stats_adequately_scoped?(search_params) @d1 = search_params[:d1].blank? ? nil : search_params[:d1] @d2 = search_params[:d2].blank? ? nil : search_params[:d2] else search_params[:d1] = nil search_params[:d2] = nil end @filters_open = !@q.nil? || !@observations_taxon_id.blank? || !@observations_taxon_name.blank? || !@iconic_taxa.blank? || @id_please == true || !@with_photos.blank? || !@with_sounds.blank? || !@identifications.blank? || !@quality_grade.blank? || !@captive.blank? || !@out_of_range.blank? || !@observed_on.blank? || !@place.blank? || !@ofv_params.blank? || !@pcid.blank? || !@geoprivacy.blank? || !@rank.blank? || !@lrank.blank? || !@hrank.blank? @filters_open = search_params[:filters_open] == 'true' if search_params.has_key?(:filters_open) end # Refresh lists affected by taxon changes in a batch of new/edited # observations. Note that if you don't set @skip_refresh_lists on the records # in @observations before this is called, this won't do anything def refresh_lists_for_batch return true if @observations.blank? taxa = @observations.to_a.compact.select(&:skip_refresh_lists).map(&:taxon).uniq.compact return true if taxa.blank? List.delay(:priority => USER_PRIORITY).refresh_for_user(current_user, :taxa => taxa.map(&:id)) true end # Tries to create a new observation from the specified Facebook photo ID and # update the existing @observation with the new properties, without saving def sync_facebook_photo fb = current_user.facebook_api if fb fbp_json = FacebookPhoto.get_api_response(params[:facebook_photo_id], :user => current_user) @facebook_photo = FacebookPhoto.new_from_api_response(fbp_json) else @facebook_photo = nil end if @facebook_photo && @facebook_photo.owned_by?(current_user) @facebook_observation = @facebook_photo.to_observation sync_attrs = [:description] # facebook strips exif metadata so we can't get geo or observed_on :-/ #, :species_guess, :taxon_id, :observed_on, :observed_on_string, :latitude, :longitude, :place_guess] unless params[:facebook_sync_attrs].blank? sync_attrs = sync_attrs & params[:facebook_sync_attrs] end sync_attrs.each do |sync_attr| # merge facebook_observation with existing observation @observation[sync_attr] ||= @facebook_observation[sync_attr] end unless @observation.observation_photos.detect {|op| op.photo.native_photo_id == @facebook_photo.native_photo_id} @observation.observation_photos.build(:photo => @facebook_photo) end unless @observation.new_record? flash.now[:notice] = t(:preview_of_synced_observation, :url => url_for) end else flash.now[:error] = t(:sorry_we_didnt_find_that_photo) end end # Tries to create a new observation from the specified Flickr photo ID and # update the existing @observation with the new properties, without saving def sync_flickr_photo flickr = get_flickraw begin fp = flickr.photos.getInfo(:photo_id => params[:flickr_photo_id]) @flickr_photo = FlickrPhoto.new_from_flickraw(fp, :user => current_user) rescue FlickRaw::FailedResponse => e Rails.logger.debug "[DEBUG] FlickRaw failed to find photo " + "#{params[:flickr_photo_id]}: #{e}\n#{e.backtrace.join("\n")}" @flickr_photo = nil rescue Timeout::Error => e flash.now[:error] = t(:sorry_flickr_isnt_responding_at_the_moment) Rails.logger.error "[ERROR #{Time.now}] Timeout: #{e}" Airbrake.notify(e, :request => request, :session => session) Logstasher.write_exception(e, request: request, session: session, user: current_user) return end if fp && @flickr_photo && @flickr_photo.valid? @flickr_observation = @flickr_photo.to_observation sync_attrs = %w(description species_guess taxon_id observed_on observed_on_string latitude longitude place_guess map_scale) unless params[:flickr_sync_attrs].blank? sync_attrs = sync_attrs & params[:flickr_sync_attrs] end sync_attrs.each do |sync_attr| # merge flickr_observation with existing observation val = @flickr_observation.send(sync_attr) @observation.send("#{sync_attr}=", val) unless val.blank? end # Note: the following is sort of a hacky alternative to build(). We # need to append a new photo object without saving it, but build() won't # work here b/c Photo and its descedents use STI, and type is a # protected attributes that can't be mass-assigned. unless @observation.observation_photos.detect {|op| op.photo.native_photo_id == @flickr_photo.native_photo_id} @observation.observation_photos.build(:photo => @flickr_photo) end unless @observation.new_record? flash.now[:notice] = t(:preview_of_synced_observation, :url => url_for) end if (@existing_photo = Photo.find_by_native_photo_id(@flickr_photo.native_photo_id)) && (@existing_photo_observation = @existing_photo.observations.first) && @existing_photo_observation.id != @observation.id msg = t(:heads_up_this_photo_is_already_associated_with, :url => url_for(@existing_photo_observation)) flash.now[:notice] = flash.now[:notice].blank? ? msg : "#{flash.now[:notice]}<br/>#{msg}" end else flash.now[:error] = t(:sorry_we_didnt_find_that_photo) end end def sync_picasa_photo begin api_response = PicasaPhoto.get_api_response(params[:picasa_photo_id], :user => current_user) rescue Timeout::Error => e flash.now[:error] = t(:sorry_picasa_isnt_responding_at_the_moment) Rails.logger.error "[ERROR #{Time.now}] Timeout: #{e}" Airbrake.notify(e, :request => request, :session => session) Logstasher.write_exception(e, request: request, session: session, user: current_user) return end unless api_response Rails.logger.debug "[DEBUG] Failed to find Picasa photo for #{params[:picasa_photo_id]}" return end @picasa_photo = PicasaPhoto.new_from_api_response(api_response, :user => current_user) if @picasa_photo && @picasa_photo.valid? @picasa_observation = @picasa_photo.to_observation sync_attrs = PHOTO_SYNC_ATTRS unless params[:picasa_sync_attrs].blank? sync_attrs = sync_attrs & params[:picasa_sync_attrs] end sync_attrs.each do |sync_attr| @observation.send("#{sync_attr}=", @picasa_observation.send(sync_attr)) end unless @observation.observation_photos.detect {|op| op.photo.native_photo_id == @picasa_photo.native_photo_id} @observation.observation_photos.build(:photo => @picasa_photo) end flash.now[:notice] = t(:preview_of_synced_observation, :url => url_for) else flash.now[:error] = t(:sorry_we_didnt_find_that_photo) end end def sync_local_photo unless @local_photo = Photo.find_by_id(params[:local_photo_id]) flash.now[:error] = t(:that_photo_doesnt_exist) return end if @local_photo.metadata.blank? flash.now[:error] = t(:sorry_we_dont_have_any_metadata_for_that_photo) return end o = @local_photo.to_observation PHOTO_SYNC_ATTRS.each do |sync_attr| @observation.send("#{sync_attr}=", o.send(sync_attr)) unless o.send(sync_attr).blank? end unless @observation.observation_photos.detect {|op| op.photo_id == @local_photo.id} @observation.observation_photos.build(:photo => @local_photo) end unless @observation.new_record? flash.now[:notice] = t(:preview_of_synced_observation, :url => url_for) end if @existing_photo_observation = @local_photo.observations.where("observations.id != ?", @observation).first msg = t(:heads_up_this_photo_is_already_associated_with, :url => url_for(@existing_photo_observation)) flash.now[:notice] = flash.now[:notice].blank? ? msg : "#{flash.now[:notice]}<br/>#{msg}" end end def load_photo_identities return if @skipping_preloading unless logged_in? @photo_identity_urls = [] @photo_identities = [] return true end if Rails.env.development? FacebookPhoto PicasaPhoto LocalPhoto FlickrPhoto end @photo_identities = Photo.subclasses.map do |klass| assoc_name = klass.to_s.underscore.split('_').first + "_identity" current_user.send(assoc_name) if current_user.respond_to?(assoc_name) end.compact reference_photo = @observation.try(:observation_photos).try(:first).try(:photo) reference_photo ||= @observations.try(:first).try(:observation_photos).try(:first).try(:photo) unless params[:action] === "show" || params[:action] === "update" reference_photo ||= current_user.photos.order("id ASC").last end if reference_photo assoc_name = (reference_photo.subtype || reference_photo.class.to_s). underscore.split('_').first + "_identity" if current_user.respond_to?(assoc_name) @default_photo_identity = current_user.send(assoc_name) else @default_photo_source = 'local' end end if params[:facebook_photo_id] if @default_photo_identity = @photo_identities.detect{|pi| pi.to_s =~ /facebook/i} @default_photo_source = 'facebook' end elsif params[:flickr_photo_id] if @default_photo_identity = @photo_identities.detect{|pi| pi.to_s =~ /flickr/i} @default_photo_source = 'flickr' end end @default_photo_source ||= if @default_photo_identity if @default_photo_identity.class.name =~ /Identity/ @default_photo_identity.class.name.underscore.humanize.downcase.split.first else @default_photo_identity.provider_name end elsif @default_photo_identity "local" end @default_photo_identity_url = nil @photo_identity_urls = @photo_identities.map do |identity| provider_name = if identity.is_a?(ProviderAuthorization) if identity.provider_name =~ /google/i "picasa" else identity.provider_name end else identity.class.to_s.underscore.split('_').first # e.g. FlickrIdentity=>'flickr' end url = "/#{provider_name.downcase}/photo_fields?context=user" @default_photo_identity_url = url if identity == @default_photo_identity "{title: '#{provider_name.capitalize}', url: '#{url}'}" end @photo_sources = @photo_identities.inject({}) do |memo, ident| if ident.respond_to?(:source_options) memo[ident.class.name.underscore.humanize.downcase.split.first] = ident.source_options elsif ident.is_a?(ProviderAuthorization) if ident.provider_name == "facebook" memo[:facebook] = { :title => 'Facebook', :url => '/facebook/photo_fields', :contexts => [ ["Your photos", 'user'] ] } elsif ident.provider_name =~ /google/ memo[:picasa] = { :title => 'Picasa', :url => '/picasa/photo_fields', :contexts => [ ["Your photos", 'user', {:searchable => true}] ] } end end memo end end def load_sound_identities return if @skipping_preloading unless logged_in? logger.info "not logged in" @sound_identities = [] return true end @sound_identities = current_user.soundcloud_identity ? [current_user.soundcloud_identity] : [] end def load_observation scope = Observation.where(id: params[:id] || params[:observation_id]) unless @skipping_preloading scope = scope.includes([ :quality_metrics, :flags, { photos: :flags }, :identifications, :projects, { taxon: :taxon_names }]) end @observation = begin scope.first rescue RangeError => e Logstasher.write_exception(e, request: request, session: session, user: current_user) nil end render_404 unless @observation end def require_owner unless logged_in? && current_user.id == @observation.user_id msg = t(:you_dont_have_permission_to_do_that) respond_to do |format| format.html do flash[:error] = msg return redirect_to @observation end format.json do return render :json => {:error => msg} end end end end def render_observations_to_json(options = {}) if (partial = params[:partial]) && PARTIALS.include?(partial) Observation.preload_associations(@observations, [ :stored_preferences, { :taxon => :taxon_descriptions }, { :iconic_taxon => :taxon_descriptions } ]) data = @observations.map do |observation| item = { :instance => observation, :extra => { :taxon => observation.taxon, :iconic_taxon => observation.iconic_taxon, :user => {login: observation.user.login, name: observation.user.name} } } item[:html] = view_context.render_in_format(:html, :partial => partial, :object => observation) item end render :json => data else opts = options opts[:methods] ||= [] opts[:methods] += [:short_description, :user_login, :iconic_taxon_name, :tag_list, :faves_count] opts[:methods].uniq! opts[:include] ||= {} opts[:include][:taxon] ||= { :only => [:id, :name, :rank, :ancestry], :methods => [:common_name] } opts[:include][:iconic_taxon] ||= {:only => [:id, :name, :rank, :rank_level, :ancestry]} opts[:include][:user] ||= {:only => :login, :methods => [:user_icon_url]} opts[:include][:photos] ||= { :methods => [:license_code, :attribution], :except => [:original_url, :file_processing, :file_file_size, :file_content_type, :file_file_name, :mobile, :metadata] } extra = params[:extra].to_s.split(',') if extra.include?('projects') opts[:include][:project_observations] ||= { :include => {:project => {:only => [:id, :title]}}, :except => [:tracking_code] } end if extra.include?('observation_photos') opts[:include][:observation_photos] ||= { :include => {:photo => {:except => [:metadata]}} } end if extra.include?('identifications') taxon_options = Taxon.default_json_options taxon_options[:methods] += [:iconic_taxon_name, :image_url, :common_name, :default_name] opts[:include][:identifications] ||= { 'include': { user: { only: [:name, :login, :id], methods: [:user_icon_url] }, taxon: { only: [:id, :name, :rank, :rank_level], methods: [:iconic_taxon_name, :image_url, :common_name, :default_name] } } } end if @ofv_params || extra.include?('fields') opts[:include][:observation_field_values] ||= { :except => [:observation_field_id], :include => { :observation_field => { :only => [:id, :datatype, :name, :allowed_values] } } } end pagination_headers_for(@observations) opts[:viewer] = current_user if @observations.respond_to?(:scoped) Observation.preload_associations(@observations, [ {:observation_photos => { :photo => :user } }, :photos, :iconic_taxon ]) end render :json => @observations.to_json(opts) end end def render_observations_to_csv(options = {}) first = %w(scientific_name datetime description place_guess latitude longitude tag_list common_name url image_url user_login) only = (first + Observation::CSV_COLUMNS).uniq except = %w(map_scale timeframe iconic_taxon_id delta geom user_agent cached_tag_list) unless options[:show_private] == true except += %w(private_latitude private_longitude private_positional_accuracy) end only = only - except unless @ofv_params.blank? only += @ofv_params.map{|k,v| "field:#{v[:normalized_name]}"} if @observations.respond_to?(:scoped) Observation.preload_associations(@observations, { :observation_field_values => :observation_field }) end end Observation.preload_associations(@observations, [ :tags, :taxon, :photos, :user, :quality_metrics ]) pagination_headers_for(@observations) render :text => Observation.as_csv(@observations, only.map{|c| c.to_sym}, { ssl: request.protocol =~ /https/ }) end def render_observations_to_kml(options = {}) @net_hash = options if params[:kml_type] == "network_link" kml_query = request.query_parameters.reject{|k,v| REJECTED_KML_FEED_PARAMS.include?(k.to_s) || k.to_s == "kml_type"}.to_query kml_href = "#{request.base_url}#{request.path}" kml_href += "?#{kml_query}" unless kml_query.blank? @net_hash = { :id => "AllObs", :link_id =>"AllObs", :snippet => "#{CONFIG.site_name} Feed for Everyone", :description => "#{CONFIG.site_name} Feed for Everyone", :name => "#{CONFIG.site_name} Feed for Everyone", :href => kml_href } render :layout => false, :action => 'network_link' return end render :layout => false, :action => "index" end # create project observations if a project was specified and project allows # auto-joining def create_project_observations return unless params[:project_id] if params[:project_id].is_a?(Array) params[:project_id].each do |pid| errors = create_project_observation_records(pid) end else errors = create_project_observation_records(params[:project_id]) if !errors.blank? if request.format.html? flash[:error] = t(:your_observations_couldnt_be_added_to_that_project, :errors => errors.to_sentence) else Rails.logger.error "[ERROR #{Time.now}] Failed to add #{@observations.size} obs to #{@project}: #{errors.to_sentence}" end end end end def create_project_observation_records(project_id) return unless project_id @project = Project.find_by_id(project_id) @project ||= Project.find(project_id) rescue nil return unless @project if @project.tracking_code_allowed?(params[:tracking_code]) tracking_code = params[:tracking_code] end errors = [] @observations.each do |observation| next if observation.new_record? po = observation.project_observations.build(project: @project, tracking_code: tracking_code, user: current_user) unless po.save if params[:uploader] observation.project_observations.delete(po) end return (errors + po.errors.full_messages).uniq end end nil end def update_user_account current_user.update_attributes(params[:user]) unless params[:user].blank? end def render_observations_partial(partial) if @observations.empty? render(:text => '') else render(partial: "partial_renderer", locals: { partial: partial, collection: @observations }, layout: false) end end def load_prefs @prefs = current_preferences if request.format && request.format.html? @view = params[:view] || current_user.try(:preferred_observations_view) || 'map' end end def delayed_csv(path_for_csv, parent, options = {}) path_for_csv_no_ext = path_for_csv.gsub(/\.csv\z/, '') if parent.observations.count < 50 Observation.generate_csv_for(parent, :path => path_for_csv, :user => current_user) render :file => path_for_csv_no_ext, :formats => [:csv] else cache_key = Observation.generate_csv_for_cache_key(parent) job_id = Rails.cache.read(cache_key) job = Delayed::Job.find_by_id(job_id) if job # Still working elsif File.exists? path_for_csv render :file => path_for_csv_no_ext, :formats => [:csv] return else # no job id, no job, let's get this party started Rails.cache.delete(cache_key) job = Observation.delay(:priority => NOTIFICATION_PRIORITY).generate_csv_for(parent, :path => path_for_csv, :user => current_user) Rails.cache.write(cache_key, job.id, :expires_in => 1.hour) end prevent_caching render :status => :accepted, :text => "This file takes a little while to generate. It should be ready shortly at #{request.url}" end end def non_elastic_taxon_stats(search_params) scope = Observation.query(search_params) scope = scope.where("1 = 2") unless stats_adequately_scoped?(search_params) species_counts_scope = scope.joins(:taxon) unless search_params[:rank] == "leaves" && logged_in? && current_user.is_curator? species_counts_scope = species_counts_scope.where("taxa.rank_level <= ?", Taxon::SPECIES_LEVEL) end species_counts_sql = if search_params[:rank] == "leaves" && logged_in? && current_user.is_curator? ancestor_ids_sql = <<-SQL SELECT DISTINCT regexp_split_to_table(ancestry, '/') AS ancestor_id FROM taxa JOIN ( #{species_counts_scope.to_sql} ) AS observations ON observations.taxon_id = taxa.id SQL <<-SQL SELECT o.taxon_id, count(*) AS count_all FROM ( #{species_counts_scope.to_sql} ) AS o LEFT OUTER JOIN ( #{ancestor_ids_sql} ) AS ancestor_ids ON o.taxon_id::text = ancestor_ids.ancestor_id WHERE ancestor_ids.ancestor_id IS NULL GROUP BY o.taxon_id ORDER BY count_all desc LIMIT 5 SQL else <<-SQL SELECT o.taxon_id, count(*) AS count_all FROM (#{species_counts_scope.to_sql}) AS o GROUP BY o.taxon_id ORDER BY count_all desc LIMIT 5 SQL end @species_counts = ActiveRecord::Base.connection.execute(species_counts_sql) taxon_ids = @species_counts.map{|r| r['taxon_id']} rank_counts_sql = <<-SQL SELECT o.rank_name, count(*) AS count_all FROM (#{scope.joins(:taxon).select("DISTINCT ON (taxa.id) taxa.rank AS rank_name").to_sql}) AS o GROUP BY o.rank_name SQL @raw_rank_counts = ActiveRecord::Base.connection.execute(rank_counts_sql) @rank_counts = {} @total = 0 @raw_rank_counts.each do |row| @total += row['count_all'].to_i @rank_counts[row['rank_name']] = row['count_all'].to_i end # TODO: we should set a proper value for @rank_counts[:leaves] end def elastic_taxon_stats(search_params) if search_params[:rank] == "leaves" search_params.delete(:rank) showing_leaves = true end elastic_params = prepare_counts_elastic_query(search_params) taxon_counts = Observation.elastic_search(elastic_params.merge(size: 0, aggregate: { distinct_taxa: { cardinality: { field: "taxon.id", precision_threshold: 10000 } }, rank: { terms: { field: "taxon.rank", size: 30, order: { "distinct_taxa": :desc } }, aggs: { distinct_taxa: { cardinality: { field: "taxon.id", precision_threshold: 10000 } } } } })).response.aggregations @total = taxon_counts.distinct_taxa.value @rank_counts = Hash[ taxon_counts.rank.buckets. map{ |b| [ b["key"], b["distinct_taxa"]["value"] ] } ] elastic_params[:filters] << { range: { "taxon.rank_level" => { lte: Taxon::RANK_LEVELS["species"] } } } species_counts = Observation.elastic_search(elastic_params.merge(size: 0, aggregate: { species: { "taxon.id": 100 } })).response.aggregations # the count is a string to maintain backward compatibility @species_counts = species_counts.species.buckets. map{ |b| { "taxon_id" => b["key"], "count_all" => b["doc_count"].to_s } } if showing_leaves leaf_ids = Observation.elastic_taxon_leaf_ids(elastic_params) @rank_counts[:leaves] = leaf_ids.count # we fetch extra taxa above so we can safely filter # out the non-leaf taxa from the result @species_counts.delete_if{ |s| !leaf_ids.include?(s["taxon_id"]) } end # limit the species_counts to 5 @species_counts = @species_counts[0...5] end def non_elastic_user_stats(search_params, limit) scope = Observation.query(search_params) scope = scope.where("1 = 2") unless stats_adequately_scoped?(search_params) @user_counts = user_obs_counts(scope, limit).to_a @user_taxon_counts = user_taxon_counts(scope, limit).to_a obs_user_ids = @user_counts.map{|r| r['user_id']}.sort tax_user_ids = @user_taxon_counts.map{|r| r['user_id']}.sort # the list of top users is probably different for obs and taxa, so grab the leftovers from each leftover_obs_user_ids = tax_user_ids - obs_user_ids leftover_tax_user_ids = obs_user_ids - tax_user_ids @user_counts += user_obs_counts(scope.where("observations.user_id IN (?)", leftover_obs_user_ids)).to_a @user_taxon_counts += user_taxon_counts(scope.where("observations.user_id IN (?)", leftover_tax_user_ids)).to_a @user_counts = @user_counts[0...limit] @user_taxon_counts = @user_taxon_counts[0...limit] @total = scope.select("DISTINCT observations.user_id").count end def elastic_user_stats(search_params, limit) elastic_params = prepare_counts_elastic_query(search_params) user_obs = Observation.elastic_user_observation_counts(elastic_params, limit) @user_counts = user_obs[:counts] @total = user_obs[:total] @user_taxon_counts = Observation.elastic_user_taxon_counts(elastic_params, limit: limit, count_users: @total) # # the list of top users is probably different for obs and taxa, so grab the leftovers from each obs_user_ids = @user_counts.map{|r| r['user_id']}.sort tax_user_ids = @user_taxon_counts.map{|r| r['user_id']}.sort leftover_obs_user_ids = tax_user_ids - obs_user_ids leftover_tax_user_ids = obs_user_ids - tax_user_ids leftover_obs_user_elastic_params = elastic_params.marshal_copy leftover_obs_user_elastic_params[:where]['user.id'] = leftover_obs_user_ids leftover_tax_user_elastic_params = elastic_params.marshal_copy leftover_tax_user_elastic_params[:where]['user.id'] = leftover_tax_user_ids @user_counts += Observation.elastic_user_observation_counts(leftover_obs_user_elastic_params)[:counts].to_a @user_taxon_counts += Observation.elastic_user_taxon_counts(leftover_tax_user_elastic_params, count_users: leftover_tax_user_ids.length).to_a # don't want to return more than were asked for @user_counts = @user_counts[0...limit] @user_taxon_counts = @user_taxon_counts[0...limit] end def prepare_counts_elastic_query(search_params) elastic_params = Observation.params_to_elastic_query( search_params, current_user: current_user). select{ |k,v| [ :where, :filters ].include?(k) } end def search_cache_key(search_params) search_cache_params = search_params.reject{|k,v| %w(controller action format partial).include?(k.to_s)} # models to IDs - classes are inconsistently represented as strings search_cache_params.each{ |k,v| search_cache_params[k] = ElasticModel.id_or_object(v) } search_cache_params[:locale] ||= I18n.locale search_cache_params[:per_page] ||= search_params[:per_page] search_cache_params[:site_name] ||= SITE_NAME if CONFIG.site_only_observations search_cache_params[:bounds] ||= CONFIG.bounds.to_h if CONFIG.bounds "obs_index_#{Digest::MD5.hexdigest(search_cache_params.sort.to_s)}" end def prepare_map_params(search_params = {}) map_params = valid_map_params(search_params) non_viewer_params = map_params.reject{ |k,v| k == :viewer } if @display_map_tiles if non_viewer_params.empty? # there are no options, so show all observations by default @enable_show_all_layer = true elsif non_viewer_params.length == 1 && map_params[:taxon] # there is just a taxon, so show the taxon observations lyers @map_params = { taxon_layers: [ { taxon: map_params[:taxon], observations: true, ranges: { disabled: true }, places: { disabled: true }, gbif: { disabled: true } } ], focus: :observations } else # otherwise show our catch-all "Featured Observations" custom layer map_params[:viewer_id] = current_user.id if logged_in? @map_params = { observation_layers: [ map_params.merge(observations: @observations) ] } end end end def determine_if_map_should_be_shown( search_params ) if @display_map_tiles = Observation.able_to_use_elasticsearch?( search_params ) prepare_map_params(search_params) end end def valid_map_params(search_params = {}) # make sure we have the params as processed by Observation.query_params map_params = (search_params && search_params[:_query_params_set]) ? search_params.clone : Observation.query_params(params) map_params = map_params.map{ |k,v| if v.is_a?(Array) [ k, v.map{ |vv| ElasticModel.id_or_object(vv) } ] else [ k, ElasticModel.id_or_object(v) ] end }.to_h if map_params[:observations_taxon] map_params[:taxon_id] = map_params.delete(:observations_taxon) end if map_params[:projects] map_params[:project_ids] = map_params.delete(:projects) end if map_params[:user] map_params[:user_id] = map_params.delete(:user) end map_params.select do |k,v| ! [ :utf8, :controller, :action, :page, :per_page, :preferences, :color, :_query_params_set, :order_by, :order ].include?( k.to_sym ) end.compact end def decide_if_skipping_preloading @skipping_preloading = (params[:partial] == "cached_component") end def observations_index_search(params) # making `page` default to a string because HTTP params are # usually strings and we want to keep the cache_key consistent params[:page] ||= "1" search_params = Observation.get_search_params(params, current_user: current_user, site: @site) search_params = Observation.apply_pagination_options(search_params, user_preferences: @prefs) if perform_caching && search_params[:q].blank? && (!logged_in? || search_params[:page].to_i == 1) search_key = search_cache_key(search_params) # Get the cached filtered observations observations = Rails.cache.fetch(search_key, expires_in: 5.minutes, compress: true) do obs = Observation.page_of_results(search_params) # this is doing preloading, as is some code below, but this isn't # entirely redundant. If we preload now we can cache the preloaded # data to save extra time later on. Observation.preload_for_component(obs, logged_in: !!current_user) obs end else observations = Observation.page_of_results(search_params) end set_up_instance_variables(search_params) { params: params, search_params: search_params, observations: observations } end end reverted unintended change #encoding: utf-8 class ObservationsController < ApplicationController skip_before_action :verify_authenticity_token, only: :index, if: :json_request? protect_from_forgery unless: -> { request.format.widget? } #, except: [:stats, :user_stags, :taxa] before_filter :decide_if_skipping_preloading, only: [ :index ] before_filter :allow_external_iframes, only: [:stats, :user_stats, :taxa, :map] before_filter :allow_cors, only: [:index], 'if': -> { Rails.env.development? } WIDGET_CACHE_EXPIRATION = 15.minutes caches_action :of, :expires_in => 1.day, :cache_path => Proc.new {|c| c.params.merge(:locale => I18n.locale)}, :if => Proc.new {|c| c.request.format != :html } cache_sweeper :observation_sweeper, :only => [:create, :update, :destroy] rescue_from ::AbstractController::ActionNotFound do unless @selected_user = User.find_by_login(params[:action]) return render_404 end by_login end before_action :doorkeeper_authorize!, only: [ :create, :update, :destroy, :viewed_updates, :update_fields, :review ], if: lambda { authenticate_with_oauth? } before_filter :load_user_by_login, :only => [:by_login, :by_login_all] before_filter :return_here, :only => [:index, :by_login, :show, :import, :export, :add_from_list, :new, :project] before_filter :authenticate_user!, :unless => lambda { authenticated_with_oauth? }, :except => [:explore, :index, :of, :show, :by_login, :nearby, :widget, :project, :stats, :taxa, :taxon_stats, :user_stats, :community_taxon_summary, :map] load_only = [ :show, :edit, :edit_photos, :update_photos, :destroy, :fields, :viewed_updates, :community_taxon_summary, :update_fields, :review ] before_filter :load_observation, :only => load_only blocks_spam :only => load_only, :instance => :observation before_filter :require_owner, :only => [:edit, :edit_photos, :update_photos, :destroy] before_filter :curator_required, :only => [:curation, :accumulation, :phylogram] before_filter :load_photo_identities, :only => [:new, :new_batch, :show, :new_batch_csv,:edit, :update, :edit_batch, :create, :import, :import_photos, :import_sounds, :new_from_list] before_filter :load_sound_identities, :only => [:new, :new_batch, :show, :new_batch_csv,:edit, :update, :edit_batch, :create, :import, :import_photos, :import_sounds, :new_from_list] before_filter :photo_identities_required, :only => [:import_photos] after_filter :refresh_lists_for_batch, :only => [:create, :update] MOBILIZED = [:add_from_list, :nearby, :add_nearby, :project, :by_login, :index, :show] before_filter :unmobilized, :except => MOBILIZED before_filter :mobilized, :only => MOBILIZED before_filter :load_prefs, :only => [:index, :project, :by_login] ORDER_BY_FIELDS = %w"created_at observed_on project species_guess votes id" REJECTED_FEED_PARAMS = %w"page view filters_open partial action id locale" REJECTED_KML_FEED_PARAMS = REJECTED_FEED_PARAMS + %w"swlat swlng nelat nelng BBOX" MAP_GRID_PARAMS_TO_CONSIDER = REJECTED_KML_FEED_PARAMS + %w( order order_by taxon_id taxon_name projects user_id place_id utf8 d1 d2 ) DISPLAY_ORDER_BY_FIELDS = { 'created_at' => 'date added', 'observations.id' => 'date added', 'id' => 'date added', 'observed_on' => 'date observed', 'species_guess' => 'species name', 'project' => "date added to project", 'votes' => 'faves' } PARTIALS = %w(cached_component observation_component observation mini project_observation) EDIT_PARTIALS = %w(add_photos) PHOTO_SYNC_ATTRS = [:description, :species_guess, :taxon_id, :observed_on, :observed_on_string, :latitude, :longitude, :place_guess] # GET /observations # GET /observations.xml def index if !logged_in? && params[:page].to_i > 100 authenticate_user! return false end params = request.params showing_partial = (params[:partial] && PARTIALS.include?(params[:partial])) # the new default /observations doesn't need any observations # looked up now as it will use Angular/Node. This is for legacy # API methods, and HTML/views and partials if request.format.html? &&!request.format.mobile? && !showing_partial params = params else h = observations_index_search(params) params = h[:params] search_params = h[:search_params] @observations = h[:observations] end respond_to do |format| format.html do if showing_partial pagination_headers_for(@observations) return render_observations_partial(params[:partial]) end # one of the few things we do in Rails. Look up the taxon_name param unless params[:taxon_name].blank? sn = params[:taxon_name].to_s.strip.gsub(/[\s_]+/, ' ').downcase if t = TaxonName.where("lower(name) = ?", sn).first.try(:taxon) params[:taxon_id] = t.id end end render layout: "bootstrap", locals: { params: params } end format.json do Observation.preload_for_component(@observations, logged_in: logged_in?) Observation.preload_associations(@observations, :tags) render_observations_to_json end format.mobile format.geojson do render :json => @observations.to_geojson(:except => [ :geom, :latitude, :longitude, :map_scale, :num_identification_agreements, :num_identification_disagreements, :delta, :location_is_exact]) end format.atom do @updated_at = Observation.last.updated_at end format.dwc do Observation.preload_for_component(@observations, logged_in: logged_in?) Observation.preload_associations(@observations, [ :identifications ]) end format.csv do render_observations_to_csv end format.kml do render_observations_to_kml( :snippet => "#{CONFIG.site_name} Feed for Everyone", :description => "#{CONFIG.site_name} Feed for Everyone", :name => "#{CONFIG.site_name} Feed for Everyone" ) end format.widget do if params[:markup_only] == 'true' render :js => render_to_string(:partial => "widget.html.erb", :locals => { :show_user => true, :target => params[:target], :default_image => params[:default_image], :silence => params[:silence] }) else render :js => render_to_string(:partial => "widget.js.erb", :locals => { :show_user => true }) end end end end def of if request.format == :html redirect_to observations_path(:taxon_id => params[:id]) return end unless @taxon = Taxon.find_by_id(params[:id].to_i) render_404 && return end @observations = Observation.of(@taxon). includes([ :user, :iconic_taxon, { :taxon => :taxon_descriptions }, { :observation_photos => :photo } ]). order("observations.id desc"). limit(500).sort_by{|o| [o.quality_grade == "research" ? 1 : 0, o.id]} respond_to do |format| format.json do render :json => @observations.to_json( :methods => [ :user_login, :iconic_taxon_name, :obs_image_url], :include => [ { :user => { :only => :login } }, :taxon, :iconic_taxon ] ) end format.geojson do render :json => @observations.to_geojson(:except => [ :geom, :latitude, :longitude, :map_scale, :num_identification_agreements, :num_identification_disagreements, :delta, :location_is_exact]) end end end # GET /observations/1 # GET /observations/1.xml def show unless @skipping_preloading @quality_metrics = @observation.quality_metrics.includes(:user) if logged_in? @previous = Observation.page_of_results({ user_id: @observation.user.id, per_page: 1, max_id: @observation.id - 1, order_by: "id", order: "desc" }).first @prev = @previous @next = Observation.page_of_results({ user_id: @observation.user.id, per_page: 1, min_id: @observation.id + 1, order_by: "id", order: "asc" }).first @user_quality_metrics = @observation.quality_metrics.select{|qm| qm.user_id == current_user.id} @project_invitations = @observation.project_invitations.limit(100).to_a @project_invitations_by_project_id = @project_invitations.index_by(&:project_id) end @coordinates_viewable = @observation.coordinates_viewable_by?(current_user) end respond_to do |format| format.html do if params[:partial] == "cached_component" return render(partial: "cached_component", object: @observation, layout: false) end # always display the time in the zone in which is was observed Time.zone = @observation.user.time_zone @identifications = @observation.identifications.includes(:user, :taxon => :photos) @current_identifications = @identifications.select{|o| o.current?} @owners_identification = @current_identifications.detect do |ident| ident.user_id == @observation.user_id end @community_identification = if @observation.community_taxon Identification.new(:taxon => @observation.community_taxon, :observation => @observation) end if logged_in? @viewers_identification = @current_identifications.detect do |ident| ident.user_id == current_user.id end end @current_identifications_by_taxon = @current_identifications.select do |ident| ident.user_id != ident.observation.user_id end.group_by{|i| i.taxon} @sorted_current_identifications_by_taxon = @current_identifications_by_taxon.sort_by do |row| row.last.size end.reverse if logged_in? @projects = current_user.project_users.includes(:project).joins(:project).limit(1000).order("lower(projects.title)").map(&:project) @project_addition_allowed = @observation.user_id == current_user.id @project_addition_allowed ||= @observation.user.preferred_project_addition_by != User::PROJECT_ADDITION_BY_NONE end @places = @coordinates_viewable ? @observation.places : @observation.public_places @project_observations = @observation.project_observations.joins(:project).limit(100).to_a @project_observations_by_project_id = @project_observations.index_by(&:project_id) @comments_and_identifications = (@observation.comments.all + @identifications).sort_by{|r| r.created_at} @photos = @observation.observation_photos.includes(:photo => [:flags]).sort_by do |op| op.position || @observation.observation_photos.size + op.id.to_i end.map{|op| op.photo}.compact @flagged_photos = @photos.select{|p| p.flagged?} @sounds = @observation.sounds.all if @observation.observed_on @day_observations = Observation.by(@observation.user).on(@observation.observed_on) .includes([ :photos, :user ]) .paginate(:page => 1, :per_page => 14) end if logged_in? @subscription = @observation.update_subscriptions.where(user: current_user).first end @observation_links = @observation.observation_links.sort_by{|ol| ol.href} @posts = @observation.posts.published.limit(50) if @observation.taxon unless @places.blank? @listed_taxon = ListedTaxon. joins(:place). where([ "taxon_id = ? AND place_id IN (?) AND establishment_means IS NOT NULL", @observation.taxon_id, @places ]). order("establishment_means IN ('endemic', 'introduced') DESC, places.bbox_area ASC").first @conservation_status = ConservationStatus. where(:taxon_id => @observation.taxon).where("place_id IN (?)", @places). where("iucn >= ?", Taxon::IUCN_NEAR_THREATENED). includes(:place).first end @conservation_status ||= ConservationStatus.where(:taxon_id => @observation.taxon).where("place_id IS NULL"). where("iucn >= ?", Taxon::IUCN_NEAR_THREATENED).first end @observer_provider_authorizations = @observation.user.provider_authorizations @shareable_image_url = if !@photos.blank? && photo = @photos.detect{|p| p.medium_url =~ /^http/} FakeView.image_url(photo.best_url(:original)) else FakeView.iconic_taxon_image_url(@observation.taxon, :size => 200) end @shareable_title = if !@observation.species_guess.blank? @observation.species_guess elsif @observation.taxon if comname = FakeView.common_taxon_name( @observation.taxon, place: @site.try(:place) ).try(:name) "#{comname} (#{@observation.taxon.name})" else @observation.taxon.name end else I18n.t( "something" ) end @shareable_description = @observation.to_plain_s( no_place_guess: !@coordinates_viewable ) @shareable_description += ".\n\n#{@observation.description}" unless @observation.description.blank? if logged_in? user_viewed_updates end if params[:test] == "idcats" && logged_in? leading_taxon_ids = @identifications.select(&:leading?).map(&:taxon_id) if leading_taxon_ids.size > 0 sql = <<-SQL SELECT user_id, count(*) AS ident_count FROM identifications WHERE category = 'improving' AND taxon_id IN (#{leading_taxon_ids.join( "," )}) GROUP BY user_id HAVING count(*) > 0 ORDER BY count(*) DESC LIMIT 10 SQL @users_who_can_help = User.joins( "JOIN (#{sql}) AS ident_users ON ident_users.user_id = users.id" ).order("ident_count DESC").limit(10) elsif @observation.taxon && @observation.taxon.rank_level > Taxon::SPECIES_LEVEL sql = <<-SQL SELECT user_id, count(*) AS ident_count FROM identifications LEFT OUTER JOIN taxon_ancestors ta ON ta.taxon_id = identifications.taxon_id WHERE category = 'improving' AND ta.ancestor_taxon_id = #{@observation.taxon_id} GROUP BY user_id HAVING count(*) > 0 ORDER BY count(*) DESC LIMIT 10 SQL @users_who_can_help = User.joins( "JOIN (#{sql}) AS ident_users ON ident_users.user_id = users.id" ).order("ident_count DESC").limit(10) end end if params[:partial] return render(:partial => params[:partial], :object => @observation, :layout => false) end end format.mobile format.xml { render :xml => @observation } format.json do taxon_options = Taxon.default_json_options taxon_options[:methods] += [:iconic_taxon_name, :image_url, :common_name, :default_name] render :json => @observation.to_json( :viewer => current_user, :methods => [:user_login, :iconic_taxon_name, :captive_flag], :include => { :user => User.default_json_options, :observation_field_values => {:include => {:observation_field => {:only => [:name]}}}, :project_observations => { :include => { :project => { :only => [:id, :title, :description], :methods => [:icon_url] } } }, :observation_photos => { :include => { :photo => { :methods => [:license_code, :attribution], :except => [:original_url, :file_processing, :file_file_size, :file_content_type, :file_file_name, :mobile, :metadata, :user_id, :native_realname, :native_photo_id] } } }, :comments => { :include => { :user => { :only => [:name, :login, :id], :methods => [:user_icon_url] } } }, :taxon => taxon_options, :identifications => { :include => { :user => { :only => [:name, :login, :id], :methods => [:user_icon_url] }, :taxon => taxon_options } }, :faves => { :only => [:created_at], :include => { :user => { :only => [:name, :login, :id], :methods => [:user_icon_url] } } } }) end format.atom do cache end end end # GET /observations/new # GET /observations/new.xml # An attempt at creating a simple new page for batch add def new @observation = Observation.new(:user => current_user) @observation.time_zone = current_user.time_zone if params[:copy] && (copy_obs = Observation.find_by_id(params[:copy])) && copy_obs.user_id == current_user.id %w(observed_on_string time_zone place_guess geoprivacy map_scale positional_accuracy).each do |a| @observation.send("#{a}=", copy_obs.send(a)) end @observation.latitude = copy_obs.private_latitude || copy_obs.latitude @observation.longitude = copy_obs.private_longitude || copy_obs.longitude copy_obs.observation_photos.each do |op| @observation.observation_photos.build(:photo => op.photo) end copy_obs.observation_field_values.each do |ofv| @observation.observation_field_values.build(:observation_field => ofv.observation_field, :value => ofv.value) end end @taxon = Taxon.find_by_id(params[:taxon_id].to_i) unless params[:taxon_id].blank? unless params[:taxon_name].blank? @taxon ||= TaxonName.where("lower(name) = ?", params[:taxon_name].to_s.strip.gsub(/[\s_]+/, ' ').downcase). first.try(:taxon) end if !params[:project_id].blank? @project = if params[:project_id].to_i == 0 Project.includes(:project_observation_fields => :observation_field).find(params[:project_id]) else Project.includes(:project_observation_fields => :observation_field).find_by_id(params[:project_id].to_i) end if @project @place = @project.place @project_curators = @project.project_users.where("role IN (?)", [ProjectUser::MANAGER, ProjectUser::CURATOR]) @tracking_code = params[:tracking_code] if @project.tracking_code_allowed?(params[:tracking_code]) @kml_assets = @project.project_assets.select{|pa| pa.asset_file_name =~ /\.km[lz]$/} end end @place ||= Place.find(params[:place_id]) unless params[:place_id].blank? rescue nil if @place @place_geometry = PlaceGeometry.without_geom.where(place_id: @place).first end if params[:facebook_photo_id] begin sync_facebook_photo rescue Koala::Facebook::APIError => e raise e unless e.message =~ /OAuthException/ redirect_to ProviderAuthorization::AUTH_URLS['facebook'] return end end sync_flickr_photo if params[:flickr_photo_id] && current_user.flickr_identity sync_picasa_photo if params[:picasa_photo_id] && current_user.picasa_identity sync_local_photo if params[:local_photo_id] @welcome = params[:welcome] # this should happen AFTER photo syncing so params can override attrs # from the photo [:latitude, :longitude, :place_guess, :location_is_exact, :map_scale, :positional_accuracy, :positioning_device, :positioning_method, :observed_on_string].each do |obs_attr| next if params[obs_attr].blank? # sync_photo indicates that the user clicked sync photo, so presumably they'd # like the photo attrs to override the URL # invite links are the other case, in which URL params *should* override the # photo attrs b/c the person who made the invite link chose a taxon or something if params[:sync_photo] @observation.send("#{obs_attr}=", params[obs_attr]) if @observation.send(obs_attr).blank? else @observation.send("#{obs_attr}=", params[obs_attr]) end end if @taxon @observation.taxon = @taxon @observation.species_guess = if @taxon.common_name @taxon.common_name.name else @taxon.name end elsif !params[:taxon_name].blank? @observation.species_guess = params[:taxon_name] end @observation_fields = ObservationField.recently_used_by(current_user).limit(10) respond_to do |format| format.html do @observations = [@observation] end format.json { render :json => @observation } end end # GET /observations/1/edit def edit # Only the owner should be able to see this. unless current_user.id == @observation.user_id or current_user.is_admin? redirect_to observation_path(@observation) return end # Make sure user is editing the REAL coordinates if @observation.coordinates_obscured? @observation.latitude = @observation.private_latitude @observation.longitude = @observation.private_longitude @observation.place_guess = @observation.private_place_guess end if params[:facebook_photo_id] begin sync_facebook_photo rescue Koala::Facebook::APIError => e raise e unless e.message =~ /OAuthException/ redirect_to ProviderAuthorization::AUTH_URLS['facebook'] return end end sync_flickr_photo if params[:flickr_photo_id] sync_picasa_photo if params[:picasa_photo_id] sync_local_photo if params[:local_photo_id] @observation_fields = ObservationField.recently_used_by(current_user).limit(10) if @observation.quality_metrics.detect{|qm| qm.user_id == @observation.user_id && qm.metric == QualityMetric::WILD && !qm.agree?} @observation.captive_flag = true end if params[:interpolate_coordinates].yesish? @observation.interpolate_coordinates end respond_to do |format| format.html do if params[:partial] && EDIT_PARTIALS.include?(params[:partial]) return render(:partial => params[:partial], :object => @observation, :layout => false) end end end end # POST /observations # POST /observations.xml def create # Handle the case of a single obs params[:observations] = [['0', params[:observation]]] if params[:observation] if params[:observations].blank? && params[:observation].blank? respond_to do |format| format.html do flash[:error] = t(:no_observations_submitted) redirect_to new_observation_path end format.json { render :status => :unprocessable_entity, :json => "No observations submitted!" } end return end @observations = params[:observations].map do |fieldset_index, observation| next if observation.blank? observation.delete('fieldset_index') if observation[:fieldset_index] o = unless observation[:uuid].blank? current_user.observations.where( uuid: observation[:uuid] ).first end # when we add UUIDs to everything and either stop using strings or # ensure that everything is lowercase, we can stop doing this if o.blank? && !observation[:uuid].blank? o = current_user.observations.where( uuid: observation[:uuid].downcase ).first end o ||= Observation.new o.assign_attributes(observation_params(observation)) o.user = current_user o.user_agent = request.user_agent unless o.site_id o.site = @site || current_user.site o.site = o.site.becomes(Site) if o.site end if doorkeeper_token && (a = doorkeeper_token.application) o.oauth_application = a.becomes(OauthApplication) end # Get photos photos = [] Photo.subclasses.each do |klass| klass_key = klass.to_s.underscore.pluralize.to_sym if params[klass_key] && params[klass_key][fieldset_index] photos += retrieve_photos(params[klass_key][fieldset_index], :user => current_user, :photo_class => klass) end if params["#{klass_key}_to_sync"] && params["#{klass_key}_to_sync"][fieldset_index] if photo = photos.to_a.compact.last photo_o = photo.to_observation PHOTO_SYNC_ATTRS.each do |a| o.send("#{a}=", photo_o.send(a)) if o.send(a).blank? end end end end photo = photos.compact.last if o.new_record? && photo && photo.respond_to?(:to_observation) && !params[:uploader] && (o.observed_on_string.blank? || o.latitude.blank? || o.taxon.blank?) photo_o = photo.to_observation if o.observed_on_string.blank? o.observed_on_string = photo_o.observed_on_string o.observed_on = photo_o.observed_on o.time_observed_at = photo_o.time_observed_at end if o.latitude.blank? o.latitude = photo_o.latitude o.longitude = photo_o.longitude end o.taxon = photo_o.taxon if o.taxon.blank? o.species_guess = photo_o.species_guess if o.species_guess.blank? end o.photos = photos.map{ |p| p.new_record? && !p.is_a?(LocalPhoto) ? Photo.local_photo_from_remote_photo(p) : p } o.sounds << Sound.from_observation_params(params, fieldset_index, current_user) o end current_user.observations << @observations.compact create_project_observations update_user_account # check for errors errors = false if params[:uploader] @observations.compact.each { |obs| obs.errors.delete(:project_observations) errors = true if obs.errors.any? } else @observations.compact.each { |obs| errors = true unless obs.valid? } end respond_to do |format| format.html do unless errors flash[:notice] = params[:success_msg] || t(:observations_saved) if params[:commit] == t(:save_and_add_another) o = @observations.first redirect_to :action => 'new', :latitude => o.coordinates_obscured? ? o.private_latitude : o.latitude, :longitude => o.coordinates_obscured? ? o.private_longitude : o.longitude, :place_guess => o.place_guess, :observed_on_string => o.observed_on_string, :location_is_exact => o.location_is_exact, :map_scale => o.map_scale, :positional_accuracy => o.positional_accuracy, :positioning_method => o.positioning_method, :positioning_device => o.positioning_device, :project_id => params[:project_id] elsif @observations.size == 1 redirect_to observation_path(@observations.first) else redirect_to :action => self.current_user.login end else if @observations.size == 1 if @project @place = @project.place @project_curators = @project.project_users.where("role IN (?)", [ProjectUser::MANAGER, ProjectUser::CURATOR]) @tracking_code = params[:tracking_code] if @project.tracking_code_allowed?(params[:tracking_code]) @kml_assets = @project.project_assets.select{|pa| pa.asset_file_name =~ /\.km[lz]$/} end render :action => 'new' else render :action => 'edit_batch' end end end format.json do if errors json = if @observations.size == 1 && is_iphone_app_2? {:error => @observations.map{|o| o.errors.full_messages}.flatten.uniq.compact.to_sentence} else {:errors => @observations.map{|o| o.errors.full_messages}} end render :json => json, :status => :unprocessable_entity else Observation.refresh_es_index if @observations.size == 1 && is_iphone_app_2? render :json => @observations[0].to_json( :viewer => current_user, :methods => [:user_login, :iconic_taxon_name], :include => { :taxon => Taxon.default_json_options } ) else render :json => @observations.to_json(viewer: current_user, methods: [ :user_login, :iconic_taxon_name, :project_observations ]) end end end end end # PUT /observations/1 # PUT /observations/1.xml def update observation_user = current_user unless params[:admin_action].nil? || !current_user.is_admin? observation_user = Observation.find(params[:id]).user end # Handle the case of a single obs if params[:observation] params[:observations] = [[params[:id], params[:observation]]] elsif params[:id] && params[:observations] params[:observations] = [[params[:id], params[:observations][0]]] end if params[:observations].blank? && params[:observation].blank? respond_to do |format| format.html do flash[:error] = t(:no_observations_submitted) redirect_to new_observation_path end format.json { render :status => :unprocessable_entity, :json => "No observations submitted!" } end return end @observations = Observation.where(id: params[:observations].map{ |k,v| k }, user_id: observation_user) # Make sure there's no evil going on unique_user_ids = @observations.map(&:user_id).uniq more_than_one_observer = unique_user_ids.size > 1 admin_action = unique_user_ids.first != observation_user.id && current_user.has_role?(:admin) if !@observations.blank? && more_than_one_observer && !admin_action msg = t(:you_dont_have_permission_to_edit_that_observation) respond_to do |format| format.html do flash[:error] = msg redirect_to(@observation || observations_path) end format.json do render :status => :unprocessable_entity, :json => {:error => msg} end end return end # Convert the params to a hash keyed by ID. Yes, it's weird hashed_params = Hash[*params[:observations].to_a.flatten] errors = false extra_msg = nil @observations.each_with_index do |observation,i| fieldset_index = observation.id.to_s # Update the flickr photos # Note: this ignore photos thing is a total hack and should only be # included if you are updating observations but aren't including flickr # fields, e.g. when removing something from ID please if !params[:ignore_photos] && !is_mobile_app? # Get photos updated_photos = [] old_photo_ids = observation.photo_ids Photo.subclasses.each do |klass| klass_key = klass.to_s.underscore.pluralize.to_sym next if klass_key.blank? if params[klass_key] && params[klass_key][fieldset_index] updated_photos += retrieve_photos(params[klass_key][fieldset_index], :user => current_user, :photo_class => klass, :sync => true) end end if updated_photos.empty? observation.photos.clear else observation.photos = updated_photos.map{ |p| p.new_record? && !p.is_a?(LocalPhoto) ? Photo.local_photo_from_remote_photo(p) : p } end Photo.subclasses.each do |klass| klass_key = klass.to_s.underscore.pluralize.to_sym next unless params["#{klass_key}_to_sync"] && params["#{klass_key}_to_sync"][fieldset_index] next unless photo = observation.photos.last photo_o = photo.to_observation PHOTO_SYNC_ATTRS.each do |a| hashed_params[observation.id.to_s] ||= {} if hashed_params[observation.id.to_s][a].blank? && observation.send(a).blank? hashed_params[observation.id.to_s][a] = photo_o.send(a) end end end end # Kind of like :ignore_photos, but :editing_sounds makes it opt-in rather than opt-out # If editing sounds and no sound parameters are present, assign to an empty array # This way, sounds will be removed if params[:editing_sounds] params[:soundcloud_sounds] ||= {fieldset_index => []} params[:soundcloud_sounds][fieldset_index] ||= [] observation.sounds = Sound.from_observation_params(params, fieldset_index, current_user) end unless observation.update_attributes(observation_params(hashed_params[observation.id.to_s])) errors = true end if !errors && params[:project_id] && !observation.project_observations.where(:project_id => params[:project_id]).exists? if @project ||= Project.find(params[:project_id]) project_observation = ProjectObservation.create(:project => @project, :observation => observation) extra_msg = if project_observation.valid? "Successfully added to #{@project.title}" else "Failed to add to #{@project.title}: #{project_observation.errors.full_messages.to_sentence}" end end end end respond_to do |format| if errors format.html do if @observations.size == 1 @observation = @observations.first render :action => 'edit' else render :action => 'edit_batch' end end format.xml { render :xml => @observations.collect(&:errors), :status => :unprocessable_entity } format.json do render :status => :unprocessable_entity, :json => { :error => @observations.map{|o| o.errors.full_messages.to_sentence}.to_sentence, :errors => @observations.collect(&:errors) } end elsif @observations.empty? msg = if params[:id] t(:that_observation_no_longer_exists) else t(:those_observations_no_longer_exist) end format.html do flash[:error] = msg redirect_back_or_default(observations_by_login_path(current_user.login)) end format.json { render :json => {:error => msg}, :status => :gone } else format.html do flash[:notice] = "#{t(:observations_was_successfully_updated)} #{extra_msg}" if @observations.size == 1 redirect_to observation_path(@observations.first) else redirect_to observations_by_login_path(observation_user.login) end end format.xml { head :ok } format.js { render :json => @observations } format.json do Observation.refresh_es_index if @observations.size == 1 && is_iphone_app_2? render :json => @observations[0].to_json( viewer: current_user, methods: [:user_login, :iconic_taxon_name], include: { taxon: Taxon.default_json_options, observation_field_values: {}, project_observations: { include: { project: { only: [:id, :title, :description], methods: [:icon_url] } } }, observation_photos: { include: { photo: { methods: [:license_code, :attribution], except: [:original_url, :file_processing, :file_file_size, :file_content_type, :file_file_name, :mobile, :metadata, :user_id, :native_realname, :native_photo_id] } } }, } ) else render json: @observations.to_json( methods: [:user_login, :iconic_taxon_name], viewer: current_user ) end end end end end def edit_photos @observation_photos = @observation.observation_photos if @observation_photos.blank? flash[:error] = t(:that_observation_doesnt_have_any_photos) return redirect_to edit_observation_path(@observation) end end def update_photos @observation_photos = ObservationPhoto.where(id: params[:observation_photos].map{|k,v| k}) @observation_photos.each do |op| next unless @observation.observation_photo_ids.include?(op.id) op.update_attributes(params[:observation_photos][op.id.to_s]) end flash[:notice] = t(:photos_updated) redirect_to edit_observation_path(@observation) end # DELETE /observations/1 # DELETE /observations/1.xml def destroy @observation.destroy respond_to do |format| format.html do flash[:notice] = t(:observation_was_deleted) redirect_to(observations_by_login_path(current_user.login)) end format.xml { head :ok } format.json do Observation.refresh_es_index head :ok end end end ## Custom actions ############################################################ def curation @flags = Flag.where(resolved: false, flaggable_type: "Observation"). includes(:user, :flaggable). paginate(page: params[:page]) end def new_batch @step = 1 @observations = [] if params[:batch] params[:batch][:taxa].each_line do |taxon_name_str| next if taxon_name_str.strip.blank? latitude = params[:batch][:latitude] longitude = params[:batch][:longitude] @observations << Observation.new( :user => current_user, :species_guess => taxon_name_str, :taxon => Taxon.single_taxon_for_name(taxon_name_str.strip), :place_guess => params[:batch][:place_guess], :longitude => longitude, :latitude => latitude, :map_scale => params[:batch][:map_scale], :positional_accuracy => params[:batch][:positional_accuracy], :positioning_method => params[:batch][:positioning_method], :positioning_device => params[:batch][:positioning_device], :location_is_exact => params[:batch][:location_is_exact], :observed_on_string => params[:batch][:observed_on_string], :time_zone => current_user.time_zone) end @step = 2 end end def new_bulk_csv if params[:upload].blank? || params[:upload] && params[:upload][:datafile].blank? flash[:error] = "You must select a CSV file to upload." return redirect_to :action => "import" end unique_hash = { :class => 'BulkObservationFile', :user_id => current_user.id, :filename => params[:upload]['datafile'].original_filename, :project_id => params[:upload][:project_id] } # Copy to a temp directory path = private_page_cache_path(File.join( "bulk_observation_files", "#{unique_hash.to_s.parameterize}-#{Time.now}.csv" )) FileUtils.mkdir_p File.dirname(path), :mode => 0755 File.open(path, 'wb') { |f| f.write(params[:upload]['datafile'].read) } unless CONFIG.coordinate_systems.blank? || params[:upload][:coordinate_system].blank? if coordinate_system = CONFIG.coordinate_systems[params[:upload][:coordinate_system]] proj4 = coordinate_system.proj4 end end # Send the filename to a background processor bof = BulkObservationFile.new( path, current_user.id, project_id: params[:upload][:project_id], coord_system: proj4 ) Delayed::Job.enqueue( bof, priority: USER_PRIORITY, unique_hash: unique_hash ) # Notify the user that it's getting processed and return them to the upload screen. flash[:notice] = 'Observation file has been queued for import.' if params[:upload][:project_id].blank? redirect_to import_observations_path else project = Project.find(params[:upload][:project_id].to_i) redirect_to(project_path(project)) end end # Edit a batch of observations def edit_batch observation_ids = params[:o].is_a?(String) ? params[:o].split(',') : [] @observations = Observation.where("id in (?) AND user_id = ?", observation_ids, current_user). includes(:quality_metrics, {:observation_photos => :photo}, :taxon) @observations.map do |o| if o.coordinates_obscured? o.latitude = o.private_latitude o.longitude = o.private_longitude o.place_guess = o.private_place_guess end if qm = o.quality_metrics.detect{|qm| qm.user_id == o.user_id} o.captive_flag = qm.metric == QualityMetric::WILD && !qm.agree? ? 1 : 0 else o.captive_flag = "unknown" end o end end def delete_batch @observations = Observation.where(id: params[:o].split(','), user_id: current_user) @observations.each do |observation| observation.destroy if observation.user == current_user end respond_to do |format| format.html do flash[:notice] = t(:observations_deleted) redirect_to observations_by_login_path(current_user.login) end format.js { render :text => "Observations deleted.", :status => 200 } end end # Import observations from external sources def import if @default_photo_identity ||= @photo_identities.first provider_name = if @default_photo_identity.is_a?(ProviderAuthorization) @default_photo_identity.photo_source_name else @default_photo_identity.class.to_s.underscore.split('_').first end @default_photo_identity_url = "/#{provider_name.downcase}/photo_fields?context=user" end @project = Project.find(params[:project_id].to_i) if params[:project_id] if logged_in? @projects = current_user.project_users.joins(:project).includes(:project).order('lower(projects.title)').collect(&:project) @project_templates = {} @projects.each do |p| @project_templates[p.title] = p.observation_fields.order(:position) if @project && p.id == @project.id end end end def import_photos photos = Photo.subclasses.map do |klass| retrieve_photos(params[klass.to_s.underscore.pluralize.to_sym], :user => current_user, :photo_class => klass) end.flatten.compact @observations = photos.map{|p| p.to_observation} @observation_photos = ObservationPhoto.joins(:photo, :observation). where("photos.native_photo_id IN (?)", photos.map(&:native_photo_id)) @step = 2 render :template => 'observations/new_batch' rescue Timeout::Error => e flash[:error] = t(:sorry_that_photo_provider_isnt_responding) Rails.logger.error "[ERROR #{Time.now}] Timeout: #{e}" redirect_to :action => "import" end def import_sounds sounds = Sound.from_observation_params(params, 0, current_user) @observations = sounds.map{|s| s.to_observation} @step = 2 render :template => 'observations/new_batch' end def export if params[:flow_task_id] if @flow_task = ObservationsExportFlowTask.find_by_id(params[:flow_task_id]) output = @flow_task.outputs.first @export_url = output ? FakeView.uri_join(root_url, output.file.url).to_s : nil end end @recent_exports = ObservationsExportFlowTask. where(user_id: current_user).order(id: :desc).limit(20) @observation_fields = ObservationField.recently_used_by(current_user).limit(50).sort_by{|of| of.name.downcase} set_up_instance_variables(Observation.get_search_params(params, current_user: current_user, site: @site)) respond_to do |format| format.html end end def add_from_list @order = params[:order] || "alphabetical" if @list = List.find_by_id(params[:id]) @cache_key = {:controller => "observations", :action => "add_from_list", :id => @list.id, :order => @order} unless fragment_exist?(@cache_key) @listed_taxa = @list.listed_taxa.order_by(@order).includes( taxon: [:photos, { taxon_names: :place_taxon_names } ]).paginate(page: 1, per_page: 1000) @listed_taxa_alphabetical = @listed_taxa.to_a.sort! {|a,b| a.taxon.default_name.name <=> b.taxon.default_name.name} @listed_taxa = @listed_taxa_alphabetical if @order == ListedTaxon::ALPHABETICAL_ORDER @taxon_ids_by_name = {} ancestor_ids = @listed_taxa.map {|lt| lt.taxon.ancestry.to_s.split('/')}.flatten.uniq @orders = Taxon.where(rank: "order", id: ancestor_ids).order(:ancestry) @families = Taxon.where(rank: "family", id: ancestor_ids).order(:ancestry) end end @user_lists = current_user.lists.limit(100) respond_to do |format| format.html format.mobile { render "add_from_list.html.erb" } format.js do if fragment_exist?(@cache_key) render read_fragment(@cache_key) else render :partial => 'add_from_list.html.erb' end end end end def new_from_list @taxa = Taxon.where(id: params[:taxa]).includes(:taxon_names) if @taxa.blank? flash[:error] = t(:no_taxa_selected) return redirect_to :action => :add_from_list end @observations = @taxa.map do |taxon| current_user.observations.build(:taxon => taxon, :species_guess => taxon.default_name.name, :time_zone => current_user.time_zone) end @step = 2 render :new_batch end # gets observations by user login def by_login block_if_spammer(@selected_user) && return params.update(:user_id => @selected_user.id, :viewer => current_user, :filter_spam => (current_user.blank? || current_user != @selected_user) ) search_params = Observation.get_search_params(params, current_user: current_user) search_params = Observation.apply_pagination_options(search_params, user_preferences: @prefs) @observations = Observation.page_of_results(search_params) set_up_instance_variables(search_params) Observation.preload_for_component(@observations, logged_in: !!current_user) respond_to do |format| format.html do determine_if_map_should_be_shown(search_params) @observer_provider_authorizations = @selected_user.provider_authorizations if logged_in? && @selected_user.id == current_user.id @project_users = current_user.project_users.joins(:project).order("projects.title") if @proj_obs_errors = Rails.cache.read("proj_obs_errors_#{current_user.id}") @project = Project.find_by_id(@proj_obs_errors[:project_id]) @proj_obs_errors_obs = current_user.observations. where(id: @proj_obs_errors[:errors].keys).includes(:photos, :taxon) Rails.cache.delete("proj_obs_errors_#{current_user.id}") end end if (partial = params[:partial]) && PARTIALS.include?(partial) return render_observations_partial(partial) end end format.mobile format.json do if timestamp = Chronic.parse(params[:updated_since]) deleted_observation_ids = DeletedObservation.where("user_id = ? AND created_at >= ?", @selected_user, timestamp). select(:observation_id).limit(500).map(&:observation_id) response.headers['X-Deleted-Observations'] = deleted_observation_ids.join(',') end render_observations_to_json end format.kml do render_observations_to_kml( :snippet => "#{CONFIG.site_name} Feed for User: #{@selected_user.login}", :description => "#{CONFIG.site_name} Feed for User: #{@selected_user.login}", :name => "#{CONFIG.site_name} Feed for User: #{@selected_user.login}" ) end format.atom format.csv do render_observations_to_csv(:show_private => logged_in? && @selected_user.id == current_user.id) end format.widget do if params[:markup_only]=='true' render :js => render_to_string(:partial => "widget.html.erb", :locals => { :show_user => false, :target => params[:target], :default_image => params[:default_image], :silence => params[:silence] }) else render :js => render_to_string(:partial => "widget.js.erb") end end end end def by_login_all if @selected_user.id != current_user.id flash[:error] = t(:you_dont_have_permission_to_do_that) redirect_back_or_default(root_url) return end path_for_csv = private_page_cache_path("observations/#{@selected_user.login}.all.csv") delayed_csv(path_for_csv, @selected_user) end # Renders observation components as form fields for inclusion in # observation-picking form widgets def selector search_params = Observation.get_search_params(params, current_user: current_user) search_params = Observation.apply_pagination_options(search_params) @observations = Observation.latest.query(search_params).paginate( page: search_params[:page], per_page: search_params[:per_page]) Observation.preload_for_component(@observations, logged_in: !!current_user) respond_to do |format| format.html { render :layout => false, :partial => 'selector'} # format.js end end def widget @project = Project.find_by_id(params[:project_id].to_i) if params[:project_id] @place = Place.find_by_id(params[:place_id].to_i) if params[:place_id] @taxon = Taxon.find_by_id(params[:taxon_id].to_i) if params[:taxon_id] @order_by = params[:order_by] || "observed_on" @order = params[:order] || "desc" @limit = params[:limit] || 5 @limit = @limit.to_i if %w"logo-small.gif logo-small.png logo-small-white.png none".include?(params[:logo]) @logo = params[:logo] end @logo ||= "logo-small.gif" @layout = params[:layout] || "large" url_params = { :format => "widget", :limit => @limit, :order => @order, :order_by => @order_by, :layout => @layout, } @widget_url = if @place observations_url(url_params.merge(:place_id => @place.id)) elsif @taxon observations_url(url_params.merge(:taxon_id => @taxon.id)) elsif @project project_observations_url(@project.id, url_params) elsif logged_in? observations_by_login_feed_url(current_user.login, url_params) end if @widget_url @widget_url.gsub!('http:', '') end respond_to do |format| format.html end end def nearby @lat = params[:latitude].to_f @lon = params[:longitude].to_f if @lat && @lon @observations = Observation.elastic_paginate( page: params[:page], sort: { _geo_distance: { location: [ @lon, @lat ], unit: "km", order: "asc" } } ) end @observations ||= Observation.latest.paginate(:page => params[:page]) request.format = :mobile respond_to do |format| format.mobile end end def add_nearby @observation = current_user.observations.build(:time_zone => current_user.time_zone) request.format = :mobile respond_to do |format| format.mobile end end def project @project = Project.find(params[:id]) rescue nil unless @project flash[:error] = t(:that_project_doesnt_exist) redirect_to request.env["HTTP_REFERER"] || projects_path return end params[:projects] = @project.id search_params = Observation.get_search_params(params, current_user: current_user) search_params = Observation.apply_pagination_options(search_params, user_preferences: @prefs) search_params.delete(:id) @observations = Observation.page_of_results(search_params) set_up_instance_variables(search_params) Observation.preload_for_component(@observations, logged_in: !!current_user) @project_observations = @project.project_observations.where(observation: @observations.map(&:id)). includes([ { :curator_identification => [ :taxon, :user ] } ]) @project_observations_by_observation_id = @project_observations.index_by(&:observation_id) @kml_assets = @project.project_assets.select{|pa| pa.asset_file_name =~ /\.km[lz]$/} respond_to do |format| format.html do determine_if_map_should_be_shown(search_params) if (partial = params[:partial]) && PARTIALS.include?(partial) return render_observations_partial(partial) end end format.json do render_observations_to_json end format.atom do @updated_at = Observation.last.updated_at render :action => "index" end format.csv do pagination_headers_for(@observations) render :text => ProjectObservation.to_csv(@project_observations, :user => current_user) end format.kml do render_observations_to_kml( :snippet => "#{@project.title.html_safe} Observations", :description => "Observations feed for the #{CONFIG.site_name} project '#{@project.title.html_safe}'", :name => "#{@project.title.html_safe} Observations" ) end format.widget do if params[:markup_only] == 'true' render :js => render_to_string(:partial => "widget.html.erb", :locals => { :show_user => true, :target => params[:target], :default_image => params[:default_image], :silence => params[:silence] }) else render :js => render_to_string(:partial => "widget.js.erb", :locals => { :show_user => true }) end end format.mobile end end def project_all @project = Project.find(params[:id]) rescue nil unless @project flash[:error] = t(:that_project_doesnt_exist) redirect_to request.env["HTTP_REFERER"] || projects_path return end unless @project.curated_by?(current_user) flash[:error] = t(:only_project_curators_can_do_that) redirect_to request.env["HTTP_REFERER"] || @project return end path_for_csv = private_page_cache_path("observations/project/#{@project.slug}.all.csv") delayed_csv(path_for_csv, @project) end def identify render layout: "bootstrap" end def upload render layout: "basic" end def identotron @observation = Observation.find_by_id((params[:observation] || params[:observation_id]).to_i) @taxon = Taxon.find_by_id(params[:taxon].to_i) @q = params[:q] unless params[:q].blank? if @observation @places = if @observation.coordinates_viewable_by?( current_user ) @observation.places.try(:reverse) else @observation.public_places.try(:reverse) end if @observation.taxon && @observation.taxon.species_or_lower? @taxon ||= @observation.taxon.genus else @taxon ||= @observation.taxon end if @taxon && @places @place = @places.reverse.detect {|p| p.taxa.self_and_descendants_of(@taxon).exists?} end end @place ||= (Place.find(params[:place_id]) rescue nil) || @places.try(:last) @default_taxa = @taxon ? @taxon.ancestors : Taxon::ICONIC_TAXA @taxon ||= Taxon::LIFE @default_taxa = [@default_taxa, @taxon].flatten.compact @establishment_means = params[:establishment_means] if ListedTaxon::ESTABLISHMENT_MEANS.include?(params[:establishment_means]) respond_to do |format| format.html end end def fields @project = Project.find(params[:project_id]) rescue nil @observation_fields = if @project @project.observation_fields elsif params[:observation_fields] ObservationField.where("id IN (?)", params[:observation_fields]) else @observation_fields = ObservationField.recently_used_by(current_user).limit(10) end render :layout => false end def update_fields unless @observation.fields_addable_by?(current_user) respond_to do |format| msg = t(:you_dont_have_permission_to_do_that) format.html do flash[:error] = msg redirect_back_or_default @observation end format.json do render :status => 401, :json => {:error => msg} end end return end if params[:observation].blank? respond_to do |format| msg = t(:you_must_choose_an_observation_field) format.html do flash[:error] = msg redirect_back_or_default @observation end format.json do render :status => :unprocessable_entity, :json => {:error => msg} end end return end ofv_attrs = params[:observation][:observation_field_values_attributes] ofv_attrs.each do |k,v| ofv_attrs[k][:updater_user_id] = current_user.id end o = { :observation_field_values_attributes => ofv_attrs} respond_to do |format| if @observation.update_attributes(o) if !params[:project_id].blank? && @observation.user_id == current_user.id && (@project = Project.find(params[:project_id]) rescue nil) @project_observation = @observation.project_observations.create(project: @project, user: current_user) end format.html do flash[:notice] = I18n.t(:observations_was_successfully_updated) if @project_observation && !@project_observation.valid? flash[:notice] += I18n.t(:however_there_were_some_issues, :issues => @project_observation.errors.full_messages.to_sentence) end redirect_to @observation end format.json do render :json => @observation.to_json( :viewer => current_user, :include => { :observation_field_values => {:include => {:observation_field => {:only => [:name]}}} } ) end else msg = "Failed update observation: #{@observation.errors.full_messages.to_sentence}" format.html do flash[:error] = msg redirect_to @observation end format.json do render :status => :unprocessable_entity, :json => {:error => msg} end end end end def photo @observations = [] @errors = [] if params[:files].blank? respond_to do |format| format.json do render :status => :unprocessable_entity, :json => { :error => "You must include files to convert to observations." } end end return end params[:files].each_with_index do |file, i| lp = LocalPhoto.new(:file => file, :user => current_user) o = lp.to_observation if params[:observations] && obs_params = params[:observations][i] obs_params.each do |k,v| o.send("#{k}=", v) unless v.blank? end end o.site ||= @site || current_user.site if o.save @observations << o else @errors << o.errors end end respond_to do |format| format.json do unless @errors.blank? render :status => :unprocessable_entity, json: {errors: @errors.map{|e| e.full_messages.to_sentence}} return end render_observations_to_json(:include => { :taxon => { :only => [:name, :id, :rank, :rank_level, :is_iconic], :methods => [:default_name, :image_url, :iconic_taxon_name, :conservation_status_name], :include => { :iconic_taxon => { :only => [:id, :name] }, :taxon_names => { :only => [:id, :name, :lexicon] } } } }) end end end def stats @headless = @footless = true stats_adequately_scoped? respond_to do |format| format.html end end def taxa can_view_leaves = logged_in? && current_user.is_curator? params[:rank] = nil unless can_view_leaves params[:skip_order] = true search_params = Observation.get_search_params(params, current_user: current_user) if stats_adequately_scoped?(search_params) if Observation.able_to_use_elasticsearch?(search_params) if params[:rank] == "leaves" search_params.delete(:rank) end elastic_params = prepare_counts_elastic_query(search_params) # using 0 for the aggregation count to get all results distinct_taxa = Observation.elastic_search(elastic_params.merge(size: 0, aggregate: { species: { "taxon.id": 0 } })).response.aggregations @taxa = Taxon.where(id: distinct_taxa.species.buckets.map{ |b| b["key"] }) # if `leaves` were requested, remove any taxon in another's ancestry if params[:rank] == "leaves" ancestors = { } @taxa.each do |t| t.ancestor_ids.each do |aid| ancestors[aid] ||= 0 ancestors[aid] += 1 end end @taxa = @taxa.select{ |t| !ancestors[t.id] } end else oscope = Observation.query(search_params) if params[:rank] == "leaves" && can_view_leaves ancestor_ids_sql = <<-SQL SELECT DISTINCT regexp_split_to_table(ancestry, '/') AS ancestor_id FROM taxa JOIN ( #{oscope.to_sql} ) AS observations ON observations.taxon_id = taxa.id SQL sql = <<-SQL SELECT DISTINCT ON (taxa.id) taxa.* FROM taxa LEFT OUTER JOIN ( #{ancestor_ids_sql} ) AS ancestor_ids ON taxa.id::text = ancestor_ids.ancestor_id JOIN ( #{oscope.to_sql} ) AS observations ON observations.taxon_id = taxa.id WHERE ancestor_ids.ancestor_id IS NULL SQL @taxa = Taxon.find_by_sql(sql) else @taxa = Taxon.find_by_sql("SELECT DISTINCT ON (taxa.id) taxa.* from taxa INNER JOIN (#{oscope.to_sql}) as o ON o.taxon_id = taxa.id") end end # hack to test what this would look like @taxa = case params[:order] when "observations_count" @taxa.sort_by do |t| c = if search_params[:place] # this is a dumb hack. if i was smarter, i would have tried tp pull # this out of the sql with GROUP and COUNT, but I couldn't figure it # out --kueda 20150430 if lt = search_params[:place].listed_taxa.where(primary_listing: true, taxon_id: t.id).first lt.observations_count else # if there's no listed taxon assume it's been observed once 1 end else t.observations_count end c.to_i * -1 end when "name" @taxa.sort_by(&:name) else @taxa end else @taxa = [ ] end respond_to do |format| format.html do @headless = true ancestor_ids = @taxa.map{|t| t.ancestor_ids[1..-1]}.flatten.uniq ancestors = Taxon.where(id: ancestor_ids) taxa_to_arrange = (ancestors + @taxa).sort_by{|t| "#{t.ancestry}/#{t.id}"} @arranged_taxa = Taxon.arrange_nodes(taxa_to_arrange) @taxon_names_by_taxon_id = TaxonName. where(taxon_id: taxa_to_arrange.map(&:id).uniq). includes(:place_taxon_names). group_by(&:taxon_id) render :layout => "bootstrap" end format.csv do Taxon.preload_associations(@taxa, [ :ancestor_taxa, { taxon_names: :place_taxon_names }]) render :text => @taxa.to_csv( :only => [:id, :name, :rank, :rank_level, :ancestry, :is_active], :methods => [:common_name_string, :iconic_taxon_name, :taxonomic_kingdom_name, :taxonomic_phylum_name, :taxonomic_class_name, :taxonomic_order_name, :taxonomic_family_name, :taxonomic_genus_name, :taxonomic_species_name] ) end format.json do Taxon.preload_associations(@taxa, :taxon_descriptions) render :json => { :taxa => @taxa } end end end def taxon_stats params[:skip_order] = true search_params = Observation.get_search_params(params, current_user: current_user) if stats_adequately_scoped?(search_params) && request.format.json? if Observation.able_to_use_elasticsearch?(search_params) elastic_taxon_stats(search_params) else non_elastic_taxon_stats(search_params) end else @species_counts = [ ] @rank_counts = { } end @taxa = Taxon.where(id: @species_counts.map{ |r| r["taxon_id"] }). includes({ taxon_photos: :photo }, :taxon_names) @taxa_by_taxon_id = @taxa.index_by(&:id) @species_counts_json = @species_counts.map do |row| taxon = @taxa_by_taxon_id[row['taxon_id'].to_i] taxon.locale = I18n.locale { :count => row['count_all'], :taxon => taxon.as_json( :methods => [:default_name, :image_url, :iconic_taxon_name, :conservation_status_name], :only => [:id, :name, :rank, :rank_level] ) } end respond_to do |format| format.json do render :json => { :total => @total, :species_counts => @species_counts_json, :rank_counts => @rank_counts } end end end def user_stats params[:skip_order] = true search_params = Observation.get_search_params(params, current_user: current_user) limit = params[:limit].to_i limit = 500 if limit > 500 || limit <= 0 stats_adequately_scoped?(search_params) # all the HTML view needs to know is stats_adequately_scoped? if request.format.json? if Observation.able_to_use_elasticsearch?(search_params) elastic_user_stats(search_params, limit) else non_elastic_user_stats(search_params, limit) end @user_ids = @user_counts.map{ |c| c["user_id"] } | @user_taxon_counts.map{ |c| c["user_id"] } @users = User.where(id: @user_ids). select("id, login, name, icon_file_name, icon_updated_at, icon_content_type") @users_by_id = @users.index_by(&:id) else @user_counts = [ ] @user_taxon_counts = [ ] end respond_to do |format| format.html do @headless = true render layout: "bootstrap" end format.json do render :json => { :total => @total, :most_observations => @user_counts.map{|row| @users_by_id[row['user_id'].to_i].blank? ? nil : { :count => row['count_all'].to_i, :user => @users_by_id[row['user_id'].to_i].as_json( :only => [:id, :name, :login], :methods => [:user_icon_url] ) } }.compact, :most_species => @user_taxon_counts.map{|row| @users_by_id[row['user_id'].to_i].blank? ? nil : { :count => row['count_all'].to_i, :user => @users_by_id[row['user_id'].to_i].as_json( :only => [:id, :name, :login], :methods => [:user_icon_url] ) } }.compact } end end end def moimport if @api_key = params[:api_key] mot = MushroomObserverImportFlowTask.new @mo_user_id = mot.mo_user_id( @api_key ) @mo_user_name = mot.mo_user_name( @api_key ) @results = mot.get_results_xml( api_key: @api_key ).map{ |r| [r, mot.observation_from_result( r, skip_images: true )] } end respond_to do |format| format.html { render layout: "bootstrap" } end end private def observation_params(options = {}) p = options.blank? ? params : options p.permit( :captive_flag, :coordinate_system, :description, :force_quality_metrics, :geo_x, :geo_y, :geoprivacy, :iconic_taxon_id, :latitude, :license, :location_is_exact, :longitude, :make_license_default, :make_licenses_same, :map_scale, :oauth_application_id, :observed_on_string, :place_guess, :positional_accuracy, :positioning_device, :positioning_method, :prefers_community_taxon, :quality_grade, :species_guess, :tag_list, :taxon_id, :taxon_name, :time_zone, :uuid, :zic_time_zone, :site_id, observation_field_values_attributes: [ :_destroy, :id, :observation_field_id, :value ] ) end def user_obs_counts(scope, limit = 500) user_counts_sql = <<-SQL SELECT o.user_id, count(*) AS count_all FROM (#{scope.to_sql}) AS o GROUP BY o.user_id ORDER BY count_all desc LIMIT #{limit} SQL ActiveRecord::Base.connection.execute(user_counts_sql) end def user_taxon_counts(scope, limit = 500) unique_taxon_users_scope = scope. select("DISTINCT observations.taxon_id, observations.user_id"). joins(:taxon). where("taxa.rank_level <= ?", Taxon::SPECIES_LEVEL) user_taxon_counts_sql = <<-SQL SELECT o.user_id, count(*) AS count_all FROM (#{unique_taxon_users_scope.to_sql}) AS o GROUP BY o.user_id ORDER BY count_all desc LIMIT #{limit} SQL ActiveRecord::Base.connection.execute(user_taxon_counts_sql) end public def accumulation params[:order_by] = "observed_on" params[:order] = "asc" search_params = Observation.get_search_params(params, current_user: current_user) set_up_instance_variables(search_params) scope = Observation.query(search_params) scope = scope.where("1 = 2") unless stats_adequately_scoped?(search_params) scope = scope.joins(:taxon). select("observations.id, observations.user_id, observations.created_at, observations.observed_on, observations.time_observed_at, observations.time_zone, taxa.ancestry, taxon_id"). where("time_observed_at IS NOT NULL") rows = ActiveRecord::Base.connection.execute(scope.to_sql) row = rows.first @observations = rows.map do |row| { :id => row['id'].to_i, :user_id => row['user_id'].to_i, :created_at => DateTime.parse(row['created_at']), :observed_on => row['observed_on'] ? Date.parse(row['observed_on']) : nil, :time_observed_at => row['time_observed_at'] ? DateTime.parse(row['time_observed_at']).in_time_zone(row['time_zone']) : nil, :offset_hours => DateTime.parse(row['time_observed_at']).in_time_zone(row['time_zone']).utc_offset / 60 / 60, :ancestry => row['ancestry'], :taxon_id => row['taxon_id'] ? row['taxon_id'].to_i : nil } end respond_to do |format| format.html do @headless = true render :layout => "bootstrap" end format.json do render :json => { :observations => @observations } end end end def phylogram params[:skip_order] = true search_params = Observation.get_search_params(params, current_user: current_user) scope = Observation.query(search_params) scope = scope.where("1 = 2") unless stats_adequately_scoped?(search_params) ancestor_ids_sql = <<-SQL SELECT DISTINCT regexp_split_to_table(ancestry, '/') AS ancestor_id FROM taxa JOIN ( #{scope.to_sql} ) AS observations ON observations.taxon_id = taxa.id SQL sql = <<-SQL SELECT taxa.id, name, ancestry FROM taxa LEFT OUTER JOIN ( #{ancestor_ids_sql} ) AS ancestor_ids ON taxa.id::text = ancestor_ids.ancestor_id JOIN ( #{scope.to_sql} ) AS observations ON observations.taxon_id = taxa.id WHERE ancestor_ids.ancestor_id IS NULL SQL @taxa = ActiveRecord::Base.connection.execute(sql) respond_to do |format| format.html do @headless = true render :layout => "bootstrap" end format.json do render :json => { :taxa => @taxa } end end end def viewed_updates user_viewed_updates respond_to do |format| format.html { redirect_to @observation } format.json { head :no_content } end end def review user_reviewed respond_to do |format| format.html { redirect_to @observation } format.json do Observation.refresh_es_index head :no_content end end end def email_export unless flow_task = current_user.flow_tasks.find_by_id(params[:id]) render status: :unprocessable_entity, text: "Flow task doesn't exist" return end if flow_task.user_id != current_user.id render status: :unprocessable_entity, text: "You don't have permission to do that" return end if flow_task.outputs.exists? Emailer.observations_export_notification(flow_task).deliver_now render status: :ok, text: "" return elsif flow_task.error Emailer.observations_export_failed_notification(flow_task).deliver_now render status: :ok, text: "" return end flow_task.options = flow_task.options.merge(:email => true) if flow_task.save render status: :ok, text: "" else render status: :unprocessable_entity, text: flow_task.errors.full_messages.to_sentence end end def community_taxon_summary render :layout => false, :partial => "community_taxon_summary" end def map @taxa = [ ] @places = [ ] @user = User.find_by_id(params[:user_id]) @project = Project.find(params[:project_id]) rescue nil if params[:taxon_id] @taxa = [ Taxon.find_by_id(params[:taxon_id].to_i) ] elsif params[:taxon_ids] @taxa = Taxon.where(id: params[:taxon_ids]) end if params[:place_id] @places = [ Place.find_by_id(params[:place_id].to_i) ] elsif params[:place_ids] @places = Place.where(id: params[:place_ids]) end if params[:render_place_id] @render_place = Place.find_by_id(params[:render_place_id]) end if @taxa.length == 1 @taxon = @taxa.first @taxon_hash = { } common_name = view_context.common_taxon_name(@taxon).try(:name) rank_label = @taxon.rank ? t('ranks.#{ @taxon.rank.downcase }', default: @taxon.rank).capitalize : t(:unknown_rank) display_name = common_name || (rank_label + " " + @taxon.name) @taxon_hash[:display_label] = I18n.t(:observations_of_taxon, taxon_name: display_name) if @taxon.iconic_taxon @taxon_hash[:iconic_taxon_name] = @taxon.iconic_taxon.name end end @elastic_params = valid_map_params @default_color = params[:color] || (@taxa.empty? ? "heatmap" : nil) @map_style = (( params[:color] || @taxa.any? ) && params[:color] != "heatmap" ) ? "colored_heatmap" : "heatmap" @map_type = ( params[:type] == "map" ) ? "MAP" : "SATELLITE" @default_color = params[:heatmap_colors] if @map_style == "heatmap" @about_url = CONFIG.map_about_url ? CONFIG.map_about_url : view_context.wiki_page_url('help', anchor: 'mapsymbols') end ## Protected / private actions ############################################### private def user_viewed_updates return unless logged_in? obs_updates = UpdateAction.joins(:update_subscribers). where(resource: @observation). where("update_subscribers.subscriber_id = ?", current_user.id) UpdateAction.user_viewed_updates(obs_updates, current_user.id) end def user_reviewed return unless logged_in? review = ObservationReview.where(observation_id: @observation.id, user_id: current_user.id).first_or_create reviewed = if request.delete? false else params[:reviewed] === "false" ? false : true end review.update_attributes({ user_added: true, reviewed: reviewed }) review.observation.elastic_index! end def stats_adequately_scoped?(search_params = { }) # use the supplied search_params if available. Those will already have # tried to resolve and instances referred to by ID stats_params = search_params.blank? ? params : search_params if stats_params[:d1] d1 = (Date.parse(stats_params[:d1]) rescue Date.today) d2 = stats_params[:d2] ? (Date.parse(stats_params[:d2]) rescue Date.today) : Date.today return false if d2 - d1 > 366 end @stats_adequately_scoped = !( stats_params[:d1].blank? && stats_params[:projects].blank? && stats_params[:place_id].blank? && stats_params[:user_id].blank? && stats_params[:on].blank? && stats_params[:created_on].blank? && stats_params[:apply_project_rules_for].blank? ) end def retrieve_photos(photo_list = nil, options = {}) return [] if photo_list.blank? photo_list = photo_list.values if photo_list.is_a?(Hash) photo_list = [photo_list] unless photo_list.is_a?(Array) photo_class = options[:photo_class] || Photo # simple algorithm, # 1. create an array to be passed back to the observation obj # 2. check to see if that photo's data has already been stored # 3. if yes # retrieve Photo obj and put in array # if no # create Photo obj and put in array # 4. return array photos = [] native_photo_ids = photo_list.map{|p| p.to_s}.uniq # the photos may exist in their native photo_class, or cached # as a LocalPhoto, so lookup both and combine results existing = (LocalPhoto.where(subtype: photo_class, native_photo_id: native_photo_ids) + photo_class.includes(:user).where(native_photo_id: native_photo_ids)). index_by{|p| p.native_photo_id } photo_list.uniq.each do |photo_id| if (photo = existing[photo_id]) || options[:sync] api_response = begin photo_class.get_api_response(photo_id, :user => current_user) rescue JSON::ParserError => e Rails.logger.error "[ERROR #{Time.now}] Failed to parse JSON from Flickr: #{e}" next end end # Sync existing if called for if photo photo.user ||= options[:user] if options[:sync] # sync the photo URLs b/c they change when photos become private photo.api_response = api_response # set to make sure user validation works photo.sync photo.save if photo.changed? end end # Create a new one if one doesn't already exist unless photo photo = if photo_class == LocalPhoto if photo_id.is_a?(Fixnum) || photo_id.is_a?(String) LocalPhoto.find_by_id(photo_id) else LocalPhoto.new(:file => photo_id, :user => current_user) unless photo_id.blank? end else api_response ||= begin photo_class.get_api_response(photo_id, :user => current_user) rescue JSON::ParserError => e Rails.logger.error "[ERROR #{Time.now}] Failed to parse JSON from Flickr: #{e}" nil end if api_response photo_class.new_from_api_response(api_response, :user => current_user, :native_photo_id => photo_id) end end end if photo.blank? Rails.logger.error "[ERROR #{Time.now}] Failed to get photo for photo_class: #{photo_class}, photo_id: #{photo_id}" elsif photo.valid? || existing[photo_id] photos << photo else Rails.logger.error "[ERROR #{Time.now}] #{current_user} tried to save an observation with a new invalid photo (#{photo}): #{photo.errors.full_messages.to_sentence}" end end photos end def set_up_instance_variables(search_params) @swlat = search_params[:swlat] unless search_params[:swlat].blank? @swlng = search_params[:swlng] unless search_params[:swlng].blank? @nelat = search_params[:nelat] unless search_params[:nelat].blank? @nelng = search_params[:nelng] unless search_params[:nelng].blank? if search_params[:place].is_a?(Array) && search_params[:place].length == 1 search_params[:place] = search_params[:place].first end unless search_params[:place].blank? || search_params[:place].is_a?(Array) @place = search_params[:place] end @q = search_params[:q] unless search_params[:q].blank? @search_on = search_params[:search_on] @iconic_taxa = search_params[:iconic_taxa_instances] @observations_taxon_id = search_params[:observations_taxon_id] @observations_taxon = search_params[:observations_taxon] @observations_taxon_name = search_params[:taxon_name] @observations_taxon_ids = search_params[:taxon_ids] || search_params[:observations_taxon_ids] @observations_taxa = search_params[:observations_taxa] search_params[:has] ||= [ ] search_params[:has] << "photos" if search_params[:photos].yesish? search_params[:has] << "sounds" if search_params[:sounds].yesish? if search_params[:has] @id_please = true if search_params[:has].include?('id_please') @with_photos = true if search_params[:has].include?('photos') @with_sounds = true if search_params[:has].include?('sounds') @with_geo = true if search_params[:has].include?('geo') end @quality_grade = search_params[:quality_grade] @reviewed = search_params[:reviewed] @captive = search_params[:captive] @identifications = search_params[:identifications] @out_of_range = search_params[:out_of_range] @license = search_params[:license] @photo_license = search_params[:photo_license] @sound_license = search_params[:sound_license] @order_by = search_params[:order_by] @order = search_params[:order] @observed_on = search_params[:observed_on] @observed_on_year = search_params[:observed_on_year] @observed_on_month = [ search_params[:observed_on_month] ].flatten.first @observed_on_day = search_params[:observed_on_day] @ofv_params = search_params[:ofv_params] @site_uri = params[:site] unless params[:site].blank? @user = search_params[:user] @projects = search_params[:projects] @pcid = search_params[:pcid] @geoprivacy = search_params[:geoprivacy] unless search_params[:geoprivacy].blank? @rank = search_params[:rank] @hrank = search_params[:hrank] @lrank = search_params[:lrank] @verifiable = search_params[:verifiable] @threatened = search_params[:threatened] @introduced = search_params[:introduced] @popular = search_params[:popular] if stats_adequately_scoped?(search_params) @d1 = search_params[:d1].blank? ? nil : search_params[:d1] @d2 = search_params[:d2].blank? ? nil : search_params[:d2] else search_params[:d1] = nil search_params[:d2] = nil end @filters_open = !@q.nil? || !@observations_taxon_id.blank? || !@observations_taxon_name.blank? || !@iconic_taxa.blank? || @id_please == true || !@with_photos.blank? || !@with_sounds.blank? || !@identifications.blank? || !@quality_grade.blank? || !@captive.blank? || !@out_of_range.blank? || !@observed_on.blank? || !@place.blank? || !@ofv_params.blank? || !@pcid.blank? || !@geoprivacy.blank? || !@rank.blank? || !@lrank.blank? || !@hrank.blank? @filters_open = search_params[:filters_open] == 'true' if search_params.has_key?(:filters_open) end # Refresh lists affected by taxon changes in a batch of new/edited # observations. Note that if you don't set @skip_refresh_lists on the records # in @observations before this is called, this won't do anything def refresh_lists_for_batch return true if @observations.blank? taxa = @observations.to_a.compact.select(&:skip_refresh_lists).map(&:taxon).uniq.compact return true if taxa.blank? List.delay(:priority => USER_PRIORITY).refresh_for_user(current_user, :taxa => taxa.map(&:id)) true end # Tries to create a new observation from the specified Facebook photo ID and # update the existing @observation with the new properties, without saving def sync_facebook_photo fb = current_user.facebook_api if fb fbp_json = FacebookPhoto.get_api_response(params[:facebook_photo_id], :user => current_user) @facebook_photo = FacebookPhoto.new_from_api_response(fbp_json) else @facebook_photo = nil end if @facebook_photo && @facebook_photo.owned_by?(current_user) @facebook_observation = @facebook_photo.to_observation sync_attrs = [:description] # facebook strips exif metadata so we can't get geo or observed_on :-/ #, :species_guess, :taxon_id, :observed_on, :observed_on_string, :latitude, :longitude, :place_guess] unless params[:facebook_sync_attrs].blank? sync_attrs = sync_attrs & params[:facebook_sync_attrs] end sync_attrs.each do |sync_attr| # merge facebook_observation with existing observation @observation[sync_attr] ||= @facebook_observation[sync_attr] end unless @observation.observation_photos.detect {|op| op.photo.native_photo_id == @facebook_photo.native_photo_id} @observation.observation_photos.build(:photo => @facebook_photo) end unless @observation.new_record? flash.now[:notice] = t(:preview_of_synced_observation, :url => url_for) end else flash.now[:error] = t(:sorry_we_didnt_find_that_photo) end end # Tries to create a new observation from the specified Flickr photo ID and # update the existing @observation with the new properties, without saving def sync_flickr_photo flickr = get_flickraw begin fp = flickr.photos.getInfo(:photo_id => params[:flickr_photo_id]) @flickr_photo = FlickrPhoto.new_from_flickraw(fp, :user => current_user) rescue FlickRaw::FailedResponse => e Rails.logger.debug "[DEBUG] FlickRaw failed to find photo " + "#{params[:flickr_photo_id]}: #{e}\n#{e.backtrace.join("\n")}" @flickr_photo = nil rescue Timeout::Error => e flash.now[:error] = t(:sorry_flickr_isnt_responding_at_the_moment) Rails.logger.error "[ERROR #{Time.now}] Timeout: #{e}" Airbrake.notify(e, :request => request, :session => session) Logstasher.write_exception(e, request: request, session: session, user: current_user) return end if fp && @flickr_photo && @flickr_photo.valid? @flickr_observation = @flickr_photo.to_observation sync_attrs = %w(description species_guess taxon_id observed_on observed_on_string latitude longitude place_guess map_scale) unless params[:flickr_sync_attrs].blank? sync_attrs = sync_attrs & params[:flickr_sync_attrs] end sync_attrs.each do |sync_attr| # merge flickr_observation with existing observation val = @flickr_observation.send(sync_attr) @observation.send("#{sync_attr}=", val) unless val.blank? end # Note: the following is sort of a hacky alternative to build(). We # need to append a new photo object without saving it, but build() won't # work here b/c Photo and its descedents use STI, and type is a # protected attributes that can't be mass-assigned. unless @observation.observation_photos.detect {|op| op.photo.native_photo_id == @flickr_photo.native_photo_id} @observation.observation_photos.build(:photo => @flickr_photo) end unless @observation.new_record? flash.now[:notice] = t(:preview_of_synced_observation, :url => url_for) end if (@existing_photo = Photo.find_by_native_photo_id(@flickr_photo.native_photo_id)) && (@existing_photo_observation = @existing_photo.observations.first) && @existing_photo_observation.id != @observation.id msg = t(:heads_up_this_photo_is_already_associated_with, :url => url_for(@existing_photo_observation)) flash.now[:notice] = flash.now[:notice].blank? ? msg : "#{flash.now[:notice]}<br/>#{msg}" end else flash.now[:error] = t(:sorry_we_didnt_find_that_photo) end end def sync_picasa_photo begin api_response = PicasaPhoto.get_api_response(params[:picasa_photo_id], :user => current_user) rescue Timeout::Error => e flash.now[:error] = t(:sorry_picasa_isnt_responding_at_the_moment) Rails.logger.error "[ERROR #{Time.now}] Timeout: #{e}" Airbrake.notify(e, :request => request, :session => session) Logstasher.write_exception(e, request: request, session: session, user: current_user) return end unless api_response Rails.logger.debug "[DEBUG] Failed to find Picasa photo for #{params[:picasa_photo_id]}" return end @picasa_photo = PicasaPhoto.new_from_api_response(api_response, :user => current_user) if @picasa_photo && @picasa_photo.valid? @picasa_observation = @picasa_photo.to_observation sync_attrs = PHOTO_SYNC_ATTRS unless params[:picasa_sync_attrs].blank? sync_attrs = sync_attrs & params[:picasa_sync_attrs] end sync_attrs.each do |sync_attr| @observation.send("#{sync_attr}=", @picasa_observation.send(sync_attr)) end unless @observation.observation_photos.detect {|op| op.photo.native_photo_id == @picasa_photo.native_photo_id} @observation.observation_photos.build(:photo => @picasa_photo) end flash.now[:notice] = t(:preview_of_synced_observation, :url => url_for) else flash.now[:error] = t(:sorry_we_didnt_find_that_photo) end end def sync_local_photo unless @local_photo = Photo.find_by_id(params[:local_photo_id]) flash.now[:error] = t(:that_photo_doesnt_exist) return end if @local_photo.metadata.blank? flash.now[:error] = t(:sorry_we_dont_have_any_metadata_for_that_photo) return end o = @local_photo.to_observation PHOTO_SYNC_ATTRS.each do |sync_attr| @observation.send("#{sync_attr}=", o.send(sync_attr)) unless o.send(sync_attr).blank? end unless @observation.observation_photos.detect {|op| op.photo_id == @local_photo.id} @observation.observation_photos.build(:photo => @local_photo) end unless @observation.new_record? flash.now[:notice] = t(:preview_of_synced_observation, :url => url_for) end if @existing_photo_observation = @local_photo.observations.where("observations.id != ?", @observation).first msg = t(:heads_up_this_photo_is_already_associated_with, :url => url_for(@existing_photo_observation)) flash.now[:notice] = flash.now[:notice].blank? ? msg : "#{flash.now[:notice]}<br/>#{msg}" end end def load_photo_identities return if @skipping_preloading unless logged_in? @photo_identity_urls = [] @photo_identities = [] return true end if Rails.env.development? FacebookPhoto PicasaPhoto LocalPhoto FlickrPhoto end @photo_identities = Photo.subclasses.map do |klass| assoc_name = klass.to_s.underscore.split('_').first + "_identity" current_user.send(assoc_name) if current_user.respond_to?(assoc_name) end.compact reference_photo = @observation.try(:observation_photos).try(:first).try(:photo) reference_photo ||= @observations.try(:first).try(:observation_photos).try(:first).try(:photo) unless params[:action] === "show" || params[:action] === "update" reference_photo ||= current_user.photos.order("id ASC").last end if reference_photo assoc_name = (reference_photo.subtype || reference_photo.class.to_s). underscore.split('_').first + "_identity" if current_user.respond_to?(assoc_name) @default_photo_identity = current_user.send(assoc_name) else @default_photo_source = 'local' end end if params[:facebook_photo_id] if @default_photo_identity = @photo_identities.detect{|pi| pi.to_s =~ /facebook/i} @default_photo_source = 'facebook' end elsif params[:flickr_photo_id] if @default_photo_identity = @photo_identities.detect{|pi| pi.to_s =~ /flickr/i} @default_photo_source = 'flickr' end end @default_photo_source ||= if @default_photo_identity if @default_photo_identity.class.name =~ /Identity/ @default_photo_identity.class.name.underscore.humanize.downcase.split.first else @default_photo_identity.provider_name end elsif @default_photo_identity "local" end @default_photo_identity_url = nil @photo_identity_urls = @photo_identities.map do |identity| provider_name = if identity.is_a?(ProviderAuthorization) if identity.provider_name =~ /google/i "picasa" else identity.provider_name end else identity.class.to_s.underscore.split('_').first # e.g. FlickrIdentity=>'flickr' end url = "/#{provider_name.downcase}/photo_fields?context=user" @default_photo_identity_url = url if identity == @default_photo_identity "{title: '#{provider_name.capitalize}', url: '#{url}'}" end @photo_sources = @photo_identities.inject({}) do |memo, ident| if ident.respond_to?(:source_options) memo[ident.class.name.underscore.humanize.downcase.split.first] = ident.source_options elsif ident.is_a?(ProviderAuthorization) if ident.provider_name == "facebook" memo[:facebook] = { :title => 'Facebook', :url => '/facebook/photo_fields', :contexts => [ ["Your photos", 'user'] ] } elsif ident.provider_name =~ /google/ memo[:picasa] = { :title => 'Picasa', :url => '/picasa/photo_fields', :contexts => [ ["Your photos", 'user', {:searchable => true}] ] } end end memo end end def load_sound_identities return if @skipping_preloading unless logged_in? logger.info "not logged in" @sound_identities = [] return true end @sound_identities = current_user.soundcloud_identity ? [current_user.soundcloud_identity] : [] end def load_observation scope = Observation.where(id: params[:id] || params[:observation_id]) unless @skipping_preloading scope = scope.includes([ :quality_metrics, :flags, { photos: :flags }, :identifications, :projects, { taxon: :taxon_names }]) end @observation = begin scope.first rescue RangeError => e Logstasher.write_exception(e, request: request, session: session, user: current_user) nil end render_404 unless @observation end def require_owner unless logged_in? && current_user.id == @observation.user_id msg = t(:you_dont_have_permission_to_do_that) respond_to do |format| format.html do flash[:error] = msg return redirect_to @observation end format.json do return render :json => {:error => msg} end end end end def render_observations_to_json(options = {}) if (partial = params[:partial]) && PARTIALS.include?(partial) Observation.preload_associations(@observations, [ :stored_preferences, { :taxon => :taxon_descriptions }, { :iconic_taxon => :taxon_descriptions } ]) data = @observations.map do |observation| item = { :instance => observation, :extra => { :taxon => observation.taxon, :iconic_taxon => observation.iconic_taxon, :user => {login: observation.user.login, name: observation.user.name} } } item[:html] = view_context.render_in_format(:html, :partial => partial, :object => observation) item end render :json => data else opts = options opts[:methods] ||= [] opts[:methods] += [:short_description, :user_login, :iconic_taxon_name, :tag_list, :faves_count] opts[:methods].uniq! opts[:include] ||= {} opts[:include][:taxon] ||= { :only => [:id, :name, :rank, :ancestry], :methods => [:common_name] } opts[:include][:iconic_taxon] ||= {:only => [:id, :name, :rank, :rank_level, :ancestry]} opts[:include][:user] ||= {:only => :login, :methods => [:user_icon_url]} opts[:include][:photos] ||= { :methods => [:license_code, :attribution], :except => [:original_url, :file_processing, :file_file_size, :file_content_type, :file_file_name, :mobile, :metadata] } extra = params[:extra].to_s.split(',') if extra.include?('projects') opts[:include][:project_observations] ||= { :include => {:project => {:only => [:id, :title]}}, :except => [:tracking_code] } end if extra.include?('observation_photos') opts[:include][:observation_photos] ||= { :include => {:photo => {:except => [:metadata]}} } end if extra.include?('identifications') taxon_options = Taxon.default_json_options taxon_options[:methods] += [:iconic_taxon_name, :image_url, :common_name, :default_name] opts[:include][:identifications] ||= { 'include': { user: { only: [:name, :login, :id], methods: [:user_icon_url] }, taxon: { only: [:id, :name, :rank, :rank_level], methods: [:iconic_taxon_name, :image_url, :common_name, :default_name] } } } end if @ofv_params || extra.include?('fields') opts[:include][:observation_field_values] ||= { :except => [:observation_field_id], :include => { :observation_field => { :only => [:id, :datatype, :name, :allowed_values] } } } end pagination_headers_for(@observations) opts[:viewer] = current_user if @observations.respond_to?(:scoped) Observation.preload_associations(@observations, [ {:observation_photos => { :photo => :user } }, :photos, :iconic_taxon ]) end render :json => @observations.to_json(opts) end end def render_observations_to_csv(options = {}) first = %w(scientific_name datetime description place_guess latitude longitude tag_list common_name url image_url user_login) only = (first + Observation::CSV_COLUMNS).uniq except = %w(map_scale timeframe iconic_taxon_id delta geom user_agent cached_tag_list) unless options[:show_private] == true except += %w(private_latitude private_longitude private_positional_accuracy) end only = only - except unless @ofv_params.blank? only += @ofv_params.map{|k,v| "field:#{v[:normalized_name]}"} if @observations.respond_to?(:scoped) Observation.preload_associations(@observations, { :observation_field_values => :observation_field }) end end Observation.preload_associations(@observations, [ :tags, :taxon, :photos, :user, :quality_metrics ]) pagination_headers_for(@observations) render :text => Observation.as_csv(@observations, only.map{|c| c.to_sym}, { ssl: request.protocol =~ /https/ }) end def render_observations_to_kml(options = {}) @net_hash = options if params[:kml_type] == "network_link" kml_query = request.query_parameters.reject{|k,v| REJECTED_KML_FEED_PARAMS.include?(k.to_s) || k.to_s == "kml_type"}.to_query kml_href = "#{request.base_url}#{request.path}" kml_href += "?#{kml_query}" unless kml_query.blank? @net_hash = { :id => "AllObs", :link_id =>"AllObs", :snippet => "#{CONFIG.site_name} Feed for Everyone", :description => "#{CONFIG.site_name} Feed for Everyone", :name => "#{CONFIG.site_name} Feed for Everyone", :href => kml_href } render :layout => false, :action => 'network_link' return end render :layout => false, :action => "index" end # create project observations if a project was specified and project allows # auto-joining def create_project_observations return unless params[:project_id] if params[:project_id].is_a?(Array) params[:project_id].each do |pid| errors = create_project_observation_records(pid) end else errors = create_project_observation_records(params[:project_id]) if !errors.blank? if request.format.html? flash[:error] = t(:your_observations_couldnt_be_added_to_that_project, :errors => errors.to_sentence) else Rails.logger.error "[ERROR #{Time.now}] Failed to add #{@observations.size} obs to #{@project}: #{errors.to_sentence}" end end end end def create_project_observation_records(project_id) return unless project_id @project = Project.find_by_id(project_id) @project ||= Project.find(project_id) rescue nil return unless @project if @project.tracking_code_allowed?(params[:tracking_code]) tracking_code = params[:tracking_code] end errors = [] @observations.each do |observation| next if observation.new_record? po = observation.project_observations.build(project: @project, tracking_code: tracking_code, user: current_user) unless po.save if params[:uploader] observation.project_observations.delete(po) end return (errors + po.errors.full_messages).uniq end end nil end def update_user_account current_user.update_attributes(params[:user]) unless params[:user].blank? end def render_observations_partial(partial) if @observations.empty? render(:text => '') else render(partial: "partial_renderer", locals: { partial: partial, collection: @observations }, layout: false) end end def load_prefs @prefs = current_preferences if request.format && request.format.html? @view = params[:view] || current_user.try(:preferred_observations_view) || 'map' end end def delayed_csv(path_for_csv, parent, options = {}) path_for_csv_no_ext = path_for_csv.gsub(/\.csv\z/, '') if parent.observations.count < 50 Observation.generate_csv_for(parent, :path => path_for_csv, :user => current_user) render :file => path_for_csv_no_ext, :formats => [:csv] else cache_key = Observation.generate_csv_for_cache_key(parent) job_id = Rails.cache.read(cache_key) job = Delayed::Job.find_by_id(job_id) if job # Still working elsif File.exists? path_for_csv render :file => path_for_csv_no_ext, :formats => [:csv] return else # no job id, no job, let's get this party started Rails.cache.delete(cache_key) job = Observation.delay(:priority => NOTIFICATION_PRIORITY).generate_csv_for(parent, :path => path_for_csv, :user => current_user) Rails.cache.write(cache_key, job.id, :expires_in => 1.hour) end prevent_caching render :status => :accepted, :text => "This file takes a little while to generate. It should be ready shortly at #{request.url}" end end def non_elastic_taxon_stats(search_params) scope = Observation.query(search_params) scope = scope.where("1 = 2") unless stats_adequately_scoped?(search_params) species_counts_scope = scope.joins(:taxon) unless search_params[:rank] == "leaves" && logged_in? && current_user.is_curator? species_counts_scope = species_counts_scope.where("taxa.rank_level <= ?", Taxon::SPECIES_LEVEL) end species_counts_sql = if search_params[:rank] == "leaves" && logged_in? && current_user.is_curator? ancestor_ids_sql = <<-SQL SELECT DISTINCT regexp_split_to_table(ancestry, '/') AS ancestor_id FROM taxa JOIN ( #{species_counts_scope.to_sql} ) AS observations ON observations.taxon_id = taxa.id SQL <<-SQL SELECT o.taxon_id, count(*) AS count_all FROM ( #{species_counts_scope.to_sql} ) AS o LEFT OUTER JOIN ( #{ancestor_ids_sql} ) AS ancestor_ids ON o.taxon_id::text = ancestor_ids.ancestor_id WHERE ancestor_ids.ancestor_id IS NULL GROUP BY o.taxon_id ORDER BY count_all desc LIMIT 5 SQL else <<-SQL SELECT o.taxon_id, count(*) AS count_all FROM (#{species_counts_scope.to_sql}) AS o GROUP BY o.taxon_id ORDER BY count_all desc LIMIT 5 SQL end @species_counts = ActiveRecord::Base.connection.execute(species_counts_sql) taxon_ids = @species_counts.map{|r| r['taxon_id']} rank_counts_sql = <<-SQL SELECT o.rank_name, count(*) AS count_all FROM (#{scope.joins(:taxon).select("DISTINCT ON (taxa.id) taxa.rank AS rank_name").to_sql}) AS o GROUP BY o.rank_name SQL @raw_rank_counts = ActiveRecord::Base.connection.execute(rank_counts_sql) @rank_counts = {} @total = 0 @raw_rank_counts.each do |row| @total += row['count_all'].to_i @rank_counts[row['rank_name']] = row['count_all'].to_i end # TODO: we should set a proper value for @rank_counts[:leaves] end def elastic_taxon_stats(search_params) if search_params[:rank] == "leaves" search_params.delete(:rank) showing_leaves = true end elastic_params = prepare_counts_elastic_query(search_params) taxon_counts = Observation.elastic_search(elastic_params.merge(size: 0, aggregate: { distinct_taxa: { cardinality: { field: "taxon.id", precision_threshold: 10000 } }, rank: { terms: { field: "taxon.rank", size: 30, order: { "distinct_taxa": :desc } }, aggs: { distinct_taxa: { cardinality: { field: "taxon.id", precision_threshold: 10000 } } } } })).response.aggregations @total = taxon_counts.distinct_taxa.value @rank_counts = Hash[ taxon_counts.rank.buckets. map{ |b| [ b["key"], b["distinct_taxa"]["value"] ] } ] elastic_params[:filters] << { range: { "taxon.rank_level" => { lte: Taxon::RANK_LEVELS["species"] } } } species_counts = Observation.elastic_search(elastic_params.merge(size: 0, aggregate: { species: { "taxon.id": 100 } })).response.aggregations # the count is a string to maintain backward compatibility @species_counts = species_counts.species.buckets. map{ |b| { "taxon_id" => b["key"], "count_all" => b["doc_count"].to_s } } if showing_leaves leaf_ids = Observation.elastic_taxon_leaf_ids(prepare_counts_elastic_query(search_params)) @rank_counts[:leaves] = leaf_ids.count # we fetch extra taxa above so we can safely filter # out the non-leaf taxa from the result @species_counts.delete_if{ |s| !leaf_ids.include?(s["taxon_id"]) } end # limit the species_counts to 5 @species_counts = @species_counts[0...5] end def non_elastic_user_stats(search_params, limit) scope = Observation.query(search_params) scope = scope.where("1 = 2") unless stats_adequately_scoped?(search_params) @user_counts = user_obs_counts(scope, limit).to_a @user_taxon_counts = user_taxon_counts(scope, limit).to_a obs_user_ids = @user_counts.map{|r| r['user_id']}.sort tax_user_ids = @user_taxon_counts.map{|r| r['user_id']}.sort # the list of top users is probably different for obs and taxa, so grab the leftovers from each leftover_obs_user_ids = tax_user_ids - obs_user_ids leftover_tax_user_ids = obs_user_ids - tax_user_ids @user_counts += user_obs_counts(scope.where("observations.user_id IN (?)", leftover_obs_user_ids)).to_a @user_taxon_counts += user_taxon_counts(scope.where("observations.user_id IN (?)", leftover_tax_user_ids)).to_a @user_counts = @user_counts[0...limit] @user_taxon_counts = @user_taxon_counts[0...limit] @total = scope.select("DISTINCT observations.user_id").count end def elastic_user_stats(search_params, limit) elastic_params = prepare_counts_elastic_query(search_params) user_obs = Observation.elastic_user_observation_counts(elastic_params, limit) @user_counts = user_obs[:counts] @total = user_obs[:total] @user_taxon_counts = Observation.elastic_user_taxon_counts(elastic_params, limit: limit, count_users: @total) # # the list of top users is probably different for obs and taxa, so grab the leftovers from each obs_user_ids = @user_counts.map{|r| r['user_id']}.sort tax_user_ids = @user_taxon_counts.map{|r| r['user_id']}.sort leftover_obs_user_ids = tax_user_ids - obs_user_ids leftover_tax_user_ids = obs_user_ids - tax_user_ids leftover_obs_user_elastic_params = elastic_params.marshal_copy leftover_obs_user_elastic_params[:where]['user.id'] = leftover_obs_user_ids leftover_tax_user_elastic_params = elastic_params.marshal_copy leftover_tax_user_elastic_params[:where]['user.id'] = leftover_tax_user_ids @user_counts += Observation.elastic_user_observation_counts(leftover_obs_user_elastic_params)[:counts].to_a @user_taxon_counts += Observation.elastic_user_taxon_counts(leftover_tax_user_elastic_params, count_users: leftover_tax_user_ids.length).to_a # don't want to return more than were asked for @user_counts = @user_counts[0...limit] @user_taxon_counts = @user_taxon_counts[0...limit] end def prepare_counts_elastic_query(search_params) elastic_params = Observation.params_to_elastic_query( search_params, current_user: current_user). select{ |k,v| [ :where, :filters ].include?(k) } end def search_cache_key(search_params) search_cache_params = search_params.reject{|k,v| %w(controller action format partial).include?(k.to_s)} # models to IDs - classes are inconsistently represented as strings search_cache_params.each{ |k,v| search_cache_params[k] = ElasticModel.id_or_object(v) } search_cache_params[:locale] ||= I18n.locale search_cache_params[:per_page] ||= search_params[:per_page] search_cache_params[:site_name] ||= SITE_NAME if CONFIG.site_only_observations search_cache_params[:bounds] ||= CONFIG.bounds.to_h if CONFIG.bounds "obs_index_#{Digest::MD5.hexdigest(search_cache_params.sort.to_s)}" end def prepare_map_params(search_params = {}) map_params = valid_map_params(search_params) non_viewer_params = map_params.reject{ |k,v| k == :viewer } if @display_map_tiles if non_viewer_params.empty? # there are no options, so show all observations by default @enable_show_all_layer = true elsif non_viewer_params.length == 1 && map_params[:taxon] # there is just a taxon, so show the taxon observations lyers @map_params = { taxon_layers: [ { taxon: map_params[:taxon], observations: true, ranges: { disabled: true }, places: { disabled: true }, gbif: { disabled: true } } ], focus: :observations } else # otherwise show our catch-all "Featured Observations" custom layer map_params[:viewer_id] = current_user.id if logged_in? @map_params = { observation_layers: [ map_params.merge(observations: @observations) ] } end end end def determine_if_map_should_be_shown( search_params ) if @display_map_tiles = Observation.able_to_use_elasticsearch?( search_params ) prepare_map_params(search_params) end end def valid_map_params(search_params = {}) # make sure we have the params as processed by Observation.query_params map_params = (search_params && search_params[:_query_params_set]) ? search_params.clone : Observation.query_params(params) map_params = map_params.map{ |k,v| if v.is_a?(Array) [ k, v.map{ |vv| ElasticModel.id_or_object(vv) } ] else [ k, ElasticModel.id_or_object(v) ] end }.to_h if map_params[:observations_taxon] map_params[:taxon_id] = map_params.delete(:observations_taxon) end if map_params[:projects] map_params[:project_ids] = map_params.delete(:projects) end if map_params[:user] map_params[:user_id] = map_params.delete(:user) end map_params.select do |k,v| ! [ :utf8, :controller, :action, :page, :per_page, :preferences, :color, :_query_params_set, :order_by, :order ].include?( k.to_sym ) end.compact end def decide_if_skipping_preloading @skipping_preloading = (params[:partial] == "cached_component") end def observations_index_search(params) # making `page` default to a string because HTTP params are # usually strings and we want to keep the cache_key consistent params[:page] ||= "1" search_params = Observation.get_search_params(params, current_user: current_user, site: @site) search_params = Observation.apply_pagination_options(search_params, user_preferences: @prefs) if perform_caching && search_params[:q].blank? && (!logged_in? || search_params[:page].to_i == 1) search_key = search_cache_key(search_params) # Get the cached filtered observations observations = Rails.cache.fetch(search_key, expires_in: 5.minutes, compress: true) do obs = Observation.page_of_results(search_params) # this is doing preloading, as is some code below, but this isn't # entirely redundant. If we preload now we can cache the preloaded # data to save extra time later on. Observation.preload_for_component(obs, logged_in: !!current_user) obs end else observations = Observation.page_of_results(search_params) end set_up_instance_variables(search_params) { params: params, search_params: search_params, observations: observations } end end
module Spritz class Generator < Jekyll::Generator include Spritz def initialize(*args) super login_success_path = args[0]["spritz_login_success_name"] || "login_success.html" dirname = File.dirname(login_success_path) FileUtils.mkdir_p(dirname) source = File.join(File.dirname(__FILE__), "..", "login_success.html") destination = File.join(args[0]["source"], login_success_path) FileUtils.copy(source, destination) end def generate(site) get_options(site.config) warn_and_set_default return unless @options[:automode] snippet = Spritz::script_tag(@options[:client_id], @options[:url], @options[:login_success]) snippet += Spritz::redicle_tag("data-selector" => @options[:selector], "data-options" => @options[:redicle].to_json) site.posts.each do |p| p.content = snippet + p.content if p.data["spritz"].nil? or p.data["spritz"] end end end end Fix bug - read login_success_name from the spritz namespace when copying file. module Spritz class Generator < Jekyll::Generator include Spritz def initialize(*args) super login_success_path = args[0]["spritz"]["login_success_name"] || "login_success.html" dirname = File.dirname(login_success_path) FileUtils.mkdir_p(dirname) source = File.join(File.dirname(__FILE__), "..", "login_success.html") destination = File.join(args[0]["source"], login_success_path) FileUtils.copy(source, destination) end def generate(site) get_options(site.config) warn_and_set_default return unless @options[:automode] snippet = Spritz::script_tag(@options[:client_id], @options[:url], @options[:login_success]) snippet += Spritz::redicle_tag("data-selector" => @options[:selector], "data-options" => @options[:redicle].to_json) site.posts.each do |p| p.content = snippet + p.content if p.data["spritz"].nil? or p.data["spritz"] end end end end
require 'hpricot' require 'spiderfw/patches/hpricot' require 'spiderfw/templates/template_blocks' require 'spiderfw/cache/template_cache' begin require 'less' require 'spiderfw/templates/assets/less' rescue LoadError end Spider.register_resource_type(:css, :extensions => ['css'], :path => 'public') Spider.register_resource_type(:js, :extensions => ['js'], :path => 'public') module Spider module TemplateAssets; end # This class manages SHTML templates. class Template include Logger attr_accessor :_action, :_action_to, :_widget_action attr_accessor :widgets, :compiled, :id_path attr_accessor :request, :response, :owner, :owner_class, :definer_class attr_accessor :mode # :widget, ... attr_accessor :assets attr_accessor :runtime_overrides attr_reader :overrides, :path, :subtemplates, :widgets, :content attr_accessor :asset_profiles @@registered = {} @@widget_plugins = {} @@namespaces = {} @@overrides = ['content', 'override', 'override-content', 'override-attr', 'append-attr', 'append', 'prepend', 'delete', 'before', 'after'] @@asset_types = { :css => {}, :js => {}, :less => {:processor => :Less} } class << self # Returns the class TemplateCache instance def cache @@cache ||= TemplateCache.new(File.join(Spider.paths[:var], 'cache', 'templates')) end # Sets allowed blocks def allow_blocks(*tags) # :nodoc: @allowed_blocks = tags end # Returns allowed blocks def allowed_blocks # :nodoc: @allowed_blocks end def asset_types # :nodoc: @@asset_types end # Returns a new instance, loading path. def load(path) raise RuntimeError, "Template #{path} does not exist" unless File.exist?(path) template = self.new(path) template.load(path) return template end # Registers a tag def register(tag, symbol_or_class) @@registered[tag] = symbol_or_class end # Returns an hash of registered tags. def registered @@registered end # Checks if the tag is registered. def registered?(tag) return true if @@registered[tag] ns, tag = tag.split(':') if tag # that is, if there is a ns return false unless @@namespaces[ns] return @@namespaces[ns].has_tag?(tag) end return false end # Registers a namespace (mod should probably be a Spider::App, and must respond to # get_tag and has_tag? methods). def register_namespace(ns, mod) @@namespaces[ns] = mod end # Returns the Class registered for the given tag. def get_registered_class(name) if @@registered[name] klass = @@registered[name] else ns, tag = name.split(':') klass = @@namespaces[ns].get_tag(tag) if tag && @@namespaces[ns] end return nil unless klass klass = const_get_full(klass) if klass.is_a?(Symbol) return klass end # Returns the view path (see #Spider::find_asset) def real_path(path, cur_path=nil, owner_classes=nil, search_paths=[]) Spider.find_resource_path(:views, path, cur_path, owner_classes, search_paths) end def find_resource(path, cur_path=nil, owner_classes=nil, search_paths=[]) Spider.find_resource(:views, path, cur_path, owner_classes, search_paths) end def define_named_asset(name, assets, options={}) @named_assets ||= {} @named_assets[name] = { :assets => assets, :options => options } end def named_assets @named_assets || {} end def define_runtime_asset(name, &proc) @runtime_assets ||= {} @runtime_assets[name] = proc end def runtime_assets @runtime_assets || {} end def get_named_asset(name) res = [] ass = self.named_assets[name] raise "Named asset #{name} is not defined" unless ass deps = ass[:options][:depends] if ass[:options] deps = [deps] if deps && !deps.is_a?(Array) if deps deps.each do |dep| res += get_named_asset(dep) end end ass[:assets].each do |a| attributes = a[3] || {} res << {:type => a[0], :src => a[1], :app => a[2]}.merge(attributes) end res end # An array of possible override tags. # Overrides may be used when placing a widget in a template, or when including another template. # All except tpl:content may have the _search_ attribute, that is a CSS or XPath expression specifing # the nodes to override. If the _search_ attribute is missing, the override will be applied to the # root node. # # Example: # <div class="my_widget_template"> # <div class="a">aaa</div> # <div class="b">bbb</div> # </div> # # and # # <div class="my_template"> # <my:widget id="my_widget_instance"> # <tpl:override search=".b">bbb and a c</tpl:override> # </my:widget> # </div> # # will result in the widget using the template # <div class="my_widget_template"> # <div class="a">aaa</div> # <div class="b">bbb and c</div> # </div> # # The tags are in the _tpl_ namespace. # *<tpl:content [name='...'] />* overrides the content of the found element. # If name is given, will override the named content found in the # original template. # *<tpl:override />* replaces the found nodes with given content # *<tpl:override-attr name='...' value='...' />* overrides the given attribute # *<tpl:append />* appends the given content to the container # *<tpl:prepend />* prepends the given content # *<tpl:delete />* removes the found nodes # *<tpl:before />* inserts the given content before the found nodes # *<tpl:after />* inserts the given content after the found nodes def override_tags @@overrides end def parse_asset_element(el) h = {} el.attributes.to_hash.each do |k, v| h[k.to_sym] = v end h # end # { # :type => el.get_attribute('type'), # :src => el.get_attribute('src'), # :attributes => el.attributes.to_hash # } end end # Returns the class override_tags def override_tags @@overrides end def initialize(path=nil) @path = path @widgets = {} @subtemplates = {} @widget_templates = [] @subtemplate_owners = {} @id_path = [] @assets = [] @content = {} @dependencies = [] @overrides = [] @widgets_overrides = {} @widget_procs = {} @runtime_overrides = [] end # Sets the scene. def bind(scene) @scene = scene return self end # Loads the compiled template (from cache if available). def load(path=nil) @path = real_path(path) if path @path = File.expand_path(@path) # debug("TEMPLATE LOADING #{@path}") cache_path = @path.sub(Spider.paths[:root], 'ROOT').sub(Spider.paths[:spider], 'SPIDER') unless @runtime_overrides.empty? cache_path_dir = File.dirname(cache_path) cache_path_file = File.basename(cache_path, '.shtml') suffix = @runtime_overrides.map{ |ro| ro[0].to_s }.sort.join('+') cache_path = cache_path_dir+'/'+cache_path_file+'+'+suffix+'.shtml' @runtime_overrides.each do |ro| @overrides += ro[1] @dependencies << ro[2] end end @compiled = self.class.cache.fetch(cache_path) do compile(:mode => @mode) end end # Recompiles the template; returns a CompiledTemplate. def compile(options={}) compiled = CompiledTemplate.new compiled.source_path = @path doc = open(@path){ |f| Hpricot.XML(f) } root = get_el(doc) el = process_tags(root) apply_overrides(root) root.search('tpl:placeholder').remove # remove empty placeholders owner_class = @owner ? @owner.class : @owner_class @assets += owner_class.assets if owner_class res = root.children ? root.children_of_type('tpl:asset') : [] res_init = "" res.each do |r| @assets << Spider::Template.parse_asset_element(r) r.set_attribute('class', 'to_delete') end new_assets = [] @assets.each do |ass| a = parse_asset(ass[:type], ass[:src], ass) new_assets += a end @assets = new_assets root.search('.to_delete').remove root.search('tpl:assets').each do |ass| if wattr = ass.get_attribute('widgets') widgets = [] wattr.split(/,\s*/).each do |w| w_templates = nil if w =~ /(\.+)\((.+)\)/ w = $1 w_templates = $2.split('|') end klass = Spider::Template.get_registered_class(w) unless klass Spider.logger.warn("tpl:assets requested non existent widget #{w}") next end w_templates ||= [klass.default_template] w_templates.each do |wt| t = klass.load_template(wt) add_widget_template(t, klass) end end elsif sattr = ass.get_attribute('src') sattr.split(/,\s*/).each do |s| s_template = Spider::Template.new(s) s_template.owner = @owner s_template.definer_class = @definer_class s_template.load(s) @assets = s_template.assets + @assets end end end root.search('tpl:assets').remove root_block = TemplateBlocks.parse_element(root, self.class.allowed_blocks, self) if doc.children && doc.children[0].is_a?(Hpricot::DocType) root_block.doctype = doc.children[0] options[:doctype] = DocType.new(root_block.doctype) else options[:doctype] ||= DocType.new(Spider.conf.get('template.default_doctype')) end options[:root] = true options[:owner] = @owner options[:owner_class] = @owner_class || @owner.class options[:template_path] = @path options[:template] = self compiled.block = root_block.compile(options) subtemplates.each do |id, sub| sub.owner_class = @subtemplate_owners[id] compiled.subtemplates[id] = sub.compile(options.merge({:mode => :widget})) # FIXME! :mode => :widget is wrong, it's just a quick kludge @assets += compiled.subtemplates[id].assets end @widget_templates.each do |wt| wt.mode = :widget wt.load # sub_c = sub.compile(options.merge({:mode => :widget})) @assets = wt.compiled.assets + @assets end seen = {} # @assets.each_index do |i| # ass = @assets[i] # if ass[:name] # end @assets.each do |ass| ass[:profiles] = ((ass[:profiles] || []) + @asset_profiles).uniq if @asset_profiles next if seen[ass.inspect] res_init += "@assets << #{ass.inspect}\n" # res_init += "@assets << { # :type => :#{ass[:type]}, # :src => '#{ass[:src]}', # :path => '#{ass[:path]}', # :if => '#{ass[:if]}'" # res_init += ",\n :compiled => '#{ass[:compressed]}'" if ass[:compressed] # res_init += "}\n" seen[ass.inspect] = true end compiled.block.init_code = res_init + compiled.block.init_code compiled.devel_info["source.xml"] = root.to_html compiled.assets = (@assets + assets).uniq return compiled end # Processes an asset. Returns an hash with :type, :src, :path. def parse_asset(type, src, attributes={}) # FIXME: use Spider.find_asset ? type = type.to_sym if type ass = {:type => type} if attributes[:name] named = Spider::Template.get_named_asset(attributes[:name]) raise "Can't find named asset #{attributes[:name]}" unless named if attributes[:profiles] named.each{ |nmdass| nmdass[:profiles] = attributes[:profiles] } end return named.map{ |nmdass| parse_asset(nmdass[:type], nmdass[:src], nmdass) }.flatten end if attributes[:profiles] ass[:profiles] = attributes[:profiles].split(/,\s*/).map{ |p| p.to_sym } end if attributes[:app] == :runtime ass[:runtime] = src return [ass] end if attributes[:app] asset_owner = attributes[:app] asset_owner = Spider.apps_by_path[asset_owner] unless asset_owner.is_a?(Module) elsif attributes[:home] asset_owner = Spider.home else asset_owner = (@owner ? @owner.class : @owner_class ) end ass[:app] = asset_owner.app if asset_owner.respond_to?(:app) # FIXME! @definer_class is not correct for Spider::HomeController raise "Asset type not given for #{src}" unless type search_classes = [asset_owner, @definer_class] dfnr = @definer_class.superclass if @definer_class && @definer_class.respond_to?(:superclass) while dfnr && dfnr < Spider::Widget search_classes << dfnr dfnr = dfnr.respond_to?(:superclass) ? dfnr.superclass : nil end res = Spider.find_resource(type.to_sym, src, @path, search_classes) controller = nil if res && res.definer controller = res.definer.controller if res.definer.is_a?(Spider::Home) ass[:app] = :home else ass[:app] = res.definer end elsif owner_class < Spider::Controller controller = owner_class end ass[:path] = res.path if res base_url = nil if controller.respond_to?(:pub_url) if src[0].chr == '/' if controller <= Spider::HomeController src = src[(1+controller.pub_path.length)..-1] else # strips the app path from the src. FIXME: should probably be done somewhere else src = src[(2+controller.app.relative_path.length)..-1] end end base_url = controller.pub_url+'/' else base_url = '' end ass[:rel_path] = src ass[:src] = base_url + src ass_info = self.class.asset_types[type] if ass_info && ass_info[:processor] processor = TemplateAssets.const_get(ass_info[:processor]) ass = processor.process(ass) end if cpr = attributes[:compressed] if cpr == true || cpr == "true" ass[:compressed_path] = ass[:path] ass[:compressed_rel_path] = ass[:rel_path] ass[:compressed] = base_url + File.basename(ass[:path]) else compressed_res = Spider.find_resource(type.to_sym, cpr, @path, [owner_class, @definer_class]) ass[:compressed_path] = compressed_res.path ass[:compressed] = base_url+cpr end end ass[:copy_dir] = attributes[:copy_dir] ass[:copy_dir] = ass[:copy_dir] =~ /\d+/ ? ass[:copy_dir].to_i : true [:gettext, :media, :if_ie_lte, :cdn].each do |key| ass[key] = attributes[key] if attributes.key?(key) end return [ass] end # Returns the root node of the template at given path. # Will apply overrides and process extends and inclusions. def get_el(path_or_doc=nil) path = nil doc = nil if path_or_doc.is_a?(Hpricot::Doc) doc = path_or_doc path = @path else path = path_or_doc path ||= @path doc = open(path){ |f| Hpricot.XML(f) } end root = doc.root overrides = [] orig_overrides = @overrides @overrides = [] if root.children override_tags.each do |tag| overrides += root.children_of_type('tpl:'+tag) end end overrides.each{ |o| o.set_attribute('class', 'to_delete') } root.search('.to_delete').remove add_overrides overrides our_domain = nil if @definer_class our_domain = @definer_class.respond_to?(:app) ? @definer_class.app.short_name : 'spider' end @overrides += orig_overrides if root.name == 'tpl:extend' orig_overrides = @overrides @overrides = [] ext_src = root.get_attribute('src') ext_app = root.get_attribute('app') ext_widget = root.get_attribute('widget') if ext_widget ext_widget = Spider::Template.get_registered_class(ext_widget) ext_src ||= ext_widget.default_template ext_owner = ext_widget ext_app = ext_widget.app elsif ext_app ext_app = Spider.apps_by_path[ext_app] ext_owner = ext_app else ext_owner = @owner.class ext_app = ext_owner.app end ext_search_paths = nil if ext_owner && ext_owner.respond_to?(:template_paths) ext_search_paths = ext_owner.template_paths end ext = self.class.real_path(ext_src, path, ext_owner, ext_search_paths) raise "Extended template #{ext_src} not found (search path #{path}, owner #{ext_owner}, search paths #{ext_search_paths.inspect}" unless ext assets = [] if root.children assets = root.children_of_type('tpl:asset') assets += root.children_of_type('tpl:assets') end @dependencies << ext tpl = Template.new(ext) root = get_el(ext) if ext_app.short_name != our_domain root.set_attribute('tpl:text-domain', ext_app.short_name) end root.children_of_type('tpl:asset').each do |ass| ass_src = ass.get_attribute('src') if ass_src && ass_src[0].chr != '/' # ass.set_attribute('src', "/#{ext_app.relative_path}/#{ass_src}") ass.set_attribute('app', ext_app.relative_path) if ass.get_attribute('app').blank? end end @overrides += orig_overrides if assets && !assets.empty? assets.each do |ass| root.innerHTML += ass.to_html end end else assets_html = "" root.search('tpl:include').each do |incl| resource = Spider.find_resource(:views, incl.get_attribute('src'), @path, [@owner.class, @definer_class]) src = resource.path raise "Template #{@path} didn't find included '#{incl.get_attribute('src')}'" unless src @dependencies << src incl_el = self.get_el(src) assets = incl_el.children ? incl_el.children_of_type('tpl:asset') : [] assets.each{ |ass| ass.set_attribute('class', 'to_delete') ass_src = ass.get_attribute('src') if ass_src && ass_src[0].chr != '/' if resource.definer.is_a?(Spider::Home) ass.set_attribute('home', 'true') else # ass.set_attribute('src', "/#{resource.definer.relative_path}/#{ass_src}") ass.set_attribute('app', resource.definer.relative_path) end end assets_html += ass.to_html } if incl_el.children incl_el.children_of_type('tpl:assets').each do |asss| assets_html += asss.to_html end end incl_el.search('.to_delete').remove td = resource.definer.respond_to?(:app) ? resource.definer.app.short_name : 'spider' if td != our_domain incl_el.set_attribute('tpl:text-domain', td) end incl.swap(incl_el.to_html) end root.search('.to_delete').remove root.innerHTML = assets_html + root.innerHTML end return root end def process_tags(el) block = TemplateBlocks.get_block_type(el, true) raise "Bad html in #{@path}, can't parse" if el.is_a?(Hpricot::BogusETag) if block == :Tag sp_attributes = {} # FIXME: should use blocks instead el.attributes.to_hash.each do |key, value| if key[0..1] == 'sp' sp_attributes[key] = value el.remove_attribute(key) end end klass = Spider::Template.get_registered_class(el.name) tag = klass.new(el) res = process_tags(Hpricot(tag.render).root) sp_attributes.each{ |key, value| res.set_attribute(key, value) } return res else el.each_child do |child| next if child.is_a?(Hpricot::Text) || child.is_a?(Hpricot::Comment) el.replace_child(child, process_tags(child)) end end return el end # The full path of a template mentioned in this one. def real_path(path) self.class.real_path(path, File.dirname(@path), [@owner.class, @definer_class]) end def loaded? @compiled ? true : false end # Adds a widget instance to the template. # This method is usually not called directly; widgets are added during the template # init phase. def add_widget(id, widget, attributes=nil, content=nil, template=nil) @widgets[id.to_sym] ||= widget widget.id = id widget.id_path = @id_path + [id] if attributes # don't use merge to trigger custom []=(k, v) method attributes.each{ |k, v| widget.attributes[k] = v } end widget.containing_template = self widget.template = template if template widget.parent = @owner widget.parse_runtime_content_xml(content, @path) if content if @widget_procs[id.to_sym] @widget_procs[id.to_sym].each do |wp| apply_widget_proc(widget, wp) end end widget end def find_widget(path) return @widgets[path.to_sym] end # Does the init phase (evals the template's compiled _init.rb_). def init(scene) # Spider::Logger.debug("Template #{@path} INIT") load unless loaded? # debug("Template #{@path} init") # debug(@compiled.init_code) @scene = scene instance_eval(@compiled.init_code, @compiled.cache_path+'/init.rb') @init_done = true end def init_done? @init_done end # Calls the before method of all widget instances. def do_widgets_before @widgets.each do |id, w| act = (@_action_to == id) ? @_action : '' w.widget_before(act) unless w.before_done? end end # Calls the run method on all widget instances. def run_widgets @widgets.each do |id, w| w.run if w.run? && !w.did_run? end end # Does #do_widgets_before and then #run_widgets. def exec do_widgets_before run_widgets end # Does the render phase. # Will execute the following steps (if needed): # - load # - init # - exec # - eval the template's compiled run code. def render(scene=nil) prev_domain = nil if @definer_class td = @definer_class.respond_to?(:app) ? @definer_class.app.short_name : 'spider' prev_domain = Spider::GetText.set_domain(td) end scene ||= @scene load unless loaded? init(scene) unless init_done? exec @content.merge!(@widgets) # if Spider.conf.get('template.safe') # debug("RENDERING IN SAFE MODE!") # debug(@compiled.run_code) # # FIXME: must send header before safe mode # current_thread = Thread.current # t = Thread.new { # Thread.current[:stdout] = current_thread[:stdout] # $SAFE = 4 # scene.instance_eval("def __run_template\n"+@compiled.run_code+"end\n", @compiled.cache_path+'/run.rb') # scene.__run_template # scene.__run_template do |widget| # @content[widget].run # end # } # t.join # else scene.instance_eval("def __run_template\n"+@compiled.run_code+"end\n", @compiled.cache_path+'/run.rb', 0) scene.__run_template do |yielded| if yielded == :_parent @owner.parent.template.content.merge!(@content) @owner.parent.template.run_block else @content[yielded].render if @content[yielded] end end Spider::GetText.restore_domain(prev_domain) if prev_domain # end end def run_block @scene.__run_block do |yielded, block| @content[yielded].render if @content[yielded] end end # Alias for #render. def run render(@scene) end def inspect self.class.to_s end def add_subtemplate(id, template, owner) # :nodoc: @subtemplates[id] = template @subtemplate_owners[id] = owner end def add_widget_template(template, owner_class) template.owner_class = owner_class @widget_templates << template end def load_subtemplate(id, options={}) # :nodoc: load unless loaded? return nil unless @compiled.subtemplates[id] t = Template.new t.asset_profiles = options[:asset_profiles] if options[:asset_profiles] t.compiled = @compiled.subtemplates[id] return t end def add_overrides(overrides) overrides.each do |ov| w = ov.get_attribute('widget') if w first, rest = w.split('/', 2) if rest ov.set_attribute('widget', rest) else ov.remove_attribute('widget') end @widgets_overrides[first] ||= [] @widgets_overrides[first] << ov else @overrides << ov end end end def overrides_for(widget_id) @widgets_overrides[widget_id] || [] end def apply_overrides(el) info_els = Hpricot::Elements[*(el.children_of_type('tpl:asset')+ el.children_of_type('tpl:assets'))] info_els.remove if @overrides @overrides.each{ |o| apply_override(el, o) } end el.innerHTML = info_els.to_s + el.innerHTML el end # Applies an override to an (Hpricot) element. def apply_override(el, override) if override.is_a?(Proc) return override.call(el) end search_string = override.get_attribute('search') override.name = 'tpl:override-content' if override.name == 'tpl:inline-override' if search_string # # Fix Hpricot bug! # search_string.gsub!(/nth-child\((\d+)\)/) do |match| # "nth-child(#{$1.to_i-2})" # end found = el.parent.search(search_string) elsif override.name == 'tpl:content' found = el.search("tpl:placeholder[@name='#{override.get_attribute('name')}']") else if ['sp:template'].include?(el.name) found = el.children.select{ |child| child.is_a?(Hpricot::Elem) } else found = [el] end end if override.name == 'tpl:delete' found.remove else found.each do |f| o_doc = nil if override.name == 'tpl:override-content' overridden = f.innerHTML f.innerHTML = override.innerHTML f.search('tpl:overridden').each do |o| ovr = overridden if o_search = o.get_attribute('search') o_doc ||= Hpricot("<o>#{overridden}</o>") ovr = o_doc.root.search(o_search).to_html end o.swap(ovr) end elsif override.name == 'tpl:override' || override.name == 'tpl:content' overridden = f.to_html parent = f.parent if f == el f.innerHTML = override.innerHTML else f.swap(override.innerHTML) end parent.search('tpl:overridden').each do |o| ovr = overridden if o_search = o.get_attribute('search') o_doc ||= Hpricot("<o>#{overridden}</o>") ovr = o_doc.root.search(o_search).to_html end o.swap(ovr) end elsif override.name == 'tpl:override-attr' f.set_attribute(override.get_attribute("name"), override.get_attribute("value")) elsif override.name == 'tpl:append-attr' a = f.get_attribute(override.get_attribute("name")) || '' a += ' ' unless a.blank? a += override.get_attribute("value") f.set_attribute(override.get_attribute("name"), a) elsif override.name == 'tpl:append' f.innerHTML += override.innerHTML elsif override.name == 'tpl:prepend' f.innerHTML = override.innerHTML + f.innerHTML elsif override.name == 'tpl:before' f.before(override.innerHTML) elsif override.name == 'tpl:after' f.after(override.innerHTML) end end end end def with_widget(path, &proc) first, rest = path.split('/', 2) @widget_procs[first.to_sym] ||= [] wp = {:target => rest, :proc => proc } @widget_procs[first.to_sym] << wp if @widgets[first.to_sym] apply_widget_proc(@widgets[first.to_sym], wp) end end def apply_widget_proc(widget, wp) if wp[:target] widget.with_widget(wp[:target], &wp[:proc]) else widget.instance_eval(wp[:proc]) end end def inspect "#<#{self.class}:#{self.object_id} #{@path}>" end ExpressionOutputRegexp = /\{?\{\s([^\s].*?)\s\}\}?/ GettextRegexp = /([snp][snp]?)?_\(([^\)]+)?\)(\s%\s([^\s,]+(?:,\s*\S+\s*)?))?/ ERBRegexp = /(<%(.+)?%>)/ SceneVarRegexp = /@(\w[\w\d_]+)/ def self.scan_text(text) text = text.gsub(/\302\240/u, ' ') # remove annoying fake space scanner = ::StringScanner.new(text) pos = 0 c = "" while scanner.scan_until(Regexp.union(ExpressionOutputRegexp, GettextRegexp, ERBRegexp)) t = scanner.pre_match[pos..-1] pos = scanner.pos yield :plain, t, t if t && t.length > 0 case scanner.matched when ExpressionOutputRegexp if scanner.matched[1].chr == '{' yield :escaped_expr, $1, scanner.matched else yield :expr, $1, scanner.matched end when GettextRegexp gt = {:val => $2, :func => $1} gt[:vars] = $4 if $3 # interpolated vars yield :gettext, gt, scanner.matched when ERBRegexp yield :erb, $1, scanner.matched end end yield :plain, scanner.rest, scanner.rest end def self.scan_scene_vars(str) scanner = ::StringScanner.new(str) pos = 0 while scanner.scan_until(SceneVarRegexp) text = scanner.pre_match[pos..-1] yield :plain, text, text if text && text.length > 0 pos = scanner.pos yield :var, scanner.matched[1..-1] end yield :plain, scanner.rest end end # Class holding compiled template code. class CompiledTemplate attr_accessor :block, :source_path, :cache_path, :subtemplates, :devel_info, :assets def initialize() @subtemplates = {} @subtemplate_owners = {} @devel_info = {} end def init_code @block.init_code end def run_code @block.run_code end def collect_mtimes mtimes = {@source_path => File.mtime(@source_path)} @subtemplates.each{ |id, sub| mtimes.merge(sub.collect_mtimes)} return mtimes end end class TemplateCompileError < RuntimeError end class DocType attr_reader :type, :variant def initialize(type_or_str) if type_or_str.is_a?(Symbol) @type = type_or_str else parse(type_or_str.to_s) end end def parse(str) if str =~ /DOCTYPE HTML PUBLIC.+\sHTML/i @type = :html4 elsif str =~ /DOCTYPE HTML PUBLIC.+\sXHTML/i @type = :xhtml elsif str.downcase == '<!doctype html>' @type = :html5 end if str =~ /strict/i @variant = :strict elsif str =~ /transitional/i @variant = :transitional end end def html? @type == :html4 || @type == :html5 end def xhtml? @type == :xhtml end def strict? @variant == :strict end end end Fixed error if no el children require 'hpricot' require 'spiderfw/patches/hpricot' require 'spiderfw/templates/template_blocks' require 'spiderfw/cache/template_cache' begin require 'less' require 'spiderfw/templates/assets/less' rescue LoadError end Spider.register_resource_type(:css, :extensions => ['css'], :path => 'public') Spider.register_resource_type(:js, :extensions => ['js'], :path => 'public') module Spider module TemplateAssets; end # This class manages SHTML templates. class Template include Logger attr_accessor :_action, :_action_to, :_widget_action attr_accessor :widgets, :compiled, :id_path attr_accessor :request, :response, :owner, :owner_class, :definer_class attr_accessor :mode # :widget, ... attr_accessor :assets attr_accessor :runtime_overrides attr_reader :overrides, :path, :subtemplates, :widgets, :content attr_accessor :asset_profiles @@registered = {} @@widget_plugins = {} @@namespaces = {} @@overrides = ['content', 'override', 'override-content', 'override-attr', 'append-attr', 'append', 'prepend', 'delete', 'before', 'after'] @@asset_types = { :css => {}, :js => {}, :less => {:processor => :Less} } class << self # Returns the class TemplateCache instance def cache @@cache ||= TemplateCache.new(File.join(Spider.paths[:var], 'cache', 'templates')) end # Sets allowed blocks def allow_blocks(*tags) # :nodoc: @allowed_blocks = tags end # Returns allowed blocks def allowed_blocks # :nodoc: @allowed_blocks end def asset_types # :nodoc: @@asset_types end # Returns a new instance, loading path. def load(path) raise RuntimeError, "Template #{path} does not exist" unless File.exist?(path) template = self.new(path) template.load(path) return template end # Registers a tag def register(tag, symbol_or_class) @@registered[tag] = symbol_or_class end # Returns an hash of registered tags. def registered @@registered end # Checks if the tag is registered. def registered?(tag) return true if @@registered[tag] ns, tag = tag.split(':') if tag # that is, if there is a ns return false unless @@namespaces[ns] return @@namespaces[ns].has_tag?(tag) end return false end # Registers a namespace (mod should probably be a Spider::App, and must respond to # get_tag and has_tag? methods). def register_namespace(ns, mod) @@namespaces[ns] = mod end # Returns the Class registered for the given tag. def get_registered_class(name) if @@registered[name] klass = @@registered[name] else ns, tag = name.split(':') klass = @@namespaces[ns].get_tag(tag) if tag && @@namespaces[ns] end return nil unless klass klass = const_get_full(klass) if klass.is_a?(Symbol) return klass end # Returns the view path (see #Spider::find_asset) def real_path(path, cur_path=nil, owner_classes=nil, search_paths=[]) Spider.find_resource_path(:views, path, cur_path, owner_classes, search_paths) end def find_resource(path, cur_path=nil, owner_classes=nil, search_paths=[]) Spider.find_resource(:views, path, cur_path, owner_classes, search_paths) end def define_named_asset(name, assets, options={}) @named_assets ||= {} @named_assets[name] = { :assets => assets, :options => options } end def named_assets @named_assets || {} end def define_runtime_asset(name, &proc) @runtime_assets ||= {} @runtime_assets[name] = proc end def runtime_assets @runtime_assets || {} end def get_named_asset(name) res = [] ass = self.named_assets[name] raise "Named asset #{name} is not defined" unless ass deps = ass[:options][:depends] if ass[:options] deps = [deps] if deps && !deps.is_a?(Array) if deps deps.each do |dep| res += get_named_asset(dep) end end ass[:assets].each do |a| attributes = a[3] || {} res << {:type => a[0], :src => a[1], :app => a[2]}.merge(attributes) end res end # An array of possible override tags. # Overrides may be used when placing a widget in a template, or when including another template. # All except tpl:content may have the _search_ attribute, that is a CSS or XPath expression specifing # the nodes to override. If the _search_ attribute is missing, the override will be applied to the # root node. # # Example: # <div class="my_widget_template"> # <div class="a">aaa</div> # <div class="b">bbb</div> # </div> # # and # # <div class="my_template"> # <my:widget id="my_widget_instance"> # <tpl:override search=".b">bbb and a c</tpl:override> # </my:widget> # </div> # # will result in the widget using the template # <div class="my_widget_template"> # <div class="a">aaa</div> # <div class="b">bbb and c</div> # </div> # # The tags are in the _tpl_ namespace. # *<tpl:content [name='...'] />* overrides the content of the found element. # If name is given, will override the named content found in the # original template. # *<tpl:override />* replaces the found nodes with given content # *<tpl:override-attr name='...' value='...' />* overrides the given attribute # *<tpl:append />* appends the given content to the container # *<tpl:prepend />* prepends the given content # *<tpl:delete />* removes the found nodes # *<tpl:before />* inserts the given content before the found nodes # *<tpl:after />* inserts the given content after the found nodes def override_tags @@overrides end def parse_asset_element(el) h = {} el.attributes.to_hash.each do |k, v| h[k.to_sym] = v end h # end # { # :type => el.get_attribute('type'), # :src => el.get_attribute('src'), # :attributes => el.attributes.to_hash # } end end # Returns the class override_tags def override_tags @@overrides end def initialize(path=nil) @path = path @widgets = {} @subtemplates = {} @widget_templates = [] @subtemplate_owners = {} @id_path = [] @assets = [] @content = {} @dependencies = [] @overrides = [] @widgets_overrides = {} @widget_procs = {} @runtime_overrides = [] end # Sets the scene. def bind(scene) @scene = scene return self end # Loads the compiled template (from cache if available). def load(path=nil) @path = real_path(path) if path @path = File.expand_path(@path) # debug("TEMPLATE LOADING #{@path}") cache_path = @path.sub(Spider.paths[:root], 'ROOT').sub(Spider.paths[:spider], 'SPIDER') unless @runtime_overrides.empty? cache_path_dir = File.dirname(cache_path) cache_path_file = File.basename(cache_path, '.shtml') suffix = @runtime_overrides.map{ |ro| ro[0].to_s }.sort.join('+') cache_path = cache_path_dir+'/'+cache_path_file+'+'+suffix+'.shtml' @runtime_overrides.each do |ro| @overrides += ro[1] @dependencies << ro[2] end end @compiled = self.class.cache.fetch(cache_path) do compile(:mode => @mode) end end # Recompiles the template; returns a CompiledTemplate. def compile(options={}) compiled = CompiledTemplate.new compiled.source_path = @path doc = open(@path){ |f| Hpricot.XML(f) } root = get_el(doc) el = process_tags(root) apply_overrides(root) root.search('tpl:placeholder').remove # remove empty placeholders owner_class = @owner ? @owner.class : @owner_class @assets += owner_class.assets if owner_class res = root.children ? root.children_of_type('tpl:asset') : [] res_init = "" res.each do |r| @assets << Spider::Template.parse_asset_element(r) r.set_attribute('class', 'to_delete') end new_assets = [] @assets.each do |ass| a = parse_asset(ass[:type], ass[:src], ass) new_assets += a end @assets = new_assets root.search('.to_delete').remove root.search('tpl:assets').each do |ass| if wattr = ass.get_attribute('widgets') widgets = [] wattr.split(/,\s*/).each do |w| w_templates = nil if w =~ /(\.+)\((.+)\)/ w = $1 w_templates = $2.split('|') end klass = Spider::Template.get_registered_class(w) unless klass Spider.logger.warn("tpl:assets requested non existent widget #{w}") next end w_templates ||= [klass.default_template] w_templates.each do |wt| t = klass.load_template(wt) add_widget_template(t, klass) end end elsif sattr = ass.get_attribute('src') sattr.split(/,\s*/).each do |s| s_template = Spider::Template.new(s) s_template.owner = @owner s_template.definer_class = @definer_class s_template.load(s) @assets = s_template.assets + @assets end end end root.search('tpl:assets').remove root_block = TemplateBlocks.parse_element(root, self.class.allowed_blocks, self) if doc.children && doc.children[0].is_a?(Hpricot::DocType) root_block.doctype = doc.children[0] options[:doctype] = DocType.new(root_block.doctype) else options[:doctype] ||= DocType.new(Spider.conf.get('template.default_doctype')) end options[:root] = true options[:owner] = @owner options[:owner_class] = @owner_class || @owner.class options[:template_path] = @path options[:template] = self compiled.block = root_block.compile(options) subtemplates.each do |id, sub| sub.owner_class = @subtemplate_owners[id] compiled.subtemplates[id] = sub.compile(options.merge({:mode => :widget})) # FIXME! :mode => :widget is wrong, it's just a quick kludge @assets += compiled.subtemplates[id].assets end @widget_templates.each do |wt| wt.mode = :widget wt.load # sub_c = sub.compile(options.merge({:mode => :widget})) @assets = wt.compiled.assets + @assets end seen = {} # @assets.each_index do |i| # ass = @assets[i] # if ass[:name] # end @assets.each do |ass| ass[:profiles] = ((ass[:profiles] || []) + @asset_profiles).uniq if @asset_profiles next if seen[ass.inspect] res_init += "@assets << #{ass.inspect}\n" # res_init += "@assets << { # :type => :#{ass[:type]}, # :src => '#{ass[:src]}', # :path => '#{ass[:path]}', # :if => '#{ass[:if]}'" # res_init += ",\n :compiled => '#{ass[:compressed]}'" if ass[:compressed] # res_init += "}\n" seen[ass.inspect] = true end compiled.block.init_code = res_init + compiled.block.init_code compiled.devel_info["source.xml"] = root.to_html compiled.assets = (@assets + assets).uniq return compiled end # Processes an asset. Returns an hash with :type, :src, :path. def parse_asset(type, src, attributes={}) # FIXME: use Spider.find_asset ? type = type.to_sym if type ass = {:type => type} if attributes[:name] named = Spider::Template.get_named_asset(attributes[:name]) raise "Can't find named asset #{attributes[:name]}" unless named if attributes[:profiles] named.each{ |nmdass| nmdass[:profiles] = attributes[:profiles] } end return named.map{ |nmdass| parse_asset(nmdass[:type], nmdass[:src], nmdass) }.flatten end if attributes[:profiles] ass[:profiles] = attributes[:profiles].split(/,\s*/).map{ |p| p.to_sym } end if attributes[:app] == :runtime ass[:runtime] = src return [ass] end if attributes[:app] asset_owner = attributes[:app] asset_owner = Spider.apps_by_path[asset_owner] unless asset_owner.is_a?(Module) elsif attributes[:home] asset_owner = Spider.home else asset_owner = (@owner ? @owner.class : @owner_class ) end ass[:app] = asset_owner.app if asset_owner.respond_to?(:app) # FIXME! @definer_class is not correct for Spider::HomeController raise "Asset type not given for #{src}" unless type search_classes = [asset_owner, @definer_class] dfnr = @definer_class.superclass if @definer_class && @definer_class.respond_to?(:superclass) while dfnr && dfnr < Spider::Widget search_classes << dfnr dfnr = dfnr.respond_to?(:superclass) ? dfnr.superclass : nil end res = Spider.find_resource(type.to_sym, src, @path, search_classes) controller = nil if res && res.definer controller = res.definer.controller if res.definer.is_a?(Spider::Home) ass[:app] = :home else ass[:app] = res.definer end elsif owner_class < Spider::Controller controller = owner_class end ass[:path] = res.path if res base_url = nil if controller.respond_to?(:pub_url) if src[0].chr == '/' if controller <= Spider::HomeController src = src[(1+controller.pub_path.length)..-1] else # strips the app path from the src. FIXME: should probably be done somewhere else src = src[(2+controller.app.relative_path.length)..-1] end end base_url = controller.pub_url+'/' else base_url = '' end ass[:rel_path] = src ass[:src] = base_url + src ass_info = self.class.asset_types[type] if ass_info && ass_info[:processor] processor = TemplateAssets.const_get(ass_info[:processor]) ass = processor.process(ass) end if cpr = attributes[:compressed] if cpr == true || cpr == "true" ass[:compressed_path] = ass[:path] ass[:compressed_rel_path] = ass[:rel_path] ass[:compressed] = base_url + File.basename(ass[:path]) else compressed_res = Spider.find_resource(type.to_sym, cpr, @path, [owner_class, @definer_class]) ass[:compressed_path] = compressed_res.path ass[:compressed] = base_url+cpr end end ass[:copy_dir] = attributes[:copy_dir] ass[:copy_dir] = ass[:copy_dir] =~ /\d+/ ? ass[:copy_dir].to_i : true [:gettext, :media, :if_ie_lte, :cdn].each do |key| ass[key] = attributes[key] if attributes.key?(key) end return [ass] end # Returns the root node of the template at given path. # Will apply overrides and process extends and inclusions. def get_el(path_or_doc=nil) path = nil doc = nil if path_or_doc.is_a?(Hpricot::Doc) doc = path_or_doc path = @path else path = path_or_doc path ||= @path doc = open(path){ |f| Hpricot.XML(f) } end root = doc.root overrides = [] orig_overrides = @overrides @overrides = [] if root.children override_tags.each do |tag| overrides += root.children_of_type('tpl:'+tag) end end overrides.each{ |o| o.set_attribute('class', 'to_delete') } root.search('.to_delete').remove add_overrides overrides our_domain = nil if @definer_class our_domain = @definer_class.respond_to?(:app) ? @definer_class.app.short_name : 'spider' end @overrides += orig_overrides if root.name == 'tpl:extend' orig_overrides = @overrides @overrides = [] ext_src = root.get_attribute('src') ext_app = root.get_attribute('app') ext_widget = root.get_attribute('widget') if ext_widget ext_widget = Spider::Template.get_registered_class(ext_widget) ext_src ||= ext_widget.default_template ext_owner = ext_widget ext_app = ext_widget.app elsif ext_app ext_app = Spider.apps_by_path[ext_app] ext_owner = ext_app else ext_owner = @owner.class ext_app = ext_owner.app end ext_search_paths = nil if ext_owner && ext_owner.respond_to?(:template_paths) ext_search_paths = ext_owner.template_paths end ext = self.class.real_path(ext_src, path, ext_owner, ext_search_paths) raise "Extended template #{ext_src} not found (search path #{path}, owner #{ext_owner}, search paths #{ext_search_paths.inspect}" unless ext assets = [] if root.children assets = root.children_of_type('tpl:asset') assets += root.children_of_type('tpl:assets') end @dependencies << ext tpl = Template.new(ext) root = get_el(ext) if ext_app.short_name != our_domain root.set_attribute('tpl:text-domain', ext_app.short_name) end root.children_of_type('tpl:asset').each do |ass| ass_src = ass.get_attribute('src') if ass_src && ass_src[0].chr != '/' # ass.set_attribute('src', "/#{ext_app.relative_path}/#{ass_src}") ass.set_attribute('app', ext_app.relative_path) if ass.get_attribute('app').blank? end end @overrides += orig_overrides if assets && !assets.empty? assets.each do |ass| root.innerHTML += ass.to_html end end else assets_html = "" root.search('tpl:include').each do |incl| resource = Spider.find_resource(:views, incl.get_attribute('src'), @path, [@owner.class, @definer_class]) src = resource.path raise "Template #{@path} didn't find included '#{incl.get_attribute('src')}'" unless src @dependencies << src incl_el = self.get_el(src) assets = incl_el.children ? incl_el.children_of_type('tpl:asset') : [] assets.each{ |ass| ass.set_attribute('class', 'to_delete') ass_src = ass.get_attribute('src') if ass_src && ass_src[0].chr != '/' if resource.definer.is_a?(Spider::Home) ass.set_attribute('home', 'true') else # ass.set_attribute('src', "/#{resource.definer.relative_path}/#{ass_src}") ass.set_attribute('app', resource.definer.relative_path) end end assets_html += ass.to_html } if incl_el.children incl_el.children_of_type('tpl:assets').each do |asss| assets_html += asss.to_html end end incl_el.search('.to_delete').remove td = resource.definer.respond_to?(:app) ? resource.definer.app.short_name : 'spider' if td != our_domain incl_el.set_attribute('tpl:text-domain', td) end incl.swap(incl_el.to_html) end root.search('.to_delete').remove root.innerHTML = assets_html + root.innerHTML end return root end def process_tags(el) block = TemplateBlocks.get_block_type(el, true) raise "Bad html in #{@path}, can't parse" if el.is_a?(Hpricot::BogusETag) if block == :Tag sp_attributes = {} # FIXME: should use blocks instead el.attributes.to_hash.each do |key, value| if key[0..1] == 'sp' sp_attributes[key] = value el.remove_attribute(key) end end klass = Spider::Template.get_registered_class(el.name) tag = klass.new(el) res = process_tags(Hpricot(tag.render).root) sp_attributes.each{ |key, value| res.set_attribute(key, value) } return res else el.each_child do |child| next if child.is_a?(Hpricot::Text) || child.is_a?(Hpricot::Comment) el.replace_child(child, process_tags(child)) end end return el end # The full path of a template mentioned in this one. def real_path(path) self.class.real_path(path, File.dirname(@path), [@owner.class, @definer_class]) end def loaded? @compiled ? true : false end # Adds a widget instance to the template. # This method is usually not called directly; widgets are added during the template # init phase. def add_widget(id, widget, attributes=nil, content=nil, template=nil) @widgets[id.to_sym] ||= widget widget.id = id widget.id_path = @id_path + [id] if attributes # don't use merge to trigger custom []=(k, v) method attributes.each{ |k, v| widget.attributes[k] = v } end widget.containing_template = self widget.template = template if template widget.parent = @owner widget.parse_runtime_content_xml(content, @path) if content if @widget_procs[id.to_sym] @widget_procs[id.to_sym].each do |wp| apply_widget_proc(widget, wp) end end widget end def find_widget(path) return @widgets[path.to_sym] end # Does the init phase (evals the template's compiled _init.rb_). def init(scene) # Spider::Logger.debug("Template #{@path} INIT") load unless loaded? # debug("Template #{@path} init") # debug(@compiled.init_code) @scene = scene instance_eval(@compiled.init_code, @compiled.cache_path+'/init.rb') @init_done = true end def init_done? @init_done end # Calls the before method of all widget instances. def do_widgets_before @widgets.each do |id, w| act = (@_action_to == id) ? @_action : '' w.widget_before(act) unless w.before_done? end end # Calls the run method on all widget instances. def run_widgets @widgets.each do |id, w| w.run if w.run? && !w.did_run? end end # Does #do_widgets_before and then #run_widgets. def exec do_widgets_before run_widgets end # Does the render phase. # Will execute the following steps (if needed): # - load # - init # - exec # - eval the template's compiled run code. def render(scene=nil) prev_domain = nil if @definer_class td = @definer_class.respond_to?(:app) ? @definer_class.app.short_name : 'spider' prev_domain = Spider::GetText.set_domain(td) end scene ||= @scene load unless loaded? init(scene) unless init_done? exec @content.merge!(@widgets) # if Spider.conf.get('template.safe') # debug("RENDERING IN SAFE MODE!") # debug(@compiled.run_code) # # FIXME: must send header before safe mode # current_thread = Thread.current # t = Thread.new { # Thread.current[:stdout] = current_thread[:stdout] # $SAFE = 4 # scene.instance_eval("def __run_template\n"+@compiled.run_code+"end\n", @compiled.cache_path+'/run.rb') # scene.__run_template # scene.__run_template do |widget| # @content[widget].run # end # } # t.join # else scene.instance_eval("def __run_template\n"+@compiled.run_code+"end\n", @compiled.cache_path+'/run.rb', 0) scene.__run_template do |yielded| if yielded == :_parent @owner.parent.template.content.merge!(@content) @owner.parent.template.run_block else @content[yielded].render if @content[yielded] end end Spider::GetText.restore_domain(prev_domain) if prev_domain # end end def run_block @scene.__run_block do |yielded, block| @content[yielded].render if @content[yielded] end end # Alias for #render. def run render(@scene) end def inspect self.class.to_s end def add_subtemplate(id, template, owner) # :nodoc: @subtemplates[id] = template @subtemplate_owners[id] = owner end def add_widget_template(template, owner_class) template.owner_class = owner_class @widget_templates << template end def load_subtemplate(id, options={}) # :nodoc: load unless loaded? return nil unless @compiled.subtemplates[id] t = Template.new t.asset_profiles = options[:asset_profiles] if options[:asset_profiles] t.compiled = @compiled.subtemplates[id] return t end def add_overrides(overrides) overrides.each do |ov| w = ov.get_attribute('widget') if w first, rest = w.split('/', 2) if rest ov.set_attribute('widget', rest) else ov.remove_attribute('widget') end @widgets_overrides[first] ||= [] @widgets_overrides[first] << ov else @overrides << ov end end end def overrides_for(widget_id) @widgets_overrides[widget_id] || [] end def apply_overrides(el) info_els = nil if el.children info_els = Hpricot::Elements[*(el.children_of_type('tpl:asset')+ el.children_of_type('tpl:assets'))] info_els.remove end if @overrides @overrides.each{ |o| apply_override(el, o) } end if info_els el.innerHTML = info_els.to_s + el.innerHTML end el end # Applies an override to an (Hpricot) element. def apply_override(el, override) if override.is_a?(Proc) return override.call(el) end search_string = override.get_attribute('search') override.name = 'tpl:override-content' if override.name == 'tpl:inline-override' if search_string # # Fix Hpricot bug! # search_string.gsub!(/nth-child\((\d+)\)/) do |match| # "nth-child(#{$1.to_i-2})" # end found = el.parent.search(search_string) elsif override.name == 'tpl:content' found = el.search("tpl:placeholder[@name='#{override.get_attribute('name')}']") else if ['sp:template'].include?(el.name) found = el.children.select{ |child| child.is_a?(Hpricot::Elem) } else found = [el] end end if override.name == 'tpl:delete' found.remove else found.each do |f| o_doc = nil if override.name == 'tpl:override-content' overridden = f.innerHTML f.innerHTML = override.innerHTML f.search('tpl:overridden').each do |o| ovr = overridden if o_search = o.get_attribute('search') o_doc ||= Hpricot("<o>#{overridden}</o>") ovr = o_doc.root.search(o_search).to_html end o.swap(ovr) end elsif override.name == 'tpl:override' || override.name == 'tpl:content' overridden = f.to_html parent = f.parent if f == el f.innerHTML = override.innerHTML else f.swap(override.innerHTML) end parent.search('tpl:overridden').each do |o| ovr = overridden if o_search = o.get_attribute('search') o_doc ||= Hpricot("<o>#{overridden}</o>") ovr = o_doc.root.search(o_search).to_html end o.swap(ovr) end elsif override.name == 'tpl:override-attr' f.set_attribute(override.get_attribute("name"), override.get_attribute("value")) elsif override.name == 'tpl:append-attr' a = f.get_attribute(override.get_attribute("name")) || '' a += ' ' unless a.blank? a += override.get_attribute("value") f.set_attribute(override.get_attribute("name"), a) elsif override.name == 'tpl:append' f.innerHTML += override.innerHTML elsif override.name == 'tpl:prepend' f.innerHTML = override.innerHTML + f.innerHTML elsif override.name == 'tpl:before' f.before(override.innerHTML) elsif override.name == 'tpl:after' f.after(override.innerHTML) end end end end def with_widget(path, &proc) first, rest = path.split('/', 2) @widget_procs[first.to_sym] ||= [] wp = {:target => rest, :proc => proc } @widget_procs[first.to_sym] << wp if @widgets[first.to_sym] apply_widget_proc(@widgets[first.to_sym], wp) end end def apply_widget_proc(widget, wp) if wp[:target] widget.with_widget(wp[:target], &wp[:proc]) else widget.instance_eval(wp[:proc]) end end def inspect "#<#{self.class}:#{self.object_id} #{@path}>" end ExpressionOutputRegexp = /\{?\{\s([^\s].*?)\s\}\}?/ GettextRegexp = /([snp][snp]?)?_\(([^\)]+)?\)(\s%\s([^\s,]+(?:,\s*\S+\s*)?))?/ ERBRegexp = /(<%(.+)?%>)/ SceneVarRegexp = /@(\w[\w\d_]+)/ def self.scan_text(text) text = text.gsub(/\302\240/u, ' ') # remove annoying fake space scanner = ::StringScanner.new(text) pos = 0 c = "" while scanner.scan_until(Regexp.union(ExpressionOutputRegexp, GettextRegexp, ERBRegexp)) t = scanner.pre_match[pos..-1] pos = scanner.pos yield :plain, t, t if t && t.length > 0 case scanner.matched when ExpressionOutputRegexp if scanner.matched[1].chr == '{' yield :escaped_expr, $1, scanner.matched else yield :expr, $1, scanner.matched end when GettextRegexp gt = {:val => $2, :func => $1} gt[:vars] = $4 if $3 # interpolated vars yield :gettext, gt, scanner.matched when ERBRegexp yield :erb, $1, scanner.matched end end yield :plain, scanner.rest, scanner.rest end def self.scan_scene_vars(str) scanner = ::StringScanner.new(str) pos = 0 while scanner.scan_until(SceneVarRegexp) text = scanner.pre_match[pos..-1] yield :plain, text, text if text && text.length > 0 pos = scanner.pos yield :var, scanner.matched[1..-1] end yield :plain, scanner.rest end end # Class holding compiled template code. class CompiledTemplate attr_accessor :block, :source_path, :cache_path, :subtemplates, :devel_info, :assets def initialize() @subtemplates = {} @subtemplate_owners = {} @devel_info = {} end def init_code @block.init_code end def run_code @block.run_code end def collect_mtimes mtimes = {@source_path => File.mtime(@source_path)} @subtemplates.each{ |id, sub| mtimes.merge(sub.collect_mtimes)} return mtimes end end class TemplateCompileError < RuntimeError end class DocType attr_reader :type, :variant def initialize(type_or_str) if type_or_str.is_a?(Symbol) @type = type_or_str else parse(type_or_str.to_s) end end def parse(str) if str =~ /DOCTYPE HTML PUBLIC.+\sHTML/i @type = :html4 elsif str =~ /DOCTYPE HTML PUBLIC.+\sXHTML/i @type = :xhtml elsif str.downcase == '<!doctype html>' @type = :html5 end if str =~ /strict/i @variant = :strict elsif str =~ /transitional/i @variant = :transitional end end def html? @type == :html4 || @type == :html5 end def xhtml? @type == :xhtml end def strict? @variant == :strict end end end
class ParticipantsController < ApplicationController before_filter :authenticate_user! set_tab :profile helper_method :sort_column, :sort_direction access_control do allow :admin allow :functionary, :to => [:index, :show] allow :participant, :to => [:show, :edit, :update, :travel_support, :invitation] end # GET /participants # GET /participants.xml def index search_participant if current_user.has_role?(:admin) @participants = Participant.order(sort_column + ' ' + sort_direction).where(@query).paginate(:per_page => 25, :page=>params[:page]) else @participants = Participant.where(:functionary_id => current_user.functionary.id).where(@query).order(sort_column + ' ' + sort_direction).paginate(:per_page => 25, :page=>params[:page]) end respond_to do |format| format.html # index.html.erb format.js end end # GET /participants/1 def show if !Deadline.deadline_done?("Visit profile page", current_user) Deadline.first.users << current_user end @participant = Participant.find(params[:id]) respond_to do |format| format.html # show.html.erb end end def invitation @participant = Participant.find(params[:id]) if current_user == @participant.user || !current_user.has_role?(:participant) respond_to do |f| f.html {render 'invitation', :layout=>false} end else raise Acl9::AccessDenied end end def travel_support @participant = Participant.find(params[:id]) if @participant.travel_support < 1 raise Acl9::AccessDenied return end if current_user.id == @participant.user.id respond_to do |format| format.html {render 'travel_support', :layout=>false} end else raise Acl9::AccessDenied end end # GET /participants/1/edit def edit @participant = Participant.find(params[:id]) @accepted = @participant.accepted if current_user == @participant.user or current_user.has_role?(:admin, nil) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @participant } end else raise Acl9::AccessDenied end end # PUT /participants/1 # PUT /participants/1.xml def update @participant = Participant.find(params[:id]) if current_user == @participant.user or current_user.has_role?(:admin, nil) respond_to do |format| if @participant.update_attributes(params[:participant]) if @participant.applied_for_visa == 1 && !Deadline.deadline_done?("Apply for a visa", current_user) d = Deadline.find(4) d.users << current_user elsif @participant.applied_for_visa == 0 && Deadline.deadline_done?("Apply for a visa", current_user) d = Deadline.find(4) d.users.delete(current_user) end if @participant.accepted == 1 && Deadline.find(5).users.index(current_user) == nil d = Deadline.find(5) d.users << current_user elsif @participant.accepted == 0 && Deadline.find(5).users.index(current_user) != nil d = Deadline.find(5) d.users.delete(current_user) end format.html { redirect_to(@participant, :notice => 'Participant was successfully updated.') } else format.html { render :action => "edit" } end end else raise Acl9::AccessDenied end end #NIKOLAI WAS HERE def search_participant @query = "" if params[:participant] @search_participant = Participant.new(params[:participant]) first_name = @search_participant.first_name last_name = @search_participant.last_name email = @search_participant.email workshop = @search_participant.workshop if first_name != "" if @query == "" @query = "first_name LIKE '%"+first_name+"%'" else @query += " AND first_name LIKE '%"+first_name+"%'" end end if last_name != "" if @query == "" @query = "last_name LIKE '%"+last_name+"%'" else @query += " AND last_name LIKE '%"+last_name+"%'" end end if email !="" if @query == "" @query = "email LIKE '%"+email+"%'" else @query += " AND email LIKE '%"+email+"%'" end end if workshop == nil elsif workshop !="" if @query == "" @query = "workshop LIKE 'workshop'" else @query += " AND workshop LIKE 'workshop'" end end end end def mail_to_search_results search_participant if current_user.has_role?(:admin) @participants = Participant.order(sort_column + ' ' + sort_direction).where(@query) else @participants = Participant.where(:functionary_id => current_user.functionary.id).where(@query).order(sort_column + ' ' + sort_direction) end if params[:mailform] subject = params[:mailform][:subject] text = params[:mailform][:text] respond_to do |format| format.js end @participants.each do |a| sleep(0.5) ParticipantsMailer.send_mail(a, subject, text) end end end private def sort_column Participant.column_names.include?(params[:sort]) ? params[:sort] : "last_name" end def sort_direction %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc" end end No idea what I'm commiting class ParticipantsController < ApplicationController before_filter :authenticate_user! set_tab :profile helper_method :sort_column, :sort_direction access_control do allow :admin allow :functionary, :to => [:index, :show] allow :participant, :to => [:show, :edit, :update, :travel_support, :invitation] end # GET /participants # GET /participants.xml def index search_participant if current_user.has_role?(:admin) @participants = Participant.order(sort_column + ' ' + sort_direction).where(@query).paginate(:per_page => 100, :page=>params[:page]) else @participants = Participant.where(:functionary_id => current_user.functionary.id).where(@query).order(sort_column + ' ' + sort_direction).paginate(:per_page => 25, :page=>params[:page]) end respond_to do |format| format.html # index.html.erb format.js end end # GET /participants/1 def show if !Deadline.deadline_done?("Visit profile page", current_user) Deadline.first.users << current_user end @participant = Participant.find(params[:id]) respond_to do |format| format.html # show.html.erb end end def invitation @participant = Participant.find(params[:id]) if current_user == @participant.user || !current_user.has_role?(:participant) respond_to do |f| f.html {render 'invitation', :layout=>false} end else raise Acl9::AccessDenied end end def travel_support @participant = Participant.find(params[:id]) if @participant.travel_support < 1 raise Acl9::AccessDenied return end if current_user.id == @participant.user.id respond_to do |format| format.html {render 'travel_support', :layout=>false} end else raise Acl9::AccessDenied end end # GET /participants/1/edit def edit @participant = Participant.find(params[:id]) @accepted = @participant.accepted if current_user == @participant.user or current_user.has_role?(:admin, nil) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @participant } end else raise Acl9::AccessDenied end end # PUT /participants/1 # PUT /participants/1.xml def update @participant = Participant.find(params[:id]) if current_user == @participant.user or current_user.has_role?(:admin, nil) respond_to do |format| if @participant.update_attributes(params[:participant]) if @participant.applied_for_visa == 1 && !Deadline.deadline_done?("Apply for a visa", current_user) d = Deadline.find(4) d.users << current_user elsif @participant.applied_for_visa == 0 && Deadline.deadline_done?("Apply for a visa", current_user) d = Deadline.find(4) d.users.delete(current_user) end if @participant.accepted == 1 && Deadline.find(5).users.index(current_user) == nil d = Deadline.find(5) d.users << current_user elsif @participant.accepted == 0 && Deadline.find(5).users.index(current_user) != nil d = Deadline.find(5) d.users.delete(current_user) end format.html { redirect_to(@participant, :notice => 'Participant was successfully updated.') } else format.html { render :action => "edit" } end end else raise Acl9::AccessDenied end end #NIKOLAI WAS HERE def search_participant @query = "" if params[:participant] @search_participant = Participant.new(params[:participant]) first_name = @search_participant.first_name last_name = @search_participant.last_name email = @search_participant.email workshop = @search_participant.workshop accepted = @search_partcipant.accepted if first_name != "" if @query == "" @query = "first_name LIKE '%"+first_name+"%'" else @query += " AND first_name LIKE '%"+first_name+"%'" end end if last_name != "" if @query == "" @query = "last_name LIKE '%"+last_name+"%'" else @query += " AND last_name LIKE '%"+last_name+"%'" end end if email !="" if @query == "" @query = "email LIKE '%"+email+"%'" else @query += " AND email LIKE '%"+email+"%'" end end if workshop == nil elsif workshop !="" if @query == "" @query = "workshop LIKE '#{workshop}'" else @query += " AND workshop LIKE '#{workshop}'" end end if accepted == 0 elsif accepted == 1 if @query == "" @query = "accepted = 1" else @query += " AND accepted = 1" end end end end def mail_to_search_results search_participant if current_user.has_role?(:admin) @participants = Participant.order(sort_column + ' ' + sort_direction).where(@query) else @participants = Participant.where(:functionary_id => current_user.functionary.id).where(@query).order(sort_column + ' ' + sort_direction) end if params[:mailform] subject = params[:mailform][:subject] text = params[:mailform][:text] respond_to do |format| format.js end @participants.each do |a| sleep(0.5) ParticipantsMailer.send_mail(a, subject, text) end end end private def sort_column Participant.column_names.include?(params[:sort]) ? params[:sort] : "last_name" end def sort_direction %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc" end end
require 'sprockets/asset_attributes' require 'sprockets/bundled_asset' require 'sprockets/digest' require 'sprockets/errors' require 'sprockets/static_asset' require 'digest/md5' require 'pathname' module Sprockets class EnvironmentIndex include Digest, Server, Processing, StaticCompilation attr_reader :logger, :context_class def initialize(environment, trail, static_root) @logger = environment.logger @context_class = environment.context_class @digest_class = environment.digest_class @digest_key_prefix = environment.digest_key_prefix @trail = trail.index @assets = {} @entries = {} @mtimes = {} @md5s = {} @static_root = static_root ? Pathname.new(static_root) : nil @mime_types = environment.mime_types @engines = environment.engines @processors = environment.processors @bundle_processors = environment.bundle_processors end def root @trail.root end def paths @trail.paths end def extensions @trail.extensions end def index self end def resolve(logical_path, options = {}) if block_given? @trail.find(logical_path.to_s, logical_index_path(logical_path), options) do |path| yield Pathname.new(path) end else resolve(logical_path, options) do |pathname| return pathname end raise FileNotFound, "couldn't find file '#{logical_path}'" end end def find_asset(path, options = {}) options[:_index] ||= self pathname = Pathname.new(path) if pathname.absolute? build_asset(detect_logical_path(path).to_s, pathname, options) else logical_path = path.to_s.sub(/^\//, '') if @assets.key?(logical_path) @assets[logical_path] else @assets[logical_path] = find_asset_in_static_root(pathname) || find_asset_in_path(pathname, options) end end end alias_method :[], :find_asset def attributes_for(path) AssetAttributes.new(self, path) end def content_type_of(path) attributes_for(path).content_type end def mtime(pathname) filename = pathname.to_s if @mtimes.key?(filename) @mtimes[filename] else begin @mtimes[filename] = File.mtime(filename) rescue Errno::ENOENT @mtimes[filename] = nil end end end def md5(pathname) filename = pathname.to_s if @md5s.key?(filename) @md5s[filename] else begin @md5s[filename] = Digest::MD5.new(filename).hexdigest rescue Errno::ENOENT @md5s[filename] = nil end end end protected def expire_index! raise TypeError, "can't modify immutable index" end def find_asset_in_path(logical_path, options = {}) if fingerprint = path_fingerprint(logical_path) pathname = resolve(logical_path.to_s.sub("-#{fingerprint}", '')) else pathname = resolve(logical_path) end rescue FileNotFound nil else asset = build_asset(logical_path, pathname, options) if fingerprint && fingerprint != asset.digest logger.error "Nonexistent asset #{logical_path} @ #{fingerprint}" asset = nil end asset end def build_asset(logical_path, pathname, options) if asset = @assets[logical_path.to_s] return asset end pathname = Pathname.new(pathname) if processors(content_type_of(pathname)).any? asset = BundledAsset.new(self, logical_path, pathname, options) else asset = StaticAsset.new(self, logical_path, pathname) end @assets[logical_path.to_s] = asset end private def logical_index_path(logical_path) pathname = Pathname.new(logical_path) attributes = attributes_for(logical_path) if attributes.basename_without_extensions.to_s == 'index' logical_path else basename = "#{attributes.basename_without_extensions}/index#{attributes.extensions.join}" pathname.dirname.to_s == '.' ? basename : pathname.dirname.join(basename).to_s end end def detect_logical_path(filename) if root_path = paths.detect { |path| filename.to_s[path] } root_pathname = Pathname.new(root_path) logical_path = Pathname.new(filename).relative_path_from(root_pathname) path_without_engine_extensions(logical_path) end end def path_without_engine_extensions(pathname) attributes_for(pathname).engine_extensions.inject(pathname) do |p, ext| p.sub(ext, '') end end end end Remove md5 method require 'sprockets/asset_attributes' require 'sprockets/bundled_asset' require 'sprockets/digest' require 'sprockets/errors' require 'sprockets/static_asset' require 'pathname' module Sprockets class EnvironmentIndex include Digest, Server, Processing, StaticCompilation attr_reader :logger, :context_class def initialize(environment, trail, static_root) @logger = environment.logger @context_class = environment.context_class @digest_class = environment.digest_class @digest_key_prefix = environment.digest_key_prefix @trail = trail.index @assets = {} @entries = {} @mtimes = {} @digests = {} @static_root = static_root ? Pathname.new(static_root) : nil @mime_types = environment.mime_types @engines = environment.engines @processors = environment.processors @bundle_processors = environment.bundle_processors end def root @trail.root end def paths @trail.paths end def extensions @trail.extensions end def index self end def resolve(logical_path, options = {}) if block_given? @trail.find(logical_path.to_s, logical_index_path(logical_path), options) do |path| yield Pathname.new(path) end else resolve(logical_path, options) do |pathname| return pathname end raise FileNotFound, "couldn't find file '#{logical_path}'" end end def find_asset(path, options = {}) options[:_index] ||= self pathname = Pathname.new(path) if pathname.absolute? build_asset(detect_logical_path(path).to_s, pathname, options) else logical_path = path.to_s.sub(/^\//, '') if @assets.key?(logical_path) @assets[logical_path] else @assets[logical_path] = find_asset_in_static_root(pathname) || find_asset_in_path(pathname, options) end end end alias_method :[], :find_asset def attributes_for(path) AssetAttributes.new(self, path) end def content_type_of(path) attributes_for(path).content_type end def mtime(pathname) filename = pathname.to_s if @mtimes.key?(filename) @mtimes[filename] else begin @mtimes[filename] = File.mtime(filename) rescue Errno::ENOENT @mtimes[filename] = nil end end end def file_hexdigest_digest(pathname) filename = pathname.to_s if @digests.key?(filename) @digests[filename] else begin @digests[filename] = digest.file(filename).hexdigest rescue Errno::ENOENT @digests[filename] = nil end end end protected def expire_index! raise TypeError, "can't modify immutable index" end def find_asset_in_path(logical_path, options = {}) if fingerprint = path_fingerprint(logical_path) pathname = resolve(logical_path.to_s.sub("-#{fingerprint}", '')) else pathname = resolve(logical_path) end rescue FileNotFound nil else asset = build_asset(logical_path, pathname, options) if fingerprint && fingerprint != asset.digest logger.error "Nonexistent asset #{logical_path} @ #{fingerprint}" asset = nil end asset end def build_asset(logical_path, pathname, options) if asset = @assets[logical_path.to_s] return asset end pathname = Pathname.new(pathname) if processors(content_type_of(pathname)).any? asset = BundledAsset.new(self, logical_path, pathname, options) else asset = StaticAsset.new(self, logical_path, pathname) end @assets[logical_path.to_s] = asset end private def logical_index_path(logical_path) pathname = Pathname.new(logical_path) attributes = attributes_for(logical_path) if attributes.basename_without_extensions.to_s == 'index' logical_path else basename = "#{attributes.basename_without_extensions}/index#{attributes.extensions.join}" pathname.dirname.to_s == '.' ? basename : pathname.dirname.join(basename).to_s end end def detect_logical_path(filename) if root_path = paths.detect { |path| filename.to_s[path] } root_pathname = Pathname.new(root_path) logical_path = Pathname.new(filename).relative_path_from(root_pathname) path_without_engine_extensions(logical_path) end end def path_without_engine_extensions(pathname) attributes_for(pathname).engine_extensions.inject(pathname) do |p, ext| p.sub(ext, '') end end end end
class ParticipantsController < ApplicationController load_and_authorize_resource def index @participants = Participant.paginate(page: params[:page]).joins(:user) .order('users.first_name ASC', 'users.last_name ASC') .where(approved_first_deadline: [1, 2], approved_second_deadline: [1, 2]) if params[:search].present? k = "%#{params[:search]}%" @participants = @participants .where("users.first_name LIKE ? OR users.last_name LIKE ? OR users.email LIKE ?", k, k, k) end if params[:only_checked_in].present? if params[:only_checked_in] == "1" @participants = @participants.where("checked_in = 1") elsif params[:only_checked_in] == "0" @participants = @participants.where("checked_in = 0 OR checked_in IS NULL") end if params[:host_status].present? if params[:host_status] == "1" @participants = @participants.where("host_id IS NOT NULL") elsif params[:host_status] == "0" @participants = @participants.where("host_id IS NULL") end end end if params[:country].nil? == false && params[:country][:country_id].present? == true @participants = @participants.joins(:profile).where('country_id = ? OR citizenship_id = ?',params[:country][:country_id], params[:country][:country_id]) end if !params[:workshop].nil? && params[:workshop][:workshop_id].present? @participants = @participants.where('participants.workshop_id = ?',params[:workshop][:workshop_id]) end end def update #Only used for updating internal comments @participant = Participant.find(params[:id]) @participant.internal_comments = params[:participant][:internal_comments] if @participant.save flash[:notice] = 'Successfully updated participant' else flash[:alert] = 'An error occurred, please try again' end redirect_to participant_path(@participant) end def show @participant = Participant.find(params[:id]) end def match_list @participants = Participant.paginate(page: params[:page]).joins(:user) .order('users.first_name ASC', 'users.last_name ASC') .where(approved_first_deadline: [1, 2]) @participants = @participants.where('host_id IS NULL') if params[:search].present? k = "%#{params[:search]}%" @participants = @participants .where("users.first_name LIKE ? OR users.last_name LIKE ? OR users.email LIKE ?", k, k, k) end if params[:only_checked_in].present? && params[:only_checked_in] == "1" @participants = @participants.where("checked_in = 1") end if params[:country].nil? == false && params[:country][:country_id].present? == true @participants = @participants.joins(:profile).where('country_id = ? OR citizenship_id = ?',params[:country][:country_id], params[:country][:country_id]) end if !params[:gender].blank? @participants = @participants.joins(:profile).where('gender = ?',params[:gender]) end if !params[:pref_gender].blank? @participants = @participants.joins(:profile).where('host_gender_preference = ?',params[:pref_gender]) end if !params[:allergy_animals].blank? @participants = @participants.joins(:profile).where('allergy_animals = ?', params[:allergy_animals]) end #@participants = @participants.paginate(page: params[:page]) if params[:match_now].blank? @match_now = false else @match_now = true @host = Host.find(params[:host_id]) end render 'hosts/match/index' end def match @participant = Participant.find(params[:id]) temphosts = Host.get_all_non_deleted if params[:search].present? k = "%#{params[:search]}%" temphosts = temphosts .where("firstname LIKE ? OR lastname LIKE ?", k, k) end if !params[:gender_pref].blank? temphosts = temphosts.where("sex = ?",params[:gender_pref]) end if !params[:animals].blank? temphosts = temphosts.where("animales = ?",params[:animals]) end if !params[:day_early].blank? temphosts = temphosts.where("Onedayearly = ?",params[:day_early]) end if !params[:day_late].blank? temphosts = temphosts.where("extraday = ?",params[:day_late]) end if !params[:student].blank? temphosts = temphosts.where("isstudent = ?",params[:student]) end if !params[:hosted_before].blank? temphosts = temphosts.where("beenhost = ?",params[:hosted_before]) end if !params[:sleeping].blank? temphosts = temphosts.where("sleeping = ?",params[:sleeping]) end if !params[:free_spaces].blank? && params[:free_spaces] == '1' #Fix this later @hosts = Array.new temphosts.each do |h| if h.has_free_beds? @hosts.push h end end else @hosts = temphosts end @hosts = @hosts.paginate(page: params[:page]) render 'hosts/match/host/index' end def apply_match participant = Participant.find(params[:participant_id]) if participant.host_id.nil? participant.host_id = params[:host_id] if participant.save flash[:notice] = 'Host and participant matched successfully' else flash[:alert] = 'An error occurred, please try again' end else flash[:alert] = 'This participant has already been matched with a host' end #match_list() redirect_to host_path(params[:host_id]) end def unmatch session[:return_to] = request.referer participant = Participant.find(params[:participant_id]) participant.host_id = nil if participant.save flash[:notice] = 'Host and participant unmatched successfully' else flash[:alert] = 'An error occurred, please try again' end redirect_to session.delete(:return_to) end def lock_host session[:return_to] = request.referer participant = Participant.find(params[:participant_id]) if participant.host_id.nil? flash[:alert] = "Unable to lock because no host is set" else participant.host_locked = true if participant.save flash[:notice] = 'Matching successfully locked' else flash[:alert] = 'An error occured, please try again' end end redirect_to session.delete(:return_to) end def check_in session[:return_to] = request.referer participant = Participant.find(params[:participant_id]) participant.checked_in = true participant.check_in_time = DateTime.now if participant.save flash[:notice] = 'Participant successfully checked in' else flash[:alert] = 'An error occured, please try again' end redirect_to session.delete(:return_to) end end Fixes small bug class ParticipantsController < ApplicationController load_and_authorize_resource def index @participants = Participant.paginate(page: params[:page]).joins(:user) .order('users.first_name ASC', 'users.last_name ASC') .where(approved_first_deadline: [1, 2], approved_second_deadline: [1, 2]) if params[:search].present? k = "%#{params[:search]}%" @participants = @participants .where("users.first_name LIKE ? OR users.last_name LIKE ? OR users.email LIKE ?", k, k, k) end if params[:only_checked_in].present? if params[:only_checked_in] == "1" @participants = @participants.where("checked_in = 1") elsif params[:only_checked_in] == "0" @participants = @participants.where("checked_in = 0 OR checked_in IS NULL") end end if params[:host_status].present? if params[:host_status] == "1" @participants = @participants.where("host_id IS NOT NULL") elsif params[:host_status] == "0" @participants = @participants.where("host_id IS NULL") end end if params[:country].nil? == false && params[:country][:country_id].present? == true @participants = @participants.joins(:profile).where('country_id = ? OR citizenship_id = ?',params[:country][:country_id], params[:country][:country_id]) end if !params[:workshop].nil? && params[:workshop][:workshop_id].present? @participants = @participants.where('participants.workshop_id = ?',params[:workshop][:workshop_id]) end end def update #Only used for updating internal comments @participant = Participant.find(params[:id]) @participant.internal_comments = params[:participant][:internal_comments] if @participant.save flash[:notice] = 'Successfully updated participant' else flash[:alert] = 'An error occurred, please try again' end redirect_to participant_path(@participant) end def show @participant = Participant.find(params[:id]) end def match_list @participants = Participant.paginate(page: params[:page]).joins(:user) .order('users.first_name ASC', 'users.last_name ASC') .where(approved_first_deadline: [1, 2]) @participants = @participants.where('host_id IS NULL') if params[:search].present? k = "%#{params[:search]}%" @participants = @participants .where("users.first_name LIKE ? OR users.last_name LIKE ? OR users.email LIKE ?", k, k, k) end if params[:only_checked_in].present? && params[:only_checked_in] == "1" @participants = @participants.where("checked_in = 1") end if params[:country].nil? == false && params[:country][:country_id].present? == true @participants = @participants.joins(:profile).where('country_id = ? OR citizenship_id = ?',params[:country][:country_id], params[:country][:country_id]) end if !params[:gender].blank? @participants = @participants.joins(:profile).where('gender = ?',params[:gender]) end if !params[:pref_gender].blank? @participants = @participants.joins(:profile).where('host_gender_preference = ?',params[:pref_gender]) end if !params[:allergy_animals].blank? @participants = @participants.joins(:profile).where('allergy_animals = ?', params[:allergy_animals]) end #@participants = @participants.paginate(page: params[:page]) if params[:match_now].blank? @match_now = false else @match_now = true @host = Host.find(params[:host_id]) end render 'hosts/match/index' end def match @participant = Participant.find(params[:id]) temphosts = Host.get_all_non_deleted if params[:search].present? k = "%#{params[:search]}%" temphosts = temphosts .where("firstname LIKE ? OR lastname LIKE ?", k, k) end if !params[:gender_pref].blank? temphosts = temphosts.where("sex = ?",params[:gender_pref]) end if !params[:animals].blank? temphosts = temphosts.where("animales = ?",params[:animals]) end if !params[:day_early].blank? temphosts = temphosts.where("Onedayearly = ?",params[:day_early]) end if !params[:day_late].blank? temphosts = temphosts.where("extraday = ?",params[:day_late]) end if !params[:student].blank? temphosts = temphosts.where("isstudent = ?",params[:student]) end if !params[:hosted_before].blank? temphosts = temphosts.where("beenhost = ?",params[:hosted_before]) end if !params[:sleeping].blank? temphosts = temphosts.where("sleeping = ?",params[:sleeping]) end if !params[:free_spaces].blank? && params[:free_spaces] == '1' #Fix this later @hosts = Array.new temphosts.each do |h| if h.has_free_beds? @hosts.push h end end else @hosts = temphosts end @hosts = @hosts.paginate(page: params[:page]) render 'hosts/match/host/index' end def apply_match participant = Participant.find(params[:participant_id]) if participant.host_id.nil? participant.host_id = params[:host_id] if participant.save flash[:notice] = 'Host and participant matched successfully' else flash[:alert] = 'An error occurred, please try again' end else flash[:alert] = 'This participant has already been matched with a host' end #match_list() redirect_to host_path(params[:host_id]) end def unmatch session[:return_to] = request.referer participant = Participant.find(params[:participant_id]) participant.host_id = nil if participant.save flash[:notice] = 'Host and participant unmatched successfully' else flash[:alert] = 'An error occurred, please try again' end redirect_to session.delete(:return_to) end def lock_host session[:return_to] = request.referer participant = Participant.find(params[:participant_id]) if participant.host_id.nil? flash[:alert] = "Unable to lock because no host is set" else participant.host_locked = true if participant.save flash[:notice] = 'Matching successfully locked' else flash[:alert] = 'An error occured, please try again' end end redirect_to session.delete(:return_to) end def check_in session[:return_to] = request.referer participant = Participant.find(params[:participant_id]) participant.checked_in = true participant.check_in_time = DateTime.now if participant.save flash[:notice] = 'Participant successfully checked in' else flash[:alert] = 'An error occured, please try again' end redirect_to session.delete(:return_to) end end
class PublicationsController < ApplicationController include IndexPager include DotGenerator include Seek::TaggingCommon require 'pubmed_query_tool' #before_filter :login_required before_filter :find_assets, :only => [ :index ] before_filter :fetch_publication, :only => [:show, :edit, :update, :destroy] before_filter :associate_authors, :only => [:edit, :update] def preview element=params[:element] @publication = Publication.find_by_id(params[:id]) render :update do |page| if @publication page.replace_html element,:partial=>"publications/resource_preview",:locals=>{:resource=>@publication} else page.replace_html element,:text=>"Nothing is selected to preview." end end end # GET /publications/1 # GET /publications/1.xml def show respond_to do |format| format.html # show.html.erb format.xml format.svg { render :text=>to_svg(@publication,params[:deep]=='false',@publication)} format.dot { render :text=>to_dot(@publication,params[:deep]=='false',@publication)} format.png { render :text=>to_png(@publication,params[:deep]=='false',@publication)} end end # GET /publications/new # GET /publications/new.xml def new respond_to do |format| format.html # new.html.erb format.xml end end # GET /publications/1/edit def edit end # POST /publications # POST /publications.xml def create @publication = Publication.new(params[:publication]) @publication.pubmed_id=nil if @publication.pubmed_id.blank? @publication.doi=nil if @publication.doi.blank? result = get_data(@publication, @publication.pubmed_id, @publication.doi) assay_ids = params[:assay_ids] || [] @publication.contributor = current_user respond_to do |format| if @publication.save result.authors.each do |author| pa = PublicationAuthor.new() pa.publication = @publication pa.first_name = author.first_name pa.last_name = author.last_name pa.save end Assay.find(assay_ids).each do |assay| Relationship.create_or_update_attributions(assay,{"Publication", @publication.id}.to_json, Relationship::RELATED_TO_PUBLICATION) if assay.can_edit?(current_user) end #Make a policy policy = Policy.create(:name => "publication_policy", :sharing_scope => Policy::EVERYONE, :access_type => Policy::VISIBLE, :use_custom_sharing => true) @publication.policy = policy @publication.save #add managers (authors + contributor) @publication.creators.each do |author| policy.permissions << Permission.create(:contributor => author, :policy => policy, :access_type => Policy::MANAGING) end #Add contributor @publication.policy.permissions << Permission.create(:contributor => @publication.contributor.person, :policy => policy, :access_type => Policy::MANAGING) flash[:notice] = 'Publication was successfully created.' format.html { redirect_to(edit_publication_url(@publication)) } format.xml { render :xml => @publication, :status => :created, :location => @publication } else format.html { render :action => "new" } format.xml { render :xml => @publication.errors, :status => :unprocessable_entity } end end end # PUT /publications/1 # PUT /publications/1.xml def update valid = true to_add = [] to_remove = [] params[:author].keys.sort.each do |author_id| author_assoc = params[:author][author_id] unless author_assoc.blank? to_remove << PublicationAuthor.find_by_id(author_id) p = Person.find(author_assoc) if @publication.creators.include?(p) @publication.errors.add_to_base("Multiple authors cannot be associated with the same SEEK person.") valid = false else to_add << p end end end #Check for duplicate authors if valid && (to_add.uniq.size != to_add.size) @publication.errors.add_to_base("Multiple authors cannot be associated with the same SEEK person.") valid = false end update_tags @publication assay_ids = params[:assay_ids] || [] respond_to do |format| publication_params = params[:publication]||{} publication_params[:event_ids] = params[:event_ids]||[] if valid && @publication.update_attributes(publication_params) to_add.each {|a| @publication.creators << a} to_remove.each {|a| a.destroy} # Update relationship Assay.find(assay_ids).each do |assay| if assay.can_edit?(current_user) && Relationship.find_all_by_object_id(@publication.id, :conditions => "subject_id = #{assay.id}").empty? Relationship.create_or_update_attributions(assay,{"Publication", @publication.id}.to_json, Relationship::RELATED_TO_PUBLICATION) end end #Destroy Assay relationship that aren't needed associate_relationships = Relationship.find(:all,:conditions=>["object_id = ? and subject_type = ?",@publication.id,"Assay"]) logger.info associate_relationships associate_relationships.each do |associate_relationship| if associate_relationship.subject.can_edit?(current_user) && !assay_ids.include?(associate_relationship.subject_id.to_s) Relationship.destroy(associate_relationship.id) end end #Create policy if not present (should be) if @publication.policy.nil? @publication.policy = Policy.create(:name => "publication_policy", :sharing_scope => Policy::EVERYONE, :access_type => Policy::VISIBLE, :use_custom_sharing => true) @publication.save end #Update policy so current authors have manage permissions @publication.creators.each do |author| @publication.policy.permissions.clear @publication.policy.permissions << Permission.create(:contributor => author, :policy => @publication.policy, :access_type => Policy::MANAGING) end #Add contributor @publication.policy.permissions << Permission.create(:contributor => @publication.contributor.person, :policy => @publication.policy, :access_type => Policy::MANAGING) flash[:notice] = 'Publication was successfully updated.' format.html { redirect_to(@publication) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @publication.errors, :status => :unprocessable_entity } end end end # DELETE /publications/1 # DELETE /publications/1.xml def destroy @publication.destroy respond_to do |format| format.html { redirect_to(publications_path) } format.xml { head :ok } end end def fetch_preview begin @publication = Publication.new(params[:publication]) @publication.project_id = params[:project_id] key = params[:key] protocol = params[:protocol] pubmed_id = nil doi = nil if protocol == "pubmed" pubmed_id = key elsif protocol == "doi" doi = key if doi.start_with?("doi:") doi = doi.gsub("doi:","") end end result = get_data(@publication, pubmed_id, doi) rescue if protocol == "pubmed" if key.match(/[0-9]+/).nil? @error_text = "Please ensure the PubMed ID is entered in the correct format, e.g. <i>16845108</i>" else @error_text = "No publication could be found on PubMed with that ID" end elsif protocol == "doi" if key.match(/[0-9]+(\.)[0-9]+.*/).nil? @error_text = "Please ensure the DOI is entered in the correct format, e.g. <i>10.1093/nar/gkl320</i>" else @error_text = "No valid publication could be found with that DOI" end end respond_to do |format| format.html { render :partial => "publications/publication_error", :locals => { :publication => @publication, :error_text => @error_text}, :status => 500} end else respond_to do |format| format.html { render :partial => "publications/publication_preview", :locals => { :publication => @publication, :authors => result.authors} } end end end #Try and relate non_seek_authors to people in SEEK based on name and project def associate_authors publication = @publication project = publication.project || current_user.person.projects.first association = {} publication.non_seek_authors.each do |author| matches = [] #Get author by last name last_name_matches = Person.find_all_by_last_name(author.last_name) matches = last_name_matches #If no results, try searching by normalised name, taken from grouped_pagination.rb if matches.size < 1 text = author.last_name #handle the characters that can't be handled through normalization %w[ØO].each do |s| text.gsub!(/[#{s[0..-2]}]/, s[-1..-1]) end codepoints = text.mb_chars.normalize(:d).split(//u) ascii=codepoints.map(&:to_s).reject{|e| e.length > 1}.join last_name_matches = Person.find_all_by_last_name(ascii) matches = last_name_matches end #If more than one result, filter by project if matches.size > 1 project_matches = matches.select{|p| p.projects.include?(project)} if project_matches.size >= 1 #use this result unless it resulted in no matches matches = project_matches end end #If more than one result, filter by first initial if matches.size > 1 first_and_last_name_matches = matches.select{|p| p.first_name.at(0).upcase == author.first_name.at(0).upcase} if first_and_last_name_matches.size >= 1 #use this result unless it resulted in no matches matches = first_and_last_name_matches end end #Take the first match as the guess association[author.id] = matches.first end @author_associations = association end def disassociate_authors @publication = Publication.find(params[:id]) @publication.creators.clear #get rid of author links @publication.non_seek_authors.clear #Query pubmed article to fetch authors result = nil pubmed_id = @publication.pubmed_id doi = @publication.doi if pubmed_id query = PubmedQuery.new("seek",Seek::Config.pubmed_api_email) result = query.fetch(pubmed_id) elsif doi query = DoiQuery.new(Seek::Config.crossref_api_email) result = query.fetch(doi) end unless result.nil? result.authors.each do |author| pa = PublicationAuthor.new() pa.publication = @publication pa.first_name = author.first_name pa.last_name = author.last_name pa.save end end respond_to do |format| format.html { redirect_to(edit_publication_url(@publication)) } format.xml { head :ok } end end private def fetch_publication begin publication = Publication.find(params[:id]) if publication.can_perform? translate_action(action_name) @publication = publication else respond_to do |format| flash[:error] = "You are not authorized to perform this action" format.html { redirect_to publications_path } end return false end rescue ActiveRecord::RecordNotFound respond_to do |format| flash[:error] = "Couldn't find the publication" format.html { redirect_to publications_path } end return false end end def get_data(publication, pubmed_id, doi=nil) if !pubmed_id.nil? query = PubmedQuery.new("sysmo-seek",Seek::Config.pubmed_api_email) result = query.fetch(pubmed_id) unless result.nil? publication.extract_pubmed_metadata(result) return result else raise "Error - No publication could be found with that PubMed ID" end elsif !doi.nil? query = DoiQuery.new(Seek::Config.crossref_api_email) result = query.fetch(doi) unless result.nil? publication.extract_doi_metadata(result) return result else raise "Error - No publication could be found with that DOI" end end end end removed current_user from merge of can_edit? checks when associating publications and assays class PublicationsController < ApplicationController include IndexPager include DotGenerator include Seek::TaggingCommon require 'pubmed_query_tool' #before_filter :login_required before_filter :find_assets, :only => [ :index ] before_filter :fetch_publication, :only => [:show, :edit, :update, :destroy] before_filter :associate_authors, :only => [:edit, :update] def preview element=params[:element] @publication = Publication.find_by_id(params[:id]) render :update do |page| if @publication page.replace_html element,:partial=>"publications/resource_preview",:locals=>{:resource=>@publication} else page.replace_html element,:text=>"Nothing is selected to preview." end end end # GET /publications/1 # GET /publications/1.xml def show respond_to do |format| format.html # show.html.erb format.xml format.svg { render :text=>to_svg(@publication,params[:deep]=='false',@publication)} format.dot { render :text=>to_dot(@publication,params[:deep]=='false',@publication)} format.png { render :text=>to_png(@publication,params[:deep]=='false',@publication)} end end # GET /publications/new # GET /publications/new.xml def new respond_to do |format| format.html # new.html.erb format.xml end end # GET /publications/1/edit def edit end # POST /publications # POST /publications.xml def create @publication = Publication.new(params[:publication]) @publication.pubmed_id=nil if @publication.pubmed_id.blank? @publication.doi=nil if @publication.doi.blank? result = get_data(@publication, @publication.pubmed_id, @publication.doi) assay_ids = params[:assay_ids] || [] @publication.contributor = current_user respond_to do |format| if @publication.save result.authors.each do |author| pa = PublicationAuthor.new() pa.publication = @publication pa.first_name = author.first_name pa.last_name = author.last_name pa.save end Assay.find(assay_ids).each do |assay| Relationship.create_or_update_attributions(assay,{"Publication", @publication.id}.to_json, Relationship::RELATED_TO_PUBLICATION) if assay.can_edit? end #Make a policy policy = Policy.create(:name => "publication_policy", :sharing_scope => Policy::EVERYONE, :access_type => Policy::VISIBLE, :use_custom_sharing => true) @publication.policy = policy @publication.save #add managers (authors + contributor) @publication.creators.each do |author| policy.permissions << Permission.create(:contributor => author, :policy => policy, :access_type => Policy::MANAGING) end #Add contributor @publication.policy.permissions << Permission.create(:contributor => @publication.contributor.person, :policy => policy, :access_type => Policy::MANAGING) flash[:notice] = 'Publication was successfully created.' format.html { redirect_to(edit_publication_url(@publication)) } format.xml { render :xml => @publication, :status => :created, :location => @publication } else format.html { render :action => "new" } format.xml { render :xml => @publication.errors, :status => :unprocessable_entity } end end end # PUT /publications/1 # PUT /publications/1.xml def update valid = true to_add = [] to_remove = [] params[:author].keys.sort.each do |author_id| author_assoc = params[:author][author_id] unless author_assoc.blank? to_remove << PublicationAuthor.find_by_id(author_id) p = Person.find(author_assoc) if @publication.creators.include?(p) @publication.errors.add_to_base("Multiple authors cannot be associated with the same SEEK person.") valid = false else to_add << p end end end #Check for duplicate authors if valid && (to_add.uniq.size != to_add.size) @publication.errors.add_to_base("Multiple authors cannot be associated with the same SEEK person.") valid = false end update_tags @publication assay_ids = params[:assay_ids] || [] respond_to do |format| publication_params = params[:publication]||{} publication_params[:event_ids] = params[:event_ids]||[] if valid && @publication.update_attributes(publication_params) to_add.each {|a| @publication.creators << a} to_remove.each {|a| a.destroy} # Update relationship Assay.find(assay_ids).each do |assay| if assay.can_edit? && Relationship.find_all_by_object_id(@publication.id, :conditions => "subject_id = #{assay.id}").empty? Relationship.create_or_update_attributions(assay,{"Publication", @publication.id}.to_json, Relationship::RELATED_TO_PUBLICATION) end end #Destroy Assay relationship that aren't needed associate_relationships = Relationship.find(:all,:conditions=>["object_id = ? and subject_type = ?",@publication.id,"Assay"]) logger.info associate_relationships associate_relationships.each do |associate_relationship| if associate_relationship.subject.can_edit? && !assay_ids.include?(associate_relationship.subject_id.to_s) Relationship.destroy(associate_relationship.id) end end #Create policy if not present (should be) if @publication.policy.nil? @publication.policy = Policy.create(:name => "publication_policy", :sharing_scope => Policy::EVERYONE, :access_type => Policy::VISIBLE, :use_custom_sharing => true) @publication.save end #Update policy so current authors have manage permissions @publication.creators.each do |author| @publication.policy.permissions.clear @publication.policy.permissions << Permission.create(:contributor => author, :policy => @publication.policy, :access_type => Policy::MANAGING) end #Add contributor @publication.policy.permissions << Permission.create(:contributor => @publication.contributor.person, :policy => @publication.policy, :access_type => Policy::MANAGING) flash[:notice] = 'Publication was successfully updated.' format.html { redirect_to(@publication) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @publication.errors, :status => :unprocessable_entity } end end end # DELETE /publications/1 # DELETE /publications/1.xml def destroy @publication.destroy respond_to do |format| format.html { redirect_to(publications_path) } format.xml { head :ok } end end def fetch_preview begin @publication = Publication.new(params[:publication]) @publication.project_id = params[:project_id] key = params[:key] protocol = params[:protocol] pubmed_id = nil doi = nil if protocol == "pubmed" pubmed_id = key elsif protocol == "doi" doi = key if doi.start_with?("doi:") doi = doi.gsub("doi:","") end end result = get_data(@publication, pubmed_id, doi) rescue if protocol == "pubmed" if key.match(/[0-9]+/).nil? @error_text = "Please ensure the PubMed ID is entered in the correct format, e.g. <i>16845108</i>" else @error_text = "No publication could be found on PubMed with that ID" end elsif protocol == "doi" if key.match(/[0-9]+(\.)[0-9]+.*/).nil? @error_text = "Please ensure the DOI is entered in the correct format, e.g. <i>10.1093/nar/gkl320</i>" else @error_text = "No valid publication could be found with that DOI" end end respond_to do |format| format.html { render :partial => "publications/publication_error", :locals => { :publication => @publication, :error_text => @error_text}, :status => 500} end else respond_to do |format| format.html { render :partial => "publications/publication_preview", :locals => { :publication => @publication, :authors => result.authors} } end end end #Try and relate non_seek_authors to people in SEEK based on name and project def associate_authors publication = @publication project = publication.project || current_user.person.projects.first association = {} publication.non_seek_authors.each do |author| matches = [] #Get author by last name last_name_matches = Person.find_all_by_last_name(author.last_name) matches = last_name_matches #If no results, try searching by normalised name, taken from grouped_pagination.rb if matches.size < 1 text = author.last_name #handle the characters that can't be handled through normalization %w[ØO].each do |s| text.gsub!(/[#{s[0..-2]}]/, s[-1..-1]) end codepoints = text.mb_chars.normalize(:d).split(//u) ascii=codepoints.map(&:to_s).reject{|e| e.length > 1}.join last_name_matches = Person.find_all_by_last_name(ascii) matches = last_name_matches end #If more than one result, filter by project if matches.size > 1 project_matches = matches.select{|p| p.projects.include?(project)} if project_matches.size >= 1 #use this result unless it resulted in no matches matches = project_matches end end #If more than one result, filter by first initial if matches.size > 1 first_and_last_name_matches = matches.select{|p| p.first_name.at(0).upcase == author.first_name.at(0).upcase} if first_and_last_name_matches.size >= 1 #use this result unless it resulted in no matches matches = first_and_last_name_matches end end #Take the first match as the guess association[author.id] = matches.first end @author_associations = association end def disassociate_authors @publication = Publication.find(params[:id]) @publication.creators.clear #get rid of author links @publication.non_seek_authors.clear #Query pubmed article to fetch authors result = nil pubmed_id = @publication.pubmed_id doi = @publication.doi if pubmed_id query = PubmedQuery.new("seek",Seek::Config.pubmed_api_email) result = query.fetch(pubmed_id) elsif doi query = DoiQuery.new(Seek::Config.crossref_api_email) result = query.fetch(doi) end unless result.nil? result.authors.each do |author| pa = PublicationAuthor.new() pa.publication = @publication pa.first_name = author.first_name pa.last_name = author.last_name pa.save end end respond_to do |format| format.html { redirect_to(edit_publication_url(@publication)) } format.xml { head :ok } end end private def fetch_publication begin publication = Publication.find(params[:id]) if publication.can_perform? translate_action(action_name) @publication = publication else respond_to do |format| flash[:error] = "You are not authorized to perform this action" format.html { redirect_to publications_path } end return false end rescue ActiveRecord::RecordNotFound respond_to do |format| flash[:error] = "Couldn't find the publication" format.html { redirect_to publications_path } end return false end end def get_data(publication, pubmed_id, doi=nil) if !pubmed_id.nil? query = PubmedQuery.new("sysmo-seek",Seek::Config.pubmed_api_email) result = query.fetch(pubmed_id) unless result.nil? publication.extract_pubmed_metadata(result) return result else raise "Error - No publication could be found with that PubMed ID" end elsif !doi.nil? query = DoiQuery.new(Seek::Config.crossref_api_email) result = query.fetch(doi) unless result.nil? publication.extract_doi_metadata(result) return result else raise "Error - No publication could be found with that DOI" end end end end
module Radars class BlipsController < ApplicationController def new @blip = radar.new_blip(params[:blip]) render "new", locals: { quadrants: quadrants, rings: rings, blip: blip, topics: topics } end def create @blip = radar.new_blip(blip_params) if @blip.save redirect_to radar_quadrant_path(radar, quadrant: blip.quadrant) else render "new", locals: { quadrants: quadrants, rings: rings, blip: blip, topics: topics } end end def show render "show", locals: { quadrants: quadrants, rings: rings, blip: blip.decorate, topics: topics } end def edit render "edit", locals: { quadrants: quadrants, rings: rings, blip: blip, topics: topics } end def update if blip.update(blip_params) redirect_to radar, notice: "Blip updated" else render "edit", locals: { quadrants: quadrants, rings: rings, blip: blip, topics: topics } end end def destroy blip.destroy! quadrant = blip.quadrant redirect_to radar_quadrant_path(radar, quadrant) end private def blip_params params.require(:blip).permit(:topic_id, :quadrant, :ring, :notes) end def radar @radar ||= current_user.find_radar(uuid: params[:radar_id]) end def blip @blip ||= radar.find_blip(params[:id]) end def quadrants Blip::QUADRANTS.each_with_object({}) do |item, result| result[item.titleize] = item end end def rings Blip::RINGS.each_with_object({}) do |item, result| result[item.titleize] = item end end def topics current_user.topics.by_name end end end Fix fail module Radars class BlipsController < ApplicationController before_action :authenticate_user!, except: :show def new @blip = radar.new_blip(params[:blip]) render "new", locals: { quadrants: quadrants, rings: rings, blip: blip, topics: topics } end def create @blip = radar.new_blip(blip_params) if @blip.save redirect_to radar_quadrant_path(radar, quadrant: blip.quadrant) else render "new", locals: { quadrants: quadrants, rings: rings, blip: blip, topics: topics } end end def show render "show", locals: { quadrants: quadrants, rings: rings, blip: blip.decorate } # , topics: topics } end def edit render "edit", locals: { quadrants: quadrants, rings: rings, blip: blip, topics: topics } end def update if blip.update(blip_params) redirect_to radar, notice: "Blip updated" else render "edit", locals: { quadrants: quadrants, rings: rings, blip: blip, topics: topics } end end def destroy blip.destroy! quadrant = blip.quadrant redirect_to radar_quadrant_path(radar, quadrant) end private def blip_params params.require(:blip).permit(:topic_id, :quadrant, :ring, :notes) end def radar if current_user @radar ||= current_user.find_radar(uuid: params[:radar_id]) else @radar ||= Radar.find_by(uuid: params[:radar_id]) end end def blip @blip ||= radar.find_blip(params[:id]) end def quadrants Blip::QUADRANTS.each_with_object({}) do |item, result| result[item.titleize] = item end end def rings Blip::RINGS.each_with_object({}) do |item, result| result[item.titleize] = item end end def topics current_user.topics.by_name end end end
class ReceiveTextController < ApplicationController skip_before_filter :verify_authenticity_token skip_before_filter :authenticate_user! def index message_body = params["Body"] from_number = params["From"] @twilio_message = TwilioMessage.new @twilio_message.message_sid = params[:MessageSid] @twilio_message.date_created = params[:DateCreated] @twilio_message.date_updated = params[:DateUpdated] @twilio_message.date_sent = params[:DateSent] @twilio_message.account_sid = params[:AccountSid] @twilio_message.from = params[:From] @twilio_message.to = params[:To] @twilio_message.body = params[:Body] @twilio_message.status = params[:SmsStatus] @twilio_message.error_code = params[:ErrorCode] @twilio_message.error_message = params[:ErrorMessage] @twilio_message.direction = params[:Direction] @twilio_message.save from_number = params[:From].sub("+1","").to_i # Removing +1 and converting to integer message = "Sorry, please try again. Text 'Hello' or 12345 to complete your signup!" if params[:Body].include? "12345" or params[:Body].downcase.include? 'hello' @twilio_message.signup_verify = "Verified" message = "Thank you for verifying your account. We will mail you your $5 VISA gift card right away." this_person = Person.find_by(phone_number: from_number) this_person.verified = "Verified by Text Message" this_person.save # Trigger add to Mailchimp list begin mailchimpSend = Gibbon.list_subscribe({:id => Logan::Application.config.cut_group_mailchimp_list_id, :email_address => this_person.email_address, :double_optin => 'false', :update_existing => 'true', :merge_vars => {:FNAME => this_person.first_name, :LNAME => this_person.last_name, :MMERGE3 => this_person.geography_id, :MMERGE4 => this_person.postal_code, :MMERGE5 => this_person.participation_type, :MMERGE6 => this_person.voted, :MMERGE7 => this_person.called_311, :MMERGE8 => this_person.primary_device_description, :MMERGE9 => this_person.secondary_device_id, :MMERGE10 => this_person.secondary_device_description, :MMERGE11 => this_person.primary_connection_id, :MMERGE12 => this_person.primary_connection_description, :MMERGE13 => this_person.primary_device_id}}) rescue Gibbon::MailChimpError => e Rails.logger.fatal("[ReceiveTextController#index] fatal error sending #{this_person.id} to Mailchimp: #{e.message}") end elsif params["Body"] == "Remove me" @twilio_message.signup_verify = "Cancelled" this_person = Person.find_by(phone_number: from_number) this_person.verified = "Removal Request by Text Message" this_person.save message = "We are sorry for bothering you. You have been removed from the CUTGroup." end @twilio_message.save twiml = Twilio::TwiML::Response.new do |r| r.Message message end respond_to do |format| format.xml {render xml: twiml.text} end end def smssignup wufoo = WuParty.new(ENV['WUFOO_ACCOUNT'],ENV['WUFOO_API']) wufoo.forms session["counter"] ||= 0 session["fieldanswers"] ||= Hash.new session["fieldquestions"] ||= Hash.new session["phone_number"] ||= params[:From].sub("+1","").to_i # Removing +1 and converting to integer session["contact"] ||= "EMAIL" session["errorcount"] ||= 0 message_body = params["Body"] @incoming = TwilioMessage.new @incoming.message_sid = params[:MessageSid] @incoming.date_created = params[:DateCreated] @incoming.date_updated = params[:DateUpdated] @incoming.date_sent = params[:DateSent] @incoming.account_sid = params[:AccountSid] @incoming.from = params[:From] @incoming.to = params[:To] @incoming.body = params[:Body] @incoming.status = params[:SmsStatus] @incoming.error_code = params[:ErrorCode] @incoming.error_message = params[:ErrorMessage] @incoming.direction = params[:Direction] @incoming.save form = wufoo.form(ENV['WUFOO_SIGNUP_FORM']) fields = form.flattened_fields #fieldids = Array.new @twiliowufoo = TwilioWufoo.where("twilio_keyword = ? AND status = ?", params[:Body], true).first if message_body == "99999" message = "You said 99999" session["counter"] = -1 session["fieldanswers"] = Hash.new session["fieldquestions"] = Hash.new session["contact"] = "EMAIL" session["errorcount"] = 0 elsif @twiliowufoo form = wufoo.form(@twiliowufoo.wufoo_formid) fields = form.flattened_fields if session["counter"] == 0 message = "#{fields[session["counter"]]['Title']}" elsif session["counter"] < (fields.length - 1) session["fieldanswers"][fields[session["counter"]-1]['ID']] = params["Body"] message = "#{fields[session["counter"]]['Title']}" # If the question asked for an email check if response contains a @ and . or a skip if fields[session["counter"] - 1]['Title'].include? "email address" if !( params["Body"] =~ /.+@.+\..+/) and !(params["Body"].upcase.include? "SKIP") message = "Oops, it looks like that isn't a valid email address. Please try again or text 'SKIP' to skip adding an email." session["counter"] -= 1 end # If the question is a multiple choice using single letter response, check for single letter elsif fields[session["counter"] - 1]['Title'].include? "A)" #if !( params["Body"].strip.upcase == "A") if !( params["Body"].strip.upcase =~ /A|B|C|D/) if session["errorcount"] == 0 message = "Please type only the letter of your answer. Thank you!" session["counter"] -= 1 session["errorcount"] += 1 elsif session["errorcount"] == 1 message = "Please type only the letter of your answer or type SKIP. Thank you!" session["counter"] -= 1 session["errorcount"] += 1 else session["errorcount"] = 0 end else session["errorcount"] = 0 end elsif fields[session["counter"] - 1]['Title'].include? "receive notifications" if params["Body"].upcase.strip == "TEXT" session["contact"] = "TEXT" end end elsif session["counter"] == (fields.length - 1) session["fieldanswers"][fields[session["counter"]-1]['ID']] = params["Body"] session["fieldanswers"][fields[session["counter"]]['ID']] = from_number result = form.submit(session["fieldanswers"]) message = "You are now signed up for CUTGroup! Your $5 gift card will be in the mail. When new tests come up, you'll receive a text from 773-747-6239 with more details." if session["contact"] == "EMAIL" message = "You are now signed up for CUTGroup! Your $5 gift card will be in the mail. When new tests come up, you'll receive an email from smarziano@cct.org with details." end else message = "You have already completed the sign up process." end end @incoming.save twiml = Twilio::TwiML::Response.new do |r| r.Message message end respond_to do |format| format.xml {render xml: twiml.text} end session["counter"] += 1 end end sms debug class ReceiveTextController < ApplicationController skip_before_filter :verify_authenticity_token skip_before_filter :authenticate_user! def index message_body = params["Body"] from_number = params["From"] @twilio_message = TwilioMessage.new @twilio_message.message_sid = params[:MessageSid] @twilio_message.date_created = params[:DateCreated] @twilio_message.date_updated = params[:DateUpdated] @twilio_message.date_sent = params[:DateSent] @twilio_message.account_sid = params[:AccountSid] @twilio_message.from = params[:From] @twilio_message.to = params[:To] @twilio_message.body = params[:Body] @twilio_message.status = params[:SmsStatus] @twilio_message.error_code = params[:ErrorCode] @twilio_message.error_message = params[:ErrorMessage] @twilio_message.direction = params[:Direction] @twilio_message.save from_number = params[:From].sub("+1","").to_i # Removing +1 and converting to integer message = "Sorry, please try again. Text 'Hello' or 12345 to complete your signup!" if params[:Body].include? "12345" or params[:Body].downcase.include? 'hello' @twilio_message.signup_verify = "Verified" message = "Thank you for verifying your account. We will mail you your $5 VISA gift card right away." this_person = Person.find_by(phone_number: from_number) this_person.verified = "Verified by Text Message" this_person.save # Trigger add to Mailchimp list begin mailchimpSend = Gibbon.list_subscribe({:id => Logan::Application.config.cut_group_mailchimp_list_id, :email_address => this_person.email_address, :double_optin => 'false', :update_existing => 'true', :merge_vars => {:FNAME => this_person.first_name, :LNAME => this_person.last_name, :MMERGE3 => this_person.geography_id, :MMERGE4 => this_person.postal_code, :MMERGE5 => this_person.participation_type, :MMERGE6 => this_person.voted, :MMERGE7 => this_person.called_311, :MMERGE8 => this_person.primary_device_description, :MMERGE9 => this_person.secondary_device_id, :MMERGE10 => this_person.secondary_device_description, :MMERGE11 => this_person.primary_connection_id, :MMERGE12 => this_person.primary_connection_description, :MMERGE13 => this_person.primary_device_id}}) rescue Gibbon::MailChimpError => e Rails.logger.fatal("[ReceiveTextController#index] fatal error sending #{this_person.id} to Mailchimp: #{e.message}") end elsif params["Body"] == "Remove me" @twilio_message.signup_verify = "Cancelled" this_person = Person.find_by(phone_number: from_number) this_person.verified = "Removal Request by Text Message" this_person.save message = "We are sorry for bothering you. You have been removed from the CUTGroup." end @twilio_message.save twiml = Twilio::TwiML::Response.new do |r| r.Message message end respond_to do |format| format.xml {render xml: twiml.text} end end def smssignup wufoo = WuParty.new(ENV['WUFOO_ACCOUNT'],ENV['WUFOO_API']) wufoo.forms session["counter"] ||= 0 session["fieldanswers"] ||= Hash.new session["fieldquestions"] ||= Hash.new session["phone_number"] ||= params[:From].sub("+1","").to_i # Removing +1 and converting to integer session["contact"] ||= "EMAIL" session["errorcount"] ||= 0 session["form"] ||= '' session["fields"] ||= '' message_body = params["Body"].strip @incoming = TwilioMessage.new @incoming.message_sid = params[:MessageSid] @incoming.date_created = params[:DateCreated] @incoming.date_updated = params[:DateUpdated] @incoming.date_sent = params[:DateSent] @incoming.account_sid = params[:AccountSid] @incoming.from = params[:From] @incoming.to = params[:To] @incoming.body = params[:Body] @incoming.status = params[:SmsStatus] @incoming.error_code = params[:ErrorCode] @incoming.error_message = params[:ErrorMessage] @incoming.direction = params[:Direction] @incoming.save @twiliowufoo = TwilioWufoo.where("twilio_keyword = ? AND status = ?", params[:Body].strip.upcase, true).first message = "Initial message" if message_body == "99999" message = "You said 99999" session["counter"] = -1 session["fieldanswers"] = Hash.new session["fieldquestions"] = Hash.new session["contact"] = "EMAIL" session["errorcount"] = 0 session["form"] = '' session["fields"] = '' elsif @twiliowufoo and session["counter"] == 0 session["form"] = wufoo.form(@twiliowufoo.wufoo_formid) session["fields"] = fields = session["form"].flattened_fields message = "#{session["fields"][session["counter"]]['Title']}" # elsif session["counter"] < (session["fields"].length - 1) # session["fieldanswers"][session["fields"][session["counter"]-1]['ID']] = params["Body"].strip # #message = "#{session["fields"][session["counter"]]['Title']}" # message = "one" # If the question asked for an email check if response contains a @ and . or a skip # if session["fields"][session["counter"] - 1]['Title'].include? "email address" # if !( params["Body"] =~ /.+@.+\..+/) and !(params["Body"].upcase.include? "SKIP") # message = "Oops, it looks like that isn't a valid email address. Please try again or text 'SKIP' to skip adding an email." # session["counter"] -= 1 # end # # If the question is a multiple choice using single letter response, check for single letter # elsif session["fields"][session["counter"] - 1]['Title'].include? "A)" # #if !( params["Body"].strip.upcase == "A") # if !( params["Body"].strip.upcase =~ /A|B|C|D/) # if session["errorcount"] == 0 # message = "Please type only the letter of your answer. Thank you!" # session["counter"] -= 1 # session["errorcount"] += 1 # elsif session["errorcount"] == 1 # message = "Please type only the letter of your answer or type SKIP. Thank you!" # session["counter"] -= 1 # session["errorcount"] += 1 # else # session["errorcount"] = 0 # end # else # session["errorcount"] = 0 # end # elsif session["fields"][session["counter"] - 1]['Title'].include? "receive notifications" # if params["Body"].upcase.strip == "TEXT" # session["contact"] = "TEXT" # end # end # elsif session["counter"] == (session["fields"].length - 1) # session["fieldanswers"][session["fields"][session["counter"]-1]['ID']] = params["Body"] # session["fieldanswers"][session["fields"][session["counter"]]['ID']] = session["phone_number"] # result = session["form"].submit(session["fieldanswers"]) # message = "You are now signed up for CUTGroup! Your $5 gift card will be in the mail. When new tests come up, you'll receive a text from 773-747-6239 with more details." # if session["contact"] == "EMAIL" # message = "You are now signed up for CUTGroup! Your $5 gift card will be in the mail. When new tests come up, you'll receive an email from smarziano@cct.org with details." # end # else # message = "You have already completed the sign up process." # end else #message = session["counter"] message = "2" #message = session["fields"] session["counter"] = -1 session["fieldanswers"] = Hash.new session["fieldquestions"] = Hash.new session["contact"] = "EMAIL" session["errorcount"] = 0 end @incoming.save twiml = Twilio::TwiML::Response.new do |r| r.Message message end respond_to do |format| format.xml {render xml: twiml.text} end session["counter"] += 1 end end
class ReservationsController < ApplicationController load_and_authorize_resource layout 'application_with_sidebar' before_filter :require_login, only: [:index, :show] before_filter :set_reservation, only: [:show,:edit,:update,:destroy,:checkout_email,:checkin_email,:renew] def set_user @user = User.find(params[:user_id]) end def set_reservation @reservation = Reservation.find(params[:id]) end def index #define our source of reservations depending on user status @reservations_source = (can? :manage, Reservation) ? Reservation : current_user.reservations default_filter = (can? :manage, Reservation) ? :upcoming : :reserved filters = [:reserved, :checked_out, :overdue, :missed, :returned, :upcoming, :requested, :approved_requests, :denied_requests] #if the filter is defined in the params, store those reservations filters.each do |filter| if params[filter] @reservations_set = [@reservations_source.send(filter)].delete_if{|a| a.empty?} end end @default = false #if no filter is defined if @reservations_set.nil? @default = true @reservations_set = [@reservations_source.send(default_filter)].delete_if{|a| a.empty?} end end def show end def new if cart.items.empty? flash[:error] = "You need to add items to your cart before making a reservation." redirect_to catalog_path else # error handling @errors = cart.validate_all unless @errors.empty? if can? :override, :reservation_errors flash[:error] = 'Are you sure you want to continue? Please review the errors below.' else flash[:error] = 'Please review the errors below. If uncorrected, your reservation will be filed as a request, and subject to administrator approval.' end end # this is used to initialize each reservation later @reservation = Reservation.new(start_date: cart.start_date, due_date: cart.due_date, reserver_id: cart.reserver_id) end end def create successful_reservations = [] #using http://stackoverflow.com/questions/7233859/ruby-on-rails-updating-multiple-models-from-the-one-controller as inspiration Reservation.transaction do begin cart_reservations = cart.prepare_all @errors = cart.validate_all if @errors.empty? # If the reservation is a finalized reservation, save it as auto-approved ... params[:reservation][:approval_status] = "auto" success_message = "Reservation created successfully." # errors are caught in the rollback elsif can? :override, :reservation_errors # display a different flash notice for privileged persons params[:reservation][:approval_status] = "auto" success_message = "Reservation created successfully, despite the aforementioned errors." else # ... otherwise mark it as a Reservation Request. params[:reservation][:approval_status] = "requested" success_message = "This request has been successfully submitted, and is now subject to approval by an administrator." end cart_reservations.each do |cart_res| @reservation = Reservation.new(params[:reservation]) @reservation.equipment_model = cart_res.equipment_model @reservation.save! successful_reservations << @reservation end session[:cart] = Cart.new # emails are probably failing---this code was already commented out 2014.06.19, and we don't know why. #if AppConfig.first.reservation_confirmation_email_active? # #UserMailer.reservation_confirmation(complete_reservation).deliver #end if can? :manage, Reservation if params[:reservation][:start_date].to_date === Date::today.to_date flash[:notice] = "Are you simultaneously checking out equipment for someone? Note that\ only the reservation has been made. Don't forget to continue to checkout." end redirect_to manage_reservations_for_user_path(params[:reservation][:reserver_id]) and return else flash[:notice] = success_message redirect_to catalog_path and return end rescue ActiveRecord::RecordNotSaved, ActiveRecord::RecordInvalid => e redirect_to catalog_path, flash: {error: "Oops, something went wrong with making your reservation.<br/> #{e.message}".html_safe} raise ActiveRecord::Rollback end end end def edit @option_array = @reservation.equipment_model.equipment_objects.collect { |e| [e.name, e.id] } end def update # for editing reservations; not for checkout or check-in #make copy of params res = params[:reservation].clone # adjust dates to match intended input of Month / Day / Year res[:start_date] = Date.strptime(params[:reservation][:start_date],'%m/%d/%Y') res[:due_date] = Date.strptime(params[:reservation][:due_date],'%m/%d/%Y') message = "Successfully edited reservation." # update attributes if params[:equipment_object] && params[:equipment_object] != '' object = EquipmentObject.find(params[:equipment_object]) unless object.available? r = object.current_reservation r.equipment_object_id = @reservation.equipment_object_id r.save message << " Note equipment item #{r.equipment_object.name} is now assigned to \ #{ActionController::Base.helpers.link_to('reservation #' + r.id.to_s, reservation_path(r))} \ (#{r.reserver.render_name})" end res[:equipment_object_id] = params[:equipment_object] end # save changes to database Reservation.update(@reservation, res) # flash success and exit flash[:notice] = message redirect_to @reservation end def checkout error_msgs = "" reservations_to_be_checked_out = [] set_user if !@user.terms_of_service_accepted && !params[:terms_of_service_accepted] flash[:error] = "You must confirm that the user accepts the Terms of Service." redirect_to :back and return elsif !@user.terms_of_service_accepted && params[:terms_of_service_accepted] @user.terms_of_service_accepted = true @user.save end # throw all the reservations that are being checked out into an array params[:reservations].each do |reservation_id, reservation_hash| if reservation_hash[:equipment_object_id] != ('' or nil) then # update attributes for all equipment that is checked off r = Reservation.find(reservation_id) r.checkout_handler = current_user r.checked_out = Time.now r.equipment_object = EquipmentObject.find(reservation_hash[:equipment_object_id]) # deal with checkout procedures procedures_not_done = "" # initialize r.equipment_model.checkout_procedures.each do |check| if reservation_hash[:checkout_procedures] == nil # if none were checked, note that procedures_not_done += "* " + check.step + "\n" elsif !reservation_hash[:checkout_procedures].keys.include?(check.id.to_s) # if you didn't check it of, add to string procedures_not_done += "* " + check.step + "\n" end end # add procedures_not_done to r.notes so admin gets the errors # if no notes and some procedures not done if procedures_not_done.present? modified_notes = reservation_hash[:notes].present? ? reservation_hash[:notes] + "\n\n" : "" r.notes = modified_notes + "The following checkout procedures were not performed:\n" + procedures_not_done r.notes_unsent = true elsif reservation_hash[:notes].present? # if all procedures were done r.notes = reservation_hash[:notes] r.notes_unsent = true end r.notes.strip! if r.notes? # put the data into the container we defined at the beginning of this action reservations_to_be_checked_out << r end end # done with throwing things into the array #All-encompassing checks, only need to be done once if reservations_to_be_checked_out.first.nil? # Prevents the nil error from not selecting any reservations flash[:error] = "No reservation selected." redirect_to :back and return # move method to user model TODO elsif reservations_to_be_checked_out.first.reserver.overdue_reservations? error_msgs += "User has overdue equipment." end # make sure we're not checking out the same object in more than one reservation if !reservations_to_be_checked_out.first.checkout_object_uniqueness(reservations_to_be_checked_out) # if objects not unique, flash error flash[:error] = "The same equipment item cannot be simultaneously checked out in multiple reservations." redirect_to :back and return end # act on the errors if !error_msgs.empty? # If any requirements are not met... if can? :override, :checkout_errors # Admins can ignore them error_msgs = " Admin Override: Equipment has been successfully checked out even though " + error_msgs else # everyone else is redirected flash[:error] = error_msgs redirect_to :back and return end end # transaction this process ^downarrow # save reservations reservations_to_be_checked_out.each do |reservation| # updates to reservations are saved reservation.save! # save! end # prep for receipt page and exit @check_in_set = [] @check_out_set = reservations_to_be_checked_out render 'receipt' and return rescue Exception => e redirect_to manage_reservations_for_user_path(reservations_to_be_checked_out.first.reserver), flash: {error: "Oops, something went wrong checking out your reservation.<br/> #{e.message}".html_safe} end def checkin reservations_to_be_checked_in = [] params[:reservations].each do |reservation_id, reservation_hash| if reservation_hash[:checkin?] == "1" then # update attributes for all equipment that is checked off r = Reservation.find(reservation_id) if r.checked_in flash[:error] = "One or more items you were trying to checkout has already been checked in." redirect_to :back return end r.checkin_handler = current_user r.checked_in = Time.now # deal with checkout procedures procedures_not_done = "" # initialize r.equipment_model.checkin_procedures.each do |check| if reservation_hash[:checkin_procedures] == NIL # if none were checked, note that procedures_not_done += "* " + check.step + "\n" elsif !reservation_hash[:checkin_procedures].keys.include?(check.id.to_s) # if you didn"t check it of, add to string procedures_not_done += "* " + check.step + "\n" end end # add procedures_not_done to r.notes so admin gets the errors previous_notes = r.notes.present? ? "Checkout Notes:\n" + r.notes + "\n\n" : "" new_notes = reservation_hash[:notes].present? ? "Checkin Notes:\n" + reservation_hash[:notes] : "" if procedures_not_done.present? r.notes = previous_notes + new_notes + "\n\nThe following check-in procedures were not performed:\n" + procedures_not_done r.notes_unsent = true elsif new_notes.present? # if all procedures were done r.notes = previous_notes + new_notes # add blankline because there may well have been previous notes r.notes_unsent = true else r.notes = previous_notes end r.notes.strip! if r.notes? # if equipment was overdue, send an email confirmation if r.status == 'returned overdue' AdminMailer.overdue_checked_in_fine_admin(r).deliver UserMailer.overdue_checked_in_fine(r).deliver end # put the data into the container we defined at the beginning of this action reservations_to_be_checked_in << r end end # flash errors if reservations_to_be_checked_in.empty? flash[:error] = "No reservation selected!" redirect_to :back and return end # save the reservations reservations_to_be_checked_in.each do |reservation| reservation.save! end # prep for receipt page and exit @user = reservations_to_be_checked_in.first.reserver @check_in_set = reservations_to_be_checked_in @check_out_set = [] render 'receipt' and return rescue Exception => e redirect_to :back, flash: {error: "Oops, something went wrong checking in your reservation.<br/> #{e.message}".html_safe} end def destroy set_reservation @reservation.destroy flash[:notice] = "Successfully destroyed reservation." redirect_to reservations_url end def upcoming @reservations_set = [Reservation.upcoming].delete_if{|a| a.empty?} end def manage # initializer set_user @check_out_set = @user.due_for_checkout @check_in_set = @user.due_for_checkin render :manage, layout: 'application' end def current set_user @user_overdue_reservations_set = [Reservation.overdue.for_reserver(@user)].delete_if{|a| a.empty?} @user_checked_out_today_reservations_set = [Reservation.checked_out_today.for_reserver(@user)].delete_if{|a| a.empty?} @user_checked_out_previous_reservations_set = [Reservation.checked_out_previous.for_reserver(@user)].delete_if{|a| a.empty?} @user_reserved_reservations_set = [Reservation.reserved.for_reserver(@user)].delete_if{|a| a.empty?} render 'current_reservations' end # two paths to create receipt emails for checking in and checking out items. def checkout_email if UserMailer.checkout_receipt(@reservation).deliver redirect_to :back flash[:notice] = "Successfully delivered receipt email." else redirect_to @reservation flash[:error] = "Unable to deliver receipt email. Please contact administrator for more support. " end end def checkin_email if UserMailer.checkin_receipt(@reservation).deliver redirect_to :back flash[:notice] = "Successfully delivered receipt email." else redirect_to @reservation flash[:error] = "Unable to deliver receipt email. Please contact administrator for more support. " end end def renew @reservation.due_date += @reservation.max_renewal_length_available.days if @reservation.times_renewed == NIL # this check can be removed? just run the else now? @reservation.times_renewed = 1 else @reservation.times_renewed += 1 end if !@reservation.save redirect_to @reservation flash[:error] = "Unable to update reservation dates. Please contact us for support." end respond_to do |format| format.html{redirect_to root_path} format.js{render action: "renew_box"} end end def review set_reservation @all_current_requests_by_user = @reservation.reserver.reservations.requested.delete_if{|res| res.id == @reservation.id} @errors = @reservation.validate end def approve_request set_reservation @reservation.approval_status = "approved" if @reservation.save flash[:notice] = "Request successfully approved" redirect_to reservations_path(:requested => true) else flash[:error] = "Oops! Something went wrong. Unable to approve reservation." redirect_to @reservation end end def deny_request set_reservation @reservation.approval_status = "denied" if @reservation.save flash[:notice] = "Request successfully denied" redirect_to reservations_path(:requested => true) else flash[:error] = "Oops! Something went wrong. Unable to deny reservation. We're not sure what that's all about." redirect_to @reservation end end end Added set_user to before_filter class ReservationsController < ApplicationController load_and_authorize_resource layout 'application_with_sidebar' before_filter :require_login, only: [:index, :show] before_filter :set_reservation, only: [:show, :edit, :update, :destroy, :checkout_email, :checkin_email, :renew] before_filter :set_user, only: [:manage, :current, :checkout] def set_user @user = User.find(params[:user_id]) end def set_reservation @reservation = Reservation.find(params[:id]) end def index #define our source of reservations depending on user status @reservations_source = (can? :manage, Reservation) ? Reservation : current_user.reservations default_filter = (can? :manage, Reservation) ? :upcoming : :reserved filters = [:reserved, :checked_out, :overdue, :missed, :returned, :upcoming, :requested, :approved_requests, :denied_requests] #if the filter is defined in the params, store those reservations filters.each do |filter| if params[filter] @reservations_set = [@reservations_source.send(filter)].delete_if{|a| a.empty?} end end @default = false #if no filter is defined if @reservations_set.nil? @default = true @reservations_set = [@reservations_source.send(default_filter)].delete_if{|a| a.empty?} end end def show end def new if cart.items.empty? flash[:error] = "You need to add items to your cart before making a reservation." redirect_to catalog_path else # error handling @errors = cart.validate_all unless @errors.empty? if can? :override, :reservation_errors flash[:error] = 'Are you sure you want to continue? Please review the errors below.' else flash[:error] = 'Please review the errors below. If uncorrected, your reservation will be filed as a request, and subject to administrator approval.' end end # this is used to initialize each reservation later @reservation = Reservation.new(start_date: cart.start_date, due_date: cart.due_date, reserver_id: cart.reserver_id) end end def create successful_reservations = [] #using http://stackoverflow.com/questions/7233859/ruby-on-rails-updating-multiple-models-from-the-one-controller as inspiration Reservation.transaction do begin cart_reservations = cart.prepare_all @errors = cart.validate_all if @errors.empty? # If the reservation is a finalized reservation, save it as auto-approved ... params[:reservation][:approval_status] = "auto" success_message = "Reservation created successfully." # errors are caught in the rollback elsif can? :override, :reservation_errors # display a different flash notice for privileged persons params[:reservation][:approval_status] = "auto" success_message = "Reservation created successfully, despite the aforementioned errors." else # ... otherwise mark it as a Reservation Request. params[:reservation][:approval_status] = "requested" success_message = "This request has been successfully submitted, and is now subject to approval by an administrator." end cart_reservations.each do |cart_res| @reservation = Reservation.new(params[:reservation]) @reservation.equipment_model = cart_res.equipment_model @reservation.save! successful_reservations << @reservation end session[:cart] = Cart.new # emails are probably failing---this code was already commented out 2014.06.19, and we don't know why. #if AppConfig.first.reservation_confirmation_email_active? # #UserMailer.reservation_confirmation(complete_reservation).deliver #end if can? :manage, Reservation if params[:reservation][:start_date].to_date === Date::today.to_date flash[:notice] = "Are you simultaneously checking out equipment for someone? Note that\ only the reservation has been made. Don't forget to continue to checkout." end redirect_to manage_reservations_for_user_path(params[:reservation][:reserver_id]) and return else flash[:notice] = success_message redirect_to catalog_path and return end rescue ActiveRecord::RecordNotSaved, ActiveRecord::RecordInvalid => e redirect_to catalog_path, flash: {error: "Oops, something went wrong with making your reservation.<br/> #{e.message}".html_safe} raise ActiveRecord::Rollback end end end def edit @option_array = @reservation.equipment_model.equipment_objects.collect { |e| [e.name, e.id] } end def update # for editing reservations; not for checkout or check-in #make copy of params res = params[:reservation].clone # adjust dates to match intended input of Month / Day / Year res[:start_date] = Date.strptime(params[:reservation][:start_date],'%m/%d/%Y') res[:due_date] = Date.strptime(params[:reservation][:due_date],'%m/%d/%Y') message = "Successfully edited reservation." # update attributes if params[:equipment_object] && params[:equipment_object] != '' object = EquipmentObject.find(params[:equipment_object]) unless object.available? r = object.current_reservation r.equipment_object_id = @reservation.equipment_object_id r.save message << " Note equipment item #{r.equipment_object.name} is now assigned to \ #{ActionController::Base.helpers.link_to('reservation #' + r.id.to_s, reservation_path(r))} \ (#{r.reserver.render_name})" end res[:equipment_object_id] = params[:equipment_object] end # save changes to database Reservation.update(@reservation, res) # flash success and exit flash[:notice] = message redirect_to @reservation end def checkout error_msgs = "" reservations_to_be_checked_out = [] if !@user.terms_of_service_accepted && !params[:terms_of_service_accepted] flash[:error] = "You must confirm that the user accepts the Terms of Service." redirect_to :back and return elsif !@user.terms_of_service_accepted && params[:terms_of_service_accepted] @user.terms_of_service_accepted = true @user.save end # throw all the reservations that are being checked out into an array params[:reservations].each do |reservation_id, reservation_hash| if reservation_hash[:equipment_object_id] != ('' or nil) then # update attributes for all equipment that is checked off r = Reservation.find(reservation_id) r.checkout_handler = current_user r.checked_out = Time.now r.equipment_object = EquipmentObject.find(reservation_hash[:equipment_object_id]) # deal with checkout procedures procedures_not_done = "" # initialize r.equipment_model.checkout_procedures.each do |check| if reservation_hash[:checkout_procedures] == nil # if none were checked, note that procedures_not_done += "* " + check.step + "\n" elsif !reservation_hash[:checkout_procedures].keys.include?(check.id.to_s) # if you didn't check it of, add to string procedures_not_done += "* " + check.step + "\n" end end # add procedures_not_done to r.notes so admin gets the errors # if no notes and some procedures not done if procedures_not_done.present? modified_notes = reservation_hash[:notes].present? ? reservation_hash[:notes] + "\n\n" : "" r.notes = modified_notes + "The following checkout procedures were not performed:\n" + procedures_not_done r.notes_unsent = true elsif reservation_hash[:notes].present? # if all procedures were done r.notes = reservation_hash[:notes] r.notes_unsent = true end r.notes.strip! if r.notes? # put the data into the container we defined at the beginning of this action reservations_to_be_checked_out << r end end # done with throwing things into the array #All-encompassing checks, only need to be done once if reservations_to_be_checked_out.first.nil? # Prevents the nil error from not selecting any reservations flash[:error] = "No reservation selected." redirect_to :back and return # move method to user model TODO elsif reservations_to_be_checked_out.first.reserver.overdue_reservations? error_msgs += "User has overdue equipment." end # make sure we're not checking out the same object in more than one reservation if !reservations_to_be_checked_out.first.checkout_object_uniqueness(reservations_to_be_checked_out) # if objects not unique, flash error flash[:error] = "The same equipment item cannot be simultaneously checked out in multiple reservations." redirect_to :back and return end # act on the errors if !error_msgs.empty? # If any requirements are not met... if can? :override, :checkout_errors # Admins can ignore them error_msgs = " Admin Override: Equipment has been successfully checked out even though " + error_msgs else # everyone else is redirected flash[:error] = error_msgs redirect_to :back and return end end # transaction this process ^downarrow # save reservations reservations_to_be_checked_out.each do |reservation| # updates to reservations are saved reservation.save! # save! end # prep for receipt page and exit @check_in_set = [] @check_out_set = reservations_to_be_checked_out render 'receipt' and return rescue Exception => e redirect_to manage_reservations_for_user_path(reservations_to_be_checked_out.first.reserver), flash: {error: "Oops, something went wrong checking out your reservation.<br/> #{e.message}".html_safe} end def checkin reservations_to_be_checked_in = [] params[:reservations].each do |reservation_id, reservation_hash| if reservation_hash[:checkin?] == "1" then # update attributes for all equipment that is checked off r = Reservation.find(reservation_id) if r.checked_in flash[:error] = "One or more items you were trying to checkout has already been checked in." redirect_to :back return end r.checkin_handler = current_user r.checked_in = Time.now # deal with checkout procedures procedures_not_done = "" # initialize r.equipment_model.checkin_procedures.each do |check| if reservation_hash[:checkin_procedures] == NIL # if none were checked, note that procedures_not_done += "* " + check.step + "\n" elsif !reservation_hash[:checkin_procedures].keys.include?(check.id.to_s) # if you didn"t check it of, add to string procedures_not_done += "* " + check.step + "\n" end end # add procedures_not_done to r.notes so admin gets the errors previous_notes = r.notes.present? ? "Checkout Notes:\n" + r.notes + "\n\n" : "" new_notes = reservation_hash[:notes].present? ? "Checkin Notes:\n" + reservation_hash[:notes] : "" if procedures_not_done.present? r.notes = previous_notes + new_notes + "\n\nThe following check-in procedures were not performed:\n" + procedures_not_done r.notes_unsent = true elsif new_notes.present? # if all procedures were done r.notes = previous_notes + new_notes # add blankline because there may well have been previous notes r.notes_unsent = true else r.notes = previous_notes end r.notes.strip! if r.notes? # if equipment was overdue, send an email confirmation if r.status == 'returned overdue' AdminMailer.overdue_checked_in_fine_admin(r).deliver UserMailer.overdue_checked_in_fine(r).deliver end # put the data into the container we defined at the beginning of this action reservations_to_be_checked_in << r end end # flash errors if reservations_to_be_checked_in.empty? flash[:error] = "No reservation selected!" redirect_to :back and return end # save the reservations reservations_to_be_checked_in.each do |reservation| reservation.save! end # prep for receipt page and exit @user = reservations_to_be_checked_in.first.reserver @check_in_set = reservations_to_be_checked_in @check_out_set = [] render 'receipt' and return rescue Exception => e redirect_to :back, flash: {error: "Oops, something went wrong checking in your reservation.<br/> #{e.message}".html_safe} end def destroy set_reservation @reservation.destroy flash[:notice] = "Successfully destroyed reservation." redirect_to reservations_url end def upcoming @reservations_set = [Reservation.upcoming].delete_if{|a| a.empty?} end def manage # initializer @check_out_set = @user.due_for_checkout @check_in_set = @user.due_for_checkin render :manage, layout: 'application' end def current @user_overdue_reservations_set = [Reservation.overdue.for_reserver(@user)].delete_if{|a| a.empty?} @user_checked_out_today_reservations_set = [Reservation.checked_out_today.for_reserver(@user)].delete_if{|a| a.empty?} @user_checked_out_previous_reservations_set = [Reservation.checked_out_previous.for_reserver(@user)].delete_if{|a| a.empty?} @user_reserved_reservations_set = [Reservation.reserved.for_reserver(@user)].delete_if{|a| a.empty?} render 'current_reservations' end # two paths to create receipt emails for checking in and checking out items. def checkout_email if UserMailer.checkout_receipt(@reservation).deliver redirect_to :back flash[:notice] = "Successfully delivered receipt email." else redirect_to @reservation flash[:error] = "Unable to deliver receipt email. Please contact administrator for more support. " end end def checkin_email if UserMailer.checkin_receipt(@reservation).deliver redirect_to :back flash[:notice] = "Successfully delivered receipt email." else redirect_to @reservation flash[:error] = "Unable to deliver receipt email. Please contact administrator for more support. " end end def renew @reservation.due_date += @reservation.max_renewal_length_available.days if @reservation.times_renewed == NIL # this check can be removed? just run the else now? @reservation.times_renewed = 1 else @reservation.times_renewed += 1 end if !@reservation.save redirect_to @reservation flash[:error] = "Unable to update reservation dates. Please contact us for support." end respond_to do |format| format.html{redirect_to root_path} format.js{render action: "renew_box"} end end def review set_reservation @all_current_requests_by_user = @reservation.reserver.reservations.requested.delete_if{|res| res.id == @reservation.id} @errors = @reservation.validate end def approve_request set_reservation @reservation.approval_status = "approved" if @reservation.save flash[:notice] = "Request successfully approved" redirect_to reservations_path(:requested => true) else flash[:error] = "Oops! Something went wrong. Unable to approve reservation." redirect_to @reservation end end def deny_request set_reservation @reservation.approval_status = "denied" if @reservation.save flash[:notice] = "Request successfully denied" redirect_to reservations_path(:requested => true) else flash[:error] = "Oops! Something went wrong. Unable to deny reservation. We're not sure what that's all about." redirect_to @reservation end end end
# frozen_string_literal: true class ReservationsController < ApplicationController before_action :require_admin, only: [:streaming] include ReservationsHelper def new if user_made_two_very_short_reservations_in_last_ten_minutes? flash[:alert] = 'You made 2 very short reservations in the last ten minutes, please wait a bit before making another one. If there was a problem with your server, let us know in the comments below' redirect_to root_path end @reservation ||= new_reservation @reservation.generate_rcon_password! if @reservation.poor_rcon_password? end def new_gameye @gameye_locations = GameyeServer.locations if user_made_two_very_short_reservations_in_last_ten_minutes? flash[:alert] = 'You made 2 very short reservations in the last ten minutes, please wait a bit before making another one. If there was a problem with your server, let us know in the comments below' redirect_to root_path end @reservation ||= new_reservation @reservation.generate_rcon_password! if @reservation.poor_rcon_password? end def create_gameye @reservation = current_user.reservations.build(reservation_params) if @reservation.valid? $lock.synchronize('save-reservation-server-gameye') do @reservation.save! end reservation_saved if @reservation.persisted? else @gameye_locations = GameyeServer.locations render :new_gameye end end def create @reservation = current_user.reservations.build(reservation_params) if @reservation.valid? $lock.synchronize("save-reservation-server-#{@reservation.server_id}") do @reservation.save! end reservation_saved if @reservation.persisted? else render :new end end def i_am_feeling_lucky @reservation = IAmFeelingLucky.new(current_user).build_reservation if @reservation.valid? $lock.synchronize("save-reservation-server-#{@reservation.server_id}") do @reservation.save! end reservation_saved if @reservation.persisted? else flash[:alert] = "You're not very lucky, no server is available for the timerange #{@reservation.human_timerange} :(" redirect_to root_path end end def index @users_reservations = current_user.reservations.ordered.paginate(page: params[:page], per_page: 20) end def played_in @users_games = Reservation.includes(:user, server: :location).played_in(current_user.uid) end def edit @reservation = reservation end def update if reservation.past? flash[:alert] = "Reservation has expired, can't update it anymore" redirect_to root_path else update_reservation end end def extend_reservation if reservation.extend! flash[:notice] = "Reservation extended to #{I18n.l(reservation.ends_at, format: :datepicker)}" else flash[:alert] = 'Could not extend, conflicting reservation' end redirect_to root_path end def show if reservation if reservation.gameye_location.present? render :show_gameye else render :show end else redirect_to new_reservation_path end end def gameye if reservation render :show_gameye else redirect_to new_reservation_path end end def destroy if reservation.cancellable? cancel_reservation elsif reservation.just_started? flash[:alert] = 'Your reservation was started in the last 2 minutes. Please give the server some time to start before ending your reservation' else end_reservation end redirect_to root_path end def status reservation respond_to do |format| format.json end end def streaming filename = Rails.root.join('log', 'streaming', "#{reservation.logsecret}.log") @streaming_log = File.open(filename) end private def reservation @reservation ||= find_reservation end helper_method :reservation def reservation_saved if @reservation.now? @reservation.update_attribute(:start_instantly, true) if @reservation.gameye? ReservationWorker.new.perform(reservation.id, 'start') flash[:notice] = 'Match started on Gameye. The server is now being configured, give it a minute to boot' redirect_to gameye_path(@reservation) else @reservation.start_reservation flash[:notice] = "Reservation created for #{@reservation.server_name}. The server is now being configured, give it a minute to start and <a href='#{@reservation.server_connect_url}'>click here to join</a> or enter in console: #{@reservation.connect_string}".html_safe redirect_to reservation_path(@reservation) end else flash[:notice] = "Reservation created for #{@reservation}" redirect_to root_path end end def user_made_two_very_short_reservations_in_last_ten_minutes? count = current_user.reservations .where('starts_at > ?', 10.minutes.ago) .where('ended = ?', true) .count !current_user.admin? && count >= 2 end end Catch missing log file to show # frozen_string_literal: true class ReservationsController < ApplicationController before_action :require_admin, only: [:streaming] include ReservationsHelper def new if user_made_two_very_short_reservations_in_last_ten_minutes? flash[:alert] = 'You made 2 very short reservations in the last ten minutes, please wait a bit before making another one. If there was a problem with your server, let us know in the comments below' redirect_to root_path end @reservation ||= new_reservation @reservation.generate_rcon_password! if @reservation.poor_rcon_password? end def new_gameye @gameye_locations = GameyeServer.locations if user_made_two_very_short_reservations_in_last_ten_minutes? flash[:alert] = 'You made 2 very short reservations in the last ten minutes, please wait a bit before making another one. If there was a problem with your server, let us know in the comments below' redirect_to root_path end @reservation ||= new_reservation @reservation.generate_rcon_password! if @reservation.poor_rcon_password? end def create_gameye @reservation = current_user.reservations.build(reservation_params) if @reservation.valid? $lock.synchronize('save-reservation-server-gameye') do @reservation.save! end reservation_saved if @reservation.persisted? else @gameye_locations = GameyeServer.locations render :new_gameye end end def create @reservation = current_user.reservations.build(reservation_params) if @reservation.valid? $lock.synchronize("save-reservation-server-#{@reservation.server_id}") do @reservation.save! end reservation_saved if @reservation.persisted? else render :new end end def i_am_feeling_lucky @reservation = IAmFeelingLucky.new(current_user).build_reservation if @reservation.valid? $lock.synchronize("save-reservation-server-#{@reservation.server_id}") do @reservation.save! end reservation_saved if @reservation.persisted? else flash[:alert] = "You're not very lucky, no server is available for the timerange #{@reservation.human_timerange} :(" redirect_to root_path end end def index @users_reservations = current_user.reservations.ordered.paginate(page: params[:page], per_page: 20) end def played_in @users_games = Reservation.includes(:user, server: :location).played_in(current_user.uid) end def edit @reservation = reservation end def update if reservation.past? flash[:alert] = "Reservation has expired, can't update it anymore" redirect_to root_path else update_reservation end end def extend_reservation if reservation.extend! flash[:notice] = "Reservation extended to #{I18n.l(reservation.ends_at, format: :datepicker)}" else flash[:alert] = 'Could not extend, conflicting reservation' end redirect_to root_path end def show if reservation if reservation.gameye_location.present? render :show_gameye else render :show end else redirect_to new_reservation_path end end def gameye if reservation render :show_gameye else redirect_to new_reservation_path end end def destroy if reservation.cancellable? cancel_reservation elsif reservation.just_started? flash[:alert] = 'Your reservation was started in the last 2 minutes. Please give the server some time to start before ending your reservation' else end_reservation end redirect_to root_path end def status reservation respond_to do |format| format.json end end def streaming filename = Rails.root.join('log', 'streaming', "#{reservation.logsecret}.log") begin @streaming_log = File.open(filename) rescue Errno::ENOENT flash[:error] = "No such streaming logfile #{reservation.logsecret}.log" redirect_to reservation_path(reservation) end end private def reservation @reservation ||= find_reservation end helper_method :reservation def reservation_saved if @reservation.now? @reservation.update_attribute(:start_instantly, true) if @reservation.gameye? ReservationWorker.new.perform(reservation.id, 'start') flash[:notice] = 'Match started on Gameye. The server is now being configured, give it a minute to boot' redirect_to gameye_path(@reservation) else @reservation.start_reservation flash[:notice] = "Reservation created for #{@reservation.server_name}. The server is now being configured, give it a minute to start and <a href='#{@reservation.server_connect_url}'>click here to join</a> or enter in console: #{@reservation.connect_string}".html_safe redirect_to reservation_path(@reservation) end else flash[:notice] = "Reservation created for #{@reservation}" redirect_to root_path end end def user_made_two_very_short_reservations_in_last_ten_minutes? count = current_user.reservations .where('starts_at > ?', 10.minutes.ago) .where('ended = ?', true) .count !current_user.admin? && count >= 2 end end
class TimeEntriesController < ApplicationController load_and_authorize_resource :time_sheet load_and_authorize_resource :time_entry, through: :time_sheet respond_to :html, :json, :js before_filter :load_time_types def new end def edit @time_entry = TimeEntry.find(params[:id]) end def create @time_entry.save respond_with @time_entry, location: default_return_location end def update @time_entry.update_attributes(params[:time_entry]) respond_with @time_entry, location: default_return_location end def destroy @time_entry.destroy respond_with(@time_entry, location: default_return_location) do |format| format.js { render nothing: true } end end private def default_return_location time_sheet_path(@time_sheet) end def load_time_types @time_types = TimeType.work end end remove obsolete assignment class TimeEntriesController < ApplicationController load_and_authorize_resource :time_sheet load_and_authorize_resource :time_entry, through: :time_sheet respond_to :html, :json, :js before_filter :load_time_types def new end def edit end def create @time_entry.save respond_with @time_entry, location: default_return_location end def update @time_entry.update_attributes(params[:time_entry]) respond_with @time_entry, location: default_return_location end def destroy @time_entry.destroy respond_with(@time_entry, location: default_return_location) do |format| format.js { render nothing: true } end end private def default_return_location time_sheet_path(@time_sheet) end def load_time_types @time_types = TimeType.work end end
require 'date' class TransactionsController < ApplicationController def create #binding.pry @user = User.find(params[:transaction][:owner_id]) #binding.pry @user_lacquer = UserLacquer.find(params[:transaction][:user_lacquer_id]) owner = User.find(@user_lacquer.user_id) lacquer = Lacquer.find(@user_lacquer.lacquer_id) # binding.pry @transaction = Transaction.new(user_lacquer_id: params[:transaction][:user_lacquer_id], requester_id: params[:transaction][:requester_id], owner_id: params[:transaction][:owner_id], type: params[:transaction][:type], due_date: params[:transaction][:due_date]) #transaction.state = 'pending' if @transaction.save respond_to do |format| format.js { } end #flash[:notice] = "You've successfully asked #{owner.first_name} to loan you #{lacquer.name}" end #redirect_to(:back) end def update #binding.pry @transaction = Transaction.find(params[:id]) @user_lacquer = UserLacquer.find(@transaction.user_lacquer_id) if params[:state] @transaction.update(state: params[:state]) end if params[:loan] && params[:loan][:due_date] @transaction.update(due_date: params[:loan][:due_date]) end # if params[:transaction] && params[:transaction][:due_date] # @transaction.update(due_date: params[:transaction][:due_date]) # end if params[:date_became_active] @transaction.update(date_became_active: params[:date_became_active]) end if @transaction.state == 'accepted' #binding.pry @user_lacquer.on_loan = true @user_lacquer.save #binding.pry elsif @transaction.state == 'completed' @user_lacquer.on_loan = false @user_lacquer.save @transaction.date_ended = Date.today end redirect_to(:back) end def destroy if params[:loan] @user_lacquer = UserLacquer.find(params[:loan][:user_lacquer_id]) elsif params[:transaction] @user_lacquer = UserLacquer.find(params[:transaction][:user_lacquer_id]) end #binding.pry @user = User.find(params[:transaction][:owner_id]) @transaction = Transaction.find(params[:id]) if @transaction.state == 'pending' && @transaction.requester == current_user @transaction.destroy else flash[:notice] = "The transaction could not be deleted at this time." end respond_to do |format| format.js { } end #redirect_to(:back) end # private # def transaction_params # params.require(:transaction).permit(:type, :user_lacquer_id, :requester_id) # end end Update transactions_controller.rb require 'date' class TransactionsController < ApplicationController def create @user = User.find(params[:transaction][:owner_id]) @user_lacquer = UserLacquer.find(params[:transaction][:user_lacquer_id]) owner = User.find(@user_lacquer.user_id) lacquer = Lacquer.find(@user_lacquer.lacquer_id) @transaction = Transaction.new(user_lacquer_id: params[:transaction][:user_lacquer_id], requester_id: params[:transaction][:requester_id], owner_id: params[:transaction][:owner_id], type: params[:transaction][:type], due_date: params[:transaction][:due_date]) #transaction.state = 'pending' if @transaction.save respond_to do |format| format.js { } end #flash[:notice] = "You've successfully asked #{owner.first_name} to loan you #{lacquer.name}" end #redirect_to(:back) end def update @transaction = Transaction.find(params[:id]) @user_lacquer = UserLacquer.find(@transaction.user_lacquer_id) if params[:state] @transaction.update(state: params[:state]) end if params[:loan] && params[:loan][:due_date] @transaction.update(due_date: params[:loan][:due_date]) end # if params[:transaction] && params[:transaction][:due_date] # @transaction.update(due_date: params[:transaction][:due_date]) # end if params[:date_became_active] @transaction.update(date_became_active: params[:date_became_active]) end if @transaction.state == 'accepted' @user_lacquer.on_loan = true @user_lacquer.save elsif @transaction.state == 'completed' @user_lacquer.on_loan = false @user_lacquer.save @transaction.date_ended = Date.today end redirect_to(:back) end def destroy if params[:loan] @user_lacquer = UserLacquer.find(params[:loan][:user_lacquer_id]) elsif params[:transaction] @user_lacquer = UserLacquer.find(params[:transaction][:user_lacquer_id]) end @user = User.find(params[:transaction][:owner_id]) @transaction = Transaction.find(params[:id]) if @transaction.state == 'pending' && @transaction.requester == current_user @transaction.destroy else flash[:notice] = "The transaction could not be deleted at this time." end respond_to do |format| format.js { } end #redirect_to(:back) end # private # def transaction_params # params.require(:transaction).permit(:type, :user_lacquer_id, :requester_id) # end end
class TratamientosController < ApplicationController end configurar metodos en controlador class TratamientosController < ApplicationController def new @tratamiento = Tratamiento.new end def create @tratamiento = Tratamiento.new(tratamiento_params) if @tratamineto.save redirect_to new_tratamiento_path, :notice => "GUARDADO" else redirect_to new_tratamiento_path, :notice => "NO GUARDADO" end end def edit end def update end def anular end private def tratamiento_params params.require(:tratamiento).permit(:nombre, :numeracion) end end
class TreeDisplayController < ApplicationController helper :application def action_allowed? true end # direct access to questionnaires def goto_questionnaires node_object = TreeFolder.find_by_name('Questionnaires') session[:root] = FolderNode.find_by_node_object_id(node_object.id).id redirect_to controller: 'tree_display', action: 'list' end # direct access to review rubrics def goto_review_rubrics node_object = TreeFolder.find_by_name('Review') session[:root] = FolderNode.find_by_node_object_id(node_object.id).id redirect_to controller: 'tree_display', action: 'list' end # direct access to metareview rubrics def goto_metareview_rubrics node_object = TreeFolder.find_by_name('Metareview') session[:root] = FolderNode.find_by_node_object_id(node_object.id).id redirect_to controller: 'tree_display', action: 'list' end # direct access to teammate review rubrics def goto_teammatereview_rubrics node_object = TreeFolder.find_by_name('Teammate Review') session[:root] = FolderNode.find_by_node_object_id(node_object.id).id redirect_to controller: 'tree_display', action: 'list' end # direct access to author feedbacks def goto_author_feedbacks node_object = TreeFolder.find_by_name('Author Feedback') session[:root] = FolderNode.find_by_node_object_id(node_object.id).id redirect_to controller: 'tree_display', action: 'list' end # direct access to global survey def goto_global_survey node_object = TreeFolder.find_by_name('Global Survey') session[:root] = FolderNode.find_by_node_object_id(node_object.id).id redirect_to controller: 'tree_display', action: 'list' end # direct access to surveys def goto_surveys node_object = TreeFolder.find_by_name('Survey') session[:root] = FolderNode.find_by_node_object_id(node_object.id).id redirect_to controller: 'tree_display', action: 'list' end # direct access to course evaluations def goto_course_evaluations node_object = TreeFolder.find_by_name('Course Evaluation') session[:root] = FolderNode.find_by_node_object_id(node_object.id).id redirect_to controller: 'tree_display', action: 'list' end # direct access to courses def goto_courses node_object = TreeFolder.find_by_name('Courses') session[:root] = FolderNode.find_by_node_object_id(node_object.id).id redirect_to controller: 'tree_display', action: 'list' end def goto_bookmarkrating_rubrics node_object = TreeFolder.find_by_name('Bookmarkrating') session[:root] = FolderNode.find_by_node_object_id(node_object.id).id redirect_to controller: 'tree_display', action: 'list' end # direct access to assignments def goto_assignments node_object = TreeFolder.find_by_name('Assignments') session[:root] = FolderNode.find_by_node_object_id(node_object.id).id redirect_to controller: 'tree_display', action: 'list' end # called when the display is requested # ajbudlon, July 3rd 2008 def list redirect_to controller: :student_task, action: :list if current_user.student? # if params[:commit] == 'Search' # search_node_root = {'Q' => 1, 'C' => 2, 'A' => 3} # if params[:search_string] # search_node = params[:searchnode] # session[:root] = search_node_root[search_node] # search_string = params[:search_string] # else # search_string = nil # end # else # search_string = nil # end # search_string = filter if params[:commit] == 'Filter' # search_string = nil if params[:commit] == 'Reset' # @search = search_string # display = params[:display] #|| session[:display] # if display # @sortvar = display[:sortvar] # @sortorder = display[:sortorder] # end # @sortvar ||= 'created_at' # @sortorder ||= 'desc' # if session[:root] # @root_node = Node.find(session[:root]) # @child_nodes = @root_node.get_children(@sortvar,@sortorder,session[:user].id,@show,nil,@search) # else # child_nodes = FolderNode.get() # end # @reactjsParams = {} # @reactjsParams[:nodeType] = 'FolderNode' # @reactjsParams[:child_nodes] = child_nodes end def folder_node_ng respond_to do |format| format.html { render json: FolderNode.get } end end # for folder nodes def children_node_ng child_nodes = if params[:reactParams][:child_nodes].is_a? String JSON.parse(params[:reactParams][:child_nodes]) else params[:reactParams][:child_nodes] end tmp_res = {} res = {} child_nodes.each do |node| fnode = eval(params[:reactParams][:nodeType]).new node.each do |a| fnode[a[0]] = a[1] end # fnode is the parent node # ch_nodes are childrens ch_nodes = fnode.get_children(nil, nil, session[:user].id, nil, nil) tmp_res[fnode.get_name] = ch_nodes # cnode = fnode.get_children("created_at", "desc", 2, nil, nil) end tmp_res.keys.each do |node_type| res[node_type] = [] tmp_res[node_type].each do |node| tmp_object = {} tmp_object["nodeinfo"] = node tmp_object["name"] = node.get_name tmp_object["type"] = node.type if node_type == 'Courses' || node_type == "Assignments" tmp_object["directory"] = node.get_directory tmp_object["creation_date"] = node.get_creation_date tmp_object["updated_date"] = node.get_modified_date # tmpObject["private"] = node.get_private tmp_object["private"] = node.get_instructor_id === session[:user].id ? true : false instructor_id = node.get_instructor_id ## if current user's role is TA for a course, then that course will be listed under his course listing. if session[:user].role.ta? == 'Teaching Assistant' && Ta.get_my_instructors(session[:user].id).include?(instructor_id) && ta_for_current_course?(node) tmp_object["private"] = true end tmp_object["instructor_id"] = instructor_id tmp_object["instructor"] = unless instructor_id.nil? User.find(instructor_id).name end tmp_object["is_available"] = is_available(session[:user], instructor_id) || (session[:user].role.ta? && Ta.get_my_instructors(session[:user].id).include?(instructor_id) && ta_for_current_course?(node)) if node_type == "Assignments" tmp_object["course_id"] = node.get_course_id tmp_object["max_team_size"] = node.get_max_team_size tmp_object["is_intelligent"] = node.get_is_intelligent tmp_object["require_quiz"] = node.get_require_quiz tmp_object["allow_suggestions"] = node.get_allow_suggestions tmp_object["has_topic"] = SignUpTopic.where(['assignment_id = ?', node.node_object_id]).first ? true : false end end res[node_type] << tmp_object end end respond_to do |format| format.html { render json: res } end end def ta_for_current_course?(node) ta_mappings = TaMapping.where(ta_id: session[:user].id) if node.type == "CourseNode" ta_mappings.each do |ta_mapping| return true if ta_mapping.course_id == node.node_object_id end elsif node.type == "AssignmentNode" course_id = Assignment.find(node.node_object_id).course_id ta_mappings.each do |ta_mapping| return true if ta_mapping.course_id == course_id end end false end # for child nodes def children_node_2_ng child_nodes = if params[:reactParams2][:child_nodes].is_a? String JSON.parse(params[:reactParams2][:child_nodes]) else params[:reactParams2][:child_nodes] end res = [] fnode = eval(params[:reactParams2][:nodeType]).new child_nodes.each do |key, value| fnode[key] = value end ch_nodes = fnode.get_children(nil, nil, session[:user].id, nil, nil) tmp_res = ch_nodes if tmp_res tmp_res.each do |child| node_type = child.type res2 = {} res2["nodeinfo"] = child res2["name"] = child.get_name res2["key"] = params[:reactParams2][:key] res2["type"] = node_type res2["private"] = child.get_private res2["creation_date"] = child.get_creation_date res2["updated_date"] = child.get_modified_date if node_type == 'CourseNode' || node_type == "AssignmentNode" res2["directory"] = child.get_directory instructor_id = child.get_instructor_id res2["instructor_id"] = instructor_id res2["instructor"] = unless instructor_id.nil? User.find(instructor_id).name end # current user is the instructor (role can be admin/instructor/ta) of this course. available_condition_1 = is_available(session[:user], instructor_id) # instructor created the course, current user is the ta of this course. available_condition_2 = session[:user].role_id == 6 and Ta.get_my_instructors(session[:user].id).include?(instructor_id) and ta_for_current_course?(child) # ta created the course, current user is the instructor of this ta. instructor_ids = [] TaMapping.where(ta_id: instructor_id).each {|mapping| instructor_ids << Course.find(mapping.course_id).instructor_id } available_condition_3 = session[:user].role_id == 2 and instructor_ids.include? session[:user].id res2["is_available"] = available_condition_1 || available_condition_2 || available_condition_3 if node_type == "AssignmentNode" res2["course_id"] = child.get_course_id res2["max_team_size"] = child.get_max_team_size res2["is_intelligent"] = child.get_is_intelligent res2["require_quiz"] = child.get_require_quiz res2["allow_suggestions"] = child.get_allow_suggestions res2["has_topic"] = SignUpTopic.where(['assignment_id = ?', child.node_object_id]).first ? true : false end end res << res2 end end respond_to do |format| format.html { render json: res } end end def bridge_to_is_available user = session[:user] owner_id = params[:owner_id] is_available(user, owner_id) end def session_last_open_tab res = session[:last_open_tab] respond_to do |format| format.html { render json: res } end end def set_session_last_open_tab session[:last_open_tab] = params[:tab] res = session[:last_open_tab] respond_to do |format| format.html { render json: res } end end def drill session[:root] = params[:root] redirect_to controller: 'tree_display', action: 'list' end def filter search = params[:filter_string] filter_node = params[:filternode] qid = 'filter+' if filter_node == 'QAN' assignment = Assignment.find_by_name(search) if assignment assignment_questionnaires = AssignmentQuestionnaire.where(assignment_id: assignment.id) if assignment_questionnaires assignment_questionnaires.each {|q| qid << "#{q.questionnaire_id}+" } session[:root] = 1 end end elsif filter_node == 'ACN' session[:root] = 2 qid << search end qid end end duplicate methods class TreeDisplayController < ApplicationController helper :application def action_allowed? true end def goto_controller(name_parameter) node_object = TreeFolder.find_by_name(name_parameter) session[:root] = FolderNode.find_by_node_object_id(node_object.id).id redirect_to controller: 'tree_display', action: 'list' end # direct access to questionnaires def goto_questionnaires(parameter_name) goto_controller('Questionnaires') end # direct access to review rubrics def goto_review_rubrics goto_controller('Review') end # direct access to metareview rubrics def goto_metareview_rubrics goto_controller('Metareview') end # direct access to teammate review rubrics def goto_teammatereview_rubrics goto_controller('Teammate Review') end # direct access to author feedbacks def goto_author_feedbacks goto_controller('Author Feedback') end # direct access to global survey def goto_global_survey goto_controller('Global Survey') end # direct access to surveys def goto_surveys goto_controller('Survey') end # direct access to course evaluations def goto_course_evaluations goto_controller('Course Evaluation') end # direct access to courses def goto_courses goto_controller('Courses') end def goto_bookmarkrating_rubrics goto_controller('Bookmarkrating') end # direct access to assignments def goto_assignments goto_controller('Assignments') end # called when the display is requested # ajbudlon, July 3rd 2008 def list redirect_to controller: :student_task, action: :list if current_user.student? # if params[:commit] == 'Search' # search_node_root = {'Q' => 1, 'C' => 2, 'A' => 3} # if params[:search_string] # search_node = params[:searchnode] # session[:root] = search_node_root[search_node] # search_string = params[:search_string] # else # search_string = nil # end # else # search_string = nil # end # search_string = filter if params[:commit] == 'Filter' # search_string = nil if params[:commit] == 'Reset' # @search = search_string # display = params[:display] #|| session[:display] # if display # @sortvar = display[:sortvar] # @sortorder = display[:sortorder] # end # @sortvar ||= 'created_at' # @sortorder ||= 'desc' # if session[:root] # @root_node = Node.find(session[:root]) # @child_nodes = @root_node.get_children(@sortvar,@sortorder,session[:user].id,@show,nil,@search) # else # child_nodes = FolderNode.get() # end # @reactjsParams = {} # @reactjsParams[:nodeType] = 'FolderNode' # @reactjsParams[:child_nodes] = child_nodes end def folder_node_ng respond_to do |format| format.html { render json: FolderNode.get } end end # for folder nodes def children_node_ng child_nodes = if params[:reactParams][:child_nodes].is_a? String JSON.parse(params[:reactParams][:child_nodes]) else params[:reactParams][:child_nodes] end tmp_res = {} res = {} child_nodes.each do |node| fnode = eval(params[:reactParams][:nodeType]).new node.each do |a| fnode[a[0]] = a[1] end # fnode is the parent node # ch_nodes are childrens ch_nodes = fnode.get_children(nil, nil, session[:user].id, nil, nil) tmp_res[fnode.get_name] = ch_nodes # cnode = fnode.get_children("created_at", "desc", 2, nil, nil) end tmp_res.keys.each do |node_type| res[node_type] = [] tmp_res[node_type].each do |node| tmp_object = {} tmp_object["nodeinfo"] = node tmp_object["name"] = node.get_name tmp_object["type"] = node.type if node_type == 'Courses' || node_type == "Assignments" tmp_object["directory"] = node.get_directory tmp_object["creation_date"] = node.get_creation_date tmp_object["updated_date"] = node.get_modified_date # tmpObject["private"] = node.get_private tmp_object["private"] = node.get_instructor_id === session[:user].id ? true : false instructor_id = node.get_instructor_id ## if current user's role is TA for a course, then that course will be listed under his course listing. if session[:user].role.ta? == 'Teaching Assistant' && Ta.get_my_instructors(session[:user].id).include?(instructor_id) && ta_for_current_course?(node) tmp_object["private"] = true end tmp_object["instructor_id"] = instructor_id tmp_object["instructor"] = unless instructor_id.nil? User.find(instructor_id).name end tmp_object["is_available"] = is_available(session[:user], instructor_id) || (session[:user].role.ta? && Ta.get_my_instructors(session[:user].id).include?(instructor_id) && ta_for_current_course?(node)) if node_type == "Assignments" tmp_object["course_id"] = node.get_course_id tmp_object["max_team_size"] = node.get_max_team_size tmp_object["is_intelligent"] = node.get_is_intelligent tmp_object["require_quiz"] = node.get_require_quiz tmp_object["allow_suggestions"] = node.get_allow_suggestions tmp_object["has_topic"] = SignUpTopic.where(['assignment_id = ?', node.node_object_id]).first ? true : false end end res[node_type] << tmp_object end end respond_to do |format| format.html { render json: res } end end def ta_for_current_course?(node) ta_mappings = TaMapping.where(ta_id: session[:user].id) if node.type == "CourseNode" ta_mappings.each do |ta_mapping| return true if ta_mapping.course_id == node.node_object_id end elsif node.type == "AssignmentNode" course_id = Assignment.find(node.node_object_id).course_id ta_mappings.each do |ta_mapping| return true if ta_mapping.course_id == course_id end end false end # for child nodes def children_node_2_ng child_nodes = if params[:reactParams2][:child_nodes].is_a? String JSON.parse(params[:reactParams2][:child_nodes]) else params[:reactParams2][:child_nodes] end res = [] fnode = eval(params[:reactParams2][:nodeType]).new child_nodes.each do |key, value| fnode[key] = value end ch_nodes = fnode.get_children(nil, nil, session[:user].id, nil, nil) tmp_res = ch_nodes if tmp_res tmp_res.each do |child| node_type = child.type res2 = {} res2["nodeinfo"] = child res2["name"] = child.get_name res2["key"] = params[:reactParams2][:key] res2["type"] = node_type res2["private"] = child.get_private res2["creation_date"] = child.get_creation_date res2["updated_date"] = child.get_modified_date if node_type == 'CourseNode' || node_type == "AssignmentNode" res2["directory"] = child.get_directory instructor_id = child.get_instructor_id res2["instructor_id"] = instructor_id res2["instructor"] = unless instructor_id.nil? User.find(instructor_id).name end # current user is the instructor (role can be admin/instructor/ta) of this course. available_condition_1 = is_available(session[:user], instructor_id) # instructor created the course, current user is the ta of this course. available_condition_2 = session[:user].role_id == 6 and Ta.get_my_instructors(session[:user].id).include?(instructor_id) and ta_for_current_course?(child) # ta created the course, current user is the instructor of this ta. instructor_ids = [] TaMapping.where(ta_id: instructor_id).each {|mapping| instructor_ids << Course.find(mapping.course_id).instructor_id } available_condition_3 = session[:user].role_id == 2 and instructor_ids.include? session[:user].id res2["is_available"] = available_condition_1 || available_condition_2 || available_condition_3 if node_type == "AssignmentNode" res2["course_id"] = child.get_course_id res2["max_team_size"] = child.get_max_team_size res2["is_intelligent"] = child.get_is_intelligent res2["require_quiz"] = child.get_require_quiz res2["allow_suggestions"] = child.get_allow_suggestions res2["has_topic"] = SignUpTopic.where(['assignment_id = ?', child.node_object_id]).first ? true : false end end res << res2 end end respond_to do |format| format.html { render json: res } end end def bridge_to_is_available user = session[:user] owner_id = params[:owner_id] is_available(user, owner_id) end def session_last_open_tab res = session[:last_open_tab] respond_to do |format| format.html { render json: res } end end def set_session_last_open_tab session[:last_open_tab] = params[:tab] res = session[:last_open_tab] respond_to do |format| format.html { render json: res } end end def drill session[:root] = params[:root] redirect_to controller: 'tree_display', action: 'list' end def filter search = params[:filter_string] filter_node = params[:filternode] qid = 'filter+' if filter_node == 'QAN' assignment = Assignment.find_by_name(search) if assignment assignment_questionnaires = AssignmentQuestionnaire.where(assignment_id: assignment.id) if assignment_questionnaires assignment_questionnaires.each {|q| qid << "#{q.questionnaire_id}+" } session[:root] = 1 end end elsif filter_node == 'ACN' session[:root] = 2 qid << search end qid end end
class TreeDisplayController < ApplicationController helper :application def action_allowed? true end #refactored method to provide direct access to parameters def goto_controller(name_parameter) node_object = TreeFolder.find_by(name: name_parameter) session[:root] = FolderNode.find_by(node_object_id: node_object.id).id redirect_to controller: 'tree_display', action: 'list' end # direct access to questionnaires def goto_questionnaires goto_controller('Questionnaires') end # direct access to review rubrics def goto_review_rubrics goto_controller('Review') end # direct access to metareview rubrics def goto_metareview_rubrics goto_controller('Metareview') end # direct access to teammate review rubrics def goto_teammatereview_rubrics goto_controller('Teammate Review') end # direct access to author feedbacks def goto_author_feedbacks goto_controller('Author Feedback') end # direct access to global survey def goto_global_survey goto_controller('Global Survey') end # direct access to surveys def goto_surveys goto_controller('Survey') end # direct access to course evaluations def goto_course_evaluations goto_controller('Course Evaluation') end # direct access to courses def goto_courses goto_controller('Courses') end def goto_bookmarkrating_rubrics goto_controller('Bookmarkrating') end # direct access to assignments def goto_assignments goto_controller('Assignments') end # called when the display is requested # ajbudlon, July 3rd 2008 def list redirect_to controller: :student_task, action: :list if current_user.student? # if params[:commit] == 'Search' # search_node_root = {'Q' => 1, 'C' => 2, 'A' => 3} # if params[:search_string] # search_node = params[:searchnode] # session[:root] = search_node_root[search_node] # search_string = params[:search_string] # else # search_string = nil # end # else # search_string = nil # end # search_string = filter if params[:commit] == 'Filter' # search_string = nil if params[:commit] == 'Reset' # @search = search_string # display = params[:display] #|| session[:display] # if display # @sortvar = display[:sortvar] # @sortorder = display[:sortorder] # end # @sortvar ||= 'created_at' # @sortorder ||= 'desc' # if session[:root] # @root_node = Node.find(session[:root]) # @child_nodes = @root_node.get_children(@sortvar,@sortorder,session[:user].id,@show,nil,@search) # else # child_nodes = FolderNode.get() # end # @reactjsParams = {} # @reactjsParams[:nodeType] = 'FolderNode' # @reactjsParams[:child_nodes] = child_nodes end def folder_node_ng_getter respond_to do |format| format.html { render json: FolderNode.get } end end def child_nodes_from_params(child_nodes) if child_nodes.is_a? String JSON.parse(child_nodes) else child_nodes end end def assignments_func(node, tmp_object) tmp_object.merge!( "course_id" => node.get_course_id, "max_team_size" => node.get_max_team_size, "is_intelligent" => node.get_is_intelligent, "require_quiz" => node.get_require_quiz, "allow_suggestions" => node.get_allow_suggestions, "has_topic" => SignUpTopic.where(['assignment_id = ?', node.node_object_id]).first ? true : false ) end def update_in_ta_course_listing(instructor_id, node, tmp_object) tmp_object["private"] = true if session[:user].role.ta? == 'Teaching Assistant' && Ta.get_my_instructors(session[:user].id).include?(instructor_id) && ta_for_current_course?(node) # end end def update_is_available(tmp_object, instructor_id, node) tmp_object["is_available"] = is_available(session[:user], instructor_id) || (session[:user].role.ta? && Ta.get_my_instructors(session[:user].id).include?(instructor_id) && ta_for_current_course?(node)) end def update_instructor(tmp_object, instructor_id) tmp_object["instructor_id"] = instructor_id tmp_object["instructor"] = nil tmp_object["instructor"] = User.find(instructor_id).name if instructor_id end def update_tmp_obj(tmp_object, node) tmp_object.merge!( "directory" => node.get_directory, "creation_date" => node.get_creation_date, "updated_date" => node.get_modified_date, "private" => node.get_instructor_id == session[:user].id ? true : false ) end def courses_assignments_obj(node_type, tmp_object, node) update_tmp_obj(tmp_object, node) # tmpObject["private"] = node.get_private instructor_id = node.get_instructor_id ## if current user's role is TA for a course, then that course will be listed under his course listing. update_in_ta_course_listing(instructor_id, node, tmp_object) update_instructor(tmp_object, instructor_id) update_is_available(tmp_object, instructor_id, node) assignments_func(node, tmp_object) if node_type == "Assignments" end def res_node_for_child(tmp_res) res = {} tmp_res.keys.each do |node_type| res[node_type] = [] tmp_res[node_type].each do |node| tmp_object = { "nodeinfo" => node, "name" => node.get_name, "type" => node.type } if node_type == 'Courses' || node_type == "Assignments" courses_assignments_obj(node_type, tmp_object, node) end res[node_type] << tmp_object end end res end def update_fnode_children(fnode, tmp_res) # fnode is the parent node # ch_nodes are childrens ch_nodes = fnode.get_children(nil, nil, session[:user].id, nil, nil) tmp_res[fnode.get_name] = ch_nodes end def init_fnode_update_children(params, node, tmp_res) fnode = (params[:reactParams][:nodeType]).constantize.new node.each do |a| fnode[a[0]] = a[1] end update_fnode_children(fnode, tmp_res) end # for folder nodes def children_node_ng child_nodes = child_nodes_from_params(params[:reactParams][:child_nodes]) tmp_res = {} child_nodes.each do |node| init_fnode_update_children(params, node, tmp_res) # res = res_node_for_child(tmp_res) # cnode = fnode.get_children("created_at", "desc", 2, nil, nil) end res = res_node_for_child(tmp_res) respond_to do |format| format.html { render json: res } end end def coursenode?(ta_mappings, node) ta_mappings.each do |ta_mapping| return true if ta_mapping.course_id == node.node_object_id end end def assignmentnode?(ta_mappings, node) course_id = Assignment.find(node.node_object_id).course_id ta_mappings.each do |ta_mapping| return true if ta_mapping.course_id == course_id end end def ta_for_current_course?(node) ta_mappings = TaMapping.where(ta_id: session[:user].id) if node.type == "CourseNode" return true if coursenode?(ta_mappings, node) elsif node.type == "AssignmentNode" return true if assignmentnode?(ta_mappings, node) end false end def available_condition2?(instructor_id, child) # instructor created the course, current user is the ta of this course. session[:user].role_id == 6 and Ta.get_my_instructors(session[:user].id).include?(instructor_id) and ta_for_current_course?(child) end def available_condition3?(instructor_id) # ta created the course, current user is the instructor of this ta. instructor_ids = [] TaMapping.where(ta_id: instructor_id).each {|mapping| instructor_ids << Course.find(mapping.course_id).instructor_id } session[:user].role_id == 2 and instructor_ids.include? session[:user].id end def update_is_available_2(res2, instructor_id, child) # current user is the instructor (role can be admin/instructor/ta) of this course. is_available_condition1 res2["is_available"] = is_available(session[:user], instructor_id) || available_condition2?(instructor_id, child) || available_condition3?(instructor_id) end def coursenode_assignmentnode(res2, child) res2["directory"] = child.get_directory instructor_id = child.get_instructor_id update_instructor(res2, instructor_id) update_is_available_2(res2, instructor_id, child) assignments_func(child, res2) if node_type == "AssignmentNode" end def res_node_for_child_2(tmp_res) res = [] if tmp_res tmp_res.each do |child| node_type = child.type res2 = { "nodeinfo" => child, "name" => child.get_name, "key" => params[:reactParams2][:key], "type" => node_type, "private" => child.get_private, "creation_date" => child.get_creation_date, "updated_date" => child.get_modified_date } if node_type == 'CourseNode' || node_type == "AssignmentNode" coursenode_assignmentnode(res2, child) end res << res2 end end res2 end def init_fnode_2(fnode, child_nodes) child_nodes.each do |key, value| fnode[key] = value end end def get_tmp_res(params, child_nodes) fnode = (params[:reactParams][:nodeType]).constantize.new init_fnode_2(fnode, child_nodes) ch_nodes = fnode.get_children(nil, nil, session[:user].id, nil, nil) tmp_res = ch_nodes res_node_for_child_2(tmp_res) end # for child nodes def children_node_2_ng child_nodes = child_nodes_from_params(params[:reactParams2][:child_nodes]) res = get_tmp_res(params, child_nodes) respond_to do |format| format.html { render json: res } end end def bridge_to_is_available user = session[:user] owner_id = params[:owner_id] is_available(user, owner_id) end def session_last_open_tab res = session[:last_open_tab] respond_to do |format| format.html { render json: res } end end def set_session_last_open_tab session[:last_open_tab] = params[:tab] res = session[:last_open_tab] respond_to do |format| format.html { render json: res } end end def drill session[:root] = params[:root] redirect_to controller: 'tree_display', action: 'list' end def filter_qan(search, qid) assignment = Assignment.find_by(name: search) if assignment assignment_questionnaires = AssignmentQuestionnaire.where(assignment_id: assignment.id) if assignment_questionnaires assignment_questionnaires.each {|q| qid << "#{q.questionnaire_id}+" } session[:root] = 1 end end qid end def filter qid = 'filter+' search = params[:filter_string] filter_node = params[:filternode] if filter_node == 'QAN' qid = filter_qan(search, qid) elsif filter_node == 'ACN' session[:root] = 2 qid << search end qid end end Changing method names to make it more readable and fixing comments class TreeDisplayController < ApplicationController helper :application def action_allowed? true end #refactored method to provide direct access to parameters def goto_controller(name_parameter) node_object = TreeFolder.find_by(name: name_parameter) session[:root] = FolderNode.find_by(node_object_id: node_object.id).id redirect_to controller: 'tree_display', action: 'list' end # direct access to questionnaires def goto_questionnaires goto_controller('Questionnaires') end # direct access to review rubrics def goto_review_rubrics goto_controller('Review') end # direct access to metareview rubrics def goto_metareview_rubrics goto_controller('Metareview') end # direct access to teammate review rubrics def goto_teammatereview_rubrics goto_controller('Teammate Review') end # direct access to author feedbacks def goto_author_feedbacks goto_controller('Author Feedback') end # direct access to global survey def goto_global_survey goto_controller('Global Survey') end # direct access to surveys def goto_surveys goto_controller('Survey') end # direct access to course evaluations def goto_course_evaluations goto_controller('Course Evaluation') end # direct access to courses def goto_courses goto_controller('Courses') end def goto_bookmarkrating_rubrics goto_controller('Bookmarkrating') end # direct access to assignments def goto_assignments goto_controller('Assignments') end # called when the display is requested # ajbudlon, July 3rd 2008 def list redirect_to controller: :student_task, action: :list if current_user.student? # if params[:commit] == 'Search' # search_node_root = {'Q' => 1, 'C' => 2, 'A' => 3} # if params[:search_string] # search_node = params[:searchnode] # session[:root] = search_node_root[search_node] # search_string = params[:search_string] # else # search_string = nil # end # else # search_string = nil # end # search_string = filter if params[:commit] == 'Filter' # search_string = nil if params[:commit] == 'Reset' # @search = search_string # display = params[:display] #|| session[:display] # if display # @sortvar = display[:sortvar] # @sortorder = display[:sortorder] # end # @sortvar ||= 'created_at' # @sortorder ||= 'desc' # if session[:root] # @root_node = Node.find(session[:root]) # @child_nodes = @root_node.get_children(@sortvar,@sortorder,session[:user].id,@show,nil,@search) # else # child_nodes = FolderNode.get() # end # @reactjsParams = {} # @reactjsParams[:nodeType] = 'FolderNode' # @reactjsParams[:child_nodes] = child_nodes end def folder_node_ng_getter respond_to do |format| format.html { render json: FolderNode.get } end end def child_nodes_from_params(child_nodes) if child_nodes.is_a? String JSON.parse(child_nodes) else child_nodes end end def assignments_func(node, tmp_object) tmp_object.merge!( "course_id" => node.get_course_id, "max_team_size" => node.get_max_team_size, "is_intelligent" => node.get_is_intelligent, "require_quiz" => node.get_require_quiz, "allow_suggestions" => node.get_allow_suggestions, "has_topic" => SignUpTopic.where(['assignment_id = ?', node.node_object_id]).first ? true : false ) end def update_in_ta_course_listing(instructor_id, node, tmp_object) tmp_object["private"] = true if session[:user].role.ta? == 'Teaching Assistant' && Ta.get_my_instructors(session[:user].id).include?(instructor_id) && ta_for_current_course?(node) # end end def update_is_available(tmp_object, instructor_id, node) tmp_object["is_available"] = is_available(session[:user], instructor_id) || (session[:user].role.ta? && Ta.get_my_instructors(session[:user].id).include?(instructor_id) && ta_for_current_course?(node)) end def update_instructor(tmp_object, instructor_id) tmp_object["instructor_id"] = instructor_id tmp_object["instructor"] = nil tmp_object["instructor"] = User.find(instructor_id).name if instructor_id end def update_tmp_obj(tmp_object, node) tmp_object.merge!( "directory" => node.get_directory, "creation_date" => node.get_creation_date, "updated_date" => node.get_modified_date, "private" => node.get_instructor_id == session[:user].id ? true : false ) end def courses_assignments_obj(node_type, tmp_object, node) update_tmp_obj(tmp_object, node) # tmpObject["private"] = node.get_private instructor_id = node.get_instructor_id ## if current user's role is TA for a course, then that course will be listed under his course listing. update_in_ta_course_listing(instructor_id, node, tmp_object) update_instructor(tmp_object, instructor_id) update_is_available(tmp_object, instructor_id, node) assignments_func(node, tmp_object) if node_type == "Assignments" end def res_node_for_child(tmp_res) res = {} tmp_res.keys.each do |node_type| res[node_type] = [] tmp_res[node_type].each do |node| tmp_object = { "nodeinfo" => node, "name" => node.get_name, "type" => node.type } if node_type == 'Courses' || node_type == "Assignments" courses_assignments_obj(node_type, tmp_object, node) end res[node_type] << tmp_object end end res end def update_fnode_children(fnode, tmp_res) # fnode is the parent node # ch_nodes are childrens # cnode = fnode.get_children("created_at", "desc", 2, nil, nil) ch_nodes = fnode.get_children(nil, nil, session[:user].id, nil, nil) tmp_res[fnode.get_name] = ch_nodes end def initialize_fnode_update_children(params, node, tmp_res) fnode = (params[:reactParams][:nodeType]).constantize.new node.each do |a| fnode[a[0]] = a[1] end update_fnode_children(fnode, tmp_res) end # for folder nodes def children_node_ng child_nodes = child_nodes_from_params(params[:reactParams][:child_nodes]) tmp_res = {} child_nodes.each do |node| initialize_fnode_update_children(params, node, tmp_res) end # res = res_node_for_child(tmp_res) res = res_node_for_child(tmp_res) respond_to do |format| format.html { render json: res } end end def coursenode?(ta_mappings, node) ta_mappings.each do |ta_mapping| return true if ta_mapping.course_id == node.node_object_id end end def assignmentnode?(ta_mappings, node) course_id = Assignment.find(node.node_object_id).course_id ta_mappings.each do |ta_mapping| return true if ta_mapping.course_id == course_id end end def ta_for_current_course?(node) ta_mappings = TaMapping.where(ta_id: session[:user].id) if node.type == "CourseNode" return true if coursenode?(ta_mappings, node) elsif node.type == "AssignmentNode" return true if assignmentnode?(ta_mappings, node) end false end def available_condition2?(instructor_id, child) # instructor created the course, current user is the ta of this course. session[:user].role_id == 6 and Ta.get_my_instructors(session[:user].id).include?(instructor_id) and ta_for_current_course?(child) end def available_condition3?(instructor_id) # ta created the course, current user is the instructor of this ta. instructor_ids = [] TaMapping.where(ta_id: instructor_id).each {|mapping| instructor_ids << Course.find(mapping.course_id).instructor_id } session[:user].role_id == 2 and instructor_ids.include? session[:user].id end def update_is_available_2(res2, instructor_id, child) # current user is the instructor (role can be admin/instructor/ta) of this course. is_available_condition1 res2["is_available"] = is_available(session[:user], instructor_id) || available_condition2?(instructor_id, child) || available_condition3?(instructor_id) end def coursenode_assignmentnode(res2, child) res2["directory"] = child.get_directory instructor_id = child.get_instructor_id update_instructor(res2, instructor_id) update_is_available_2(res2, instructor_id, child) assignments_func(child, res2) if node_type == "AssignmentNode" end def res_node_for_child_2(tmp_res) res = [] if tmp_res tmp_res.each do |child| node_type = child.type res2 = { "nodeinfo" => child, "name" => child.get_name, "key" => params[:reactParams2][:key], "type" => node_type, "private" => child.get_private, "creation_date" => child.get_creation_date, "updated_date" => child.get_modified_date } if node_type == 'CourseNode' || node_type == "AssignmentNode" coursenode_assignmentnode(res2, child) end res << res2 end end res2 end def init_fnode_2(fnode, child_nodes) child_nodes.each do |key, value| fnode[key] = value end end def get_tmp_res(params, child_nodes) fnode = (params[:reactParams][:nodeType]).constantize.new init_fnode_2(fnode, child_nodes) ch_nodes = fnode.get_children(nil, nil, session[:user].id, nil, nil) tmp_res = ch_nodes res_node_for_child_2(tmp_res) end # for child nodes def children_node_2_ng child_nodes = child_nodes_from_params(params[:reactParams2][:child_nodes]) res = get_tmp_res(params, child_nodes) respond_to do |format| format.html { render json: res } end end def bridge_to_is_available user = session[:user] owner_id = params[:owner_id] is_available(user, owner_id) end def session_last_open_tab res = session[:last_open_tab] respond_to do |format| format.html { render json: res } end end def set_session_last_open_tab session[:last_open_tab] = params[:tab] res = session[:last_open_tab] respond_to do |format| format.html { render json: res } end end def drill session[:root] = params[:root] redirect_to controller: 'tree_display', action: 'list' end def filter_qan(search, qid) assignment = Assignment.find_by(name: search) if assignment assignment_questionnaires = AssignmentQuestionnaire.where(assignment_id: assignment.id) if assignment_questionnaires assignment_questionnaires.each {|q| qid << "#{q.questionnaire_id}+" } session[:root] = 1 end end qid end def filter qid = 'filter+' search = params[:filter_string] filter_node = params[:filternode] if filter_node == 'QAN' qid = filter_qan(search, qid) elsif filter_node == 'ACN' session[:root] = 2 qid << search end qid end end
module Metatron module ApplicationHelper def header_tags [ metatron_tags ].join("\n").html_safe end def metatron_tags [ meta_tag(property: 'fb:app_id', content: '1434650413476851'), meta_tag(name: 'twitter:card', content: 'summary_large_image'), meta_tag(name: 'twitter:site', content: '@IPlayRedGaming'), meta_tag(name: 'twitter:creator', content: '@IPlayRedGaming'), meta_tag(property: 'og:type', content: 'website'), meta_tag(property: 'og:site_name', content: 'I Play Red'), meta_tag(property: 'og:url', content: url), tag(:link, rel: 'canonical', href: url), title_tags, description_tags, image_tags, keywords_tags, ].flatten.compact.join("\n").html_safe end def keywords_tags return [] unless (keywords).present? [ meta_tag(name: 'keywords', content: keywords), ] end def image_tags return [] unless metatron.image [ meta_tag(property: 'og:image', content: metatron.image), meta_tag(name: 'twitter:image:src', content: metatron.image) ] end def description_tags [ meta_tag(name: 'description', content: metatron.description), meta_tag(property: 'og:description', content: metatron.description), meta_tag(name: 'twitter:description', content: metatron.description) ] end def title_tags [ content_tag(:title, metatron.title), meta_tag(name: 'title', content: metatron.title), meta_tag(property: 'og:title', content: metatron.title), meta_tag(name: 'twitter:title', content: metatron.title) ] end private def keywords @keywords ||= begin Array[metatron.keywords, I18n.t('meta.keywords', default: '')].flatten.select(&:present?).map do |section| section.to_s.split(',') end.flatten.select(&:present?).map(&:strip).uniq.join(', ') end end def url (metatron.url || request.url).split('?')[0] end def meta_tag(options) tag(:meta, options) end end end add og video module Metatron module ApplicationHelper def header_tags [ metatron_tags ].join("\n").html_safe end def metatron_tags [ meta_tag(property: 'fb:app_id', content: '1434650413476851'), meta_tag(name: 'twitter:card', content: 'summary_large_image'), meta_tag(name: 'twitter:site', content: '@IPlayRedGaming'), meta_tag(name: 'twitter:creator', content: '@IPlayRedGaming'), meta_tag(property: 'og:type', content: 'website'), meta_tag(property: 'og:site_name', content: 'I Play Red'), meta_tag(property: 'og:url', content: url), tag(:link, rel: 'canonical', href: url), title_tags, description_tags, image_tags, video_tags, keywords_tags, ].flatten.compact.join("\n").html_safe end def keywords_tags return [] unless (keywords).present? [ meta_tag(name: 'keywords', content: keywords), ] end def image_tags return [] unless metatron.image [ meta_tag(property: 'og:image', content: metatron.image), meta_tag(name: 'twitter:image:src', content: metatron.image) ] end def video_tags [ meta_tag(property: 'og:video', content: metatron.video), ] end def description_tags [ meta_tag(name: 'description', content: metatron.description), meta_tag(property: 'og:description', content: metatron.description), meta_tag(name: 'twitter:description', content: metatron.description) ] end def title_tags [ content_tag(:title, metatron.title), meta_tag(name: 'title', content: metatron.title), meta_tag(property: 'og:title', content: metatron.title), meta_tag(name: 'twitter:title', content: metatron.title) ] end private def keywords @keywords ||= begin Array[metatron.keywords, I18n.t('meta.keywords', default: '')].flatten.select(&:present?).map do |section| section.to_s.split(',') end.flatten.select(&:present?).map(&:strip).uniq.join(', ') end end def url (metatron.url || request.url).split('?')[0] end def meta_tag(options) tag(:meta, options) end end end
add surround_input module CustomInputs class SurroundInput < SimpleForm::Inputs::StringInput include UiBibz::Ui::Core def input(wrapper_options) UiBibz::Ui::Core::SurroundField.new(attribute_name, input_options, input_html_options).render end end end
require 'nokogiri' require 'pry' class StlPublicServices::Scraper attr_accessor :url def initialize(url) @url = url end def scrape_service_info(url) html = Nokogiri::HTML(open(url)) services = {} html.css('div.col-md-8 div').each do |listing| service_names = listing.css('h4 a').text urls = listing.css('a').attribute('href').value phone = listing.css('div:nth-child(1)').text.scan(/P\S+\s\S+\s\S+/).join.gsub "Phone: ", "" fax = listing.css('div:nth-child(1)').text.scan(/F\S+\s\S+\s\S+/).join.gsub "Fax: ", "" binding.pry end end end Further refactor scraper, got name and url working now require 'nokogiri' require 'pry' class StlPublicServices::Scraper attr_accessor :url def initialize(url) @url = url end def scrape_service_info(url) html = Nokogiri::HTML(open(url)) services = {} html.css('h4 a').each do |title| name = title.text.to_sym services[name] = { :name => name.to_s, :url => title.attribute('href').text } binding.pry end end end
require 'strong_routes/rails/route_mapper' module StrongRoutes module Rails class Railtie < ::Rails::Railtie config.strong_routes = StrongRoutes.config initializer 'strong_routes.initialize' do |app| # Need to force Rails to load the routes since there's no way to hook # in after routes are loaded app.reload_routes! config.strong_routes.allowed_routes ||= [] config.strong_routes.allowed_routes += RouteMapper.map(app.routes) case when config.strong_routes.insert_before? then app.config.middleware.insert_before(config.strong_routes.insert_before, Allow) when config.strong_routes.insert_after? then app.config.middleware.insert_after(config.strong_routes.insert_after, Allow) else app.config.middleware.insert_before(::Rails::Rack::Logger, Allow) end end end end end Configure allowed routes in an after initializer Configure allowed routes in an after initializer so initializers that depend on routes have a chance to initialize (i.e. Devise). require 'strong_routes/rails/route_mapper' module StrongRoutes module Rails class Railtie < ::Rails::Railtie config.strong_routes = StrongRoutes.config initializer 'strong_routes.initialize' do |app| case when config.strong_routes.insert_before? then app.config.middleware.insert_before(config.strong_routes.insert_before, Allow) when config.strong_routes.insert_after? then app.config.middleware.insert_after(config.strong_routes.insert_after, Allow) else app.config.middleware.insert_before(::Rails::Rack::Logger, Allow) end end # Load this late so initializers that depend on routes have a chance to # initialize (i.e. Devise) config.after_initialize do |app| # Need to force Rails to load the routes since there's no way to hook # in after routes are loaded app.reload_routes! config.strong_routes.allowed_routes ||= [] config.strong_routes.allowed_routes += RouteMapper.map(app.routes) end end end end