11167: Removed conditional code
[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_filter :require_thread_api_token, if: proc { |ctrl|
13     Rails.configuration.anonymous_user_token and
14     'show' == ctrl.action_name
15   }
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
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]])
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]])
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))
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 = [(Rails.configuration.anonymous_user_token || nil),
128               params[:reader_token],
129               Thread.current[:arvados_api_token]].compact
130     usable_token = find_usable_token(tokens) do
131       coll = Collection.find(params[:uuid])
132     end
133     if usable_token.nil?
134       # Response already rendered.
135       return
136     end
137
138     opts = {}
139     if usable_token == params[:reader_token]
140       opts[:path_token] = usable_token
141     elsif usable_token == Rails.configuration.anonymous_user_token
142       # Don't pass a token at all
143     else
144       # We pass the current user's real token only if it's necessary
145       # to read the collection.
146       opts[:query_token] = usable_token
147     end
148     opts[:disposition] = params[:disposition] if params[:disposition]
149     return redirect_to keep_web_url(params[:uuid], params[:file], opts)
150   end
151
152   def sharing_scopes
153     ["GET /arvados/v1/collections/#{@object.uuid}", "GET /arvados/v1/collections/#{@object.uuid}/", "GET /arvados/v1/keep_services/accessible"]
154   end
155
156   def search_scopes
157     begin
158       ApiClientAuthorization.filter([['scopes', '=', sharing_scopes]]).results
159     rescue ArvadosApiClient::AccessForbiddenException
160       nil
161     end
162   end
163
164   def find_object_by_uuid
165     if not Keep::Locator.parse params[:id]
166       super
167     end
168   end
169
170   def show
171     return super if !@object
172
173     @logs = []
174
175     if params["tab_pane"] == "Provenance_graph"
176       @prov_svg = ProvenanceHelper::create_provenance_graph(@object.provenance, "provenance_svg",
177                                                             {:request => request,
178                                                              :direction => :top_down,
179                                                              :combine_jobs => :script_only}) rescue nil
180     end
181
182     if current_user
183       if Keep::Locator.parse params["uuid"]
184         @same_pdh = Collection.filter([["portable_data_hash", "=", @object.portable_data_hash]]).limit(20)
185         if @same_pdh.results.size == 1
186           redirect_to collection_path(@same_pdh[0]["uuid"])
187           return
188         end
189         owners = @same_pdh.map(&:owner_uuid).to_a.uniq
190         preload_objects_for_dataclass Group, owners
191         preload_objects_for_dataclass User, owners
192         uuids = @same_pdh.map(&:uuid).to_a.uniq
193         preload_links_for_objects uuids
194         render 'hash_matches'
195         return
196       else
197         if Job.api_exists?(:index)
198           jobs_with = lambda do |conds|
199             Job.limit(RELATION_LIMIT).where(conds)
200               .results.sort_by { |j| j.finished_at || j.created_at }
201           end
202           @output_of = jobs_with.call(output: @object.portable_data_hash)
203           @log_of = jobs_with.call(log: @object.portable_data_hash)
204         end
205
206         @project_links = Link.limit(RELATION_LIMIT).order("modified_at DESC")
207           .where(head_uuid: @object.uuid, link_class: 'name').results
208         project_hash = Group.where(uuid: @project_links.map(&:tail_uuid)).to_hash
209         @projects = project_hash.values
210
211         @permissions = Link.limit(RELATION_LIMIT).order("modified_at DESC")
212           .where(head_uuid: @object.uuid, link_class: 'permission',
213                  name: 'can_read').results
214         @search_sharing = search_scopes
215
216         if params["tab_pane"] == "Used_by"
217           @used_by_svg = ProvenanceHelper::create_provenance_graph(@object.used_by, "used_by_svg",
218                                                                    {:request => request,
219                                                                     :direction => :top_down,
220                                                                     :combine_jobs => :script_only,
221                                                                     :pdata_only => true}) rescue nil
222         end
223       end
224     end
225     super
226   end
227
228   def sharing_popup
229     @search_sharing = search_scopes
230     render("sharing_popup.js", content_type: "text/javascript")
231   end
232
233   helper_method :download_link
234
235   def download_link
236     token = @search_sharing.first.api_token
237     if Rails.configuration.keep_web_url || Rails.configuration.keep_web_download_url
238       keep_web_url(@object.uuid, nil, {path_token: token})
239     else
240       collections_url + "/download/#{@object.uuid}/#{token}/"
241     end
242   end
243
244   def share
245     ApiClientAuthorization.create(scopes: sharing_scopes)
246     sharing_popup
247   end
248
249   def unshare
250     search_scopes.each do |s|
251       s.destroy
252     end
253     sharing_popup
254   end
255
256   def remove_selected_files
257     uuids, source_paths = selected_collection_files params
258
259     arv_coll = Arv::Collection.new(@object.manifest_text)
260     source_paths[uuids[0]].each do |p|
261       arv_coll.rm "."+p
262     end
263
264     if @object.update_attributes manifest_text: arv_coll.manifest_text
265       show
266     else
267       self.render_error status: 422
268     end
269   end
270
271   def update
272     updated_attr = params[:collection].each.select {|a| a[0].andand.start_with? 'rename-file-path:'}
273
274     if updated_attr.size > 0
275       # Is it file rename?
276       file_path = updated_attr[0][0].split('rename-file-path:')[-1]
277
278       new_file_path = updated_attr[0][1]
279       if new_file_path.start_with?('./')
280         # looks good
281       elsif new_file_path.start_with?('/')
282         new_file_path = '.' + new_file_path
283       else
284         new_file_path = './' + new_file_path
285       end
286
287       arv_coll = Arv::Collection.new(@object.manifest_text)
288
289       if arv_coll.exist?(new_file_path)
290         @errors = 'Duplicate file path. Please use a different name.'
291         self.render_error status: 422
292       else
293         arv_coll.rename "./"+file_path, new_file_path
294
295         if @object.update_attributes manifest_text: arv_coll.manifest_text
296           show
297         else
298           self.render_error status: 422
299         end
300       end
301     else
302       # Not a file rename; use default
303       super
304     end
305   end
306
307   def tags
308     render
309   end
310
311   def save_tags
312     tags_param = params['tag_data']
313     if tags_param
314       if tags_param.is_a?(String) && tags_param == "empty"
315         tags = {}
316       else
317         tags = tags_param
318       end
319     end
320
321     if tags
322       if @object.update_attributes properties: tags
323         @saved_tags = true
324         render
325       else
326         self.render_error status: 422
327       end
328     end
329   end
330
331   protected
332
333   def find_usable_token(token_list)
334     # Iterate over every given token to make it the current token and
335     # yield the given block.
336     # If the block succeeds, return the token it used.
337     # Otherwise, render an error response based on the most specific
338     # error we encounter, and return nil.
339     most_specific_error = [401]
340     token_list.each do |api_token|
341       begin
342         # We can't load the corresponding user, because the token may not
343         # be scoped for that.
344         using_specific_api_token(api_token, load_user: false) do
345           yield
346           return api_token
347         end
348       rescue ArvadosApiClient::ApiError => error
349         if error.api_status >= most_specific_error.first
350           most_specific_error = [error.api_status, error]
351         end
352       end
353     end
354     case most_specific_error.shift
355     when 401, 403
356       redirect_to_login
357     when 404
358       render_not_found(*most_specific_error)
359     end
360     return nil
361   end
362
363   def keep_web_url(uuid_or_pdh, file, opts)
364     munged_id = uuid_or_pdh.sub('+', '-')
365     fmt = {uuid_or_pdh: munged_id}
366
367     tmpl = Rails.configuration.keep_web_url
368     if Rails.configuration.keep_web_download_url and
369         (!tmpl or opts[:disposition] == 'attachment')
370       # Prefer the attachment-only-host when we want an attachment
371       # (and when there is no preview link configured)
372       tmpl = Rails.configuration.keep_web_download_url
373     elsif not Rails.configuration.trust_all_content
374       check_uri = URI.parse(tmpl % fmt)
375       if opts[:query_token] and
376           not check_uri.host.start_with?(munged_id + "--") and
377           not check_uri.host.start_with?(munged_id + ".")
378         # We're about to pass a token in the query string, but
379         # keep-web can't accept that safely at a single-origin URL
380         # template (unless it's -attachment-only-host).
381         tmpl = Rails.configuration.keep_web_download_url
382         if not tmpl
383           raise ArgumentError, "Download precluded by site configuration"
384         end
385         logger.warn("Using download link, even though inline content " \
386                     "was requested: #{check_uri.to_s}")
387       end
388     end
389
390     if tmpl == Rails.configuration.keep_web_download_url
391       # This takes us to keep-web's -attachment-only-host so there is
392       # no need to add ?disposition=attachment.
393       opts.delete :disposition
394     end
395
396     uri = URI.parse(tmpl % fmt)
397     uri.path += '/' unless uri.path.end_with? '/'
398     if opts[:path_token]
399       uri.path += 't=' + opts[:path_token] + '/'
400     end
401     uri.path += '_/'
402     uri.path += URI.escape(file) if file
403
404     query = Hash[URI.decode_www_form(uri.query || '')]
405     { query_token: 'api_token',
406       disposition: 'disposition' }.each do |opt, param|
407       if opts.include? opt
408         query[param] = opts[opt]
409       end
410     end
411     unless query.empty?
412       uri.query = URI.encode_www_form(query)
413     end
414
415     uri.to_s
416   end
417 end