Merge branch 'master' into 15803-unsetup
[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'
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_to :back
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             end
91           when :move
92             dst = src
93           else
94             raise ArgumentError.new "Unsupported action #{action}"
95           end
96           dst.owner_uuid = @object.uuid
97           dst.tail_uuid = @object.uuid if dst.class == Link
98         end
99         begin
100           dst.save!
101         rescue
102           dst.name += " (#{Time.now.localtime})" if dst.respond_to? :name=
103           dst.save!
104         end
105       end
106     end
107     if (resource_classes == [Collection] and
108         @object.is_a? Group and
109         @object.group_class == 'project') or
110         @object.is_a? User
111       # In the common case where only collections are copied/moved
112       # into a project, it's polite to land on the collections tab on
113       # the destination project.
114       redirect_to project_url(@object.uuid, anchor: 'Data_collections')
115     else
116       # Otherwise just land on the default (Description) tab.
117       redirect_to @object
118     end
119   end
120
121   expose_action :combine_selected_files_into_collection do
122     uuids, source_paths = selected_collection_files params
123
124     new_coll = Arv::Collection.new
125     Collection.where(uuid: uuids.uniq).with_count("none").
126         select([:uuid, :manifest_text]).each do |coll|
127       src_coll = Arv::Collection.new(coll.manifest_text)
128       src_pathlist = source_paths[coll.uuid]
129       if src_pathlist.any?(&:blank?)
130         src_pathlist = src_coll.each_file_path
131         destdir = nil
132       else
133         destdir = "."
134       end
135       src_pathlist.each do |src_path|
136         src_path = src_path.sub(/^(\.\/|\/|)/, "./")
137         src_stream, _, basename = src_path.rpartition("/")
138         dst_stream = destdir || src_stream
139         # Generate a unique name by adding (1), (2), etc. to it.
140         # If the filename has a dot that's not at the beginning, insert the
141         # number just before that.  Otherwise, append the number to the name.
142         if match = basename.match(/[^\.]\./)
143           suffix_start = match.begin(0) + 1
144         else
145           suffix_start = basename.size
146         end
147         suffix_size = 0
148         dst_path = nil
149         loop.each_with_index do |_, try_count|
150           dst_path = "#{dst_stream}/#{basename}"
151           break unless new_coll.exist?(dst_path)
152           uniq_suffix = "(#{try_count + 1})"
153           basename[suffix_start, suffix_size] = uniq_suffix
154           suffix_size = uniq_suffix.size
155         end
156         new_coll.cp_r(src_path, dst_path, src_coll)
157       end
158     end
159
160     coll_attrs = {
161       manifest_text: new_coll.manifest_text,
162       name: "Collection created at #{Time.now.localtime}",
163     }
164     flash = {}
165
166     # set owner_uuid to current project, provided it is writable
167     action_data = Oj.load(params['action_data'] || "{}")
168     if action_data['current_project_uuid'] and
169         current_project = Group.find?(action_data['current_project_uuid']) and
170         current_project.writable_by.andand.include?(current_user.uuid)
171       coll_attrs[:owner_uuid] = current_project.uuid
172       flash[:message] =
173         "Created new collection in the project #{current_project.name}."
174     else
175       flash[:message] = "Created new collection in your Home project."
176     end
177
178     newc = Collection.create!(coll_attrs)
179     source_paths.each_key do |src_uuid|
180       unless Link.create({
181                            tail_uuid: src_uuid,
182                            head_uuid: newc.uuid,
183                            link_class: "provenance",
184                            name: "provided",
185                          })
186         flash[:error] = "
187 An error occurred when saving provenance information for this collection.
188 You can try recreating the collection to get a copy with full provenance data."
189         break
190       end
191     end
192     redirect_to(newc, flash: flash)
193   end
194
195   def report_issue_popup
196     respond_to do |format|
197       format.js
198       format.html
199     end
200   end
201
202   def report_issue
203     logger.warn "report_issue: #{params.inspect}"
204
205     respond_to do |format|
206       IssueReporter.send_report(current_user, params).deliver
207       format.js {render body: nil}
208     end
209   end
210
211   # star / unstar the current project
212   def star
213     links = Link.where(tail_uuid: current_user.uuid,
214                        head_uuid: @object.uuid,
215                        link_class: 'star')
216
217     if params['status'] == 'create'
218       # create 'star' link if one does not already exist
219       if !links.andand.any?
220         dst = Link.new(owner_uuid: current_user.uuid,
221                        tail_uuid: current_user.uuid,
222                        head_uuid: @object.uuid,
223                        link_class: 'star',
224                        name: @object.uuid)
225         dst.save!
226       end
227     else # delete any existing 'star' links
228       if links.andand.any?
229         links.each do |link|
230           link.destroy
231         end
232       end
233     end
234
235     respond_to do |format|
236       format.js
237     end
238   end
239
240   protected
241
242   def derive_unique_filename filename, manifest_files
243     filename_parts = filename.split('.')
244     filename_part = filename_parts[0]
245     counter = 1
246     while true
247       return filename if !manifest_files.include? filename
248       filename_parts[0] = filename_part + "(" + counter.to_s + ")"
249       filename = filename_parts.join('.')
250       counter += 1
251     end
252   end
253
254 end