3354: try again with edit (pencil) icon to the _right_ of the editable textile-render...
[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_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 do
178         extra_attrs = { href: url_for(@object) }
179         @object.textile_attributes.each do |textile_attr|
180           extra_attrs.merge!({ "#{textile_attr}Textile" => view_context.render_content_from_database(@object.attributes[textile_attr]) })
181         end
182         render json: @object.attributes.merge(extra_attrs)
183       end
184       f.html {
185         if params['tab_pane']
186           comparable = self.respond_to? :compare
187           render(partial: 'show_' + params['tab_pane'].downcase,
188                  locals: { comparable: comparable, objects: @objects })
189         elsif request.method.in? ['GET', 'HEAD']
190           render
191         else
192           redirect_to params[:return_to] || @object
193         end
194       }
195       f.js { render }
196     end
197   end
198
199   def choose
200     params[:limit] ||= 40
201     find_objects_for_index if !@objects
202     respond_to do |f|
203       if params[:partial]
204         f.json {
205           render json: {
206             content: render_to_string(partial: "choose_rows.html",
207                                       formats: [:html]),
208             next_page_href: next_page_href(partial: params[:partial])
209           }
210         }
211       end
212       f.js {
213         render partial: 'choose', locals: {multiple: params[:multiple]}
214       }
215     end
216   end
217
218   def render_content
219     if !@object
220       return render_not_found("object not found")
221     end
222   end
223
224   def new
225     @object = model_class.new
226   end
227
228   def update
229     @updates ||= params[@object.resource_param_name.to_sym]
230     @updates.keys.each do |attr|
231       if @object.send(attr).is_a? Hash
232         if @updates[attr].is_a? String
233           @updates[attr] = Oj.load @updates[attr]
234         end
235         if params[:merge] || params["merge_#{attr}".to_sym]
236           # Merge provided Hash with current Hash, instead of
237           # replacing.
238           @updates[attr] = @object.send(attr).with_indifferent_access.
239             deep_merge(@updates[attr].with_indifferent_access)
240         end
241       end
242     end
243     if @object.update_attributes @updates
244       show
245     else
246       self.render_error status: 422
247     end
248   end
249
250   def create
251     @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
252     @new_resource_attrs ||= {}
253     @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
254     @object ||= model_class.new @new_resource_attrs, params["options"]
255     if @object.save
256       respond_to do |f|
257         f.json { render json: @object.attributes.merge(href: url_for(@object)) }
258         f.html {
259           redirect_to @object
260         }
261         f.js { render }
262       end
263     else
264       self.render_error status: 422
265     end
266   end
267
268   # Clone the given object, merging any attribute values supplied as
269   # with a create action.
270   def copy
271     @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
272     @new_resource_attrs ||= {}
273     @object = @object.dup
274     @object.update_attributes @new_resource_attrs
275     if not @new_resource_attrs[:name] and @object.respond_to? :name
276       if @object.name and @object.name != ''
277         @object.name = "Copy of #{@object.name}"
278       else
279         @object.name = ""
280       end
281     end
282     @object.save!
283     show
284   end
285
286   def destroy
287     if @object.destroy
288       respond_to do |f|
289         f.json { render json: @object }
290         f.html {
291           redirect_to(params[:return_to] || :back)
292         }
293         f.js { render }
294       end
295     else
296       self.render_error status: 422
297     end
298   end
299
300   def current_user
301     Thread.current[:user]
302   end
303
304   def model_class
305     controller_name.classify.constantize
306   end
307
308   def breadcrumb_page_name
309     (@breadcrumb_page_name ||
310      (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
311      action_name)
312   end
313
314   def index_pane_list
315     %w(Recent)
316   end
317
318   def show_pane_list
319     %w(Attributes Advanced)
320   end
321
322   protected
323
324   def strip_token_from_path(path)
325     path.sub(/([\?&;])api_token=[^&;]*[&;]?/, '\1')
326   end
327
328   def redirect_to_login
329     respond_to do |f|
330       f.html {
331         if request.method.in? ['GET', 'HEAD']
332           redirect_to arvados_api_client.arvados_login_url(return_to: strip_token_from_path(request.url))
333         else
334           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."
335           redirect_to :back
336         end
337       }
338       f.json {
339         @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.']
340         self.render_error status: 422
341       }
342     end
343     false  # For convenience to return from callbacks
344   end
345
346   def using_specific_api_token(api_token)
347     start_values = {}
348     [:arvados_api_token, :user].each do |key|
349       start_values[key] = Thread.current[key]
350     end
351     load_api_token(api_token)
352     begin
353       yield
354     ensure
355       start_values.each_key { |key| Thread.current[key] = start_values[key] }
356     end
357   end
358
359
360   def accept_uuid_as_id_param
361     if params[:id] and params[:id].match /\D/
362       params[:uuid] = params.delete :id
363     end
364   end
365
366   def find_object_by_uuid
367     begin
368       if not model_class
369         @object = nil
370       elsif not params[:uuid].is_a?(String)
371         @object = model_class.where(uuid: params[:uuid]).first
372       elsif params[:uuid].empty?
373         @object = nil
374       elsif (model_class != Link and
375              resource_class_for_uuid(params[:uuid]) == Link)
376         @name_link = Link.find(params[:uuid])
377         @object = model_class.find(@name_link.head_uuid)
378       else
379         @object = model_class.find(params[:uuid])
380       end
381     rescue ArvadosApiClient::NotFoundException, RuntimeError => error
382       if error.is_a?(RuntimeError) and (error.message !~ /^argument to find\(/)
383         raise
384       end
385       render_not_found(error)
386       return false
387     end
388   end
389
390   def thread_clear
391     load_api_token(nil)
392     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
393     yield
394     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
395   end
396
397   # Set up the thread with the given API token and associated user object.
398   def load_api_token(new_token)
399     Thread.current[:arvados_api_token] = new_token
400     if new_token.nil?
401       Thread.current[:user] = nil
402     elsif (new_token == session[:arvados_api_token]) and
403         session[:user].andand[:is_active]
404       Thread.current[:user] = User.new(session[:user])
405     else
406       Thread.current[:user] = User.current
407     end
408   end
409
410   # If there's a valid api_token parameter, set up the session with that
411   # user's information.  Return true if the method redirects the request
412   # (usually a post-login redirect); false otherwise.
413   def setup_user_session
414     return false unless params[:api_token]
415     Thread.current[:arvados_api_token] = params[:api_token]
416     begin
417       user = User.current
418     rescue ArvadosApiClient::NotLoggedInException
419       false  # We may redirect to login, or not, based on the current action.
420     else
421       session[:arvados_api_token] = params[:api_token]
422       session[:user] = {
423         uuid: user.uuid,
424         email: user.email,
425         first_name: user.first_name,
426         last_name: user.last_name,
427         is_active: user.is_active,
428         is_admin: user.is_admin,
429         prefs: user.prefs
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 select_theme
525     return Rails.configuration.arvados_theme
526   end
527
528   @@notification_tests = []
529
530   @@notification_tests.push lambda { |controller, current_user|
531     AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
532       return nil
533     end
534     return lambda { |view|
535       view.render partial: 'notifications/ssh_key_notification'
536     }
537   }
538
539   #@@notification_tests.push lambda { |controller, current_user|
540   #  Job.limit(1).where(created_by: current_user.uuid).each do
541   #    return nil
542   #  end
543   #  return lambda { |view|
544   #    view.render partial: 'notifications/jobs_notification'
545   #  }
546   #}
547
548   @@notification_tests.push lambda { |controller, current_user|
549     Collection.limit(1).where(created_by: current_user.uuid).each do
550       return nil
551     end
552     return lambda { |view|
553       view.render partial: 'notifications/collections_notification'
554     }
555   }
556
557   @@notification_tests.push lambda { |controller, current_user|
558     PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
559       return nil
560     end
561     return lambda { |view|
562       view.render partial: 'notifications/pipelines_notification'
563     }
564   }
565
566   def check_user_notifications
567     return if params['tab_pane']
568
569     @notification_count = 0
570     @notifications = []
571
572     if current_user
573       @showallalerts = false
574       @@notification_tests.each do |t|
575         a = t.call(self, current_user)
576         if a
577           @notification_count += 1
578           @notifications.push a
579         end
580       end
581     end
582
583     if @notification_count == 0
584       @notification_count = ''
585     end
586   end
587
588   helper_method :all_projects
589   def all_projects
590     @all_projects ||= Group.
591       filter([['group_class','=','project']]).order('name')
592   end
593
594   helper_method :my_projects
595   def my_projects
596     return @my_projects if @my_projects
597     @my_projects = []
598     root_of = {}
599     all_projects.each do |g|
600       root_of[g.uuid] = g.owner_uuid
601       @my_projects << g
602     end
603     done = false
604     while not done
605       done = true
606       root_of = root_of.each_with_object({}) do |(child, parent), h|
607         if root_of[parent]
608           h[child] = root_of[parent]
609           done = false
610         else
611           h[child] = parent
612         end
613       end
614     end
615     @my_projects = @my_projects.select do |g|
616       root_of[g.uuid] == current_user.uuid
617     end
618   end
619
620   helper_method :projects_shared_with_me
621   def projects_shared_with_me
622     my_project_uuids = my_projects.collect &:uuid
623     all_projects.reject { |x| x.uuid.in? my_project_uuids }
624   end
625
626   helper_method :recent_jobs_and_pipelines
627   def recent_jobs_and_pipelines
628     (Job.limit(10) |
629      PipelineInstance.limit(10)).
630       sort_by do |x|
631       (x.finished_at || x.started_at rescue nil) || x.modified_at || x.created_at
632     end.reverse
633   end
634
635   helper_method :my_project_tree
636   def my_project_tree
637     build_project_trees
638     @my_project_tree
639   end
640
641   helper_method :shared_project_tree
642   def shared_project_tree
643     build_project_trees
644     @shared_project_tree
645   end
646
647   def build_project_trees
648     return if @my_project_tree and @shared_project_tree
649     parent_of = {current_user.uuid => 'me'}
650     all_projects.each do |ob|
651       parent_of[ob.uuid] = ob.owner_uuid
652     end
653     children_of = {false => [], 'me' => [current_user]}
654     all_projects.each do |ob|
655       if ob.owner_uuid != current_user.uuid and
656           not parent_of.has_key? ob.owner_uuid
657         parent_of[ob.uuid] = false
658       end
659       children_of[parent_of[ob.uuid]] ||= []
660       children_of[parent_of[ob.uuid]] << ob
661     end
662     buildtree = lambda do |children_of, root_uuid=false|
663       tree = {}
664       children_of[root_uuid].andand.each do |ob|
665         tree[ob] = buildtree.call(children_of, ob.uuid)
666       end
667       tree
668     end
669     sorted_paths = lambda do |tree, depth=0|
670       paths = []
671       tree.keys.sort_by { |ob|
672         ob.is_a?(String) ? ob : ob.friendly_link_name
673       }.each do |ob|
674         paths << {object: ob, depth: depth}
675         paths += sorted_paths.call tree[ob], depth+1
676       end
677       paths
678     end
679     @my_project_tree =
680       sorted_paths.call buildtree.call(children_of, 'me')
681     @shared_project_tree =
682       sorted_paths.call({'Shared with me' =>
683                           buildtree.call(children_of, false)})
684   end
685
686   helper_method :get_object
687   def get_object uuid
688     if @get_object.nil? and @objects
689       @get_object = @objects.each_with_object({}) do |object, h|
690         h[object.uuid] = object
691       end
692     end
693     @get_object ||= {}
694     @get_object[uuid]
695   end
696
697   helper_method :project_breadcrumbs
698   def project_breadcrumbs
699     crumbs = []
700     current = @name_link || @object
701     while current
702       if current.is_a?(Group) and current.group_class == 'project'
703         crumbs.prepend current
704       end
705       if current.is_a? Link
706         current = Group.find?(current.tail_uuid)
707       else
708         current = Group.find?(current.owner_uuid)
709       end
710     end
711     crumbs
712   end
713
714   helper_method :current_project_uuid
715   def current_project_uuid
716     if @object.is_a? Group and @object.group_class == 'project'
717       @object.uuid
718     elsif @name_link.andand.tail_uuid
719       @name_link.tail_uuid
720     elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
721       @object.owner_uuid
722     else
723       nil
724     end
725   end
726
727   # helper method to get links for given object or uuid
728   helper_method :links_for_object
729   def links_for_object object_or_uuid
730     raise ArgumentError, 'No input argument' unless object_or_uuid
731     preload_links_for_objects([object_or_uuid])
732     uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
733     @all_links_for[uuid] ||= []
734   end
735
736   # helper method to preload links for given objects and uuids
737   helper_method :preload_links_for_objects
738   def preload_links_for_objects objects_and_uuids
739     @all_links_for ||= {}
740
741     raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
742     return @all_links_for if objects_and_uuids.empty?
743
744     uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
745
746     # if already preloaded for all of these uuids, return
747     if not uuids.select { |x| @all_links_for[x].nil? }.any?
748       return @all_links_for
749     end
750
751     uuids.each do |x|
752       @all_links_for[x] = []
753     end
754
755     # TODO: make sure we get every page of results from API server
756     Link.filter([['head_uuid', 'in', uuids]]).each do |link|
757       @all_links_for[link.head_uuid] << link
758     end
759     @all_links_for
760   end
761
762   # helper method to get a certain number of objects of a specific type
763   # this can be used to replace any uses of: "dataclass.limit(n)"
764   helper_method :get_n_objects_of_class
765   def get_n_objects_of_class dataclass, size
766     @objects_map_for ||= {}
767
768     raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
769     raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
770
771     # if the objects_map_for has a value for this dataclass, and the
772     # size used to retrieve those objects is equal, return it
773     size_key = "#{dataclass.name}_size"
774     if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
775         (@objects_map_for[size_key] == size)
776       return @objects_map_for[dataclass.name]
777     end
778
779     @objects_map_for[size_key] = size
780     @objects_map_for[dataclass.name] = dataclass.limit(size)
781   end
782
783   # helper method to get collections for the given uuid
784   helper_method :collections_for_object
785   def collections_for_object uuid
786     raise ArgumentError, 'No input argument' unless uuid
787     preload_collections_for_objects([uuid])
788     @all_collections_for[uuid] ||= []
789   end
790
791   # helper method to preload collections for the given uuids
792   helper_method :preload_collections_for_objects
793   def preload_collections_for_objects uuids
794     @all_collections_for ||= {}
795
796     raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
797     return @all_collections_for if uuids.empty?
798
799     # if already preloaded for all of these uuids, return
800     if not uuids.select { |x| @all_collections_for[x].nil? }.any?
801       return @all_collections_for
802     end
803
804     uuids.each do |x|
805       @all_collections_for[x] = []
806     end
807
808     # TODO: make sure we get every page of results from API server
809     Collection.where(uuid: uuids).each do |collection|
810       @all_collections_for[collection.uuid] << collection
811     end
812     @all_collections_for
813   end
814
815   # helper method to get log collections for the given log
816   helper_method :log_collections_for_object
817   def log_collections_for_object log
818     raise ArgumentError, 'No input argument' unless log
819
820     preload_log_collections_for_objects([log])
821
822     uuid = log
823     fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
824     if fixup && fixup.size>1
825       uuid = fixup[1]
826     end
827
828     @all_log_collections_for[uuid] ||= []
829   end
830
831   # helper method to preload collections for the given uuids
832   helper_method :preload_log_collections_for_objects
833   def preload_log_collections_for_objects logs
834     @all_log_collections_for ||= {}
835
836     raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
837     return @all_log_collections_for if logs.empty?
838
839     uuids = []
840     logs.each do |log|
841       fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
842       if fixup && fixup.size>1
843         uuids << fixup[1]
844       else
845         uuids << log
846       end
847     end
848
849     # if already preloaded for all of these uuids, return
850     if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
851       return @all_log_collections_for
852     end
853
854     uuids.each do |x|
855       @all_log_collections_for[x] = []
856     end
857
858     # TODO: make sure we get every page of results from API server
859     Collection.where(uuid: uuids).each do |collection|
860       @all_log_collections_for[collection.uuid] << collection
861     end
862     @all_log_collections_for
863   end
864
865   # helper method to get object of a given dataclass and uuid
866   helper_method :object_for_dataclass
867   def object_for_dataclass dataclass, uuid
868     raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
869     preload_objects_for_dataclass(dataclass, [uuid])
870     @objects_for[uuid]
871   end
872
873   # helper method to preload objects for given dataclass and uuids
874   helper_method :preload_objects_for_dataclass
875   def preload_objects_for_dataclass dataclass, uuids
876     @objects_for ||= {}
877
878     raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
879     raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
880
881     return @objects_for if uuids.empty?
882
883     # if already preloaded for all of these uuids, return
884     if not uuids.select { |x| @objects_for[x].nil? }.any?
885       return @objects_for
886     end
887
888     dataclass.where(uuid: uuids).each do |obj|
889       @objects_for[obj.uuid] = obj
890     end
891     @objects_for
892   end
893
894   def wiselinks_layout
895     'body'
896   end
897 end