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