Merge branch '3114-copy-to-project' closes #3114
[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       # If we later have trouble contacting the API server, we still want
440       # to be able to render basic user information in the UI--see
441       # render_exception above.  We store that in the session here.  This is
442       # not intended to be used as a general-purpose cache.  See #2891.
443       session[:user] = {
444         uuid: user.uuid,
445         email: user.email,
446         first_name: user.first_name,
447         last_name: user.last_name,
448         is_active: user.is_active,
449         is_admin: user.is_admin,
450         prefs: user.prefs
451       }
452
453       if !request.format.json? and request.method.in? ['GET', 'HEAD']
454         # Repeat this request with api_token in the (new) session
455         # cookie instead of the query string.  This prevents API
456         # tokens from appearing in (and being inadvisedly copied
457         # and pasted from) browser Location bars.
458         redirect_to strip_token_from_path(request.fullpath)
459         true
460       else
461         false
462       end
463     ensure
464       Thread.current[:arvados_api_token] = nil
465     end
466   end
467
468   # Save the session API token in thread-local storage, and yield.
469   # This method also takes care of session setup if the request
470   # provides a valid api_token parameter.
471   # If a token is unavailable or expired, the block is still run, with
472   # a nil token.
473   def set_thread_api_token
474     if Thread.current[:arvados_api_token]
475       yield   # An API token has already been found - pass it through.
476       return
477     elsif setup_user_session
478       return  # A new session was set up and received a response.
479     end
480
481     begin
482       load_api_token(session[:arvados_api_token])
483       yield
484     rescue ArvadosApiClient::NotLoggedInException
485       # If we got this error with a token, it must've expired.
486       # Retry the request without a token.
487       unless Thread.current[:arvados_api_token].nil?
488         load_api_token(nil)
489         yield
490       end
491     ensure
492       # Remove token in case this Thread is used for anything else.
493       load_api_token(nil)
494     end
495   end
496
497   # Redirect to login/welcome if client provided expired API token (or none at all)
498   def require_thread_api_token
499     if Thread.current[:arvados_api_token]
500       yield
501     elsif session[:arvados_api_token]
502       # Expired session. Clear it before refreshing login so that,
503       # if this login procedure fails, we end up showing the "please
504       # log in" page instead of getting stuck in a redirect loop.
505       session.delete :arvados_api_token
506       redirect_to_login
507     else
508       redirect_to welcome_users_path(return_to: request.fullpath)
509     end
510   end
511
512   def ensure_current_user_is_admin
513     unless current_user and current_user.is_admin
514       @errors = ['Permission denied']
515       self.render_error status: 401
516     end
517   end
518
519   helper_method :unsigned_user_agreements
520   def unsigned_user_agreements
521     @signed_ua_uuids ||= UserAgreement.signatures.map &:head_uuid
522     @unsigned_user_agreements ||= UserAgreement.all.map do |ua|
523       if not @signed_ua_uuids.index ua.uuid
524         Collection.find(ua.uuid)
525       end
526     end.compact
527   end
528
529   def check_user_agreements
530     if current_user && !current_user.is_active
531       if not current_user.is_invited
532         return redirect_to inactive_users_path(return_to: request.fullpath)
533       end
534       if unsigned_user_agreements.empty?
535         # No agreements to sign. Perhaps we just need to ask?
536         current_user.activate
537         if !current_user.is_active
538           logger.warn "#{current_user.uuid.inspect}: " +
539             "No user agreements to sign, but activate failed!"
540         end
541       end
542       if !current_user.is_active
543         redirect_to user_agreements_path(return_to: request.fullpath)
544       end
545     end
546     true
547   end
548
549   def check_user_profile
550     if request.method.downcase != 'get' || params[:partial] ||
551        params[:tab_pane] || params[:action_method] ||
552        params[:action] == 'setup_popup'
553       return true
554     end
555
556     if missing_required_profile?
557       redirect_to profile_user_path(current_user.uuid, return_to: request.fullpath)
558     end
559     true
560   end
561
562   helper_method :missing_required_profile?
563   def missing_required_profile?
564     missing_required = false
565
566     profile_config = Rails.configuration.user_profile_form_fields
567     if current_user && profile_config
568       current_user_profile = current_user.prefs[:profile]
569       profile_config.kind_of?(Array) && profile_config.andand.each do |entry|
570         if entry['required']
571           if !current_user_profile ||
572              !current_user_profile[entry['key'].to_sym] ||
573              current_user_profile[entry['key'].to_sym].empty?
574             missing_required = true
575             break
576           end
577         end
578       end
579     end
580
581     missing_required
582   end
583
584   def select_theme
585     return Rails.configuration.arvados_theme
586   end
587
588   @@notification_tests = []
589
590   @@notification_tests.push lambda { |controller, current_user|
591     AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
592       return nil
593     end
594     return lambda { |view|
595       view.render partial: 'notifications/ssh_key_notification'
596     }
597   }
598
599   @@notification_tests.push lambda { |controller, current_user|
600     Collection.limit(1).where(created_by: current_user.uuid).each do
601       return nil
602     end
603     return lambda { |view|
604       view.render partial: 'notifications/collections_notification'
605     }
606   }
607
608   @@notification_tests.push lambda { |controller, current_user|
609     PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
610       return nil
611     end
612     return lambda { |view|
613       view.render partial: 'notifications/pipelines_notification'
614     }
615   }
616
617   def check_user_notifications
618     return if params['tab_pane']
619
620     @notification_count = 0
621     @notifications = []
622
623     if current_user.andand.is_active
624       @showallalerts = false
625       @@notification_tests.each do |t|
626         a = t.call(self, current_user)
627         if a
628           @notification_count += 1
629           @notifications.push a
630         end
631       end
632     end
633
634     if @notification_count == 0
635       @notification_count = ''
636     end
637   end
638
639   helper_method :all_projects
640   def all_projects
641     @all_projects ||= Group.
642       filter([['group_class','=','project']]).order('name')
643   end
644
645   helper_method :my_projects
646   def my_projects
647     return @my_projects if @my_projects
648     @my_projects = []
649     root_of = {}
650     all_projects.each do |g|
651       root_of[g.uuid] = g.owner_uuid
652       @my_projects << g
653     end
654     done = false
655     while not done
656       done = true
657       root_of = root_of.each_with_object({}) do |(child, parent), h|
658         if root_of[parent]
659           h[child] = root_of[parent]
660           done = false
661         else
662           h[child] = parent
663         end
664       end
665     end
666     @my_projects = @my_projects.select do |g|
667       root_of[g.uuid] == current_user.uuid
668     end
669   end
670
671   helper_method :projects_shared_with_me
672   def projects_shared_with_me
673     my_project_uuids = my_projects.collect &:uuid
674     all_projects.reject { |x| x.uuid.in? my_project_uuids }
675   end
676
677   helper_method :recent_jobs_and_pipelines
678   def recent_jobs_and_pipelines
679     (Job.limit(10) |
680      PipelineInstance.limit(10)).
681       sort_by do |x|
682       (x.finished_at || x.started_at rescue nil) || x.modified_at || x.created_at
683     end.reverse
684   end
685
686   helper_method :my_project_tree
687   def my_project_tree
688     build_project_trees
689     @my_project_tree
690   end
691
692   helper_method :shared_project_tree
693   def shared_project_tree
694     build_project_trees
695     @shared_project_tree
696   end
697
698   def build_project_trees
699     return if @my_project_tree and @shared_project_tree
700     parent_of = {current_user.uuid => 'me'}
701     all_projects.each do |ob|
702       parent_of[ob.uuid] = ob.owner_uuid
703     end
704     children_of = {false => [], 'me' => [current_user]}
705     all_projects.each do |ob|
706       if ob.owner_uuid != current_user.uuid and
707           not parent_of.has_key? ob.owner_uuid
708         parent_of[ob.uuid] = false
709       end
710       children_of[parent_of[ob.uuid]] ||= []
711       children_of[parent_of[ob.uuid]] << ob
712     end
713     buildtree = lambda do |children_of, root_uuid=false|
714       tree = {}
715       children_of[root_uuid].andand.each do |ob|
716         tree[ob] = buildtree.call(children_of, ob.uuid)
717       end
718       tree
719     end
720     sorted_paths = lambda do |tree, depth=0|
721       paths = []
722       tree.keys.sort_by { |ob|
723         ob.is_a?(String) ? ob : ob.friendly_link_name
724       }.each do |ob|
725         paths << {object: ob, depth: depth}
726         paths += sorted_paths.call tree[ob], depth+1
727       end
728       paths
729     end
730     @my_project_tree =
731       sorted_paths.call buildtree.call(children_of, 'me')
732     @shared_project_tree =
733       sorted_paths.call({'Shared with me' =>
734                           buildtree.call(children_of, false)})
735   end
736
737   helper_method :get_object
738   def get_object uuid
739     if @get_object.nil? and @objects
740       @get_object = @objects.each_with_object({}) do |object, h|
741         h[object.uuid] = object
742       end
743     end
744     @get_object ||= {}
745     @get_object[uuid]
746   end
747
748   helper_method :project_breadcrumbs
749   def project_breadcrumbs
750     crumbs = []
751     current = @name_link || @object
752     while current
753       if current.is_a?(Group) and current.group_class == 'project'
754         crumbs.prepend current
755       end
756       if current.is_a? Link
757         current = Group.find?(current.tail_uuid)
758       else
759         current = Group.find?(current.owner_uuid)
760       end
761     end
762     crumbs
763   end
764
765   helper_method :current_project_uuid
766   def current_project_uuid
767     if @object.is_a? Group and @object.group_class == 'project'
768       @object.uuid
769     elsif @name_link.andand.tail_uuid
770       @name_link.tail_uuid
771     elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
772       @object.owner_uuid
773     else
774       nil
775     end
776   end
777
778   # helper method to get links for given object or uuid
779   helper_method :links_for_object
780   def links_for_object object_or_uuid
781     raise ArgumentError, 'No input argument' unless object_or_uuid
782     preload_links_for_objects([object_or_uuid])
783     uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
784     @all_links_for[uuid] ||= []
785   end
786
787   # helper method to preload links for given objects and uuids
788   helper_method :preload_links_for_objects
789   def preload_links_for_objects objects_and_uuids
790     @all_links_for ||= {}
791
792     raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
793     return @all_links_for if objects_and_uuids.empty?
794
795     uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
796
797     # if already preloaded for all of these uuids, return
798     if not uuids.select { |x| @all_links_for[x].nil? }.any?
799       return @all_links_for
800     end
801
802     uuids.each do |x|
803       @all_links_for[x] = []
804     end
805
806     # TODO: make sure we get every page of results from API server
807     Link.filter([['head_uuid', 'in', uuids]]).each do |link|
808       @all_links_for[link.head_uuid] << link
809     end
810     @all_links_for
811   end
812
813   # helper method to get a certain number of objects of a specific type
814   # this can be used to replace any uses of: "dataclass.limit(n)"
815   helper_method :get_n_objects_of_class
816   def get_n_objects_of_class dataclass, size
817     @objects_map_for ||= {}
818
819     raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
820     raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
821
822     # if the objects_map_for has a value for this dataclass, and the
823     # size used to retrieve those objects is equal, return it
824     size_key = "#{dataclass.name}_size"
825     if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
826         (@objects_map_for[size_key] == size)
827       return @objects_map_for[dataclass.name]
828     end
829
830     @objects_map_for[size_key] = size
831     @objects_map_for[dataclass.name] = dataclass.limit(size)
832   end
833
834   # helper method to get collections for the given uuid
835   helper_method :collections_for_object
836   def collections_for_object uuid
837     raise ArgumentError, 'No input argument' unless uuid
838     preload_collections_for_objects([uuid])
839     @all_collections_for[uuid] ||= []
840   end
841
842   # helper method to preload collections for the given uuids
843   helper_method :preload_collections_for_objects
844   def preload_collections_for_objects uuids
845     @all_collections_for ||= {}
846
847     raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
848     return @all_collections_for if uuids.empty?
849
850     # if already preloaded for all of these uuids, return
851     if not uuids.select { |x| @all_collections_for[x].nil? }.any?
852       return @all_collections_for
853     end
854
855     uuids.each do |x|
856       @all_collections_for[x] = []
857     end
858
859     # TODO: make sure we get every page of results from API server
860     Collection.where(uuid: uuids).each do |collection|
861       @all_collections_for[collection.uuid] << collection
862     end
863     @all_collections_for
864   end
865
866   # helper method to get log collections for the given log
867   helper_method :log_collections_for_object
868   def log_collections_for_object log
869     raise ArgumentError, 'No input argument' unless log
870
871     preload_log_collections_for_objects([log])
872
873     uuid = log
874     fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
875     if fixup && fixup.size>1
876       uuid = fixup[1]
877     end
878
879     @all_log_collections_for[uuid] ||= []
880   end
881
882   # helper method to preload collections for the given uuids
883   helper_method :preload_log_collections_for_objects
884   def preload_log_collections_for_objects logs
885     @all_log_collections_for ||= {}
886
887     raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
888     return @all_log_collections_for if logs.empty?
889
890     uuids = []
891     logs.each do |log|
892       fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
893       if fixup && fixup.size>1
894         uuids << fixup[1]
895       else
896         uuids << log
897       end
898     end
899
900     # if already preloaded for all of these uuids, return
901     if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
902       return @all_log_collections_for
903     end
904
905     uuids.each do |x|
906       @all_log_collections_for[x] = []
907     end
908
909     # TODO: make sure we get every page of results from API server
910     Collection.where(uuid: uuids).each do |collection|
911       @all_log_collections_for[collection.uuid] << collection
912     end
913     @all_log_collections_for
914   end
915
916   # helper method to get object of a given dataclass and uuid
917   helper_method :object_for_dataclass
918   def object_for_dataclass dataclass, uuid
919     raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
920     preload_objects_for_dataclass(dataclass, [uuid])
921     @objects_for[uuid]
922   end
923
924   # helper method to preload objects for given dataclass and uuids
925   helper_method :preload_objects_for_dataclass
926   def preload_objects_for_dataclass dataclass, uuids
927     @objects_for ||= {}
928
929     raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
930     raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
931
932     return @objects_for if uuids.empty?
933
934     # if already preloaded for all of these uuids, return
935     if not uuids.select { |x| @objects_for[x].nil? }.any?
936       return @objects_for
937     end
938
939     dataclass.where(uuid: uuids).each do |obj|
940       @objects_for[obj.uuid] = obj
941     end
942     @objects_for
943   end
944
945   def wiselinks_layout
946     'body'
947   end
948 end