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