Compare commits
4 Commits
2c87713818
...
keep_track
| Author | SHA1 | Date | |
|---|---|---|---|
| d152a999c9 | |||
| f9cd09431d | |||
| 6149dfd297 | |||
| a47646bd5f |
@@ -1,3 +1,2 @@
|
|||||||
DROP TABLE items;
|
DROP TABLE items;
|
||||||
DROP TABLE looted;
|
DROP TABLE loot;
|
||||||
DROP TABLE shop;
|
|
||||||
|
|||||||
@@ -5,8 +5,8 @@ CREATE TABLE items (
|
|||||||
base_price INTEGER NOT NULL
|
base_price INTEGER NOT NULL
|
||||||
);
|
);
|
||||||
|
|
||||||
-- The items that have been looted
|
-- The loot
|
||||||
CREATE TABLE looted (
|
CREATE TABLE loot (
|
||||||
id INTEGER PRIMARY KEY NOT NULL,
|
id INTEGER PRIMARY KEY NOT NULL,
|
||||||
name VARCHAR NOT NULL,
|
name VARCHAR NOT NULL,
|
||||||
base_price INTEGER NOT NULL,
|
base_price INTEGER NOT NULL,
|
||||||
@@ -14,9 +14,3 @@ CREATE TABLE looted (
|
|||||||
FOREIGN KEY (owner_id) REFERENCES players(id)
|
FOREIGN KEY (owner_id) REFERENCES players(id)
|
||||||
);
|
);
|
||||||
|
|
||||||
-- The items that are available in shop
|
|
||||||
CREATE TABLE shop (
|
|
||||||
id INTEGER PRIMARY KEY NOT NULL,
|
|
||||||
name VARCHAR NOT NULL,
|
|
||||||
base_price INTEGER NOT NULL
|
|
||||||
);
|
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ pub type DbConnection = SqliteConnection;
|
|||||||
pub type Pool = r2d2::Pool<ConnectionManager<DbConnection>>;
|
pub type Pool = r2d2::Pool<ConnectionManager<DbConnection>>;
|
||||||
/// The result of a query on DB
|
/// The result of a query on DB
|
||||||
pub type QueryResult<T> = Result<T, diesel::result::Error>;
|
pub type QueryResult<T> = Result<T, diesel::result::Error>;
|
||||||
pub type UpdateResult = QueryResult<Update>;
|
pub type UpdateResult = QueryResult<Vec<Update>>;
|
||||||
|
|
||||||
/// Sets up a connection pool and returns it.
|
/// Sets up a connection pool and returns it.
|
||||||
/// Uses the DATABASE_URL environment variable (must be set)
|
/// Uses the DATABASE_URL environment variable (must be set)
|
||||||
@@ -43,36 +43,36 @@ pub fn create_pool() -> Pool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Every possible update which can happen during a query
|
/// Every possible update which can happen during a query
|
||||||
|
/// Updates are relative to a Player
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
pub enum Update {
|
pub enum Update {
|
||||||
Wealth(Wealth),
|
Wealth(Wealth),
|
||||||
ItemAdded(Item),
|
ItemAdded(Item),
|
||||||
ItemRemoved(Item),
|
ItemRemoved(Item),
|
||||||
|
ItemBought(Item),
|
||||||
|
ItemSold(Item),
|
||||||
ClaimAdded(Claim),
|
ClaimAdded(Claim),
|
||||||
ClaimRemoved(Claim),
|
ClaimRemoved(Claim),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Update {
|
impl Update {
|
||||||
/// Change back what has been updated
|
/// Change back what has been updated
|
||||||
fn undo(&self, conn: &DbConnection, id: i32) -> UpdateResult {
|
fn undo(&self, conn: &DbConnection, id: i32) -> QueryResult<()> {
|
||||||
Ok(match self {
|
match self {
|
||||||
Update::Wealth(diff) => AsPlayer(conn, id).update_wealth(-diff.to_gp())?,
|
Update::Wealth(diff) => { AsPlayer(conn, id).update_wealth(-diff.to_gp())?; },
|
||||||
Update::ItemAdded(item) => LootManager(conn, id).find(item.id)?.remove(conn)?,
|
Update::ItemAdded(item) => { diesel::delete(crate::schema::loot::table.find(item.id))
|
||||||
Update::ItemRemoved(item) => LootManager(conn, id).add_from(&item)?,
|
.execute(conn)?; },
|
||||||
|
Update::ItemRemoved(item) => { LootManager(conn, id).add_from(&item)?; },
|
||||||
|
Update::ItemBought(item) => { LootManager(conn, id).change_owner(item.id, models::item::OF_SHOP)?;},
|
||||||
|
Update::ItemSold(item) => { LootManager(conn, models::item::SOLD).change_owner(item.id, id)?; },
|
||||||
// Unused for now
|
// Unused for now
|
||||||
Update::ClaimAdded(claim) => Update::ClaimRemoved(*claim),
|
Update::ClaimAdded(claim) => {},
|
||||||
Update::ClaimRemoved(claim) => Update::ClaimAdded(*claim),
|
Update::ClaimRemoved(claim) => {},
|
||||||
})
|
};
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// TODO: use this to wrap update in UpdateResult, allowing unified interface
|
|
||||||
/// whether a query makes multiple updates or just one.
|
|
||||||
enum OneOrMore {
|
|
||||||
One(Update),
|
|
||||||
More(Vec<Update>),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every value which can be queried
|
/// Every value which can be queried
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum Value {
|
pub enum Value {
|
||||||
@@ -99,82 +99,6 @@ impl serde::Serialize for Value {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sells a single item inside a transaction
|
|
||||||
///
|
|
||||||
/// # Returns
|
|
||||||
/// The deleted entity and the updated Wealth (as a difference from previous value)
|
|
||||||
pub fn sell_item_transaction(
|
|
||||||
conn: &DbConnection,
|
|
||||||
id: i32,
|
|
||||||
loot_id: i32,
|
|
||||||
price_mod: Option<f64>,
|
|
||||||
) -> QueryResult<(Update, Wealth)> {
|
|
||||||
conn.transaction(|| {
|
|
||||||
let to_delete = LootManager(conn, id).find(loot_id)?;
|
|
||||||
let mut sell_value = to_delete.sell_value() as f64;
|
|
||||||
if let Some(modifier) = price_mod {
|
|
||||||
sell_value *= modifier;
|
|
||||||
}
|
|
||||||
let deleted = to_delete.remove(conn)?;
|
|
||||||
if let Update::Wealth(wealth) = AsPlayer(conn, id).update_wealth(sell_value)? {
|
|
||||||
Ok((deleted, wealth))
|
|
||||||
} else {
|
|
||||||
Err(diesel::result::Error::RollbackTransaction)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Buys a single item, copied from inventory.
|
|
||||||
/// Runs inside a transaction
|
|
||||||
///
|
|
||||||
/// # Returns
|
|
||||||
/// The created entity and the updated Wealth (as a difference from previous value)
|
|
||||||
pub fn buy_item_from_inventory(
|
|
||||||
conn: &DbConnection,
|
|
||||||
id: i32,
|
|
||||||
item_id: i32,
|
|
||||||
price_mod: Option<f64>,
|
|
||||||
) -> QueryResult<(Update, Wealth)> {
|
|
||||||
conn.transaction(|| {
|
|
||||||
// Find item in inventory
|
|
||||||
let item = Inventory(conn).find(item_id)?;
|
|
||||||
let new_item = LootManager(conn, id).add_from(&item)?;
|
|
||||||
let sell_price = match price_mod {
|
|
||||||
Some(modifier) => item.value() * modifier,
|
|
||||||
None => item.value(),
|
|
||||||
};
|
|
||||||
if let Update::Wealth(diff) = AsPlayer(conn, id).update_wealth(-sell_price)? {
|
|
||||||
Ok((new_item, diff))
|
|
||||||
} else {
|
|
||||||
Err(diesel::result::Error::RollbackTransaction)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn buy_item_from_shop(
|
|
||||||
conn: &DbConnection,
|
|
||||||
id: i32,
|
|
||||||
item_id: i32,
|
|
||||||
price_mod: Option<f64>,
|
|
||||||
) -> QueryResult<(Update, Wealth)> {
|
|
||||||
conn.transaction(|| {
|
|
||||||
let shop = Shop(conn);
|
|
||||||
// Find item in inventory
|
|
||||||
let item = shop.get(item_id)?;
|
|
||||||
let new_item = LootManager(conn, id).add_from(&item)?;
|
|
||||||
let _deleted = shop.remove(item_id)?;
|
|
||||||
let sell_price = match price_mod {
|
|
||||||
Some(modifier) => item.value() * modifier,
|
|
||||||
None => item.value(),
|
|
||||||
};
|
|
||||||
if let Update::Wealth(diff) = AsPlayer(conn, id).update_wealth(-sell_price)? {
|
|
||||||
Ok((new_item, diff))
|
|
||||||
} else {
|
|
||||||
Err(diesel::result::Error::RollbackTransaction)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/// Resolve all pending claims and dispatch claimed items.
|
/// Resolve all pending claims and dispatch claimed items.
|
||||||
///
|
///
|
||||||
@@ -239,234 +163,6 @@ pub fn split_and_share(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(Update::Wealth(Wealth::from_gp(shared_total)))
|
Ok(vec!(Update::Wealth(Wealth::from_gp(shared_total))))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(none)]
|
|
||||||
mod tests_old {
|
|
||||||
use super::*;
|
|
||||||
type TestConnection = DbConnection;
|
|
||||||
|
|
||||||
/// Return a connection to a fresh database (stored in memory)
|
|
||||||
fn test_connection() -> TestConnection {
|
|
||||||
let test_conn = DbConnection::establish(":memory:").unwrap();
|
|
||||||
diesel_migrations::run_pending_migrations(&test_conn).unwrap();
|
|
||||||
test_conn
|
|
||||||
}
|
|
||||||
|
|
||||||
/// When migrations are run, a special player with id 0 and name "Groupe"
|
|
||||||
/// must be created.
|
|
||||||
#[test]
|
|
||||||
fn global_group_is_autocreated() {
|
|
||||||
let conn = test_connection();
|
|
||||||
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
|
||||||
assert_eq!(players.len(), 1);
|
|
||||||
let group = players.get(0).unwrap();
|
|
||||||
assert_eq!(group.id, 0);
|
|
||||||
assert_eq!(group.name, "Groupe".to_string());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// When a player updates wealth, a difference is returned by API.
|
|
||||||
/// Added to the previous amount of coins, it should equal the updated weath.
|
|
||||||
#[test]
|
|
||||||
fn as_player_updates_wealth() {
|
|
||||||
let conn = test_connection();
|
|
||||||
DbApi::with_conn(&conn)
|
|
||||||
.as_admin()
|
|
||||||
.add_player("PlayerName", 403.21)
|
|
||||||
.unwrap();
|
|
||||||
let diff = DbApi::with_conn(&conn)
|
|
||||||
.as_player(1)
|
|
||||||
.update_wealth(-401.21)
|
|
||||||
.ok();
|
|
||||||
// Check the returned diff
|
|
||||||
assert_eq!(diff, Some((-1, -2, -1, -4)));
|
|
||||||
let diff = diff.unwrap();
|
|
||||||
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
|
||||||
let player = players.get(1).unwrap();
|
|
||||||
// Check that we can add old value to return diff to get resulting value
|
|
||||||
assert_eq!(
|
|
||||||
(player.cp, player.sp, player.gp, player.pp),
|
|
||||||
(1 + diff.0, 2 + diff.1, 3 + diff.2, 4 + diff.3)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn as_admin_add_player() {
|
|
||||||
let conn = test_connection();
|
|
||||||
let result = DbApi::with_conn(&conn)
|
|
||||||
.as_admin()
|
|
||||||
.add_player("PlayerName", 403.21);
|
|
||||||
assert_eq!(result.is_ok(), true);
|
|
||||||
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
|
||||||
assert_eq!(players.len(), 2);
|
|
||||||
let new_player = players.get(1).unwrap();
|
|
||||||
assert_eq!(new_player.name, "PlayerName");
|
|
||||||
assert_eq!(
|
|
||||||
(new_player.cp, new_player.sp, new_player.gp, new_player.pp),
|
|
||||||
(1, 2, 3, 4)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn as_admin_resolve_claims() {
|
|
||||||
let conn = test_connection();
|
|
||||||
let claims = DbApi::with_conn(&conn).fetch_claims().unwrap();
|
|
||||||
assert_eq!(claims.len(), 0);
|
|
||||||
|
|
||||||
// Add items
|
|
||||||
assert_eq!(
|
|
||||||
DbApi::with_conn(&conn)
|
|
||||||
.as_admin()
|
|
||||||
.add_loot(vec![("Épée", 40), ("Arc", 40),])
|
|
||||||
.is_ok(),
|
|
||||||
true
|
|
||||||
);
|
|
||||||
// Add players
|
|
||||||
DbApi::with_conn(&conn)
|
|
||||||
.as_admin()
|
|
||||||
.add_player("Player1", 0.0)
|
|
||||||
.unwrap();
|
|
||||||
DbApi::with_conn(&conn)
|
|
||||||
.as_admin()
|
|
||||||
.add_player("Player2", 0.0)
|
|
||||||
.unwrap();
|
|
||||||
// Put claims on one different item each
|
|
||||||
DbApi::with_conn(&conn).as_player(1).claim(1).unwrap();
|
|
||||||
DbApi::with_conn(&conn).as_player(2).claim(2).unwrap();
|
|
||||||
let result = DbApi::with_conn(&conn).as_admin().resolve_claims();
|
|
||||||
assert_eq!(result.is_ok(), true);
|
|
||||||
// Check that both players received an item
|
|
||||||
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
|
||||||
for &i in [1, 2].into_iter() {
|
|
||||||
assert_eq!(
|
|
||||||
DbApi::with_conn(&conn).as_player(i).loot().unwrap().len(),
|
|
||||||
1
|
|
||||||
);
|
|
||||||
let player = players.get(i as usize).unwrap();
|
|
||||||
assert_eq!(player.debt, 20);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn as_player_claim_item() {
|
|
||||||
let conn = test_connection();
|
|
||||||
DbApi::with_conn(&conn)
|
|
||||||
.as_admin()
|
|
||||||
.add_player("Player", 0.0)
|
|
||||||
.unwrap();
|
|
||||||
DbApi::with_conn(&conn)
|
|
||||||
.as_admin()
|
|
||||||
.add_loot(vec![("Épée", 25)])
|
|
||||||
.unwrap();
|
|
||||||
// Claim an existing item
|
|
||||||
let result = DbApi::with_conn(&conn).as_player(1).claim(1);
|
|
||||||
assert_eq!(result.is_ok(), true);
|
|
||||||
let claims = DbApi::with_conn(&conn).fetch_claims().unwrap();
|
|
||||||
assert_eq!(claims.len(), 1);
|
|
||||||
let claim = claims.get(0).unwrap();
|
|
||||||
assert_eq!(claim.player_id, 1);
|
|
||||||
assert_eq!(claim.loot_id, 1);
|
|
||||||
// Claim an inexistant item
|
|
||||||
let result = DbApi::with_conn(&conn).as_player(1).claim(2);
|
|
||||||
assert_eq!(result.is_ok(), false);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn as_player_unclaim_item() {
|
|
||||||
let conn = test_connection();
|
|
||||||
DbApi::with_conn(&conn)
|
|
||||||
.as_admin()
|
|
||||||
.add_player("Player", 0.0)
|
|
||||||
.unwrap();
|
|
||||||
DbApi::with_conn(&conn)
|
|
||||||
.as_admin()
|
|
||||||
.add_loot(vec![("Épée", 25)])
|
|
||||||
.unwrap();
|
|
||||||
// Claim an existing item
|
|
||||||
let result = DbApi::with_conn(&conn).as_player(1).claim(1);
|
|
||||||
assert_eq!(result.is_ok(), true);
|
|
||||||
// Claiming twice is an error
|
|
||||||
let result = DbApi::with_conn(&conn).as_player(1).claim(1);
|
|
||||||
assert_eq!(result.is_ok(), false);
|
|
||||||
// Unclaiming and item
|
|
||||||
let result = DbApi::with_conn(&conn).as_player(1).unclaim(1);
|
|
||||||
assert_eq!(result.is_ok(), true);
|
|
||||||
// Check that not claimed items will not be unclaimed...
|
|
||||||
let result = DbApi::with_conn(&conn).as_player(1).unclaim(1);
|
|
||||||
assert_eq!(result.is_ok(), false);
|
|
||||||
let claims = DbApi::with_conn(&conn).fetch_claims().unwrap();
|
|
||||||
assert_eq!(claims.len(), 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// All-in-one checks one a simple buy/sell procedure
|
|
||||||
///
|
|
||||||
/// Checks that player's chest and wealth are updated.
|
|
||||||
/// Checks that items are sold at half their value.
|
|
||||||
/// Checks that a player cannot sell item he does not own.
|
|
||||||
#[test]
|
|
||||||
fn as_player_simple_buy_sell() {
|
|
||||||
let conn = test_connection();
|
|
||||||
// Adds a sword into inventory
|
|
||||||
{
|
|
||||||
use schema::items::dsl::*;
|
|
||||||
diesel::insert_into(items)
|
|
||||||
.values((name.eq("Sword"), base_price.eq(800)))
|
|
||||||
.execute(&conn)
|
|
||||||
.expect("Could not set up items table");
|
|
||||||
}
|
|
||||||
DbApi::with_conn(&conn)
|
|
||||||
.as_admin()
|
|
||||||
.add_player("Player", 1000.0)
|
|
||||||
.unwrap();
|
|
||||||
// Buy an item
|
|
||||||
let bought = DbApi::with_conn(&conn).as_player(1).buy(&vec![(1, None)]);
|
|
||||||
assert_eq!(bought.ok(), Some((0, 0, 0, -8))); // Returns diff of player wealth ?
|
|
||||||
let chest = DbApi::with_conn(&conn).as_player(1).loot().unwrap();
|
|
||||||
assert_eq!(chest.len(), 1);
|
|
||||||
let loot = chest.get(0).unwrap();
|
|
||||||
assert_eq!(loot.name, "Sword");
|
|
||||||
assert_eq!(loot.base_price, 800);
|
|
||||||
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
|
||||||
let player = players.get(1).unwrap();
|
|
||||||
assert_eq!(player.pp, 2);
|
|
||||||
// A player cannot sell loot from an other's chest
|
|
||||||
let result = DbApi::with_conn(&conn)
|
|
||||||
.as_player(0)
|
|
||||||
.sell(&vec![(loot.id, None)]);
|
|
||||||
assert_eq!(result.is_ok(), false);
|
|
||||||
// Sell back
|
|
||||||
let sold = DbApi::with_conn(&conn)
|
|
||||||
.as_player(1)
|
|
||||||
.sell(&vec![(loot.id, None)]);
|
|
||||||
assert_eq!(sold.ok(), Some((0, 0, 0, 4)));
|
|
||||||
let chest = DbApi::with_conn(&conn).as_player(1).loot().unwrap();
|
|
||||||
assert_eq!(chest.len(), 0);
|
|
||||||
let players = DbApi::with_conn(&conn).fetch_players().unwrap();
|
|
||||||
let player = players.get(1).unwrap();
|
|
||||||
assert_eq!(player.pp, 6);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn as_admin_add_loot() {
|
|
||||||
let conn = test_connection();
|
|
||||||
assert_eq!(
|
|
||||||
0,
|
|
||||||
DbApi::with_conn(&conn).as_player(0).loot().unwrap().len()
|
|
||||||
);
|
|
||||||
let loot_to_add = vec![("Cape d'invisibilité", 8000), ("Arc long", 25)];
|
|
||||||
let result = DbApi::with_conn(&conn)
|
|
||||||
.as_admin()
|
|
||||||
.add_loot(loot_to_add.clone());
|
|
||||||
assert_eq!(result.is_ok(), true);
|
|
||||||
let looted = DbApi::with_conn(&conn).as_player(0).loot().unwrap();
|
|
||||||
assert_eq!(looted.len(), 2);
|
|
||||||
// NB: Not a problem now, but this adds constraints of items being
|
|
||||||
// created in the same order.
|
|
||||||
for (added, to_add) in looted.into_iter().zip(loot_to_add) {
|
|
||||||
assert_eq!(added.name, to_add.0);
|
|
||||||
assert_eq!(added.base_price, to_add.1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -73,22 +73,22 @@ impl<'q> Claims<'q> {
|
|||||||
.values(&claim)
|
.values(&claim)
|
||||||
.execute(self.0)?;
|
.execute(self.0)?;
|
||||||
// Return the created claim
|
// Return the created claim
|
||||||
Ok(
|
Ok(vec!(
|
||||||
Update::ClaimAdded(
|
Update::ClaimAdded(
|
||||||
claims::table
|
claims::table
|
||||||
.order(claims::dsl::id.desc())
|
.order(claims::dsl::id.desc())
|
||||||
.first::<Claim>(self.0)?
|
.first::<Claim>(self.0)?
|
||||||
)
|
)
|
||||||
)
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Removes a claim from database, returning it
|
/// Removes a claim from database, returning it
|
||||||
pub fn remove(self, player_id: i32, loot_id: i32) -> UpdateResult {
|
pub fn remove(self, player_id: i32, loot_id: i32) -> UpdateResult {
|
||||||
let claim = self.find(player_id, loot_id)?;
|
let claim = self.find(player_id, loot_id)?;
|
||||||
claim.remove(self.0)?;
|
claim.remove(self.0)?;
|
||||||
Ok(
|
Ok(vec!(
|
||||||
Update::ClaimRemoved(claim)
|
Update::ClaimRemoved(claim)
|
||||||
)
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn filtered_by_loot(&self, loot_id: i32) -> QueryResult<Vec<Claim>> {
|
pub fn filtered_by_loot(&self, loot_id: i32) -> QueryResult<Vec<Claim>> {
|
||||||
|
|||||||
@@ -39,18 +39,14 @@ impl Event {
|
|||||||
|
|
||||||
/// TODO: why a move here ??
|
/// TODO: why a move here ??
|
||||||
/// Undo all updates in a single transaction
|
/// Undo all updates in a single transaction
|
||||||
pub fn undo(self, conn: &DbConnection) -> QueryResult<UpdateList> {
|
pub fn undo(self, conn: &DbConnection) -> QueryResult<()> {
|
||||||
conn.transaction(move || {
|
conn.transaction(move || {
|
||||||
if let Some(ref updates) = self.updates {
|
if let Some(ref updates) = self.updates {
|
||||||
let undone = updates.0.iter()
|
for update in updates.inner() {
|
||||||
// TODO: swallow errors !
|
update.undo(conn, self.player_id)?;
|
||||||
.filter_map(|u| u.undo(conn, self.player_id).ok())
|
}
|
||||||
.collect();
|
|
||||||
diesel::delete(history::table.find(self.id)).execute(conn)?;
|
|
||||||
Ok(UpdateList(undone))
|
|
||||||
} else {
|
|
||||||
Ok(UpdateList(vec![]))
|
|
||||||
}
|
}
|
||||||
|
Ok(())
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,10 +2,10 @@ use diesel::dsl::{exists, Eq, Filter, Find, Select};
|
|||||||
use diesel::expression::exists::Exists;
|
use diesel::expression::exists::Exists;
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
|
|
||||||
use crate::schema::{items, looted, shop};
|
use crate::schema::{items, loot};
|
||||||
use crate::{DbConnection, QueryResult, Update, UpdateResult, Claims };
|
use crate::{Claims, DbConnection, QueryResult, Update, UpdateResult};
|
||||||
type ItemColumns = (looted::id, looted::name, looted::base_price);
|
type ItemColumns = (loot::id, loot::name, loot::base_price);
|
||||||
const ITEM_COLUMNS: ItemColumns = (looted::id, looted::name, looted::base_price);
|
const ITEM_COLUMNS: ItemColumns = (loot::id, loot::name, loot::base_price);
|
||||||
type OwnedBy = Select<OwnedLoot, ItemColumns>;
|
type OwnedBy = Select<OwnedLoot, ItemColumns>;
|
||||||
|
|
||||||
/// Represents a basic item
|
/// Represents a basic item
|
||||||
@@ -27,23 +27,58 @@ impl Item {
|
|||||||
self.base_price as f64 / 2.0
|
self.base_price as f64 / 2.0
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn remove(self, conn: &DbConnection) -> UpdateResult {
|
|
||||||
conn.transaction(
|
|
||||||
|| -> UpdateResult
|
|
||||||
{
|
|
||||||
Claims(conn).delete_for_loot(self.id)?;
|
|
||||||
diesel::delete(looted::table.find(self.id)).execute(conn)?;
|
|
||||||
|
|
||||||
Ok(Update::ItemRemoved(self))
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn owned_by(player: i32) -> OwnedBy {
|
fn owned_by(player: i32) -> OwnedBy {
|
||||||
Loot::owned_by(player).select(ITEM_COLUMNS)
|
Loot::owned_by(player).select(ITEM_COLUMNS)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Owner status
|
||||||
|
pub(crate) const OF_GROUP: i32 = 0;
|
||||||
|
pub(crate) const OF_SHOP: i32 = -1;
|
||||||
|
pub(crate) const SOLD: i32 = -2;
|
||||||
|
|
||||||
|
type WithOwner = Eq<loot::owner_id, i32>;
|
||||||
|
type OwnedLoot = Filter<loot::table, WithOwner>;
|
||||||
|
|
||||||
|
/// An owned item
|
||||||
|
///
|
||||||
|
/// The owner is a Player, the Group, the Merchant
|
||||||
|
/// OR the SOLD state.
|
||||||
|
#[derive(Identifiable, Debug, Queryable)]
|
||||||
|
#[table_name = "loot"]
|
||||||
|
pub(crate) struct Loot {
|
||||||
|
id: i32,
|
||||||
|
name: String,
|
||||||
|
base_price: i32,
|
||||||
|
owner_id: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Loot {
|
||||||
|
/// A filter on Loot that is owned by given player
|
||||||
|
pub(super) fn owned_by(id: i32) -> OwnedLoot {
|
||||||
|
loot::table.filter(loot::owner_id.eq(id))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn set_owner(&self, owner: i32, conn: &DbConnection) -> QueryResult<()> {
|
||||||
|
diesel::update(loot::table.find(self.id))
|
||||||
|
.set(loot::dsl::owner_id.eq(owner))
|
||||||
|
.execute(conn)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn into_item(self) -> Item {
|
||||||
|
Item {
|
||||||
|
id: self.id,
|
||||||
|
name: self.name,
|
||||||
|
base_price: self.base_price,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn find(id: i32) -> Find<loot::table, i32> {
|
||||||
|
loot::table.find(id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub struct Inventory<'q>(pub &'q DbConnection);
|
pub struct Inventory<'q>(pub &'q DbConnection);
|
||||||
|
|
||||||
impl<'q> Inventory<'q> {
|
impl<'q> Inventory<'q> {
|
||||||
@@ -56,90 +91,93 @@ impl<'q> Inventory<'q> {
|
|||||||
pub fn find(&self, item_id: i32) -> QueryResult<Item> {
|
pub fn find(&self, item_id: i32) -> QueryResult<Item> {
|
||||||
items::table.find(item_id).first::<Item>(self.0)
|
items::table.find(item_id).first::<Item>(self.0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn find_by_name(&self, item_name: &str) -> QueryResult<Item> {
|
||||||
|
Ok(items::table
|
||||||
|
.filter(items::dsl::name.like(item_name))
|
||||||
|
.first(self.0)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check the inventory against a list of item names
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
///
|
||||||
|
/// A tuple of found items and errors
|
||||||
|
pub fn check_list(&self, item_names: Vec<String>) -> QueryResult<(Vec<Item>, String)> {
|
||||||
|
let all_items = self.all()?;
|
||||||
|
let mut found = Vec::new();
|
||||||
|
let mut errors = String::new();
|
||||||
|
for name in &item_names {
|
||||||
|
match self.find_by_name(name) {
|
||||||
|
Ok(item) => found.push(item),
|
||||||
|
Err(_) => errors.push_str(&format!("{},\n", name)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok((found, errors))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The shop resource
|
||||||
pub struct Shop<'q>(pub &'q DbConnection);
|
pub struct Shop<'q>(pub &'q DbConnection);
|
||||||
|
|
||||||
impl<'q> Shop<'q> {
|
impl<'q> Shop<'q> {
|
||||||
|
// Rename to list
|
||||||
pub fn all(&self) -> QueryResult<Vec<Item>> {
|
pub fn all(&self) -> QueryResult<Vec<Item>> {
|
||||||
shop::table.load(self.0)
|
Item::owned_by(OF_SHOP).load(self.0)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get(&self, id: i32) -> QueryResult<Item> {
|
fn buy_single(&self, buyer: i32, item_id: i32, price_mod: Option<f64>) -> UpdateResult {
|
||||||
shop::table.find(&id).first::<Item>(self.0)
|
use crate::AsPlayer;
|
||||||
|
let item = self.get(item_id)?;
|
||||||
|
let sell_price = match price_mod {
|
||||||
|
Some(modifier) => item.base_price as f64 * modifier,
|
||||||
|
None => item.base_price as f64,
|
||||||
|
};
|
||||||
|
self.0.transaction(|| {
|
||||||
|
let mut updates = AsPlayer(self.0, buyer).update_wealth(-sell_price)?;
|
||||||
|
item.set_owner(buyer, self.0)?;
|
||||||
|
updates.push(Update::ItemBought(item.into_item()));
|
||||||
|
Ok(updates)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn remove(&self, id: i32) -> QueryResult<()> {
|
pub fn buy(&self, items: Vec<(i32, Option<f64>)>, buyer: i32) -> UpdateResult {
|
||||||
diesel::delete(
|
// TODO: check that player has enough money !
|
||||||
shop::table.find(&id)
|
let has_enough_gold = true;
|
||||||
).execute(self.0)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn replace_list(&self, items: Vec<Item>) -> QueryResult<()> {
|
if has_enough_gold {
|
||||||
self.0.transaction(
|
let mut updates = Vec::new();
|
||||||
|| -> QueryResult<()>
|
for (item_id, price_mod) in items.into_iter() {
|
||||||
{
|
updates.append(&mut self.buy_single(buyer, item_id, price_mod)?)
|
||||||
// Remove all content
|
|
||||||
diesel::delete(shop::table).execute(self.0)?;
|
|
||||||
// Adds new list
|
|
||||||
for item in &items {
|
|
||||||
let new_item = NewItem {
|
|
||||||
name: &item.name,
|
|
||||||
base_price: item.base_price,
|
|
||||||
};
|
|
||||||
diesel::insert_into(shop::table)
|
|
||||||
.values(&new_item)
|
|
||||||
.execute(self.0)?;
|
|
||||||
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
)
|
Ok(updates)
|
||||||
}
|
} else {
|
||||||
}
|
unimplemented!();
|
||||||
|
|
||||||
type WithOwner = Eq<looted::owner_id, i32>;
|
|
||||||
type OwnedLoot = Filter<looted::table, WithOwner>;
|
|
||||||
|
|
||||||
/// Represents an item that has been looted,
|
|
||||||
/// hence has an owner.
|
|
||||||
#[derive(Identifiable, Debug, Queryable)]
|
|
||||||
#[table_name = "looted"]
|
|
||||||
pub(super) struct Loot {
|
|
||||||
id: i32,
|
|
||||||
name: String,
|
|
||||||
base_price: i32,
|
|
||||||
owner: i32,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Loot {
|
|
||||||
/// A filter on Loot that is owned by given player
|
|
||||||
pub(super) fn owned_by(id: i32) -> OwnedLoot {
|
|
||||||
looted::table.filter(looted::owner_id.eq(id))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn exists(id: i32) -> Exists<Find<looted::table, i32>> {
|
|
||||||
exists(looted::table.find(id))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn set_owner(&self, owner: i32, conn: &DbConnection) -> QueryResult<()> {
|
|
||||||
diesel::update(looted::table.find(self.id))
|
|
||||||
.set(looted::dsl::owner_id.eq(owner))
|
|
||||||
.execute(conn)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn into_item(self) -> Item {
|
|
||||||
Item {
|
|
||||||
id: self.id,
|
|
||||||
name: self.name,
|
|
||||||
base_price: self.base_price,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn find(id: i32) -> Find<looted::table, i32> {
|
pub(crate) fn get(&self, id: i32) -> QueryResult<Loot> {
|
||||||
looted::table.find(id)
|
Loot::owned_by(OF_SHOP).find(&id).first::<Loot>(self.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn replace_list(&self, items: Vec<Item>) -> QueryResult<()> {
|
||||||
|
use self::loot::dsl::*;
|
||||||
|
self.0.transaction(|| -> QueryResult<()> {
|
||||||
|
// Remove all content
|
||||||
|
diesel::delete(Loot::owned_by(OF_SHOP)).execute(self.0)?;
|
||||||
|
// Adds new list
|
||||||
|
for item in &items {
|
||||||
|
let new_item = NewLoot {
|
||||||
|
name: &item.name,
|
||||||
|
base_price: item.base_price,
|
||||||
|
owner_id: OF_SHOP,
|
||||||
|
};
|
||||||
|
diesel::insert_into(loot)
|
||||||
|
.values(&new_item)
|
||||||
|
.execute(self.0)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -152,28 +190,50 @@ impl<'q> LootManager<'q> {
|
|||||||
Ok(Item::owned_by(self.1).load(self.0)?)
|
Ok(Item::owned_by(self.1).load(self.0)?)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn get(&self, item_id: i32) -> QueryResult<Loot> {
|
||||||
|
Ok(Loot::owned_by(self.1).find(item_id).first(self.0)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn change_owner(&self, item_id: i32, new_owner: i32) -> QueryResult<()> {
|
||||||
|
Ok(self.get(item_id)?.set_owner(new_owner, self.0)?)
|
||||||
|
}
|
||||||
|
|
||||||
/// Finds an item by id
|
/// Finds an item by id
|
||||||
///
|
///
|
||||||
/// Returns a NotFound error if an item is found by it
|
/// Returns a NotFound error if an item is found by it
|
||||||
/// does not belong to this player
|
/// does not belong to this player
|
||||||
pub fn find(&self, loot_id: i32) -> QueryResult<Item> {
|
pub fn find(&self, loot_id: i32) -> QueryResult<Item> {
|
||||||
Ok(Loot::find(loot_id).first(self.0).and_then(|loot: Loot| {
|
Ok(self.get(loot_id)?.into_item())
|
||||||
if loot.owner != self.1 {
|
}
|
||||||
Err(diesel::result::Error::NotFound)
|
|
||||||
} else {
|
fn sell_single(&self, loot_id: i32, price_mod: Option<f64>) -> UpdateResult {
|
||||||
Ok(Item {
|
let to_sell = self.get(loot_id)?;
|
||||||
id: loot.id,
|
let mut sell_value = to_sell.base_price as f64 / 2.0;
|
||||||
name: loot.name,
|
if let Some(modifier) = price_mod {
|
||||||
base_price: loot.base_price,
|
sell_value *= modifier;
|
||||||
})
|
}
|
||||||
|
self.0.transaction(|| {
|
||||||
|
let mut updates = crate::AsPlayer(self.0, self.1).update_wealth(sell_value)?;
|
||||||
|
to_sell.set_owner(SOLD, self.0)?;
|
||||||
|
updates.push(Update::ItemSold(to_sell.into_item()));
|
||||||
|
Ok(updates)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sell(&self, items: Vec<(i32, Option<f64>)>) -> UpdateResult {
|
||||||
|
self.0.transaction(|| {
|
||||||
|
let mut updates = Vec::new();
|
||||||
|
for (loot_id, price_mod) in items.into_iter() {
|
||||||
|
updates.append(&mut self.sell_single(loot_id, price_mod)?);
|
||||||
}
|
}
|
||||||
})?)
|
Ok(updates)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The last item added to the chest
|
/// The last item added to the chest
|
||||||
pub fn last(&self) -> QueryResult<Item> {
|
pub fn last(&self) -> QueryResult<Item> {
|
||||||
Ok(Item::owned_by(self.1)
|
Ok(Item::owned_by(self.1)
|
||||||
.order(looted::dsl::id.desc())
|
.order(loot::dsl::id.desc())
|
||||||
.first(self.0)?)
|
.first(self.0)?)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -192,19 +252,19 @@ impl<'q> LootManager<'q> {
|
|||||||
base_price: item.base_price,
|
base_price: item.base_price,
|
||||||
owner_id: self.1,
|
owner_id: self.1,
|
||||||
};
|
};
|
||||||
diesel::insert_into(looted::table)
|
diesel::insert_into(loot::table)
|
||||||
.values(&new_item)
|
.values(&new_item)
|
||||||
.execute(self.0)?;
|
.execute(self.0)?;
|
||||||
Ok(Update::ItemAdded(self.last()?))
|
Ok(vec![Update::ItemAdded(self.last()?)])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An item being looted or bought.
|
/// An item being loot or bought.
|
||||||
///
|
///
|
||||||
/// The owner is set to 0 in case of looting,
|
/// The owner is set to 0 in case of looting,
|
||||||
/// to the id of buying player otherwise.
|
/// to the id of buying player otherwise.
|
||||||
#[derive(Insertable)]
|
#[derive(Insertable)]
|
||||||
#[table_name = "looted"]
|
#[table_name = "loot"]
|
||||||
struct NewLoot<'a> {
|
struct NewLoot<'a> {
|
||||||
name: &'a str,
|
name: &'a str,
|
||||||
base_price: i32,
|
base_price: i32,
|
||||||
@@ -212,7 +272,7 @@ struct NewLoot<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Insertable)]
|
#[derive(Insertable)]
|
||||||
#[table_name = "shop"]
|
#[table_name = "items"]
|
||||||
struct NewItem<'a> {
|
struct NewItem<'a> {
|
||||||
name: &'a str,
|
name: &'a str,
|
||||||
base_price: i32,
|
base_price: i32,
|
||||||
|
|||||||
@@ -89,7 +89,7 @@ impl<'q> AsPlayer<'q> {
|
|||||||
.filter(id.eq(self.1))
|
.filter(id.eq(self.1))
|
||||||
.set(&updated_wealth)
|
.set(&updated_wealth)
|
||||||
.execute(self.0)?;
|
.execute(self.0)?;
|
||||||
Ok(Update::Wealth(updated_wealth - current_wealth))
|
Ok(vec!(Update::Wealth(updated_wealth - current_wealth)))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Updates this player's debt
|
/// Updates this player's debt
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ table! {
|
|||||||
}
|
}
|
||||||
|
|
||||||
table! {
|
table! {
|
||||||
looted (id) {
|
loot (id) {
|
||||||
id -> Integer,
|
id -> Integer,
|
||||||
name -> Text,
|
name -> Text,
|
||||||
base_price -> Integer,
|
base_price -> Integer,
|
||||||
@@ -54,26 +54,16 @@ table! {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
table! {
|
|
||||||
shop (id) {
|
|
||||||
id -> Integer,
|
|
||||||
name -> Text,
|
|
||||||
base_price -> Integer,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
joinable!(claims -> looted (loot_id));
|
|
||||||
joinable!(claims -> players (player_id));
|
joinable!(claims -> players (player_id));
|
||||||
joinable!(history -> players (player_id));
|
joinable!(history -> players (player_id));
|
||||||
joinable!(looted -> players (owner_id));
|
joinable!(loot -> players (owner_id));
|
||||||
joinable!(notifications -> players (player_id));
|
joinable!(notifications -> players (player_id));
|
||||||
|
|
||||||
allow_tables_to_appear_in_same_query!(
|
allow_tables_to_appear_in_same_query!(
|
||||||
claims,
|
claims,
|
||||||
history,
|
history,
|
||||||
items,
|
items,
|
||||||
looted,
|
loot,
|
||||||
notifications,
|
notifications,
|
||||||
players,
|
players,
|
||||||
shop,
|
|
||||||
);
|
);
|
||||||
|
|||||||
264
src/api.rs
264
src/api.rs
@@ -20,6 +20,12 @@ pub struct NewGroupLoot {
|
|||||||
pub items: ItemList,
|
pub items: ItemList,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
|
pub struct NewPlayer {
|
||||||
|
name : String,
|
||||||
|
wealth : f64,
|
||||||
|
}
|
||||||
|
|
||||||
/// A generic response for all queries
|
/// A generic response for all queries
|
||||||
#[derive(Serialize, Debug, Default)]
|
#[derive(Serialize, Debug, Default)]
|
||||||
pub struct ApiResponse {
|
pub struct ApiResponse {
|
||||||
@@ -34,14 +40,18 @@ pub struct ApiResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ApiResponse {
|
impl ApiResponse {
|
||||||
fn push_update(&mut self, update: db::Update) {
|
fn push_updates(&mut self, mut updates: Vec<db::Update>) {
|
||||||
if let Some(v) = self.updates.as_mut() {
|
if let Some(v) = self.updates.as_mut() {
|
||||||
v.push(update);
|
v.append(&mut updates);
|
||||||
} else {
|
} else {
|
||||||
self.updates = Some(vec![update]);
|
self.updates = Some(updates);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn push_update(&mut self, update: db::Update) {
|
||||||
|
self.push_updates(vec!(update))
|
||||||
|
}
|
||||||
|
|
||||||
fn push_error<S: Into<String>>(&mut self, error: S) {
|
fn push_error<S: Into<String>>(&mut self, error: S) {
|
||||||
if let Some(errors) = self.errors.as_mut() {
|
if let Some(errors) = self.errors.as_mut() {
|
||||||
*errors = format!("{}\n{}", errors, error.into());
|
*errors = format!("{}\n{}", errors, error.into());
|
||||||
@@ -64,177 +74,145 @@ pub enum ApiError {
|
|||||||
InvalidAction(String),
|
InvalidAction(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Every allowed queries on the database
|
pub enum ApiEndpoint {
|
||||||
pub enum ApiActions {
|
InventoryList,
|
||||||
// Application level
|
InventoryCheck(Vec<String>),
|
||||||
FetchPlayers,
|
InventoryAdd(String, i32), // db::Inventory(conn)::add(new_item)
|
||||||
FetchInventory,
|
|
||||||
FetchShopInventory,
|
ShopList, // db::Shop(conn)::list()
|
||||||
FetchClaims,
|
BuyItems(i32, BuySellParams), // db::Shop(conn)::buy(params)
|
||||||
CheckItemList(Vec<String>),
|
RefreshShop(ItemList), // db::Shop(conn)::replace_list(items)
|
||||||
// Player level
|
|
||||||
FetchPlayer(i32),
|
ClaimsList,
|
||||||
FetchPlayerClaims(i32),
|
|
||||||
FetchNotifications(i32),
|
// db::Players::get returns AsPlayer<'q>
|
||||||
FetchLoot(i32),
|
PlayerList, //db::Players(conn)::list()
|
||||||
UpdateWealth(i32, f64),
|
PlayerAdd(NewPlayer), //db::Players(conn)::add(player)
|
||||||
BuyItems(i32, BuySellParams),
|
PlayerFetch(i32), // db::Players(conn)::get(id)
|
||||||
SellItems(i32, BuySellParams),
|
PlayerClaims(i32), // db::Players(conn)::get(id).claims()
|
||||||
ClaimItems(i32, IdList),
|
PlayerNotifications(i32), // db::Players(conn)::get(id).notifications()
|
||||||
UndoLastAction(i32),
|
PlayerLoot(i32),// db::Players(conn)::get(id).loot()
|
||||||
// Group level
|
PlayerUpdateWealth(i32, f64), // db::Players(conn)::get(id).update_wealth(f64)
|
||||||
AddLoot(NewGroupLoot),
|
SellItems(i32, BuySellParams), // db::Players(conn)::get(id).sell(params)
|
||||||
// Admin level
|
ClaimItems(i32, IdList), // db::Players(conn)::get(id).claim(items)
|
||||||
RefreshShopInventory(ItemList),
|
UndoLastAction(i32), // db::Players(conn)::get(id).undo_last()
|
||||||
//AddPlayer(String, f64),
|
AddLoot(NewGroupLoot), // db::Group(conn)::add_loot(loot)
|
||||||
//AddInventoryItem(pub String, pub i32),
|
ResolveClaims, // db::Group(conn)::resolve_claims()
|
||||||
//ResolveClaims,
|
|
||||||
//SetClaimsTimeout(pub i32),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static ERROR_MSG : &str = "Une erreur est survenue";
|
||||||
|
|
||||||
pub fn execute(
|
pub fn execute(
|
||||||
conn: &DbConnection,
|
conn: &DbConnection,
|
||||||
query: ApiActions,
|
query: ApiEndpoint,
|
||||||
) -> Result<ApiResponse, diesel::result::Error> {
|
) -> Result<ApiResponse, diesel::result::Error> {
|
||||||
let mut response = ApiResponse::default();
|
let mut response = ApiResponse::default();
|
||||||
// Return an Option<String> that describes what happened.
|
// Return an Option<String> that describes what happened.
|
||||||
// If there is some value, store the actions in db so that it can be reversed.
|
// If there is some value, store the actions in db so that it can be reversed.
|
||||||
let action_text: Option<(i32, &str)> = match query {
|
let action_text: Option<(i32, &str)> = match query {
|
||||||
ApiActions::CheckItemList(names) => {
|
// Inventory
|
||||||
let (items, errors) = {
|
ApiEndpoint::InventoryList => {
|
||||||
let mut found = Vec::new();
|
match db::Inventory(conn).all() {
|
||||||
let mut errors = String::new();
|
Ok(items) => response.set_value(Value::ItemList(items)),
|
||||||
let items = db::Inventory(conn).all()?;
|
Err(_) => response.push_error(ERROR_MSG),
|
||||||
for name in &names {
|
}
|
||||||
if let Some(item) = items.iter().filter(|i| &i.name == name).take(1).next() {
|
|
||||||
found.push(item.clone())
|
|
||||||
} else {
|
|
||||||
errors.push_str(&format!("{},\n", name));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
(found, errors)
|
|
||||||
};
|
|
||||||
|
|
||||||
response.set_value(Value::ItemList(items));
|
|
||||||
response.push_error(errors);
|
|
||||||
dbg!(&names, &response);
|
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
ApiActions::FetchPlayers => {
|
ApiEndpoint::InventoryCheck(names) => {
|
||||||
|
match db::Inventory(conn).check_list(names) {
|
||||||
|
Ok((items, errors)) => {
|
||||||
|
response.set_value(Value::ItemList(items));
|
||||||
|
response.push_error(errors);
|
||||||
|
}
|
||||||
|
Err(_) => response.push_error(ERROR_MSG),
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
ApiEndpoint::InventoryAdd(name, value) => {
|
||||||
|
response.push_error("Not implemented");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
//Shop
|
||||||
|
ApiEndpoint::ShopList => {
|
||||||
|
match db::Shop(conn).all() {
|
||||||
|
Ok(items) => response.set_value(Value::ItemList(items)),
|
||||||
|
Err(_) => response.push_error(ERROR_MSG),
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
ApiEndpoint::BuyItems(buyer, params) => {
|
||||||
|
match db::Shop(conn).buy(params.items, buyer) {
|
||||||
|
Ok(updates) => {
|
||||||
|
response.notify("Objets achetés !");
|
||||||
|
response.push_updates(updates);
|
||||||
|
Some((buyer, "Achat d'objets"))
|
||||||
|
},
|
||||||
|
Err(_) => {
|
||||||
|
response.push_error(ERROR_MSG);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Players
|
||||||
|
ApiEndpoint::PlayerList => {
|
||||||
response.set_value(Value::PlayerList(db::Players(conn).all_except_group()?));
|
response.set_value(Value::PlayerList(db::Players(conn).all_except_group()?));
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
ApiActions::FetchInventory => {
|
ApiEndpoint::PlayerFetch(id) => {
|
||||||
response.set_value(Value::ItemList(db::Inventory(conn).all()?));
|
|
||||||
None
|
|
||||||
}
|
|
||||||
ApiActions::FetchShopInventory => {
|
|
||||||
response.set_value(Value::ItemList(db::Shop(conn).all()?));
|
|
||||||
None
|
|
||||||
}
|
|
||||||
ApiActions::FetchClaims => {
|
|
||||||
response.set_value(Value::ClaimList(db::Claims(conn).all()?));
|
|
||||||
None
|
|
||||||
}
|
|
||||||
ApiActions::FetchPlayer(id) => {
|
|
||||||
response.set_value(Value::Player(db::Players(conn).find(id)?));
|
response.set_value(Value::Player(db::Players(conn).find(id)?));
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
ApiActions::FetchPlayerClaims(id) => {
|
ApiEndpoint::ClaimsList => {
|
||||||
|
response.set_value(Value::ClaimList(db::Claims(conn).all()?));
|
||||||
|
None
|
||||||
|
}
|
||||||
|
ApiEndpoint::PlayerClaims(id) => {
|
||||||
response.set_value(Value::ClaimList(db::Claims(conn).by_player(id)?));
|
response.set_value(Value::ClaimList(db::Claims(conn).by_player(id)?));
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
ApiActions::FetchNotifications(id) => {
|
ApiEndpoint::PlayerNotifications(id) => {
|
||||||
response.set_value(Value::Notifications(
|
response.set_value(Value::Notifications(
|
||||||
db::AsPlayer(conn, id).notifications()?,
|
db::AsPlayer(conn, id).notifications()?,
|
||||||
));
|
));
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
ApiActions::FetchLoot(id) => {
|
ApiEndpoint::PlayerLoot(id) => {
|
||||||
response.set_value(Value::ItemList(db::LootManager(conn, id).all()?));
|
response.set_value(Value::ItemList(db::LootManager(conn, id).all()?));
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
ApiActions::UpdateWealth(id, amount) => {
|
ApiEndpoint::PlayerUpdateWealth(id, amount) => {
|
||||||
response.push_update(db::AsPlayer(conn, id).update_wealth(amount)?);
|
response.push_updates(db::AsPlayer(conn, id).update_wealth(amount)?);
|
||||||
response.notify(format!("Mis à jour ({}po)!", amount));
|
response.notify(format!("Mis à jour ({}po)!", amount));
|
||||||
Some((id, "Argent mis à jour"))
|
Some((id, "Argent mis à jour"))
|
||||||
}
|
}
|
||||||
ApiActions::BuyItems(id, params) => {
|
|
||||||
// TODO: check that player has enough money !
|
|
||||||
let has_enough_gold = true;
|
|
||||||
|
|
||||||
if has_enough_gold {
|
|
||||||
let mut gains: Vec<db::Wealth> = Vec::with_capacity(params.items.len());
|
|
||||||
for (item_id, price_mod) in params.items.into_iter() {
|
|
||||||
if let Ok((item, diff)) = db::buy_item_from_shop(conn, id, item_id, price_mod) {
|
|
||||||
response.push_update(item);
|
|
||||||
gains.push(diff);
|
|
||||||
} else {
|
|
||||||
response.push_error(format!("Error adding {}", item_id));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let added_items = gains.len();
|
|
||||||
let total_amount = gains
|
|
||||||
.into_iter()
|
|
||||||
.fold(db::Wealth::from_gp(0.0), |acc, i| acc + i);
|
|
||||||
response.notify(format!(
|
|
||||||
"{} objets achetés pour {}po",
|
|
||||||
added_items,
|
|
||||||
total_amount.to_gp()
|
|
||||||
));
|
|
||||||
response.push_update(Update::Wealth(total_amount));
|
|
||||||
Some((id, "Achat d'objets"))
|
|
||||||
} else {
|
|
||||||
response.push_error("Vous n'avez pas assez d'argent !");
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Behavior differs if player is group or regular.
|
// Behavior differs if player is group or regular.
|
||||||
// Group sells item like players then split the total amount among players.
|
// Group sells item like players then split the total amount among players.
|
||||||
ApiActions::SellItems(id, params) => {
|
ApiEndpoint::SellItems(id, params) => {
|
||||||
conn.transaction(|| -> Result<Option<(i32, &str)>, diesel::result::Error> {
|
conn.transaction(|| -> Result<Option<(i32, &str)>, diesel::result::Error> {
|
||||||
let mut gains: Vec<db::Wealth> = Vec::with_capacity(params.items.len());
|
let mut updates = db::LootManager(conn, id).sell(params.items)?;
|
||||||
for (loot_id, price_mod) in params.items.iter() {
|
let total_amount: i32 = updates.iter()
|
||||||
if let Ok((deleted, diff)) =
|
.filter_map(|u| match u {
|
||||||
db::sell_item_transaction(conn, id, *loot_id, *price_mod)
|
Update::Wealth(diff) => Some(diff.to_gp() as i32),
|
||||||
{
|
_ => None
|
||||||
response.push_update(deleted);
|
}).sum();
|
||||||
gains.push(diff);
|
|
||||||
} else {
|
|
||||||
response
|
|
||||||
.push_error(format!("Erreur lors de la vente (loot_id : {})", loot_id));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let sold_items = gains.len();
|
|
||||||
let total_amount = gains
|
|
||||||
.into_iter()
|
|
||||||
.fold(db::Wealth::from_gp(0.0), |acc, i| acc + i);
|
|
||||||
match id {
|
match id {
|
||||||
0 => {
|
0 => {
|
||||||
let players = params.players.unwrap_or_default();
|
let players = params.players.unwrap_or_default();
|
||||||
if let Update::Wealth(shared) =
|
updates.append(
|
||||||
db::split_and_share(conn, total_amount.to_gp() as i32, players)?
|
&mut db::split_and_share(conn, total_amount, players)?
|
||||||
{
|
);
|
||||||
response.notify(format!(
|
response.notify("Les objets ont été vendus");
|
||||||
"Les objets ont été vendus, les joueurs ont reçu (au total) {} po",
|
response.push_updates(updates);
|
||||||
shared.to_gp()
|
|
||||||
));
|
|
||||||
response.push_update(Update::Wealth(total_amount - shared));
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
_ => {
|
_ => {
|
||||||
response.notify(format!(
|
response.notify("Objets vendus !");
|
||||||
"{} objet(s) vendu(s) pour {} po",
|
response.push_updates(updates);
|
||||||
sold_items,
|
|
||||||
total_amount.to_gp()
|
|
||||||
));
|
|
||||||
response.push_update(Update::Wealth(total_amount));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(Some((id, "Vente d'objets")))
|
Ok(Some((id, "Vente d'objets")))
|
||||||
})?
|
})?
|
||||||
}
|
}
|
||||||
ApiActions::ClaimItems(id, items) => {
|
ApiEndpoint::ClaimItems(id, items) => {
|
||||||
conn.transaction(|| -> Result<Option<(i32, &str)>, diesel::result::Error> {
|
conn.transaction(|| -> Result<Option<(i32, &str)>, diesel::result::Error> {
|
||||||
let current_claims: HashSet<i32> = db::Claims(conn)
|
let current_claims: HashSet<i32> = db::Claims(conn)
|
||||||
.all()?
|
.all()?
|
||||||
@@ -245,21 +223,19 @@ pub fn execute(
|
|||||||
let new_claims: HashSet<i32> = items.into_iter().collect();
|
let new_claims: HashSet<i32> = items.into_iter().collect();
|
||||||
// Claims to delete
|
// Claims to delete
|
||||||
for item in current_claims.difference(&new_claims) {
|
for item in current_claims.difference(&new_claims) {
|
||||||
response.push_update(db::Claims(conn).remove(id, *item)?);
|
response.push_updates(db::Claims(conn).remove(id, *item)?);
|
||||||
}
|
}
|
||||||
// Claims to add
|
// Claims to add
|
||||||
for item in new_claims.difference(¤t_claims) {
|
for item in new_claims.difference(¤t_claims) {
|
||||||
response.push_update(db::Claims(conn).add(id, *item)?);
|
response.push_updates(db::Claims(conn).add(id, *item)?);
|
||||||
}
|
}
|
||||||
Ok(None)
|
Ok(None)
|
||||||
})?
|
})?
|
||||||
}
|
}
|
||||||
ApiActions::UndoLastAction(id) => {
|
ApiEndpoint::UndoLastAction(id) => {
|
||||||
if let Ok(event) = db::models::history::get_last_of_player(conn, id) {
|
if let Ok(event) = db::models::history::get_last_of_player(conn, id) {
|
||||||
let name = String::from(event.name());
|
let name = String::from(event.name());
|
||||||
for undone in event.undo(conn)?.into_inner().into_iter() {
|
event.undo(conn)?;
|
||||||
response.push_update(undone);
|
|
||||||
}
|
|
||||||
response.notify(format!("'{}' annulé(e)", name));
|
response.notify(format!("'{}' annulé(e)", name));
|
||||||
} else {
|
} else {
|
||||||
response.push_error("Aucune action trouvée")
|
response.push_error("Aucune action trouvée")
|
||||||
@@ -267,11 +243,11 @@ pub fn execute(
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
// Group actions
|
// Group actions
|
||||||
ApiActions::AddLoot(data) => {
|
ApiEndpoint::AddLoot(data) => {
|
||||||
let mut added_items = 0;
|
let mut added_items = 0;
|
||||||
for item in data.items.into_iter() {
|
for item in data.items.into_iter() {
|
||||||
if let Ok(added) = db::LootManager(conn, 0).add_from(&item) {
|
if let Ok(added) = db::LootManager(conn, 0).add_from(&item) {
|
||||||
response.push_update(added);
|
response.push_updates(added);
|
||||||
added_items += 1;
|
added_items += 1;
|
||||||
} else {
|
} else {
|
||||||
response.push_error(format!("Error adding {:?}", item));
|
response.push_error(format!("Error adding {:?}", item));
|
||||||
@@ -286,9 +262,19 @@ pub fn execute(
|
|||||||
};
|
};
|
||||||
Some((0, "Nouveau loot"))
|
Some((0, "Nouveau loot"))
|
||||||
}
|
}
|
||||||
|
ApiEndpoint::ResolveClaims => {
|
||||||
|
response.push_error("Not implemented!");
|
||||||
|
None
|
||||||
|
}
|
||||||
// Admin actions
|
// Admin actions
|
||||||
ApiActions::RefreshShopInventory(items) => {
|
ApiEndpoint::RefreshShop(items) => {
|
||||||
db::Shop(conn).replace_list(items)?;
|
db::Shop(conn).replace_list(items)?;
|
||||||
|
response.notify("Inventaire du marchand renouvelé !");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
ApiEndpoint::PlayerAdd(data) => {
|
||||||
|
db::Players(conn).add(&data.name, data.wealth)?;
|
||||||
|
response.notify("Joueur ajouté !");
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
106
src/server.rs
106
src/server.rs
@@ -11,9 +11,8 @@ use futures::{
|
|||||||
future::{ok, Either, FutureResult},
|
future::{ok, Either, FutureResult},
|
||||||
Future,
|
Future,
|
||||||
};
|
};
|
||||||
use std::env;
|
|
||||||
use serde_json;
|
use serde_json;
|
||||||
|
use std::env;
|
||||||
|
|
||||||
use crate::api;
|
use crate::api;
|
||||||
use lootalot_db as db;
|
use lootalot_db as db;
|
||||||
@@ -31,7 +30,7 @@ type MaybeForbidden =
|
|||||||
/// Wraps call to the database query and convert its result as a async HttpResponse
|
/// Wraps call to the database query and convert its result as a async HttpResponse
|
||||||
fn db_call(
|
fn db_call(
|
||||||
pool: AppPool,
|
pool: AppPool,
|
||||||
query: api::ApiActions,
|
query: api::ApiEndpoint,
|
||||||
) -> impl Future<Item = HttpResponse, Error = Error> {
|
) -> impl Future<Item = HttpResponse, Error = Error> {
|
||||||
let conn = pool.get().unwrap();
|
let conn = pool.get().unwrap();
|
||||||
web::block(move || api::execute(&conn, query)).then(|res| match res {
|
web::block(move || api::execute(&conn, query)).then(|res| match res {
|
||||||
@@ -43,7 +42,7 @@ fn db_call(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn restricted_to_group(id: i32, params: (AppPool, api::ApiActions)) -> MaybeForbidden {
|
fn restricted_to_group(id: i32, params: (AppPool, api::ApiEndpoint)) -> MaybeForbidden {
|
||||||
if id != 0 {
|
if id != 0 {
|
||||||
actix_web::Either::B(HttpResponse::Forbidden().finish())
|
actix_web::Either::B(HttpResponse::Forbidden().finish())
|
||||||
} else {
|
} else {
|
||||||
@@ -102,7 +101,7 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn configure_api(config: &mut web::ServiceConfig) {
|
fn configure_api(config: &mut web::ServiceConfig) {
|
||||||
use api::ApiActions as Q;
|
use api::ApiEndpoint as Q;
|
||||||
config.service(
|
config.service(
|
||||||
web::scope("/api")
|
web::scope("/api")
|
||||||
.wrap(RestrictedAccess)
|
.wrap(RestrictedAccess)
|
||||||
@@ -110,46 +109,51 @@ fn configure_api(config: &mut web::ServiceConfig) {
|
|||||||
web::scope("/players")
|
web::scope("/players")
|
||||||
.service(
|
.service(
|
||||||
web::resource("/")
|
web::resource("/")
|
||||||
.route(web::get().to_async(|pool| db_call(pool, Q::FetchPlayers))), //.route(web::post().to_async(endpoints::new_player))
|
.route(web::get().to_async(|pool| db_call(pool, Q::PlayerList)))
|
||||||
|
.route(web::post().to_async(
|
||||||
|
|pool, player: web::Json<api::NewPlayer>| {
|
||||||
|
db_call(pool, Q::PlayerAdd(player.into_inner()))
|
||||||
|
},
|
||||||
|
)),
|
||||||
) // List of players
|
) // List of players
|
||||||
.service(
|
.service(
|
||||||
web::scope("/{player_id}")
|
web::scope("/{player_id}")
|
||||||
.route(
|
/*.route(
|
||||||
"/",
|
"/",
|
||||||
web::get().to_async(|pool, player: PlayerId| {
|
web::get().to_async(|pool, player: PlayerId| {
|
||||||
db_call(pool, Q::FetchPlayer(*player))
|
db_call(pool, Q::FetchPlayer(*player))
|
||||||
}),
|
}),
|
||||||
)
|
)*/
|
||||||
.route(
|
.route(
|
||||||
"/notifications",
|
"/notifications",
|
||||||
web::get().to_async(|pool, player: PlayerId| {
|
web::get().to_async(|pool, player: PlayerId| {
|
||||||
db_call(pool, Q::FetchNotifications(*player))
|
db_call(pool, Q::PlayerNotifications(*player))
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.service(
|
.service(
|
||||||
web::resource("/claims")
|
web::resource("/claims")
|
||||||
.route(web::get().to_async(|pool, player: PlayerId| {
|
.route(web::get().to_async(|pool, player: PlayerId| {
|
||||||
db_call(pool, Q::FetchPlayerClaims(*player))
|
db_call(pool, Q::PlayerClaims(*player))
|
||||||
}))
|
}))
|
||||||
.route(web::post().to_async(
|
.route(web::post().to_async(
|
||||||
|pool, (player, data): (PlayerId, IdList)| {
|
|pool, (player, data): (PlayerId, IdList)| {
|
||||||
db_call(pool, Q::ClaimItems(*player, data.into_inner()))
|
db_call(pool, Q::ClaimItems(*player, data.into_inner()))
|
||||||
},
|
},
|
||||||
))
|
)),
|
||||||
)
|
)
|
||||||
.service(
|
.service(
|
||||||
web::resource("/wealth")
|
web::resource("/wealth")
|
||||||
//.route(web::get().to_async(...))
|
//.route(web::get().to_async(...))
|
||||||
.route(web::put().to_async(
|
.route(web::put().to_async(
|
||||||
|pool, (player, data): (PlayerId, web::Json<f64>)| {
|
|pool, (player, data): (PlayerId, web::Json<f64>)| {
|
||||||
db_call(pool, Q::UpdateWealth(*player, *data))
|
db_call(pool, Q::PlayerUpdateWealth(*player, *data))
|
||||||
},
|
},
|
||||||
)),
|
)),
|
||||||
)
|
)
|
||||||
.service(
|
.service(
|
||||||
web::resource("/loot")
|
web::resource("/loot")
|
||||||
.route(web::get().to_async(|pool, player: PlayerId| {
|
.route(web::get().to_async(|pool, player: PlayerId| {
|
||||||
db_call(pool, Q::FetchLoot(*player))
|
db_call(pool, Q::PlayerLoot(*player))
|
||||||
}))
|
}))
|
||||||
.route(web::put().to_async(
|
.route(web::put().to_async(
|
||||||
move |pool, (player, data): (PlayerId, BuySellParams)| {
|
move |pool, (player, data): (PlayerId, BuySellParams)| {
|
||||||
@@ -180,25 +184,25 @@ fn configure_api(config: &mut web::ServiceConfig) {
|
|||||||
)
|
)
|
||||||
.route(
|
.route(
|
||||||
"/claims",
|
"/claims",
|
||||||
web::get().to_async(|pool| db_call(pool, Q::FetchClaims)),
|
web::get().to_async(|pool| db_call(pool, Q::ClaimsList)),
|
||||||
)
|
)
|
||||||
.service(
|
.service(
|
||||||
web::resource("/shop")
|
web::resource("/shop")
|
||||||
.route(web::get().to_async(|pool| db_call(pool, Q::FetchShopInventory)))
|
.route(web::get().to_async(|pool| db_call(pool, Q::ShopList)))
|
||||||
.route(
|
.route(
|
||||||
web::post().to_async(|pool, items: web::Json<api::ItemList>| {
|
web::post().to_async(|pool, items: web::Json<api::ItemList>| {
|
||||||
db_call(pool, Q::RefreshShopInventory(items.into_inner()))
|
db_call(pool, Q::RefreshShop(items.into_inner()))
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.service(
|
.service(
|
||||||
web::resource("/items")
|
web::resource("/items")
|
||||||
.route(
|
.route(
|
||||||
web::get().to_async(move |pool: AppPool| db_call(pool, Q::FetchInventory)),
|
web::get().to_async(move |pool: AppPool| db_call(pool, Q::InventoryList)),
|
||||||
)
|
)
|
||||||
.route(web::post().to_async(
|
.route(web::post().to_async(
|
||||||
move |pool: AppPool, items: web::Json<Vec<String>>| {
|
move |pool: AppPool, items: web::Json<Vec<String>>| {
|
||||||
db_call(pool, Q::CheckItemList(items.into_inner()))
|
db_call(pool, Q::InventoryCheck(items.into_inner()))
|
||||||
},
|
},
|
||||||
)),
|
)),
|
||||||
),
|
),
|
||||||
@@ -210,10 +214,10 @@ struct AuthRequest {
|
|||||||
key: String,
|
key: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug,Copy,Clone, Serialize, Deserialize)]
|
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
|
||||||
enum SessionKind {
|
enum SessionKind {
|
||||||
Player(i32),
|
Player(i32),
|
||||||
Admin
|
Admin,
|
||||||
}
|
}
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
@@ -223,24 +227,25 @@ fn check_key(key: &str, db: HashMap<&str, SessionKind>) -> Option<SessionKind> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn login(id: Identity, key: web::Query<AuthRequest>) -> HttpResponse {
|
fn login(id: Identity, key: web::Query<AuthRequest>) -> HttpResponse {
|
||||||
if let Some(session_kind) =
|
if let Some(session_kind) = check_key(
|
||||||
check_key(
|
&key.key.to_string(),
|
||||||
&key.key.to_string(),
|
[
|
||||||
[("0", SessionKind::Player(0)),
|
("0", SessionKind::Player(0)),
|
||||||
("1", SessionKind::Player(1)),
|
("1", SessionKind::Player(1)),
|
||||||
("2", SessionKind::Player(2)),
|
("2", SessionKind::Player(2)),
|
||||||
("admin", SessionKind::Admin),
|
("admin", SessionKind::Admin),
|
||||||
].iter().cloned().collect::<HashMap<&str, SessionKind>>()
|
]
|
||||||
)
|
.iter()
|
||||||
{
|
.cloned()
|
||||||
id.remember(serde_json::to_string(&session_kind).expect("Serialize SessionKind error"));
|
.collect::<HashMap<&str, SessionKind>>(),
|
||||||
HttpResponse::build(StatusCode::TEMPORARY_REDIRECT)
|
) {
|
||||||
.header(header::LOCATION, "/")
|
id.remember(serde_json::to_string(&session_kind).expect("Serialize SessionKind error"));
|
||||||
.finish()
|
HttpResponse::build(StatusCode::TEMPORARY_REDIRECT)
|
||||||
|
.header(header::LOCATION, "/")
|
||||||
|
.finish()
|
||||||
} else {
|
} else {
|
||||||
HttpResponse::Forbidden().finish()
|
HttpResponse::Forbidden().finish()
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn logout(id: Identity) -> HttpResponse {
|
fn logout(id: Identity) -> HttpResponse {
|
||||||
@@ -268,19 +273,22 @@ fn enter_session(id: Identity, pool: AppPool) -> impl Future<Item = HttpResponse
|
|||||||
// unlogged case with web::block below
|
// unlogged case with web::block below
|
||||||
.unwrap_or(SessionKind::Player(-1));
|
.unwrap_or(SessionKind::Player(-1));
|
||||||
|
|
||||||
web::block(move || api::execute(&conn, match logged {
|
web::block(move || {
|
||||||
SessionKind::Player(id) => api::ApiActions::FetchPlayer(id),
|
api::execute(
|
||||||
SessionKind::Admin => api::ApiActions::FetchPlayers
|
&conn,
|
||||||
}
|
match logged {
|
||||||
)).then(
|
SessionKind::Player(id) => api::ApiEndpoint::PlayerFetch(id),
|
||||||
|res| match res {
|
SessionKind::Admin => api::ApiEndpoint::PlayerList,
|
||||||
Ok(r) => HttpResponse::Ok().json(r.value),
|
},
|
||||||
Err(e) => {
|
)
|
||||||
dbg!(&e);
|
})
|
||||||
HttpResponse::Forbidden().finish()
|
.then(|res| match res {
|
||||||
}
|
Ok(r) => HttpResponse::Ok().json(r.value),
|
||||||
},
|
Err(e) => {
|
||||||
)
|
dbg!(&e);
|
||||||
|
HttpResponse::Forbidden().finish()
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn serve() -> std::io::Result<()> {
|
pub fn serve() -> std::io::Result<()> {
|
||||||
@@ -310,7 +318,7 @@ pub fn serve() -> std::io::Result<()> {
|
|||||||
.route("/session", web::get().to_async(enter_session))
|
.route("/session", web::get().to_async(enter_session))
|
||||||
.route("/login", web::get().to(login))
|
.route("/login", web::get().to(login))
|
||||||
.route("/logout", web::get().to(logout))
|
.route("/logout", web::get().to(logout))
|
||||||
//.service(fs::Files::new("/", www_root.clone()).index_file("index.html"))
|
//.service(fs::Files::new("/", www_root.clone()).index_file("index.html"))
|
||||||
})
|
})
|
||||||
.bind("127.0.0.1:8088")?
|
.bind("127.0.0.1:8088")?
|
||||||
.run()
|
.run()
|
||||||
|
|||||||
Reference in New Issue
Block a user