6476: skip require_thread_api_token filter when anonymous browsing is enabled and...
[arvados.git] / apps / workbench / app / controllers / actions_controller.rb
1 require "arvados/collection"
2
3 class ActionsController < ApplicationController
4
5   skip_around_filter :require_thread_api_token, if: proc { |ctrl|
6     Rails.configuration.anonymous_user_token and
7     'show' == ctrl.action_name and
8     params['uuid'] and
9     (model_class == Collection or
10      model_class == Group or
11      model_class == Job or
12      model_class == PipelineInstance or
13      model_class == PipelineTemplate)
14   }
15   skip_filter :require_thread_api_token, only: [:report_issue_popup, :report_issue]
16   skip_filter :check_user_agreements, only: [:report_issue_popup, :report_issue]
17
18   @@exposed_actions = {}
19   def self.expose_action method, &block
20     @@exposed_actions[method] = true
21     define_method method, block
22   end
23
24   def model_class
25     ArvadosBase::resource_class_for_uuid(params[:uuid])
26   end
27
28   def show
29     @object = model_class.andand.find(params[:uuid])
30     if @object.is_a? Link and
31         @object.link_class == 'name' and
32         ArvadosBase::resource_class_for_uuid(@object.head_uuid) == Collection
33       redirect_to collection_path(id: @object.uuid)
34     elsif @object.is_a?(Group) and @object.group_class == 'project'
35       redirect_to project_path(id: @object.uuid)
36     elsif @object
37       redirect_to @object
38     else
39       raise ActiveRecord::RecordNotFound
40     end
41   end
42
43   def post
44     params.keys.collect(&:to_sym).each do |param|
45       if @@exposed_actions[param]
46         return self.send(param)
47       end
48     end
49     redirect_to :back
50   end
51
52   expose_action :copy_selections_into_project do
53     move_or_copy :copy
54   end
55
56   expose_action :move_selections_into_project do
57     move_or_copy :move
58   end
59
60   def move_or_copy action
61     uuids_to_add = params["selection"]
62     uuids_to_add = [ uuids_to_add ] unless uuids_to_add.is_a? Array
63     resource_classes = uuids_to_add.
64       collect { |x| ArvadosBase::resource_class_for_uuid(x) }.
65       uniq
66     resource_classes.each do |resource_class|
67       resource_class.filter([['uuid','in',uuids_to_add]]).each do |src|
68         if resource_class == Collection and not Collection.attribute_info.include?(:name)
69           dst = Link.new(owner_uuid: @object.uuid,
70                          tail_uuid: @object.uuid,
71                          head_uuid: src.uuid,
72                          link_class: 'name',
73                          name: src.uuid)
74         else
75           case action
76           when :copy
77             dst = src.dup
78             if dst.respond_to? :'name='
79               if dst.name
80                 dst.name = "Copy of #{dst.name}"
81               else
82                 dst.name = "Copy of unnamed #{dst.class_for_display.downcase}"
83               end
84             end
85             if resource_class == Collection
86               dst.manifest_text = Collection.select([:manifest_text]).where(uuid: src.uuid).first.manifest_text
87             end
88           when :move
89             dst = src
90           else
91             raise ArgumentError.new "Unsupported action #{action}"
92           end
93           dst.owner_uuid = @object.uuid
94           dst.tail_uuid = @object.uuid if dst.class == Link
95         end
96         begin
97           dst.save!
98         rescue
99           dst.name += " (#{Time.now.localtime})" if dst.respond_to? :name=
100           dst.save!
101         end
102       end
103     end
104     if (resource_classes == [Collection] and
105         @object.is_a? Group and
106         @object.group_class == 'project') or
107         @object.is_a? User
108       # In the common case where only collections are copied/moved
109       # into a project, it's polite to land on the collections tab on
110       # the destination project.
111       redirect_to project_url(@object.uuid, anchor: 'Data_collections')
112     else
113       # Otherwise just land on the default (Description) tab.
114       redirect_to @object
115     end
116   end
117
118   expose_action :combine_selected_files_into_collection do
119     link_uuids, coll_ids = params["selection"].partition do |sel_s|
120       ArvadosBase::resource_class_for_uuid(sel_s) == Link
121     end
122
123     unless link_uuids.empty?
124       Link.select([:head_uuid]).where(uuid: link_uuids).each do |link|
125         if ArvadosBase::resource_class_for_uuid(link.head_uuid) == Collection
126           coll_ids << link.head_uuid
127         end
128       end
129     end
130
131     uuids = []
132     pdhs = []
133     source_paths = Hash.new { |hash, key| hash[key] = [] }
134     coll_ids.each do |coll_id|
135       if m = CollectionsHelper.match(coll_id)
136         key = m[1] + m[2]
137         pdhs << key
138         source_paths[key] << m[4]
139       elsif m = CollectionsHelper.match_uuid_with_optional_filepath(coll_id)
140         key = m[1]
141         uuids << key
142         source_paths[key] << m[4]
143       end
144     end
145
146     unless pdhs.empty?
147       Collection.where(portable_data_hash: pdhs.uniq).
148           select([:uuid, :portable_data_hash]).each do |coll|
149         unless source_paths[coll.portable_data_hash].empty?
150           uuids << coll.uuid
151           source_paths[coll.uuid] = source_paths.delete(coll.portable_data_hash)
152         end
153       end
154     end
155
156     new_coll = Arv::Collection.new
157     Collection.where(uuid: uuids.uniq).
158         select([:uuid, :manifest_text]).each do |coll|
159       src_coll = Arv::Collection.new(coll.manifest_text)
160       src_pathlist = source_paths[coll.uuid]
161       if src_pathlist.any?(&:blank?)
162         src_pathlist = src_coll.each_file_path
163         destdir = nil
164       else
165         destdir = "."
166       end
167       src_pathlist.each do |src_path|
168         src_path = src_path.sub(/^(\.\/|\/|)/, "./")
169         src_stream, _, basename = src_path.rpartition("/")
170         dst_stream = destdir || src_stream
171         # Generate a unique name by adding (1), (2), etc. to it.
172         # If the filename has a dot that's not at the beginning, insert the
173         # number just before that.  Otherwise, append the number to the name.
174         if match = basename.match(/[^\.]\./)
175           suffix_start = match.begin(0) + 1
176         else
177           suffix_start = basename.size
178         end
179         suffix_size = 0
180         dst_path = nil
181         loop.each_with_index do |_, try_count|
182           dst_path = "#{dst_stream}/#{basename}"
183           break unless new_coll.exist?(dst_path)
184           uniq_suffix = "(#{try_count + 1})"
185           basename[suffix_start, suffix_size] = uniq_suffix
186           suffix_size = uniq_suffix.size
187         end
188         new_coll.cp_r(src_path, dst_path, src_coll)
189       end
190     end
191
192     coll_attrs = {
193       manifest_text: new_coll.manifest_text,
194       name: "Collection created at #{Time.now.localtime}",
195     }
196     flash = {}
197
198     # set owner_uuid to current project, provided it is writable
199     action_data = Oj.load(params['action_data'] || "{}")
200     if action_data['current_project_uuid'] and
201         current_project = Group.find?(action_data['current_project_uuid']) and
202         current_project.writable_by.andand.include?(current_user.uuid)
203       coll_attrs[:owner_uuid] = current_project.uuid
204       flash[:message] =
205         "Created new collection in the project #{current_project.name}."
206     else
207       flash[:message] = "Created new collection in your Home project."
208     end
209
210     newc = Collection.create!(coll_attrs)
211     source_paths.each_key do |src_uuid|
212       unless Link.create({
213                            tail_uuid: src_uuid,
214                            head_uuid: newc.uuid,
215                            link_class: "provenance",
216                            name: "provided",
217                          })
218         flash[:error] = "
219 An error occurred when saving provenance information for this collection.
220 You can try recreating the collection to get a copy with full provenance data."
221         break
222       end
223     end
224     redirect_to(newc, flash: flash)
225   end
226
227   def report_issue_popup
228     respond_to do |format|
229       format.js
230       format.html
231     end
232   end
233
234   def report_issue
235     logger.warn "report_issue: #{params.inspect}"
236
237     respond_to do |format|
238       IssueReporter.send_report(current_user, params).deliver
239       format.js {render nothing: true}
240     end
241   end
242
243   protected
244
245   def derive_unique_filename filename, manifest_files
246     filename_parts = filename.split('.')
247     filename_part = filename_parts[0]
248     counter = 1
249     while true
250       return filename if !manifest_files.include? filename
251       filename_parts[0] = filename_part + "(" + counter.to_s + ")"
252       filename = filename_parts.join('.')
253       counter += 1
254     end
255   end
256
257 end