forked from a4agarwal/dropzone-user-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSCP Upload with Gallery.dropzone
executable file
·324 lines (278 loc) · 10 KB
/
SCP Upload with Gallery.dropzone
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
#!/usr/bin/ruby
# Dropzone Destination Info
# Name: SCP Upload with Gallery Creation
# Description: Uploads files to a remote SSH server. If multiple files are being uploaded, a 'gallery' is created. 'Option' zips the files up.
# Handles: NSFilenamesPboardType
# Events: Dragged, TestConnection
# KeyModifiers: Option, Control
# Creator: wulfovitch - based on code from Holistic Software Buggers
# URL: http://wulfovitch.net
# IconURL: http://wulfovitch.net/images/scp_image_upload.png
# OptionsNIB: ExtendedLogin
# DefaultPort: 22
require 'scp'
$host_info = {:server => ENV['SERVER'],
:port => ENV['PORT'],
:username => ENV['USERNAME'],
:password => ENV['PASSWORD']}
$image_max_width = '1024'
$image_max_height = '1024'
def dragged
delete_zip = false
if ENV['KEY_MODIFIERS'] == "Option"
# Zip up files before uploading
if $items.length == 1
# Use directory or file name as zip file name
dir_name = $items[0].split(File::SEPARATOR)[-1]
file = ZipFiles.zip($items, "#{dir_name}.zip")
else
file = ZipFiles.zip($items, "files.zip")
end
# Remove quotes
items = file[1..-2]
delete_zip = true
else
title_text = ""
if ENV['KEY_MODIFIERS'] == "Control"
output = `./CocoaDialog standard-inputbox --title "Enter Title" --e --informative-text "Enter the name for your files:"`
button, title_text = output.split("\n")
if button == "2" or title_text == nil
$dz.finish("Cancelled")
$dz.url(false)
return
end
end
$dz.begin("Resizing Images...")
$dz.determinate(true)
tmp_folder = "/tmp/dz_scp_tmp/"
if title_text.empty?
upload_folder_name = "#{Time.now.strftime("%Y-%m-%d_%I-%M-%S")}"
title_text = "#{Time.now.strftime("%Y-%m-%d %I:%M:%S")}"
else
upload_folder_name = "#{Time.now.strftime("%Y-%m-%d_")}#{title_text}"
title_text = "#{title_text} • #{Time.now.strftime("%Y-%m-%d")}"
end
upload_folder = "#{tmp_folder}#{upload_folder_name}/"
system("/bin/mkdir #{tmp_folder}")
system("/bin/mkdir #{upload_folder}")
system("/bin/mkdir #{upload_folder}#{upload_folder_name}")
items = Array.new
$items.each_with_index { |item, index|
file = File.basename(item, '.*')
ext = File.extname(item).downcase
if image?(item)
resized_image = "#{upload_folder}#{file}#{ext}"
convert_command_found = system("/usr/local/bin/convert #{item} -resize '#{$image_max_width}x#{$image_max_height}>' #{resized_image}")
if convert_command_found
items << resized_image
else
items << item
end
else
items << item
end
$dz.percent((((index+1).to_f / $items.length.to_f) * 100.0).to_i)
}
# only one file is uploaded, no need for a special folder
if items.length == 1
upload_folder_name = nil
else
# create html file, if multiple files are present
f = File.new("#{upload_folder}index.html", "w")
if f
f.syswrite("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n")
f.syswrite("\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n")
f.syswrite("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n")
f.syswrite("<head>\n")
f.syswrite(" <title>#{title_text}</title>\n")
f.syswrite(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n")
f.syswrite("</head>\n")
f.syswrite("<body>\n")
items.each_with_index { |item, index|
f.syswrite(" <p>\n")
slash = (ENV['ROOT_URL'][-1,1] == "/" ? "" : "/")
filename = "#{File.basename(item, '.*')}#{File.extname(item)}"
if image?(filename)
f.syswrite(" <img src=\"#{filename}\" alt=\"#{filename}\"/>\n")
else
f.syswrite(" <a href=\"#{filename}\">#{filename}</a>\n")
end
f.syswrite(" </p>\n")
}
f.syswrite("</body>\n")
f.syswrite("</html>")
items << f.path
end
end
end
if $items.length == 1
end
$dz.begin("Starting transfer...")
$dz.determinate(false)
unless upload_folder_name.nil?
# create folder on remote location
SCP.do_upload("#{upload_folder}#{upload_folder_name}", ENV['REMOTE_PATH'], $host_info)
# drop files into the just created folder
remote_paths = SCP.do_upload(items, ENV['REMOTE_PATH']+upload_folder_name, $host_info)
else
remote_paths = SCP.do_upload(items, ENV['REMOTE_PATH'], $host_info)
end
ZipFiles.delete_zip(items) if delete_zip
# Put URL of uploaded file on pasteboard
finish_text = "Upload Complete"
if remote_paths.length == 1
filename = remote_paths[0].split(File::SEPARATOR)[-1].strip[0..-2]
if ENV['ROOT_URL'] != nil
slash = (ENV['ROOT_URL'][-1,1] == "/" ? "" : "/")
url = ENV['ROOT_URL'] + slash + filename
finish_text = "URL is now on clipboard"
else
url = filename
end
else
filename = items.at(-1).split(File::SEPARATOR)[-1].strip[0..-1]
slash = (ENV['ROOT_URL'][-1,1] == "/" ? "" : "/")
url = ENV['ROOT_URL'] + slash + upload_folder_name
finish_text = "URL is now on clipboard"
end
system("/bin/rm -rf #{tmp_folder}")
$dz.finish(finish_text)
$dz.url(url)
end
def image?(filename)
allowed_exts = ["jpg", "jpeg", "gif", "tif", "tiff", "png", "bmp"]
ext = File.extname(filename).downcase[1..-1]
allowed_exts.include?(ext)
end
def testconnection
SCP.test_connection($host_info)
end
class SCP
def self.do_upload(source_files, destination, host_info)
last_percent = 0
last_uploaded_path = ""
set_determinate = false
uploaded_file_paths = []
host_info = self.sanitize_host_info(host_info)
destination = (destination != nil ? destination : "~/")
self.upload(source_files, destination, host_info[:server], host_info[:port],
host_info[:username], host_info[:password]) do |percent, remote_path|
remote_file = remote_path.split(File::SEPARATOR)[-1][0..-2]
if remote_path != last_uploaded_path
$dz.begin("Uploading #{remote_file}...")
uploaded_file_paths << remote_path
end
last_uploaded_path = remote_path
if not set_determinate
# Switch to determinate now file sizes have been calculated and upload is beginning
$dz.determinate(true)
set_determinate = true
end
$dz.percent(percent) if last_percent != percent
last_percent = percent
end
return uploaded_file_paths
end
def self.upload(localpaths, remotedir, host, port, user, pass, &block)
alert_title = "SCP Upload Error"
begin
Net::SSH.start(host, user, {:password => pass, :port => port}) do |ssh|
files = []
size = 0
localpaths.each do |localpath|
path = self.path_contents(localpath, remotedir)
files.concat path[:files]
size += path[:size]
end
transferred = 0
$dz.begin("Uploading #{files.size} files...") if files.length > 1
files.each do |local, remote|
if local.empty? then
# Try to create the directory
begin
ssh.exec! "mkdir \"#{remote}\""
rescue
# $dz.error("Error creating directory", $!)
# Remote already exists?
end
else
begin
# Send the file
bytesSent = 0
ssh.scp.upload!(local, remote) do |ch, name, sent, total|
bytesSent = sent
if size != 0
percent = ((transferred + sent) * 100 / size)
else
percent = 100
end
yield percent, remote
end
transferred += bytesSent
rescue
$dz.error(alert_title, $!)
end
end
end
end
rescue Timeout::Error
$dz.error(alert_title, "Connection timed out.")
rescue SocketError
$dz.error(alert_title, "Server not found.")
rescue Net::SSH::AuthenticationFailed
$dz.error(alert_title, "Username or password incorrect.")
rescue
$dz.error(error_title, $!)
end
end
def self.path_contents(localfile, remotedir)
files = []
size = 0
filestat = File.stat(localfile)
# Check if this is a file or directory
if filestat.directory? then
remotedir += ('/' + File.basename(localfile)).gsub('//', '/')
# Make sure we create the remote directory later
files.push ['', remotedir]
# Recurse through dir
Dir.foreach localfile do |file|
next if file == '.' or file == '..'
local = (localfile + '/' + file).gsub('//', '/')
begin
p = path_contents(local, remotedir)
rescue
next
end
size += p[:size]
files.concat p[:files]
end
elsif filestat.file? then
# Increment the size
size += File.size localfile;
remotefile = (remotedir + '/' + File.basename(localfile)).gsub('//', '/')
files.push [localfile, "\"" + remotefile + "\""]
end
return { :files => files, :size => size }
end
def self.sanitize_host_info(host_info)
host_info[:port] = (host_info[:port] != nil ? host_info[:port].to_i : 22)
return host_info
end
def self.test_connection(host_info)
host_info = self.sanitize_host_info(host_info)
error_title = "Connection Failed"
begin
Net::SSH.start(host_info[:server], host_info[:username], {:password => host_info[:password], :port => host_info[:port]}) do |ssh|
end
rescue Timeout::Error
$dz.error(error_title, "Connection timed out.")
rescue SocketError
$dz.error(error_title, "Server not found.")
rescue Net::SSH::AuthenticationFailed
$dz.error("Authentication Failed", "Username or password incorrect.")
rescue
$dz.error(error_title, $!)
end
$dz.alert("Connection Successful", "SCP connection succeeded.")
end
end