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