Merge branch 'master' into 11453-federated-tokens
[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_filter :thread_clear
15   around_filter :set_current_request_id
16   around_filter :set_thread_api_token
17   # Methods that don't require login should
18   #   skip_around_filter :require_thread_api_token
19   around_filter :require_thread_api_token, except: ERROR_ACTIONS
20   before_filter :ensure_arvados_api_exists, only: [:index, :show]
21   before_filter :set_cache_buster
22   before_filter :accept_uuid_as_id_param, except: ERROR_ACTIONS
23   before_filter :check_user_agreements, except: ERROR_ACTIONS
24   before_filter :check_user_profile, except: ERROR_ACTIONS
25   before_filter :load_filters_and_paging_params, except: ERROR_ACTIONS
26   before_filter :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     @updates.keys.each do |attr|
357       if @object.send(attr).is_a? Hash
358         if @updates[attr].is_a? String
359           @updates[attr] = Oj.load @updates[attr]
360         end
361         if params[:merge] || params["merge_#{attr}".to_sym]
362           # Merge provided Hash with current Hash, instead of
363           # replacing.
364           @updates[attr] = @object.send(attr).with_indifferent_access.
365             deep_merge(@updates[attr].with_indifferent_access)
366         end
367       end
368     end
369     if @object.update_attributes @updates
370       show
371     else
372       self.render_error status: 422
373     end
374   end
375
376   def create
377     @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
378     @new_resource_attrs ||= {}
379     @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
380     @object ||= model_class.new @new_resource_attrs, params["options"]
381
382     if @object.save
383       show
384     else
385       render_error status: 422
386     end
387   end
388
389   # Clone the given object, merging any attribute values supplied as
390   # with a create action.
391   def copy
392     @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
393     @new_resource_attrs ||= {}
394     @object = @object.dup
395     @object.update_attributes @new_resource_attrs
396     if not @new_resource_attrs[:name] and @object.respond_to? :name
397       if @object.name and @object.name != ''
398         @object.name = "Copy of #{@object.name}"
399       else
400         @object.name = ""
401       end
402     end
403     @object.save!
404     show
405   end
406
407   def destroy
408     if @object.destroy
409       respond_to do |f|
410         f.json { render json: @object }
411         f.html {
412           redirect_to(params[:return_to] || :back)
413         }
414         f.js { render }
415       end
416     else
417       self.render_error status: 422
418     end
419   end
420
421   def current_user
422     Thread.current[:user]
423   end
424
425   def model_class
426     controller_name.classify.constantize
427   end
428
429   def breadcrumb_page_name
430     (@breadcrumb_page_name ||
431      (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
432      action_name)
433   end
434
435   def index_pane_list
436     %w(Recent)
437   end
438
439   def show_pane_list
440     %w(Attributes Advanced)
441   end
442
443   def set_share_links
444     @user_is_manager = false
445     @share_links = []
446
447     if @object.uuid != current_user.andand.uuid
448       begin
449         @share_links = Link.permissions_for(@object)
450         @user_is_manager = true
451       rescue ArvadosApiClient::AccessForbiddenException,
452         ArvadosApiClient::NotFoundException
453       end
454     end
455   end
456
457   def share_with
458     if not params[:uuids].andand.any?
459       @errors = ["No user/group UUIDs specified to share with."]
460       return render_error(status: 422)
461     end
462     results = {"success" => [], "errors" => []}
463     params[:uuids].each do |shared_uuid|
464       begin
465         Link.create(tail_uuid: shared_uuid, link_class: "permission",
466                     name: "can_read", head_uuid: @object.uuid)
467       rescue ArvadosApiClient::ApiError => error
468         error_list = error.api_response.andand[:errors]
469         if error_list.andand.any?
470           results["errors"] += error_list.map { |e| "#{shared_uuid}: #{e}" }
471         else
472           error_code = error.api_status || "Bad status"
473           results["errors"] << "#{shared_uuid}: #{error_code} response"
474         end
475       else
476         results["success"] << shared_uuid
477       end
478     end
479     if results["errors"].empty?
480       results.delete("errors")
481       status = 200
482     else
483       status = 422
484     end
485     respond_to do |f|
486       f.json { render(json: results, status: status) }
487     end
488   end
489
490   helper_method :is_starred
491   def is_starred
492     links = Link.where(tail_uuid: current_user.uuid,
493                head_uuid: @object.uuid,
494                link_class: 'star')
495
496     return links.andand.any?
497   end
498
499   protected
500
501   helper_method :strip_token_from_path
502   def strip_token_from_path(path)
503     path.sub(/([\?&;])api_token=[^&;]*[&;]?/, '\1')
504   end
505
506   def redirect_to_login
507     if request.xhr? or request.format.json?
508       @errors = ['You are not logged in. Most likely your session has timed out and you need to log in again.']
509       render_error status: 401
510     elsif request.method.in? ['GET', 'HEAD']
511       redirect_to arvados_api_client.arvados_login_url(return_to: strip_token_from_path(request.url))
512     else
513       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."
514       redirect_to :back
515     end
516     false  # For convenience to return from callbacks
517   end
518
519   def using_specific_api_token(api_token, opts={})
520     start_values = {}
521     [:arvados_api_token, :user].each do |key|
522       start_values[key] = Thread.current[key]
523     end
524     if opts.fetch(:load_user, true)
525       load_api_token(api_token)
526     else
527       Thread.current[:arvados_api_token] = api_token
528       Thread.current[:user] = nil
529     end
530     begin
531       yield
532     ensure
533       start_values.each_key { |key| Thread.current[key] = start_values[key] }
534     end
535   end
536
537
538   def accept_uuid_as_id_param
539     if params[:id] and params[:id].match /\D/
540       params[:uuid] = params.delete :id
541     end
542   end
543
544   def find_object_by_uuid
545     begin
546       if not model_class
547         @object = nil
548       elsif params[:uuid].nil? or params[:uuid].empty?
549         @object = nil
550       elsif not params[:uuid].is_a?(String)
551         @object = model_class.where(uuid: params[:uuid]).first
552       elsif (model_class != Link and
553              resource_class_for_uuid(params[:uuid]) == Link)
554         @name_link = Link.find(params[:uuid])
555         @object = model_class.find(@name_link.head_uuid)
556       else
557         @object = model_class.find(params[:uuid])
558         load_preloaded_objects [@object]
559       end
560     rescue ArvadosApiClient::NotFoundException, ArvadosApiClient::NotLoggedInException, RuntimeError => error
561       if error.is_a?(RuntimeError) and (error.message !~ /^argument to find\(/)
562         raise
563       end
564       render_not_found(error)
565       return false
566     end
567   end
568
569   def thread_clear
570     load_api_token(nil)
571     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
572     yield
573     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
574   end
575
576   def set_current_request_id
577     response.headers['X-Request-Id'] =
578       Thread.current[:request_id] =
579       "req-" + Random::DEFAULT.rand(2**128).to_s(36)[0..19]
580     yield
581     Thread.current[:request_id] = nil
582   end
583
584   def append_info_to_payload(payload)
585     super
586     payload[:request_id] = response.headers['X-Request-Id']
587   end
588
589   # Set up the thread with the given API token and associated user object.
590   def load_api_token(new_token)
591     Thread.current[:arvados_api_token] = new_token
592     if new_token.nil?
593       Thread.current[:user] = nil
594     else
595       Thread.current[:user] = User.current
596     end
597   end
598
599   # If there's a valid api_token parameter, set up the session with that
600   # user's information.  Return true if the method redirects the request
601   # (usually a post-login redirect); false otherwise.
602   def setup_user_session
603     return false unless params[:api_token]
604     Thread.current[:arvados_api_token] = params[:api_token]
605     begin
606       user = User.current
607     rescue ArvadosApiClient::NotLoggedInException
608       false  # We may redirect to login, or not, based on the current action.
609     else
610       session[:arvados_api_token] = params[:api_token]
611       # If we later have trouble contacting the API server, we still want
612       # to be able to render basic user information in the UI--see
613       # render_exception above.  We store that in the session here.  This is
614       # not intended to be used as a general-purpose cache.  See #2891.
615       session[:user] = {
616         uuid: user.uuid,
617         email: user.email,
618         first_name: user.first_name,
619         last_name: user.last_name,
620         is_active: user.is_active,
621         is_admin: user.is_admin,
622         prefs: user.prefs
623       }
624
625       if !request.format.json? and request.method.in? ['GET', 'HEAD']
626         # Repeat this request with api_token in the (new) session
627         # cookie instead of the query string.  This prevents API
628         # tokens from appearing in (and being inadvisedly copied
629         # and pasted from) browser Location bars.
630         redirect_to strip_token_from_path(request.fullpath)
631         true
632       else
633         false
634       end
635     ensure
636       Thread.current[:arvados_api_token] = nil
637     end
638   end
639
640   # Save the session API token in thread-local storage, and yield.
641   # This method also takes care of session setup if the request
642   # provides a valid api_token parameter.
643   # If a token is unavailable or expired, the block is still run, with
644   # a nil token.
645   def set_thread_api_token
646     if Thread.current[:arvados_api_token]
647       yield   # An API token has already been found - pass it through.
648       return
649     elsif setup_user_session
650       return  # A new session was set up and received a response.
651     end
652
653     begin
654       load_api_token(session[:arvados_api_token])
655       yield
656     rescue ArvadosApiClient::NotLoggedInException
657       # If we got this error with a token, it must've expired.
658       # Retry the request without a token.
659       unless Thread.current[:arvados_api_token].nil?
660         load_api_token(nil)
661         yield
662       end
663     ensure
664       # Remove token in case this Thread is used for anything else.
665       load_api_token(nil)
666     end
667   end
668
669   # Redirect to login/welcome if client provided expired API token (or
670   # none at all)
671   def require_thread_api_token
672     if Thread.current[:arvados_api_token]
673       yield
674     elsif session[:arvados_api_token]
675       # Expired session. Clear it before refreshing login so that,
676       # if this login procedure fails, we end up showing the "please
677       # log in" page instead of getting stuck in a redirect loop.
678       session.delete :arvados_api_token
679       redirect_to_login
680     elsif request.xhr?
681       # If we redirect to the welcome page, the browser will handle
682       # the 302 by itself and the client code will end up rendering
683       # the "welcome" page in some content area where it doesn't make
684       # sense. Instead, we send 401 ("authenticate and try again" or
685       # "display error", depending on how smart the client side is).
686       @errors = ['You are not logged in.']
687       render_error status: 401
688     else
689       redirect_to welcome_users_path(return_to: request.fullpath)
690     end
691   end
692
693   def ensure_current_user_is_admin
694     if not current_user
695       @errors = ['Not logged in']
696       render_error status: 401
697     elsif not current_user.is_admin
698       @errors = ['Permission denied']
699       render_error status: 403
700     end
701   end
702
703   helper_method :unsigned_user_agreements
704   def unsigned_user_agreements
705     @signed_ua_uuids ||= UserAgreement.signatures.map &:head_uuid
706     @unsigned_user_agreements ||= UserAgreement.all.map do |ua|
707       if not @signed_ua_uuids.index ua.uuid
708         Collection.find(ua.uuid)
709       end
710     end.compact
711   end
712
713   def check_user_agreements
714     if current_user && !current_user.is_active
715       if not current_user.is_invited
716         return redirect_to inactive_users_path(return_to: request.fullpath)
717       end
718       if unsigned_user_agreements.empty?
719         # No agreements to sign. Perhaps we just need to ask?
720         current_user.activate
721         if !current_user.is_active
722           logger.warn "#{current_user.uuid.inspect}: " +
723             "No user agreements to sign, but activate failed!"
724         end
725       end
726       if !current_user.is_active
727         redirect_to user_agreements_path(return_to: request.fullpath)
728       end
729     end
730     true
731   end
732
733   def check_user_profile
734     return true if !current_user
735     if request.method.downcase != 'get' || params[:partial] ||
736        params[:tab_pane] || params[:action_method] ||
737        params[:action] == 'setup_popup'
738       return true
739     end
740
741     if missing_required_profile?
742       redirect_to profile_user_path(current_user.uuid, return_to: request.fullpath)
743     end
744     true
745   end
746
747   helper_method :missing_required_profile?
748   def missing_required_profile?
749     missing_required = false
750
751     profile_config = Rails.configuration.user_profile_form_fields
752     if current_user && profile_config
753       current_user_profile = current_user.prefs[:profile]
754       profile_config.kind_of?(Array) && profile_config.andand.each do |entry|
755         if entry['required']
756           if !current_user_profile ||
757              !current_user_profile[entry['key'].to_sym] ||
758              current_user_profile[entry['key'].to_sym].empty?
759             missing_required = true
760             break
761           end
762         end
763       end
764     end
765
766     missing_required
767   end
768
769   def select_theme
770     return Rails.configuration.arvados_theme
771   end
772
773   @@notification_tests = []
774
775   @@notification_tests.push lambda { |controller, current_user|
776     return nil if Rails.configuration.shell_in_a_box_url
777     AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
778       return nil
779     end
780     return lambda { |view|
781       view.render partial: 'notifications/ssh_key_notification'
782     }
783   }
784
785   @@notification_tests.push lambda { |controller, current_user|
786     Collection.limit(1).where(created_by: current_user.uuid).each do
787       return nil
788     end
789     return lambda { |view|
790       view.render partial: 'notifications/collections_notification'
791     }
792   }
793
794   @@notification_tests.push lambda { |controller, current_user|
795     if PipelineInstance.api_exists?(:index)
796       PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
797         return nil
798       end
799     else
800       return nil
801     end
802     return lambda { |view|
803       view.render partial: 'notifications/pipelines_notification'
804     }
805   }
806
807   helper_method :user_notifications
808   def user_notifications
809     return [] if @errors or not current_user.andand.is_active or not Rails.configuration.show_user_notifications
810     @notifications ||= @@notification_tests.map do |t|
811       t.call(self, current_user)
812     end.compact
813   end
814
815   helper_method :all_projects
816   def all_projects
817     @all_projects ||= Group.
818       filter([['group_class','=','project']]).order('name')
819   end
820
821   helper_method :my_projects
822   def my_projects
823     return @my_projects if @my_projects
824     @my_projects = []
825     root_of = {}
826     all_projects.each do |g|
827       root_of[g.uuid] = g.owner_uuid
828       @my_projects << g
829     end
830     done = false
831     while not done
832       done = true
833       root_of = root_of.each_with_object({}) do |(child, parent), h|
834         if root_of[parent]
835           h[child] = root_of[parent]
836           done = false
837         else
838           h[child] = parent
839         end
840       end
841     end
842     @my_projects = @my_projects.select do |g|
843       root_of[g.uuid] == current_user.uuid
844     end
845   end
846
847   helper_method :projects_shared_with_me
848   def projects_shared_with_me
849     my_project_uuids = my_projects.collect &:uuid
850     all_projects.reject { |x| x.uuid.in? my_project_uuids }
851   end
852
853   helper_method :recent_jobs_and_pipelines
854   def recent_jobs_and_pipelines
855     (Job.limit(10) |
856      PipelineInstance.limit(10)).
857       sort_by do |x|
858       (x.finished_at || x.started_at rescue nil) || x.modified_at || x.created_at
859     end.reverse
860   end
861
862   helper_method :running_pipelines
863   def running_pipelines
864     pi = PipelineInstance.order(["started_at asc", "created_at asc"]).filter([["state", "in", ["RunningOnServer", "RunningOnClient"]]])
865     jobs = {}
866     pi.each do |pl|
867       pl.components.each do |k,v|
868         if v.is_a? Hash and v[:job]
869           jobs[v[:job][:uuid]] = {}
870         end
871       end
872     end
873
874     if jobs.keys.any?
875       Job.filter([["uuid", "in", jobs.keys]]).each do |j|
876         jobs[j[:uuid]] = j
877       end
878
879       pi.each do |pl|
880         pl.components.each do |k,v|
881           if v.is_a? Hash and v[:job]
882             v[:job] = jobs[v[:job][:uuid]]
883           end
884         end
885       end
886     end
887
888     pi
889   end
890
891   helper_method :recent_processes
892   def recent_processes lim
893     lim = 12 if lim.nil?
894
895     procs = {}
896     if PipelineInstance.api_exists?(:index)
897       cols = %w(uuid owner_uuid created_at modified_at pipeline_template_uuid name state started_at finished_at)
898       pipelines = PipelineInstance.select(cols).limit(lim).order(["created_at desc"])
899       pipelines.results.each { |pi| procs[pi] = pi.created_at }
900     end
901
902     crs = ContainerRequest.limit(lim).order(["created_at desc"]).filter([["requesting_container_uuid", "=", nil]])
903     crs.results.each { |c| procs[c] = c.created_at }
904
905     Hash[procs.sort_by {|key, value| value}].keys.reverse.first(lim)
906   end
907
908   helper_method :recent_collections
909   def recent_collections lim
910     c = Collection.limit(lim).order(["modified_at desc"]).results
911     own = {}
912     Group.filter([["uuid", "in", c.map(&:owner_uuid)]]).each do |g|
913       own[g[:uuid]] = g
914     end
915     {collections: c, owners: own}
916   end
917
918   helper_method :my_starred_projects
919   def my_starred_projects user
920     return if @starred_projects
921     links = Link.filter([['tail_uuid', '=', user.uuid],
922                          ['link_class', '=', 'star'],
923                          ['head_uuid', 'is_a', 'arvados#group']]).select(%w(head_uuid))
924     uuids = links.collect { |x| x.head_uuid }
925     starred_projects = Group.filter([['uuid', 'in', uuids]]).order('name')
926     @starred_projects = starred_projects.results
927   end
928
929   # If there are more than 200 projects that are readable by the user,
930   # build the tree using only the top 200+ projects owned by the user,
931   # from the top three levels.
932   # That is: get toplevel projects under home, get subprojects of
933   # these projects, and so on until we hit the limit.
934   def my_wanted_projects(user, page_size=100)
935     return @my_wanted_projects if @my_wanted_projects
936
937     from_top = []
938     uuids = [user.uuid]
939     depth = 0
940     @too_many_projects = false
941     @reached_level_limit = false
942     while from_top.size <= page_size*2
943       current_level = Group.filter([['group_class','=','project'],
944                                     ['owner_uuid', 'in', uuids]])
945                       .order('name').limit(page_size*2)
946       break if current_level.results.size == 0
947       @too_many_projects = true if current_level.items_available > current_level.results.size
948       from_top.concat current_level.results
949       uuids = current_level.results.collect(&:uuid)
950       depth += 1
951       if depth >= 3
952         @reached_level_limit = true
953         break
954       end
955     end
956     @my_wanted_projects = from_top
957   end
958
959   helper_method :my_wanted_projects_tree
960   def my_wanted_projects_tree(user, page_size=100)
961     build_my_wanted_projects_tree(user, page_size)
962     [@my_wanted_projects_tree, @too_many_projects, @reached_level_limit]
963   end
964
965   def build_my_wanted_projects_tree(user, page_size=100)
966     return @my_wanted_projects_tree if @my_wanted_projects_tree
967
968     parent_of = {user.uuid => 'me'}
969     my_wanted_projects(user, page_size).each do |ob|
970       parent_of[ob.uuid] = ob.owner_uuid
971     end
972     children_of = {false => [], 'me' => [user]}
973     my_wanted_projects(user, page_size).each do |ob|
974       if ob.owner_uuid != user.uuid and
975           not parent_of.has_key? ob.owner_uuid
976         parent_of[ob.uuid] = false
977       end
978       children_of[parent_of[ob.uuid]] ||= []
979       children_of[parent_of[ob.uuid]] << ob
980     end
981     buildtree = lambda do |children_of, root_uuid=false|
982       tree = {}
983       children_of[root_uuid].andand.each do |ob|
984         tree[ob] = buildtree.call(children_of, ob.uuid)
985       end
986       tree
987     end
988     sorted_paths = lambda do |tree, depth=0|
989       paths = []
990       tree.keys.sort_by { |ob|
991         ob.is_a?(String) ? ob : ob.friendly_link_name
992       }.each do |ob|
993         paths << {object: ob, depth: depth}
994         paths += sorted_paths.call tree[ob], depth+1
995       end
996       paths
997     end
998     @my_wanted_projects_tree =
999       sorted_paths.call buildtree.call(children_of, 'me')
1000   end
1001
1002   helper_method :get_object
1003   def get_object uuid
1004     if @get_object.nil? and @objects
1005       @get_object = @objects.each_with_object({}) do |object, h|
1006         h[object.uuid] = object
1007       end
1008     end
1009     @get_object ||= {}
1010     @get_object[uuid]
1011   end
1012
1013   helper_method :project_breadcrumbs
1014   def project_breadcrumbs
1015     crumbs = []
1016     current = @name_link || @object
1017     while current
1018       # Halt if a group ownership loop is detected. API should refuse
1019       # to produce this state, but it could still arise from a race
1020       # condition when group ownership changes between our find()
1021       # queries.
1022       break if crumbs.collect(&:uuid).include? current.uuid
1023
1024       if current.is_a?(Group) and current.group_class == 'project'
1025         crumbs.prepend current
1026       end
1027       if current.is_a? Link
1028         current = Group.find?(current.tail_uuid)
1029       else
1030         current = Group.find?(current.owner_uuid)
1031       end
1032     end
1033     crumbs
1034   end
1035
1036   helper_method :current_project_uuid
1037   def current_project_uuid
1038     if @object.is_a? Group and @object.group_class == 'project'
1039       @object.uuid
1040     elsif @name_link.andand.tail_uuid
1041       @name_link.tail_uuid
1042     elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
1043       @object.owner_uuid
1044     else
1045       nil
1046     end
1047   end
1048
1049   # helper method to get links for given object or uuid
1050   helper_method :links_for_object
1051   def links_for_object object_or_uuid
1052     raise ArgumentError, 'No input argument' unless object_or_uuid
1053     preload_links_for_objects([object_or_uuid])
1054     uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
1055     @all_links_for[uuid] ||= []
1056   end
1057
1058   # helper method to preload links for given objects and uuids
1059   helper_method :preload_links_for_objects
1060   def preload_links_for_objects objects_and_uuids
1061     @all_links_for ||= {}
1062
1063     raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
1064     return @all_links_for if objects_and_uuids.empty?
1065
1066     uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
1067
1068     # if already preloaded for all of these uuids, return
1069     if not uuids.select { |x| @all_links_for[x].nil? }.any?
1070       return @all_links_for
1071     end
1072
1073     uuids.each do |x|
1074       @all_links_for[x] = []
1075     end
1076
1077     # TODO: make sure we get every page of results from API server
1078     Link.filter([['head_uuid', 'in', uuids]]).each do |link|
1079       @all_links_for[link.head_uuid] << link
1080     end
1081     @all_links_for
1082   end
1083
1084   # helper method to get a certain number of objects of a specific type
1085   # this can be used to replace any uses of: "dataclass.limit(n)"
1086   helper_method :get_n_objects_of_class
1087   def get_n_objects_of_class dataclass, size
1088     @objects_map_for ||= {}
1089
1090     raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
1091     raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
1092
1093     # if the objects_map_for has a value for this dataclass, and the
1094     # size used to retrieve those objects is equal, return it
1095     size_key = "#{dataclass.name}_size"
1096     if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
1097         (@objects_map_for[size_key] == size)
1098       return @objects_map_for[dataclass.name]
1099     end
1100
1101     @objects_map_for[size_key] = size
1102     @objects_map_for[dataclass.name] = dataclass.limit(size)
1103   end
1104
1105   # helper method to get collections for the given uuid
1106   helper_method :collections_for_object
1107   def collections_for_object uuid
1108     raise ArgumentError, 'No input argument' unless uuid
1109     preload_collections_for_objects([uuid])
1110     @all_collections_for[uuid] ||= []
1111   end
1112
1113   # helper method to preload collections for the given uuids
1114   helper_method :preload_collections_for_objects
1115   def preload_collections_for_objects uuids
1116     @all_collections_for ||= {}
1117
1118     raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
1119     return @all_collections_for if uuids.empty?
1120
1121     # if already preloaded for all of these uuids, return
1122     if not uuids.select { |x| @all_collections_for[x].nil? }.any?
1123       return @all_collections_for
1124     end
1125
1126     uuids.each do |x|
1127       @all_collections_for[x] = []
1128     end
1129
1130     # TODO: make sure we get every page of results from API server
1131     Collection.where(uuid: uuids).each do |collection|
1132       @all_collections_for[collection.uuid] << collection
1133     end
1134     @all_collections_for
1135   end
1136
1137   # helper method to get log collections for the given log
1138   helper_method :log_collections_for_object
1139   def log_collections_for_object log
1140     raise ArgumentError, 'No input argument' unless log
1141
1142     preload_log_collections_for_objects([log])
1143
1144     uuid = log
1145     fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
1146     if fixup && fixup.size>1
1147       uuid = fixup[1]
1148     end
1149
1150     @all_log_collections_for[uuid] ||= []
1151   end
1152
1153   # helper method to preload collections for the given uuids
1154   helper_method :preload_log_collections_for_objects
1155   def preload_log_collections_for_objects logs
1156     @all_log_collections_for ||= {}
1157
1158     raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
1159     return @all_log_collections_for if logs.empty?
1160
1161     uuids = []
1162     logs.each do |log|
1163       fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
1164       if fixup && fixup.size>1
1165         uuids << fixup[1]
1166       else
1167         uuids << log
1168       end
1169     end
1170
1171     # if already preloaded for all of these uuids, return
1172     if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
1173       return @all_log_collections_for
1174     end
1175
1176     uuids.each do |x|
1177       @all_log_collections_for[x] = []
1178     end
1179
1180     # TODO: make sure we get every page of results from API server
1181     Collection.where(uuid: uuids).each do |collection|
1182       @all_log_collections_for[collection.uuid] << collection
1183     end
1184     @all_log_collections_for
1185   end
1186
1187   # Helper method to get one collection for the given portable_data_hash
1188   # This is used to determine if a pdh is readable by the current_user
1189   helper_method :collection_for_pdh
1190   def collection_for_pdh pdh
1191     raise ArgumentError, 'No input argument' unless pdh
1192     preload_for_pdhs([pdh])
1193     @all_pdhs_for[pdh] ||= []
1194   end
1195
1196   # Helper method to preload one collection each for the given pdhs
1197   # This is used to determine if a pdh is readable by the current_user
1198   helper_method :preload_for_pdhs
1199   def preload_for_pdhs pdhs
1200     @all_pdhs_for ||= {}
1201
1202     raise ArgumentError, 'Argument is not an array' unless pdhs.is_a? Array
1203     return @all_pdhs_for if pdhs.empty?
1204
1205     # if already preloaded for all of these pdhs, return
1206     if not pdhs.select { |x| @all_pdhs_for[x].nil? }.any?
1207       return @all_pdhs_for
1208     end
1209
1210     pdhs.each do |x|
1211       @all_pdhs_for[x] = []
1212     end
1213
1214     Collection.select(%w(portable_data_hash)).where(portable_data_hash: pdhs).distinct().each do |collection|
1215       @all_pdhs_for[collection.portable_data_hash] << collection
1216     end
1217     @all_pdhs_for
1218   end
1219
1220   # helper method to get object of a given dataclass and uuid
1221   helper_method :object_for_dataclass
1222   def object_for_dataclass dataclass, uuid, by_attr=nil
1223     raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
1224     preload_objects_for_dataclass(dataclass, [uuid], by_attr)
1225     @objects_for[uuid]
1226   end
1227
1228   # helper method to preload objects for given dataclass and uuids
1229   helper_method :preload_objects_for_dataclass
1230   def preload_objects_for_dataclass dataclass, uuids, by_attr=nil
1231     @objects_for ||= {}
1232
1233     raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
1234     raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
1235
1236     return @objects_for if uuids.empty?
1237
1238     # if already preloaded for all of these uuids, return
1239     if not uuids.select { |x| !@objects_for.include?(x) }.any?
1240       return @objects_for
1241     end
1242
1243     # preset all uuids to nil
1244     uuids.each do |x|
1245       @objects_for[x] = nil
1246     end
1247     if by_attr and ![:uuid, :name].include?(by_attr)
1248       raise ArgumentError, "Preloading only using lookups by uuid or name are supported: #{by_attr}"
1249     elsif by_attr and by_attr == :name
1250       dataclass.where(name: uuids).each do |obj|
1251         @objects_for[obj.name] = obj
1252       end
1253     else
1254       key_prefix = "request_#{Thread.current.object_id}_#{dataclass.to_s}_"
1255       dataclass.where(uuid: uuids).each do |obj|
1256         @objects_for[obj.uuid] = obj
1257         if dataclass == Collection
1258           # The collecions#index defaults to "all attributes except manifest_text"
1259           # Hence, this object is not suitable for preloading the find() cache.
1260         else
1261           Rails.cache.write(key_prefix + obj.uuid, obj.as_json)
1262         end
1263       end
1264     end
1265     @objects_for
1266   end
1267
1268   # helper method to load objects that are already preloaded
1269   helper_method :load_preloaded_objects
1270   def load_preloaded_objects objs
1271     @objects_for ||= {}
1272     objs.each do |obj|
1273       @objects_for[obj.uuid] = obj
1274     end
1275   end
1276
1277   # helper method to get the names of collection files selected
1278   helper_method :selected_collection_files
1279   def selected_collection_files params
1280     link_uuids, coll_ids = params["selection"].partition do |sel_s|
1281       ArvadosBase::resource_class_for_uuid(sel_s) == Link
1282     end
1283
1284     unless link_uuids.empty?
1285       Link.select([:head_uuid]).where(uuid: link_uuids).each do |link|
1286         if ArvadosBase::resource_class_for_uuid(link.head_uuid) == Collection
1287           coll_ids << link.head_uuid
1288         end
1289       end
1290     end
1291
1292     uuids = []
1293     pdhs = []
1294     source_paths = Hash.new { |hash, key| hash[key] = [] }
1295     coll_ids.each do |coll_id|
1296       if m = CollectionsHelper.match(coll_id)
1297         key = m[1] + m[2]
1298         pdhs << key
1299         source_paths[key] << m[4]
1300       elsif m = CollectionsHelper.match_uuid_with_optional_filepath(coll_id)
1301         key = m[1]
1302         uuids << key
1303         source_paths[key] << m[4]
1304       end
1305     end
1306
1307     unless pdhs.empty?
1308       Collection.where(portable_data_hash: pdhs.uniq).
1309           select([:uuid, :portable_data_hash]).each do |coll|
1310         unless source_paths[coll.portable_data_hash].empty?
1311           uuids << coll.uuid
1312           source_paths[coll.uuid] = source_paths.delete(coll.portable_data_hash)
1313         end
1314       end
1315     end
1316
1317     [uuids, source_paths]
1318   end
1319
1320   def wiselinks_layout
1321     'body'
1322   end
1323 end