Files
simple-instant-stream/crates/entity/src/stream_session.rs
T
2026-09-17 18:57:35 +01:00

90 lines
2.4 KiB
Rust

use sea_orm::{
ActiveValue::{NotSet, Set},
entity::prelude::*,
sea_query::Expr,
sqlx::types::chrono::{self, Utc},
};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "stream_session")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub stream_key_id: i32,
pub started_at: DateTimeUtc,
pub ended_at: Option<DateTimeUtc>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::stream_key::Entity",
from = "Column::StreamKeyId",
to = "super::stream_key::Column::Id"
)]
StreamKey,
}
impl Related<super::stream_key::Entity> for Entity {
fn to() -> RelationDef {
Relation::StreamKey.def()
}
}
impl ActiveModelBehavior for ActiveModel {}
impl Model {
pub async fn create_stream_session(
db: &DatabaseConnection,
stream_key_id: i32,
started_at: chrono::DateTime<Utc>,
) -> Result<Model, DbErr> {
ActiveModel {
id: NotSet,
stream_key_id: Set(stream_key_id),
started_at: Set(started_at),
ended_at: NotSet,
..Default::default()
}
.insert(db)
.await
}
pub async fn get_all_active_sessions(db: &DatabaseConnection) -> Result<Vec<Model>, DbErr> {
Entity::find()
.filter(Column::EndedAt.is_null())
.all(db)
.await
}
pub async fn get_active_by_stream_key_id(
db: &DatabaseConnection,
stream_key_id: i32,
) -> Result<Option<Model>, DbErr> {
Entity::find()
.filter(Column::StreamKeyId.eq(stream_key_id))
.filter(Column::EndedAt.is_null())
.one(db)
.await
}
pub async fn clean_unended_streams(db: &DatabaseConnection) -> Result<u64, DbErr> {
let result = Entity::update_many()
.filter(Column::EndedAt.is_null())
.col_expr(Column::EndedAt, Expr::col(Column::StartedAt).into())
.exec(db)
.await?;
Ok(result.rows_affected)
}
}
impl ActiveModel {
pub async fn finish_stream_session(
mut self,
db: &DatabaseConnection,
ended_at: chrono::DateTime<Utc>,
) -> Result<Model, DbErr> {
self.ended_at = Set(Some(ended_at));
self.update(db).await
}
}