feat: MovieDto enrichment, movie detail page, PWA, watchlist, watchlist federation

This commit is contained in:
2026-05-13 00:23:45 +02:00
parent 2fd8734d23
commit 53df90ab1f
84 changed files with 2755 additions and 398 deletions

View File

@@ -0,0 +1,9 @@
CREATE TABLE IF NOT EXISTS watchlist_entries (
id TEXT PRIMARY KEY NOT NULL,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
movie_id TEXT NOT NULL REFERENCES movies(id) ON DELETE CASCADE,
added_at TIMESTAMPTZ NOT NULL,
UNIQUE(user_id, movie_id)
);
CREATE INDEX IF NOT EXISTS idx_watchlist_user ON watchlist_entries(user_id, added_at DESC);

View File

@@ -0,0 +1,12 @@
CREATE TABLE IF NOT EXISTS ap_remote_watchlist_entries (
ap_id TEXT PRIMARY KEY NOT NULL,
actor_url TEXT NOT NULL,
movie_title TEXT NOT NULL,
release_year INTEGER NOT NULL,
external_metadata_id TEXT,
poster_url TEXT,
added_at TIMESTAMPTZ NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_remote_watchlist_actor
ON ap_remote_watchlist_entries(actor_url);

View File

@@ -19,10 +19,11 @@ mod models;
mod persons;
mod profile;
mod users;
mod watchlist;
use models::{
DiaryRow, DirectorCountRow, FeedRow, MonthlyRatingRow, MovieRow, MovieStatsRow, ReviewRow,
UserTotalsRow, datetime_to_str,
DiaryRow, DirectorCountRow, FeedRow, MonthlyRatingRow, MovieRow, MovieStatsRow,
MovieSummaryRow, ReviewRow, UserTotalsRow, datetime_to_str,
};
pub use image_ref::{PostgresImageRefAdapter, create_image_ref};
@@ -31,6 +32,7 @@ pub use import_session::PostgresImportSessionRepository;
pub use persons::{PostgresPersonAdapter, create_person_adapter};
pub use profile::PostgresMovieProfileRepository;
pub use users::PostgresUserRepository;
pub use watchlist::PostgresWatchlistRepository;
fn format_year_month(ym: &str) -> String {
let parts: Vec<&str> = ym.splitn(2, '-').collect();
@@ -300,7 +302,7 @@ impl MovieRepository for PostgresRepository {
.fetch_optional(&self.pool)
.await
.map_err(Self::map_err)?
.map(MovieRow::to_domain)
.map(MovieRow::into_domain)
.transpose()
}
@@ -314,7 +316,7 @@ impl MovieRepository for PostgresRepository {
.fetch_optional(&self.pool)
.await
.map_err(Self::map_err)?
.map(MovieRow::to_domain)
.map(MovieRow::into_domain)
.transpose()
}
@@ -335,7 +337,7 @@ impl MovieRepository for PostgresRepository {
.await
.map_err(Self::map_err)?
.into_iter()
.map(MovieRow::to_domain)
.map(MovieRow::into_domain)
.collect()
}
@@ -383,21 +385,34 @@ impl MovieRepository for PostgresRepository {
async fn list_movies(
&self,
page: &domain::models::collections::PageParams,
search: Option<&str>,
) -> Result<domain::models::collections::Paginated<domain::models::Movie>, DomainError> {
filter: &domain::models::MovieFilter,
) -> Result<domain::models::collections::Paginated<domain::models::MovieSummary>, DomainError> {
use sqlx::Row;
let limit = page.limit as i64;
let offset = page.offset as i64;
let pattern = search.map(|s| format!("%{}%", s.to_lowercase()));
let pattern = filter.search.as_deref().map(|s| format!("%{}%", s.to_lowercase()));
let genre = filter.genre.as_deref();
let language = filter.language.as_deref();
let rows: Vec<models::MovieRow> = sqlx::query_as(
"SELECT id, external_metadata_id, title, release_year, director, poster_path \
FROM movies \
WHERE ($1::text IS NULL OR LOWER(title) LIKE $1) \
ORDER BY title ASC \
LIMIT $2 OFFSET $3",
let rows: Vec<MovieSummaryRow> = sqlx::query_as(
"SELECT \
m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path, \
p.overview, p.runtime_minutes, p.original_language, p.collection_name, \
array_agg(g.name) FILTER (WHERE g.name IS NOT NULL) AS genres \
FROM movies m \
LEFT JOIN movie_profiles p ON p.movie_id = m.id \
LEFT JOIN movie_genres g ON g.movie_id = m.id \
WHERE ($1::text IS NULL OR LOWER(m.title) LIKE $1) \
AND ($2::text IS NULL OR p.original_language = $2) \
AND ($3::text IS NULL OR m.id IN (SELECT movie_id FROM movie_genres WHERE LOWER(name) = LOWER($3))) \
GROUP BY m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path, \
p.overview, p.runtime_minutes, p.original_language, p.collection_name \
ORDER BY m.title ASC \
LIMIT $4 OFFSET $5",
)
.bind(&pattern)
.bind(language)
.bind(genre)
.bind(limit)
.bind(offset)
.fetch_all(&self.pool)
@@ -405,17 +420,25 @@ impl MovieRepository for PostgresRepository {
.map_err(Self::map_err)?;
let total: i64 = sqlx::query(
"SELECT COUNT(*) FROM movies WHERE ($1::text IS NULL OR LOWER(title) LIKE $1)",
"SELECT COUNT(DISTINCT m.id) \
FROM movies m \
LEFT JOIN movie_profiles p ON p.movie_id = m.id \
WHERE ($1::text IS NULL OR LOWER(m.title) LIKE $1) \
AND ($2::text IS NULL OR p.original_language = $2) \
AND ($3::text IS NULL OR m.id IN (SELECT movie_id FROM movie_genres WHERE LOWER(name) = LOWER($3)))",
)
.bind(&pattern)
.bind(language)
.bind(genre)
.fetch_one(&self.pool)
.await
.map_err(Self::map_err)?
.try_get(0)
.unwrap_or(0);
let items = rows.into_iter()
.map(|r| r.to_domain())
let items = rows
.into_iter()
.map(|r| r.into_domain())
.collect::<Result<Vec<_>, _>>()?;
Ok(domain::models::collections::Paginated {
@@ -480,7 +503,7 @@ impl ReviewRepository for PostgresRepository {
.fetch_optional(&self.pool)
.await
.map_err(Self::map_err)?
.map(ReviewRow::to_domain)
.map(ReviewRow::into_domain)
.transpose()
}
@@ -540,7 +563,7 @@ impl DiaryRepository for PostgresRepository {
let items = rows
.into_iter()
.map(DiaryRow::to_domain)
.map(DiaryRow::into_domain)
.collect::<Result<Vec<_>, _>>()?;
Ok(Paginated {
@@ -681,7 +704,7 @@ impl DiaryRepository for PostgresRepository {
let items = rows
.into_iter()
.map(FeedRow::to_domain)
.map(FeedRow::into_domain)
.collect::<Result<Vec<_>, _>>()?;
Ok(Paginated {
@@ -704,7 +727,7 @@ impl DiaryRepository for PostgresRepository {
.await
.map_err(Self::map_err)?
.ok_or_else(|| DomainError::NotFound(format!("Movie {}", id_str)))?
.to_domain()?;
.into_domain()?;
let viewings = sqlx::query_as::<_, ReviewRow>(
"SELECT id, movie_id, user_id, rating, comment,
@@ -718,7 +741,7 @@ impl DiaryRepository for PostgresRepository {
.await
.map_err(Self::map_err)?
.into_iter()
.map(ReviewRow::to_domain)
.map(ReviewRow::into_domain)
.collect::<Result<Vec<_>, _>>()?;
Ok(ReviewHistory::new(movie, viewings))
@@ -742,7 +765,7 @@ impl DiaryRepository for PostgresRepository {
.await
.map_err(Self::map_err)?;
rows.into_iter().map(DiaryRow::to_domain).collect()
rows.into_iter().map(DiaryRow::into_domain).collect()
}
async fn get_movie_stats(&self, movie_id: &MovieId) -> Result<MovieStats, DomainError> {
@@ -763,7 +786,7 @@ impl DiaryRepository for PostgresRepository {
.fetch_one(&self.pool)
.await
.map_err(Self::map_err)
.map(MovieStatsRow::to_domain)
.map(MovieStatsRow::into_domain)
}
async fn get_movie_social_feed(
@@ -808,7 +831,7 @@ impl DiaryRepository for PostgresRepository {
let items = rows
.into_iter()
.map(FeedRow::to_domain)
.map(FeedRow::into_domain)
.collect::<Result<Vec<_>, _>>()?;
Ok(Paginated {
@@ -918,6 +941,7 @@ pub async fn wire(database_url: &str) -> anyhow::Result<(
std::sync::Arc<dyn domain::ports::ImportSessionRepository>,
std::sync::Arc<dyn domain::ports::ImportProfileRepository>,
std::sync::Arc<dyn domain::ports::MovieProfileRepository>,
std::sync::Arc<dyn domain::ports::WatchlistRepository>,
)> {
use anyhow::Context;
@@ -934,6 +958,7 @@ pub async fn wire(database_url: &str) -> anyhow::Result<(
let import_session_repo = std::sync::Arc::new(PostgresImportSessionRepository::new(pool.clone()));
let import_profile_repo = std::sync::Arc::new(PostgresImportProfileRepository::new(pool.clone()));
let movie_profile_repo = std::sync::Arc::new(PostgresMovieProfileRepository::new(pool.clone()));
let watchlist_repo = std::sync::Arc::new(PostgresWatchlistRepository::new(pool.clone()));
Ok((
pool.clone(),
@@ -945,5 +970,6 @@ pub async fn wire(database_url: &str) -> anyhow::Result<(
import_session_repo as _,
import_profile_repo as _,
movie_profile_repo as _,
watchlist_repo as _,
))
}

View File

@@ -1,7 +1,7 @@
use chrono::NaiveDateTime;
use domain::{
errors::DomainError,
models::{DiaryEntry, FeedEntry, Movie, Review, ReviewSource, UserSummary},
models::{DiaryEntry, FeedEntry, Movie, MovieSummary, Review, ReviewSource, UserSummary},
value_objects::{
Comment, Email, ExternalMetadataId, MovieId, MovieTitle, PosterPath, Rating, ReleaseYear,
ReviewId, UserId,
@@ -20,7 +20,7 @@ pub(crate) struct MovieRow {
}
impl MovieRow {
pub fn to_domain(self) -> Result<Movie, DomainError> {
pub fn into_domain(self) -> Result<Movie, DomainError> {
let id = MovieId::from_uuid(parse_uuid(&self.id)?);
let external_metadata_id = self
.external_metadata_id
@@ -40,6 +40,43 @@ impl MovieRow {
}
}
#[derive(sqlx::FromRow)]
pub(crate) struct MovieSummaryRow {
pub id: String,
pub external_metadata_id: Option<String>,
pub title: String,
pub release_year: i64,
pub director: Option<String>,
pub poster_path: Option<String>,
pub genres: Option<Vec<String>>,
pub runtime_minutes: Option<i64>,
pub original_language: Option<String>,
pub overview: Option<String>,
pub collection_name: Option<String>,
}
impl MovieSummaryRow {
pub fn into_domain(self) -> Result<MovieSummary, DomainError> {
let movie = MovieRow {
id: self.id,
external_metadata_id: self.external_metadata_id,
title: self.title,
release_year: self.release_year,
director: self.director,
poster_path: self.poster_path,
}
.into_domain()?;
Ok(MovieSummary {
movie,
genres: self.genres.unwrap_or_default(),
runtime_minutes: self.runtime_minutes.map(|v| v as u32),
original_language: self.original_language,
overview: self.overview,
collection_name: self.collection_name,
})
}
}
#[derive(sqlx::FromRow)]
pub(crate) struct ReviewRow {
pub id: String,
@@ -53,7 +90,7 @@ pub(crate) struct ReviewRow {
}
impl ReviewRow {
pub fn to_domain(self) -> Result<Review, DomainError> {
pub fn into_domain(self) -> Result<Review, DomainError> {
let id = ReviewId::from_uuid(parse_uuid(&self.id)?);
let movie_id = MovieId::from_uuid(parse_uuid(&self.movie_id)?);
let user_id = UserId::from_uuid(parse_uuid(&self.user_id)?);
@@ -90,7 +127,7 @@ pub(crate) struct DiaryRow {
}
impl DiaryRow {
pub fn to_domain(self) -> Result<DiaryEntry, DomainError> {
pub fn into_domain(self) -> Result<DiaryEntry, DomainError> {
let movie = MovieRow {
id: self.id,
external_metadata_id: self.external_metadata_id,
@@ -99,7 +136,7 @@ impl DiaryRow {
director: self.director,
poster_path: self.poster_path,
}
.to_domain()?;
.into_domain()?;
let review = ReviewRow {
id: self.review_id,
movie_id: self.movie_id,
@@ -110,7 +147,7 @@ impl DiaryRow {
created_at: self.created_at,
remote_actor_url: self.remote_actor_url,
}
.to_domain()?;
.into_domain()?;
Ok(DiaryEntry::new(movie, review))
}
}
@@ -135,7 +172,7 @@ pub(crate) struct FeedRow {
}
impl FeedRow {
pub fn to_domain(self) -> Result<FeedEntry, DomainError> {
pub fn into_domain(self) -> Result<FeedEntry, DomainError> {
let diary = DiaryRow {
id: self.id,
external_metadata_id: self.external_metadata_id,
@@ -152,7 +189,7 @@ impl FeedRow {
created_at: self.created_at,
remote_actor_url: self.remote_actor_url,
}
.to_domain()?;
.into_domain()?;
Ok(FeedEntry::new(diary, self.user_email))
}
}
@@ -170,7 +207,7 @@ pub(crate) struct MovieStatsRow {
}
impl MovieStatsRow {
pub fn to_domain(self) -> domain::models::MovieStats {
pub fn into_domain(self) -> domain::models::MovieStats {
domain::models::MovieStats {
total_count: self.total_count as u64,
avg_rating: self.avg_rating,
@@ -195,7 +232,7 @@ pub(crate) struct UserSummaryRow {
}
impl UserSummaryRow {
pub fn to_domain(self) -> Result<UserSummary, DomainError> {
pub fn into_domain(self) -> Result<UserSummary, DomainError> {
Ok(UserSummary::new(
UserId::from_uuid(parse_uuid(&self.id)?),
Email::new(self.email)?,

View File

@@ -231,7 +231,7 @@ impl UserRepository for PostgresUserRepository {
.await
.map_err(Self::map_err)?
.into_iter()
.map(UserSummaryRow::to_domain)
.map(UserSummaryRow::into_domain)
.collect()
}
}

View File

@@ -0,0 +1,169 @@
use async_trait::async_trait;
use domain::{
errors::DomainError,
models::{WatchlistEntry, WatchlistWithMovie, collections::{PageParams, Paginated}},
ports::WatchlistRepository,
value_objects::{MovieId, UserId, WatchlistEntryId},
};
use sqlx::{PgPool, Row};
use crate::models::{parse_uuid, parse_datetime, MovieRow};
pub struct PostgresWatchlistRepository {
pool: PgPool,
}
impl PostgresWatchlistRepository {
pub fn new(pool: PgPool) -> Self {
Self { pool }
}
fn map_err(e: sqlx::Error) -> DomainError {
tracing::error!("Database error: {:?}", e);
DomainError::InfrastructureError("Database operation failed".into())
}
}
#[async_trait]
impl WatchlistRepository for PostgresWatchlistRepository {
async fn add(&self, entry: &WatchlistEntry) -> Result<(), DomainError> {
let id = entry.id.value().to_string();
let user_id = entry.user_id.value().to_string();
let movie_id = entry.movie_id.value().to_string();
let added_at = entry.added_at;
sqlx::query(
"INSERT INTO watchlist_entries (id, user_id, movie_id, added_at) \
VALUES ($1, $2, $3, $4) \
ON CONFLICT (user_id, movie_id) DO NOTHING",
)
.bind(&id)
.bind(&user_id)
.bind(&movie_id)
.bind(added_at)
.execute(&self.pool)
.await
.map_err(Self::map_err)?;
Ok(())
}
async fn remove(&self, user_id: &UserId, movie_id: &MovieId) -> Result<(), DomainError> {
let uid = user_id.value().to_string();
let mid = movie_id.value().to_string();
let result = sqlx::query(
"DELETE FROM watchlist_entries WHERE user_id = $1 AND movie_id = $2",
)
.bind(&uid)
.bind(&mid)
.execute(&self.pool)
.await
.map_err(Self::map_err)?;
if result.rows_affected() == 0 {
return Err(DomainError::NotFound(format!(
"Watchlist entry for movie {} not found",
mid
)));
}
Ok(())
}
async fn remove_if_present(
&self,
user_id: &UserId,
movie_id: &MovieId,
) -> Result<bool, DomainError> {
let uid = user_id.value().to_string();
let mid = movie_id.value().to_string();
let result = sqlx::query(
"DELETE FROM watchlist_entries WHERE user_id = $1 AND movie_id = $2",
)
.bind(&uid)
.bind(&mid)
.execute(&self.pool)
.await
.map_err(Self::map_err)?;
Ok(result.rows_affected() > 0)
}
async fn get_for_user(
&self,
user_id: &UserId,
page: &PageParams,
) -> Result<Paginated<WatchlistWithMovie>, DomainError> {
let uid = user_id.value().to_string();
let limit = page.limit as i64;
let offset = page.offset as i64;
let rows = sqlx::query(
"SELECT w.id, w.user_id, w.movie_id, \
to_char(w.added_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') AS added_at, \
m.id AS m_id, m.external_metadata_id, m.title, m.release_year, \
m.director, m.poster_path \
FROM watchlist_entries w \
JOIN movies m ON m.id = w.movie_id \
WHERE w.user_id = $1 \
ORDER BY w.added_at DESC \
LIMIT $2 OFFSET $3",
)
.bind(&uid)
.bind(limit)
.bind(offset)
.fetch_all(&self.pool)
.await
.map_err(Self::map_err)?;
let total: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM watchlist_entries WHERE user_id = $1",
)
.bind(&uid)
.fetch_one(&self.pool)
.await
.map_err(Self::map_err)?;
let items = rows
.into_iter()
.map(|row| {
let entry = WatchlistEntry {
id: WatchlistEntryId::from_uuid(parse_uuid(&row.try_get::<String, _>("id").map_err(|e| DomainError::InfrastructureError(e.to_string()))?)?),
user_id: UserId::from_uuid(parse_uuid(&row.try_get::<String, _>("user_id").map_err(|e| DomainError::InfrastructureError(e.to_string()))?)?),
movie_id: MovieId::from_uuid(parse_uuid(&row.try_get::<String, _>("movie_id").map_err(|e| DomainError::InfrastructureError(e.to_string()))?)?),
added_at: parse_datetime(&row.try_get::<String, _>("added_at").map_err(|e| DomainError::InfrastructureError(e.to_string()))?)?,
};
let movie = MovieRow {
id: row.try_get("m_id").map_err(|e| DomainError::InfrastructureError(e.to_string()))?,
external_metadata_id: row.try_get("external_metadata_id").map_err(|e| DomainError::InfrastructureError(e.to_string()))?,
title: row.try_get("title").map_err(|e| DomainError::InfrastructureError(e.to_string()))?,
release_year: row.try_get("release_year").map_err(|e| DomainError::InfrastructureError(e.to_string()))?,
director: row.try_get("director").map_err(|e| DomainError::InfrastructureError(e.to_string()))?,
poster_path: row.try_get("poster_path").map_err(|e| DomainError::InfrastructureError(e.to_string()))?,
}
.into_domain()?;
Ok(WatchlistWithMovie { entry, movie })
})
.collect::<Result<Vec<_>, DomainError>>()?;
Ok(Paginated {
items,
total_count: total as u64,
limit: page.limit,
offset: page.offset,
})
}
async fn contains(&self, user_id: &UserId, movie_id: &MovieId) -> Result<bool, DomainError> {
let uid = user_id.value().to_string();
let mid = movie_id.value().to_string();
let count: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM watchlist_entries WHERE user_id = $1 AND movie_id = $2",
)
.bind(&uid)
.bind(&mid)
.fetch_one(&self.pool)
.await
.map_err(Self::map_err)?;
Ok(count > 0)
}
}