require 'sinatra'
require 'mailgun'

post '/contact' do
  puts "[#{Time.now}] - REQUEST FROM: #{request.ip}\n#{request.inspect}"
  m = Mailgun::Client.new "key-18a97c4b0ceb1e2750c98efad2bb0a33"
  request_origin = request.env['HTTP_ORIGIN']
  accepted_origins = ['http://www.streamkeys.com', 'http://streamkeys.com', 'http://staging.streamkeys.com', 'http://0.0.0.0:4000', 'http://localhost:4000']

  #If the request is not coming from accepted host reject it
  unless accepted_origins.include? request_origin
    puts "BAD ORIGIN: #{request_origin}"
    halt 500
  end

  #If the request was submitted too quickly it is probably a spambot
  time_diff = Time.now.to_i - (params[:timestamp].to_i / 1000)
  unless time_diff > 4 and time_diff < 3600
    puts "TIMEOUT: #{time_diff}"
    halt 500
  end

  message = {
    :subject => 'Streamkeys contact form',
    :text => "Url: #{params[:url]}\nEmail: #{params[:email]}\nMessage: #{params[:message]}",
    :to => 'minilogo@gmail.com',
    :from => 'contact@streamkeys.com'
  }

  response.headers['Access-Control-Allow-Origin'] = request_origin
  m.send_message('streamkeys.com', message)

  halt 200
end
