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