1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
6 require "arvados/collection"
9 class CollectionsController < ApplicationController
10 include ActionController::Live
12 skip_around_filter :require_thread_api_token, if: proc { |ctrl|
13 Rails.configuration.anonymous_user_token and
14 'show' == ctrl.action_name
16 skip_around_filter(:require_thread_api_token,
17 only: [:show_file, :show_file_links])
18 skip_before_filter(: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_filter :check_user_agreements, only: :show_file
22 skip_before_filter :check_user_profile, only: :show_file
27 panes = %w(Files Upload Tags Provenance_graph Used_by Advanced)
28 panes = panes - %w(Upload) unless (@object.editable? rescue false)
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]])
40 logger.debug persist_links.inspect
42 return unprocessable "Invalid value #{value.inspect}"
44 if params[:value] == 'persistent'
45 if not persist_links.any?
46 Link.create(link_class: 'resources',
48 tail_uuid: current_user.uuid,
49 head_uuid: @object.uuid)
52 persist_links.each do |link|
58 f.json { render json: @object }
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]])
69 @objects = (base_search.where(uuid: tags.collect(&:head_uuid)) |
70 base_search.where(any: ['contains', params[:search]])).
74 limit = params[:limit].to_i
80 offset = params[:offset].to_i
85 @objects = base_search.limit(limit).offset(offset)
87 @links = Link.where(head_uuid: @objects.collect(&:uuid))
90 @collection_info[c.uuid] = {
99 @collection_info[link.head_uuid] ||= {}
100 info = @collection_info[link.head_uuid]
103 info[:tag_links] << link
106 info[:wanted_by_me] ||= link.tail_uuid == current_user.uuid
108 info[:provenance] << link.name
112 @request_url = request.url
118 if Rails.configuration.keep_web_url || Rails.configuration.keep_web_download_url
119 # show_file will redirect to keep-web's directory listing
122 Thread.current[:reader_tokens] = [params[:reader_token]]
123 return if false.equal?(find_object_by_uuid)
128 # The order of searched tokens is important: because the anonymous user
129 # token is passed along with every API request, we have to check it first.
130 # Otherwise, it's impossible to know whether any other request succeeded
131 # because of the reader token.
133 tokens = [(Rails.configuration.anonymous_user_token || nil),
134 params[:reader_token],
135 Thread.current[:arvados_api_token]].compact
136 usable_token = find_usable_token(tokens) do
137 coll = Collection.find(params[:uuid])
140 # Response already rendered.
145 if usable_token == params[:reader_token]
146 opts[:path_token] = usable_token
147 elsif usable_token == Rails.configuration.anonymous_user_token
148 # Don't pass a token at all
150 # We pass the current user's real token only if it's necessary
151 # to read the collection.
152 opts[:query_token] = usable_token
154 opts[:disposition] = params[:disposition] if params[:disposition]
155 return redirect_to keep_web_url(params[:uuid], params[:file], opts)
159 ["GET /arvados/v1/collections/#{@object.uuid}", "GET /arvados/v1/collections/#{@object.uuid}/", "GET /arvados/v1/keep_services/accessible"]
164 ApiClientAuthorization.filter([['scopes', '=', sharing_scopes]]).results
165 rescue ArvadosApiClient::AccessForbiddenException
170 def find_object_by_uuid
171 if not Keep::Locator.parse params[:id]
177 return super if !@object
181 if params["tab_pane"] == "Provenance_graph"
182 @prov_svg = ProvenanceHelper::create_provenance_graph(@object.provenance, "provenance_svg",
183 {:request => request,
184 :direction => :top_down,
185 :combine_jobs => :script_only}) rescue nil
189 if Keep::Locator.parse params["uuid"]
190 @same_pdh = Collection.filter([["portable_data_hash", "=", @object.portable_data_hash]]).limit(20)
191 if @same_pdh.results.size == 1
192 redirect_to collection_path(@same_pdh[0]["uuid"])
195 owners = @same_pdh.map(&:owner_uuid).to_a.uniq
196 preload_objects_for_dataclass Group, owners
197 preload_objects_for_dataclass User, owners
198 uuids = @same_pdh.map(&:uuid).to_a.uniq
199 preload_links_for_objects uuids
200 render 'hash_matches'
203 if Job.api_exists?(:index)
204 jobs_with = lambda do |conds|
205 Job.limit(RELATION_LIMIT).where(conds)
206 .results.sort_by { |j| j.finished_at || j.created_at }
208 @output_of = jobs_with.call(output: @object.portable_data_hash)
209 @log_of = jobs_with.call(log: @object.portable_data_hash)
212 @project_links = Link.limit(RELATION_LIMIT).order("modified_at DESC")
213 .where(head_uuid: @object.uuid, link_class: 'name').results
214 project_hash = Group.where(uuid: @project_links.map(&:tail_uuid)).to_hash
215 @projects = project_hash.values
217 @permissions = Link.limit(RELATION_LIMIT).order("modified_at DESC")
218 .where(head_uuid: @object.uuid, link_class: 'permission',
219 name: 'can_read').results
220 @search_sharing = search_scopes
222 if params["tab_pane"] == "Used_by"
223 @used_by_svg = ProvenanceHelper::create_provenance_graph(@object.used_by, "used_by_svg",
224 {:request => request,
225 :direction => :top_down,
226 :combine_jobs => :script_only,
227 :pdata_only => true}) rescue nil
235 @search_sharing = search_scopes
236 render("sharing_popup.js", content_type: "text/javascript")
239 helper_method :download_link
242 token = @search_sharing.first.api_token
243 if Rails.configuration.keep_web_url || Rails.configuration.keep_web_download_url
244 keep_web_url(@object.uuid, nil, {path_token: token})
246 collections_url + "/download/#{@object.uuid}/#{token}/"
251 ApiClientAuthorization.create(scopes: sharing_scopes)
256 search_scopes.each do |s|
262 def remove_selected_files
263 uuids, source_paths = selected_collection_files params
265 arv_coll = Arv::Collection.new(@object.manifest_text)
266 source_paths[uuids[0]].each do |p|
270 if @object.update_attributes manifest_text: arv_coll.manifest_text
273 self.render_error status: 422
278 updated_attr = params[:collection].each.select {|a| a[0].andand.start_with? 'rename-file-path:'}
280 if updated_attr.size > 0
282 file_path = updated_attr[0][0].split('rename-file-path:')[-1]
284 new_file_path = updated_attr[0][1]
285 if new_file_path.start_with?('./')
287 elsif new_file_path.start_with?('/')
288 new_file_path = '.' + new_file_path
290 new_file_path = './' + new_file_path
293 arv_coll = Arv::Collection.new(@object.manifest_text)
295 if arv_coll.exist?(new_file_path)
296 @errors = 'Duplicate file path. Please use a different name.'
297 self.render_error status: 422
299 arv_coll.rename "./"+file_path, new_file_path
301 if @object.update_attributes manifest_text: arv_coll.manifest_text
304 self.render_error status: 422
308 # Not a file rename; use default
318 tags_param = params['tag_data']
320 if tags_param.is_a?(String) && tags_param == "empty"
328 if @object.update_attributes properties: tags
332 self.render_error status: 422
339 def find_usable_token(token_list)
340 # Iterate over every given token to make it the current token and
341 # yield the given block.
342 # If the block succeeds, return the token it used.
343 # Otherwise, render an error response based on the most specific
344 # error we encounter, and return nil.
345 most_specific_error = [401]
346 token_list.each do |api_token|
348 # We can't load the corresponding user, because the token may not
349 # be scoped for that.
350 using_specific_api_token(api_token, load_user: false) do
354 rescue ArvadosApiClient::ApiError => error
355 if error.api_status >= most_specific_error.first
356 most_specific_error = [error.api_status, error]
360 case most_specific_error.shift
364 render_not_found(*most_specific_error)
369 def keep_web_url(uuid_or_pdh, file, opts)
370 munged_id = uuid_or_pdh.sub('+', '-')
371 fmt = {uuid_or_pdh: munged_id}
373 tmpl = Rails.configuration.keep_web_url
374 if Rails.configuration.keep_web_download_url and
375 (!tmpl or opts[:disposition] == 'attachment')
376 # Prefer the attachment-only-host when we want an attachment
377 # (and when there is no preview link configured)
378 tmpl = Rails.configuration.keep_web_download_url
379 elsif not Rails.configuration.trust_all_content
380 check_uri = URI.parse(tmpl % fmt)
381 if opts[:query_token] and
382 not check_uri.host.start_with?(munged_id + "--") and
383 not check_uri.host.start_with?(munged_id + ".")
384 # We're about to pass a token in the query string, but
385 # keep-web can't accept that safely at a single-origin URL
386 # template (unless it's -attachment-only-host).
387 tmpl = Rails.configuration.keep_web_download_url
389 raise ArgumentError, "Download precluded by site configuration"
391 logger.warn("Using download link, even though inline content " \
392 "was requested: #{check_uri.to_s}")
396 if tmpl == Rails.configuration.keep_web_download_url
397 # This takes us to keep-web's -attachment-only-host so there is
398 # no need to add ?disposition=attachment.
399 opts.delete :disposition
402 uri = URI.parse(tmpl % fmt)
403 uri.path += '/' unless uri.path.end_with? '/'
405 uri.path += 't=' + opts[:path_token] + '/'
408 uri.path += URI.escape(file) if file
410 query = Hash[URI.decode_www_form(uri.query || '')]
411 { query_token: 'api_token',
412 disposition: 'disposition' }.each do |opt, param|
414 query[param] = opts[opt]
418 uri.query = URI.encode_www_form(query)