Merge branch 'master' into 3889-functional-testing
[arvados.git] / apps / workbench / app / controllers / application_controller.rb
1 class ApplicationController < ActionController::Base
2   include ArvadosApiClientHelper
3   include ApplicationHelper
4
5   respond_to :html, :json, :js
6   protect_from_forgery
7
8   ERROR_ACTIONS = [:render_error, :render_not_found]
9
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 :accept_uuid_as_id_param, except: ERROR_ACTIONS
16   before_filter :check_user_agreements, except: ERROR_ACTIONS
17   before_filter :check_user_profile, except: ERROR_ACTIONS
18   before_filter :check_user_notifications, 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
21   theme :select_theme
22
23   begin
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)
32   end
33
34   def unprocessable(message=nil)
35     @errors ||= []
36
37     @errors << message if message
38     render_error status: 422
39   end
40
41   def render_error(opts={})
42     opts[:status] ||= 500
43     respond_to do |f|
44       # json must come before html here, so it gets used as the
45       # default format when js is requested by the client. This lets
46       # ajax:error callback parse the response correctly, even though
47       # the browser can't.
48       f.json { render opts.merge(json: {success: false, errors: @errors}) }
49       f.html { render({action: 'error'}.merge(opts)) }
50     end
51   end
52
53   def render_exception(e)
54     logger.error e.inspect
55     logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
56     err_opts = {status: 422}
57     if e.is_a?(ArvadosApiClient::ApiError)
58       err_opts.merge!(action: 'api_error', locals: {api_error: e})
59       @errors = e.api_response[:errors]
60     elsif @object.andand.errors.andand.full_messages.andand.any?
61       @errors = @object.errors.full_messages
62     else
63       @errors = [e.to_s]
64     end
65     # Make user information available on the error page, falling back to the
66     # session cache if the API server is unavailable.
67     begin
68       load_api_token(session[:arvados_api_token])
69     rescue ArvadosApiClient::ApiError
70       unless session[:user].nil?
71         begin
72           Thread.current[:user] = User.new(session[:user])
73         rescue ArvadosApiClient::ApiError
74           # This can happen if User's columns are unavailable.  Nothing to do.
75         end
76       end
77     end
78     # Preload projects trees for the template.  If that's not doable, set empty
79     # trees so error page rendering can proceed.  (It's easier to rescue the
80     # exception here than in a template.)
81     unless current_user.nil?
82       begin
83         build_project_trees
84       rescue ArvadosApiClient::ApiError
85         # Fall back to the default-setting code later.
86       end
87     end
88     @my_project_tree ||= []
89     @shared_project_tree ||= []
90     render_error(err_opts)
91   end
92
93   def render_not_found(e=ActionController::RoutingError.new("Path not found"))
94     logger.error e.inspect
95     @errors = ["Path not found"]
96     set_thread_api_token do
97       self.render_error(action: '404', status: 404)
98     end
99   end
100
101   def load_filters_and_paging_params
102     @order = params[:order] || 'created_at desc'
103     @order = [@order] unless @order.is_a? Array
104
105     @limit ||= 200
106     if params[:limit]
107       @limit = params[:limit].to_i
108     end
109
110     @offset ||= 0
111     if params[:offset]
112       @offset = params[:offset].to_i
113     end
114
115     @filters ||= []
116     if params[:filters]
117       filters = params[:filters]
118       if filters.is_a? String
119         filters = Oj.load filters
120       elsif filters.is_a? Array
121         filters = filters.collect do |filter|
122           if filter.is_a? String
123             # Accept filters[]=["foo","=","bar"]
124             Oj.load filter
125           else
126             # Accept filters=[["foo","=","bar"]]
127             filter
128           end
129         end
130       end
131       # After this, params[:filters] can be trusted to be an array of arrays:
132       params[:filters] = filters
133       @filters += filters
134     end
135   end
136
137   def find_objects_for_index
138     @objects ||= model_class
139     @objects = @objects.filter(@filters).limit(@limit).offset(@offset)
140   end
141
142   def render_index
143     respond_to do |f|
144       f.json { render json: @objects }
145       f.html {
146         if params[:tab_pane]
147           render_pane params[:tab_pane]
148         else
149           render
150         end
151       }
152       f.js { render }
153     end
154   end
155
156   helper_method :render_pane
157   def render_pane tab_pane, opts={}
158     render_opts = {
159       partial: 'show_' + tab_pane.downcase,
160       locals: {
161         comparable: self.respond_to?(:compare),
162         objects: @objects,
163         tab_pane: tab_pane
164       }.merge(opts[:locals] || {})
165     }
166     if opts[:to_string]
167       render_to_string render_opts
168     else
169       render render_opts
170     end
171   end
172
173   def index
174     find_objects_for_index if !@objects
175     render_index
176   end
177
178   helper_method :next_page_offset
179   def next_page_offset objects=nil
180     if !objects
181       objects = @objects
182     end
183     if objects.respond_to?(:result_offset) and
184         objects.respond_to?(:result_limit) and
185         objects.respond_to?(:items_available)
186       next_offset = objects.result_offset + objects.result_limit
187       if next_offset < objects.items_available
188         next_offset
189       else
190         nil
191       end
192     end
193   end
194
195   helper_method :next_page_href
196   def next_page_href with_params={}
197     if next_page_offset
198       url_for with_params.merge(offset: next_page_offset)
199     end
200   end
201
202   def show
203     if !@object
204       return render_not_found("object not found")
205     end
206     respond_to do |f|
207       f.json do
208         extra_attrs = { href: url_for(action: :show, id: @object) }
209         @object.textile_attributes.each do |textile_attr|
210           extra_attrs.merge!({ "#{textile_attr}Textile" => view_context.render_markup(@object.attributes[textile_attr]) })
211         end
212         render json: @object.attributes.merge(extra_attrs)
213       end
214       f.html {
215         if params['tab_pane']
216           render_pane(if params['tab_pane'].is_a? Hash then params['tab_pane']["name"] else params['tab_pane'] end)
217         elsif request.method.in? ['GET', 'HEAD']
218           render
219         else
220           redirect_to params[:return_to] || @object
221         end
222       }
223       f.js { render }
224     end
225   end
226
227   def choose
228     params[:limit] ||= 40
229     respond_to do |f|
230       if params[:partial]
231         f.json {
232           find_objects_for_index if !@objects
233           render json: {
234             content: render_to_string(partial: "choose_rows.html",
235                                       formats: [:html]),
236             next_page_href: next_page_href(partial: params[:partial])
237           }
238         }
239       end
240       f.js {
241         find_objects_for_index if !@objects
242         render partial: 'choose', locals: {multiple: params[:multiple]}
243       }
244     end
245   end
246
247   def render_content
248     if !@object
249       return render_not_found("object not found")
250     end
251   end
252
253   def new
254     @object = model_class.new
255   end
256
257   def update
258     @updates ||= params[@object.resource_param_name.to_sym]
259     @updates.keys.each do |attr|
260       if @object.send(attr).is_a? Hash
261         if @updates[attr].is_a? String
262           @updates[attr] = Oj.load @updates[attr]
263         end
264         if params[:merge] || params["merge_#{attr}".to_sym]
265           # Merge provided Hash with current Hash, instead of
266           # replacing.
267           @updates[attr] = @object.send(attr).with_indifferent_access.
268             deep_merge(@updates[attr].with_indifferent_access)
269         end
270       end
271     end
272     if @object.update_attributes @updates
273       show
274     else
275       self.render_error status: 422
276     end
277   end
278
279   def create
280     @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
281     @new_resource_attrs ||= {}
282     @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
283     @object ||= model_class.new @new_resource_attrs, params["options"]
284     if @object.save
285       respond_to do |f|
286         f.json { render json: @object.attributes.merge(href: url_for(action: :show, id: @object)) }
287         f.html {
288           redirect_to @object
289         }
290         f.js { render }
291       end
292     else
293       self.render_error status: 422
294     end
295   end
296
297   # Clone the given object, merging any attribute values supplied as
298   # with a create action.
299   def copy
300     @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
301     @new_resource_attrs ||= {}
302     @object = @object.dup
303     @object.update_attributes @new_resource_attrs
304     if not @new_resource_attrs[:name] and @object.respond_to? :name
305       if @object.name and @object.name != ''
306         @object.name = "Copy of #{@object.name}"
307       else
308         @object.name = ""
309       end
310     end
311     @object.save!
312     show
313   end
314
315   def destroy
316     if @object.destroy
317       respond_to do |f|
318         f.json { render json: @object }
319         f.html {
320           redirect_to(params[:return_to] || :back)
321         }
322         f.js { render }
323       end
324     else
325       self.render_error status: 422
326     end
327   end
328
329   def current_user
330     Thread.current[:user]
331   end
332
333   def model_class
334     controller_name.classify.constantize
335   end
336
337   def breadcrumb_page_name
338     (@breadcrumb_page_name ||
339      (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
340      action_name)
341   end
342
343   def index_pane_list
344     %w(Recent)
345   end
346
347   def show_pane_list
348     %w(Attributes Advanced)
349   end
350
351   protected
352
353   def strip_token_from_path(path)
354     path.sub(/([\?&;])api_token=[^&;]*[&;]?/, '\1')
355   end
356
357   def redirect_to_login
358     respond_to do |f|
359       f.html {
360         if request.method.in? ['GET', 'HEAD']
361           redirect_to arvados_api_client.arvados_login_url(return_to: strip_token_from_path(request.url))
362         else
363           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."
364           redirect_to :back
365         end
366       }
367       f.json {
368         @errors = ['You do not seem to be logged in. You did not supply an API token with this request, and your session (if any) has timed out.']
369         self.render_error status: 422
370       }
371     end
372     false  # For convenience to return from callbacks
373   end
374
375   def using_specific_api_token(api_token)
376     start_values = {}
377     [:arvados_api_token, :user].each do |key|
378       start_values[key] = Thread.current[key]
379     end
380     load_api_token(api_token)
381     begin
382       yield
383     ensure
384       start_values.each_key { |key| Thread.current[key] = start_values[key] }
385     end
386   end
387
388
389   def accept_uuid_as_id_param
390     if params[:id] and params[:id].match /\D/
391       params[:uuid] = params.delete :id
392     end
393   end
394
395   def find_object_by_uuid
396     begin
397       if not model_class
398         @object = nil
399       elsif not params[:uuid].is_a?(String)
400         @object = model_class.where(uuid: params[:uuid]).first
401       elsif params[:uuid].empty?
402         @object = nil
403       elsif (model_class != Link and
404              resource_class_for_uuid(params[:uuid]) == Link)
405         @name_link = Link.find(params[:uuid])
406         @object = model_class.find(@name_link.head_uuid)
407       else
408         @object = model_class.find(params[:uuid])
409       end
410     rescue ArvadosApiClient::NotFoundException, RuntimeError => error
411       if error.is_a?(RuntimeError) and (error.message !~ /^argument to find\(/)
412         raise
413       end
414       render_not_found(error)
415       return false
416     end
417   end
418
419   def thread_clear
420     load_api_token(nil)
421     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
422     yield
423     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
424   end
425
426   # Set up the thread with the given API token and associated user object.
427   def load_api_token(new_token)
428     Thread.current[:arvados_api_token] = new_token
429     if new_token.nil?
430       Thread.current[:user] = nil
431     else
432       Thread.current[:user] = User.current
433     end
434   end
435
436   # If there's a valid api_token parameter, set up the session with that
437   # user's information.  Return true if the method redirects the request
438   # (usually a post-login redirect); false otherwise.
439   def setup_user_session
440     return false unless params[:api_token]
441     Thread.current[:arvados_api_token] = params[:api_token]
442     begin
443       user = User.current
444     rescue ArvadosApiClient::NotLoggedInException
445       false  # We may redirect to login, or not, based on the current action.
446     else
447       session[:arvados_api_token] = params[:api_token]
448       # If we later have trouble contacting the API server, we still want
449       # to be able to render basic user information in the UI--see
450       # render_exception above.  We store that in the session here.  This is
451       # not intended to be used as a general-purpose cache.  See #2891.
452       session[:user] = {
453         uuid: user.uuid,
454         email: user.email,
455         first_name: user.first_name,
456         last_name: user.last_name,
457         is_active: user.is_active,
458         is_admin: user.is_admin,
459         prefs: user.prefs
460       }
461
462       if !request.format.json? and request.method.in? ['GET', 'HEAD']
463         # Repeat this request with api_token in the (new) session
464         # cookie instead of the query string.  This prevents API
465         # tokens from appearing in (and being inadvisedly copied
466         # and pasted from) browser Location bars.
467         redirect_to strip_token_from_path(request.fullpath)
468         true
469       else
470         false
471       end
472     ensure
473       Thread.current[:arvados_api_token] = nil
474     end
475   end
476
477   # Save the session API token in thread-local storage, and yield.
478   # This method also takes care of session setup if the request
479   # provides a valid api_token parameter.
480   # If a token is unavailable or expired, the block is still run, with
481   # a nil token.
482   def set_thread_api_token
483     if Thread.current[:arvados_api_token]
484       yield   # An API token has already been found - pass it through.
485       return
486     elsif setup_user_session
487       return  # A new session was set up and received a response.
488     end
489
490     begin
491       load_api_token(session[:arvados_api_token])
492       yield
493     rescue ArvadosApiClient::NotLoggedInException
494       # If we got this error with a token, it must've expired.
495       # Retry the request without a token.
496       unless Thread.current[:arvados_api_token].nil?
497         load_api_token(nil)
498         yield
499       end
500     ensure
501       # Remove token in case this Thread is used for anything else.
502       load_api_token(nil)
503     end
504   end
505
506   # Redirect to login/welcome if client provided expired API token (or none at all)
507   def require_thread_api_token
508     if Thread.current[:arvados_api_token]
509       yield
510     elsif session[:arvados_api_token]
511       # Expired session. Clear it before refreshing login so that,
512       # if this login procedure fails, we end up showing the "please
513       # log in" page instead of getting stuck in a redirect loop.
514       session.delete :arvados_api_token
515       redirect_to_login
516     else
517       redirect_to welcome_users_path(return_to: request.fullpath)
518     end
519   end
520
521   def ensure_current_user_is_admin
522     unless current_user and current_user.is_admin
523       @errors = ['Permission denied']
524       self.render_error status: 401
525     end
526   end
527
528   helper_method :unsigned_user_agreements
529   def unsigned_user_agreements
530     @signed_ua_uuids ||= UserAgreement.signatures.map &:head_uuid
531     @unsigned_user_agreements ||= UserAgreement.all.map do |ua|
532       if not @signed_ua_uuids.index ua.uuid
533         Collection.find(ua.uuid)
534       end
535     end.compact
536   end
537
538   def check_user_agreements
539     if current_user && !current_user.is_active
540       if not current_user.is_invited
541         return redirect_to inactive_users_path(return_to: request.fullpath)
542       end
543       if unsigned_user_agreements.empty?
544         # No agreements to sign. Perhaps we just need to ask?
545         current_user.activate
546         if !current_user.is_active
547           logger.warn "#{current_user.uuid.inspect}: " +
548             "No user agreements to sign, but activate failed!"
549         end
550       end
551       if !current_user.is_active
552         redirect_to user_agreements_path(return_to: request.fullpath)
553       end
554     end
555     true
556   end
557
558   def check_user_profile
559     if request.method.downcase != 'get' || params[:partial] ||
560        params[:tab_pane] || params[:action_method] ||
561        params[:action] == 'setup_popup'
562       return true
563     end
564
565     if missing_required_profile?
566       redirect_to profile_user_path(current_user.uuid, return_to: request.fullpath)
567     end
568     true
569   end
570
571   helper_method :missing_required_profile?
572   def missing_required_profile?
573     missing_required = false
574
575     profile_config = Rails.configuration.user_profile_form_fields
576     if current_user && profile_config
577       current_user_profile = current_user.prefs[:profile]
578       profile_config.kind_of?(Array) && profile_config.andand.each do |entry|
579         if entry['required']
580           if !current_user_profile ||
581              !current_user_profile[entry['key'].to_sym] ||
582              current_user_profile[entry['key'].to_sym].empty?
583             missing_required = true
584             break
585           end
586         end
587       end
588     end
589
590     missing_required
591   end
592
593   def select_theme
594     return Rails.configuration.arvados_theme
595   end
596
597   @@notification_tests = []
598
599   @@notification_tests.push lambda { |controller, current_user|
600     AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
601       return nil
602     end
603     return lambda { |view|
604       view.render partial: 'notifications/ssh_key_notification'
605     }
606   }
607
608   @@notification_tests.push lambda { |controller, current_user|
609     Collection.limit(1).where(created_by: current_user.uuid).each do
610       return nil
611     end
612     return lambda { |view|
613       view.render partial: 'notifications/collections_notification'
614     }
615   }
616
617   @@notification_tests.push lambda { |controller, current_user|
618     PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
619       return nil
620     end
621     return lambda { |view|
622       view.render partial: 'notifications/pipelines_notification'
623     }
624   }
625
626   def check_user_notifications
627     return if params['tab_pane']
628
629     @notification_count = 0
630     @notifications = []
631
632     if current_user.andand.is_active
633       @showallalerts = false
634       @@notification_tests.each do |t|
635         a = t.call(self, current_user)
636         if a
637           @notification_count += 1
638           @notifications.push a
639         end
640       end
641     end
642
643     if @notification_count == 0
644       @notification_count = ''
645     end
646   end
647
648   helper_method :all_projects
649   def all_projects
650     @all_projects ||= Group.
651       filter([['group_class','=','project']]).order('name')
652   end
653
654   helper_method :my_projects
655   def my_projects
656     return @my_projects if @my_projects
657     @my_projects = []
658     root_of = {}
659     all_projects.each do |g|
660       root_of[g.uuid] = g.owner_uuid
661       @my_projects << g
662     end
663     done = false
664     while not done
665       done = true
666       root_of = root_of.each_with_object({}) do |(child, parent), h|
667         if root_of[parent]
668           h[child] = root_of[parent]
669           done = false
670         else
671           h[child] = parent
672         end
673       end
674     end
675     @my_projects = @my_projects.select do |g|
676       root_of[g.uuid] == current_user.uuid
677     end
678   end
679
680   helper_method :projects_shared_with_me
681   def projects_shared_with_me
682     my_project_uuids = my_projects.collect &:uuid
683     all_projects.reject { |x| x.uuid.in? my_project_uuids }
684   end
685
686   helper_method :recent_jobs_and_pipelines
687   def recent_jobs_and_pipelines
688     (Job.limit(10) |
689      PipelineInstance.limit(10)).
690       sort_by do |x|
691       (x.finished_at || x.started_at rescue nil) || x.modified_at || x.created_at
692     end.reverse
693   end
694
695   helper_method :running_pipelines
696   def running_pipelines
697     pi = PipelineInstance.order(["started_at asc", "created_at asc"]).filter([["state", "in", ["RunningOnServer", "RunningOnClient"]]])
698     jobs = {}
699     pi.each do |pl|
700       pl.components.each do |k,v|
701         if v.is_a? Hash and v[:job]
702           jobs[v[:job][:uuid]] = {}
703         end
704       end
705     end
706
707     Job.filter([["uuid", "in", jobs.keys]]).each do |j|
708       jobs[j[:uuid]] = j
709     end
710
711     pi.each do |pl|
712       pl.components.each do |k,v|
713         if v.is_a? Hash and v[:job]
714           v[:job] = jobs[v[:job][:uuid]]
715         end
716       end
717     end
718
719     pi
720   end
721
722   helper_method :finished_pipelines
723   def finished_pipelines lim
724     PipelineInstance.limit(lim).order(["finished_at desc"]).filter([["state", "in", ["Complete", "Failed", "Paused"]], ["finished_at", "!=", nil]])
725   end
726
727   helper_method :recent_collections
728   def recent_collections lim
729     c = Collection.limit(lim).order(["modified_at desc"]).filter([["owner_uuid", "is_a", "arvados#group"]])
730     own = {}
731     Group.filter([["uuid", "in", c.map(&:owner_uuid)]]).each do |g|
732       own[g[:uuid]] = g
733     end
734     {collections: c, owners: own}
735   end
736
737   helper_method :my_project_tree
738   def my_project_tree
739     build_project_trees
740     @my_project_tree
741   end
742
743   helper_method :shared_project_tree
744   def shared_project_tree
745     build_project_trees
746     @shared_project_tree
747   end
748
749   def build_project_trees
750     return if @my_project_tree and @shared_project_tree
751     parent_of = {current_user.uuid => 'me'}
752     all_projects.each do |ob|
753       parent_of[ob.uuid] = ob.owner_uuid
754     end
755     children_of = {false => [], 'me' => [current_user]}
756     all_projects.each do |ob|
757       if ob.owner_uuid != current_user.uuid and
758           not parent_of.has_key? ob.owner_uuid
759         parent_of[ob.uuid] = false
760       end
761       children_of[parent_of[ob.uuid]] ||= []
762       children_of[parent_of[ob.uuid]] << ob
763     end
764     buildtree = lambda do |children_of, root_uuid=false|
765       tree = {}
766       children_of[root_uuid].andand.each do |ob|
767         tree[ob] = buildtree.call(children_of, ob.uuid)
768       end
769       tree
770     end
771     sorted_paths = lambda do |tree, depth=0|
772       paths = []
773       tree.keys.sort_by { |ob|
774         ob.is_a?(String) ? ob : ob.friendly_link_name
775       }.each do |ob|
776         paths << {object: ob, depth: depth}
777         paths += sorted_paths.call tree[ob], depth+1
778       end
779       paths
780     end
781     @my_project_tree =
782       sorted_paths.call buildtree.call(children_of, 'me')
783     @shared_project_tree =
784       sorted_paths.call({'Projects shared with me' =>
785                           buildtree.call(children_of, false)})
786   end
787
788   helper_method :get_object
789   def get_object uuid
790     if @get_object.nil? and @objects
791       @get_object = @objects.each_with_object({}) do |object, h|
792         h[object.uuid] = object
793       end
794     end
795     @get_object ||= {}
796     @get_object[uuid]
797   end
798
799   helper_method :project_breadcrumbs
800   def project_breadcrumbs
801     crumbs = []
802     current = @name_link || @object
803     while current
804       if current.is_a?(Group) and current.group_class == 'project'
805         crumbs.prepend current
806       end
807       if current.is_a? Link
808         current = Group.find?(current.tail_uuid)
809       else
810         current = Group.find?(current.owner_uuid)
811       end
812     end
813     crumbs
814   end
815
816   helper_method :current_project_uuid
817   def current_project_uuid
818     if @object.is_a? Group and @object.group_class == 'project'
819       @object.uuid
820     elsif @name_link.andand.tail_uuid
821       @name_link.tail_uuid
822     elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
823       @object.owner_uuid
824     else
825       nil
826     end
827   end
828
829   # helper method to get links for given object or uuid
830   helper_method :links_for_object
831   def links_for_object object_or_uuid
832     raise ArgumentError, 'No input argument' unless object_or_uuid
833     preload_links_for_objects([object_or_uuid])
834     uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
835     @all_links_for[uuid] ||= []
836   end
837
838   # helper method to preload links for given objects and uuids
839   helper_method :preload_links_for_objects
840   def preload_links_for_objects objects_and_uuids
841     @all_links_for ||= {}
842
843     raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
844     return @all_links_for if objects_and_uuids.empty?
845
846     uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
847
848     # if already preloaded for all of these uuids, return
849     if not uuids.select { |x| @all_links_for[x].nil? }.any?
850       return @all_links_for
851     end
852
853     uuids.each do |x|
854       @all_links_for[x] = []
855     end
856
857     # TODO: make sure we get every page of results from API server
858     Link.filter([['head_uuid', 'in', uuids]]).each do |link|
859       @all_links_for[link.head_uuid] << link
860     end
861     @all_links_for
862   end
863
864   # helper method to get a certain number of objects of a specific type
865   # this can be used to replace any uses of: "dataclass.limit(n)"
866   helper_method :get_n_objects_of_class
867   def get_n_objects_of_class dataclass, size
868     @objects_map_for ||= {}
869
870     raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
871     raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
872
873     # if the objects_map_for has a value for this dataclass, and the
874     # size used to retrieve those objects is equal, return it
875     size_key = "#{dataclass.name}_size"
876     if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
877         (@objects_map_for[size_key] == size)
878       return @objects_map_for[dataclass.name]
879     end
880
881     @objects_map_for[size_key] = size
882     @objects_map_for[dataclass.name] = dataclass.limit(size)
883   end
884
885   # helper method to get collections for the given uuid
886   helper_method :collections_for_object
887   def collections_for_object uuid
888     raise ArgumentError, 'No input argument' unless uuid
889     preload_collections_for_objects([uuid])
890     @all_collections_for[uuid] ||= []
891   end
892
893   # helper method to preload collections for the given uuids
894   helper_method :preload_collections_for_objects
895   def preload_collections_for_objects uuids
896     @all_collections_for ||= {}
897
898     raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
899     return @all_collections_for if uuids.empty?
900
901     # if already preloaded for all of these uuids, return
902     if not uuids.select { |x| @all_collections_for[x].nil? }.any?
903       return @all_collections_for
904     end
905
906     uuids.each do |x|
907       @all_collections_for[x] = []
908     end
909
910     # TODO: make sure we get every page of results from API server
911     Collection.where(uuid: uuids).each do |collection|
912       @all_collections_for[collection.uuid] << collection
913     end
914     @all_collections_for
915   end
916
917   # helper method to get log collections for the given log
918   helper_method :log_collections_for_object
919   def log_collections_for_object log
920     raise ArgumentError, 'No input argument' unless log
921
922     preload_log_collections_for_objects([log])
923
924     uuid = log
925     fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
926     if fixup && fixup.size>1
927       uuid = fixup[1]
928     end
929
930     @all_log_collections_for[uuid] ||= []
931   end
932
933   # helper method to preload collections for the given uuids
934   helper_method :preload_log_collections_for_objects
935   def preload_log_collections_for_objects logs
936     @all_log_collections_for ||= {}
937
938     raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
939     return @all_log_collections_for if logs.empty?
940
941     uuids = []
942     logs.each do |log|
943       fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
944       if fixup && fixup.size>1
945         uuids << fixup[1]
946       else
947         uuids << log
948       end
949     end
950
951     # if already preloaded for all of these uuids, return
952     if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
953       return @all_log_collections_for
954     end
955
956     uuids.each do |x|
957       @all_log_collections_for[x] = []
958     end
959
960     # TODO: make sure we get every page of results from API server
961     Collection.where(uuid: uuids).each do |collection|
962       @all_log_collections_for[collection.uuid] << collection
963     end
964     @all_log_collections_for
965   end
966
967   # helper method to get object of a given dataclass and uuid
968   helper_method :object_for_dataclass
969   def object_for_dataclass dataclass, uuid
970     raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
971     preload_objects_for_dataclass(dataclass, [uuid])
972     @objects_for[uuid]
973   end
974
975   # helper method to preload objects for given dataclass and uuids
976   helper_method :preload_objects_for_dataclass
977   def preload_objects_for_dataclass dataclass, uuids
978     @objects_for ||= {}
979
980     raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
981     raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
982
983     return @objects_for if uuids.empty?
984
985     # if already preloaded for all of these uuids, return
986     if not uuids.select { |x| @objects_for[x].nil? }.any?
987       return @objects_for
988     end
989
990     dataclass.where(uuid: uuids).each do |obj|
991       @objects_for[obj.uuid] = obj
992     end
993     @objects_for
994   end
995
996   def wiselinks_layout
997     'body'
998   end
999 end