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