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