dcav-http-upload-server/server.rb

58 lines
1.5 KiB
Ruby
Raw Normal View History

2017-07-31 21:19:44 +00:00
require 'sinatra'
set :bind, '127.0.0.1'
2017-07-31 21:19:44 +00:00
set :port, '35257'
USERS = { 'christoffermadsen' => 'lolol' }
2017-07-31 21:19:44 +00:00
FILENAME_GENERATOR = lambda {rand(36**6).to_s(36)}
2017-07-31 23:23:17 +00:00
get '/' do
split_log = Array.new
File.open 'uploads.log', 'r' do |log|
log.each_line { |l| split_log << l }
end
count = split_log.count
latest = split_log[-1]
body "<b>#{count}</b> image#{unless count == 1 then "s" end} uploaded<br>" +
"Latest uploaded: <b>#{latest}</b>"
end
2017-07-31 21:19:44 +00:00
post '/upload' do
user = params['user']
pass = params['pass']
device_id = params['device_id']
puts "Receiving data from user #{user} on device #{device_id}"
puts "Authenticating with passphrase \"#{pass}\" on device #{device_id}"
unless pass == USERS[user]
return 401
end
puts "Authentication successful for user #{user} on device #{device_id}"
# Prefer filename sent with the request
impure_filename = (request['filename'] || FILENAME_GENERATOR.call) << ".png"
filename = sanitize_filename(impure_filename)
puts ENV['HOME']
File.open "#{ENV['HOME']}/public_html/screenshots/#{filename}", 'w+' do |f|
2017-07-31 21:19:44 +00:00
f << request['imagedata'][:tempfile].read
end
File.open "uploads.log", 'a+' do |log|
2017-07-31 23:23:17 +00:00
log << filename + "\n"
end
2017-07-31 21:19:44 +00:00
return [200, filename]
end
def sanitize_filename(filename)
# https://stackoverflow.com/questions/1939333/how-to-make-a-ruby-string-safe-for-a-filesystem#
fn = filename.split /(?<=.)\.(?=[^.])(?!.*\.[^.])/m
fn.map! { |s| s.gsub /[^a-z0-9\-]+/i, '_' }
return fn.join '.'
end