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 my_starred_projects current_user
93 build_my_wanted_projects_tree current_user
94 rescue ArvadosApiClient::ApiError
95 # Fall back to the default-setting code later.
98 @starred_projects ||= []
99 @my_wanted_projects_tree ||= []
100 render_error(err_opts)
103 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
104 logger.error e.inspect
105 @errors = ["Path not found"]
106 set_thread_api_token do
107 self.render_error(action: '404', status: 404)
113 # The order can be left empty to allow it to default.
114 # Or it can be a comma separated list of real database column names, one per model.
115 # Column names should always be qualified by a table name and a direction is optional, defaulting to asc
116 # (e.g. "collections.name" or "collections.name desc").
117 # If a column name is specified, that table will be sorted by that column.
118 # If there are objects from different models that will be shown (such as in Pipelines and processes tab),
119 # 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")
120 # Currently only one sort column name and direction can be specified for each model.
121 def load_filters_and_paging_params
122 if params[:order].blank?
123 @order = 'created_at desc'
124 elsif params[:order].is_a? Array
125 @order = params[:order]
128 @order = JSON.load(params[:order])
130 @order = params[:order].split(',')
133 @order = [@order] unless @order.is_a? Array
137 @limit = params[:limit].to_i
142 @offset = params[:offset].to_i
147 filters = params[:filters]
148 if filters.is_a? String
149 filters = Oj.load filters
150 elsif filters.is_a? Array
151 filters = filters.collect do |filter|
152 if filter.is_a? String
153 # Accept filters[]=["foo","=","bar"]
156 # Accept filters=[["foo","=","bar"]]
161 # After this, params[:filters] can be trusted to be an array of arrays:
162 params[:filters] = filters
167 def find_objects_for_index
168 @objects ||= model_class
169 @objects = @objects.filter(@filters).limit(@limit).offset(@offset)
170 @objects.fetch_multiple_pages(false)
177 @next_page_href = next_page_href(partial: params[:partial], filters: @filters.to_json)
179 content: render_to_string(partial: "show_#{params[:partial]}",
181 next_page_href: @next_page_href
184 render json: @objects
189 render_pane params[:tab_pane]
198 helper_method :render_pane
199 def render_pane tab_pane, opts={}
201 partial: 'show_' + tab_pane.downcase,
203 comparable: self.respond_to?(:compare),
206 }.merge(opts[:locals] || {})
209 render_to_string render_opts
216 find_objects_for_index if !@objects
220 helper_method :next_page_offset
221 def next_page_offset objects=nil
225 if objects.respond_to?(:result_offset) and
226 objects.respond_to?(:result_limit) and
227 objects.respond_to?(:items_available)
228 next_offset = objects.result_offset + objects.result_limit
229 if next_offset < objects.items_available
237 helper_method :next_page_href
238 def next_page_href with_params={}
240 url_for with_params.merge(offset: next_page_offset)
244 helper_method :next_page_filters
245 def next_page_filters nextpage_operator
246 next_page_filters = @filters.reject do |attr, op, val|
247 (attr == 'created_at' and op == nextpage_operator) or
248 (attr == 'uuid' and op == 'not in')
252 last_created_at = @objects.last.created_at
255 @objects.each do |obj|
256 last_uuids << obj.uuid if obj.created_at.eql?(last_created_at)
259 next_page_filters += [['created_at', nextpage_operator, last_created_at]]
260 next_page_filters += [['uuid', 'not in', last_uuids]]
268 return render_not_found("object not found")
272 extra_attrs = { href: url_for(action: :show, id: @object) }
273 @object.textile_attributes.each do |textile_attr|
274 extra_attrs.merge!({ "#{textile_attr}Textile" => view_context.render_markup(@object.attributes[textile_attr]) })
276 render json: @object.attributes.merge(extra_attrs)
279 if params['tab_pane']
280 render_pane(if params['tab_pane'].is_a? Hash then params['tab_pane']["name"] else params['tab_pane'] end)
281 elsif request.request_method.in? ['GET', 'HEAD']
284 redirect_to (params[:return_to] ||
285 polymorphic_url(@object,
286 anchor: params[:redirect_to_anchor]))
293 def redirect_to uri, *args
295 if not uri.is_a? String
296 uri = polymorphic_url(uri)
298 render json: {href: uri}
305 params[:limit] ||= 40
309 find_objects_for_index if !@objects
311 content: render_to_string(partial: "choose_rows.html",
313 next_page_href: next_page_href(partial: params[:partial])
318 find_objects_for_index if !@objects
319 render partial: 'choose', locals: {multiple: params[:multiple]}
326 return render_not_found("object not found")
331 @object = model_class.new
335 @updates ||= params[@object.resource_param_name.to_sym]
336 @updates.keys.each do |attr|
337 if @object.send(attr).is_a? Hash
338 if @updates[attr].is_a? String
339 @updates[attr] = Oj.load @updates[attr]
341 if params[:merge] || params["merge_#{attr}".to_sym]
342 # Merge provided Hash with current Hash, instead of
344 @updates[attr] = @object.send(attr).with_indifferent_access.
345 deep_merge(@updates[attr].with_indifferent_access)
349 if @object.update_attributes @updates
352 self.render_error status: 422
357 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
358 @new_resource_attrs ||= {}
359 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
360 @object ||= model_class.new @new_resource_attrs, params["options"]
365 render_error status: 422
369 # Clone the given object, merging any attribute values supplied as
370 # with a create action.
372 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
373 @new_resource_attrs ||= {}
374 @object = @object.dup
375 @object.update_attributes @new_resource_attrs
376 if not @new_resource_attrs[:name] and @object.respond_to? :name
377 if @object.name and @object.name != ''
378 @object.name = "Copy of #{@object.name}"
390 f.json { render json: @object }
392 redirect_to(params[:return_to] || :back)
397 self.render_error status: 422
402 Thread.current[:user]
406 controller_name.classify.constantize
409 def breadcrumb_page_name
410 (@breadcrumb_page_name ||
411 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
420 %w(Attributes Advanced)
424 @user_is_manager = false
427 if @object.uuid != current_user.andand.uuid
429 @share_links = Link.permissions_for(@object)
430 @user_is_manager = true
431 rescue ArvadosApiClient::AccessForbiddenException,
432 ArvadosApiClient::NotFoundException
438 if not params[:uuids].andand.any?
439 @errors = ["No user/group UUIDs specified to share with."]
440 return render_error(status: 422)
442 results = {"success" => [], "errors" => []}
443 params[:uuids].each do |shared_uuid|
445 Link.create(tail_uuid: shared_uuid, link_class: "permission",
446 name: "can_read", head_uuid: @object.uuid)
447 rescue ArvadosApiClient::ApiError => error
448 error_list = error.api_response.andand[:errors]
449 if error_list.andand.any?
450 results["errors"] += error_list.map { |e| "#{shared_uuid}: #{e}" }
452 error_code = error.api_status || "Bad status"
453 results["errors"] << "#{shared_uuid}: #{error_code} response"
456 results["success"] << shared_uuid
459 if results["errors"].empty?
460 results.delete("errors")
466 f.json { render(json: results, status: status) }
470 helper_method :is_starred
472 links = Link.where(tail_uuid: current_user.uuid,
473 head_uuid: @object.uuid,
476 return links.andand.any?
481 helper_method :strip_token_from_path
482 def strip_token_from_path(path)
483 path.sub(/([\?&;])api_token=[^&;]*[&;]?/, '\1')
486 def redirect_to_login
487 if request.xhr? or request.format.json?
488 @errors = ['You are not logged in. Most likely your session has timed out and you need to log in again.']
489 render_error status: 401
490 elsif request.method.in? ['GET', 'HEAD']
491 redirect_to arvados_api_client.arvados_login_url(return_to: strip_token_from_path(request.url))
493 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."
496 false # For convenience to return from callbacks
499 def using_specific_api_token(api_token, opts={})
501 [:arvados_api_token, :user].each do |key|
502 start_values[key] = Thread.current[key]
504 if opts.fetch(:load_user, true)
505 load_api_token(api_token)
507 Thread.current[:arvados_api_token] = api_token
508 Thread.current[:user] = nil
513 start_values.each_key { |key| Thread.current[key] = start_values[key] }
518 def accept_uuid_as_id_param
519 if params[:id] and params[:id].match /\D/
520 params[:uuid] = params.delete :id
524 def find_object_by_uuid
528 elsif not params[:uuid].is_a?(String)
529 @object = model_class.where(uuid: params[:uuid]).first
530 elsif params[:uuid].empty?
532 elsif (model_class != Link and
533 resource_class_for_uuid(params[:uuid]) == Link)
534 @name_link = Link.find(params[:uuid])
535 @object = model_class.find(@name_link.head_uuid)
537 @object = model_class.find(params[:uuid])
539 rescue ArvadosApiClient::NotFoundException, ArvadosApiClient::NotLoggedInException, RuntimeError => error
540 if error.is_a?(RuntimeError) and (error.message !~ /^argument to find\(/)
543 render_not_found(error)
550 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
552 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
555 # Set up the thread with the given API token and associated user object.
556 def load_api_token(new_token)
557 Thread.current[:arvados_api_token] = new_token
559 Thread.current[:user] = nil
561 Thread.current[:user] = User.current
565 # If there's a valid api_token parameter, set up the session with that
566 # user's information. Return true if the method redirects the request
567 # (usually a post-login redirect); false otherwise.
568 def setup_user_session
569 return false unless params[:api_token]
570 Thread.current[:arvados_api_token] = params[:api_token]
573 rescue ArvadosApiClient::NotLoggedInException
574 false # We may redirect to login, or not, based on the current action.
576 session[:arvados_api_token] = params[:api_token]
577 # If we later have trouble contacting the API server, we still want
578 # to be able to render basic user information in the UI--see
579 # render_exception above. We store that in the session here. This is
580 # not intended to be used as a general-purpose cache. See #2891.
584 first_name: user.first_name,
585 last_name: user.last_name,
586 is_active: user.is_active,
587 is_admin: user.is_admin,
591 if !request.format.json? and request.method.in? ['GET', 'HEAD']
592 # Repeat this request with api_token in the (new) session
593 # cookie instead of the query string. This prevents API
594 # tokens from appearing in (and being inadvisedly copied
595 # and pasted from) browser Location bars.
596 redirect_to strip_token_from_path(request.fullpath)
602 Thread.current[:arvados_api_token] = nil
606 # Save the session API token in thread-local storage, and yield.
607 # This method also takes care of session setup if the request
608 # provides a valid api_token parameter.
609 # If a token is unavailable or expired, the block is still run, with
611 def set_thread_api_token
612 if Thread.current[:arvados_api_token]
613 yield # An API token has already been found - pass it through.
615 elsif setup_user_session
616 return # A new session was set up and received a response.
620 load_api_token(session[:arvados_api_token])
622 rescue ArvadosApiClient::NotLoggedInException
623 # If we got this error with a token, it must've expired.
624 # Retry the request without a token.
625 unless Thread.current[:arvados_api_token].nil?
630 # Remove token in case this Thread is used for anything else.
635 # Redirect to login/welcome if client provided expired API token (or
637 def require_thread_api_token
638 if Thread.current[:arvados_api_token]
640 elsif session[:arvados_api_token]
641 # Expired session. Clear it before refreshing login so that,
642 # if this login procedure fails, we end up showing the "please
643 # log in" page instead of getting stuck in a redirect loop.
644 session.delete :arvados_api_token
647 # If we redirect to the welcome page, the browser will handle
648 # the 302 by itself and the client code will end up rendering
649 # the "welcome" page in some content area where it doesn't make
650 # sense. Instead, we send 401 ("authenticate and try again" or
651 # "display error", depending on how smart the client side is).
652 @errors = ['You are not logged in.']
653 render_error status: 401
655 redirect_to welcome_users_path(return_to: request.fullpath)
659 def ensure_current_user_is_admin
661 @errors = ['Not logged in']
662 render_error status: 401
663 elsif not current_user.is_admin
664 @errors = ['Permission denied']
665 render_error status: 403
669 helper_method :unsigned_user_agreements
670 def unsigned_user_agreements
671 @signed_ua_uuids ||= UserAgreement.signatures.map &:head_uuid
672 @unsigned_user_agreements ||= UserAgreement.all.map do |ua|
673 if not @signed_ua_uuids.index ua.uuid
674 Collection.find(ua.uuid)
679 def check_user_agreements
680 if current_user && !current_user.is_active
681 if not current_user.is_invited
682 return redirect_to inactive_users_path(return_to: request.fullpath)
684 if unsigned_user_agreements.empty?
685 # No agreements to sign. Perhaps we just need to ask?
686 current_user.activate
687 if !current_user.is_active
688 logger.warn "#{current_user.uuid.inspect}: " +
689 "No user agreements to sign, but activate failed!"
692 if !current_user.is_active
693 redirect_to user_agreements_path(return_to: request.fullpath)
699 def check_user_profile
700 return true if !current_user
701 if request.method.downcase != 'get' || params[:partial] ||
702 params[:tab_pane] || params[:action_method] ||
703 params[:action] == 'setup_popup'
707 if missing_required_profile?
708 redirect_to profile_user_path(current_user.uuid, return_to: request.fullpath)
713 helper_method :missing_required_profile?
714 def missing_required_profile?
715 missing_required = false
717 profile_config = Rails.configuration.user_profile_form_fields
718 if current_user && profile_config
719 current_user_profile = current_user.prefs[:profile]
720 profile_config.kind_of?(Array) && profile_config.andand.each do |entry|
722 if !current_user_profile ||
723 !current_user_profile[entry['key'].to_sym] ||
724 current_user_profile[entry['key'].to_sym].empty?
725 missing_required = true
736 return Rails.configuration.arvados_theme
739 @@notification_tests = []
741 @@notification_tests.push lambda { |controller, current_user|
742 return nil if Rails.configuration.shell_in_a_box_url
743 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
746 return lambda { |view|
747 view.render partial: 'notifications/ssh_key_notification'
751 @@notification_tests.push lambda { |controller, current_user|
752 Collection.limit(1).where(created_by: current_user.uuid).each do
755 return lambda { |view|
756 view.render partial: 'notifications/collections_notification'
760 @@notification_tests.push lambda { |controller, current_user|
761 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
764 return lambda { |view|
765 view.render partial: 'notifications/pipelines_notification'
769 helper_method :user_notifications
770 def user_notifications
771 return [] if @errors or not current_user.andand.is_active
772 @notifications ||= @@notification_tests.map do |t|
773 t.call(self, current_user)
777 helper_method :all_projects
779 @all_projects ||= Group.
780 filter([['group_class','=','project']]).order('name')
783 helper_method :my_projects
785 return @my_projects if @my_projects
788 all_projects.each do |g|
789 root_of[g.uuid] = g.owner_uuid
795 root_of = root_of.each_with_object({}) do |(child, parent), h|
797 h[child] = root_of[parent]
804 @my_projects = @my_projects.select do |g|
805 root_of[g.uuid] == current_user.uuid
809 helper_method :projects_shared_with_me
810 def projects_shared_with_me
811 my_project_uuids = my_projects.collect &:uuid
812 all_projects.reject { |x| x.uuid.in? my_project_uuids }
815 helper_method :recent_jobs_and_pipelines
816 def recent_jobs_and_pipelines
818 PipelineInstance.limit(10)).
820 (x.finished_at || x.started_at rescue nil) || x.modified_at || x.created_at
824 helper_method :running_pipelines
825 def running_pipelines
826 pi = PipelineInstance.order(["started_at asc", "created_at asc"]).filter([["state", "in", ["RunningOnServer", "RunningOnClient"]]])
829 pl.components.each do |k,v|
830 if v.is_a? Hash and v[:job]
831 jobs[v[:job][:uuid]] = {}
837 Job.filter([["uuid", "in", jobs.keys]]).each do |j|
842 pl.components.each do |k,v|
843 if v.is_a? Hash and v[:job]
844 v[:job] = jobs[v[:job][:uuid]]
853 helper_method :recent_processes
854 def recent_processes lim
857 pipelines = PipelineInstance.limit(lim).order(["created_at desc"])
859 crs = ContainerRequest.limit(lim).order(["created_at desc"]).filter([["requesting_container_uuid", "=", nil]])
861 pipelines.results.each { |pi| procs[pi] = pi.created_at }
862 crs.results.each { |c| procs[c] = c.created_at }
864 Hash[procs.sort_by {|key, value| value}].keys.reverse.first(lim)
867 helper_method :recent_collections
868 def recent_collections lim
869 c = Collection.limit(lim).order(["modified_at desc"]).filter([["owner_uuid", "is_a", "arvados#group"]])
871 Group.filter([["uuid", "in", c.map(&:owner_uuid)]]).each do |g|
874 {collections: c, owners: own}
877 helper_method :my_starred_projects
878 def my_starred_projects user
879 return if @starred_projects
880 links = Link.filter([['tail_uuid', '=', user.uuid],
881 ['link_class', '=', 'star'],
882 ['head_uuid', 'is_a', 'arvados#group']]).select(%w(head_uuid))
883 uuids = links.collect { |x| x.head_uuid }
884 starred_projects = Group.filter([['uuid', 'in', uuids]]).order('name')
885 @starred_projects = starred_projects.results
888 # If there are more than 200 projects that are readable by the user,
889 # build the tree using only the top 200+ projects owned by the user,
890 # from the top three levels.
891 # That is: get toplevel projects under home, get subprojects of
892 # these projects, and so on until we hit the limit.
893 def my_wanted_projects user, page_size=100
894 return @my_wanted_projects if @my_wanted_projects
899 @too_many_projects = false
900 @reached_level_limit = false
901 while from_top.size <= page_size*2
902 current_level = Group.filter([['group_class','=','project'],
903 ['owner_uuid', 'in', uuids]])
904 .order('name').limit(page_size*2)
905 break if current_level.results.size == 0
906 @too_many_projects = true if current_level.items_available > current_level.results.size
907 from_top.concat current_level.results
908 uuids = current_level.results.collect { |x| x.uuid }
911 @reached_level_limit = true
915 @my_wanted_projects = from_top
918 helper_method :my_wanted_projects_tree
919 def my_wanted_projects_tree user, page_size=100
920 build_my_wanted_projects_tree user, page_size
921 [@my_wanted_projects_tree, @too_many_projects, @reached_level_limit]
924 def build_my_wanted_projects_tree user, page_size=100
925 return @my_wanted_projects_tree if @my_wanted_projects_tree
927 parent_of = {user.uuid => 'me'}
928 my_wanted_projects(user, page_size).each do |ob|
929 parent_of[ob.uuid] = ob.owner_uuid
931 children_of = {false => [], 'me' => [user]}
932 my_wanted_projects(user, page_size).each do |ob|
933 if ob.owner_uuid != user.uuid and
934 not parent_of.has_key? ob.owner_uuid
935 parent_of[ob.uuid] = false
937 children_of[parent_of[ob.uuid]] ||= []
938 children_of[parent_of[ob.uuid]] << ob
940 buildtree = lambda do |children_of, root_uuid=false|
942 children_of[root_uuid].andand.each do |ob|
943 tree[ob] = buildtree.call(children_of, ob.uuid)
947 sorted_paths = lambda do |tree, depth=0|
949 tree.keys.sort_by { |ob|
950 ob.is_a?(String) ? ob : ob.friendly_link_name
952 paths << {object: ob, depth: depth}
953 paths += sorted_paths.call tree[ob], depth+1
957 @my_wanted_projects_tree =
958 sorted_paths.call buildtree.call(children_of, 'me')
961 helper_method :get_object
963 if @get_object.nil? and @objects
964 @get_object = @objects.each_with_object({}) do |object, h|
965 h[object.uuid] = object
972 helper_method :project_breadcrumbs
973 def project_breadcrumbs
975 current = @name_link || @object
977 # Halt if a group ownership loop is detected. API should refuse
978 # to produce this state, but it could still arise from a race
979 # condition when group ownership changes between our find()
981 break if crumbs.collect(&:uuid).include? current.uuid
983 if current.is_a?(Group) and current.group_class == 'project'
984 crumbs.prepend current
986 if current.is_a? Link
987 current = Group.find?(current.tail_uuid)
989 current = Group.find?(current.owner_uuid)
995 helper_method :current_project_uuid
996 def current_project_uuid
997 if @object.is_a? Group and @object.group_class == 'project'
999 elsif @name_link.andand.tail_uuid
1000 @name_link.tail_uuid
1001 elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
1008 # helper method to get links for given object or uuid
1009 helper_method :links_for_object
1010 def links_for_object object_or_uuid
1011 raise ArgumentError, 'No input argument' unless object_or_uuid
1012 preload_links_for_objects([object_or_uuid])
1013 uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
1014 @all_links_for[uuid] ||= []
1017 # helper method to preload links for given objects and uuids
1018 helper_method :preload_links_for_objects
1019 def preload_links_for_objects objects_and_uuids
1020 @all_links_for ||= {}
1022 raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
1023 return @all_links_for if objects_and_uuids.empty?
1025 uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
1027 # if already preloaded for all of these uuids, return
1028 if not uuids.select { |x| @all_links_for[x].nil? }.any?
1029 return @all_links_for
1033 @all_links_for[x] = []
1036 # TODO: make sure we get every page of results from API server
1037 Link.filter([['head_uuid', 'in', uuids]]).each do |link|
1038 @all_links_for[link.head_uuid] << link
1043 # helper method to get a certain number of objects of a specific type
1044 # this can be used to replace any uses of: "dataclass.limit(n)"
1045 helper_method :get_n_objects_of_class
1046 def get_n_objects_of_class dataclass, size
1047 @objects_map_for ||= {}
1049 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
1050 raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
1052 # if the objects_map_for has a value for this dataclass, and the
1053 # size used to retrieve those objects is equal, return it
1054 size_key = "#{dataclass.name}_size"
1055 if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
1056 (@objects_map_for[size_key] == size)
1057 return @objects_map_for[dataclass.name]
1060 @objects_map_for[size_key] = size
1061 @objects_map_for[dataclass.name] = dataclass.limit(size)
1064 # helper method to get collections for the given uuid
1065 helper_method :collections_for_object
1066 def collections_for_object uuid
1067 raise ArgumentError, 'No input argument' unless uuid
1068 preload_collections_for_objects([uuid])
1069 @all_collections_for[uuid] ||= []
1072 # helper method to preload collections for the given uuids
1073 helper_method :preload_collections_for_objects
1074 def preload_collections_for_objects uuids
1075 @all_collections_for ||= {}
1077 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
1078 return @all_collections_for if uuids.empty?
1080 # if already preloaded for all of these uuids, return
1081 if not uuids.select { |x| @all_collections_for[x].nil? }.any?
1082 return @all_collections_for
1086 @all_collections_for[x] = []
1089 # TODO: make sure we get every page of results from API server
1090 Collection.where(uuid: uuids).each do |collection|
1091 @all_collections_for[collection.uuid] << collection
1093 @all_collections_for
1096 # helper method to get log collections for the given log
1097 helper_method :log_collections_for_object
1098 def log_collections_for_object log
1099 raise ArgumentError, 'No input argument' unless log
1101 preload_log_collections_for_objects([log])
1104 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
1105 if fixup && fixup.size>1
1109 @all_log_collections_for[uuid] ||= []
1112 # helper method to preload collections for the given uuids
1113 helper_method :preload_log_collections_for_objects
1114 def preload_log_collections_for_objects logs
1115 @all_log_collections_for ||= {}
1117 raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
1118 return @all_log_collections_for if logs.empty?
1122 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
1123 if fixup && fixup.size>1
1130 # if already preloaded for all of these uuids, return
1131 if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
1132 return @all_log_collections_for
1136 @all_log_collections_for[x] = []
1139 # TODO: make sure we get every page of results from API server
1140 Collection.where(uuid: uuids).each do |collection|
1141 @all_log_collections_for[collection.uuid] << collection
1143 @all_log_collections_for
1146 # Helper method to get one collection for the given portable_data_hash
1147 # This is used to determine if a pdh is readable by the current_user
1148 helper_method :collection_for_pdh
1149 def collection_for_pdh pdh
1150 raise ArgumentError, 'No input argument' unless pdh
1151 preload_for_pdhs([pdh])
1152 @all_pdhs_for[pdh] ||= []
1155 # Helper method to preload one collection each for the given pdhs
1156 # This is used to determine if a pdh is readable by the current_user
1157 helper_method :preload_for_pdhs
1158 def preload_for_pdhs pdhs
1159 @all_pdhs_for ||= {}
1161 raise ArgumentError, 'Argument is not an array' unless pdhs.is_a? Array
1162 return @all_pdhs_for if pdhs.empty?
1164 # if already preloaded for all of these pdhs, return
1165 if not pdhs.select { |x| @all_pdhs_for[x].nil? }.any?
1166 return @all_pdhs_for
1170 @all_pdhs_for[x] = []
1173 Collection.select(%w(portable_data_hash)).where(portable_data_hash: pdhs).distinct().each do |collection|
1174 @all_pdhs_for[collection.portable_data_hash] << collection
1179 # helper method to get object of a given dataclass and uuid
1180 helper_method :object_for_dataclass
1181 def object_for_dataclass dataclass, uuid
1182 raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
1183 preload_objects_for_dataclass(dataclass, [uuid])
1187 # helper method to preload objects for given dataclass and uuids
1188 helper_method :preload_objects_for_dataclass
1189 def preload_objects_for_dataclass dataclass, uuids
1192 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
1193 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
1195 return @objects_for if uuids.empty?
1197 # if already preloaded for all of these uuids, return
1198 if not uuids.select { |x| !@objects_for.include?(x) }.any?
1202 # preset all uuids to nil
1204 @objects_for[x] = nil
1206 dataclass.where(uuid: uuids).each do |obj|
1207 @objects_for[obj.uuid] = obj
1212 def wiselinks_layout