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