63 lines
1.4 KiB
Rust
63 lines
1.4 KiB
Rust
|
use mongod::{
|
||
|
assert_reference_of,
|
||
|
derive::{Model, Referencable},
|
||
|
Model, Referencable, Reference, Validate,
|
||
|
};
|
||
|
use mongodb::bson::doc;
|
||
|
use serde::{Deserialize, Serialize};
|
||
|
|
||
|
use crate::library::user::User;
|
||
|
|
||
|
use super::track::Track;
|
||
|
|
||
|
#[derive(Debug, Clone, Serialize, Deserialize, Model, Referencable)]
|
||
|
pub struct Event {
|
||
|
pub _id: String,
|
||
|
pub kind: EventKind,
|
||
|
pub user: Reference,
|
||
|
pub track: Reference,
|
||
|
pub timestamp: i64,
|
||
|
}
|
||
|
|
||
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||
|
pub enum EventKind {
|
||
|
Play,
|
||
|
Played,
|
||
|
Stop,
|
||
|
}
|
||
|
|
||
|
impl Event {
|
||
|
pub async fn create(kind: EventKind, user: &User, track: Reference) -> Self {
|
||
|
let event = Self {
|
||
|
_id: uuid::Uuid::new_v4().to_string(),
|
||
|
kind: kind,
|
||
|
user: user.reference(),
|
||
|
track,
|
||
|
timestamp: chrono::Utc::now().timestamp(),
|
||
|
};
|
||
|
|
||
|
event.insert().await.unwrap();
|
||
|
|
||
|
event
|
||
|
}
|
||
|
|
||
|
pub async fn get_latest_events_of(u: &User) -> Vec<Self> {
|
||
|
Self::find(
|
||
|
doc! { "user": u.reference() },
|
||
|
Some(300),
|
||
|
Some(doc! { "timestamp": -1 }),
|
||
|
)
|
||
|
.await
|
||
|
.unwrap()
|
||
|
}
|
||
|
}
|
||
|
|
||
|
impl Validate for Event {
|
||
|
async fn validate(&self) -> Result<(), String> {
|
||
|
assert_reference_of!(self.user, User);
|
||
|
assert_reference_of!(self.track, Track);
|
||
|
|
||
|
Ok(())
|
||
|
}
|
||
|
}
|