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