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