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