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