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