forked from commonsguy/cw-omnibus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.rb
73 lines (56 loc) · 1.42 KB
/
server.rb
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
require 'fileutils'
require 'time'
require 'sinatra'
require 'json'
BACKUP_ROOT='/tmp/backups'
get '/' do
'Hello world!'
end
get '/api/backups' do
result=[]
if File.exist?(BACKUP_ROOT)
Dir.foreach(BACKUP_ROOT) do |item|
next if item == '.' or item == '..'
subdir=File.join(BACKUP_ROOT, item)
if File.directory?(subdir)
f=File.join(subdir, "metadata.json")
if File.exist?(f)
metadata=JSON.load(open(f))
metadata['dataset']="/api/backups/#{item}/dataset"
result << metadata
end
end
end
end
result.sort_by!{|metadata| metadata['timestamp']}
result.reverse!
JSON.pretty_generate(result)
end
post '/api/backups' do
id=SecureRandom.uuid
dir=File.join(BACKUP_ROOT, id)
FileUtils.mkdir_p(dir)
f=File.join(dir, "metadata.json")
metadata={'timestamp'=>Time.new.xmlschema}
File.open(f, 'w') {|io| io.write(JSON.generate(metadata))}
redirect to('/api/backups/'+id), 201
end
put '/api/backups/:id/dataset' do
dir=File.join(BACKUP_ROOT, params[:id])
if File.exist?(dir)
f=File.join(dir, "backup.zip")
File.open(f, 'w') {|io| io.write(request.body.read)}
redirect to("/api/backups/#{params[:id]}/dataset"), 201
else
status 404
end
end
get '/api/backups/:id/dataset' do
dir=File.join(BACKUP_ROOT, params[:id])
f=File.join(dir, "backup.zip")
if File.exist?(f)
send_file f
else
status 404
end
end