support aquiring server props and test dropping them

This commit is contained in:
Evan Carroll 2026-01-20 18:33:15 -06:00
parent 3e1afb82c8
commit 7852790a1e
9 changed files with 858 additions and 150 deletions

View file

@ -295,6 +295,7 @@ pub enum AvatarLayer {
#[default] #[default]
Clothes, Clothes,
Accessories, Accessories,
Emote,
} }
impl std::fmt::Display for AvatarLayer { impl std::fmt::Display for AvatarLayer {
@ -303,6 +304,7 @@ impl std::fmt::Display for AvatarLayer {
AvatarLayer::Skin => write!(f, "skin"), AvatarLayer::Skin => write!(f, "skin"),
AvatarLayer::Clothes => write!(f, "clothes"), AvatarLayer::Clothes => write!(f, "clothes"),
AvatarLayer::Accessories => write!(f, "accessories"), AvatarLayer::Accessories => write!(f, "accessories"),
AvatarLayer::Emote => write!(f, "emote"),
} }
} }
} }
@ -315,6 +317,7 @@ impl std::str::FromStr for AvatarLayer {
"skin" => Ok(AvatarLayer::Skin), "skin" => Ok(AvatarLayer::Skin),
"clothes" => Ok(AvatarLayer::Clothes), "clothes" => Ok(AvatarLayer::Clothes),
"accessories" => Ok(AvatarLayer::Accessories), "accessories" => Ok(AvatarLayer::Accessories),
"emote" => Ok(AvatarLayer::Emote),
_ => Err(format!("Invalid avatar layer: {}", s)), _ => Err(format!("Invalid avatar layer: {}", s)),
} }
} }
@ -685,21 +688,40 @@ pub struct InventoryResponse {
pub items: Vec<InventoryItem>, pub items: Vec<InventoryItem>,
} }
/// A public prop from server or realm library. /// Extended prop info for acquisition UI (works for both server and realm props).
/// Used for the public inventory tabs (Server/Realm). /// Includes ownership and availability status for the current user.
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "ssr", derive(sqlx::FromRow))] #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
pub struct PublicProp { pub struct PropAcquisitionInfo {
pub id: Uuid, pub id: Uuid,
pub name: String, pub name: String,
pub asset_path: String, pub asset_path: String,
pub description: Option<String>, pub description: Option<String>,
pub is_unique: bool,
/// User already has this prop in their inventory.
pub user_owns: bool,
/// For unique props: someone has already claimed it.
pub is_claimed: bool,
/// Prop is within its availability window (or has no window).
pub is_available: bool,
} }
/// Response for public props list. /// Request to acquire a prop (server or realm).
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PublicPropsResponse { pub struct AcquirePropRequest {
pub props: Vec<PublicProp>, pub prop_id: Uuid,
}
/// Response after acquiring a prop.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AcquirePropResponse {
pub item: InventoryItem,
}
/// Response for prop acquisition list with status.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PropAcquisitionListResponse {
pub props: Vec<PropAcquisitionInfo>,
} }
/// A prop dropped in a channel, available for pickup. /// A prop dropped in a channel, available for pickup.

View file

@ -3,7 +3,7 @@
use sqlx::PgExecutor; use sqlx::PgExecutor;
use uuid::Uuid; use uuid::Uuid;
use crate::models::{InventoryItem, PublicProp}; use crate::models::{InventoryItem, PropAcquisitionInfo};
use chattyness_error::AppError; use chattyness_error::AppError;
/// List all inventory items for a user. /// List all inventory items for a user.
@ -92,66 +92,455 @@ pub async fn drop_inventory_item<'e>(
Ok(()) Ok(())
} }
/// List all public server props. /// List public server props with optional acquisition status.
/// ///
/// Returns props that are: /// Returns props that are active and public, with flags indicating:
/// - Active (`is_active = true`) /// - `user_owns`: Whether the user already has this prop (false if no user_id)
/// - Public (`is_public = true`) /// - `is_claimed`: Whether a unique prop has been claimed by anyone
/// - Currently available (within availability window if set) /// - `is_available`: Whether the prop is within its availability window
pub async fn list_public_server_props<'e>( ///
/// When `user_id` is None, returns default values for user-specific fields.
pub async fn list_server_props<'e>(
executor: impl PgExecutor<'e>, executor: impl PgExecutor<'e>,
) -> Result<Vec<PublicProp>, AppError> { user_id: Option<Uuid>,
let props = sqlx::query_as::<_, PublicProp>( ) -> Result<Vec<PropAcquisitionInfo>, AppError> {
let props = sqlx::query_as::<_, PropAcquisitionInfo>(
r#" r#"
SELECT SELECT
id, p.id,
name, p.name,
asset_path, p.asset_path,
description p.description,
FROM server.props p.is_unique,
WHERE is_active = true CASE
AND is_public = true WHEN $1::uuid IS NOT NULL THEN EXISTS(
AND (available_from IS NULL OR available_from <= now()) SELECT 1 FROM auth.inventory i
AND (available_until IS NULL OR available_until > now()) WHERE i.user_id = $1 AND i.server_prop_id = p.id
ORDER BY name ASC )
ELSE false
END AS user_owns,
CASE
WHEN p.is_unique THEN EXISTS(
SELECT 1 FROM auth.inventory i WHERE i.server_prop_id = p.id
)
ELSE false
END AS is_claimed,
(p.available_from IS NULL OR p.available_from <= now())
AND (p.available_until IS NULL OR p.available_until > now()) AS is_available
FROM server.props p
WHERE p.is_active = true
AND p.is_public = true
ORDER BY p.name ASC
"#, "#,
) )
.bind(user_id)
.fetch_all(executor) .fetch_all(executor)
.await?; .await?;
Ok(props) Ok(props)
} }
/// List all public realm props for a specific realm. /// List public realm props with optional acquisition status.
/// ///
/// Returns props that are: /// Returns props that are active and public in the specified realm, with flags indicating:
/// - In the specified realm /// - `user_owns`: Whether the user already has this prop (false if no user_id)
/// - Active (`is_active = true`) /// - `is_claimed`: Whether a unique prop has been claimed by anyone
/// - Public (`is_public = true`) /// - `is_available`: Whether the prop is within its availability window
/// - Currently available (within availability window if set) ///
pub async fn list_public_realm_props<'e>( /// When `user_id` is None, returns default values for user-specific fields.
pub async fn list_realm_props<'e>(
executor: impl PgExecutor<'e>, executor: impl PgExecutor<'e>,
realm_id: Uuid, realm_id: Uuid,
) -> Result<Vec<PublicProp>, AppError> { user_id: Option<Uuid>,
let props = sqlx::query_as::<_, PublicProp>( ) -> Result<Vec<PropAcquisitionInfo>, AppError> {
let props = sqlx::query_as::<_, PropAcquisitionInfo>(
r#" r#"
SELECT SELECT
id, p.id,
name, p.name,
asset_path, p.asset_path,
description p.description,
FROM realm.props p.is_unique,
WHERE realm_id = $1 CASE
AND is_active = true WHEN $2::uuid IS NOT NULL THEN EXISTS(
AND is_public = true SELECT 1 FROM auth.inventory i
AND (available_from IS NULL OR available_from <= now()) WHERE i.user_id = $2 AND i.realm_prop_id = p.id
AND (available_until IS NULL OR available_until > now()) )
ORDER BY name ASC ELSE false
END AS user_owns,
CASE
WHEN p.is_unique THEN EXISTS(
SELECT 1 FROM auth.inventory i WHERE i.realm_prop_id = p.id
)
ELSE false
END AS is_claimed,
(p.available_from IS NULL OR p.available_from <= now())
AND (p.available_until IS NULL OR p.available_until > now()) AS is_available
FROM realm.props p
WHERE p.realm_id = $1
AND p.is_active = true
AND p.is_public = true
ORDER BY p.name ASC
"#, "#,
) )
.bind(realm_id) .bind(realm_id)
.bind(user_id)
.fetch_all(executor) .fetch_all(executor)
.await?; .await?;
Ok(props) Ok(props)
} }
/// Acquire a server prop into user's inventory.
///
/// Atomically validates and acquires the prop:
/// - Validates prop is active, public, within availability window
/// - For unique props: checks no one owns it yet
/// - For non-unique props: checks user doesn't already own it
/// - Inserts into `auth.inventory` with `origin = server_library`
///
/// Returns the created inventory item or an appropriate error.
pub async fn acquire_server_prop<'e>(
executor: impl PgExecutor<'e>,
prop_id: Uuid,
user_id: Uuid,
) -> Result<InventoryItem, AppError> {
// Use a CTE to atomically check conditions and insert
let result: Option<InventoryItem> = sqlx::query_as(
r#"
WITH prop_check AS (
SELECT
p.id,
p.name,
p.asset_path,
p.default_layer,
p.is_unique,
p.is_transferable,
p.is_portable,
p.is_droppable,
p.is_active,
p.is_public,
(p.available_from IS NULL OR p.available_from <= now()) AS available_from_ok,
(p.available_until IS NULL OR p.available_until > now()) AS available_until_ok
FROM server.props p
WHERE p.id = $1
),
ownership_check AS (
SELECT
pc.*,
EXISTS(
SELECT 1 FROM auth.inventory i
WHERE i.user_id = $2 AND i.server_prop_id = $1
) AS user_owns,
CASE
WHEN pc.is_unique THEN EXISTS(
SELECT 1 FROM auth.inventory i WHERE i.server_prop_id = $1
)
ELSE false
END AS is_claimed
FROM prop_check pc
),
inserted AS (
INSERT INTO auth.inventory (
user_id,
server_prop_id,
prop_name,
prop_asset_path,
layer,
origin,
is_transferable,
is_portable,
is_droppable
)
SELECT
$2,
oc.id,
oc.name,
oc.asset_path,
oc.default_layer,
'server_library'::server.prop_origin,
oc.is_transferable,
oc.is_portable,
oc.is_droppable
FROM ownership_check oc
WHERE oc.is_active = true
AND oc.is_public = true
AND oc.available_from_ok = true
AND oc.available_until_ok = true
AND oc.user_owns = false
AND oc.is_claimed = false
RETURNING
id,
prop_name,
prop_asset_path,
layer,
is_transferable,
is_portable,
is_droppable,
origin,
acquired_at
)
SELECT * FROM inserted
"#,
)
.bind(prop_id)
.bind(user_id)
.fetch_optional(executor)
.await?;
match result {
Some(item) => Ok(item),
None => {
// Need to determine the specific error case
// We'll do a separate query to understand why it failed
Err(AppError::Conflict(
"Unable to acquire prop - it may not exist, not be available, or already owned"
.to_string(),
))
}
}
}
/// Get detailed acquisition error for a server prop.
///
/// This is called when acquire_server_prop fails to determine the specific error.
pub async fn get_server_prop_acquisition_error<'e>(
executor: impl PgExecutor<'e>,
prop_id: Uuid,
user_id: Uuid,
) -> Result<AppError, AppError> {
#[derive(sqlx::FromRow)]
#[allow(dead_code)]
struct PropStatus {
exists: bool,
is_active: bool,
is_public: bool,
is_available: bool,
is_unique: bool,
user_owns: bool,
is_claimed: bool,
}
let status: Option<PropStatus> = sqlx::query_as(
r#"
SELECT
true AS exists,
p.is_active,
p.is_public,
(p.available_from IS NULL OR p.available_from <= now())
AND (p.available_until IS NULL OR p.available_until > now()) AS is_available,
p.is_unique,
EXISTS(
SELECT 1 FROM auth.inventory i
WHERE i.user_id = $2 AND i.server_prop_id = $1
) AS user_owns,
CASE
WHEN p.is_unique THEN EXISTS(
SELECT 1 FROM auth.inventory i WHERE i.server_prop_id = $1
)
ELSE false
END AS is_claimed
FROM server.props p
WHERE p.id = $1
"#,
)
.bind(prop_id)
.bind(user_id)
.fetch_optional(executor)
.await?;
match status {
None => Ok(AppError::NotFound("Server prop not found".to_string())),
Some(s) if !s.is_active || !s.is_public => {
Ok(AppError::Forbidden("This prop is not available".to_string()))
}
Some(s) if !s.is_available => Ok(AppError::Forbidden(
"This prop is not currently available".to_string(),
)),
Some(s) if s.user_owns => Ok(AppError::Conflict("You already own this prop".to_string())),
Some(s) if s.is_claimed => Ok(AppError::Conflict(
"This unique prop has already been claimed by another user".to_string(),
)),
Some(_) => Ok(AppError::Internal(
"Unknown error acquiring prop".to_string(),
)),
}
}
/// Acquire a realm prop into user's inventory.
///
/// Atomically validates and acquires the prop:
/// - Validates prop belongs to realm, is active, public, within availability window
/// - For unique props: checks no one owns it yet
/// - For non-unique props: checks user doesn't already own it
/// - Inserts into `auth.inventory` with `origin = realm_library`
///
/// Returns the created inventory item or an appropriate error.
pub async fn acquire_realm_prop<'e>(
executor: impl PgExecutor<'e>,
prop_id: Uuid,
realm_id: Uuid,
user_id: Uuid,
) -> Result<InventoryItem, AppError> {
// Use a CTE to atomically check conditions and insert
let result: Option<InventoryItem> = sqlx::query_as(
r#"
WITH prop_check AS (
SELECT
p.id,
p.name,
p.asset_path,
p.default_layer,
p.is_unique,
p.is_transferable,
p.is_droppable,
p.is_active,
p.is_public,
(p.available_from IS NULL OR p.available_from <= now()) AS available_from_ok,
(p.available_until IS NULL OR p.available_until > now()) AS available_until_ok
FROM realm.props p
WHERE p.id = $1 AND p.realm_id = $2
),
ownership_check AS (
SELECT
pc.*,
EXISTS(
SELECT 1 FROM auth.inventory i
WHERE i.user_id = $3 AND i.realm_prop_id = $1
) AS user_owns,
CASE
WHEN pc.is_unique THEN EXISTS(
SELECT 1 FROM auth.inventory i WHERE i.realm_prop_id = $1
)
ELSE false
END AS is_claimed
FROM prop_check pc
),
inserted AS (
INSERT INTO auth.inventory (
user_id,
realm_prop_id,
prop_name,
prop_asset_path,
layer,
origin,
is_transferable,
is_portable,
is_droppable
)
SELECT
$3,
oc.id,
oc.name,
oc.asset_path,
oc.default_layer,
'realm_library'::server.prop_origin,
oc.is_transferable,
true, -- realm props are portable by default
oc.is_droppable
FROM ownership_check oc
WHERE oc.is_active = true
AND oc.is_public = true
AND oc.available_from_ok = true
AND oc.available_until_ok = true
AND oc.user_owns = false
AND oc.is_claimed = false
RETURNING
id,
prop_name,
prop_asset_path,
layer,
is_transferable,
is_portable,
is_droppable,
origin,
acquired_at
)
SELECT * FROM inserted
"#,
)
.bind(prop_id)
.bind(realm_id)
.bind(user_id)
.fetch_optional(executor)
.await?;
match result {
Some(item) => Ok(item),
None => {
// Need to determine the specific error case
Err(AppError::Conflict(
"Unable to acquire prop - it may not exist, not be available, or already owned"
.to_string(),
))
}
}
}
/// Get detailed acquisition error for a realm prop.
///
/// This is called when acquire_realm_prop fails to determine the specific error.
pub async fn get_realm_prop_acquisition_error<'e>(
executor: impl PgExecutor<'e>,
prop_id: Uuid,
realm_id: Uuid,
user_id: Uuid,
) -> Result<AppError, AppError> {
#[derive(sqlx::FromRow)]
#[allow(dead_code)]
struct PropStatus {
exists: bool,
is_active: bool,
is_public: bool,
is_available: bool,
is_unique: bool,
user_owns: bool,
is_claimed: bool,
}
let status: Option<PropStatus> = sqlx::query_as(
r#"
SELECT
true AS exists,
p.is_active,
p.is_public,
(p.available_from IS NULL OR p.available_from <= now())
AND (p.available_until IS NULL OR p.available_until > now()) AS is_available,
p.is_unique,
EXISTS(
SELECT 1 FROM auth.inventory i
WHERE i.user_id = $3 AND i.realm_prop_id = $1
) AS user_owns,
CASE
WHEN p.is_unique THEN EXISTS(
SELECT 1 FROM auth.inventory i WHERE i.realm_prop_id = $1
)
ELSE false
END AS is_claimed
FROM realm.props p
WHERE p.id = $1 AND p.realm_id = $2
"#,
)
.bind(prop_id)
.bind(realm_id)
.bind(user_id)
.fetch_optional(executor)
.await?;
match status {
None => Ok(AppError::NotFound("Realm prop not found".to_string())),
Some(s) if !s.is_active || !s.is_public => {
Ok(AppError::Forbidden("This prop is not available".to_string()))
}
Some(s) if !s.is_available => Ok(AppError::Forbidden(
"This prop is not currently available".to_string(),
)),
Some(s) if s.user_owns => Ok(AppError::Conflict("You already own this prop".to_string())),
Some(s) if s.is_claimed => Ok(AppError::Conflict(
"This unique prop has already been claimed by another user".to_string(),
)),
Some(_) => Ok(AppError::Internal(
"Unknown error acquiring prop".to_string(),
)),
}
}

View file

@ -8,6 +8,30 @@ use uuid::Uuid;
use crate::models::{InventoryItem, LooseProp}; use crate::models::{InventoryItem, LooseProp};
use chattyness_error::AppError; use chattyness_error::AppError;
/// Ensure an instance exists for a scene.
///
/// In this system, scenes are used directly as instances (channel_id = scene_id).
/// This creates an instance record if one doesn't exist, using the scene_id as the instance_id.
/// This is needed for loose_props foreign key constraint.
pub async fn ensure_scene_instance<'e>(
executor: impl PgExecutor<'e>,
scene_id: Uuid,
) -> Result<(), AppError> {
sqlx::query(
r#"
INSERT INTO scene.instances (id, scene_id, instance_type)
SELECT $1, $1, 'public'::scene.instance_type
WHERE EXISTS (SELECT 1 FROM realm.scenes WHERE id = $1)
ON CONFLICT (id) DO NOTHING
"#,
)
.bind(scene_id)
.execute(executor)
.await?;
Ok(())
}
/// List all loose props in a channel (excluding expired). /// List all loose props in a channel (excluding expired).
pub async fn list_channel_loose_props<'e>( pub async fn list_channel_loose_props<'e>(
executor: impl PgExecutor<'e>, executor: impl PgExecutor<'e>,
@ -106,8 +130,8 @@ pub async fn drop_prop_to_canvas<'e>(
instance_id as channel_id, instance_id as channel_id,
server_prop_id, server_prop_id,
realm_prop_id, realm_prop_id,
ST_X(position) as position_x, ST_X(position)::real as position_x,
ST_Y(position) as position_y, ST_Y(position)::real as position_y,
dropped_by, dropped_by,
expires_at, expires_at,
created_at created_at

View file

@ -8,66 +8,194 @@ use sqlx::PgPool;
use uuid::Uuid; use uuid::Uuid;
use chattyness_db::{ use chattyness_db::{
models::{InventoryResponse, PublicPropsResponse}, User,
models::{
AcquirePropRequest, AcquirePropResponse, InventoryResponse, PropAcquisitionListResponse,
},
queries::{inventory, realms}, queries::{inventory, realms},
}; };
use chattyness_error::AppError; use chattyness_error::AppError;
use crate::auth::{AuthUser, RlsConn}; use crate::auth::{AuthUser, OptionalAuthUser, RlsConn};
/// Get user's full inventory. /// Get user's full inventory.
/// ///
/// GET /api/inventory /// GET /api/user/{uuid}/inventory
pub async fn get_inventory( ///
/// Supports "me" as a special UUID value to get the current user's inventory.
pub async fn get_user_inventory(
rls_conn: RlsConn, rls_conn: RlsConn,
AuthUser(user): AuthUser, AuthUser(user): AuthUser,
Path(uuid_str): Path<String>,
) -> Result<Json<InventoryResponse>, AppError> { ) -> Result<Json<InventoryResponse>, AppError> {
let mut conn = rls_conn.acquire().await; // Resolve "me" to current user ID, otherwise parse UUID
let target_user_id = if uuid_str.eq_ignore_ascii_case("me") {
user.id
} else {
uuid_str.parse::<Uuid>().map_err(|_| {
AppError::Validation(format!("Invalid user UUID: {}", uuid_str))
})?
};
let items = inventory::list_user_inventory(&mut *conn, user.id).await?; // For now, users can only view their own inventory
if target_user_id != user.id {
return Err(AppError::Forbidden(
"You can only view your own inventory".to_string(),
));
}
let mut conn = rls_conn.acquire().await;
let items = inventory::list_user_inventory(&mut *conn, target_user_id).await?;
Ok(Json(InventoryResponse { items })) Ok(Json(InventoryResponse { items }))
} }
/// Drop an item from inventory. /// Drop an item from inventory.
/// ///
/// DELETE /api/inventory/{item_id} /// DELETE /api/user/{uuid}/inventory/{item_id}
pub async fn drop_item( pub async fn drop_item(
rls_conn: RlsConn, rls_conn: RlsConn,
AuthUser(user): AuthUser, AuthUser(user): AuthUser,
Path(item_id): Path<Uuid>, Path((uuid_str, item_id)): Path<(String, Uuid)>,
) -> Result<Json<serde_json::Value>, AppError> { ) -> Result<Json<serde_json::Value>, AppError> {
let mut conn = rls_conn.acquire().await; // Resolve "me" to current user ID
let target_user_id = if uuid_str.eq_ignore_ascii_case("me") {
user.id
} else {
uuid_str.parse::<Uuid>().map_err(|_| {
AppError::Validation(format!("Invalid user UUID: {}", uuid_str))
})?
};
// Users can only drop from their own inventory
if target_user_id != user.id {
return Err(AppError::Forbidden(
"You can only drop items from your own inventory".to_string(),
));
}
let mut conn = rls_conn.acquire().await;
inventory::drop_inventory_item(&mut *conn, user.id, item_id).await?; inventory::drop_inventory_item(&mut *conn, user.id, item_id).await?;
Ok(Json(serde_json::json!({ "success": true }))) Ok(Json(serde_json::json!({ "success": true })))
} }
/// Get public server props. /// Get server prop catalog.
/// ///
/// GET /api/inventory/server /// GET /api/server/inventory
///
/// Returns all public server props. If the user is authenticated (non-guest),
/// includes acquisition status (user_owns, is_claimed, is_available).
/// For guests/unauthenticated, returns default status values.
pub async fn get_server_props( pub async fn get_server_props(
State(pool): State<PgPool>, State(pool): State<PgPool>,
) -> Result<Json<PublicPropsResponse>, AppError> { OptionalAuthUser(maybe_user): OptionalAuthUser,
let props = inventory::list_public_server_props(&pool).await?; ) -> Result<Json<PropAcquisitionListResponse>, AppError> {
// Get user_id if authenticated and not a guest
let user_id = maybe_user
.as_ref()
.filter(|u: &&User| !u.is_guest())
.map(|u| u.id);
Ok(Json(PublicPropsResponse { props })) let props = inventory::list_server_props(&pool, user_id).await?;
Ok(Json(PropAcquisitionListResponse { props }))
} }
/// Get public realm props. /// Get realm prop catalog.
/// ///
/// GET /api/realms/{slug}/inventory /// GET /api/realms/{slug}/inventory
///
/// Returns all public realm props for the specified realm. If the user is authenticated
/// (non-guest), includes acquisition status. For guests/unauthenticated, returns default status.
pub async fn get_realm_props( pub async fn get_realm_props(
State(pool): State<PgPool>, State(pool): State<PgPool>,
OptionalAuthUser(maybe_user): OptionalAuthUser,
Path(slug): Path<String>, Path(slug): Path<String>,
) -> Result<Json<PublicPropsResponse>, AppError> { ) -> Result<Json<PropAcquisitionListResponse>, AppError> {
// Get the realm by slug to get its ID // Get the realm by slug to get its ID
let realm = realms::get_realm_by_slug(&pool, &slug) let realm = realms::get_realm_by_slug(&pool, &slug)
.await? .await?
.ok_or_else(|| AppError::NotFound(format!("Realm '{}' not found", slug)))?; .ok_or_else(|| AppError::NotFound(format!("Realm '{}' not found", slug)))?;
let props = inventory::list_public_realm_props(&pool, realm.id).await?; // Get user_id if authenticated and not a guest
let user_id = maybe_user
.as_ref()
.filter(|u: &&User| !u.is_guest())
.map(|u| u.id);
Ok(Json(PublicPropsResponse { props })) let props = inventory::list_realm_props(&pool, realm.id, user_id).await?;
Ok(Json(PropAcquisitionListResponse { props }))
}
/// Acquire a server prop into user's inventory.
///
/// POST /api/server/inventory/request
pub async fn acquire_server_prop(
rls_conn: RlsConn,
AuthUser(user): AuthUser,
Json(req): Json<AcquirePropRequest>,
) -> Result<Json<AcquirePropResponse>, AppError> {
// Guests cannot acquire props
if user.is_guest() {
return Err(AppError::Forbidden(
"Guests cannot acquire props".to_string(),
));
}
let mut conn = rls_conn.acquire().await;
// Try to acquire the prop
match inventory::acquire_server_prop(&mut *conn, req.prop_id, user.id).await {
Ok(item) => Ok(Json(AcquirePropResponse { item })),
Err(_) => {
// Get the specific error reason
let error =
inventory::get_server_prop_acquisition_error(&mut *conn, req.prop_id, user.id)
.await?;
Err(error)
}
}
}
/// Acquire a realm prop into user's inventory.
///
/// POST /api/realms/{slug}/inventory/request
pub async fn acquire_realm_prop(
rls_conn: RlsConn,
State(pool): State<PgPool>,
AuthUser(user): AuthUser,
Path(slug): Path<String>,
Json(req): Json<AcquirePropRequest>,
) -> Result<Json<AcquirePropResponse>, AppError> {
// Guests cannot acquire props
if user.is_guest() {
return Err(AppError::Forbidden(
"Guests cannot acquire props".to_string(),
));
}
// Get the realm by slug to get its ID
let realm = realms::get_realm_by_slug(&pool, &slug)
.await?
.ok_or_else(|| AppError::NotFound(format!("Realm '{}' not found", slug)))?;
let mut conn = rls_conn.acquire().await;
// Try to acquire the prop
match inventory::acquire_realm_prop(&mut *conn, req.prop_id, realm.id, user.id).await {
Ok(item) => Ok(Json(AcquirePropResponse { item })),
Err(_) => {
// Get the specific error reason
let error = inventory::get_realm_prop_acquisition_error(
&mut *conn,
req.prop_id,
realm.id,
user.id,
)
.await?;
Err(error)
}
}
} }

View file

@ -58,13 +58,22 @@ pub fn api_router() -> Router<AppState> {
"/realms/{slug}/avatar/slot", "/realms/{slug}/avatar/slot",
axum::routing::put(avatars::assign_slot).delete(avatars::clear_slot), axum::routing::put(avatars::assign_slot).delete(avatars::clear_slot),
) )
// Inventory routes (require authentication) // User inventory routes
.route("/inventory", get(inventory::get_inventory)) .route("/user/{uuid}/inventory", get(inventory::get_user_inventory))
.route( .route(
"/inventory/{item_id}", "/user/{uuid}/inventory/{item_id}",
axum::routing::delete(inventory::drop_item), axum::routing::delete(inventory::drop_item),
) )
// Public inventory routes (public server/realm props) // Server prop catalog (enriched if authenticated)
.route("/inventory/server", get(inventory::get_server_props)) .route("/server/inventory", get(inventory::get_server_props))
.route(
"/server/inventory/request",
axum::routing::post(inventory::acquire_server_prop),
)
// Realm prop catalog (enriched if authenticated)
.route("/realms/{slug}/inventory", get(inventory::get_realm_props)) .route("/realms/{slug}/inventory", get(inventory::get_realm_props))
.route(
"/realms/{slug}/inventory/request",
axum::routing::post(inventory::acquire_realm_prop),
)
} }

View file

@ -607,6 +607,20 @@ async fn handle_socket(
} }
} }
ClientMessage::DropProp { inventory_item_id } => { ClientMessage::DropProp { inventory_item_id } => {
// Ensure instance exists for this scene (required for loose_props FK)
// In this system, channel_id = scene_id
if let Err(e) = loose_props::ensure_scene_instance(
&mut *recv_conn,
channel_id,
)
.await
{
tracing::error!(
"[WS] Failed to ensure scene instance: {:?}",
e
);
}
// Get user's current position for random offset // Get user's current position for random offset
let member_info = channel_members::get_channel_member( let member_info = channel_members::get_channel_member(
&mut *recv_conn, &mut *recv_conn,

View file

@ -4,7 +4,7 @@ use leptos::prelude::*;
use leptos::reactive::owner::LocalStorage; use leptos::reactive::owner::LocalStorage;
use uuid::Uuid; use uuid::Uuid;
use chattyness_db::models::{InventoryItem, PublicProp}; use chattyness_db::models::{InventoryItem, PropAcquisitionInfo};
#[cfg(feature = "hydrate")] #[cfg(feature = "hydrate")]
use chattyness_db::ws_messages::ClientMessage; use chattyness_db::ws_messages::ClientMessage;
@ -46,13 +46,13 @@ pub fn InventoryPopup(
let (selected_item, set_selected_item) = signal(Option::<Uuid>::None); let (selected_item, set_selected_item) = signal(Option::<Uuid>::None);
let (dropping, set_dropping) = signal(false); let (dropping, set_dropping) = signal(false);
// Server props state // Server props state (with acquisition info for authenticated users)
let (server_props, set_server_props) = signal(Vec::<PublicProp>::new()); let (server_props, set_server_props) = signal(Vec::<PropAcquisitionInfo>::new());
let (server_loading, set_server_loading) = signal(false); let (server_loading, set_server_loading) = signal(false);
let (server_error, set_server_error) = signal(Option::<String>::None); let (server_error, set_server_error) = signal(Option::<String>::None);
// Realm props state // Realm props state (with acquisition info for authenticated users)
let (realm_props, set_realm_props) = signal(Vec::<PublicProp>::new()); let (realm_props, set_realm_props) = signal(Vec::<PropAcquisitionInfo>::new());
let (realm_loading, set_realm_loading) = signal(false); let (realm_loading, set_realm_loading) = signal(false);
let (realm_error, set_realm_error) = signal(Option::<String>::None); let (realm_error, set_realm_error) = signal(Option::<String>::None);
@ -61,6 +61,9 @@ pub fn InventoryPopup(
let (server_loaded, set_server_loaded) = signal(false); let (server_loaded, set_server_loaded) = signal(false);
let (realm_loaded, set_realm_loaded) = signal(false); let (realm_loaded, set_realm_loaded) = signal(false);
// Trigger to refresh my inventory after acquisition
let (inventory_refresh_trigger, set_inventory_refresh_trigger) = signal(0u32);
// Fetch my inventory when popup opens or tab is selected // Fetch my inventory when popup opens or tab is selected
#[cfg(feature = "hydrate")] #[cfg(feature = "hydrate")]
{ {
@ -68,6 +71,9 @@ pub fn InventoryPopup(
use leptos::task::spawn_local; use leptos::task::spawn_local;
Effect::new(move |_| { Effect::new(move |_| {
// Track refresh trigger to refetch after acquisition
let _refresh = inventory_refresh_trigger.get();
if !open.get() { if !open.get() {
// Reset state when closing // Reset state when closing
set_selected_item.set(None); set_selected_item.set(None);
@ -86,7 +92,7 @@ pub fn InventoryPopup(
set_error.set(None); set_error.set(None);
spawn_local(async move { spawn_local(async move {
let response = Request::get("/api/inventory").send().await; let response = Request::get("/api/user/me/inventory").send().await;
match response { match response {
Ok(resp) if resp.ok() => { Ok(resp) if resp.ok() => {
if let Ok(data) = resp if let Ok(data) = resp
@ -112,6 +118,7 @@ pub fn InventoryPopup(
} }
// Fetch server props when server tab is selected // Fetch server props when server tab is selected
// Uses status endpoint if authenticated (non-guest), otherwise basic endpoint
#[cfg(feature = "hydrate")] #[cfg(feature = "hydrate")]
{ {
use gloo_net::http::Request; use gloo_net::http::Request;
@ -126,17 +133,19 @@ pub fn InventoryPopup(
set_server_error.set(None); set_server_error.set(None);
spawn_local(async move { spawn_local(async move {
let response = Request::get("/api/inventory/server").send().await; // Single endpoint returns enriched data if authenticated
let response = Request::get("/api/server/inventory").send().await;
match response { match response {
Ok(resp) if resp.ok() => { Ok(resp) if resp.ok() => {
if let Ok(data) = resp if let Ok(data) = resp
.json::<chattyness_db::models::PublicPropsResponse>() .json::<chattyness_db::models::PropAcquisitionListResponse>()
.await .await
{ {
set_server_props.set(data.props); set_server_props.set(data.props);
set_server_loaded.set(true); set_server_loaded.set(true);
} else { } else {
set_server_error.set(Some("Failed to parse server props".to_string())); set_server_error
.set(Some("Failed to parse server props".to_string()));
} }
} }
Ok(resp) => { Ok(resp) => {
@ -175,19 +184,20 @@ pub fn InventoryPopup(
set_realm_error.set(None); set_realm_error.set(None);
spawn_local(async move { spawn_local(async move {
let response = Request::get(&format!("/api/realms/{}/inventory", slug)) // Single endpoint returns enriched data if authenticated
.send() let endpoint = format!("/api/realms/{}/inventory", slug);
.await; let response = Request::get(&endpoint).send().await;
match response { match response {
Ok(resp) if resp.ok() => { Ok(resp) if resp.ok() => {
if let Ok(data) = resp if let Ok(data) = resp
.json::<chattyness_db::models::PublicPropsResponse>() .json::<chattyness_db::models::PropAcquisitionListResponse>()
.await .await
{ {
set_realm_props.set(data.props); set_realm_props.set(data.props);
set_realm_loaded.set(true); set_realm_loaded.set(true);
} else { } else {
set_realm_error.set(Some("Failed to parse realm props".to_string())); set_realm_error
.set(Some("Failed to parse realm props".to_string()));
} }
} }
Ok(resp) => { Ok(resp) => {
@ -272,23 +282,40 @@ pub fn InventoryPopup(
// Server tab // Server tab
<Show when=move || active_tab.get() == "server"> <Show when=move || active_tab.get() == "server">
<PublicPropsTab <AcquisitionPropsTab
props=server_props props=server_props
set_props=set_server_props
loading=server_loading loading=server_loading
error=server_error error=server_error
tab_name="Server" tab_name="Server"
empty_message="No public server props available" empty_message="No public server props available"
is_guest=is_guest
acquire_endpoint="/api/server/inventory/request"
on_acquired=Callback::new(move |_| {
// Trigger inventory refresh and reset loaded state
set_my_inventory_loaded.set(false);
set_inventory_refresh_trigger.update(|n| *n += 1);
})
/> />
</Show> </Show>
// Realm tab // Realm tab
<Show when=move || active_tab.get() == "realm"> <Show when=move || active_tab.get() == "realm">
<PublicPropsTab <AcquisitionPropsTab
props=realm_props props=realm_props
set_props=set_realm_props
loading=realm_loading loading=realm_loading
error=realm_error error=realm_error
tab_name="Realm" tab_name="Realm"
empty_message="No public realm props available" empty_message="No public realm props available"
is_guest=is_guest
acquire_endpoint_is_realm=true
realm_slug=realm_slug
on_acquired=Callback::new(move |_| {
// Trigger inventory refresh and reset loaded state
set_my_inventory_loaded.set(false);
set_inventory_refresh_trigger.update(|n| *n += 1);
})
/> />
</Show> </Show>
</div> </div>
@ -450,17 +477,103 @@ fn MyInventoryTab(
} }
} }
/// Public props tab content (read-only display). /// Acquisition props tab content with acquire functionality.
#[component] #[component]
fn PublicPropsTab( fn AcquisitionPropsTab(
#[prop(into)] props: Signal<Vec<PublicProp>>, #[prop(into)] props: Signal<Vec<PropAcquisitionInfo>>,
set_props: WriteSignal<Vec<PropAcquisitionInfo>>,
#[prop(into)] loading: Signal<bool>, #[prop(into)] loading: Signal<bool>,
#[prop(into)] error: Signal<Option<String>>, #[prop(into)] error: Signal<Option<String>>,
tab_name: &'static str, tab_name: &'static str,
empty_message: &'static str, empty_message: &'static str,
#[prop(into)] is_guest: Signal<bool>,
/// Static endpoint for server props (e.g., "/api/server/inventory/request")
#[prop(optional)]
acquire_endpoint: Option<&'static str>,
/// Whether this is a realm props tab (uses dynamic endpoint with slug)
#[prop(optional, default = false)]
acquire_endpoint_is_realm: bool,
/// Realm slug for realm prop acquisition (required if acquire_endpoint_is_realm is true)
#[prop(optional, into)]
realm_slug: Signal<String>,
#[prop(into)] on_acquired: Callback<()>,
) -> impl IntoView { ) -> impl IntoView {
// Selected prop for showing details // Selected prop for showing details
let (selected_prop, set_selected_prop) = signal(Option::<Uuid>::None); let (selected_prop, set_selected_prop) = signal(Option::<Uuid>::None);
let (acquiring, set_acquiring) = signal(false);
let (acquire_error, set_acquire_error) = signal(Option::<String>::None);
// Handle acquire action
let acquire_endpoint_opt = acquire_endpoint.map(|s| s.to_string());
let do_acquire = Callback::new(move |prop_id: Uuid| {
#[cfg(feature = "hydrate")]
{
set_acquiring.set(true);
set_acquire_error.set(None);
let endpoint = if acquire_endpoint_is_realm {
let slug = realm_slug.get();
if slug.is_empty() {
set_acquire_error.set(Some("No realm selected".to_string()));
set_acquiring.set(false);
return;
}
format!("/api/realms/{}/inventory/request", slug)
} else {
acquire_endpoint_opt.clone().unwrap_or_default()
};
let on_acquired = on_acquired.clone();
leptos::task::spawn_local(async move {
use gloo_net::http::Request;
// Simple body with just prop_id - realm_id comes from URL for realm props
let body = serde_json::json!({
"prop_id": prop_id
});
let response = Request::post(&endpoint)
.header("Content-Type", "application/json")
.body(body.to_string())
.unwrap()
.send()
.await;
match response {
Ok(resp) if resp.ok() => {
// Update local state to mark prop as owned
set_props.update(|props| {
if let Some(prop) = props.iter_mut().find(|p| p.id == prop_id) {
prop.user_owns = true;
}
});
// Notify parent to refresh inventory
on_acquired.run(());
}
Ok(resp) => {
// Try to parse error message from response
if let Ok(error_json) = resp.json::<serde_json::Value>().await {
let error_msg = error_json
.get("error")
.and_then(|e| e.as_str())
.unwrap_or("Unknown error");
set_acquire_error.set(Some(error_msg.to_string()));
} else {
set_acquire_error.set(Some(format!(
"Failed to acquire prop: {}",
resp.status()
)));
}
}
Err(e) => {
set_acquire_error.set(Some(format!("Network error: {}", e)));
}
}
set_acquiring.set(false);
});
}
});
view! { view! {
// Loading state // Loading state
@ -477,6 +590,13 @@ fn PublicPropsTab(
</div> </div>
</Show> </Show>
// Acquire error state
<Show when=move || acquire_error.get().is_some()>
<div class="bg-red-900/20 border border-red-600 rounded p-4 mb-4">
<p class="text-red-400">{move || acquire_error.get().unwrap_or_default()}</p>
</div>
</Show>
// Empty state // Empty state
<Show when=move || !loading.get() && error.get().is_none() && props.get().is_empty()> <Show when=move || !loading.get() && error.get().is_none() && props.get().is_empty()>
<div class="flex flex-col items-center justify-center py-12 text-center"> <div class="flex flex-col items-center justify-center py-12 text-center">
@ -501,7 +621,7 @@ fn PublicPropsTab(
<For <For
each=move || props.get() each=move || props.get()
key=|prop| prop.id key=|prop| prop.id
children=move |prop: PublicProp| { children=move |prop: PropAcquisitionInfo| {
let prop_id = prop.id; let prop_id = prop.id;
let prop_name = prop.name.clone(); let prop_name = prop.name.clone();
let is_selected = move || selected_prop.get() == Some(prop_id); let is_selected = move || selected_prop.get() == Some(prop_id);
@ -511,13 +631,21 @@ fn PublicPropsTab(
format!("/static/{}", prop.asset_path) format!("/static/{}", prop.asset_path)
}; };
// Visual indicator for ownership status
let user_owns = prop.user_owns;
let is_claimed = prop.is_claimed;
view! { view! {
<button <button
type="button" type="button"
class=move || format!( class=move || format!(
"aspect-square rounded-lg border-2 transition-all p-1 focus:outline-none focus:ring-2 focus:ring-blue-500 {}", "aspect-square rounded-lg border-2 transition-all p-1 focus:outline-none focus:ring-2 focus:ring-blue-500 relative {}",
if is_selected() { if is_selected() {
"border-blue-500 bg-blue-900/30" "border-blue-500 bg-blue-900/30"
} else if user_owns {
"border-green-500/50 bg-green-900/20"
} else if is_claimed {
"border-red-500/50 bg-red-900/20 opacity-50"
} else { } else {
"border-gray-600 hover:border-gray-500 bg-gray-700/50" "border-gray-600 hover:border-gray-500 bg-gray-700/50"
} }
@ -534,27 +662,63 @@ fn PublicPropsTab(
alt="" alt=""
class="w-full h-full object-contain" class="w-full h-full object-contain"
/> />
// Ownership badge
<Show when=move || user_owns>
<span class="absolute top-0 right-0 w-3 h-3 bg-green-500 rounded-full transform translate-x-1 -translate-y-1" title="Owned" />
</Show>
</button> </button>
} }
} }
/> />
</div> </div>
// Selected prop details (read-only) // Selected prop details with acquire button
{move || { {move || {
let prop_id = selected_prop.get()?; let prop_id = selected_prop.get()?;
let prop = props.get().into_iter().find(|p| p.id == prop_id)?; let prop = props.get().into_iter().find(|p| p.id == prop_id)?;
let guest = is_guest.get();
let is_acquiring = acquiring.get();
// Determine button state
let (button_text, button_class, button_disabled, button_title) = if guest {
("Sign in to Acquire", "bg-gray-600 text-gray-400 cursor-not-allowed", true, "Guests cannot acquire props")
} else if prop.user_owns {
("Already Owned", "bg-green-700 text-white cursor-default", true, "You already own this prop")
} else if prop.is_claimed && prop.is_unique {
("Claimed", "bg-red-700 text-white cursor-not-allowed", true, "This unique prop has been claimed by another user")
} else if !prop.is_available {
("Unavailable", "bg-gray-600 text-gray-400 cursor-not-allowed", true, "This prop is not currently available")
} else if is_acquiring {
("Acquiring...", "bg-blue-600 text-white opacity-50", true, "")
} else {
("Acquire", "bg-blue-600 hover:bg-blue-700 text-white", false, "Add this prop to your inventory")
};
let prop_name = prop.name.clone();
let prop_description = prop.description.clone();
Some(view! { Some(view! {
<div class="mt-4 pt-4 border-t border-gray-700"> <div class="mt-4 pt-4 border-t border-gray-700">
<div class="flex items-center justify-between"> <div class="flex items-center justify-between">
<div> <div>
<h3 class="text-white font-medium">{prop.name.clone()}</h3> <h3 class="text-white font-medium">{prop_name}</h3>
{prop.description.map(|desc| view! { {prop_description.map(|desc| view! {
<p class="text-gray-400 text-sm">{desc}</p> <p class="text-gray-400 text-sm">{desc}</p>
})} })}
</div> </div>
<p class="text-gray-500 text-sm italic">"View only"</p> <button
type="button"
class=format!("px-4 py-2 rounded-lg transition-colors {}", button_class)
on:click=move |_| {
if !button_disabled {
do_acquire.run(prop_id);
}
}
disabled=button_disabled
title=button_title
>
{button_text}
</button>
</div> </div>
</div> </div>
}) })
@ -563,3 +727,4 @@ fn PublicPropsTab(
</Show> </Show>
} }
} }

View file

@ -71,9 +71,10 @@ COMMENT ON TYPE server.portability IS 'Whether prop can be used outside origin r
CREATE TYPE server.avatar_layer AS ENUM ( CREATE TYPE server.avatar_layer AS ENUM (
'skin', -- Background layer (behind user, body/face) 'skin', -- Background layer (behind user, body/face)
'clothes', -- Middle layer (with user, worn items) 'clothes', -- Middle layer (with user, worn items)
'accessories' -- Foreground layer (in front of user, held/attached items) 'accessories', -- Foreground layer (in front of user, held/attached items)
'emote' -- Facial expression layer (overlays face)
); );
COMMENT ON TYPE server.avatar_layer IS 'Z-layer for avatar prop positioning: skin (behind), clothes (with), accessories (front)'; COMMENT ON TYPE server.avatar_layer IS 'Z-layer for avatar prop positioning: skin (behind), clothes (with), accessories (front), emote (expressions)';
-- Emotion state for avatar overlays (moved from props schema) -- Emotion state for avatar overlays (moved from props schema)
CREATE TYPE server.emotion_state AS ENUM ( CREATE TYPE server.emotion_state AS ENUM (

View file

@ -58,24 +58,16 @@ capitalize() {
} }
# Function to determine tags based on filename # Function to determine tags based on filename
# Tags complement default_layer/default_emotion - avoid redundant info # Tags complement default_layer - avoid redundant info
get_tags() { get_tags() {
local filename="$1" local filename="$1"
case "$filename" in case "$filename" in
face.svg) face.svg)
# Content layer prop - "skin" is already in default_layer # Base face prop - "skin" is already in default_layer
echo '["base", "face"]' echo '["base", "face"]'
;; ;;
smile.svg | happy.svg | neutral.svg | sad.svg | angry.svg | surprised.svg | thinking.svg | laughing.svg | crying.svg | love.svg | confused.svg) neutral.svg | smile.svg | sad.svg | angry.svg | surprised.svg | thinking.svg | laughing.svg | crying.svg | love.svg | confused.svg | sleeping.svg | wink.svg)
# Emotion props - emotion is already in default_emotion # Facial expression props - "emote" is already in default_layer
echo '["face"]'
;;
sleeping.svg)
# Emotion prop for sleeping
echo '["face"]'
;;
wink.svg)
# Emotion prop for wink
echo '["face"]' echo '["face"]'
;; ;;
*) *)
@ -85,7 +77,7 @@ get_tags() {
} }
# Function to get positioning fields based on filename # Function to get positioning fields based on filename
# Returns: "layer:<value>" for content layer props, "emotion:<value>" for emotion props, "none" for generic props # Returns: "layer:<value>" for content layer props, "none" for generic props
get_positioning() { get_positioning() {
local filename="$1" local filename="$1"
case "$filename" in case "$filename" in
@ -93,41 +85,9 @@ get_positioning() {
# Base face is a content layer prop (skin layer) # Base face is a content layer prop (skin layer)
echo "layer:skin" echo "layer:skin"
;; ;;
neutral.svg) neutral.svg | smile.svg | sad.svg | angry.svg | surprised.svg | thinking.svg | laughing.svg | crying.svg | love.svg | confused.svg | sleeping.svg | wink.svg)
echo "emotion:neutral" # Facial expression props use the emote layer
;; echo "layer:emote"
smile.svg)
echo "emotion:happy"
;;
sad.svg)
echo "emotion:sad"
;;
angry.svg)
echo "emotion:angry"
;;
surprised.svg)
echo "emotion:surprised"
;;
thinking.svg)
echo "emotion:thinking"
;;
laughing.svg)
echo "emotion:laughing"
;;
crying.svg)
echo "emotion:crying"
;;
love.svg)
echo "emotion:love"
;;
confused.svg)
echo "emotion:confused"
;;
sleeping.svg)
echo "emotion:sleeping"
;;
wink.svg)
echo "emotion:wink"
;; ;;
*) *)
echo "none" echo "none"
@ -159,13 +119,9 @@ for file in "$STOCKAVATAR_DIR"/*.svg; do
case "$positioning_type" in case "$positioning_type" in
layer) layer)
# Content layer prop # Content layer prop (skin, clothes, accessories, emote)
positioning_json="\"default_layer\": \"$positioning_value\", \"default_position\": 4" positioning_json="\"default_layer\": \"$positioning_value\", \"default_position\": 4"
;; ;;
emotion)
# Emotion layer prop
positioning_json="\"default_emotion\": \"$positioning_value\", \"default_position\": 4"
;;
*) *)
# Generic prop (no default positioning) # Generic prop (no default positioning)
positioning_json="" positioning_json=""