Files
2025-09-29 00:52:08 +02:00

170 lines
2.9 KiB
Ruby
Executable File

require 'mysql'
def with_db
dbh = Mysql::new('ediw-toolsb1','system','rdsgokuhero8e5rg','stockmarket')
begin
yield dbh
ensure
dbh.close
end
end
#!/usr/bin/ruby -w
# chat.rb
require 'gserver'
class StockServer < GServer
def initialize(port=20607, host=GServer::DEFAULT_HOST)
@clients = []
super(port, host, Float::MAX, $stderr, true)
end
def init_system( msg )
puts("init")
with_db do |db|
db.query('create table StockMeta (version INTEGER)')
db.query('create table StockItem (id INTEGER PRIMARY KEY, name TEXT, price INTEGER, baseprice INTEGER, soldtoday INTEGER)')
end
end
def make_safe_label( str )
str.strip!
str = str[1...(str.size - 1)]
str.strip!
"'#{str}'"
end
def get_price( msg, sock )
puts("get_price")
msgtoks = msg.split(',')
itemid = msgtoks[1]
itemssold = msgtoks[2]
msg = "/got_price, "
with_db do |db|
db.query_with_result = true
res = db.query("select * from StockItem where id = #{itemid}")
out = Array.new()
out[0] = itemid
out[1] = "test"
out[2] = 100
out[3] = 100
out[4] = 0
res.each { |x|
out[0] = x[0]
out[1] = x[1]
out[2] = x[2]
out[3] = x[3]
out[4] = x[4]
}
msg << out[2].to_s
end
puts("sending back...")
sock.print(msg)
puts(msg)
end
def make_sale( msg, sock )
puts("make_sale")
msgtoks = msg.split(',')
itemid = msgtoks[1]
itemssold = msgtoks[2]
puts("itemsold #{itemssold}")
msg = "/made_sale"
with_db do |db|
db.query_with_result = true
res = db.query("select * from StockItem where id = #{itemid}")
out = Array.new()
out[0] = itemid.to_i
out[1] = "test"
out[2] = 100
out[3] = 100
out[4] = itemssold.to_i
res.each { |x|
puts("Found existing! #{out[4]}")
out[4] = x[4].to_i + out[4]
}
query = "replace into StockItem values (#{out[0]}, \"#{out[1]}\", #{out[2]}, #{out[3]}, #{out[4]})"
puts(query)
db.query(query)
end
puts("sending back...")
sock.print(msg)
puts(msg)
end
def serve(sock)
begin
@clients << sock
hostname = sock.peeraddr[2] || sock.peeraddr[3]
until sock.eof? do
#while true do
message = sock.gets.chomp
msgtoks = message.split(',')
puts("#{msgtoks[0]}")
begin
case msgtoks[0]
when "/init" then init_system(message)
when "/make_sale" then make_sale(message, sock)
when "/get_price" then get_price(message, sock)
end
rescue
end
end
rescue
puts("there was an exception")
ensure
@clients.delete(sock)
end
end
end
server = StockServer.new(20607,"EDIW-GSMITH.rockstar.t2.corp")
server.start(-1)
server.join