20259: Add documentation for banner and tooltip features
[arvados.git] / apps / workbench / app / controllers / collections_controller.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 require "arvados/keep"
6 require "arvados/collection"
7 require "uri"
8
9 class CollectionsController < ApplicationController
10   include ActionController::Live
11
12   skip_around_action :require_thread_api_token, if: proc { |ctrl|
13     !Rails.configuration.Users.AnonymousUserToken.empty? and
14     'show' == ctrl.action_name
15   }
16   skip_around_action(:require_thread_api_token,
17                      only: [:show_file, :show_file_links])
18   skip_before_action(:find_object_by_uuid,
19                      only: [:provenance, :show_file, :show_file_links])
20   # We depend on show_file to display the user agreement:
21   skip_before_action :check_user_agreements, only: :show_file
22   skip_before_action :check_user_profile, only: :show_file
23
24   RELATION_LIMIT = 5
25
26   def show_pane_list
27     panes = %w(Files Upload Tags Provenance_graph Used_by Advanced)
28     panes = panes - %w(Upload) unless (@object.editable? rescue false)
29     panes
30   end
31
32   def set_persistent
33     case params[:value]
34     when 'persistent', 'cache'
35       persist_links = Link.filter([['owner_uuid', '=', current_user.uuid],
36                                    ['link_class', '=', 'resources'],
37                                    ['name', '=', 'wants'],
38                                    ['tail_uuid', '=', current_user.uuid],
39                                    ['head_uuid', '=', @object.uuid]]).with_count("none")
40       logger.debug persist_links.inspect
41     else
42       return unprocessable "Invalid value #{value.inspect}"
43     end
44     if params[:value] == 'persistent'
45       if not persist_links.any?
46         Link.create(link_class: 'resources',
47                     name: 'wants',
48                     tail_uuid: current_user.uuid,
49                     head_uuid: @object.uuid)
50       end
51     else
52       persist_links.each do |link|
53         link.destroy || raise
54       end
55     end
56
57     respond_to do |f|
58       f.json { render json: @object }
59     end
60   end
61
62   def index
63     # API server index doesn't return manifest_text by default, but our
64     # callers want it unless otherwise specified.
65     @select ||= Collection.columns.map(&:name)
66     base_search = Collection.select(@select)
67     if params[:search].andand.length.andand > 0
68       tags = Link.where(any: ['contains', params[:search]]).with_count("none")
69       @objects = (base_search.where(uuid: tags.collect(&:head_uuid)) |
70                       base_search.where(any: ['contains', params[:search]])).
71         uniq { |c| c.uuid }
72     else
73       if params[:limit]
74         limit = params[:limit].to_i
75       else
76         limit = 100
77       end
78
79       if params[:offset]
80         offset = params[:offset].to_i
81       else
82         offset = 0
83       end
84
85       @objects = base_search.limit(limit).offset(offset)
86     end
87     @links = Link.where(head_uuid: @objects.collect(&:uuid)).with_count("none")
88     @collection_info = {}
89     @objects.each do |c|
90       @collection_info[c.uuid] = {
91         tag_links: [],
92         wanted: false,
93         wanted_by_me: false,
94         provenance: [],
95         links: []
96       }
97     end
98     @links.each do |link|
99       @collection_info[link.head_uuid] ||= {}
100       info = @collection_info[link.head_uuid]
101       case link.link_class
102       when 'tag'
103         info[:tag_links] << link
104       when 'resources'
105         info[:wanted] = true
106         info[:wanted_by_me] ||= link.tail_uuid == current_user.uuid
107       when 'provenance'
108         info[:provenance] << link.name
109       end
110       info[:links] << link
111     end
112     @request_url = request.url
113
114     render_index
115   end
116
117   def show_file_links
118     return show_file
119   end
120
121   def show_file
122     # The order of searched tokens is important: because the anonymous user
123     # token is passed along with every API request, we have to check it first.
124     # Otherwise, it's impossible to know whether any other request succeeded
125     # because of the reader token.
126     coll = nil
127     tokens = [(if !Rails.configuration.Users.AnonymousUserToken.empty? then
128                 Rails.configuration.Users.AnonymousUserToken else nil end),
129               params[:reader_token],
130               Thread.current[:arvados_api_token]].compact
131     usable_token = find_usable_token(tokens) do
132       coll = Collection.find(params[:uuid])
133     end
134     if usable_token.nil?
135       # Response already rendered.
136       return
137     end
138
139     opts = {}
140     if usable_token == params[:reader_token]
141       opts[:path_token] = usable_token
142     elsif usable_token == Rails.configuration.Users.AnonymousUserToken
143       # Don't pass a token at all
144     else
145       # We pass the current user's real token only if it's necessary
146       # to read the collection.
147       opts[:query_token] = usable_token
148     end
149     opts[:disposition] = params[:disposition] if params[:disposition]
150     return redirect_to keep_web_url(params[:uuid], params[:file], opts)
151   end
152
153   def sharing_scopes
154     ["GET /arvados/v1/collections/#{@object.uuid}", "GET /arvados/v1/collections/#{@object.uuid}/", "GET /arvados/v1/keep_services/accessible"]
155   end
156
157   def search_scopes
158     begin
159       ApiClientAuthorization.filter([['scopes', '=', sharing_scopes]]).results
160     rescue ArvadosApiClient::AccessForbiddenException
161       nil
162     end
163   end
164
165   def find_object_by_uuid
166     if not Keep::Locator.parse params[:id]
167       super
168     end
169   end
170
171   def show
172     return super if !@object
173
174     @logs = []
175
176     if params["tab_pane"] == "Provenance_graph"
177       @prov_svg = ProvenanceHelper::create_provenance_graph(@object.provenance, "provenance_svg",
178                                                             {:request => request,
179                                                              :direction => "RL",
180                                                              :combine_jobs => :script_only}) rescue nil
181     end
182
183     if current_user
184       if Keep::Locator.parse params["uuid"]
185         @same_pdh = Collection.filter([["portable_data_hash", "=", @object.portable_data_hash]]).limit(20)
186         if @same_pdh.results.size == 1
187           redirect_to collection_path(@same_pdh[0]["uuid"])
188           return
189         end
190         owners = @same_pdh.map(&:owner_uuid).to_a.uniq
191         preload_objects_for_dataclass Group, owners
192         preload_objects_for_dataclass User, owners
193         uuids = @same_pdh.map(&:uuid).to_a.uniq
194         preload_links_for_objects uuids
195         render 'hash_matches'
196         return
197       else
198         if Job.api_exists?(:index)
199           jobs_with = lambda do |conds|
200             Job.limit(RELATION_LIMIT).with_count("none").where(conds)
201               .results.sort_by { |j| j.finished_at || j.created_at }
202           end
203           @output_of = jobs_with.call(output: @object.portable_data_hash)
204           @log_of = jobs_with.call(log: @object.portable_data_hash)
205         end
206
207         @project_links = Link.limit(RELATION_LIMIT).with_count("none").order("modified_at DESC")
208           .where(head_uuid: @object.uuid, link_class: 'name').results
209         project_hash = Group.where(uuid: @project_links.map(&:tail_uuid)).with_count("none").to_hash
210         @projects = project_hash.values
211
212         @permissions = Link.limit(RELATION_LIMIT).with_count("none").order("modified_at DESC")
213           .where(head_uuid: @object.uuid, link_class: 'permission',
214                  name: 'can_read').results
215         @search_sharing = search_scopes
216
217         if params["tab_pane"] == "Used_by"
218           @used_by_svg = ProvenanceHelper::create_provenance_graph(@object.used_by, "used_by_svg",
219                                                                    {:request => request,
220                                                                     :direction => "LR",
221                                                                     :combine_jobs => :script_only,
222                                                                     :pdata_only => true}) rescue nil
223         end
224       end
225     end
226     super
227   end
228
229   def sharing_popup
230     @search_sharing = search_scopes
231     render("sharing_popup.js", content_type: "text/javascript")
232   end
233
234   helper_method :download_link
235
236   def download_link
237     token = @search_sharing.first.api_token
238     keep_web_url(@object.uuid, nil, {path_token: token})
239   end
240
241   def share
242     ApiClientAuthorization.create(scopes: sharing_scopes)
243     sharing_popup
244   end
245
246   def unshare
247     search_scopes.each do |s|
248       s.destroy
249     end
250     sharing_popup
251   end
252
253   def remove_selected_files
254     uuids, source_paths = selected_collection_files params
255
256     arv_coll = Arv::Collection.new(@object.manifest_text)
257     source_paths[uuids[0]].each do |p|
258       arv_coll.rm "."+p
259     end
260
261     if @object.update_attributes manifest_text: arv_coll.manifest_text
262       show
263     else
264       self.render_error status: 422
265     end
266   end
267
268   def update
269     updated_attr = params[:collection].to_unsafe_hash.each.select {|a| a[0].andand.start_with? 'rename-file-path:'}
270
271     if updated_attr.size > 0
272       # Is it file rename?
273       file_path = updated_attr[0][0].split('rename-file-path:')[-1]
274
275       new_file_path = updated_attr[0][1]
276       if new_file_path.start_with?('./')
277         # looks good
278       elsif new_file_path.start_with?('/')
279         new_file_path = '.' + new_file_path
280       else
281         new_file_path = './' + new_file_path
282       end
283
284       arv_coll = Arv::Collection.new(@object.manifest_text)
285
286       if arv_coll.exist?(new_file_path)
287         @errors = 'Duplicate file path. Please use a different name.'
288         self.render_error status: 422
289       else
290         arv_coll.rename "./"+file_path, new_file_path
291
292         if @object.update_attributes manifest_text: arv_coll.manifest_text
293           show
294         else
295           self.render_error status: 422
296         end
297       end
298     else
299       # Not a file rename; use default
300       super
301     end
302   end
303
304   protected
305
306   def find_usable_token(token_list)
307     # Iterate over every given token to make it the current token and
308     # yield the given block.
309     # If the block succeeds, return the token it used.
310     # Otherwise, render an error response based on the most specific
311     # error we encounter, and return nil.
312     most_specific_error = [401]
313     token_list.each do |api_token|
314       begin
315         # We can't load the corresponding user, because the token may not
316         # be scoped for that.
317         using_specific_api_token(api_token, load_user: false) do
318           yield
319           return api_token
320         end
321       rescue ArvadosApiClient::ApiError => error
322         if error.api_status >= most_specific_error.first
323           most_specific_error = [error.api_status, error]
324         end
325       end
326     end
327     case most_specific_error.shift
328     when 401, 403
329       redirect_to_login
330     when 404
331       render_not_found(*most_specific_error)
332     end
333     return nil
334   end
335
336   def keep_web_url(uuid_or_pdh, file, opts)
337     munged_id = uuid_or_pdh.sub('+', '-')
338
339     tmpl = Rails.configuration.Services.WebDAV.ExternalURL.to_s
340
341     if Rails.configuration.Services.WebDAVDownload.ExternalURL != URI("") and
342         (tmpl.empty? or opts[:disposition] == 'attachment')
343       # Prefer the attachment-only-host when we want an attachment
344       # (and when there is no preview link configured)
345       tmpl = Rails.configuration.Services.WebDAVDownload.ExternalURL.to_s
346     elsif not Rails.configuration.Collections.TrustAllContent
347       check_uri = URI.parse(tmpl.sub("*", munged_id))
348       if opts[:query_token] and
349         (check_uri.host.nil? or (
350           not check_uri.host.start_with?(munged_id + "--") and
351           not check_uri.host.start_with?(munged_id + ".")))
352         # We're about to pass a token in the query string, but
353         # keep-web can't accept that safely at a single-origin URL
354         # template (unless it's -attachment-only-host).
355         tmpl = Rails.configuration.Services.WebDAVDownload.ExternalURL.to_s
356         if tmpl.empty?
357           raise ArgumentError, "Download precluded by site configuration"
358         end
359         logger.warn("Using download link, even though inline content " \
360                     "was requested: #{check_uri.to_s}")
361       end
362     end
363
364     if tmpl == Rails.configuration.Services.WebDAVDownload.ExternalURL.to_s
365       # This takes us to keep-web's -attachment-only-host so there is
366       # no need to add ?disposition=attachment.
367       opts.delete :disposition
368     end
369
370     uri = URI.parse(tmpl.sub("*", munged_id))
371     if tmpl.index("*").nil?
372       uri.path = "/c=#{munged_id}"
373     end
374     uri.path += '/' unless uri.path.end_with? '/'
375     if opts[:path_token]
376       uri.path += 't=' + opts[:path_token] + '/'
377     end
378     uri.path += '_/'
379     uri.path += URI.escape(file) if file
380
381     query = Hash[URI.decode_www_form(uri.query || '')]
382     { query_token: 'api_token',
383       disposition: 'disposition' }.each do |opt, param|
384       if opts.include? opt
385         query[param] = opts[opt]
386       end
387     end
388     unless query.empty?
389       uri.query = URI.encode_www_form(query)
390     end
391
392     uri.to_s
393   end
394 end