shop bois

This commit is contained in:
ntr
2019-07-13 18:27:38 +10:00
parent 52b1e14541
commit 2fa7310aaa
16 changed files with 210 additions and 121 deletions
+35 -31
View File
@@ -14,6 +14,7 @@ use instance::{Instance, instance_delete};
use mtx::{Mtx, FREE_MTX};
use pg::Db;
use failure::Error;
use failure::{err_msg, format_err};
@@ -23,13 +24,13 @@ static PASSWORD_MIN_LEN: usize = 11;
pub struct Account {
pub id: Uuid,
pub name: String,
pub credits: u32,
pub balance: u32,
pub subscribed: bool,
}
pub fn select(tx: &mut Transaction, id: Uuid) -> Result<Account, Error> {
let query = "
SELECT id, name, credits, subscribed
SELECT id, name, balance, subscribed
FROM accounts
WHERE id = $1;
";
@@ -40,18 +41,18 @@ pub fn select(tx: &mut Transaction, id: Uuid) -> Result<Account, Error> {
let row = result.iter().next()
.ok_or(format_err!("account not found {:?}", id))?;
let db_credits: i64 = row.get(2);
let credits = u32::try_from(db_credits)
.or(Err(format_err!("user {:?} has unparsable balance {:?}", id, db_credits)))?;
let db_balance: i64 = row.get(2);
let balance = u32::try_from(db_balance)
.or(Err(format_err!("user {:?} has unparsable balance {:?}", id, db_balance)))?;
let subscribed: bool = row.get(3);
Ok(Account { id, name: row.get(1), credits, subscribed })
Ok(Account { id, name: row.get(1), balance, subscribed })
}
pub fn from_token(db: &Db, token: String) -> Result<Account, Error> {
let query = "
SELECT id, name, subscribed, credits
SELECT id, name, subscribed, balance
FROM accounts
WHERE token = $1
AND token_expiry > now();
@@ -66,17 +67,17 @@ pub fn from_token(db: &Db, token: String) -> Result<Account, Error> {
let id: Uuid = row.get(0);
let name: String = row.get(1);
let subscribed: bool = row.get(2);
let db_credits: i64 = row.get(3);
let db_balance: i64 = row.get(3);
let credits = u32::try_from(db_credits)
.or(Err(format_err!("user {:?} has unparsable balance {:?}", id, db_credits)))?;
let balance = u32::try_from(db_balance)
.or(Err(format_err!("user {:?} has unparsable balance {:?}", id, db_balance)))?;
Ok(Account { id, name, credits, subscribed })
Ok(Account { id, name, balance, subscribed })
}
pub fn login(tx: &mut Transaction, name: &String, password: &String) -> Result<Account, Error> {
let query = "
SELECT id, password, name, credits, subscribed
SELECT id, password, name, balance, subscribed
FROM accounts
WHERE name = $1
";
@@ -102,17 +103,17 @@ pub fn login(tx: &mut Transaction, name: &String, password: &String) -> Result<A
let id: Uuid = row.get(0);
let hash: String = row.get(1);
let name: String = row.get(2);
let db_credits: i64 = row.get(3);
let db_balance: i64 = row.get(3);
let subscribed: bool = row.get(4);
if !verify(password, &hash)? {
return Err(err_msg("password does not match"));
}
let credits = u32::try_from(db_credits)
.or(Err(format_err!("user {:?} has unparsable balance {:?}", id, db_credits)))?;
let balance = u32::try_from(db_balance)
.or(Err(format_err!("user {:?} has unparsable balance {:?}", id, db_balance)))?;
Ok(Account { id, name, credits, subscribed })
Ok(Account { id, name, balance, subscribed })
}
pub fn new_token(tx: &mut Transaction, id: Uuid) -> Result<String, Error> {
@@ -133,7 +134,7 @@ pub fn new_token(tx: &mut Transaction, id: Uuid) -> Result<String, Error> {
let result = tx
.query(query, &[&token, &id])?;
let row = result.iter().next()
result.iter().next()
.ok_or(format_err!("account not updated {:?}", id))?;
Ok(token)
@@ -142,9 +143,9 @@ pub fn new_token(tx: &mut Transaction, id: Uuid) -> Result<String, Error> {
pub fn credit(tx: &mut Transaction, id: Uuid, credits: i64) -> Result<String, Error> {
let query = "
UPDATE accounts
SET credits = credits + $1
SET balance = balance + $1
WHERE id = $2
RETURNING credits, name;
RETURNING balance, name;
";
let result = tx
@@ -153,38 +154,41 @@ pub fn credit(tx: &mut Transaction, id: Uuid, credits: i64) -> Result<String, Er
let row = result.iter().next()
.ok_or(format_err!("account not updated {:?}", id))?;
let db_credits: i64 = row.get(0);
let total = u32::try_from(db_credits)
.or(Err(format_err!("user {:?} has unparsable balance {:?}", id, db_credits)))?;
let db_balance: i64 = row.get(0);
let balance = u32::try_from(db_balance)
.or(Err(format_err!("user {:?} has unparsable balance {:?}", id, db_balance)))?;
let name: String = row.get(1);
info!("account credited name={:?} credited={:?} total={:?}", name, credits, total);
info!("account credited name={:?} credited={:?} balance={:?}", name, credits, balance);
Ok(name)
}
pub fn debit(tx: &mut Transaction, id: Uuid, credits: i64) -> Result<Account, Error> {
pub fn debit(tx: &mut Transaction, id: Uuid, debit: i64) -> Result<Account, Error> {
let query = "
UPDATE accounts
SET credits = credits - $1
SET balance = balance - $1
WHERE id = $2
RETURNING id, name, credits, subscribed
RETURNING id, name, balance, subscribed
";
let result = tx
.query(query, &[&credits, &id])?;
.query(query, &[&debit, &id])?;
let row = result.iter().next()
.ok_or(format_err!("account not found {:?}", id))?;
let db_credits: i64 = row.get(2);
let credits = u32::try_from(db_credits)
.or(Err(format_err!("user {:?} has unparsable balance {:?}", id, db_credits)))?;
let name: String = row.get(1);
let db_balance: i64 = row.get(2);
let balance = u32::try_from(db_balance)
.or(Err(format_err!("user {:?} has unparsable balance {:?}", id, db_balance)))?;
let subscribed: bool = row.get(3);
Ok(Account { id, name: row.get(1), credits, subscribed })
info!("account debited name={:?} debited={:?} balance={:?}", name, debit, balance);
Ok(Account { id, name: row.get(1), balance, subscribed })
}
pub fn set_subscribed(tx: &mut Transaction, id: Uuid, subscribed: bool) -> Result<String, Error> {
+2 -2
View File
@@ -11,7 +11,7 @@ use skill::{Skill, Cast, Immunity, Disable, Event};
use effect::{Cooldown, Effect, Colour};
use spec::{Spec};
use item::{Item};
use img::{img_molecular_write};
use img;
#[derive(Debug,Clone,Serialize,Deserialize)]
pub struct Colours {
@@ -883,7 +883,7 @@ pub fn construct_spawn(tx: &mut Transaction, account: Uuid, name: String) -> Res
let _returned = result.iter().next().ok_or(err_msg("no row returned"))?;
img_molecular_write(construct.img)?;
img::molecular_write(construct.img)?;
info!("spawned construct account={:} construct={:?}", account, construct);
return Ok(construct);
+12 -14
View File
@@ -9,7 +9,7 @@ use std::io::prelude::*;
use failure::Error;
use failure::err_msg;
pub fn img_molecular_write(id: Uuid) -> Result<Uuid, Error> {
pub fn molecular_write(id: Uuid) -> Result<Uuid, Error> {
let mut rng = thread_rng();
for _i in 0..100 {
@@ -27,9 +27,7 @@ pub fn img_molecular_write(id: Uuid) -> Result<Uuid, Error> {
return Err(err_msg("too many missing molecules. wrong directory?"))
}
fn invader_img_write(id: Uuid) -> Result<Uuid, Error> {
pub fn invader_write(id: Uuid) -> Result<Uuid, Error> {
let mut rng = thread_rng();
let mut svg = Vec::new();
@@ -86,17 +84,17 @@ fn invader_img_write(id: Uuid) -> Result<Uuid, Error> {
}
#[cfg(test)]
mod tests {
use super::*;
// #[cfg(test)]
// mod tests {
// use super::*;
#[test]
fn invader_img_test() {
for i in 0..100 {
invader_img_write(Uuid::new_v4()).unwrap();
}
}
}
// #[test]
// fn invader_img_test() {
// for i in 0..100 {
// invader_img_write(Uuid::new_v4()).unwrap();
// }
// }
// }
+2 -3
View File
@@ -18,8 +18,7 @@ use mob::{bot_player, instance_mobs};
use game::{Game, Phase, game_get, game_write};
use item::{Item};
use rpc::{RpcResult};
use img::{img_molecular_write};
use img;
#[derive(Debug,Clone,Copy,PartialEq,Serialize,Deserialize)]
enum InstancePhase {
@@ -706,7 +705,7 @@ pub fn instance_new(tx: &mut Transaction, account: &Account, construct_ids: Vec<
// generate bot imgs only in the real world
for c in bot.constructs.iter() {
img_molecular_write(c.img)?;
img::molecular_write(c.img)?;
}
let mut instance = Instance::new()
+80 -47
View File
@@ -2,7 +2,6 @@ use std::convert::TryFrom;
use uuid::Uuid;
// use rand::prelude::*;
use serde_cbor::{from_slice};
use postgres::transaction::Transaction;
use failure::Error;
@@ -12,17 +11,32 @@ use account;
use account::Account;
use construct::{Construct, construct_select, construct_write};
use img::{img_molecular_write};
use img;
pub const FREE_MTX: [MtxVariant; 2] = [
pub const FREE_MTX: [MtxVariant; 1] = [
MtxVariant::Rename,
MtxVariant::Reimage,
];
#[derive(Debug,Copy,Clone,Serialize,Deserialize)]
pub const SHOP_LISTINGS: [Listing; 2] = [
Listing { variant: MtxVariant::ArchitectureMolecular, credits: 10 },
Listing { variant: MtxVariant::ArchitectureInvader, credits: 10 },
];
#[derive(Debug,Clone,PartialEq,Serialize,Deserialize)]
pub struct Shop {
owned: Vec<MtxVariant>,
available: Vec<Listing>,
}
#[derive(Debug,Copy,Clone,PartialEq,Serialize,Deserialize)]
pub struct Listing {
variant: MtxVariant,
credits: u16,
}
#[derive(Debug,Copy,Clone,PartialEq,Serialize,Deserialize)]
pub enum MtxVariant {
Rename,
Reimage,
ArchitectureMolecular,
ArchitectureInvader,
}
@@ -40,7 +54,6 @@ impl TryFrom<String> for MtxVariant {
fn try_from(v: String) -> Result<MtxVariant, Error> {
match v.as_ref() {
"Rename" => Ok(MtxVariant::Rename),
"Reimage" => Ok(MtxVariant::Reimage),
"ArchitectureMolecular" => Ok(MtxVariant::ArchitectureMolecular),
"ArchitectureInvader" => Ok(MtxVariant::ArchitectureInvader),
_ => Err(format_err!("mtx variant not found variant={:?}", v)),
@@ -57,25 +70,20 @@ pub struct Mtx {
pub fn apply(tx: &mut Transaction, account: &Account, variant: MtxVariant, construct_id: Uuid) -> Result<Vec<Construct>, Error> {
let mtx = select(tx, variant, account.id)?;
let construct = construct_select(tx, construct_id, account.id)?;
match mtx.variant {
MtxVariant::Reimage => reimage(tx, construct)?,
_ => unimplemented!(),
};
let mut construct = construct_select(tx, construct_id, account.id)?;
account::debit(tx, account.id, 1)?;
account::account_constructs(tx, account)
}
pub fn reimage(tx: &mut Transaction, mut construct: Construct) -> Result<Construct, Error> {
construct = construct.new_img();
match mtx.variant {
MtxVariant::ArchitectureInvader => img::invader_write(construct.img)?,
MtxVariant::ArchitectureMolecular => img::molecular_write(construct.img)?,
MtxVariant::Rename => unimplemented!(),
// _ => unimplemented!(),
};
img_molecular_write(construct.img)?;
construct = construct_write(tx, construct)?;
Ok(construct)
construct_write(tx, construct)?;
account::account_constructs(tx, account)
}
pub fn select(tx: &mut Transaction, variant: MtxVariant, account: Uuid) -> Result<Mtx, Error> {
@@ -111,32 +119,6 @@ impl Mtx {
}
}
pub fn account_list(tx: &mut Transaction, account: Uuid) -> Result<Vec<Mtx>, Error> {
let query = "
SELECT data, id
FROM mtx
WHERE account = $1;
";
let result = tx
.query(query, &[&account])?;
let values = result.into_iter().filter_map(|row| {
let bytes: Vec<u8> = row.get(0);
// let id: Uuid = row.get(1);
match from_slice::<Mtx>(&bytes) {
Ok(i) => Some(i),
Err(e) => {
warn!("{:?}", e);
None
}
}
}).collect::<Vec<Mtx>>();
return Ok(values);
}
pub fn delete(tx: &mut Transaction, id: Uuid) -> Result<(), Error> {
let query = "
DELETE
@@ -193,3 +175,54 @@ impl Mtx {
// return Ok(self);
// }
}
pub fn account_shop(tx: &mut Transaction, account: &Account) -> Result<Shop, Error> {
let query = "
SELECT variant
FROM mtx
WHERE account = $1;
";
let result = tx
.query(query, &[&account.id])?;
let mut owned = vec![];
for row in result.iter() {
let v_str: String = row.get(0);
let variant = match MtxVariant::try_from(v_str) {
Ok(v) => v,
Err(e) => {
warn!("{:?}", e);
continue;
},
};
owned.push(variant);
};
let available = SHOP_LISTINGS.iter()
.filter(|l| !owned.contains(&l.variant))
.map(|l| *l)
.collect::<Vec<Listing>>();
debug!("account shop acount={:?} owned={:?} available={:?}",
account.name, owned, available);
return Ok(Shop { owned, available });
}
pub fn buy(tx: &mut Transaction, account: &Account, mtx: MtxVariant) -> Result<Shop, Error> {
let listing = SHOP_LISTINGS
.iter()
.find(|l| l.variant == mtx)
.ok_or(format_err!("mtx variant not found variant={:?}", mtx))?;
let account = account::debit(tx, account.id, listing.credits as i64)?;
Mtx::new(mtx, account.id)
.insert(tx)?;
info!("account purchased mtx account={:?} mtx={:?} cost={:?} balance={:?}",
account.name, mtx, listing.credits, account.balance);
account_shop(tx, &account)
}
+12 -1
View File
@@ -24,6 +24,7 @@ pub enum RpcResult {
AccountState(Account),
AccountConstructs(Vec<Construct>),
AccountInstances(Vec<Instance>),
AccountShop(mtx::Shop),
GameState(Game),
ItemInfo(ItemInfoCtr),
@@ -43,12 +44,14 @@ enum RpcRequest {
MtxConstructApply { mtx: mtx::MtxVariant, construct_id: Uuid },
MtxAccountApply { mtx: mtx::MtxVariant },
MtxBuy { mtx: mtx::MtxVariant },
GameState { id: Uuid },
GameReady { id: Uuid },
GameSkill { game_id: Uuid, construct_id: Uuid, target_construct_id: Option<Uuid>, skill: Skill },
AccountState {},
AccountShop {},
AccountConstructs {},
AccountInstances {},
@@ -100,6 +103,10 @@ pub fn receive(data: Vec<u8>, db: &Db, _client: &mut WebSocket<TcpStream>, begin
RpcRequest::AccountInstances {} =>
Ok(RpcResult::AccountInstances(account_instances(&mut tx, &account)?)),
// RpcRequest::AccountShop {} =>
// Ok(RpcResult::AccountShop(mtx::account_shop(&mut tx, &account)?)),
// RpcRequest::ConstructDelete" => handle_construct_delete(data, &mut tx, account),
@@ -145,6 +152,9 @@ pub fn receive(data: Vec<u8>, db: &Db, _client: &mut WebSocket<TcpStream>, begin
RpcRequest::MtxConstructApply { mtx, construct_id } =>
Ok(RpcResult::AccountConstructs(mtx::apply(&mut tx, account, mtx, construct_id)?)),
RpcRequest::MtxBuy { mtx } =>
Ok(RpcResult::AccountShop(mtx::buy(&mut tx, account, mtx)?)),
_ => Err(format_err!("unknown request request={:?}", request)),
};
@@ -155,7 +165,8 @@ pub fn receive(data: Vec<u8>, db: &Db, _client: &mut WebSocket<TcpStream>, begin
return response;
},
Err(e) => {
Err(format_err!("invalid message data={:?}", data))
warn!("{:?}", e);
Err(err_msg("invalid message"))
},
}
}
+13
View File
@@ -19,6 +19,7 @@ use serde_cbor::{to_vec};
use net::TOKEN_HEADER;
use rpc;
use mtx;
use pg::PgPool;
use account;
@@ -66,10 +67,22 @@ pub fn start(pool: PgPool) {
Some(t) => {
let db = ws_pool.get()
.expect("unable to get db connection");
match account::from_token(&db, t) {
Ok(a) => {
let state = to_vec(&rpc::RpcResult::AccountState(a.clone())).unwrap();
websocket.write_message(Binary(state)).unwrap();
let mut tx = db.transaction().unwrap();
let shop = mtx::account_shop(&mut tx, &a).unwrap();
let shop = to_vec(&rpc::RpcResult::AccountShop(shop)).unwrap();
websocket.write_message(Binary(shop)).unwrap();
// tx doesn't change anything
tx.commit().unwrap();
Some(a)
},
Err(e) => {