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