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