1 class ApplicationController < ActionController::Base
2 include ArvadosApiClientHelper
3 include ApplicationHelper
5 respond_to :html, :json, :js
8 ERROR_ACTIONS = [:render_error, :render_not_found]
10 around_filter :thread_clear
11 around_filter :set_thread_api_token
12 # Methods that don't require login should
13 # skip_around_filter :require_thread_api_token
14 around_filter :require_thread_api_token, except: ERROR_ACTIONS
15 before_filter :set_cache_buster
16 before_filter :accept_uuid_as_id_param, except: ERROR_ACTIONS
17 before_filter :check_user_agreements, except: ERROR_ACTIONS
18 before_filter :check_user_profile, except: ERROR_ACTIONS
19 before_filter :load_filters_and_paging_params, except: ERROR_ACTIONS
20 before_filter :find_object_by_uuid, except: [:create, :index, :choose] + ERROR_ACTIONS
24 rescue_from(ActiveRecord::RecordNotFound,
25 ActionController::RoutingError,
26 ActionController::UnknownController,
27 AbstractController::ActionNotFound,
28 with: :render_not_found)
29 rescue_from(Exception,
30 ActionController::UrlGenerationError,
31 with: :render_exception)
35 response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
36 response.headers["Pragma"] = "no-cache"
37 response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
40 def unprocessable(message=nil)
43 @errors << message if message
44 render_error status: 422
47 def render_error(opts={})
48 # Helpers can rely on the presence of @errors to know they're
49 # being used in an error page.
53 # json must come before html here, so it gets used as the
54 # default format when js is requested by the client. This lets
55 # ajax:error callback parse the response correctly, even though
57 f.json { render opts.merge(json: {success: false, errors: @errors}) }
58 f.html { render({action: 'error'}.merge(opts)) }
62 def render_exception(e)
63 logger.error e.inspect
64 logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
65 err_opts = {status: 422}
66 if e.is_a?(ArvadosApiClient::ApiError)
67 err_opts.merge!(action: 'api_error', locals: {api_error: e})
68 @errors = e.api_response[:errors]
69 elsif @object.andand.errors.andand.full_messages.andand.any?
70 @errors = @object.errors.full_messages
74 # Make user information available on the error page, falling back to the
75 # session cache if the API server is unavailable.
77 load_api_token(session[:arvados_api_token])
78 rescue ArvadosApiClient::ApiError
79 unless session[:user].nil?
81 Thread.current[:user] = User.new(session[:user])
82 rescue ArvadosApiClient::ApiError
83 # This can happen if User's columns are unavailable. Nothing to do.
87 # Preload projects trees for the template. If that's not doable, set empty
88 # trees so error page rendering can proceed. (It's easier to rescue the
89 # exception here than in a template.)
90 unless current_user.nil?
92 build_my_wanted_projects_tree current_user
93 rescue ArvadosApiClient::ApiError
94 # Fall back to the default-setting code later.
97 @my_wanted_projects_tree ||= []
98 render_error(err_opts)
101 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
102 logger.error e.inspect
103 @errors = ["Path not found"]
104 set_thread_api_token do
105 self.render_error(action: '404', status: 404)
111 # The order can be left empty to allow it to default.
112 # Or it can be a comma separated list of real database column names, one per model.
113 # Column names should always be qualified by a table name and a direction is optional, defaulting to asc
114 # (e.g. "collections.name" or "collections.name desc").
115 # If a column name is specified, that table will be sorted by that column.
116 # If there are objects from different models that will be shown (such as in Jobs and Pipelines tab),
117 # then a sort column name can optionally be specified for each model, passed as an comma-separated list (e.g. "jobs.script, pipeline_instances.name")
118 # Currently only one sort column name and direction can be specified for each model.
119 def load_filters_and_paging_params
120 if params[:order].blank?
121 @order = 'created_at desc'
122 elsif params[:order].is_a? Array
123 @order = params[:order]
126 @order = JSON.load(params[:order])
128 @order = params[:order].split(',')
131 @order = [@order] unless @order.is_a? Array
135 @limit = params[:limit].to_i
140 @offset = params[:offset].to_i
145 filters = params[:filters]
146 if filters.is_a? String
147 filters = Oj.load filters
148 elsif filters.is_a? Array
149 filters = filters.collect do |filter|
150 if filter.is_a? String
151 # Accept filters[]=["foo","=","bar"]
154 # Accept filters=[["foo","=","bar"]]
159 # After this, params[:filters] can be trusted to be an array of arrays:
160 params[:filters] = filters
165 def find_objects_for_index
166 @objects ||= model_class
167 @objects = @objects.filter(@filters).limit(@limit).offset(@offset)
168 @objects.fetch_multiple_pages(false)
175 @next_page_href = next_page_href(partial: params[:partial], filters: @filters.to_json)
177 content: render_to_string(partial: "show_#{params[:partial]}",
179 next_page_href: @next_page_href
182 render json: @objects
187 render_pane params[:tab_pane]
196 helper_method :render_pane
197 def render_pane tab_pane, opts={}
199 partial: 'show_' + tab_pane.downcase,
201 comparable: self.respond_to?(:compare),
204 }.merge(opts[:locals] || {})
207 render_to_string render_opts
214 find_objects_for_index if !@objects
218 helper_method :next_page_offset
219 def next_page_offset objects=nil
223 if objects.respond_to?(:result_offset) and
224 objects.respond_to?(:result_limit) and
225 objects.respond_to?(:items_available)
226 next_offset = objects.result_offset + objects.result_limit
227 if next_offset < objects.items_available
235 helper_method :next_page_href
236 def next_page_href with_params={}
238 url_for with_params.merge(offset: next_page_offset)
244 return render_not_found("object not found")
248 extra_attrs = { href: url_for(action: :show, id: @object) }
249 @object.textile_attributes.each do |textile_attr|
250 extra_attrs.merge!({ "#{textile_attr}Textile" => view_context.render_markup(@object.attributes[textile_attr]) })
252 render json: @object.attributes.merge(extra_attrs)
255 if params['tab_pane']
256 render_pane(if params['tab_pane'].is_a? Hash then params['tab_pane']["name"] else params['tab_pane'] end)
257 elsif request.request_method.in? ['GET', 'HEAD']
260 redirect_to (params[:return_to] ||
261 polymorphic_url(@object,
262 anchor: params[:redirect_to_anchor]))
269 def redirect_to uri, *args
271 if not uri.is_a? String
272 uri = polymorphic_url(uri)
274 render json: {href: uri}
281 params[:limit] ||= 40
285 find_objects_for_index if !@objects
287 content: render_to_string(partial: "choose_rows.html",
289 next_page_href: next_page_href(partial: params[:partial])
294 find_objects_for_index if !@objects
295 render partial: 'choose', locals: {multiple: params[:multiple]}
302 return render_not_found("object not found")
307 @object = model_class.new
311 @updates ||= params[@object.resource_param_name.to_sym]
312 @updates.keys.each do |attr|
313 if @object.send(attr).is_a? Hash
314 if @updates[attr].is_a? String
315 @updates[attr] = Oj.load @updates[attr]
317 if params[:merge] || params["merge_#{attr}".to_sym]
318 # Merge provided Hash with current Hash, instead of
320 @updates[attr] = @object.send(attr).with_indifferent_access.
321 deep_merge(@updates[attr].with_indifferent_access)
325 if @object.update_attributes @updates
328 self.render_error status: 422
333 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
334 @new_resource_attrs ||= {}
335 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
336 @object ||= model_class.new @new_resource_attrs, params["options"]
341 render_error status: 422
345 # Clone the given object, merging any attribute values supplied as
346 # with a create action.
348 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
349 @new_resource_attrs ||= {}
350 @object = @object.dup
351 @object.update_attributes @new_resource_attrs
352 if not @new_resource_attrs[:name] and @object.respond_to? :name
353 if @object.name and @object.name != ''
354 @object.name = "Copy of #{@object.name}"
366 f.json { render json: @object }
368 redirect_to(params[:return_to] || :back)
373 self.render_error status: 422
378 Thread.current[:user]
382 controller_name.classify.constantize
385 def breadcrumb_page_name
386 (@breadcrumb_page_name ||
387 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
396 %w(Attributes Advanced)
400 @user_is_manager = false
403 if @object.uuid != current_user.andand.uuid
405 @share_links = Link.permissions_for(@object)
406 @user_is_manager = true
407 rescue ArvadosApiClient::AccessForbiddenException,
408 ArvadosApiClient::NotFoundException
414 if not params[:uuids].andand.any?
415 @errors = ["No user/group UUIDs specified to share with."]
416 return render_error(status: 422)
418 results = {"success" => [], "errors" => []}
419 params[:uuids].each do |shared_uuid|
421 Link.create(tail_uuid: shared_uuid, link_class: "permission",
422 name: "can_read", head_uuid: @object.uuid)
423 rescue ArvadosApiClient::ApiError => error
424 error_list = error.api_response.andand[:errors]
425 if error_list.andand.any?
426 results["errors"] += error_list.map { |e| "#{shared_uuid}: #{e}" }
428 error_code = error.api_status || "Bad status"
429 results["errors"] << "#{shared_uuid}: #{error_code} response"
432 results["success"] << shared_uuid
435 if results["errors"].empty?
436 results.delete("errors")
442 f.json { render(json: results, status: status) }
448 helper_method :strip_token_from_path
449 def strip_token_from_path(path)
450 path.sub(/([\?&;])api_token=[^&;]*[&;]?/, '\1')
453 def redirect_to_login
454 if request.xhr? or request.format.json?
455 @errors = ['You are not logged in. Most likely your session has timed out and you need to log in again.']
456 render_error status: 401
457 elsif request.method.in? ['GET', 'HEAD']
458 redirect_to arvados_api_client.arvados_login_url(return_to: strip_token_from_path(request.url))
460 flash[:error] = "Either you are not logged in, or your session has timed out. I can't automatically log you in and re-attempt this request."
463 false # For convenience to return from callbacks
466 def using_specific_api_token(api_token, opts={})
468 [:arvados_api_token, :user].each do |key|
469 start_values[key] = Thread.current[key]
471 if opts.fetch(:load_user, true)
472 load_api_token(api_token)
474 Thread.current[:arvados_api_token] = api_token
475 Thread.current[:user] = nil
480 start_values.each_key { |key| Thread.current[key] = start_values[key] }
485 def accept_uuid_as_id_param
486 if params[:id] and params[:id].match /\D/
487 params[:uuid] = params.delete :id
491 def find_object_by_uuid
495 elsif not params[:uuid].is_a?(String)
496 @object = model_class.where(uuid: params[:uuid]).first
497 elsif params[:uuid].empty?
499 elsif (model_class != Link and
500 resource_class_for_uuid(params[:uuid]) == Link)
501 @name_link = Link.find(params[:uuid])
502 @object = model_class.find(@name_link.head_uuid)
504 @object = model_class.find(params[:uuid])
506 rescue ArvadosApiClient::NotFoundException, ArvadosApiClient::NotLoggedInException, RuntimeError => error
507 if error.is_a?(RuntimeError) and (error.message !~ /^argument to find\(/)
510 render_not_found(error)
517 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
519 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
522 # Set up the thread with the given API token and associated user object.
523 def load_api_token(new_token)
524 Thread.current[:arvados_api_token] = new_token
526 Thread.current[:user] = nil
528 Thread.current[:user] = User.current
532 # If there's a valid api_token parameter, set up the session with that
533 # user's information. Return true if the method redirects the request
534 # (usually a post-login redirect); false otherwise.
535 def setup_user_session
536 return false unless params[:api_token]
537 Thread.current[:arvados_api_token] = params[:api_token]
540 rescue ArvadosApiClient::NotLoggedInException
541 false # We may redirect to login, or not, based on the current action.
543 session[:arvados_api_token] = params[:api_token]
544 # If we later have trouble contacting the API server, we still want
545 # to be able to render basic user information in the UI--see
546 # render_exception above. We store that in the session here. This is
547 # not intended to be used as a general-purpose cache. See #2891.
551 first_name: user.first_name,
552 last_name: user.last_name,
553 is_active: user.is_active,
554 is_admin: user.is_admin,
558 if !request.format.json? and request.method.in? ['GET', 'HEAD']
559 # Repeat this request with api_token in the (new) session
560 # cookie instead of the query string. This prevents API
561 # tokens from appearing in (and being inadvisedly copied
562 # and pasted from) browser Location bars.
563 redirect_to strip_token_from_path(request.fullpath)
569 Thread.current[:arvados_api_token] = nil
573 # Save the session API token in thread-local storage, and yield.
574 # This method also takes care of session setup if the request
575 # provides a valid api_token parameter.
576 # If a token is unavailable or expired, the block is still run, with
578 def set_thread_api_token
579 if Thread.current[:arvados_api_token]
580 yield # An API token has already been found - pass it through.
582 elsif setup_user_session
583 return # A new session was set up and received a response.
587 load_api_token(session[:arvados_api_token])
589 rescue ArvadosApiClient::NotLoggedInException
590 # If we got this error with a token, it must've expired.
591 # Retry the request without a token.
592 unless Thread.current[:arvados_api_token].nil?
597 # Remove token in case this Thread is used for anything else.
602 # Redirect to login/welcome if client provided expired API token (or
604 def require_thread_api_token
605 if Thread.current[:arvados_api_token]
607 elsif session[:arvados_api_token]
608 # Expired session. Clear it before refreshing login so that,
609 # if this login procedure fails, we end up showing the "please
610 # log in" page instead of getting stuck in a redirect loop.
611 session.delete :arvados_api_token
614 # If we redirect to the welcome page, the browser will handle
615 # the 302 by itself and the client code will end up rendering
616 # the "welcome" page in some content area where it doesn't make
617 # sense. Instead, we send 401 ("authenticate and try again" or
618 # "display error", depending on how smart the client side is).
619 @errors = ['You are not logged in.']
620 render_error status: 401
622 redirect_to welcome_users_path(return_to: request.fullpath)
626 def ensure_current_user_is_admin
628 @errors = ['Not logged in']
629 render_error status: 401
630 elsif not current_user.is_admin
631 @errors = ['Permission denied']
632 render_error status: 403
636 helper_method :unsigned_user_agreements
637 def unsigned_user_agreements
638 @signed_ua_uuids ||= UserAgreement.signatures.map &:head_uuid
639 @unsigned_user_agreements ||= UserAgreement.all.map do |ua|
640 if not @signed_ua_uuids.index ua.uuid
641 Collection.find(ua.uuid)
646 def check_user_agreements
647 if current_user && !current_user.is_active
648 if not current_user.is_invited
649 return redirect_to inactive_users_path(return_to: request.fullpath)
651 if unsigned_user_agreements.empty?
652 # No agreements to sign. Perhaps we just need to ask?
653 current_user.activate
654 if !current_user.is_active
655 logger.warn "#{current_user.uuid.inspect}: " +
656 "No user agreements to sign, but activate failed!"
659 if !current_user.is_active
660 redirect_to user_agreements_path(return_to: request.fullpath)
666 def check_user_profile
667 return true if !current_user
668 if request.method.downcase != 'get' || params[:partial] ||
669 params[:tab_pane] || params[:action_method] ||
670 params[:action] == 'setup_popup'
674 if missing_required_profile?
675 redirect_to profile_user_path(current_user.uuid, return_to: request.fullpath)
680 helper_method :missing_required_profile?
681 def missing_required_profile?
682 missing_required = false
684 profile_config = Rails.configuration.user_profile_form_fields
685 if current_user && profile_config
686 current_user_profile = current_user.prefs[:profile]
687 profile_config.kind_of?(Array) && profile_config.andand.each do |entry|
689 if !current_user_profile ||
690 !current_user_profile[entry['key'].to_sym] ||
691 current_user_profile[entry['key'].to_sym].empty?
692 missing_required = true
703 return Rails.configuration.arvados_theme
706 @@notification_tests = []
708 @@notification_tests.push lambda { |controller, current_user|
709 return nil if Rails.configuration.shell_in_a_box_url
710 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
713 return lambda { |view|
714 view.render partial: 'notifications/ssh_key_notification'
718 @@notification_tests.push lambda { |controller, current_user|
719 Collection.limit(1).where(created_by: current_user.uuid).each do
722 return lambda { |view|
723 view.render partial: 'notifications/collections_notification'
727 @@notification_tests.push lambda { |controller, current_user|
728 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
731 return lambda { |view|
732 view.render partial: 'notifications/pipelines_notification'
736 helper_method :user_notifications
737 def user_notifications
738 return [] if @errors or not current_user.andand.is_active
739 @notifications ||= @@notification_tests.map do |t|
740 t.call(self, current_user)
744 helper_method :all_projects
746 @all_projects ||= Group.
747 filter([['group_class','=','project']]).order('name')
750 helper_method :my_projects
752 return @my_projects if @my_projects
755 all_projects.each do |g|
756 root_of[g.uuid] = g.owner_uuid
762 root_of = root_of.each_with_object({}) do |(child, parent), h|
764 h[child] = root_of[parent]
771 @my_projects = @my_projects.select do |g|
772 root_of[g.uuid] == current_user.uuid
776 helper_method :projects_shared_with_me
777 def projects_shared_with_me
778 my_project_uuids = my_projects.collect &:uuid
779 all_projects.reject { |x| x.uuid.in? my_project_uuids }
782 helper_method :recent_jobs_and_pipelines
783 def recent_jobs_and_pipelines
785 PipelineInstance.limit(10)).
787 (x.finished_at || x.started_at rescue nil) || x.modified_at || x.created_at
791 helper_method :running_pipelines
792 def running_pipelines
793 pi = PipelineInstance.order(["started_at asc", "created_at asc"]).filter([["state", "in", ["RunningOnServer", "RunningOnClient"]]])
796 pl.components.each do |k,v|
797 if v.is_a? Hash and v[:job]
798 jobs[v[:job][:uuid]] = {}
804 Job.filter([["uuid", "in", jobs.keys]]).each do |j|
809 pl.components.each do |k,v|
810 if v.is_a? Hash and v[:job]
811 v[:job] = jobs[v[:job][:uuid]]
820 helper_method :finished_pipelines
821 def finished_pipelines lim
822 PipelineInstance.limit(lim).order(["finished_at desc"]).filter([["state", "in", ["Complete", "Failed", "Paused"]], ["finished_at", "!=", nil]])
825 helper_method :recent_collections
826 def recent_collections lim
827 c = Collection.limit(lim).order(["modified_at desc"]).filter([["owner_uuid", "is_a", "arvados#group"]])
829 Group.filter([["uuid", "in", c.map(&:owner_uuid)]]).each do |g|
832 {collections: c, owners: own}
835 # If there are more than 200 projects that are readable by the user,
836 # build the tree using only the top 200+ projects owned by the user.
837 # That is: get toplevel projects under home, get subprojects of
838 # these projects, and so on until we hit the limit
839 def my_wanted_projects page_size=100
840 return @my_wanted_projects if @my_wanted_projects
842 all = Group.filter([['group_class','=','project']]).order('name').limit(page_size)
843 if all.items_available > page_size*3
844 @total_projects = all.items_available
846 uuids = [current_user.uuid]
847 while from_top.size <= page_size*2
848 current_level = Group.filter([['group_class','=','project'],
849 ['owner_uuid', 'in', uuids]])
850 .order('name').limit(page_size*2)
851 break if current_level.results.size == 0
852 from_top.concat current_level.results
853 uuids = current_level.results.collect { |x| x.uuid }
855 @my_wanted_projects = from_top
857 if all.results.size == all.items_available
858 @my_wanted_projects = all
860 @my_wanted_projects = Group.filter([['group_class','=','project']]).order('name')
865 helper_method :my_wanted_projects_tree
866 def my_wanted_projects_tree user, page_size=100
867 build_my_wanted_projects_tree user, page_size
868 [@my_wanted_projects_tree, @total_projects]
871 def build_my_wanted_projects_tree user, page_size=100
872 return @my_wanted_projects_tree if @my_wanted_projects_tree
874 parent_of = {user.uuid => 'me'}
875 my_wanted_projects(page_size).each do |ob|
876 parent_of[ob.uuid] = ob.owner_uuid
878 children_of = {false => [], 'me' => [user]}
879 my_wanted_projects(page_size).each do |ob|
880 if ob.owner_uuid != user.uuid and
881 not parent_of.has_key? ob.owner_uuid
882 parent_of[ob.uuid] = false
884 children_of[parent_of[ob.uuid]] ||= []
885 children_of[parent_of[ob.uuid]] << ob
887 buildtree = lambda do |children_of, root_uuid=false|
889 children_of[root_uuid].andand.each do |ob|
890 tree[ob] = buildtree.call(children_of, ob.uuid)
894 sorted_paths = lambda do |tree, depth=0|
896 tree.keys.sort_by { |ob|
897 ob.is_a?(String) ? ob : ob.friendly_link_name
899 paths << {object: ob, depth: depth}
900 paths += sorted_paths.call tree[ob], depth+1
904 @my_wanted_projects_tree =
905 sorted_paths.call buildtree.call(children_of, 'me')
908 helper_method :my_project_tree
914 helper_method :shared_project_tree
915 def shared_project_tree
920 def build_project_trees
921 return if @my_project_tree and @shared_project_tree
922 parent_of = {current_user.uuid => 'me'}
923 all_projects.each do |ob|
924 parent_of[ob.uuid] = ob.owner_uuid
926 children_of = {false => [], 'me' => [current_user]}
927 all_projects.each do |ob|
928 if ob.owner_uuid != current_user.uuid and
929 not parent_of.has_key? ob.owner_uuid
930 parent_of[ob.uuid] = false
932 children_of[parent_of[ob.uuid]] ||= []
933 children_of[parent_of[ob.uuid]] << ob
935 buildtree = lambda do |children_of, root_uuid=false|
937 children_of[root_uuid].andand.each do |ob|
938 tree[ob] = buildtree.call(children_of, ob.uuid)
942 sorted_paths = lambda do |tree, depth=0|
944 tree.keys.sort_by { |ob|
945 ob.is_a?(String) ? ob : ob.friendly_link_name
947 paths << {object: ob, depth: depth}
948 paths += sorted_paths.call tree[ob], depth+1
953 sorted_paths.call buildtree.call(children_of, 'me')
954 @shared_project_tree =
955 sorted_paths.call({'Projects shared with me' =>
956 buildtree.call(children_of, false)})
959 helper_method :get_object
961 if @get_object.nil? and @objects
962 @get_object = @objects.each_with_object({}) do |object, h|
963 h[object.uuid] = object
970 helper_method :project_breadcrumbs
971 def project_breadcrumbs
973 current = @name_link || @object
975 # Halt if a group ownership loop is detected. API should refuse
976 # to produce this state, but it could still arise from a race
977 # condition when group ownership changes between our find()
979 break if crumbs.collect(&:uuid).include? current.uuid
981 if current.is_a?(Group) and current.group_class == 'project'
982 crumbs.prepend current
984 if current.is_a? Link
985 current = Group.find?(current.tail_uuid)
987 current = Group.find?(current.owner_uuid)
993 helper_method :current_project_uuid
994 def current_project_uuid
995 if @object.is_a? Group and @object.group_class == 'project'
997 elsif @name_link.andand.tail_uuid
999 elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
1006 # helper method to get links for given object or uuid
1007 helper_method :links_for_object
1008 def links_for_object object_or_uuid
1009 raise ArgumentError, 'No input argument' unless object_or_uuid
1010 preload_links_for_objects([object_or_uuid])
1011 uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
1012 @all_links_for[uuid] ||= []
1015 # helper method to preload links for given objects and uuids
1016 helper_method :preload_links_for_objects
1017 def preload_links_for_objects objects_and_uuids
1018 @all_links_for ||= {}
1020 raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
1021 return @all_links_for if objects_and_uuids.empty?
1023 uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
1025 # if already preloaded for all of these uuids, return
1026 if not uuids.select { |x| @all_links_for[x].nil? }.any?
1027 return @all_links_for
1031 @all_links_for[x] = []
1034 # TODO: make sure we get every page of results from API server
1035 Link.filter([['head_uuid', 'in', uuids]]).each do |link|
1036 @all_links_for[link.head_uuid] << link
1041 # helper method to get a certain number of objects of a specific type
1042 # this can be used to replace any uses of: "dataclass.limit(n)"
1043 helper_method :get_n_objects_of_class
1044 def get_n_objects_of_class dataclass, size
1045 @objects_map_for ||= {}
1047 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
1048 raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
1050 # if the objects_map_for has a value for this dataclass, and the
1051 # size used to retrieve those objects is equal, return it
1052 size_key = "#{dataclass.name}_size"
1053 if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
1054 (@objects_map_for[size_key] == size)
1055 return @objects_map_for[dataclass.name]
1058 @objects_map_for[size_key] = size
1059 @objects_map_for[dataclass.name] = dataclass.limit(size)
1062 # helper method to get collections for the given uuid
1063 helper_method :collections_for_object
1064 def collections_for_object uuid
1065 raise ArgumentError, 'No input argument' unless uuid
1066 preload_collections_for_objects([uuid])
1067 @all_collections_for[uuid] ||= []
1070 # helper method to preload collections for the given uuids
1071 helper_method :preload_collections_for_objects
1072 def preload_collections_for_objects uuids
1073 @all_collections_for ||= {}
1075 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
1076 return @all_collections_for if uuids.empty?
1078 # if already preloaded for all of these uuids, return
1079 if not uuids.select { |x| @all_collections_for[x].nil? }.any?
1080 return @all_collections_for
1084 @all_collections_for[x] = []
1087 # TODO: make sure we get every page of results from API server
1088 Collection.where(uuid: uuids).each do |collection|
1089 @all_collections_for[collection.uuid] << collection
1091 @all_collections_for
1094 # helper method to get log collections for the given log
1095 helper_method :log_collections_for_object
1096 def log_collections_for_object log
1097 raise ArgumentError, 'No input argument' unless log
1099 preload_log_collections_for_objects([log])
1102 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
1103 if fixup && fixup.size>1
1107 @all_log_collections_for[uuid] ||= []
1110 # helper method to preload collections for the given uuids
1111 helper_method :preload_log_collections_for_objects
1112 def preload_log_collections_for_objects logs
1113 @all_log_collections_for ||= {}
1115 raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
1116 return @all_log_collections_for if logs.empty?
1120 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
1121 if fixup && fixup.size>1
1128 # if already preloaded for all of these uuids, return
1129 if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
1130 return @all_log_collections_for
1134 @all_log_collections_for[x] = []
1137 # TODO: make sure we get every page of results from API server
1138 Collection.where(uuid: uuids).each do |collection|
1139 @all_log_collections_for[collection.uuid] << collection
1141 @all_log_collections_for
1144 # Helper method to get one collection for the given portable_data_hash
1145 # This is used to determine if a pdh is readable by the current_user
1146 helper_method :collection_for_pdh
1147 def collection_for_pdh pdh
1148 raise ArgumentError, 'No input argument' unless pdh
1149 preload_for_pdhs([pdh])
1150 @all_pdhs_for[pdh] ||= []
1153 # Helper method to preload one collection each for the given pdhs
1154 # This is used to determine if a pdh is readable by the current_user
1155 helper_method :preload_for_pdhs
1156 def preload_for_pdhs pdhs
1157 @all_pdhs_for ||= {}
1159 raise ArgumentError, 'Argument is not an array' unless pdhs.is_a? Array
1160 return @all_pdhs_for if pdhs.empty?
1162 # if already preloaded for all of these pdhs, return
1163 if not pdhs.select { |x| @all_pdhs_for[x].nil? }.any?
1164 return @all_pdhs_for
1168 @all_pdhs_for[x] = []
1171 Collection.select(%w(portable_data_hash)).where(portable_data_hash: pdhs).distinct().each do |collection|
1172 @all_pdhs_for[collection.portable_data_hash] << collection
1177 # helper method to get object of a given dataclass and uuid
1178 helper_method :object_for_dataclass
1179 def object_for_dataclass dataclass, uuid
1180 raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
1181 preload_objects_for_dataclass(dataclass, [uuid])
1185 # helper method to preload objects for given dataclass and uuids
1186 helper_method :preload_objects_for_dataclass
1187 def preload_objects_for_dataclass dataclass, uuids
1190 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
1191 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
1193 return @objects_for if uuids.empty?
1195 # if already preloaded for all of these uuids, return
1196 if not uuids.select { |x| !@objects_for.include?(x) }.any?
1200 # preset all uuids to nil
1202 @objects_for[x] = nil
1204 dataclass.where(uuid: uuids).each do |obj|
1205 @objects_for[obj.uuid] = obj
1210 def wiselinks_layout