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