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