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