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