# 2023-01-01 13:33 # 2023-07-24 10:41 # 2023-10-20 17:24 require 'sinatra' require 'json' require 'pg' require 'io/console' set :bind => (ENV['SERVER_BIND_ADDRESS'] or '0.0.0.0') set :port => (ENV['SERVER_BIND_PORT'] or '3333') config_file_path = (ENV['SERVER_CONFIG_PATH'] or '/data/config.json') config = JSON.parse(File.read(config_file_path)) #SECRET_TOKEN = config['secret_token'] #SECRET_USERNAME = config['secret_username'] db = PG.connect(host: config['db']['host'], dbname: config['db']['dbname'], user: config['db']['user'], password: config['db']['password']) QUERY_INSERT_SCENARIO_RECORD = <<-SQL INSERT INTO scenario_record(username, format_version, source, user_initials, total_score, final_multiplier, final_clock, enemies_killed, player_move_count, scenario_id, json_data, uploaded_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, current_timestamp) RETURNING id; SQL PREP_QUERY_INSERT_SCENARIO_RECORD = db.prepare('insert_scenario_record', QUERY_INSERT_SCENARIO_RECORD) def handle_scenario_record db, data, req_data data_parsed = JSON.parse data postulations = {:total_score => data_parsed["counts"]["score"].to_i.floor, :final_multiplier => data_parsed["counts"]["multiplier"], :final_clock => data_parsed["counts"]["clock"], :enemies_killed => data_parsed["counts"]["enemies_killed"], :player_move_count => data_parsed["counts"]["player_move_count"] } pp postulations res = db.exec_prepared('insert_scenario_record', [ req_data[:username], data_parsed['format_version'], req_data[:client_ip], data_parsed["counts"]["user_initials"], postulations[:total_score], postulations[:final_multiplier], postulations[:final_clock], postulations[:enemies_killed], postulations[:player_move_count], data_parsed["counts"]["scenario_id"], data ]) "OK" end before '/api/1/replay/scenario' do pass unless request.env['CONTENT_TYPE'] == 'application/json' if request.content_length.nil? or request.content_length == 0 then halt 200 end end #use Rack::Auth::Basic, "Protected Area" do |username, password| # username == SECRET_USERNAME && password = SECRET_TOKEN #end post '/api/1/replay/scenario' do username = request.env['HTTP_X_USERNAME'] client_ip = request.ip request.body.rewind data = request.body.read req_data = { :username => username, :client_ip => client_ip } handle_scenario_record db, data, req_data end