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