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