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