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