cd74dffdfdbfea66183f730b81cf8bec90094b81
[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     elsif (new_token == session[:arvados_api_token]) and
398         session[:user].andand[:is_active]
399       Thread.current[:user] = User.new(session[:user])
400     else
401       Thread.current[:user] = User.current
402     end
403   end
404
405   # If there's a valid api_token parameter, set up the session with that
406   # user's information.  Return true if the method redirects the request
407   # (usually a post-login redirect); false otherwise.
408   def setup_user_session
409     return false unless params[:api_token]
410     Thread.current[:arvados_api_token] = params[:api_token]
411     begin
412       user = User.current
413     rescue ArvadosApiClient::NotLoggedInException
414       false  # We may redirect to login, or not, based on the current action.
415     else
416       session[:arvados_api_token] = params[:api_token]
417       session[:user] = {
418         uuid: user.uuid,
419         email: user.email,
420         first_name: user.first_name,
421         last_name: user.last_name,
422         is_active: user.is_active,
423         is_admin: user.is_admin,
424         prefs: user.prefs
425       }
426
427       if !request.format.json? and request.method.in? ['GET', 'HEAD']
428         # Repeat this request with api_token in the (new) session
429         # cookie instead of the query string.  This prevents API
430         # tokens from appearing in (and being inadvisedly copied
431         # and pasted from) browser Location bars.
432         redirect_to strip_token_from_path(request.fullpath)
433         true
434       else
435         false
436       end
437     ensure
438       Thread.current[:arvados_api_token] = nil
439     end
440   end
441
442   # Save the session API token in thread-local storage, and yield.
443   # This method also takes care of session setup if the request
444   # provides a valid api_token parameter.
445   # If a token is unavailable or expired, the block is still run, with
446   # a nil token.
447   def set_thread_api_token
448     if Thread.current[:arvados_api_token]
449       yield   # An API token has already been found - pass it through.
450       return
451     elsif setup_user_session
452       return  # A new session was set up and received a response.
453     end
454
455     begin
456       load_api_token(session[:arvados_api_token])
457       yield
458     rescue ArvadosApiClient::NotLoggedInException
459       # If we got this error with a token, it must've expired.
460       # Retry the request without a token.
461       unless Thread.current[:arvados_api_token].nil?
462         load_api_token(nil)
463         yield
464       end
465     ensure
466       # Remove token in case this Thread is used for anything else.
467       load_api_token(nil)
468     end
469   end
470
471   # Reroute this request if an API token is unavailable.
472   def require_thread_api_token
473     if Thread.current[:arvados_api_token]
474       yield
475     elsif session[:arvados_api_token]
476       # Expired session. Clear it before refreshing login so that,
477       # if this login procedure fails, we end up showing the "please
478       # log in" page instead of getting stuck in a redirect loop.
479       session.delete :arvados_api_token
480       redirect_to_login
481     else
482       render 'users/welcome'
483     end
484   end
485
486   def ensure_current_user_is_admin
487     unless current_user and current_user.is_admin
488       @errors = ['Permission denied']
489       self.render_error status: 401
490     end
491   end
492
493   def check_user_agreements
494     if current_user && !current_user.is_active
495       if not current_user.is_invited
496         return render 'users/inactive'
497       end
498       signatures = UserAgreement.signatures
499       @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
500       @required_user_agreements = UserAgreement.all.map do |ua|
501         if not @signed_ua_uuids.index ua.uuid
502           Collection.find(ua.uuid)
503         end
504       end.compact
505       if @required_user_agreements.empty?
506         # No agreements to sign. Perhaps we just need to ask?
507         current_user.activate
508         if !current_user.is_active
509           logger.warn "#{current_user.uuid.inspect}: " +
510             "No user agreements to sign, but activate failed!"
511         end
512       end
513       if !current_user.is_active
514         render 'user_agreements/index'
515       end
516     end
517     true
518   end
519
520   def check_user_profile
521     profile_config = Rails.configuration.user_profile_form_fields
522
523     if request.method.downcase != 'get' || params[:partial] ||
524        params[:tab_pane] || params[:action_method] ||
525        params[:action] == 'setup_popup'
526       return true
527     end
528
529     if current_user && profile_config
530       missing_required_profile = false
531
532       user_prefs = current_user.prefs
533       current_user.reload if !user_prefs[:profile]
534       user_prefs = current_user.prefs
535       current_user_profile = user_prefs[:profile] if user_prefs
536
537       profile_config.kind_of?(Array) && profile_config.andand.each do |entry|
538         if entry['required']
539           if !current_user_profile || !current_user_profile[entry['key'].to_sym]
540             missing_required_profile = true
541             break
542           end
543         end
544       end
545
546       if missing_required_profile
547         render 'users/profile'
548       end
549     end
550     true
551   end
552
553   def select_theme
554     return Rails.configuration.arvados_theme
555   end
556
557   @@notification_tests = []
558
559   @@notification_tests.push lambda { |controller, current_user|
560     AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
561       return nil
562     end
563     return lambda { |view|
564       view.render partial: 'notifications/ssh_key_notification'
565     }
566   }
567
568   #@@notification_tests.push lambda { |controller, current_user|
569   #  Job.limit(1).where(created_by: current_user.uuid).each do
570   #    return nil
571   #  end
572   #  return lambda { |view|
573   #    view.render partial: 'notifications/jobs_notification'
574   #  }
575   #}
576
577   @@notification_tests.push lambda { |controller, current_user|
578     Collection.limit(1).where(created_by: current_user.uuid).each do
579       return nil
580     end
581     return lambda { |view|
582       view.render partial: 'notifications/collections_notification'
583     }
584   }
585
586   @@notification_tests.push lambda { |controller, current_user|
587     PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
588       return nil
589     end
590     return lambda { |view|
591       view.render partial: 'notifications/pipelines_notification'
592     }
593   }
594
595   def check_user_notifications
596     return if params['tab_pane']
597
598     @notification_count = 0
599     @notifications = []
600
601     if current_user
602       @showallalerts = false
603       @@notification_tests.each do |t|
604         a = t.call(self, current_user)
605         if a
606           @notification_count += 1
607           @notifications.push a
608         end
609       end
610     end
611
612     if @notification_count == 0
613       @notification_count = ''
614     end
615   end
616
617   helper_method :all_projects
618   def all_projects
619     @all_projects ||= Group.
620       filter([['group_class','=','project']]).order('name')
621   end
622
623   helper_method :my_projects
624   def my_projects
625     return @my_projects if @my_projects
626     @my_projects = []
627     root_of = {}
628     all_projects.each do |g|
629       root_of[g.uuid] = g.owner_uuid
630       @my_projects << g
631     end
632     done = false
633     while not done
634       done = true
635       root_of = root_of.each_with_object({}) do |(child, parent), h|
636         if root_of[parent]
637           h[child] = root_of[parent]
638           done = false
639         else
640           h[child] = parent
641         end
642       end
643     end
644     @my_projects = @my_projects.select do |g|
645       root_of[g.uuid] == current_user.uuid
646     end
647   end
648
649   helper_method :projects_shared_with_me
650   def projects_shared_with_me
651     my_project_uuids = my_projects.collect &:uuid
652     all_projects.reject { |x| x.uuid.in? my_project_uuids }
653   end
654
655   helper_method :recent_jobs_and_pipelines
656   def recent_jobs_and_pipelines
657     (Job.limit(10) |
658      PipelineInstance.limit(10)).
659       sort_by do |x|
660       (x.finished_at || x.started_at rescue nil) || x.modified_at || x.created_at
661     end.reverse
662   end
663
664   helper_method :my_project_tree
665   def my_project_tree
666     build_project_trees
667     @my_project_tree
668   end
669
670   helper_method :shared_project_tree
671   def shared_project_tree
672     build_project_trees
673     @shared_project_tree
674   end
675
676   def build_project_trees
677     return if @my_project_tree and @shared_project_tree
678     parent_of = {current_user.uuid => 'me'}
679     all_projects.each do |ob|
680       parent_of[ob.uuid] = ob.owner_uuid
681     end
682     children_of = {false => [], 'me' => [current_user]}
683     all_projects.each do |ob|
684       if ob.owner_uuid != current_user.uuid and
685           not parent_of.has_key? ob.owner_uuid
686         parent_of[ob.uuid] = false
687       end
688       children_of[parent_of[ob.uuid]] ||= []
689       children_of[parent_of[ob.uuid]] << ob
690     end
691     buildtree = lambda do |children_of, root_uuid=false|
692       tree = {}
693       children_of[root_uuid].andand.each do |ob|
694         tree[ob] = buildtree.call(children_of, ob.uuid)
695       end
696       tree
697     end
698     sorted_paths = lambda do |tree, depth=0|
699       paths = []
700       tree.keys.sort_by { |ob|
701         ob.is_a?(String) ? ob : ob.friendly_link_name
702       }.each do |ob|
703         paths << {object: ob, depth: depth}
704         paths += sorted_paths.call tree[ob], depth+1
705       end
706       paths
707     end
708     @my_project_tree =
709       sorted_paths.call buildtree.call(children_of, 'me')
710     @shared_project_tree =
711       sorted_paths.call({'Shared with me' =>
712                           buildtree.call(children_of, false)})
713   end
714
715   helper_method :get_object
716   def get_object uuid
717     if @get_object.nil? and @objects
718       @get_object = @objects.each_with_object({}) do |object, h|
719         h[object.uuid] = object
720       end
721     end
722     @get_object ||= {}
723     @get_object[uuid]
724   end
725
726   helper_method :project_breadcrumbs
727   def project_breadcrumbs
728     crumbs = []
729     current = @name_link || @object
730     while current
731       if current.is_a?(Group) and current.group_class == 'project'
732         crumbs.prepend current
733       end
734       if current.is_a? Link
735         current = Group.find?(current.tail_uuid)
736       else
737         current = Group.find?(current.owner_uuid)
738       end
739     end
740     crumbs
741   end
742
743   helper_method :current_project_uuid
744   def current_project_uuid
745     if @object.is_a? Group and @object.group_class == 'project'
746       @object.uuid
747     elsif @name_link.andand.tail_uuid
748       @name_link.tail_uuid
749     elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
750       @object.owner_uuid
751     else
752       nil
753     end
754   end
755
756   # helper method to get links for given object or uuid
757   helper_method :links_for_object
758   def links_for_object object_or_uuid
759     raise ArgumentError, 'No input argument' unless object_or_uuid
760     preload_links_for_objects([object_or_uuid])
761     uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
762     @all_links_for[uuid] ||= []
763   end
764
765   # helper method to preload links for given objects and uuids
766   helper_method :preload_links_for_objects
767   def preload_links_for_objects objects_and_uuids
768     @all_links_for ||= {}
769
770     raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
771     return @all_links_for if objects_and_uuids.empty?
772
773     uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
774
775     # if already preloaded for all of these uuids, return
776     if not uuids.select { |x| @all_links_for[x].nil? }.any?
777       return @all_links_for
778     end
779
780     uuids.each do |x|
781       @all_links_for[x] = []
782     end
783
784     # TODO: make sure we get every page of results from API server
785     Link.filter([['head_uuid', 'in', uuids]]).each do |link|
786       @all_links_for[link.head_uuid] << link
787     end
788     @all_links_for
789   end
790
791   # helper method to get a certain number of objects of a specific type
792   # this can be used to replace any uses of: "dataclass.limit(n)"
793   helper_method :get_n_objects_of_class
794   def get_n_objects_of_class dataclass, size
795     @objects_map_for ||= {}
796
797     raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
798     raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
799
800     # if the objects_map_for has a value for this dataclass, and the
801     # size used to retrieve those objects is equal, return it
802     size_key = "#{dataclass.name}_size"
803     if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
804         (@objects_map_for[size_key] == size)
805       return @objects_map_for[dataclass.name]
806     end
807
808     @objects_map_for[size_key] = size
809     @objects_map_for[dataclass.name] = dataclass.limit(size)
810   end
811
812   # helper method to get collections for the given uuid
813   helper_method :collections_for_object
814   def collections_for_object uuid
815     raise ArgumentError, 'No input argument' unless uuid
816     preload_collections_for_objects([uuid])
817     @all_collections_for[uuid] ||= []
818   end
819
820   # helper method to preload collections for the given uuids
821   helper_method :preload_collections_for_objects
822   def preload_collections_for_objects uuids
823     @all_collections_for ||= {}
824
825     raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
826     return @all_collections_for if uuids.empty?
827
828     # if already preloaded for all of these uuids, return
829     if not uuids.select { |x| @all_collections_for[x].nil? }.any?
830       return @all_collections_for
831     end
832
833     uuids.each do |x|
834       @all_collections_for[x] = []
835     end
836
837     # TODO: make sure we get every page of results from API server
838     Collection.where(uuid: uuids).each do |collection|
839       @all_collections_for[collection.uuid] << collection
840     end
841     @all_collections_for
842   end
843
844   # helper method to get log collections for the given log
845   helper_method :log_collections_for_object
846   def log_collections_for_object log
847     raise ArgumentError, 'No input argument' unless log
848
849     preload_log_collections_for_objects([log])
850
851     uuid = log
852     fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
853     if fixup && fixup.size>1
854       uuid = fixup[1]
855     end
856
857     @all_log_collections_for[uuid] ||= []
858   end
859
860   # helper method to preload collections for the given uuids
861   helper_method :preload_log_collections_for_objects
862   def preload_log_collections_for_objects logs
863     @all_log_collections_for ||= {}
864
865     raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
866     return @all_log_collections_for if logs.empty?
867
868     uuids = []
869     logs.each do |log|
870       fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
871       if fixup && fixup.size>1
872         uuids << fixup[1]
873       else
874         uuids << log
875       end
876     end
877
878     # if already preloaded for all of these uuids, return
879     if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
880       return @all_log_collections_for
881     end
882
883     uuids.each do |x|
884       @all_log_collections_for[x] = []
885     end
886
887     # TODO: make sure we get every page of results from API server
888     Collection.where(uuid: uuids).each do |collection|
889       @all_log_collections_for[collection.uuid] << collection
890     end
891     @all_log_collections_for
892   end
893
894   # helper method to get object of a given dataclass and uuid
895   helper_method :object_for_dataclass
896   def object_for_dataclass dataclass, uuid
897     raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
898     preload_objects_for_dataclass(dataclass, [uuid])
899     @objects_for[uuid]
900   end
901
902   # helper method to preload objects for given dataclass and uuids
903   helper_method :preload_objects_for_dataclass
904   def preload_objects_for_dataclass dataclass, uuids
905     @objects_for ||= {}
906
907     raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
908     raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
909
910     return @objects_for if uuids.empty?
911
912     # if already preloaded for all of these uuids, return
913     if not uuids.select { |x| @objects_for[x].nil? }.any?
914       return @objects_for
915     end
916
917     dataclass.where(uuid: uuids).each do |obj|
918       @objects_for[obj.uuid] = obj
919     end
920     @objects_for
921   end
922
923   def wiselinks_layout
924     'body'
925   end
926 end