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