2044: Sharing link now shown in "Sharing and permissions" panel, no longer uses
[arvados.git] / apps / workbench / app / controllers / collections_controller.rb
1 class CollectionsController < ApplicationController
2   skip_around_filter(:thread_with_mandatory_api_token,
3                      only: [:show_file, :show_file_links])
4   skip_before_filter(:find_object_by_uuid,
5                      only: [:provenance, :show_file, :show_file_links])
6
7   RELATION_LIMIT = 5
8
9   def show_pane_list
10     %w(Files Attributes Metadata Provenance_graph Used_by JSON API)
11   end
12
13   def set_persistent
14     case params[:value]
15     when 'persistent', 'cache'
16       persist_links = Link.filter([['owner_uuid', '=', current_user.uuid],
17                                    ['link_class', '=', 'resources'],
18                                    ['name', '=', 'wants'],
19                                    ['tail_uuid', '=', current_user.uuid],
20                                    ['head_uuid', '=', @object.uuid]])
21       logger.debug persist_links.inspect
22     else
23       return unprocessable "Invalid value #{value.inspect}"
24     end
25     if params[:value] == 'persistent'
26       if not persist_links.any?
27         Link.create(link_class: 'resources',
28                     name: 'wants',
29                     tail_uuid: current_user.uuid,
30                     head_uuid: @object.uuid)
31       end
32     else
33       persist_links.each do |link|
34         link.destroy || raise
35       end
36     end
37
38     respond_to do |f|
39       f.json { render json: @object }
40     end
41   end
42
43   def index
44     if params[:search].andand.length.andand > 0
45       tags = Link.where(any: ['contains', params[:search]])
46       @collections = (Collection.where(uuid: tags.collect(&:head_uuid)) |
47                       Collection.where(any: ['contains', params[:search]])).
48         uniq { |c| c.uuid }
49     else
50       if params[:limit]
51         limit = params[:limit].to_i
52       else
53         limit = 100
54       end
55
56       if params[:offset]
57         offset = params[:offset].to_i
58       else
59         offset = 0
60       end
61
62       @collections = Collection.limit(limit).offset(offset)
63     end
64     @links = Link.limit(1000).
65       where(head_uuid: @collections.collect(&:uuid))
66     @collection_info = {}
67     @collections.each do |c|
68       @collection_info[c.uuid] = {
69         tag_links: [],
70         wanted: false,
71         wanted_by_me: false,
72         provenance: [],
73         links: []
74       }
75     end
76     @links.each do |link|
77       @collection_info[link.head_uuid] ||= {}
78       info = @collection_info[link.head_uuid]
79       case link.link_class
80       when 'tag'
81         info[:tag_links] << link
82       when 'resources'
83         info[:wanted] = true
84         info[:wanted_by_me] ||= link.tail_uuid == current_user.uuid
85       when 'provenance'
86         info[:provenance] << link.name
87       end
88       info[:links] << link
89     end
90     @request_url = request.url
91   end
92
93   def show_file_links
94     Thread.current[:reader_tokens] = [params[:reader_token]]
95     find_object_by_uuid
96     render layout: false
97   end
98
99   def show_file
100     # We pipe from arv-get to send the file to the user.  Before we start it,
101     # we ask the API server if the file actually exists.  This serves two
102     # purposes: it lets us return a useful status code for common errors, and
103     # helps us figure out which token to provide to arv-get.
104     coll = nil
105     tokens = [Thread.current[:arvados_api_token], params[:reader_token]].compact
106     usable_token = find_usable_token(tokens) do
107       coll = Collection.find(params[:uuid])
108     end
109     if usable_token.nil?
110       return  # Response already rendered.
111     elsif params[:file].nil? or not file_in_collection?(coll, params[:file])
112       return render_not_found
113     end
114     opts = params.merge(arvados_api_token: usable_token)
115     ext = File.extname(params[:file])
116     self.response.headers['Content-Type'] =
117       Rack::Mime::MIME_TYPES[ext] || 'application/octet-stream'
118     self.response.headers['Content-Length'] = params[:size] if params[:size]
119     self.response.headers['Content-Disposition'] = params[:disposition] if params[:disposition]
120     self.response_body = file_enumerator opts
121   end
122
123   def sharing_scopes
124     ["GET /arvados/v1/collections/#{@object.uuid}", "GET /arvados/v1/keep_services"]
125   end
126
127   def search_scopes
128     ApiClientAuthorization.where(filters: [['scopes', '=', sharing_scopes]])
129   end
130
131   def show
132     return super if !@object
133     if current_user
134       jobs_with = lambda do |conds|
135         Job.limit(RELATION_LIMIT).where(conds)
136           .results.sort_by { |j| j.finished_at || j.created_at }
137       end
138       @output_of = jobs_with.call(output: @object.uuid)
139       @log_of = jobs_with.call(log: @object.uuid)
140       folder_links = Link.limit(RELATION_LIMIT).order("modified_at DESC")
141         .where(head_uuid: @object.uuid, link_class: 'name').results
142       folder_hash = Group.where(uuid: folder_links.map(&:tail_uuid)).to_hash
143       @folders = folder_links.map { |link| folder_hash[link.tail_uuid] }
144       @permissions = Link.limit(RELATION_LIMIT).order("modified_at DESC")
145         .where(head_uuid: @object.uuid, link_class: 'permission',
146                name: 'can_read').results
147       @logs = Log.limit(RELATION_LIMIT).order("created_at DESC")
148         .where(object_uuid: @object.uuid).results
149       @is_persistent = Link.limit(1)
150         .where(head_uuid: @object.uuid, tail_uuid: current_user.uuid,
151                link_class: 'resources', name: 'wants')
152         .results.any?
153       @search_sharing = search_scopes.select { |s| s.scopes != ['all'] }
154     end
155     @prov_svg = ProvenanceHelper::create_provenance_graph(@object.provenance, "provenance_svg",
156                                                           {:request => request,
157                                                             :direction => :bottom_up,
158                                                             :combine_jobs => :script_only}) rescue nil
159     @used_by_svg = ProvenanceHelper::create_provenance_graph(@object.used_by, "used_by_svg",
160                                                              {:request => request,
161                                                                :direction => :top_down,
162                                                                :combine_jobs => :script_only,
163                                                                :pdata_only => true}) rescue nil
164   end
165
166   def sharing_popup
167     @search_sharing = search_scopes.select { |s| s.scopes != ['all'] }
168     respond_to do |format|
169       format.html
170       format.js
171     end
172   end
173
174   helper_method :download_link
175
176   def download_link
177     collections_url + "/download/#{@object.uuid}/#{@search_sharing.first.api_token}"
178   end
179
180   def share
181     a = ApiClientAuthorization.create(scopes: sharing_scopes)
182     @search_sharing = search_scopes.select { |s| s.scopes != ['all'] }
183     render 'sharing_popup'
184   end
185
186   def unshare
187     @search_sharing = search_scopes.select { |s| s.scopes != ['all'] }
188     @search_sharing.each do |s|
189       s.destroy
190     end
191     @search_sharing = search_scopes.select { |s| s.scopes != ['all'] }
192     render 'sharing_popup'
193   end
194
195   protected
196
197   def find_usable_token(token_list)
198     # Iterate over every given token to make it the current token and
199     # yield the given block.
200     # If the block succeeds, return the token it used.
201     # Otherwise, render an error response based on the most specific
202     # error we encounter, and return nil.
203     most_specific_error = [401]
204     token_list.each do |api_token|
205       using_specific_api_token(api_token) do
206         begin
207           yield
208           return api_token
209         rescue ArvadosApiClient::NotLoggedInException => error
210           status = 401
211         rescue => error
212           status = (error.message =~ /\[API: (\d+)\]$/) ? $1.to_i : nil
213           raise unless [401, 403, 404].include?(status)
214         end
215         if status >= most_specific_error.first
216           most_specific_error = [status, error]
217         end
218       end
219     end
220     case most_specific_error.shift
221     when 401, 403
222       redirect_to_login
223     when 404
224       render_not_found(*most_specific_error)
225     end
226     return nil
227   end
228
229   def file_in_collection?(collection, filename)
230     target = CollectionsHelper.file_path(File.split(filename))
231     collection.files.each do |file_spec|
232       return true if (CollectionsHelper.file_path(file_spec) == target)
233     end
234     false
235   end
236
237   def file_enumerator(opts)
238     FileStreamer.new opts
239   end
240
241   class FileStreamer
242     include ArvadosApiClientHelper
243     def initialize(opts={})
244       @opts = opts
245     end
246     def each
247       return unless @opts[:uuid] && @opts[:file]
248
249       env = Hash[ENV].dup
250
251       require 'uri'
252       u = URI.parse(arvados_api_client.arvados_v1_base)
253       env['ARVADOS_API_HOST'] = "#{u.host}:#{u.port}"
254       env['ARVADOS_API_TOKEN'] = @opts[:arvados_api_token]
255       env['ARVADOS_API_HOST_INSECURE'] = "true" if Rails.configuration.arvados_insecure_https
256
257       IO.popen([env, 'arv-get', "#{@opts[:uuid]}/#{@opts[:file]}"],
258                'rb') do |io|
259         while buf = io.read(2**16)
260           yield buf
261         end
262       end
263       Rails.logger.warn("#{@opts[:uuid]}/#{@opts[:file]}: #{$?}") if $? != 0
264     end
265   end
266 end