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