Merge branch '3296-user-profile' of git.curoverse.com:arvados into 3296-user-profile
[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       current_user.reload
521       user_prefs = current_user.prefs
522       current_user_profile = user_prefs[:profile] if user_prefs
523
524       profile_config.kind_of?(Array) && profile_config.andand.each do |entry|
525         if entry['required']
526           if !current_user_profile ||
527              !current_user_profile[entry['key'].to_sym] ||
528              current_user_profile[entry['key'].to_sym].empty?
529             missing_required_profile = true
530             break
531           end
532         end
533       end
534
535       if missing_required_profile
536         render 'users/profile'
537       end
538     end
539     true
540   end
541
542   def select_theme
543     return Rails.configuration.arvados_theme
544   end
545
546   @@notification_tests = []
547
548   @@notification_tests.push lambda { |controller, current_user|
549     AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
550       return nil
551     end
552     return lambda { |view|
553       view.render partial: 'notifications/ssh_key_notification'
554     }
555   }
556
557   #@@notification_tests.push lambda { |controller, current_user|
558   #  Job.limit(1).where(created_by: current_user.uuid).each do
559   #    return nil
560   #  end
561   #  return lambda { |view|
562   #    view.render partial: 'notifications/jobs_notification'
563   #  }
564   #}
565
566   @@notification_tests.push lambda { |controller, current_user|
567     Collection.limit(1).where(created_by: current_user.uuid).each do
568       return nil
569     end
570     return lambda { |view|
571       view.render partial: 'notifications/collections_notification'
572     }
573   }
574
575   @@notification_tests.push lambda { |controller, current_user|
576     PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
577       return nil
578     end
579     return lambda { |view|
580       view.render partial: 'notifications/pipelines_notification'
581     }
582   }
583
584   def check_user_notifications
585     return if params['tab_pane']
586
587     @notification_count = 0
588     @notifications = []
589
590     if current_user
591       @showallalerts = false
592       @@notification_tests.each do |t|
593         a = t.call(self, current_user)
594         if a
595           @notification_count += 1
596           @notifications.push a
597         end
598       end
599     end
600
601     if @notification_count == 0
602       @notification_count = ''
603     end
604   end
605
606   helper_method :all_projects
607   def all_projects
608     @all_projects ||= Group.
609       filter([['group_class','=','project']]).order('name')
610   end
611
612   helper_method :my_projects
613   def my_projects
614     return @my_projects if @my_projects
615     @my_projects = []
616     root_of = {}
617     all_projects.each do |g|
618       root_of[g.uuid] = g.owner_uuid
619       @my_projects << g
620     end
621     done = false
622     while not done
623       done = true
624       root_of = root_of.each_with_object({}) do |(child, parent), h|
625         if root_of[parent]
626           h[child] = root_of[parent]
627           done = false
628         else
629           h[child] = parent
630         end
631       end
632     end
633     @my_projects = @my_projects.select do |g|
634       root_of[g.uuid] == current_user.uuid
635     end
636   end
637
638   helper_method :projects_shared_with_me
639   def projects_shared_with_me
640     my_project_uuids = my_projects.collect &:uuid
641     all_projects.reject { |x| x.uuid.in? my_project_uuids }
642   end
643
644   helper_method :recent_jobs_and_pipelines
645   def recent_jobs_and_pipelines
646     (Job.limit(10) |
647      PipelineInstance.limit(10)).
648       sort_by do |x|
649       (x.finished_at || x.started_at rescue nil) || x.modified_at || x.created_at
650     end.reverse
651   end
652
653   helper_method :my_project_tree
654   def my_project_tree
655     build_project_trees
656     @my_project_tree
657   end
658
659   helper_method :shared_project_tree
660   def shared_project_tree
661     build_project_trees
662     @shared_project_tree
663   end
664
665   def build_project_trees
666     return if @my_project_tree and @shared_project_tree
667     parent_of = {current_user.uuid => 'me'}
668     all_projects.each do |ob|
669       parent_of[ob.uuid] = ob.owner_uuid
670     end
671     children_of = {false => [], 'me' => [current_user]}
672     all_projects.each do |ob|
673       if ob.owner_uuid != current_user.uuid and
674           not parent_of.has_key? ob.owner_uuid
675         parent_of[ob.uuid] = false
676       end
677       children_of[parent_of[ob.uuid]] ||= []
678       children_of[parent_of[ob.uuid]] << ob
679     end
680     buildtree = lambda do |children_of, root_uuid=false|
681       tree = {}
682       children_of[root_uuid].andand.each do |ob|
683         tree[ob] = buildtree.call(children_of, ob.uuid)
684       end
685       tree
686     end
687     sorted_paths = lambda do |tree, depth=0|
688       paths = []
689       tree.keys.sort_by { |ob|
690         ob.is_a?(String) ? ob : ob.friendly_link_name
691       }.each do |ob|
692         paths << {object: ob, depth: depth}
693         paths += sorted_paths.call tree[ob], depth+1
694       end
695       paths
696     end
697     @my_project_tree =
698       sorted_paths.call buildtree.call(children_of, 'me')
699     @shared_project_tree =
700       sorted_paths.call({'Shared with me' =>
701                           buildtree.call(children_of, false)})
702   end
703
704   helper_method :get_object
705   def get_object uuid
706     if @get_object.nil? and @objects
707       @get_object = @objects.each_with_object({}) do |object, h|
708         h[object.uuid] = object
709       end
710     end
711     @get_object ||= {}
712     @get_object[uuid]
713   end
714
715   helper_method :project_breadcrumbs
716   def project_breadcrumbs
717     crumbs = []
718     current = @name_link || @object
719     while current
720       if current.is_a?(Group) and current.group_class == 'project'
721         crumbs.prepend current
722       end
723       if current.is_a? Link
724         current = Group.find?(current.tail_uuid)
725       else
726         current = Group.find?(current.owner_uuid)
727       end
728     end
729     crumbs
730   end
731
732   helper_method :current_project_uuid
733   def current_project_uuid
734     if @object.is_a? Group and @object.group_class == 'project'
735       @object.uuid
736     elsif @name_link.andand.tail_uuid
737       @name_link.tail_uuid
738     elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
739       @object.owner_uuid
740     else
741       nil
742     end
743   end
744
745   # helper method to get links for given object or uuid
746   helper_method :links_for_object
747   def links_for_object object_or_uuid
748     raise ArgumentError, 'No input argument' unless object_or_uuid
749     preload_links_for_objects([object_or_uuid])
750     uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
751     @all_links_for[uuid] ||= []
752   end
753
754   # helper method to preload links for given objects and uuids
755   helper_method :preload_links_for_objects
756   def preload_links_for_objects objects_and_uuids
757     @all_links_for ||= {}
758
759     raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
760     return @all_links_for if objects_and_uuids.empty?
761
762     uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
763
764     # if already preloaded for all of these uuids, return
765     if not uuids.select { |x| @all_links_for[x].nil? }.any?
766       return @all_links_for
767     end
768
769     uuids.each do |x|
770       @all_links_for[x] = []
771     end
772
773     # TODO: make sure we get every page of results from API server
774     Link.filter([['head_uuid', 'in', uuids]]).each do |link|
775       @all_links_for[link.head_uuid] << link
776     end
777     @all_links_for
778   end
779
780   # helper method to get a certain number of objects of a specific type
781   # this can be used to replace any uses of: "dataclass.limit(n)"
782   helper_method :get_n_objects_of_class
783   def get_n_objects_of_class dataclass, size
784     @objects_map_for ||= {}
785
786     raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
787     raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
788
789     # if the objects_map_for has a value for this dataclass, and the
790     # size used to retrieve those objects is equal, return it
791     size_key = "#{dataclass.name}_size"
792     if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
793         (@objects_map_for[size_key] == size)
794       return @objects_map_for[dataclass.name]
795     end
796
797     @objects_map_for[size_key] = size
798     @objects_map_for[dataclass.name] = dataclass.limit(size)
799   end
800
801   # helper method to get collections for the given uuid
802   helper_method :collections_for_object
803   def collections_for_object uuid
804     raise ArgumentError, 'No input argument' unless uuid
805     preload_collections_for_objects([uuid])
806     @all_collections_for[uuid] ||= []
807   end
808
809   # helper method to preload collections for the given uuids
810   helper_method :preload_collections_for_objects
811   def preload_collections_for_objects uuids
812     @all_collections_for ||= {}
813
814     raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
815     return @all_collections_for if uuids.empty?
816
817     # if already preloaded for all of these uuids, return
818     if not uuids.select { |x| @all_collections_for[x].nil? }.any?
819       return @all_collections_for
820     end
821
822     uuids.each do |x|
823       @all_collections_for[x] = []
824     end
825
826     # TODO: make sure we get every page of results from API server
827     Collection.where(uuid: uuids).each do |collection|
828       @all_collections_for[collection.uuid] << collection
829     end
830     @all_collections_for
831   end
832
833   # helper method to get log collections for the given log
834   helper_method :log_collections_for_object
835   def log_collections_for_object log
836     raise ArgumentError, 'No input argument' unless log
837
838     preload_log_collections_for_objects([log])
839
840     uuid = log
841     fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
842     if fixup && fixup.size>1
843       uuid = fixup[1]
844     end
845
846     @all_log_collections_for[uuid] ||= []
847   end
848
849   # helper method to preload collections for the given uuids
850   helper_method :preload_log_collections_for_objects
851   def preload_log_collections_for_objects logs
852     @all_log_collections_for ||= {}
853
854     raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
855     return @all_log_collections_for if logs.empty?
856
857     uuids = []
858     logs.each do |log|
859       fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
860       if fixup && fixup.size>1
861         uuids << fixup[1]
862       else
863         uuids << log
864       end
865     end
866
867     # if already preloaded for all of these uuids, return
868     if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
869       return @all_log_collections_for
870     end
871
872     uuids.each do |x|
873       @all_log_collections_for[x] = []
874     end
875
876     # TODO: make sure we get every page of results from API server
877     Collection.where(uuid: uuids).each do |collection|
878       @all_log_collections_for[collection.uuid] << collection
879     end
880     @all_log_collections_for
881   end
882
883   # helper method to get object of a given dataclass and uuid
884   helper_method :object_for_dataclass
885   def object_for_dataclass dataclass, uuid
886     raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
887     preload_objects_for_dataclass(dataclass, [uuid])
888     @objects_for[uuid]
889   end
890
891   # helper method to preload objects for given dataclass and uuids
892   helper_method :preload_objects_for_dataclass
893   def preload_objects_for_dataclass dataclass, uuids
894     @objects_for ||= {}
895
896     raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
897     raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
898
899     return @objects_for if uuids.empty?
900
901     # if already preloaded for all of these uuids, return
902     if not uuids.select { |x| @objects_for[x].nil? }.any?
903       return @objects_for
904     end
905
906     dataclass.where(uuid: uuids).each do |obj|
907       @objects_for[obj.uuid] = obj
908     end
909     @objects_for
910   end
911
912   def wiselinks_layout
913     'body'
914   end
915 end