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