synthwave/src/library/event.rs

63 lines
1.8 KiB
Rust
Raw Normal View History

2024-12-18 17:59:00 +00:00
use based::{auth::User, get_pg};
2024-08-16 23:25:41 +00:00
use serde::{Deserialize, Serialize};
2024-10-04 10:00:33 +00:00
use sqlx::prelude::FromRow;
2024-08-16 23:25:41 +00:00
2024-10-05 23:12:26 +00:00
/// Represents a user event in the database.
2024-10-04 10:00:33 +00:00
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
2024-08-16 23:25:41 +00:00
pub struct Event {
2024-10-05 23:12:26 +00:00
/// Unique identifier for this event.
2024-10-04 10:00:33 +00:00
pub id: uuid::Uuid,
2024-10-05 23:12:26 +00:00
/// Timestamp of when this event occurred.
2024-10-04 17:39:51 +00:00
pub time: chrono::DateTime<chrono::Utc>,
2024-10-05 23:12:26 +00:00
/// Type of event (e.g. play, stop).
2024-08-16 23:25:41 +00:00
pub kind: EventKind,
2024-10-05 23:12:26 +00:00
/// Username of the user who performed this action.
2024-10-04 10:00:33 +00:00
pub user: String,
2024-10-05 23:12:26 +00:00
/// ID of the track associated with this event.
2024-10-04 10:00:33 +00:00
pub track: uuid::Uuid,
2024-08-16 23:25:41 +00:00
}
2024-10-05 23:12:26 +00:00
/// Enum representing different types of events that can occur.
2024-10-04 10:00:33 +00:00
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::Type)]
#[sqlx(type_name = "event_kind", rename_all = "lowercase")]
2024-08-16 23:25:41 +00:00
pub enum EventKind {
2024-10-05 23:12:26 +00:00
/// A user started playing a track.
2024-08-16 23:25:41 +00:00
Play,
2024-10-05 23:12:26 +00:00
/// A user finished playing a track.
2024-08-16 23:25:41 +00:00
Played,
2024-10-05 23:12:26 +00:00
/// A user stopped playing a track.
2024-08-16 23:25:41 +00:00
Stop,
}
impl Event {
2024-10-05 23:12:26 +00:00
/// Creates a new event in the database with the given kind, user, and track.
///
/// Returns the newly created event object.
2024-10-04 10:00:33 +00:00
pub async fn create(kind: EventKind, user: &User, track: uuid::Uuid) -> Self {
2024-10-04 17:39:51 +00:00
sqlx::query_as("INSERT INTO events (kind, \"user\", track) VALUES ($1, $2, $3) RETURNING *")
2024-10-04 10:00:33 +00:00
.bind(kind)
.bind(&user.username)
.bind(track)
.fetch_one(get_pg!())
.await
.unwrap()
2024-08-16 23:25:41 +00:00
}
2024-10-05 23:12:26 +00:00
/// Retrieves the latest 300 events performed by a given user.
///
/// Returns a vector of event objects.
2024-08-16 23:25:41 +00:00
pub async fn get_latest_events_of(u: &User) -> Vec<Self> {
2024-10-04 17:39:51 +00:00
sqlx::query_as("SELECT * FROM events WHERE \"user\" = $1 ORDER BY time DESC LIMIT 300")
2024-10-04 10:00:33 +00:00
.bind(&u.username)
.fetch_all(get_pg!())
.await
.unwrap()
2024-08-16 23:25:41 +00:00
}
}