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 Jobs and Pipelines 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)
246 return render_not_found("object not found")
250 extra_attrs = { href: url_for(action: :show, id: @object) }
251 @object.textile_attributes.each do |textile_attr|
252 extra_attrs.merge!({ "#{textile_attr}Textile" => view_context.render_markup(@object.attributes[textile_attr]) })
254 render json: @object.attributes.merge(extra_attrs)
257 if params['tab_pane']
258 render_pane(if params['tab_pane'].is_a? Hash then params['tab_pane']["name"] else params['tab_pane'] end)
259 elsif request.request_method.in? ['GET', 'HEAD']
262 redirect_to (params[:return_to] ||
263 polymorphic_url(@object,
264 anchor: params[:redirect_to_anchor]))
271 def redirect_to uri, *args
273 if not uri.is_a? String
274 uri = polymorphic_url(uri)
276 render json: {href: uri}
283 params[:limit] ||= 40
287 find_objects_for_index if !@objects
289 content: render_to_string(partial: "choose_rows.html",
291 next_page_href: next_page_href(partial: params[:partial])
296 find_objects_for_index if !@objects
297 render partial: 'choose', locals: {multiple: params[:multiple]}
304 return render_not_found("object not found")
309 @object = model_class.new
313 @updates ||= params[@object.resource_param_name.to_sym]
314 @updates.keys.each do |attr|
315 if @object.send(attr).is_a? Hash
316 if @updates[attr].is_a? String
317 @updates[attr] = Oj.load @updates[attr]
319 if params[:merge] || params["merge_#{attr}".to_sym]
320 # Merge provided Hash with current Hash, instead of
322 @updates[attr] = @object.send(attr).with_indifferent_access.
323 deep_merge(@updates[attr].with_indifferent_access)
327 if @object.update_attributes @updates
330 self.render_error status: 422
335 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
336 @new_resource_attrs ||= {}
337 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
338 @object ||= model_class.new @new_resource_attrs, params["options"]
343 render_error status: 422
347 # Clone the given object, merging any attribute values supplied as
348 # with a create action.
350 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
351 @new_resource_attrs ||= {}
352 @object = @object.dup
353 @object.update_attributes @new_resource_attrs
354 if not @new_resource_attrs[:name] and @object.respond_to? :name
355 if @object.name and @object.name != ''
356 @object.name = "Copy of #{@object.name}"
368 f.json { render json: @object }
370 redirect_to(params[:return_to] || :back)
375 self.render_error status: 422
380 Thread.current[:user]
384 controller_name.classify.constantize
387 def breadcrumb_page_name
388 (@breadcrumb_page_name ||
389 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
398 %w(Attributes Advanced)
402 @user_is_manager = false
405 if @object.uuid != current_user.andand.uuid
407 @share_links = Link.permissions_for(@object)
408 @user_is_manager = true
409 rescue ArvadosApiClient::AccessForbiddenException,
410 ArvadosApiClient::NotFoundException
416 if not params[:uuids].andand.any?
417 @errors = ["No user/group UUIDs specified to share with."]
418 return render_error(status: 422)
420 results = {"success" => [], "errors" => []}
421 params[:uuids].each do |shared_uuid|
423 Link.create(tail_uuid: shared_uuid, link_class: "permission",
424 name: "can_read", head_uuid: @object.uuid)
425 rescue ArvadosApiClient::ApiError => error
426 error_list = error.api_response.andand[:errors]
427 if error_list.andand.any?
428 results["errors"] += error_list.map { |e| "#{shared_uuid}: #{e}" }
430 error_code = error.api_status || "Bad status"
431 results["errors"] << "#{shared_uuid}: #{error_code} response"
434 results["success"] << shared_uuid
437 if results["errors"].empty?
438 results.delete("errors")
444 f.json { render(json: results, status: status) }
448 helper_method :is_starred
450 links = Link.where(tail_uuid: current_user.uuid,
451 head_uuid: @object.uuid,
454 return links.andand.any?
459 helper_method :strip_token_from_path
460 def strip_token_from_path(path)
461 path.sub(/([\?&;])api_token=[^&;]*[&;]?/, '\1')
464 def redirect_to_login
465 if request.xhr? or request.format.json?
466 @errors = ['You are not logged in. Most likely your session has timed out and you need to log in again.']
467 render_error status: 401
468 elsif request.method.in? ['GET', 'HEAD']
469 redirect_to arvados_api_client.arvados_login_url(return_to: strip_token_from_path(request.url))
471 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."
474 false # For convenience to return from callbacks
477 def using_specific_api_token(api_token, opts={})
479 [:arvados_api_token, :user].each do |key|
480 start_values[key] = Thread.current[key]
482 if opts.fetch(:load_user, true)
483 load_api_token(api_token)
485 Thread.current[:arvados_api_token] = api_token
486 Thread.current[:user] = nil
491 start_values.each_key { |key| Thread.current[key] = start_values[key] }
496 def accept_uuid_as_id_param
497 if params[:id] and params[:id].match /\D/
498 params[:uuid] = params.delete :id
502 def find_object_by_uuid
506 elsif not params[:uuid].is_a?(String)
507 @object = model_class.where(uuid: params[:uuid]).first
508 elsif params[:uuid].empty?
510 elsif (model_class != Link and
511 resource_class_for_uuid(params[:uuid]) == Link)
512 @name_link = Link.find(params[:uuid])
513 @object = model_class.find(@name_link.head_uuid)
515 @object = model_class.find(params[:uuid])
517 rescue ArvadosApiClient::NotFoundException, ArvadosApiClient::NotLoggedInException, RuntimeError => error
518 if error.is_a?(RuntimeError) and (error.message !~ /^argument to find\(/)
521 render_not_found(error)
528 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
530 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
533 # Set up the thread with the given API token and associated user object.
534 def load_api_token(new_token)
535 Thread.current[:arvados_api_token] = new_token
537 Thread.current[:user] = nil
539 Thread.current[:user] = User.current
543 # If there's a valid api_token parameter, set up the session with that
544 # user's information. Return true if the method redirects the request
545 # (usually a post-login redirect); false otherwise.
546 def setup_user_session
547 return false unless params[:api_token]
548 Thread.current[:arvados_api_token] = params[:api_token]
551 rescue ArvadosApiClient::NotLoggedInException
552 false # We may redirect to login, or not, based on the current action.
554 session[:arvados_api_token] = params[:api_token]
555 # If we later have trouble contacting the API server, we still want
556 # to be able to render basic user information in the UI--see
557 # render_exception above. We store that in the session here. This is
558 # not intended to be used as a general-purpose cache. See #2891.
562 first_name: user.first_name,
563 last_name: user.last_name,
564 is_active: user.is_active,
565 is_admin: user.is_admin,
569 if !request.format.json? and request.method.in? ['GET', 'HEAD']
570 # Repeat this request with api_token in the (new) session
571 # cookie instead of the query string. This prevents API
572 # tokens from appearing in (and being inadvisedly copied
573 # and pasted from) browser Location bars.
574 redirect_to strip_token_from_path(request.fullpath)
580 Thread.current[:arvados_api_token] = nil
584 # Save the session API token in thread-local storage, and yield.
585 # This method also takes care of session setup if the request
586 # provides a valid api_token parameter.
587 # If a token is unavailable or expired, the block is still run, with
589 def set_thread_api_token
590 if Thread.current[:arvados_api_token]
591 yield # An API token has already been found - pass it through.
593 elsif setup_user_session
594 return # A new session was set up and received a response.
598 load_api_token(session[:arvados_api_token])
600 rescue ArvadosApiClient::NotLoggedInException
601 # If we got this error with a token, it must've expired.
602 # Retry the request without a token.
603 unless Thread.current[:arvados_api_token].nil?
608 # Remove token in case this Thread is used for anything else.
613 # Redirect to login/welcome if client provided expired API token (or
615 def require_thread_api_token
616 if Thread.current[:arvados_api_token]
618 elsif session[:arvados_api_token]
619 # Expired session. Clear it before refreshing login so that,
620 # if this login procedure fails, we end up showing the "please
621 # log in" page instead of getting stuck in a redirect loop.
622 session.delete :arvados_api_token
625 # If we redirect to the welcome page, the browser will handle
626 # the 302 by itself and the client code will end up rendering
627 # the "welcome" page in some content area where it doesn't make
628 # sense. Instead, we send 401 ("authenticate and try again" or
629 # "display error", depending on how smart the client side is).
630 @errors = ['You are not logged in.']
631 render_error status: 401
633 redirect_to welcome_users_path(return_to: request.fullpath)
637 def ensure_current_user_is_admin
639 @errors = ['Not logged in']
640 render_error status: 401
641 elsif not current_user.is_admin
642 @errors = ['Permission denied']
643 render_error status: 403
647 helper_method :unsigned_user_agreements
648 def unsigned_user_agreements
649 @signed_ua_uuids ||= UserAgreement.signatures.map &:head_uuid
650 @unsigned_user_agreements ||= UserAgreement.all.map do |ua|
651 if not @signed_ua_uuids.index ua.uuid
652 Collection.find(ua.uuid)
657 def check_user_agreements
658 if current_user && !current_user.is_active
659 if not current_user.is_invited
660 return redirect_to inactive_users_path(return_to: request.fullpath)
662 if unsigned_user_agreements.empty?
663 # No agreements to sign. Perhaps we just need to ask?
664 current_user.activate
665 if !current_user.is_active
666 logger.warn "#{current_user.uuid.inspect}: " +
667 "No user agreements to sign, but activate failed!"
670 if !current_user.is_active
671 redirect_to user_agreements_path(return_to: request.fullpath)
677 def check_user_profile
678 return true if !current_user
679 if request.method.downcase != 'get' || params[:partial] ||
680 params[:tab_pane] || params[:action_method] ||
681 params[:action] == 'setup_popup'
685 if missing_required_profile?
686 redirect_to profile_user_path(current_user.uuid, return_to: request.fullpath)
691 helper_method :missing_required_profile?
692 def missing_required_profile?
693 missing_required = false
695 profile_config = Rails.configuration.user_profile_form_fields
696 if current_user && profile_config
697 current_user_profile = current_user.prefs[:profile]
698 profile_config.kind_of?(Array) && profile_config.andand.each do |entry|
700 if !current_user_profile ||
701 !current_user_profile[entry['key'].to_sym] ||
702 current_user_profile[entry['key'].to_sym].empty?
703 missing_required = true
714 return Rails.configuration.arvados_theme
717 @@notification_tests = []
719 @@notification_tests.push lambda { |controller, current_user|
720 return nil if Rails.configuration.shell_in_a_box_url
721 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
724 return lambda { |view|
725 view.render partial: 'notifications/ssh_key_notification'
729 @@notification_tests.push lambda { |controller, current_user|
730 Collection.limit(1).where(created_by: current_user.uuid).each do
733 return lambda { |view|
734 view.render partial: 'notifications/collections_notification'
738 @@notification_tests.push lambda { |controller, current_user|
739 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
742 return lambda { |view|
743 view.render partial: 'notifications/pipelines_notification'
747 helper_method :user_notifications
748 def user_notifications
749 return [] if @errors or not current_user.andand.is_active
750 @notifications ||= @@notification_tests.map do |t|
751 t.call(self, current_user)
755 helper_method :all_projects
757 @all_projects ||= Group.
758 filter([['group_class','=','project']]).order('name')
761 helper_method :my_projects
763 return @my_projects if @my_projects
766 all_projects.each do |g|
767 root_of[g.uuid] = g.owner_uuid
773 root_of = root_of.each_with_object({}) do |(child, parent), h|
775 h[child] = root_of[parent]
782 @my_projects = @my_projects.select do |g|
783 root_of[g.uuid] == current_user.uuid
787 helper_method :projects_shared_with_me
788 def projects_shared_with_me
789 my_project_uuids = my_projects.collect &:uuid
790 all_projects.reject { |x| x.uuid.in? my_project_uuids }
793 helper_method :recent_jobs_and_pipelines
794 def recent_jobs_and_pipelines
796 PipelineInstance.limit(10)).
798 (x.finished_at || x.started_at rescue nil) || x.modified_at || x.created_at
802 helper_method :running_pipelines
803 def running_pipelines
804 pi = PipelineInstance.order(["started_at asc", "created_at asc"]).filter([["state", "in", ["RunningOnServer", "RunningOnClient"]]])
807 pl.components.each do |k,v|
808 if v.is_a? Hash and v[:job]
809 jobs[v[:job][:uuid]] = {}
815 Job.filter([["uuid", "in", jobs.keys]]).each do |j|
820 pl.components.each do |k,v|
821 if v.is_a? Hash and v[:job]
822 v[:job] = jobs[v[:job][:uuid]]
831 helper_method :recent_processes
832 def recent_processes lim
835 pipelines = PipelineInstance.limit(lim).order(["created_at desc"])
837 crs = ContainerRequest.limit(lim).order(["created_at desc"]).filter([["requesting_container_uuid", "=", nil]])
838 cr_uuids = crs.results.collect { |c| c.container_uuid }
839 containers = Container.order(["created_at desc"]).results if cr_uuids.any?
842 pipelines.results.each { |pi| procs[pi] = pi.created_at }
843 containers.each { |c| procs[c] = c.created_at } if !containers.nil?
845 Hash[procs.sort_by {|key, value| value}].keys.reverse.first(lim)
848 helper_method :recent_collections
849 def recent_collections lim
850 c = Collection.limit(lim).order(["modified_at desc"]).filter([["owner_uuid", "is_a", "arvados#group"]])
852 Group.filter([["uuid", "in", c.map(&:owner_uuid)]]).each do |g|
855 {collections: c, owners: own}
858 helper_method :my_starred_projects
859 def my_starred_projects user
860 return if @starred_projects
861 links = Link.filter([['tail_uuid', '=', user.uuid],
862 ['link_class', '=', 'star'],
863 ['head_uuid', 'is_a', 'arvados#group']]).select(%w(head_uuid))
864 uuids = links.collect { |x| x.head_uuid }
865 starred_projects = Group.filter([['uuid', 'in', uuids]]).order('name')
866 @starred_projects = starred_projects.results
869 # If there are more than 200 projects that are readable by the user,
870 # build the tree using only the top 200+ projects owned by the user,
871 # from the top three levels.
872 # That is: get toplevel projects under home, get subprojects of
873 # these projects, and so on until we hit the limit.
874 def my_wanted_projects user, page_size=100
875 return @my_wanted_projects if @my_wanted_projects
880 @too_many_projects = false
881 @reached_level_limit = false
882 while from_top.size <= page_size*2
883 current_level = Group.filter([['group_class','=','project'],
884 ['owner_uuid', 'in', uuids]])
885 .order('name').limit(page_size*2)
886 break if current_level.results.size == 0
887 @too_many_projects = true if current_level.items_available > current_level.results.size
888 from_top.concat current_level.results
889 uuids = current_level.results.collect { |x| x.uuid }
892 @reached_level_limit = true
896 @my_wanted_projects = from_top
899 helper_method :my_wanted_projects_tree
900 def my_wanted_projects_tree user, page_size=100
901 build_my_wanted_projects_tree user, page_size
902 [@my_wanted_projects_tree, @too_many_projects, @reached_level_limit]
905 def build_my_wanted_projects_tree user, page_size=100
906 return @my_wanted_projects_tree if @my_wanted_projects_tree
908 parent_of = {user.uuid => 'me'}
909 my_wanted_projects(user, page_size).each do |ob|
910 parent_of[ob.uuid] = ob.owner_uuid
912 children_of = {false => [], 'me' => [user]}
913 my_wanted_projects(user, page_size).each do |ob|
914 if ob.owner_uuid != user.uuid and
915 not parent_of.has_key? ob.owner_uuid
916 parent_of[ob.uuid] = false
918 children_of[parent_of[ob.uuid]] ||= []
919 children_of[parent_of[ob.uuid]] << ob
921 buildtree = lambda do |children_of, root_uuid=false|
923 children_of[root_uuid].andand.each do |ob|
924 tree[ob] = buildtree.call(children_of, ob.uuid)
928 sorted_paths = lambda do |tree, depth=0|
930 tree.keys.sort_by { |ob|
931 ob.is_a?(String) ? ob : ob.friendly_link_name
933 paths << {object: ob, depth: depth}
934 paths += sorted_paths.call tree[ob], depth+1
938 @my_wanted_projects_tree =
939 sorted_paths.call buildtree.call(children_of, 'me')
942 helper_method :get_object
944 if @get_object.nil? and @objects
945 @get_object = @objects.each_with_object({}) do |object, h|
946 h[object.uuid] = object
953 helper_method :project_breadcrumbs
954 def project_breadcrumbs
956 current = @name_link || @object
958 # Halt if a group ownership loop is detected. API should refuse
959 # to produce this state, but it could still arise from a race
960 # condition when group ownership changes between our find()
962 break if crumbs.collect(&:uuid).include? current.uuid
964 if current.is_a?(Group) and current.group_class == 'project'
965 crumbs.prepend current
967 if current.is_a? Link
968 current = Group.find?(current.tail_uuid)
970 current = Group.find?(current.owner_uuid)
976 helper_method :current_project_uuid
977 def current_project_uuid
978 if @object.is_a? Group and @object.group_class == 'project'
980 elsif @name_link.andand.tail_uuid
982 elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
989 # helper method to get links for given object or uuid
990 helper_method :links_for_object
991 def links_for_object object_or_uuid
992 raise ArgumentError, 'No input argument' unless object_or_uuid
993 preload_links_for_objects([object_or_uuid])
994 uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
995 @all_links_for[uuid] ||= []
998 # helper method to preload links for given objects and uuids
999 helper_method :preload_links_for_objects
1000 def preload_links_for_objects objects_and_uuids
1001 @all_links_for ||= {}
1003 raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
1004 return @all_links_for if objects_and_uuids.empty?
1006 uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
1008 # if already preloaded for all of these uuids, return
1009 if not uuids.select { |x| @all_links_for[x].nil? }.any?
1010 return @all_links_for
1014 @all_links_for[x] = []
1017 # TODO: make sure we get every page of results from API server
1018 Link.filter([['head_uuid', 'in', uuids]]).each do |link|
1019 @all_links_for[link.head_uuid] << link
1024 # helper method to get a certain number of objects of a specific type
1025 # this can be used to replace any uses of: "dataclass.limit(n)"
1026 helper_method :get_n_objects_of_class
1027 def get_n_objects_of_class dataclass, size
1028 @objects_map_for ||= {}
1030 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
1031 raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
1033 # if the objects_map_for has a value for this dataclass, and the
1034 # size used to retrieve those objects is equal, return it
1035 size_key = "#{dataclass.name}_size"
1036 if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
1037 (@objects_map_for[size_key] == size)
1038 return @objects_map_for[dataclass.name]
1041 @objects_map_for[size_key] = size
1042 @objects_map_for[dataclass.name] = dataclass.limit(size)
1045 # helper method to get collections for the given uuid
1046 helper_method :collections_for_object
1047 def collections_for_object uuid
1048 raise ArgumentError, 'No input argument' unless uuid
1049 preload_collections_for_objects([uuid])
1050 @all_collections_for[uuid] ||= []
1053 # helper method to preload collections for the given uuids
1054 helper_method :preload_collections_for_objects
1055 def preload_collections_for_objects uuids
1056 @all_collections_for ||= {}
1058 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
1059 return @all_collections_for if uuids.empty?
1061 # if already preloaded for all of these uuids, return
1062 if not uuids.select { |x| @all_collections_for[x].nil? }.any?
1063 return @all_collections_for
1067 @all_collections_for[x] = []
1070 # TODO: make sure we get every page of results from API server
1071 Collection.where(uuid: uuids).each do |collection|
1072 @all_collections_for[collection.uuid] << collection
1074 @all_collections_for
1077 # helper method to get log collections for the given log
1078 helper_method :log_collections_for_object
1079 def log_collections_for_object log
1080 raise ArgumentError, 'No input argument' unless log
1082 preload_log_collections_for_objects([log])
1085 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
1086 if fixup && fixup.size>1
1090 @all_log_collections_for[uuid] ||= []
1093 # helper method to preload collections for the given uuids
1094 helper_method :preload_log_collections_for_objects
1095 def preload_log_collections_for_objects logs
1096 @all_log_collections_for ||= {}
1098 raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
1099 return @all_log_collections_for if logs.empty?
1103 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
1104 if fixup && fixup.size>1
1111 # if already preloaded for all of these uuids, return
1112 if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
1113 return @all_log_collections_for
1117 @all_log_collections_for[x] = []
1120 # TODO: make sure we get every page of results from API server
1121 Collection.where(uuid: uuids).each do |collection|
1122 @all_log_collections_for[collection.uuid] << collection
1124 @all_log_collections_for
1127 # Helper method to get one collection for the given portable_data_hash
1128 # This is used to determine if a pdh is readable by the current_user
1129 helper_method :collection_for_pdh
1130 def collection_for_pdh pdh
1131 raise ArgumentError, 'No input argument' unless pdh
1132 preload_for_pdhs([pdh])
1133 @all_pdhs_for[pdh] ||= []
1136 # Helper method to preload one collection each for the given pdhs
1137 # This is used to determine if a pdh is readable by the current_user
1138 helper_method :preload_for_pdhs
1139 def preload_for_pdhs pdhs
1140 @all_pdhs_for ||= {}
1142 raise ArgumentError, 'Argument is not an array' unless pdhs.is_a? Array
1143 return @all_pdhs_for if pdhs.empty?
1145 # if already preloaded for all of these pdhs, return
1146 if not pdhs.select { |x| @all_pdhs_for[x].nil? }.any?
1147 return @all_pdhs_for
1151 @all_pdhs_for[x] = []
1154 Collection.select(%w(portable_data_hash)).where(portable_data_hash: pdhs).distinct().each do |collection|
1155 @all_pdhs_for[collection.portable_data_hash] << collection
1160 # helper method to get object of a given dataclass and uuid
1161 helper_method :object_for_dataclass
1162 def object_for_dataclass dataclass, uuid
1163 raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
1164 preload_objects_for_dataclass(dataclass, [uuid])
1168 # helper method to preload objects for given dataclass and uuids
1169 helper_method :preload_objects_for_dataclass
1170 def preload_objects_for_dataclass dataclass, uuids
1173 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
1174 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
1176 return @objects_for if uuids.empty?
1178 # if already preloaded for all of these uuids, return
1179 if not uuids.select { |x| !@objects_for.include?(x) }.any?
1183 # preset all uuids to nil
1185 @objects_for[x] = nil
1187 dataclass.where(uuid: uuids).each do |obj|
1188 @objects_for[obj.uuid] = obj
1193 def wiselinks_layout