Merge branch 'master' into 8286-fav-projects
[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         build_project_trees
93       rescue ArvadosApiClient::ApiError
94         # Fall back to the default-setting code later.
95       end
96     end
97     @starred_projects ||= []
98     @my_project_tree ||= []
99     @shared_project_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 Jobs and Pipelines 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   def star
449     links = Link.where(tail_uuid: current_user.uuid,
450                        head_uuid: @object.uuid,
451                        link_class: 'star')
452
453     if params['status'] == 'create'
454       # create 'star' link if one does not already exist
455       if !links.andand.any?
456         dst = Link.new(owner_uuid: @object.uuid,
457                        tail_uuid: current_user.uuid,
458                        head_uuid: @object.uuid,
459                        link_class: 'star',
460                        name: @object.uuid)
461         dst.save!
462       end
463     else # delete any existing 'star' links
464       if links.andand.any?
465         links.each do |link|
466           link.destroy
467         end
468       end
469     end
470
471     show
472   end
473
474   helper_method :is_starred
475   def is_starred
476     links = Link.where(tail_uuid: current_user.uuid,
477                head_uuid: @object.uuid,
478                link_class: 'star')
479
480     return links.andand.any?
481   end
482
483   protected
484
485   helper_method :strip_token_from_path
486   def strip_token_from_path(path)
487     path.sub(/([\?&;])api_token=[^&;]*[&;]?/, '\1')
488   end
489
490   def redirect_to_login
491     if request.xhr? or request.format.json?
492       @errors = ['You are not logged in. Most likely your session has timed out and you need to log in again.']
493       render_error status: 401
494     elsif request.method.in? ['GET', 'HEAD']
495       redirect_to arvados_api_client.arvados_login_url(return_to: strip_token_from_path(request.url))
496     else
497       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."
498       redirect_to :back
499     end
500     false  # For convenience to return from callbacks
501   end
502
503   def using_specific_api_token(api_token, opts={})
504     start_values = {}
505     [:arvados_api_token, :user].each do |key|
506       start_values[key] = Thread.current[key]
507     end
508     if opts.fetch(:load_user, true)
509       load_api_token(api_token)
510     else
511       Thread.current[:arvados_api_token] = api_token
512       Thread.current[:user] = nil
513     end
514     begin
515       yield
516     ensure
517       start_values.each_key { |key| Thread.current[key] = start_values[key] }
518     end
519   end
520
521
522   def accept_uuid_as_id_param
523     if params[:id] and params[:id].match /\D/
524       params[:uuid] = params.delete :id
525     end
526   end
527
528   def find_object_by_uuid
529     begin
530       if not model_class
531         @object = nil
532       elsif not params[:uuid].is_a?(String)
533         @object = model_class.where(uuid: params[:uuid]).first
534       elsif params[:uuid].empty?
535         @object = nil
536       elsif (model_class != Link and
537              resource_class_for_uuid(params[:uuid]) == Link)
538         @name_link = Link.find(params[:uuid])
539         @object = model_class.find(@name_link.head_uuid)
540       else
541         @object = model_class.find(params[:uuid])
542       end
543     rescue ArvadosApiClient::NotFoundException, ArvadosApiClient::NotLoggedInException, RuntimeError => error
544       if error.is_a?(RuntimeError) and (error.message !~ /^argument to find\(/)
545         raise
546       end
547       render_not_found(error)
548       return false
549     end
550   end
551
552   def thread_clear
553     load_api_token(nil)
554     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
555     yield
556     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
557   end
558
559   # Set up the thread with the given API token and associated user object.
560   def load_api_token(new_token)
561     Thread.current[:arvados_api_token] = new_token
562     if new_token.nil?
563       Thread.current[:user] = nil
564     else
565       Thread.current[:user] = User.current
566     end
567   end
568
569   # If there's a valid api_token parameter, set up the session with that
570   # user's information.  Return true if the method redirects the request
571   # (usually a post-login redirect); false otherwise.
572   def setup_user_session
573     return false unless params[:api_token]
574     Thread.current[:arvados_api_token] = params[:api_token]
575     begin
576       user = User.current
577     rescue ArvadosApiClient::NotLoggedInException
578       false  # We may redirect to login, or not, based on the current action.
579     else
580       session[:arvados_api_token] = params[:api_token]
581       # If we later have trouble contacting the API server, we still want
582       # to be able to render basic user information in the UI--see
583       # render_exception above.  We store that in the session here.  This is
584       # not intended to be used as a general-purpose cache.  See #2891.
585       session[:user] = {
586         uuid: user.uuid,
587         email: user.email,
588         first_name: user.first_name,
589         last_name: user.last_name,
590         is_active: user.is_active,
591         is_admin: user.is_admin,
592         prefs: user.prefs
593       }
594
595       if !request.format.json? and request.method.in? ['GET', 'HEAD']
596         # Repeat this request with api_token in the (new) session
597         # cookie instead of the query string.  This prevents API
598         # tokens from appearing in (and being inadvisedly copied
599         # and pasted from) browser Location bars.
600         redirect_to strip_token_from_path(request.fullpath)
601         true
602       else
603         false
604       end
605     ensure
606       Thread.current[:arvados_api_token] = nil
607     end
608   end
609
610   # Save the session API token in thread-local storage, and yield.
611   # This method also takes care of session setup if the request
612   # provides a valid api_token parameter.
613   # If a token is unavailable or expired, the block is still run, with
614   # a nil token.
615   def set_thread_api_token
616     if Thread.current[:arvados_api_token]
617       yield   # An API token has already been found - pass it through.
618       return
619     elsif setup_user_session
620       return  # A new session was set up and received a response.
621     end
622
623     begin
624       load_api_token(session[:arvados_api_token])
625       yield
626     rescue ArvadosApiClient::NotLoggedInException
627       # If we got this error with a token, it must've expired.
628       # Retry the request without a token.
629       unless Thread.current[:arvados_api_token].nil?
630         load_api_token(nil)
631         yield
632       end
633     ensure
634       # Remove token in case this Thread is used for anything else.
635       load_api_token(nil)
636     end
637   end
638
639   # Redirect to login/welcome if client provided expired API token (or
640   # none at all)
641   def require_thread_api_token
642     if Thread.current[:arvados_api_token]
643       yield
644     elsif session[:arvados_api_token]
645       # Expired session. Clear it before refreshing login so that,
646       # if this login procedure fails, we end up showing the "please
647       # log in" page instead of getting stuck in a redirect loop.
648       session.delete :arvados_api_token
649       redirect_to_login
650     elsif request.xhr?
651       # If we redirect to the welcome page, the browser will handle
652       # the 302 by itself and the client code will end up rendering
653       # the "welcome" page in some content area where it doesn't make
654       # sense. Instead, we send 401 ("authenticate and try again" or
655       # "display error", depending on how smart the client side is).
656       @errors = ['You are not logged in.']
657       render_error status: 401
658     else
659       redirect_to welcome_users_path(return_to: request.fullpath)
660     end
661   end
662
663   def ensure_current_user_is_admin
664     if not current_user
665       @errors = ['Not logged in']
666       render_error status: 401
667     elsif not current_user.is_admin
668       @errors = ['Permission denied']
669       render_error status: 403
670     end
671   end
672
673   helper_method :unsigned_user_agreements
674   def unsigned_user_agreements
675     @signed_ua_uuids ||= UserAgreement.signatures.map &:head_uuid
676     @unsigned_user_agreements ||= UserAgreement.all.map do |ua|
677       if not @signed_ua_uuids.index ua.uuid
678         Collection.find(ua.uuid)
679       end
680     end.compact
681   end
682
683   def check_user_agreements
684     if current_user && !current_user.is_active
685       if not current_user.is_invited
686         return redirect_to inactive_users_path(return_to: request.fullpath)
687       end
688       if unsigned_user_agreements.empty?
689         # No agreements to sign. Perhaps we just need to ask?
690         current_user.activate
691         if !current_user.is_active
692           logger.warn "#{current_user.uuid.inspect}: " +
693             "No user agreements to sign, but activate failed!"
694         end
695       end
696       if !current_user.is_active
697         redirect_to user_agreements_path(return_to: request.fullpath)
698       end
699     end
700     true
701   end
702
703   def check_user_profile
704     return true if !current_user
705     if request.method.downcase != 'get' || params[:partial] ||
706        params[:tab_pane] || params[:action_method] ||
707        params[:action] == 'setup_popup'
708       return true
709     end
710
711     if missing_required_profile?
712       redirect_to profile_user_path(current_user.uuid, return_to: request.fullpath)
713     end
714     true
715   end
716
717   helper_method :missing_required_profile?
718   def missing_required_profile?
719     missing_required = false
720
721     profile_config = Rails.configuration.user_profile_form_fields
722     if current_user && profile_config
723       current_user_profile = current_user.prefs[:profile]
724       profile_config.kind_of?(Array) && profile_config.andand.each do |entry|
725         if entry['required']
726           if !current_user_profile ||
727              !current_user_profile[entry['key'].to_sym] ||
728              current_user_profile[entry['key'].to_sym].empty?
729             missing_required = true
730             break
731           end
732         end
733       end
734     end
735
736     missing_required
737   end
738
739   def select_theme
740     return Rails.configuration.arvados_theme
741   end
742
743   @@notification_tests = []
744
745   @@notification_tests.push lambda { |controller, current_user|
746     return nil if Rails.configuration.shell_in_a_box_url
747     AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
748       return nil
749     end
750     return lambda { |view|
751       view.render partial: 'notifications/ssh_key_notification'
752     }
753   }
754
755   @@notification_tests.push lambda { |controller, current_user|
756     Collection.limit(1).where(created_by: current_user.uuid).each do
757       return nil
758     end
759     return lambda { |view|
760       view.render partial: 'notifications/collections_notification'
761     }
762   }
763
764   @@notification_tests.push lambda { |controller, current_user|
765     PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
766       return nil
767     end
768     return lambda { |view|
769       view.render partial: 'notifications/pipelines_notification'
770     }
771   }
772
773   helper_method :user_notifications
774   def user_notifications
775     return [] if @errors or not current_user.andand.is_active
776     @notifications ||= @@notification_tests.map do |t|
777       t.call(self, current_user)
778     end.compact
779   end
780
781   helper_method :all_projects
782   def all_projects
783     @all_projects ||= Group.
784       filter([['group_class','=','project']]).order('name')
785   end
786
787   helper_method :my_projects
788   def my_projects
789     return @my_projects if @my_projects
790     @my_projects = []
791     root_of = {}
792     all_projects.each do |g|
793       root_of[g.uuid] = g.owner_uuid
794       @my_projects << g
795     end
796     done = false
797     while not done
798       done = true
799       root_of = root_of.each_with_object({}) do |(child, parent), h|
800         if root_of[parent]
801           h[child] = root_of[parent]
802           done = false
803         else
804           h[child] = parent
805         end
806       end
807     end
808     @my_projects = @my_projects.select do |g|
809       root_of[g.uuid] == current_user.uuid
810     end
811   end
812
813   helper_method :projects_shared_with_me
814   def projects_shared_with_me
815     my_project_uuids = my_projects.collect &:uuid
816     all_projects.reject { |x| x.uuid.in? my_project_uuids }
817   end
818
819   helper_method :recent_jobs_and_pipelines
820   def recent_jobs_and_pipelines
821     (Job.limit(10) |
822      PipelineInstance.limit(10)).
823       sort_by do |x|
824       (x.finished_at || x.started_at rescue nil) || x.modified_at || x.created_at
825     end.reverse
826   end
827
828   helper_method :running_pipelines
829   def running_pipelines
830     pi = PipelineInstance.order(["started_at asc", "created_at asc"]).filter([["state", "in", ["RunningOnServer", "RunningOnClient"]]])
831     jobs = {}
832     pi.each do |pl|
833       pl.components.each do |k,v|
834         if v.is_a? Hash and v[:job]
835           jobs[v[:job][:uuid]] = {}
836         end
837       end
838     end
839
840     if jobs.keys.any?
841       Job.filter([["uuid", "in", jobs.keys]]).each do |j|
842         jobs[j[:uuid]] = j
843       end
844
845       pi.each do |pl|
846         pl.components.each do |k,v|
847           if v.is_a? Hash and v[:job]
848             v[:job] = jobs[v[:job][:uuid]]
849           end
850         end
851       end
852     end
853
854     pi
855   end
856
857   helper_method :finished_pipelines
858   def finished_pipelines lim
859     PipelineInstance.limit(lim).order(["finished_at desc"]).filter([["state", "in", ["Complete", "Failed", "Paused"]], ["finished_at", "!=", nil]])
860   end
861
862   helper_method :recent_collections
863   def recent_collections lim
864     c = Collection.limit(lim).order(["modified_at desc"]).filter([["owner_uuid", "is_a", "arvados#group"]])
865     own = {}
866     Group.filter([["uuid", "in", c.map(&:owner_uuid)]]).each do |g|
867       own[g[:uuid]] = g
868     end
869     {collections: c, owners: own}
870   end
871
872   helper_method :my_starred_projects
873   def my_starred_projects
874     return if @starred_projects
875     links = Link.filter([['tail_uuid', '=', current_user.uuid],
876                          ['link_class', '=', 'star'],
877                          ['head_uuid', 'is_a', 'arvados#group']]).select(%w(head_uuid))
878     uuids =links.collect { |x| x.head_uuid }
879     starred_projects = Group.filter([['uuid', 'in', uuids]]).order('name')
880     @starred_projects = starred_projects.results
881   end
882
883   helper_method :my_project_tree
884   def my_project_tree
885     build_project_trees
886     @my_project_tree
887   end
888
889   helper_method :shared_project_tree
890   def shared_project_tree
891     build_project_trees
892     @shared_project_tree
893   end
894
895   def build_project_trees
896     return if @my_project_tree and @shared_project_tree
897     parent_of = {current_user.uuid => 'me'}
898     all_projects.each do |ob|
899       parent_of[ob.uuid] = ob.owner_uuid
900     end
901     children_of = {false => [], 'me' => [current_user]}
902     all_projects.each do |ob|
903       if ob.owner_uuid != current_user.uuid and
904           not parent_of.has_key? ob.owner_uuid
905         parent_of[ob.uuid] = false
906       end
907       children_of[parent_of[ob.uuid]] ||= []
908       children_of[parent_of[ob.uuid]] << ob
909     end
910     buildtree = lambda do |children_of, root_uuid=false|
911       tree = {}
912       children_of[root_uuid].andand.each do |ob|
913         tree[ob] = buildtree.call(children_of, ob.uuid)
914       end
915       tree
916     end
917     sorted_paths = lambda do |tree, depth=0|
918       paths = []
919       tree.keys.sort_by { |ob|
920         ob.is_a?(String) ? ob : ob.friendly_link_name
921       }.each do |ob|
922         paths << {object: ob, depth: depth}
923         paths += sorted_paths.call tree[ob], depth+1
924       end
925       paths
926     end
927     @my_project_tree =
928       sorted_paths.call buildtree.call(children_of, 'me')
929     @shared_project_tree =
930       sorted_paths.call({'Projects shared with me' =>
931                           buildtree.call(children_of, false)})
932   end
933
934   helper_method :get_object
935   def get_object uuid
936     if @get_object.nil? and @objects
937       @get_object = @objects.each_with_object({}) do |object, h|
938         h[object.uuid] = object
939       end
940     end
941     @get_object ||= {}
942     @get_object[uuid]
943   end
944
945   helper_method :project_breadcrumbs
946   def project_breadcrumbs
947     crumbs = []
948     current = @name_link || @object
949     while current
950       # Halt if a group ownership loop is detected. API should refuse
951       # to produce this state, but it could still arise from a race
952       # condition when group ownership changes between our find()
953       # queries.
954       break if crumbs.collect(&:uuid).include? current.uuid
955
956       if current.is_a?(Group) and current.group_class == 'project'
957         crumbs.prepend current
958       end
959       if current.is_a? Link
960         current = Group.find?(current.tail_uuid)
961       else
962         current = Group.find?(current.owner_uuid)
963       end
964     end
965     crumbs
966   end
967
968   helper_method :current_project_uuid
969   def current_project_uuid
970     if @object.is_a? Group and @object.group_class == 'project'
971       @object.uuid
972     elsif @name_link.andand.tail_uuid
973       @name_link.tail_uuid
974     elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
975       @object.owner_uuid
976     else
977       nil
978     end
979   end
980
981   # helper method to get links for given object or uuid
982   helper_method :links_for_object
983   def links_for_object object_or_uuid
984     raise ArgumentError, 'No input argument' unless object_or_uuid
985     preload_links_for_objects([object_or_uuid])
986     uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
987     @all_links_for[uuid] ||= []
988   end
989
990   # helper method to preload links for given objects and uuids
991   helper_method :preload_links_for_objects
992   def preload_links_for_objects objects_and_uuids
993     @all_links_for ||= {}
994
995     raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
996     return @all_links_for if objects_and_uuids.empty?
997
998     uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
999
1000     # if already preloaded for all of these uuids, return
1001     if not uuids.select { |x| @all_links_for[x].nil? }.any?
1002       return @all_links_for
1003     end
1004
1005     uuids.each do |x|
1006       @all_links_for[x] = []
1007     end
1008
1009     # TODO: make sure we get every page of results from API server
1010     Link.filter([['head_uuid', 'in', uuids]]).each do |link|
1011       @all_links_for[link.head_uuid] << link
1012     end
1013     @all_links_for
1014   end
1015
1016   # helper method to get a certain number of objects of a specific type
1017   # this can be used to replace any uses of: "dataclass.limit(n)"
1018   helper_method :get_n_objects_of_class
1019   def get_n_objects_of_class dataclass, size
1020     @objects_map_for ||= {}
1021
1022     raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
1023     raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
1024
1025     # if the objects_map_for has a value for this dataclass, and the
1026     # size used to retrieve those objects is equal, return it
1027     size_key = "#{dataclass.name}_size"
1028     if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
1029         (@objects_map_for[size_key] == size)
1030       return @objects_map_for[dataclass.name]
1031     end
1032
1033     @objects_map_for[size_key] = size
1034     @objects_map_for[dataclass.name] = dataclass.limit(size)
1035   end
1036
1037   # helper method to get collections for the given uuid
1038   helper_method :collections_for_object
1039   def collections_for_object uuid
1040     raise ArgumentError, 'No input argument' unless uuid
1041     preload_collections_for_objects([uuid])
1042     @all_collections_for[uuid] ||= []
1043   end
1044
1045   # helper method to preload collections for the given uuids
1046   helper_method :preload_collections_for_objects
1047   def preload_collections_for_objects uuids
1048     @all_collections_for ||= {}
1049
1050     raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
1051     return @all_collections_for if uuids.empty?
1052
1053     # if already preloaded for all of these uuids, return
1054     if not uuids.select { |x| @all_collections_for[x].nil? }.any?
1055       return @all_collections_for
1056     end
1057
1058     uuids.each do |x|
1059       @all_collections_for[x] = []
1060     end
1061
1062     # TODO: make sure we get every page of results from API server
1063     Collection.where(uuid: uuids).each do |collection|
1064       @all_collections_for[collection.uuid] << collection
1065     end
1066     @all_collections_for
1067   end
1068
1069   # helper method to get log collections for the given log
1070   helper_method :log_collections_for_object
1071   def log_collections_for_object log
1072     raise ArgumentError, 'No input argument' unless log
1073
1074     preload_log_collections_for_objects([log])
1075
1076     uuid = log
1077     fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
1078     if fixup && fixup.size>1
1079       uuid = fixup[1]
1080     end
1081
1082     @all_log_collections_for[uuid] ||= []
1083   end
1084
1085   # helper method to preload collections for the given uuids
1086   helper_method :preload_log_collections_for_objects
1087   def preload_log_collections_for_objects logs
1088     @all_log_collections_for ||= {}
1089
1090     raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
1091     return @all_log_collections_for if logs.empty?
1092
1093     uuids = []
1094     logs.each do |log|
1095       fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
1096       if fixup && fixup.size>1
1097         uuids << fixup[1]
1098       else
1099         uuids << log
1100       end
1101     end
1102
1103     # if already preloaded for all of these uuids, return
1104     if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
1105       return @all_log_collections_for
1106     end
1107
1108     uuids.each do |x|
1109       @all_log_collections_for[x] = []
1110     end
1111
1112     # TODO: make sure we get every page of results from API server
1113     Collection.where(uuid: uuids).each do |collection|
1114       @all_log_collections_for[collection.uuid] << collection
1115     end
1116     @all_log_collections_for
1117   end
1118
1119   # Helper method to get one collection for the given portable_data_hash
1120   # This is used to determine if a pdh is readable by the current_user
1121   helper_method :collection_for_pdh
1122   def collection_for_pdh pdh
1123     raise ArgumentError, 'No input argument' unless pdh
1124     preload_for_pdhs([pdh])
1125     @all_pdhs_for[pdh] ||= []
1126   end
1127
1128   # Helper method to preload one collection each for the given pdhs
1129   # This is used to determine if a pdh is readable by the current_user
1130   helper_method :preload_for_pdhs
1131   def preload_for_pdhs pdhs
1132     @all_pdhs_for ||= {}
1133
1134     raise ArgumentError, 'Argument is not an array' unless pdhs.is_a? Array
1135     return @all_pdhs_for if pdhs.empty?
1136
1137     # if already preloaded for all of these pdhs, return
1138     if not pdhs.select { |x| @all_pdhs_for[x].nil? }.any?
1139       return @all_pdhs_for
1140     end
1141
1142     pdhs.each do |x|
1143       @all_pdhs_for[x] = []
1144     end
1145
1146     Collection.select(%w(portable_data_hash)).where(portable_data_hash: pdhs).distinct().each do |collection|
1147       @all_pdhs_for[collection.portable_data_hash] << collection
1148     end
1149     @all_pdhs_for
1150   end
1151
1152   # helper method to get object of a given dataclass and uuid
1153   helper_method :object_for_dataclass
1154   def object_for_dataclass dataclass, uuid
1155     raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
1156     preload_objects_for_dataclass(dataclass, [uuid])
1157     @objects_for[uuid]
1158   end
1159
1160   # helper method to preload objects for given dataclass and uuids
1161   helper_method :preload_objects_for_dataclass
1162   def preload_objects_for_dataclass dataclass, uuids
1163     @objects_for ||= {}
1164
1165     raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
1166     raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
1167
1168     return @objects_for if uuids.empty?
1169
1170     # if already preloaded for all of these uuids, return
1171     if not uuids.select { |x| !@objects_for.include?(x) }.any?
1172       return @objects_for
1173     end
1174
1175     # preset all uuids to nil
1176     uuids.each do |x|
1177       @objects_for[x] = nil
1178     end
1179     dataclass.where(uuid: uuids).each do |obj|
1180       @objects_for[obj.uuid] = obj
1181     end
1182     @objects_for
1183   end
1184
1185   def wiselinks_layout
1186     'body'
1187   end
1188 end