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