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