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