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