refactor: http-axum split into api/html/federation modules, router.rs, templates per page group

This commit is contained in:
2026-10-25 21:46:03 +01:00
parent a931fb548f
commit 614aec8df9
97 changed files with 5317 additions and 5160 deletions

View File

@@ -0,0 +1,155 @@
use crate::html::templates::{LoginTemplate, RegisterTemplate};
use crate::{
html::csrf::{CsrfToken, secure_flag},
html::forms::{ErrorQuery, LoginForm, RegisterForm},
html::render::render_page,
state::AppState,
};
use api_types::HtmlPageContext;
use application::auth::{login as login_uc, queries::LoginCommand};
use axum::{
Form,
extract::{Extension, Query, State},
http::{HeaderValue, StatusCode, header::SET_COOKIE},
response::{IntoResponse, Redirect},
};
use chrono::Utc;
fn set_cookie_header(
token: &str,
max_age: i64,
secure_cookies: bool,
) -> (axum::http::HeaderName, HeaderValue) {
let val = format!(
"token={}; HttpOnly; Path=/; SameSite=Strict; Max-Age={}{}",
token,
max_age,
secure_flag(secure_cookies)
);
(
SET_COOKIE,
HeaderValue::from_str(&val).expect("valid cookie"),
)
}
pub async fn get_login_page(
State(state): State<AppState>,
Query(params): Query<ErrorQuery>,
Extension(csrf): Extension<CsrfToken>,
) -> impl IntoResponse {
let ctx = HtmlPageContext {
user_email: None,
user_id: None,
is_admin: false,
register_enabled: state.app_ctx.config.allow_registration,
rss_url: "/feed.rss".to_string(),
page_title: "Login — Movies Diary".to_string(),
canonical_url: format!("{}/login", state.app_ctx.config.base_url),
csrf_token: csrf.0,
page_rss_url: None,
pending_follow_count: 0,
};
render_page(LoginTemplate {
ctx: &ctx,
error: params.error.as_deref(),
})
}
pub async fn post_login(
State(state): State<AppState>,
Extension(csrf): Extension<CsrfToken>,
Form(form): Form<LoginForm>,
) -> impl IntoResponse {
if crate::html::csrf::mismatch(&csrf, &form.csrf_token) {
return StatusCode::FORBIDDEN.into_response();
}
match login_uc::execute(
&state.app_ctx.deps.auth.login,
LoginCommand {
email: form.email,
password: form.password,
},
)
.await
{
Ok(result) => {
let max_age = (result.expires_at - Utc::now()).num_seconds().max(0);
let cookie =
set_cookie_header(&result.token, max_age, state.app_ctx.config.secure_cookies);
([cookie], Redirect::to("/")).into_response()
}
Err(_) => Redirect::to("/login?error=Invalid+credentials").into_response(),
}
}
pub async fn get_logout(State(state): State<AppState>) -> impl IntoResponse {
let val = format!(
"token=; HttpOnly; Path=/; SameSite=Strict; Max-Age=0{}",
secure_flag(state.app_ctx.config.secure_cookies)
);
let cookie = (
SET_COOKIE,
HeaderValue::from_str(&val).expect("valid cookie"),
);
([cookie], Redirect::to("/")).into_response()
}
pub async fn get_register_page(
State(state): State<AppState>,
Query(params): Query<ErrorQuery>,
Extension(csrf): Extension<CsrfToken>,
) -> impl IntoResponse {
if !state.app_ctx.config.allow_registration {
return Redirect::to("/").into_response();
}
let ctx = HtmlPageContext {
user_email: None,
user_id: None,
is_admin: false,
register_enabled: true,
rss_url: "/feed.rss".to_string(),
page_title: "Register — Movies Diary".to_string(),
canonical_url: format!("{}/register", state.app_ctx.config.base_url),
csrf_token: csrf.0,
page_rss_url: None,
pending_follow_count: 0,
};
render_page(RegisterTemplate {
ctx: &ctx,
error: params.error.as_deref(),
})
.into_response()
}
pub async fn post_register(
State(state): State<AppState>,
Extension(csrf): Extension<CsrfToken>,
Form(form): Form<RegisterForm>,
) -> impl IntoResponse {
if !state.app_ctx.config.allow_registration {
return Redirect::to("/").into_response();
}
if crate::html::csrf::mismatch(&csrf, &form.csrf_token) {
return StatusCode::FORBIDDEN.into_response();
}
match application::auth::register_and_login::execute(
&state.app_ctx.deps.auth.register_and_login,
application::auth::commands::RegisterAndLoginCommand {
email: form.email,
username: form.username,
password: form.password,
},
)
.await
{
Ok(result) => {
let max_age = (result.expires_at - Utc::now()).num_seconds().max(0);
let cookie =
set_cookie_header(&result.token, max_age, state.app_ctx.config.secure_cookies);
([cookie], Redirect::to("/")).into_response()
}
Err(_) => {
Redirect::to("/register?error=Registration+failed.+Please+try+again.").into_response()
}
}
}

View File

@@ -0,0 +1,61 @@
use axum::{
extract::{Request, State},
http::{HeaderValue, header},
middleware::Next,
response::Response,
};
#[derive(Clone)]
pub struct CsrfToken(pub String);
pub fn extract_from_cookie(headers: &axum::http::HeaderMap) -> Option<String> {
headers
.get(header::COOKIE)
.and_then(|v| v.to_str().ok())
.and_then(|cookies| {
cookies
.split(';')
.find_map(|c| c.trim().strip_prefix("csrf=").map(str::to_string))
})
}
/// Router state for [`csrf_middleware`]: whether cookies carry the `Secure` attribute.
#[derive(Clone, Copy)]
pub struct SecureCookies(pub bool);
pub(crate) fn secure_flag(secure_cookies: bool) -> &'static str {
if secure_cookies { "; Secure" } else { "" }
}
pub async fn csrf_middleware(
State(SecureCookies(secure_cookies)): State<SecureCookies>,
mut req: Request,
next: Next,
) -> Response {
let existing = extract_from_cookie(req.headers());
let (token, needs_set) = match existing {
Some(t) => (t, false),
None => (uuid::Uuid::new_v4().to_string(), true),
};
req.extensions_mut().insert(CsrfToken(token.clone()));
let mut response = next.run(req).await;
if needs_set {
let cookie = format!(
"csrf={}; HttpOnly; Path=/; SameSite=Strict{}",
token,
secure_flag(secure_cookies)
);
if let Ok(val) = HeaderValue::from_str(&cookie) {
response.headers_mut().append(header::SET_COOKIE, val);
}
}
response
}
pub fn mismatch(token: &CsrfToken, form_value: &str) -> bool {
token.0 != form_value || form_value.is_empty()
}

View File

@@ -0,0 +1,166 @@
use crate::html::helpers::{build_page_context, encode_domain_error};
use crate::html::templates::{ActivityFeedTemplate, NewReviewTemplate, build_page_items};
use crate::support::build_export_response;
use crate::{
extractors::{OptionalCookieUser, RequiredCookieUser},
html::csrf::CsrfToken,
html::forms::{ErrorQuery, FeedQueryParams, LogReviewData, LogReviewForm},
html::render::render_page,
state::AppState,
};
use application::diary::{commands::DeleteReviewCommand, delete_review, log_review};
use axum::{
Form,
extract::{Extension, Path, Query, State},
http::StatusCode,
response::{IntoResponse, Redirect},
};
use uuid::Uuid;
pub async fn get_new_review_page(
RequiredCookieUser(user_id): RequiredCookieUser,
State(state): State<AppState>,
Query(params): Query<ErrorQuery>,
Extension(csrf): Extension<CsrfToken>,
) -> impl IntoResponse {
let mut ctx = build_page_context(&state, Some(user_id), csrf.0).await;
ctx.page_title = "Log a Review — Movies Diary".to_string();
ctx.canonical_url = format!("{}/reviews/new", state.app_ctx.config.base_url);
render_page(NewReviewTemplate {
ctx: &ctx,
error: params.error.as_deref(),
})
}
pub async fn post_review_html(
State(state): State<AppState>,
RequiredCookieUser(user_id): RequiredCookieUser,
Extension(csrf): Extension<CsrfToken>,
Form(form): Form<LogReviewForm>,
) -> impl IntoResponse {
if crate::html::csrf::mismatch(&csrf, &form.csrf_token) {
return StatusCode::FORBIDDEN.into_response();
}
let data = match LogReviewData::try_from(form) {
Ok(d) => d,
Err(_) => {
return Redirect::to("/reviews/new?error=Invalid+date+format").into_response();
}
};
match log_review::execute(
&state.app_ctx.services.review_logger,
data.into_command(user_id.value()),
)
.await
{
Ok(_) => Redirect::to("/").into_response(),
Err(e) => {
let msg = encode_domain_error(&e);
Redirect::to(&format!("/reviews/new?error={}", msg)).into_response()
}
}
}
pub async fn post_delete_review_html(
State(state): State<AppState>,
RequiredCookieUser(user_id): RequiredCookieUser,
Extension(csrf): Extension<CsrfToken>,
Path(review_id): Path<Uuid>,
Form(form): Form<crate::html::forms::DeleteRedirectForm>,
) -> impl IntoResponse {
if crate::html::csrf::mismatch(&csrf, &form.csrf_token) {
return StatusCode::FORBIDDEN.into_response();
}
let cmd = DeleteReviewCommand {
review_id,
requesting_user_id: user_id.value(),
};
match delete_review::execute(&state.app_ctx.deps.diary.delete_review, cmd).await {
Ok(()) => {
let redirect_url = form
.redirect_after
.filter(|url| {
(url.starts_with('/') && !url.starts_with("//")) || url.starts_with('?')
})
.unwrap_or_else(|| "/".to_string());
Redirect::to(&redirect_url).into_response()
}
Err(e) => crate::errors::domain_error_response(e),
}
}
pub async fn get_export_html(
State(state): State<AppState>,
RequiredCookieUser(user_id): RequiredCookieUser,
Query(params): Query<api_types::ExportQueryParams>,
) -> impl IntoResponse {
build_export_response(&params.format, user_id.value(), &state)
}
pub async fn get_activity_feed_html(
OptionalCookieUser(user_id): OptionalCookieUser,
State(state): State<AppState>,
Query(params): Query<FeedQueryParams>,
Extension(csrf): Extension<CsrfToken>,
) -> impl IntoResponse {
let ctx = build_page_context(&state, user_id.clone(), csrf.0).await;
let limit = params.limit.unwrap_or(20);
let offset = params.offset.unwrap_or(0);
let filter_following = params.filter == "following" && user_id.is_some();
let filter_str = if filter_following { "following" } else { "all" };
let sort_by_str = match params.sort_by.as_str() {
"date_asc" => "date_asc",
"rating" => "rating",
"rating_asc" => "rating_asc",
_ => "date",
};
let query = application::diary::queries::GetActivityFeedQuery {
limit,
offset,
sort_by: sort_by_str.parse().unwrap_or_default(),
search: if params.search.is_empty() {
None
} else {
Some(params.search.clone())
},
viewer_user_id: user_id.map(|u| u.value()),
filter_following,
};
match application::diary::get_activity_feed::execute(
&state.app_ctx.deps.diary.get_activity_feed,
query,
)
.await
{
Ok(entries) => {
let entry_limit = entries.limit;
let entry_offset = entries.offset;
let has_more =
(entry_offset as u64).saturating_add(entry_limit as u64) < entries.total_count;
let total_pages = (entries.total_count as u32)
.saturating_add(entry_limit.saturating_sub(1))
.checked_div(entry_limit)
.unwrap_or(1);
let current_page = entry_offset.checked_div(entry_limit).unwrap_or(0);
let page_items = build_page_items(total_pages, current_page);
render_page(ActivityFeedTemplate {
entries: entries.items.as_slice(),
current_offset: entry_offset,
limit: entry_limit,
has_more,
ctx: &ctx,
page_items,
filter: filter_str.to_string(),
sort_by: sort_by_str.to_string(),
search: params.search,
})
.into_response()
}
Err(e) => crate::errors::domain_error_response(e),
}
}

View File

@@ -0,0 +1,316 @@
use chrono::NaiveDateTime;
use serde::Deserialize;
use uuid::Uuid;
use application::diary::{
commands::{LogReviewCommand, MovieInput},
queries::GetDiaryQuery,
};
use domain::{errors::DomainError, models::ReviewSortBy};
use api_types::{DiaryQueryParams, LogReviewRequest};
pub fn empty_string_as_none<'de, D, T>(de: D) -> Result<Option<T>, D::Error>
where
D: serde::Deserializer<'de>,
T: std::str::FromStr,
T::Err: std::fmt::Display,
{
let s = Option::<String>::deserialize(de)?;
match s.as_deref() {
None | Some("") => Ok(None),
Some(s) => s.parse::<T>().map(Some).map_err(serde::de::Error::custom),
}
}
#[derive(Deserialize)]
pub struct LogReviewForm {
#[serde(default, deserialize_with = "empty_string_as_none")]
pub external_metadata_id: Option<String>,
#[serde(default, deserialize_with = "empty_string_as_none")]
pub manual_title: Option<String>,
#[serde(default, deserialize_with = "empty_string_as_none")]
pub manual_release_year: Option<u16>,
#[serde(default, deserialize_with = "empty_string_as_none")]
pub manual_director: Option<String>,
pub rating: u8,
#[serde(default, deserialize_with = "empty_string_as_none")]
pub comment: Option<String>,
pub watched_at: String,
#[serde(default, deserialize_with = "empty_string_as_none")]
pub watch_medium: Option<String>,
#[serde(default)]
pub spoilers: bool,
#[serde(rename = "_csrf", default)]
pub csrf_token: String,
}
#[derive(Deserialize)]
pub struct LoginForm {
pub email: String,
pub password: String,
#[serde(rename = "_csrf", default)]
pub csrf_token: String,
}
#[derive(Deserialize)]
pub struct RegisterForm {
pub email: String,
pub username: String,
pub password: String,
#[serde(rename = "_csrf", default)]
pub csrf_token: String,
}
#[derive(Deserialize)]
pub struct ErrorQuery {
pub error: Option<String>,
}
#[derive(Deserialize, Default)]
pub struct FeedQueryParams {
#[serde(default)]
pub filter: String,
#[serde(default)]
pub sort_by: String,
#[serde(default)]
pub search: String,
pub limit: Option<u32>,
pub offset: Option<u32>,
}
#[derive(Deserialize, Default)]
pub struct DeleteRedirectForm {
#[serde(default)]
pub redirect_after: Option<String>,
#[serde(rename = "_csrf", default)]
pub csrf_token: String,
}
#[derive(Deserialize)]
pub struct FollowForm {
pub handle: String,
#[serde(rename = "_csrf", default)]
pub csrf_token: String,
#[serde(default)]
pub redirect_after: Option<String>,
}
#[derive(Deserialize)]
pub struct UnfollowForm {
pub actor_url: String,
#[serde(rename = "_csrf", default)]
pub csrf_token: String,
}
#[derive(Deserialize)]
pub struct FollowerActionForm {
pub actor_url: String,
#[serde(rename = "_csrf", default)]
pub csrf_token: String,
}
#[derive(Deserialize)]
pub struct BlockDomainForm {
pub domain: String,
#[serde(default)]
pub reason: Option<String>,
#[serde(rename = "_csrf", default)]
pub csrf_token: String,
}
#[derive(Deserialize)]
pub struct RemoveDomainForm {
pub domain: String,
#[serde(rename = "_csrf", default)]
pub csrf_token: String,
}
#[derive(Deserialize)]
pub struct ActorUrlForm {
pub actor_url: String,
#[serde(rename = "_csrf", default)]
pub csrf_token: String,
}
#[derive(serde::Deserialize)]
pub struct WatchlistAddForm {
pub movie_id: Option<uuid::Uuid>,
pub query: Option<String>,
#[serde(default, deserialize_with = "empty_string_as_none")]
pub year: Option<u16>,
#[serde(rename = "_csrf", default)]
pub csrf_token: String,
#[serde(default)]
pub redirect_after: Option<String>,
}
#[derive(serde::Deserialize, Default)]
pub struct WatchlistQuery {
pub limit: Option<u32>,
pub offset: Option<u32>,
pub error: Option<String>,
}
#[derive(Deserialize, Default)]
pub struct ProfileQueryParams {
pub view: Option<String>,
pub limit: Option<u32>,
pub offset: Option<u32>,
pub error: Option<String>,
#[serde(default)]
pub sort_by: String,
#[serde(default)]
pub search: String,
#[serde(default)]
pub embed: bool,
}
pub struct LogReviewData {
pub external_metadata_id: Option<String>,
pub manual_title: Option<String>,
pub manual_release_year: Option<u16>,
pub manual_director: Option<String>,
pub rating: u8,
pub comment: Option<String>,
pub watched_at: NaiveDateTime,
pub watch_medium: Option<domain::value_objects::WatchMedium>,
pub spoilers: bool,
}
#[derive(Debug)]
pub struct ParseReviewError {
pub field: &'static str,
pub message: String,
}
impl TryFrom<LogReviewForm> for LogReviewData {
type Error = ParseReviewError;
fn try_from(form: LogReviewForm) -> Result<Self, Self::Error> {
let watched_at =
domain::value_objects::parse_watched_at(&form.watched_at).map_err(|_| {
ParseReviewError {
field: "watched_at",
message: format!(
"invalid date '{}'; expected YYYY-MM-DD or YYYY-MM-DDTHH:MM[:SS]",
form.watched_at
),
}
})?;
let watch_medium = form
.watch_medium
.map(|s| s.parse())
.transpose()
.map_err(|_| ParseReviewError {
field: "watch_medium",
message: "invalid watch medium".into(),
})?;
Ok(Self {
external_metadata_id: form.external_metadata_id.filter(|s| !s.trim().is_empty()),
manual_title: form.manual_title,
manual_release_year: form.manual_release_year,
manual_director: form.manual_director,
rating: form.rating,
comment: form.comment,
watched_at,
watch_medium,
spoilers: form.spoilers,
})
}
}
impl TryFrom<LogReviewRequest> for LogReviewData {
type Error = DomainError;
fn try_from(req: LogReviewRequest) -> Result<Self, Self::Error> {
let watched_at = domain::value_objects::parse_watched_at(&req.watched_at)?;
Ok(Self {
external_metadata_id: req.external_metadata_id.filter(|s| !s.trim().is_empty()),
manual_title: req.manual_title,
manual_release_year: req.manual_release_year,
manual_director: req.manual_director,
rating: req.rating,
comment: req.comment,
watched_at,
watch_medium: req.watch_medium,
spoilers: req.spoilers,
})
}
}
impl LogReviewData {
pub fn into_command(self, user_id: Uuid) -> LogReviewCommand {
LogReviewCommand {
user_id,
input: MovieInput {
movie_id: None,
external_metadata_id: self.external_metadata_id,
manual_title: self.manual_title,
manual_release_year: self.manual_release_year,
manual_director: self.manual_director,
},
rating: self.rating,
comment: self.comment,
watched_at: self.watched_at,
watch_medium: self.watch_medium,
spoilers: self.spoilers,
}
}
}
pub fn to_diary_query(p: DiaryQueryParams) -> GetDiaryQuery {
GetDiaryQuery {
limit: p.limit,
offset: p.offset,
sort_by: p.sort_by.as_deref().map(|s| match s {
"date_asc" | "asc" => ReviewSortBy::Ascending,
"rating_desc" => ReviewSortBy::ByRatingDesc,
"rating_asc" => ReviewSortBy::ByRatingAsc,
_ => ReviewSortBy::Descending,
}),
movie_id: p.movie_id,
user_id: p.user_id,
}
}
// ── Integrations forms ────────────────────────────────────────────────────────
#[derive(Deserialize)]
pub struct GenerateTokenForm {
pub provider: String,
#[serde(default)]
pub label: Option<String>,
#[serde(rename = "_csrf", default)]
pub csrf_token: String,
}
#[derive(Deserialize)]
pub struct RevokeTokenForm {
#[serde(rename = "_csrf", default)]
pub csrf_token: String,
}
#[derive(Deserialize, Default)]
pub struct IntegrationsQuery {
pub token: Option<String>,
}
#[derive(Deserialize)]
pub struct ConfirmWatchForm {
pub rating: u8,
#[serde(default)]
pub comment: Option<String>,
#[serde(rename = "_csrf", default)]
pub csrf_token: String,
}
#[derive(Deserialize)]
pub struct DismissWatchForm {
#[serde(rename = "_csrf", default)]
pub csrf_token: String,
}
#[cfg(test)]
#[path = "forms_tests.rs"]
mod tests;

View File

@@ -0,0 +1,119 @@
use super::*;
fn make_form(watched_at: &str) -> LogReviewForm {
LogReviewForm {
external_metadata_id: None,
manual_title: None,
manual_release_year: None,
manual_director: None,
rating: 4,
comment: None,
watched_at: watched_at.to_string(),
watch_medium: None,
spoilers: false,
csrf_token: String::new(),
}
}
fn make_request(watched_at: &str) -> LogReviewRequest {
LogReviewRequest {
external_metadata_id: None,
manual_title: None,
manual_release_year: None,
manual_director: None,
rating: 4,
comment: None,
watched_at: watched_at.to_string(),
watch_medium: None,
spoilers: false,
}
}
#[test]
fn form_accepts_datetime_with_seconds() {
let data = LogReviewData::try_from(make_form("2024-03-15T20:30:00")).unwrap();
assert_eq!(data.watched_at.format("%H:%M:%S").to_string(), "20:30:00");
}
#[test]
fn form_accepts_datetime_without_seconds() {
let data = LogReviewData::try_from(make_form("2024-03-15T20:30")).unwrap();
assert_eq!(data.watched_at.format("%H:%M").to_string(), "20:30");
}
#[test]
fn form_rejects_invalid_datetime() {
assert!(LogReviewData::try_from(make_form("not-a-date")).is_err());
}
#[test]
fn api_accepts_datetime_with_seconds() {
let data = LogReviewData::try_from(make_request("2024-03-15T20:30:00")).unwrap();
assert_eq!(data.watched_at.format("%H:%M:%S").to_string(), "20:30:00");
}
#[test]
fn api_accepts_datetime_without_seconds() {
let data = LogReviewData::try_from(make_request("2024-03-15T20:30")).unwrap();
assert_eq!(data.watched_at.format("%H:%M").to_string(), "20:30");
}
#[test]
fn api_rejects_invalid_datetime() {
assert!(LogReviewData::try_from(make_request("garbage")).is_err());
}
#[test]
fn whitespace_external_id_becomes_none_in_form() {
let mut form = make_form("2024-03-15T20:30:00");
form.external_metadata_id = Some(" ".to_string());
let data = LogReviewData::try_from(form).unwrap();
assert!(data.external_metadata_id.is_none());
}
#[test]
fn whitespace_external_id_becomes_none_in_request() {
let mut req = make_request("2024-03-15T20:30:00");
req.external_metadata_id = Some(" ".to_string());
let data = LogReviewData::try_from(req).unwrap();
assert!(data.external_metadata_id.is_none());
}
#[test]
fn sort_by_asc_string_becomes_ascending() {
let params = DiaryQueryParams {
sort_by: Some("asc".to_string()),
limit: None,
offset: None,
movie_id: None,
user_id: None,
};
let query = to_diary_query(params);
assert!(matches!(
query.sort_by,
Some(domain::models::ReviewSortBy::Ascending)
));
}
#[test]
fn sort_by_other_string_becomes_descending() {
let params = DiaryQueryParams {
sort_by: Some("desc".to_string()),
limit: None,
offset: None,
movie_id: None,
user_id: None,
};
let query = to_diary_query(params);
assert!(matches!(
query.sort_by,
Some(domain::models::ReviewSortBy::Descending)
));
}
#[test]
fn form_accepts_date_only() {
let data = LogReviewData::try_from(make_form("2024-03-15")).unwrap();
assert_eq!(data.watched_at.format("%H:%M:%S").to_string(), "00:00:00");
assert_eq!(data.watched_at.format("%Y-%m-%d").to_string(), "2024-03-15");
}

View File

@@ -0,0 +1,62 @@
use api_types::HtmlPageContext;
use domain::value_objects::UserId;
use crate::state::AppState;
pub(crate) fn encode_error(msg: &str) -> String {
use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode};
utf8_percent_encode(msg, NON_ALPHANUMERIC).to_string()
}
/// Error text for a classic-page `?error=` redirect. Infrastructure failures
/// are logged here — the redirect is their only exit, so nothing else would —
/// and shown to the user generically, never with internal detail.
pub(crate) fn encode_domain_error(e: &domain::errors::DomainError) -> String {
match e {
domain::errors::DomainError::InfrastructureError(_) => {
tracing::error!("Internal error: {e}");
encode_error("Something went wrong, please try again")
}
_ => encode_error(&e.to_string()),
}
}
pub(crate) async fn build_page_context(
state: &AppState,
user_id: Option<UserId>,
csrf_token: String,
) -> HtmlPageContext {
let uuid = user_id.as_ref().map(|u| u.value());
// Page chrome (email/admin badge, pending-follow badge) degrades rather than
// blanking the page: a failed lookup or count logs a warning and falls back
// to a zeroed `PageViewer`, same as the previous silent `.unwrap_or(0)` — now
// logged and explicit, per the error policy in `get_page_viewer`'s doc comment.
let (user_email, is_admin, pending_follow_count) = if let Some(ref id) = user_id {
match application::users::get_page_viewer::execute(
&state.app_ctx.deps.users.get_page_viewer,
id.value(),
)
.await
{
Ok(viewer) => (viewer.email, viewer.is_admin, viewer.pending_follow_count),
Err(e) => {
tracing::warn!("get_page_viewer failed for {}: {e}", id.value());
(None, false, 0)
}
}
} else {
(None, false, 0)
};
HtmlPageContext {
user_email,
user_id: uuid,
is_admin,
register_enabled: state.app_ctx.config.allow_registration,
rss_url: "/feed.rss".to_string(),
page_title: "Movies Diary".to_string(),
canonical_url: state.app_ctx.config.base_url.clone(),
csrf_token,
page_rss_url: None,
pending_follow_count,
}
}

View File

@@ -0,0 +1,24 @@
use crate::state::AppState;
use axum::{
extract::{Path, State},
http::{StatusCode, header},
response::IntoResponse,
};
pub async fn get_image(
State(state): State<AppState>,
Path(key): Path<String>,
) -> impl IntoResponse {
if key.starts_with("http://") || key.starts_with("https://") {
return axum::response::Redirect::temporary(&key).into_response();
}
match state.app_ctx.services.object_storage.get(&key).await {
Ok(bytes) => {
let mime = infer::get(&bytes)
.map(|t| t.mime_type())
.unwrap_or("application/octet-stream");
([(header::CONTENT_TYPE, mime)], bytes).into_response()
}
Err(_) => StatusCode::NOT_FOUND.into_response(),
}
}

View File

@@ -0,0 +1,149 @@
use crate::html::helpers::encode_domain_error;
use crate::html::render::render_page;
use crate::html::templates::ImportMappingTemplate;
use crate::support::str_to_domain_field;
use crate::{extractors::RequiredCookieUser, html::csrf::CsrfToken, state::AppState};
use application::import::{
apply_mapping as apply_import_mapping, commands::ApplyImportMappingCommand, get_mapping_stage,
};
use axum::{
Extension, Form,
extract::{Path, State},
response::{IntoResponse, Redirect},
};
use domain::models::{
FieldMapping,
import::{DomainField, Transform},
};
use domain::value_objects::ImportSessionId;
use std::collections::HashMap;
fn parse_mapping_form(form: &HashMap<String, String>) -> Vec<FieldMapping> {
let mut mappings = Vec::new();
let mut i = 0usize;
loop {
if i > 64 {
break;
}
let col_key = format!("mapping_{i}_col");
let Some(col) = form.get(&col_key).cloned() else {
break;
};
let field_str = form
.get(&format!("mapping_{i}_field"))
.map(|s| s.as_str())
.unwrap_or("");
if let Some(domain_field) = str_to_domain_field(field_str) {
let transform = if domain_field == DomainField::Rating {
let scale: f64 = form
.get(&format!("mapping_{i}_scale"))
.and_then(|s| s.parse().ok())
.unwrap_or(1.0);
Transform::RatingScale(scale)
} else if domain_field == DomainField::WatchedAt {
form.get(&format!("mapping_{i}_datefmt"))
.filter(|s| !s.is_empty())
.cloned()
.map(Transform::DateFormat)
.unwrap_or(Transform::Identity)
} else {
Transform::Identity
};
mappings.push(FieldMapping {
source_column: col,
domain_field,
transform,
});
}
i += 1;
}
mappings
}
pub async fn get_mapping_page(
State(state): State<AppState>,
RequiredCookieUser(user_id): RequiredCookieUser,
Path(session_id_str): Path<String>,
Extension(csrf): Extension<CsrfToken>,
) -> impl IntoResponse {
let Ok(session_id) = session_id_str
.parse::<uuid::Uuid>()
.map(ImportSessionId::from_uuid)
else {
return Redirect::to("/import").into_response();
};
let Ok(stage) = get_mapping_stage::execute(
&state.app_ctx.deps.import.get_mapping_stage,
session_id,
user_id.value(),
)
.await
else {
return Redirect::to("/import").into_response();
};
let ctx = crate::html::helpers::build_page_context(&state, Some(user_id), csrf.0).await;
let domain_fields: Vec<(&str, &str)> = vec![
("title", "Title"),
("release_year", "Release Year"),
("director", "Director"),
("rating", "Rating"),
("watched_at", "Watched At"),
("comment", "Comment"),
("external_metadata_id", "External ID"),
];
render_page(ImportMappingTemplate {
ctx: &ctx,
session_id: &session_id_str,
columns: &stage.columns,
sample_rows: &stage.sample_rows,
domain_fields: &domain_fields,
error: None,
})
.into_response()
}
pub async fn post_mapping(
State(state): State<AppState>,
RequiredCookieUser(user_id): RequiredCookieUser,
Path(session_id_str): Path<String>,
Extension(csrf): Extension<CsrfToken>,
Form(form): Form<HashMap<String, String>>,
) -> impl IntoResponse {
let csrf_token = form.get("_csrf").map(|s| s.as_str()).unwrap_or("");
if crate::html::csrf::mismatch(&csrf, csrf_token) {
return Redirect::to("/import").into_response();
}
let Ok(session_id) = session_id_str
.parse::<uuid::Uuid>()
.map(ImportSessionId::from_uuid)
else {
return Redirect::to("/import").into_response();
};
let mappings = parse_mapping_form(&form);
if mappings.is_empty() {
return Redirect::to(&format!(
"/import/{}/mapping?error=select+at+least+one+mapping",
session_id_str
))
.into_response();
}
match apply_import_mapping::execute(
&state.app_ctx.deps.import.apply_mapping,
ApplyImportMappingCommand {
user_id: user_id.value(),
session_id: session_id.value(),
mappings,
},
)
.await
{
Ok(_) => Redirect::to(&format!("/import/{}/preview", session_id_str)).into_response(),
Err(e) => Redirect::to(&format!(
"/import/{}/mapping?error={}",
session_id_str,
encode_domain_error(&e)
))
.into_response(),
}
}

View File

@@ -0,0 +1,7 @@
mod mapping;
mod preview;
mod upload;
pub use mapping::*;
pub use preview::*;
pub use upload::*;

View File

@@ -0,0 +1,131 @@
use crate::html::helpers::encode_domain_error;
use crate::html::mappers::import::annotated_to_preview_row;
use crate::html::render::render_page;
use crate::html::templates::{ImportPreviewRow, ImportPreviewTemplate};
use crate::{extractors::RequiredCookieUser, html::csrf::CsrfToken, state::AppState};
use application::import::{
commands::{ExecuteImportCommand, SaveImportProfileCommand},
execute as execute_import, get_preview_stage, save_profile as save_import_profile,
};
use axum::{
Extension, Form,
extract::{Path, State},
response::{IntoResponse, Redirect},
};
use domain::value_objects::ImportSessionId;
pub async fn get_preview_page(
State(state): State<AppState>,
RequiredCookieUser(user_id): RequiredCookieUser,
Path(session_id_str): Path<String>,
Extension(csrf): Extension<CsrfToken>,
) -> impl IntoResponse {
let Ok(session_id) = session_id_str
.parse::<uuid::Uuid>()
.map(ImportSessionId::from_uuid)
else {
return Redirect::to("/import").into_response();
};
let Ok(stage) = get_preview_stage::execute(
&state.app_ctx.deps.import.get_preview_stage,
session_id,
user_id.value(),
)
.await
else {
return Redirect::to("/import").into_response();
};
let preview = match stage {
get_preview_stage::PreviewStage::Ready(preview) => preview,
get_preview_stage::PreviewStage::NotYetMapped => {
return Redirect::to(&format!("/import/{}/mapping", session_id_str)).into_response();
}
};
let rows: Vec<ImportPreviewRow> = preview
.rows
.iter()
.enumerate()
.map(|(i, a)| annotated_to_preview_row(i, a))
.collect();
let ctx = crate::html::helpers::build_page_context(&state, Some(user_id), csrf.0).await;
render_page(ImportPreviewTemplate {
ctx: &ctx,
session_id: &session_id_str,
columns: &preview.columns,
rows: &rows,
})
.into_response()
}
pub async fn post_confirm(
State(state): State<AppState>,
RequiredCookieUser(user_id): RequiredCookieUser,
Path(session_id_str): Path<String>,
Extension(csrf): Extension<CsrfToken>,
Form(form_entries): Form<Vec<(String, String)>>,
) -> impl IntoResponse {
let csrf_token = form_entries
.iter()
.find(|(k, _)| k == "_csrf")
.map(|(_, v)| v.as_str())
.unwrap_or("");
if crate::html::csrf::mismatch(&csrf, csrf_token) {
return Redirect::to("/import").into_response();
}
let Ok(session_id) = session_id_str
.parse::<uuid::Uuid>()
.map(ImportSessionId::from_uuid)
else {
return Redirect::to("/import").into_response();
};
// Save profile if name provided
let profile_name = form_entries
.iter()
.find(|(k, _)| k == "profile_name")
.map(|(_, v)| v.clone())
.filter(|n| !n.trim().is_empty());
if let Some(name) = profile_name {
let _ = save_import_profile::execute(
&state.app_ctx.deps.import.save_profile,
SaveImportProfileCommand {
user_id: user_id.value(),
session_id: session_id.value(),
name,
},
)
.await;
}
// Collect all "confirmed" checkbox values
let confirmed: Vec<usize> = form_entries
.iter()
.filter(|(k, _)| k == "confirmed")
.filter_map(|(_, v)| v.parse::<usize>().ok())
.collect();
match execute_import::execute(
&state.app_ctx.deps.import.execute_import,
ExecuteImportCommand {
user_id: user_id.value(),
session_id: session_id.value(),
confirmed_indices: confirmed,
},
)
.await
{
Ok(summary) => Redirect::to(&format!(
"/import/done?imported={}&skipped={}&failed={}",
summary.imported,
summary.skipped_duplicates,
summary.failed.len()
))
.into_response(),
Err(e) => {
Redirect::to(&format!("/import?error={}", encode_domain_error(&e))).into_response()
}
}
}

View File

@@ -0,0 +1,147 @@
use crate::html::helpers::encode_domain_error;
use crate::html::render::render_page;
use crate::html::templates::{ImportProfileView, ImportUploadTemplate};
use crate::{extractors::RequiredCookieUser, html::csrf::CsrfToken, state::AppState};
use application::import::{
commands::{CreateImportSessionCommand, DeleteImportProfileCommand},
create_session as create_import_session, delete_profile as delete_import_profile,
list_profiles as list_import_profiles,
};
use axum::{
Extension, Form,
extract::{Multipart, Path, State},
response::{Html, IntoResponse, Redirect},
};
use domain::models::FileFormat;
use serde::Deserialize;
use std::collections::HashMap;
pub async fn get_import_page(
State(state): State<AppState>,
RequiredCookieUser(user_id): RequiredCookieUser,
Extension(csrf): Extension<CsrfToken>,
) -> impl IntoResponse {
let ctx = crate::html::helpers::build_page_context(&state, Some(user_id.clone()), csrf.0).await;
let profiles =
list_import_profiles::execute(&state.app_ctx.deps.import.list_profiles, &user_id)
.await
.unwrap_or_default()
.into_iter()
.map(|p| ImportProfileView {
id: p.id.value().to_string(),
name: p.name,
})
.collect::<Vec<_>>();
render_page(ImportUploadTemplate {
ctx: &ctx,
profiles: &profiles,
error: None,
})
}
pub async fn post_upload(
State(state): State<AppState>,
RequiredCookieUser(user_id): RequiredCookieUser,
mut multipart: Multipart,
) -> impl IntoResponse {
let mut file_bytes: Option<Vec<u8>> = None;
let mut format_str = "csv".to_string();
while let Ok(Some(field)) = multipart.next_field().await {
match field.name() {
Some("file") => {
if let Ok(bytes) = field.bytes().await {
file_bytes = Some(bytes.to_vec());
}
}
Some("format") => {
if let Ok(text) = field.text().await {
format_str = text;
}
}
_ => {}
}
}
let bytes = match file_bytes {
Some(b) if !b.is_empty() => b,
_ => return Redirect::to("/import?error=no+file+provided").into_response(),
};
let format = match format_str.as_str() {
"json" => FileFormat::Json,
"xlsx" => FileFormat::Xlsx,
_ => FileFormat::Csv,
};
match create_import_session::execute(
&state.app_ctx.deps.import.create_session,
CreateImportSessionCommand {
user_id: user_id.value(),
bytes,
format,
},
)
.await
{
Ok(r) => Redirect::to(&format!("/import/{}/mapping", r.session_id.value())).into_response(),
Err(e) => {
Redirect::to(&format!("/import?error={}", encode_domain_error(&e))).into_response()
}
}
}
pub async fn get_import_done(
State(state): State<AppState>,
RequiredCookieUser(user_id): RequiredCookieUser,
Extension(csrf): Extension<CsrfToken>,
axum::extract::Query(params): axum::extract::Query<ImportDoneParams>,
) -> impl IntoResponse {
let _ctx =
crate::html::helpers::build_page_context(&state, Some(user_id.clone()), csrf.0).await;
let html = format!(
r#"<!doctype html><html><body>
<h1>Import Complete</h1>
<p>Imported: {}</p>
<p>Skipped duplicates: {}</p>
<p>Failed: {}</p>
<a href="/users/{}">Go to My Profile</a>
</body></html>"#,
params.imported.unwrap_or(0),
params.skipped.unwrap_or(0),
params.failed.unwrap_or(0),
user_id.value(),
);
Html(html)
}
#[derive(Deserialize)]
pub struct ImportDoneParams {
pub imported: Option<usize>,
pub skipped: Option<usize>,
pub failed: Option<usize>,
}
pub async fn post_delete_profile(
State(state): State<AppState>,
RequiredCookieUser(user_id): RequiredCookieUser,
Path(profile_id_str): Path<String>,
Extension(csrf): Extension<CsrfToken>,
Form(form): Form<HashMap<String, String>>,
) -> impl IntoResponse {
let csrf_token = form.get("_csrf").map(|s| s.as_str()).unwrap_or("");
if crate::html::csrf::mismatch(&csrf, csrf_token) {
return Redirect::to("/import").into_response();
}
if let Ok(profile_id) = profile_id_str.parse::<uuid::Uuid>() {
let _ = delete_import_profile::execute(
&state.app_ctx.deps.import.delete_profile,
DeleteImportProfileCommand {
user_id: user_id.value(),
profile_id,
},
)
.await;
}
Redirect::to("/import").into_response()
}

View File

@@ -0,0 +1,211 @@
use crate::html::helpers::{build_page_context, encode_domain_error};
use crate::html::templates::{IntegrationsTemplate, WatchQueueTemplate};
use crate::{
extractors::RequiredCookieUser, html::csrf::CsrfToken, html::forms::ErrorQuery,
html::render::render_page, state::AppState,
};
use application::integrations::{
commands::{
ConfirmWatchEventsCommand, DismissWatchEventsCommand, GenerateWebhookTokenCommand,
RevokeWebhookTokenCommand, WatchEventConfirmation,
},
confirm as confirm_watch_events, dismiss as dismiss_watch_events,
generate_token as generate_webhook_token, get_queue as get_watch_queue,
get_tokens as get_webhook_tokens,
queries::{GetWatchQueueQuery, GetWebhookTokensQuery},
revoke_token as revoke_webhook_token,
};
use axum::{
Form,
extract::{Extension, Path, Query, State},
http::StatusCode,
response::{IntoResponse, Redirect},
};
use uuid::Uuid;
pub async fn get_integrations_page(
RequiredCookieUser(user_id): RequiredCookieUser,
State(state): State<AppState>,
Query(params): Query<crate::html::forms::IntegrationsQuery>,
Extension(csrf): Extension<CsrfToken>,
) -> impl IntoResponse {
let mut ctx = build_page_context(&state, Some(user_id.clone()), csrf.0).await;
ctx.page_title = "Integrations — Movies Diary".to_string();
ctx.canonical_url = format!("{}/settings/integrations", state.app_ctx.config.base_url);
let query = GetWebhookTokensQuery {
user_id: user_id.value(),
};
let tokens =
get_webhook_tokens::execute(&state.app_ctx.deps.integrations.get_webhook_tokens, query)
.await
.unwrap_or_default();
let token_views: Vec<crate::html::templates::WebhookTokenView> = tokens
.iter()
.map(crate::html::mappers::integrations::webhook_token_view)
.collect();
let webhook_base_url = state.app_ctx.config.base_url.clone();
render_page(IntegrationsTemplate {
ctx: &ctx,
tokens: &token_views,
webhook_base_url: &webhook_base_url,
new_token: params.token.as_deref(),
})
.into_response()
}
pub async fn post_generate_token(
RequiredCookieUser(user_id): RequiredCookieUser,
State(state): State<AppState>,
Extension(csrf): Extension<CsrfToken>,
Form(form): Form<crate::html::forms::GenerateTokenForm>,
) -> impl IntoResponse {
if crate::html::csrf::mismatch(&csrf, &form.csrf_token) {
return StatusCode::FORBIDDEN.into_response();
}
let provider = match form.provider.parse::<domain::models::WatchEventSource>() {
Ok(p) => p,
Err(_) => return Redirect::to("/settings/integrations").into_response(),
};
let cmd = GenerateWebhookTokenCommand {
user_id: user_id.value(),
provider,
label: form.label.filter(|l| !l.trim().is_empty()),
};
match generate_webhook_token::execute(
&state.app_ctx.deps.integrations.generate_webhook_token,
cmd,
)
.await
{
Ok(result) => {
let encoded = percent_encoding::utf8_percent_encode(
&result.token_plaintext,
percent_encoding::NON_ALPHANUMERIC,
);
Redirect::to(&format!("/settings/integrations?token={encoded}")).into_response()
}
Err(e) => {
tracing::error!("generate token failed: {:?}", e);
Redirect::to("/settings/integrations").into_response()
}
}
}
pub async fn post_revoke_token(
RequiredCookieUser(user_id): RequiredCookieUser,
State(state): State<AppState>,
Path(token_id): Path<Uuid>,
Extension(csrf): Extension<CsrfToken>,
Form(form): Form<crate::html::forms::RevokeTokenForm>,
) -> impl IntoResponse {
if crate::html::csrf::mismatch(&csrf, &form.csrf_token) {
return StatusCode::FORBIDDEN.into_response();
}
let cmd = RevokeWebhookTokenCommand {
user_id: user_id.value(),
token_id,
};
if let Err(e) =
revoke_webhook_token::execute(&state.app_ctx.deps.integrations.revoke_webhook_token, cmd)
.await
{
tracing::error!("revoke token failed: {:?}", e);
}
Redirect::to("/settings/integrations").into_response()
}
pub async fn get_watch_queue_page(
RequiredCookieUser(user_id): RequiredCookieUser,
State(state): State<AppState>,
Query(params): Query<ErrorQuery>,
Extension(csrf): Extension<CsrfToken>,
) -> impl IntoResponse {
let mut ctx = build_page_context(&state, Some(user_id.clone()), csrf.0).await;
ctx.page_title = "Watch Queue — Movies Diary".to_string();
ctx.canonical_url = format!("{}/watch-queue", state.app_ctx.config.base_url);
let query = GetWatchQueueQuery {
user_id: user_id.value(),
};
let events = get_watch_queue::execute(&state.app_ctx.deps.integrations.get_watch_queue, query)
.await
.unwrap_or_default();
let entries: Vec<crate::html::templates::WatchQueueDisplayEntry> = events
.iter()
.map(crate::html::mappers::integrations::watch_queue_entry)
.collect();
render_page(WatchQueueTemplate {
ctx: &ctx,
entries: &entries,
error: params.error.as_deref(),
})
.into_response()
}
pub async fn post_confirm_single(
RequiredCookieUser(user_id): RequiredCookieUser,
State(state): State<AppState>,
Path(event_id): Path<Uuid>,
Extension(csrf): Extension<CsrfToken>,
Form(form): Form<crate::html::forms::ConfirmWatchForm>,
) -> impl IntoResponse {
if crate::html::csrf::mismatch(&csrf, &form.csrf_token) {
return StatusCode::FORBIDDEN.into_response();
}
let cmd = ConfirmWatchEventsCommand {
user_id: user_id.value(),
confirmations: vec![WatchEventConfirmation {
watch_event_id: event_id,
rating: form.rating,
comment: form.comment.filter(|c| !c.trim().is_empty()),
}],
};
match confirm_watch_events::execute(&state.app_ctx.deps.integrations.confirm_watch_events, cmd)
.await
{
Ok(_) => Redirect::to("/watch-queue").into_response(),
Err(e) => {
let msg = encode_domain_error(&e);
Redirect::to(&format!("/watch-queue?error={msg}")).into_response()
}
}
}
pub async fn post_dismiss_single(
RequiredCookieUser(user_id): RequiredCookieUser,
State(state): State<AppState>,
Path(event_id): Path<Uuid>,
Extension(csrf): Extension<CsrfToken>,
Form(form): Form<crate::html::forms::DismissWatchForm>,
) -> impl IntoResponse {
if crate::html::csrf::mismatch(&csrf, &form.csrf_token) {
return StatusCode::FORBIDDEN.into_response();
}
let cmd = DismissWatchEventsCommand {
user_id: user_id.value(),
event_ids: vec![event_id],
};
match dismiss_watch_events::execute(&state.app_ctx.deps.integrations.dismiss_watch_events, cmd)
.await
{
Ok(_) => Redirect::to("/watch-queue").into_response(),
Err(e) => {
let msg = encode_domain_error(&e);
Redirect::to(&format!("/watch-queue?error={msg}")).into_response()
}
}
}

View File

@@ -0,0 +1,32 @@
use crate::html::templates::{ImportPreviewRow, ImportRowStatus};
use domain::models::AnnotatedRow;
use domain::models::import::RowResult;
pub fn annotated_to_preview_row(idx: usize, annotated: &AnnotatedRow) -> ImportPreviewRow {
match &annotated.result {
RowResult::Valid(row) => {
let cells = vec![
row.title.clone().unwrap_or_default(),
row.release_year.clone().unwrap_or_default(),
row.director.clone().unwrap_or_default(),
row.rating.clone().unwrap_or_default(),
row.watched_at.clone().unwrap_or_default(),
row.comment.clone().unwrap_or_default(),
];
ImportPreviewRow {
index: idx,
status: if annotated.is_duplicate {
ImportRowStatus::Duplicate
} else {
ImportRowStatus::Valid
},
cells,
}
}
RowResult::Invalid { errors, raw } => ImportPreviewRow {
index: idx,
status: ImportRowStatus::Invalid(errors.join("; ")),
cells: raw.iter().map(|(_, v)| v.clone()).collect(),
},
}
}

View File

@@ -0,0 +1,25 @@
use crate::html::templates::{WatchQueueDisplayEntry, WebhookTokenView};
use domain::models::{WatchEvent, WebhookToken};
pub fn webhook_token_view(t: &WebhookToken) -> WebhookTokenView {
WebhookTokenView {
id: t.id().value().to_string(),
provider: t.provider().to_string(),
label: t.label().map(String::from),
created_at: t.created_at().format("%Y-%m-%d %H:%M").to_string(),
last_used_at: t
.last_used_at()
.map(|d| d.format("%Y-%m-%d %H:%M").to_string()),
}
}
pub fn watch_queue_entry(e: &WatchEvent) -> WatchQueueDisplayEntry {
WatchQueueDisplayEntry {
id: e.id().value().to_string(),
title: e.title().to_string(),
year: e.year(),
source: e.source().to_string(),
watched_at: e.watched_at().format("%Y-%m-%d %H:%M").to_string(),
movie_url: e.movie_id().map(|m| format!("/movies/{}", m.value())),
}
}

View File

@@ -0,0 +1,4 @@
pub mod import;
pub mod integrations;
pub mod users;
pub mod watchlist;

View File

@@ -0,0 +1,45 @@
use crate::html::templates::{RemoteActorData, RemoteActorDisplay, UserSummaryView};
use application::users::get_local_profile::PendingFollowerView;
use domain::models::RemoteActorInfo;
use domain::models::UserSummary;
pub fn user_summary_view(u: &UserSummary) -> UserSummaryView {
let name = u
.display_name()
.map(String::from)
.unwrap_or_else(|| u.username().to_string());
let initial = name.chars().next().unwrap_or('?').to_ascii_uppercase();
let avg_display = u
.avg_rating
.map(|r| format!("{:.1}", r))
.unwrap_or_else(|| "\u{2014}".to_string());
let avatar_url = u.avatar_path.as_ref().map(|p| format!("/images/{}", p));
UserSummaryView {
user_id: u.user_id.value(),
display_name: name,
initial,
avg_rating_display: avg_display,
total_movies: u.total_movies,
avatar_url,
}
}
pub fn remote_actor_display(a: &RemoteActorInfo) -> RemoteActorDisplay {
let display = a.display_name.clone().unwrap_or_else(|| a.handle.clone());
let initial = display.chars().next().unwrap_or('?').to_ascii_uppercase();
RemoteActorDisplay {
handle: a.handle.clone(),
display_name: display,
initial,
url: a.url.clone(),
}
}
pub fn pending_follower_data(p: &PendingFollowerView) -> RemoteActorData {
RemoteActorData {
handle: p.handle.clone(),
url: p.url.clone(),
display_name: p.display_name.clone(),
avatar_url: p.avatar_url.clone(),
}
}

View File

@@ -0,0 +1,65 @@
use crate::html::templates::WatchlistDisplayEntry;
use domain::models::{RemoteWatchlistEntry, WatchlistWithMovie, collections::Paginated};
pub struct WatchlistPageResult {
pub display_entries: Vec<WatchlistDisplayEntry>,
pub has_more: bool,
pub current_offset: u32,
pub limit: u32,
}
pub fn build_watchlist_page(
page: Paginated<WatchlistWithMovie>,
is_owner: bool,
) -> WatchlistPageResult {
let has_more = page.offset + page.limit < page.total_count as u32;
let display_entries = page
.items
.iter()
.map(|w| {
let remove_url = if is_owner {
Some(format!("/watchlist/{}/remove", w.movie.id().value()))
} else {
None
};
WatchlistDisplayEntry {
poster_url: w
.movie
.poster_path()
.map(|p| format!("/images/{}", p.value())),
movie_title: w.movie.title().value().to_string(),
release_year: w.movie.release_year().value(),
movie_url: Some(format!("/movies/{}", w.movie.id().value())),
added_at: w.entry.added_at.format("%b %-d, %Y").to_string(),
remove_url,
}
})
.collect();
WatchlistPageResult {
display_entries,
has_more,
current_offset: page.offset,
limit: page.limit,
}
}
pub fn build_remote_watchlist_page(entries: Vec<RemoteWatchlistEntry>) -> WatchlistPageResult {
let len = entries.len() as u32;
let display_entries = entries
.into_iter()
.map(|e| WatchlistDisplayEntry {
poster_url: e.poster_url,
movie_title: e.movie_title,
release_year: e.release_year,
movie_url: None,
added_at: e.added_at.format("%b %-d, %Y").to_string(),
remove_url: None,
})
.collect();
WatchlistPageResult {
display_entries,
has_more: false,
current_offset: 0,
limit: len,
}
}

View File

@@ -1 +1,163 @@
pub mod csrf;
pub mod forms;
pub(crate) mod helpers;
mod mappers;
pub mod render;
pub mod templates;
mod auth;
mod diary;
mod images;
mod import;
mod integrations;
mod movies;
mod profile;
mod rss;
mod social;
mod tags;
mod users;
mod watchlist;
mod wrapup;
use axum::{Router, routing};
use crate::state::AppState;
/// Classic server-rendered UI routes, minus the rate-limited auth forms
/// ([`auth_router`]) and the federation-gated pages (`federation::html_routes`).
pub fn router() -> Router<AppState> {
let base = Router::new()
.route("/", routing::get(diary::get_activity_feed_html))
.route("/users", routing::get(users::get_users_list))
.route("/u/{username}", routing::get(users::get_user_by_username))
.route("/users/{id}", routing::get(profile::get_user_profile_html))
.route(
"/movies/{movie_id}",
routing::get(movies::get_movie_detail_html),
)
.route("/reviews/new", routing::get(diary::get_new_review_page))
.route("/reviews", routing::post(diary::post_review_html))
.route(
"/reviews/{id}/delete",
routing::post(diary::post_delete_review_html),
)
.route("/images/{*key}", routing::get(images::get_image))
.route(
"/posters/{path}",
routing::get(
|axum::extract::Path(p): axum::extract::Path<String>| async move {
axum::response::Redirect::permanent(&format!("/images/{}", p))
},
),
)
.route("/diary/export", routing::get(diary::get_export_html))
.route("/import", routing::get(import::get_import_page))
.route("/import/upload", routing::post(import::post_upload))
.route(
"/import/{id}/mapping",
routing::get(import::get_mapping_page).post(import::post_mapping),
)
.route(
"/import/{id}/preview",
routing::get(import::get_preview_page),
)
.route("/import/{id}/confirm", routing::post(import::post_confirm))
.route("/import/done", routing::get(import::get_import_done))
.route(
"/import/profiles/{profile_id}/delete",
routing::post(import::post_delete_profile),
)
.route("/feed.rss", routing::get(rss::get_feed))
.route("/users/{id}/feed.rss", routing::get(rss::get_user_feed))
.route(
"/settings/profile",
routing::get(users::get_profile_settings).post(users::post_profile_settings),
)
.route("/tags/{tag}", routing::get(tags::get_tag))
.route(
"/users/{id}/watchlist",
routing::get(watchlist::get_watchlist_page),
)
.route(
"/watchlist/add",
routing::post(watchlist::post_watchlist_add_html),
)
.route(
"/watchlist/{movie_id}/remove",
routing::post(watchlist::post_watchlist_remove_html),
)
.route(
"/settings/integrations",
routing::get(integrations::get_integrations_page),
)
.route(
"/settings/integrations/generate",
routing::post(integrations::post_generate_token),
)
.route(
"/settings/integrations/{id}/revoke",
routing::post(integrations::post_revoke_token),
)
.route(
"/watch-queue",
routing::get(integrations::get_watch_queue_page),
)
.route(
"/watch-queue/{id}/confirm",
routing::post(integrations::post_confirm_single),
)
.route(
"/watch-queue/{id}/dismiss",
routing::post(integrations::post_dismiss_single),
)
.route(
"/wrapups/{user_id}/{year}",
routing::get(wrapup::get_user_wrapup_html),
)
.route(
"/wrapups/global/{year}",
routing::get(wrapup::get_global_wrapup_html),
);
base.merge(social_routes())
}
/// Login, logout and registration forms; the caller adds the auth rate limiter.
pub fn auth_router() -> Router<AppState> {
Router::new()
.route(
"/login",
routing::get(auth::get_login_page).post(auth::post_login),
)
.route("/logout", routing::get(auth::get_logout))
.route(
"/register",
routing::get(auth::get_register_page).post(auth::post_register),
)
}
fn social_routes() -> Router<AppState> {
Router::new()
.route("/users/{id}/follow", routing::post(social::follow_user))
.route("/users/{id}/unfollow", routing::post(social::unfollow_user))
.route(
"/users/{id}/followers/accept",
routing::post(social::accept_follower_html),
)
.route(
"/users/{id}/followers/reject",
routing::post(social::reject_follower_html),
)
.route(
"/users/{id}/followers/remove",
routing::post(social::remove_follower_html),
)
.route(
"/users/{id}/following-list",
routing::get(social::get_following_page),
)
.route(
"/users/{id}/followers-list",
routing::get(social::get_followers_page),
)
}

View File

@@ -0,0 +1,77 @@
use crate::html::helpers::build_page_context;
use crate::html::templates::MovieDetailTemplate;
use crate::{
extractors::OptionalCookieUser, html::csrf::CsrfToken, html::render::render_page,
state::AppState,
};
use application::{
diary::{get_movie_social_page, queries::GetMovieSocialPageQuery},
watchlist::{is_on as is_on_watchlist, queries::IsOnWatchlistQuery},
};
use axum::{
extract::{Extension, Path, Query, State},
response::IntoResponse,
};
pub async fn get_movie_detail_html(
OptionalCookieUser(user_id): OptionalCookieUser,
State(state): State<AppState>,
Path(movie_id): Path<uuid::Uuid>,
Query(params): Query<api_types::PaginationQueryParams>,
Extension(csrf): Extension<CsrfToken>,
) -> impl IntoResponse {
let ctx = build_page_context(&state, user_id.clone(), csrf.0).await;
let limit = params.limit.unwrap_or(20);
let offset = params.offset.unwrap_or(0);
match get_movie_social_page::execute(
&state.app_ctx.deps.diary.get_movie_social_page,
GetMovieSocialPageQuery {
movie_id,
limit,
offset,
},
)
.await
{
Err(e) => crate::errors::domain_error_response(e),
Ok(result) => {
let histogram_max = result
.stats
.rating_histogram
.iter()
.copied()
.max()
.unwrap_or(1);
let has_more =
result.reviews.offset + result.reviews.limit < result.reviews.total_count as u32;
let on_watchlist = match &user_id {
Some(uid) => is_on_watchlist::execute(
&state.app_ctx.deps.watchlist.is_on_watchlist,
IsOnWatchlistQuery {
user_id: uid.value(),
movie_id,
},
)
.await
.unwrap_or(false),
None => false,
};
let current_offset = result.reviews.offset;
let reviews_limit = result.reviews.limit;
render_page(MovieDetailTemplate {
ctx: &ctx,
movie: &result.movie,
stats: &result.stats,
profile: result.profile.as_ref(),
reviews: result.reviews.items.as_slice(),
on_watchlist,
current_offset,
has_more,
limit: reviews_limit,
histogram_max,
})
.into_response()
}
}
}

View File

@@ -0,0 +1,260 @@
use crate::html::helpers::build_page_context;
use crate::html::templates::{
EmbedProfileTemplate, MonthlyRatingRow, ProfileTemplate, RemoteActorData, bar_height_px,
build_heatmap, build_page_items,
};
use crate::{
extractors::OptionalCookieUser, html::csrf::CsrfToken, html::render::render_page,
state::AppState,
};
use application::users::get_local_profile;
use axum::{
extract::{Extension, Path, Query, State},
http::StatusCode,
response::IntoResponse,
};
use domain::errors::DomainError;
use std::str::FromStr;
use uuid::Uuid;
const DEFAULT_PAGE_LIMIT: u32 = 5;
struct PaginationInfo {
offset: u32,
has_more: bool,
limit: u32,
page_items: Vec<crate::html::templates::PageItem>,
}
fn compute_pagination(
entries: Option<&domain::models::collections::Paginated<domain::models::DiaryEntry>>,
) -> PaginationInfo {
let (offset, has_more, limit) = entries
.map(|e| {
let has_more = (e.offset as u64).saturating_add(e.limit as u64) < e.total_count;
(e.offset, has_more, e.limit)
})
.unwrap_or((0, false, DEFAULT_PAGE_LIMIT));
let total = entries.map(|e| e.total_count as u32).unwrap_or(0);
let total_pages = total
.saturating_add(limit.saturating_sub(1))
.checked_div(limit)
.unwrap_or(1);
let current_page = offset.checked_div(limit).unwrap_or(0);
let page_items = build_page_items(total_pages, current_page);
PaginationInfo {
offset,
has_more,
limit,
page_items,
}
}
struct StatsDisplay {
avg_rating: String,
favorite_director: String,
most_active_month: String,
}
fn build_stats_display(stats: &domain::models::UserStats) -> StatsDisplay {
StatsDisplay {
avg_rating: stats
.avg_rating
.map(|r| format!("{:.1}", r))
.unwrap_or_else(|| "\u{2014}".to_string()),
favorite_director: stats
.favorite_director
.clone()
.unwrap_or_else(|| "\u{2014}".to_string()),
most_active_month: stats
.most_active_month
.clone()
.unwrap_or_else(|| "\u{2014}".to_string()),
}
}
fn build_monthly_rating_rows<'a>(
trends: Option<&'a domain::models::UserTrends>,
) -> Vec<MonthlyRatingRow<'a>> {
trends
.map(|t| {
t.monthly_ratings
.iter()
.map(|r| MonthlyRatingRow {
rating: r,
bar_height_px: bar_height_px(r.avg_rating),
})
.collect()
})
.unwrap_or_default()
}
async fn fetch_profile_goals(
state: &AppState,
user_id: Uuid,
) -> Vec<crate::html::templates::GoalViewData> {
let goals_list = application::goals::list::execute(
&state.app_ctx.deps.goals.query,
application::goals::queries::ListGoalsQuery { user_id },
)
.await
.unwrap_or_default();
goals_list
.iter()
.map(|g| crate::html::templates::GoalViewData {
year: g.goal.year(),
target_count: g.goal.target_count(),
current_count: g.current_count,
percentage: g.percentage().round(),
is_complete: g.is_complete(),
})
.collect()
}
pub async fn get_user_profile_html(
OptionalCookieUser(user_id): OptionalCookieUser,
State(state): State<AppState>,
Path(profile_user_uuid): Path<Uuid>,
headers: axum::http::HeaderMap,
Query(params): Query<crate::html::forms::ProfileQueryParams>,
Extension(csrf): Extension<CsrfToken>,
) -> impl IntoResponse {
// Content negotiation: AP clients request application/activity+json
if let Some(response) =
crate::federation::actor_document_response(&state, &headers, profile_user_uuid).await
{
return response;
}
let mut ctx = build_page_context(&state, user_id.clone(), csrf.0).await;
let view_str = params.view.as_deref().unwrap_or("recent");
let profile_view = match application::users::queries::ProfileView::from_str(view_str) {
Ok(v) => v,
Err(_) => {
return (
axum::http::StatusCode::BAD_REQUEST,
"invalid view parameter",
)
.into_response();
}
};
let sort_by_str = match params.sort_by.as_str() {
"date_asc" => "date_asc",
"rating" => "rating",
"rating_asc" => "rating_asc",
_ => "date",
};
let is_own_profile = user_id
.as_ref()
.map(|u| u.value() == profile_user_uuid)
.unwrap_or(false);
let query = application::users::queries::GetUserProfileQuery {
user_id: profile_user_uuid,
view: profile_view,
limit: params.limit,
offset: params.offset,
sort_by: sort_by_str.parse().unwrap_or_default(),
search: if params.search.is_empty() {
None
} else {
Some(params.search.clone())
},
is_own_profile,
include_remote: false,
};
match get_local_profile::execute(&state.app_ctx.deps.users.get_local_profile, query).await {
Ok(profile) => {
ctx.page_title = format!("{}'s Diary — Movies Diary", profile.identity.username);
ctx.canonical_url = format!(
"{}/users/{}",
state.app_ctx.config.base_url, profile_user_uuid
);
let pag = compute_pagination(profile.entries.as_ref());
if !is_own_profile {
ctx.page_rss_url = Some(format!("/users/{}/feed.rss", profile_user_uuid));
}
let display_name = profile
.identity
.email
.split('@')
.next()
.unwrap_or("?")
.to_string();
let stats_disp = build_stats_display(&profile.stats);
let history = profile.history.map(application::users::group_by_month);
let heatmap = history.as_deref().map(build_heatmap).unwrap_or_default();
let monthly_rating_rows = build_monthly_rating_rows(profile.trends.as_ref());
let pending_followers: Vec<RemoteActorData> = profile
.pending_followers
.iter()
.map(crate::html::mappers::users::pending_follower_data)
.collect();
if params.embed {
let profile_url = format!(
"{}/users/{}",
state.app_ctx.config.base_url, profile_user_uuid
);
let response = render_page(EmbedProfileTemplate {
profile_display_name: display_name,
profile_user_id: profile_user_uuid,
profile_url,
stats: &profile.stats,
avg_rating_display: stats_disp.avg_rating,
favorite_director_display: stats_disp.favorite_director,
most_active_month_display: stats_disp.most_active_month,
view: profile_view.as_str(),
entries: profile.entries.as_ref(),
current_offset: pag.offset,
has_more: pag.has_more,
limit: pag.limit,
history: history.as_ref(),
trends: profile.trends.as_ref(),
monthly_rating_rows,
heatmap,
page_items: pag.page_items,
sort_by: sort_by_str.to_string(),
});
let mut resp = response.into_response();
resp.headers_mut().remove("x-frame-options");
resp
} else {
let goals = fetch_profile_goals(&state, profile_user_uuid).await;
render_page(ProfileTemplate {
ctx: &ctx,
profile_display_name: display_name,
profile_user_id: profile_user_uuid,
stats: &profile.stats,
avg_rating_display: stats_disp.avg_rating,
favorite_director_display: stats_disp.favorite_director,
most_active_month_display: stats_disp.most_active_month,
view: profile_view.as_str(),
entries: profile.entries.as_ref(),
current_offset: pag.offset,
has_more: pag.has_more,
limit: pag.limit,
history: history.as_ref(),
trends: profile.trends.as_ref(),
monthly_rating_rows,
heatmap,
page_items: pag.page_items,
is_own_profile,
error: params.error,
following_count: profile.following_count,
followers_count: profile.followers_count,
pending_followers,
sort_by: sort_by_str.to_string(),
search: params.search.clone(),
goals,
})
.into_response()
}
}
Err(DomainError::NotFound(_)) => StatusCode::NOT_FOUND.into_response(),
Err(e) => crate::errors::domain_error_response(e),
}
}

View File

@@ -0,0 +1,14 @@
use axum::{
http::StatusCode,
response::{Html, IntoResponse, Response},
};
pub fn render_page(template: impl askama::Template) -> Response {
match template.render() {
Ok(html) => Html(html).into_response(),
Err(e) => {
tracing::error!("template error: {e}");
StatusCode::INTERNAL_SERVER_ERROR.into_response()
}
}
}

View File

@@ -0,0 +1,70 @@
use crate::{errors::ApiError, state::AppState};
use application::{diary::get_diary, diary::get_user_feed, diary::queries::GetDiaryQuery};
use axum::{
extract::{Path, State},
http::header,
response::IntoResponse,
};
use domain::{models::ReviewSortBy, ports::FeedChannel};
use uuid::Uuid;
const RSS_FEED_LIMIT: u32 = 50;
pub async fn get_feed(State(state): State<AppState>) -> Result<impl IntoResponse, ApiError> {
let query = GetDiaryQuery {
limit: Some(RSS_FEED_LIMIT),
offset: Some(0),
sort_by: Some(ReviewSortBy::Descending),
movie_id: None,
user_id: None,
};
let page = get_diary::execute(&state.app_ctx.deps.diary.get_diary, query).await?;
let xml = state
.rss_renderer
.render_feed(
&page.items,
&FeedChannel {
title: "Movie Diary",
link_path: "/",
self_path: "/feed.rss",
},
)
.map_err(ApiError)?;
Ok((
[(header::CONTENT_TYPE, "application/xml; charset=utf-8")],
xml,
))
}
pub async fn get_user_feed(
State(state): State<AppState>,
Path(user_id): Path<Uuid>,
) -> Result<impl IntoResponse, ApiError> {
let feed = get_user_feed::execute(
&state.app_ctx.deps.diary.get_user_feed,
user_id,
RSS_FEED_LIMIT,
)
.await?;
let title = format!("{}'s Movie Diary", feed.author.display_name);
let link_path = format!("/users/{user_id}");
let self_path = format!("/users/{user_id}/feed.rss");
let xml = state
.rss_renderer
.render_feed(
&feed.entries,
&FeedChannel {
title: &title,
link_path: &link_path,
self_path: &self_path,
},
)
.map_err(ApiError)?;
Ok((
[(header::CONTENT_TYPE, "application/xml; charset=utf-8")],
xml,
))
}

View File

@@ -0,0 +1,319 @@
use crate::html::helpers::{build_page_context, encode_domain_error};
use crate::html::templates::{FollowersTemplate, FollowingTemplate, RemoteActorData};
use crate::{
extractors::RequiredCookieUser,
html::csrf::CsrfToken,
html::forms::{FollowForm, FollowerActionForm, UnfollowForm},
html::render::render_page,
state::AppState,
};
use axum::{
Form,
extract::{Extension, Path, Query, State},
http::StatusCode,
response::{IntoResponse, Redirect},
};
use domain::value_objects::{FollowTarget, InstanceIdentity, SocialActor};
use uuid::Uuid;
fn social_actor_to_template(actor: SocialActor, instance: &InstanceIdentity) -> RemoteActorData {
RemoteActorData {
url: instance.actor_url_of(&actor.identity),
handle: actor.handle,
display_name: actor.display_name,
avatar_url: actor.avatar_url,
}
}
pub async fn follow_user(
RequiredCookieUser(user_id): RequiredCookieUser,
State(state): State<AppState>,
Path(profile_user_uuid): Path<Uuid>,
Extension(csrf): Extension<CsrfToken>,
Form(form): Form<FollowForm>,
) -> impl IntoResponse {
if user_id.value() != profile_user_uuid {
return StatusCode::FORBIDDEN.into_response();
}
if crate::html::csrf::mismatch(&csrf, &form.csrf_token) {
return StatusCode::FORBIDDEN.into_response();
}
let redirect_base = form
.redirect_after
.as_deref()
.filter(|u| u.starts_with('/') && !u.starts_with("//"))
.unwrap_or(&format!("/users/{}", profile_user_uuid))
.to_string();
match application::social::execute::execute_command(
&state.app_ctx.deps.social.command,
application::social::commands::SocialCmd::Follow {
follower_id: user_id.value(),
target: FollowTarget::Handle(form.handle),
},
)
.await
{
Ok(()) => Redirect::to(&redirect_base).into_response(),
Err(e) => {
tracing::error!("follow error: {:?}", e);
let msg = encode_domain_error(&e);
let sep = if redirect_base.contains('?') {
'&'
} else {
'?'
};
Redirect::to(&format!("{}{}error={}", redirect_base, sep, msg)).into_response()
}
}
}
pub async fn unfollow_user(
RequiredCookieUser(user_id): RequiredCookieUser,
State(state): State<AppState>,
Path(profile_user_uuid): Path<Uuid>,
Extension(csrf): Extension<CsrfToken>,
Form(form): Form<UnfollowForm>,
) -> impl IntoResponse {
if user_id.value() != profile_user_uuid {
return StatusCode::FORBIDDEN.into_response();
}
if crate::html::csrf::mismatch(&csrf, &form.csrf_token) {
return StatusCode::FORBIDDEN.into_response();
}
let instance = state.app_ctx.instance.clone();
match application::social::execute::execute_command(
&state.app_ctx.deps.social.command,
application::social::commands::SocialCmd::Unfollow {
follower_id: user_id.value(),
target: instance.identify(&form.actor_url),
},
)
.await
{
Ok(()) => {
Redirect::to(&format!("/users/{}/following-list", profile_user_uuid)).into_response()
}
Err(e) => {
let msg = encode_domain_error(&e);
Redirect::to(&format!(
"/users/{}/following-list?error={}",
profile_user_uuid, msg
))
.into_response()
}
}
}
pub async fn accept_follower_html(
RequiredCookieUser(user_id): RequiredCookieUser,
State(state): State<AppState>,
Path(profile_user_uuid): Path<Uuid>,
Extension(csrf): Extension<CsrfToken>,
Form(form): Form<FollowerActionForm>,
) -> impl IntoResponse {
if user_id.value() != profile_user_uuid {
return StatusCode::FORBIDDEN.into_response();
}
if crate::html::csrf::mismatch(&csrf, &form.csrf_token) {
return StatusCode::FORBIDDEN.into_response();
}
let instance = state.app_ctx.instance.clone();
match application::social::execute::execute_command(
&state.app_ctx.deps.social.command,
application::social::commands::SocialCmd::AcceptFollow {
owner_id: user_id.value(),
requester: instance.identify(&form.actor_url),
},
)
.await
{
Ok(_) => Redirect::to(&format!("/users/{}", profile_user_uuid)).into_response(),
Err(e) => {
let msg = encode_domain_error(&e);
Redirect::to(&format!("/users/{}?error={}", profile_user_uuid, msg)).into_response()
}
}
}
pub async fn reject_follower_html(
RequiredCookieUser(user_id): RequiredCookieUser,
State(state): State<AppState>,
Path(profile_user_uuid): Path<Uuid>,
Extension(csrf): Extension<CsrfToken>,
Form(form): Form<FollowerActionForm>,
) -> impl IntoResponse {
if user_id.value() != profile_user_uuid {
return StatusCode::FORBIDDEN.into_response();
}
if crate::html::csrf::mismatch(&csrf, &form.csrf_token) {
return StatusCode::FORBIDDEN.into_response();
}
let instance = state.app_ctx.instance.clone();
match application::social::execute::execute_command(
&state.app_ctx.deps.social.command,
application::social::commands::SocialCmd::RejectFollow {
owner_id: user_id.value(),
requester: instance.identify(&form.actor_url),
},
)
.await
{
Ok(_) => Redirect::to(&format!("/users/{}", profile_user_uuid)).into_response(),
Err(e) => {
let msg = encode_domain_error(&e);
Redirect::to(&format!("/users/{}?error={}", profile_user_uuid, msg)).into_response()
}
}
}
pub async fn get_following_page(
RequiredCookieUser(user_id): RequiredCookieUser,
State(state): State<AppState>,
Path(profile_user_uuid): Path<Uuid>,
Query(params): Query<crate::html::forms::ErrorQuery>,
Extension(csrf): Extension<CsrfToken>,
) -> impl IntoResponse {
if user_id.value() != profile_user_uuid {
return StatusCode::FORBIDDEN.into_response();
}
let mut ctx = build_page_context(&state, Some(user_id.clone()), csrf.0).await;
ctx.page_title = "Following — Movies Diary".to_string();
ctx.canonical_url = format!(
"{}/users/{}/following-list",
state.app_ctx.config.base_url, profile_user_uuid
);
let instance = state.app_ctx.instance.clone();
match application::social::get_following::execute(
&state.app_ctx.deps.social.query,
user_id.value(),
)
.await
{
Ok(following) => {
let actors: Vec<RemoteActorData> = following
.into_iter()
.map(|a| social_actor_to_template(a, &instance))
.collect();
let pending_actors: Vec<RemoteActorData> =
match application::social::get_pending_following::execute(
&state.app_ctx.deps.social.query,
user_id.value(),
)
.await
{
Ok(pending) => pending
.into_iter()
.map(|a| social_actor_to_template(a, &instance))
.collect(),
Err(e) => {
tracing::error!("get_pending_following error: {:?}", e);
Vec::new()
}
};
render_page(FollowingTemplate {
ctx,
user_id: profile_user_uuid,
actors,
pending_actors,
error: params.error,
})
.into_response()
}
Err(e) => {
tracing::error!("get_following error: {:?}", e);
(
StatusCode::INTERNAL_SERVER_ERROR,
"Failed to load following list",
)
.into_response()
}
}
}
pub async fn get_followers_page(
RequiredCookieUser(user_id): RequiredCookieUser,
State(state): State<AppState>,
Path(profile_user_uuid): Path<Uuid>,
Query(params): Query<crate::html::forms::ErrorQuery>,
Extension(csrf): Extension<CsrfToken>,
) -> impl IntoResponse {
if user_id.value() != profile_user_uuid {
return StatusCode::FORBIDDEN.into_response();
}
let mut ctx = build_page_context(&state, Some(user_id.clone()), csrf.0).await;
ctx.page_title = "Followers — Movies Diary".to_string();
ctx.canonical_url = format!(
"{}/users/{}/followers-list",
state.app_ctx.config.base_url, profile_user_uuid
);
let instance = state.app_ctx.instance.clone();
match application::social::get_followers::execute(
&state.app_ctx.deps.social.query,
user_id.value(),
)
.await
{
Ok(followers) => {
let actors: Vec<RemoteActorData> = followers
.into_iter()
.map(|a| social_actor_to_template(a, &instance))
.collect();
render_page(FollowersTemplate {
ctx,
user_id: profile_user_uuid,
actors,
error: params.error,
})
.into_response()
}
Err(e) => {
tracing::error!("get_followers error: {:?}", e);
(
StatusCode::INTERNAL_SERVER_ERROR,
"Failed to load followers list",
)
.into_response()
}
}
}
pub async fn remove_follower_html(
RequiredCookieUser(user_id): RequiredCookieUser,
State(state): State<AppState>,
Path(profile_user_uuid): Path<Uuid>,
Extension(csrf): Extension<CsrfToken>,
Form(form): Form<FollowerActionForm>,
) -> impl IntoResponse {
if user_id.value() != profile_user_uuid {
return StatusCode::FORBIDDEN.into_response();
}
if crate::html::csrf::mismatch(&csrf, &form.csrf_token) {
return StatusCode::FORBIDDEN.into_response();
}
let instance = state.app_ctx.instance.clone();
match application::social::execute::execute_command(
&state.app_ctx.deps.social.command,
application::social::commands::SocialCmd::RemoveFollower {
owner_id: user_id.value(),
follower: instance.identify(&form.actor_url),
},
)
.await
{
Ok(_) => {
Redirect::to(&format!("/users/{}/followers-list", profile_user_uuid)).into_response()
}
Err(e) => {
let msg = encode_domain_error(&e);
Redirect::to(&format!(
"/users/{}/followers-list?error={}",
profile_user_uuid, msg
))
.into_response()
}
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,22 @@
use super::*;
use domain::value_objects::{InstanceIdentity, SocialActor, SocialIdentity, UserId};
fn local_actor(uid: &UserId) -> SocialActor {
SocialActor {
identity: SocialIdentity::Local(uid.clone()),
handle: "@gabriel@md.example".into(),
display_name: None,
avatar_url: None,
}
}
#[test]
fn local_template_url_round_trips_back_to_the_same_identity() {
let instance = InstanceIdentity::new("https://md.example");
let uid = UserId::from_uuid(uuid::Uuid::new_v4());
let data = social_actor_to_template(local_actor(&uid), &instance);
assert!(!data.url.starts_with("local:"), "url was {}", data.url);
assert_eq!(instance.identify(&data.url), SocialIdentity::Local(uid));
}

View File

@@ -0,0 +1,12 @@
use axum::{
extract::Path,
response::{IntoResponse, Redirect},
};
pub async fn get_tag(Path(tag): Path<String>) -> impl IntoResponse {
if tag.eq_ignore_ascii_case("moviesdiary") {
Redirect::temporary("/")
} else {
Redirect::temporary(&format!("/?search={}", tag))
}
}

View File

@@ -1,495 +0,0 @@
pub use askama;
use askama::Template;
use api_types::HtmlPageContext;
use chrono::Datelike;
use domain::models::{
DiaryEntry, FeedEntry, MonthActivity, MonthlyRating, ReviewSource, UserStats, UserTrends,
collections::Paginated,
};
#[derive(Clone, Debug)]
pub struct WatchlistDisplayEntry {
pub poster_url: Option<String>,
pub movie_title: String,
pub release_year: u16,
pub movie_url: Option<String>,
pub added_at: String,
pub remove_url: Option<String>,
}
mod filters {
#[askama::filter_fn]
pub fn poster_src<T: std::fmt::Display>(
path: T,
_env: &dyn askama::Values,
) -> askama::Result<String> {
let p = path.to_string();
if p.starts_with("http://") || p.starts_with("https://") {
Ok(p)
} else {
Ok(format!("/images/{}", p))
}
}
}
pub struct PageItem {
pub number: u32,
pub is_current: bool,
pub is_ellipsis: bool,
}
pub fn build_page_items(total_pages: u32, current_page: u32) -> Vec<PageItem> {
if total_pages <= 1 {
return vec![];
}
let mut set = std::collections::BTreeSet::new();
set.insert(0u32);
set.insert(total_pages - 1);
let start = current_page.saturating_sub(2);
let end = (current_page + 2).min(total_pages - 1);
for p in start..=end {
set.insert(p);
}
let pages: Vec<u32> = set.into_iter().collect();
let mut items = Vec::new();
for (i, &p) in pages.iter().enumerate() {
if i > 0 && p > pages[i - 1] + 1 {
items.push(PageItem {
number: 0,
is_current: false,
is_ellipsis: true,
});
}
items.push(PageItem {
number: p,
is_current: p == current_page,
is_ellipsis: false,
});
}
items
}
#[derive(Template)]
#[template(path = "diary.html")]
pub struct DiaryTemplate<'a> {
pub entries: &'a [DiaryEntry],
pub current_offset: u32,
pub limit: u32,
pub has_more: bool,
pub ctx: &'a HtmlPageContext,
pub page_items: Vec<PageItem>,
}
#[derive(Template)]
#[template(path = "login.html")]
pub struct LoginTemplate<'a> {
pub error: Option<&'a str>,
pub ctx: &'a HtmlPageContext,
}
#[derive(Template)]
#[template(path = "register.html")]
pub struct RegisterTemplate<'a> {
pub error: Option<&'a str>,
pub ctx: &'a HtmlPageContext,
}
#[derive(Template)]
#[template(path = "new_review.html")]
pub struct NewReviewTemplate<'a> {
pub error: Option<&'a str>,
pub ctx: &'a HtmlPageContext,
}
#[derive(Template)]
#[template(path = "activity_feed.html")]
pub struct ActivityFeedTemplate<'a> {
pub entries: &'a [FeedEntry],
pub current_offset: u32,
pub limit: u32,
pub has_more: bool,
pub ctx: &'a HtmlPageContext,
pub page_items: Vec<PageItem>,
pub filter: String,
pub sort_by: String,
pub search: String,
}
#[derive(Template)]
#[template(path = "movie_detail.html")]
pub struct MovieDetailTemplate<'a> {
pub ctx: &'a HtmlPageContext,
pub movie: &'a domain::models::Movie,
pub stats: &'a domain::models::MovieStats,
pub profile: Option<&'a domain::models::MovieProfile>,
pub reviews: &'a [domain::models::FeedEntry],
pub on_watchlist: bool,
pub current_offset: u32,
pub has_more: bool,
pub limit: u32,
pub histogram_max: u64,
}
#[derive(Template)]
#[template(path = "watchlist.html")]
pub struct WatchlistTemplate<'a> {
pub ctx: &'a HtmlPageContext,
pub owner_id: uuid::Uuid,
pub display_entries: &'a [WatchlistDisplayEntry],
pub current_offset: u32,
pub has_more: bool,
pub limit: u32,
pub is_owner: bool,
pub error: Option<String>,
}
impl<'a> ActivityFeedTemplate<'a> {
pub fn filter_qs(&self) -> String {
let mut parts = vec![
format!("filter={}", self.filter),
format!("sort_by={}", self.sort_by),
];
if !self.search.is_empty() {
let encoded = self
.search
.replace(' ', "+")
.replace('#', "%23")
.replace('&', "%26")
.replace('=', "%3D");
parts.push(format!("search={}", encoded));
}
format!("&{}", parts.join("&"))
}
}
pub struct RemoteActorDisplay {
pub handle: String,
pub display_name: String,
pub initial: char,
pub url: String,
}
pub struct UserSummaryView {
pub user_id: uuid::Uuid,
pub display_name: String,
pub initial: char,
pub avg_rating_display: String,
pub total_movies: i64,
pub avatar_url: Option<String>,
}
#[derive(Template)]
#[template(path = "users.html")]
pub struct UsersTemplate<'a> {
pub users: Vec<UserSummaryView>,
pub ctx: &'a HtmlPageContext,
pub remote_actors: Vec<RemoteActorDisplay>,
}
pub struct MonthlyRatingRow<'a> {
pub rating: &'a MonthlyRating,
pub bar_height_px: i64,
}
#[derive(Template)]
#[template(path = "profile.html")]
pub struct ProfileTemplate<'a> {
pub ctx: &'a HtmlPageContext,
pub profile_display_name: String,
pub profile_user_id: uuid::Uuid,
pub stats: &'a UserStats,
pub avg_rating_display: String,
pub favorite_director_display: String,
pub most_active_month_display: String,
pub view: &'a str,
pub entries: Option<&'a Paginated<DiaryEntry>>,
pub current_offset: u32,
pub has_more: bool,
pub limit: u32,
pub history: Option<&'a Vec<MonthActivity>>,
pub trends: Option<&'a UserTrends>,
pub monthly_rating_rows: Vec<MonthlyRatingRow<'a>>,
pub heatmap: Vec<HeatmapCell>,
pub page_items: Vec<PageItem>,
pub is_own_profile: bool,
pub error: Option<String>,
pub following_count: usize,
pub followers_count: usize,
pub pending_followers: Vec<RemoteActorData>,
pub sort_by: String,
pub search: String,
pub goals: Vec<GoalViewData>,
}
pub struct GoalViewData {
pub year: u16,
pub target_count: u32,
pub current_count: u32,
pub percentage: f64,
pub is_complete: bool,
}
impl<'a> ProfileTemplate<'a> {
pub fn filter_qs(&self) -> String {
let mut parts = vec![
format!("view={}", self.view),
format!("sort_by={}", self.sort_by),
];
if !self.search.is_empty() {
let encoded = self
.search
.replace(' ', "+")
.replace('#', "%23")
.replace('&', "%26")
.replace('=', "%3D");
parts.push(format!("search={}", encoded));
}
format!("&{}", parts.join("&"))
}
}
#[derive(Template)]
#[template(path = "embed_profile.html")]
pub struct EmbedProfileTemplate<'a> {
pub profile_display_name: String,
pub profile_user_id: uuid::Uuid,
pub profile_url: String,
pub stats: &'a UserStats,
pub avg_rating_display: String,
pub favorite_director_display: String,
pub most_active_month_display: String,
pub view: &'a str,
pub entries: Option<&'a Paginated<DiaryEntry>>,
pub current_offset: u32,
pub has_more: bool,
pub limit: u32,
pub history: Option<&'a Vec<MonthActivity>>,
pub trends: Option<&'a UserTrends>,
pub monthly_rating_rows: Vec<MonthlyRatingRow<'a>>,
pub heatmap: Vec<HeatmapCell>,
pub page_items: Vec<PageItem>,
pub sort_by: String,
}
impl<'a> EmbedProfileTemplate<'a> {
pub fn filter_qs(&self) -> String {
let parts = [
format!("view={}", self.view),
format!("sort_by={}", self.sort_by),
"embed=true".to_string(),
];
format!("&{}", parts.join("&"))
}
}
pub struct RemoteActorData {
pub handle: String,
pub display_name: Option<String>,
pub url: String,
pub avatar_url: Option<String>,
}
#[derive(Template)]
#[template(path = "following.html")]
pub struct FollowingTemplate {
pub ctx: HtmlPageContext,
pub user_id: uuid::Uuid,
pub actors: Vec<RemoteActorData>,
pub pending_actors: Vec<RemoteActorData>,
pub error: Option<String>,
}
#[derive(Template)]
#[template(path = "followers.html")]
pub struct FollowersTemplate {
pub ctx: HtmlPageContext,
pub user_id: uuid::Uuid,
pub actors: Vec<RemoteActorData>,
pub error: Option<String>,
}
#[derive(Template)]
#[template(path = "blocked_domains.html")]
pub struct BlockedDomainsTemplate<'a> {
pub ctx: &'a HtmlPageContext,
pub domains: &'a [BlockedDomainEntry],
}
#[derive(Template)]
#[template(path = "blocked_actors.html")]
pub struct BlockedActorsTemplate<'a> {
pub ctx: &'a HtmlPageContext,
pub actors: &'a [BlockedActorEntry],
}
pub struct BlockedDomainEntry {
pub domain: String,
pub reason: Option<String>,
pub blocked_at: String,
}
pub struct BlockedActorEntry {
pub url: String,
pub handle: String,
pub display_name: Option<String>,
pub avatar_url: Option<String>,
}
pub struct HeatmapCell {
pub month_label: String,
pub count: i64,
pub alpha: f64,
}
pub fn build_heatmap(history: &[MonthActivity]) -> Vec<HeatmapCell> {
let current_year = chrono::Utc::now().year();
let count_for = |m: &str| -> i64 {
history
.iter()
.find(|a| a.year_month == format!("{}-{}", current_year, m))
.map(|a| a.count)
.unwrap_or(0)
};
let months = [
("01", "Jan"),
("02", "Feb"),
("03", "Mar"),
("04", "Apr"),
("05", "May"),
("06", "Jun"),
("07", "Jul"),
("08", "Aug"),
("09", "Sep"),
("10", "Oct"),
("11", "Nov"),
("12", "Dec"),
];
let counts: Vec<i64> = months.iter().map(|(m, _)| count_for(m)).collect();
let max = counts.iter().copied().max().unwrap_or(0).max(1);
months
.iter()
.zip(counts.iter())
.map(|((_, label), &count)| {
let alpha = if count == 0 {
0.05
} else {
0.15 + 0.75 * (count as f64 / max as f64)
};
HeatmapCell {
month_label: label.to_string(),
count,
alpha,
}
})
.collect()
}
pub fn bar_height_px(avg_rating: f64) -> i64 {
(avg_rating / 5.0 * 60.0) as i64
}
#[derive(Template)]
#[template(path = "profile_settings.html")]
pub struct ProfileSettingsTemplate<'a> {
pub ctx: &'a HtmlPageContext,
pub bio: Option<&'a str>,
pub avatar_url: Option<&'a str>,
pub banner_url: Option<&'a str>,
pub also_known_as: Option<&'a str>,
pub profile_fields: &'a [(String, String)],
pub saved: bool,
pub embed_url: String,
}
#[derive(Template)]
#[template(path = "integrations.html")]
pub struct IntegrationsTemplate<'a> {
pub ctx: &'a HtmlPageContext,
pub tokens: &'a [WebhookTokenView],
pub webhook_base_url: &'a str,
pub new_token: Option<&'a str>,
}
pub struct WebhookTokenView {
pub id: String,
pub provider: String,
pub label: Option<String>,
pub created_at: String,
pub last_used_at: Option<String>,
}
#[derive(Template)]
#[template(path = "watch_queue.html")]
pub struct WatchQueueTemplate<'a> {
pub ctx: &'a HtmlPageContext,
pub entries: &'a [WatchQueueDisplayEntry],
pub error: Option<&'a str>,
}
pub struct WatchQueueDisplayEntry {
pub id: String,
pub title: String,
pub year: Option<u16>,
pub source: String,
pub watched_at: String,
pub movie_url: Option<String>,
}
#[derive(Template)]
#[template(path = "import_upload.html")]
pub struct ImportUploadTemplate<'a> {
pub ctx: &'a HtmlPageContext,
pub profiles: &'a [ImportProfileView],
pub error: Option<&'a str>,
}
pub struct ImportProfileView {
pub id: String,
pub name: String,
}
#[derive(Template)]
#[template(path = "import_mapping.html")]
pub struct ImportMappingTemplate<'a> {
pub ctx: &'a HtmlPageContext,
pub session_id: &'a str,
pub columns: &'a [String],
pub sample_rows: &'a [Vec<String>],
pub domain_fields: &'a [(&'static str, &'static str)],
pub error: Option<&'a str>,
}
#[derive(Template)]
#[template(path = "import_preview.html")]
pub struct ImportPreviewTemplate<'a> {
pub ctx: &'a HtmlPageContext,
pub session_id: &'a str,
pub columns: &'a [String],
pub rows: &'a [ImportPreviewRow],
}
pub struct ImportPreviewRow {
pub index: usize,
pub status: ImportRowStatus,
pub cells: Vec<String>,
}
pub enum ImportRowStatus {
Valid,
Duplicate,
Invalid(String),
}
#[derive(Template)]
#[template(path = "wrapup.html")]
pub struct WrapUpPageTemplate<'a> {
pub ctx: &'a HtmlPageContext,
pub report: &'a domain::models::wrapup::WrapUpReport,
pub year_label: String,
pub watch_time_display: String,
pub rating_max: u32,
pub genre_max: u32,
pub rating_pcts: [f64; 5],
pub genre_pcts: Vec<f64>,
}

View File

@@ -0,0 +1,16 @@
use api_types::HtmlPageContext;
use askama::Template;
#[derive(Template)]
#[template(path = "login.html")]
pub struct LoginTemplate<'a> {
pub error: Option<&'a str>,
pub ctx: &'a HtmlPageContext,
}
#[derive(Template)]
#[template(path = "register.html")]
pub struct RegisterTemplate<'a> {
pub error: Option<&'a str>,
pub ctx: &'a HtmlPageContext,
}

View File

@@ -0,0 +1,36 @@
pub struct PageItem {
pub number: u32,
pub is_current: bool,
pub is_ellipsis: bool,
}
pub fn build_page_items(total_pages: u32, current_page: u32) -> Vec<PageItem> {
if total_pages <= 1 {
return vec![];
}
let mut set = std::collections::BTreeSet::new();
set.insert(0u32);
set.insert(total_pages - 1);
let start = current_page.saturating_sub(2);
let end = (current_page + 2).min(total_pages - 1);
for p in start..=end {
set.insert(p);
}
let pages: Vec<u32> = set.into_iter().collect();
let mut items = Vec::new();
for (i, &p) in pages.iter().enumerate() {
if i > 0 && p > pages[i - 1] + 1 {
items.push(PageItem {
number: 0,
is_current: false,
is_ellipsis: true,
});
}
items.push(PageItem {
number: p,
is_current: p == current_page,
is_ellipsis: false,
});
}
items
}

View File

@@ -0,0 +1,55 @@
use super::{PageItem, filters};
use api_types::HtmlPageContext;
use askama::Template;
use domain::models::{DiaryEntry, FeedEntry, ReviewSource};
#[derive(Template)]
#[template(path = "diary.html")]
pub struct DiaryTemplate<'a> {
pub entries: &'a [DiaryEntry],
pub current_offset: u32,
pub limit: u32,
pub has_more: bool,
pub ctx: &'a HtmlPageContext,
pub page_items: Vec<PageItem>,
}
#[derive(Template)]
#[template(path = "new_review.html")]
pub struct NewReviewTemplate<'a> {
pub error: Option<&'a str>,
pub ctx: &'a HtmlPageContext,
}
#[derive(Template)]
#[template(path = "activity_feed.html")]
pub struct ActivityFeedTemplate<'a> {
pub entries: &'a [FeedEntry],
pub current_offset: u32,
pub limit: u32,
pub has_more: bool,
pub ctx: &'a HtmlPageContext,
pub page_items: Vec<PageItem>,
pub filter: String,
pub sort_by: String,
pub search: String,
}
impl<'a> ActivityFeedTemplate<'a> {
pub fn filter_qs(&self) -> String {
let mut parts = vec![
format!("filter={}", self.filter),
format!("sort_by={}", self.sort_by),
];
if !self.search.is_empty() {
let encoded = self
.search
.replace(' ', "+")
.replace('#', "%23")
.replace('&', "%26")
.replace('=', "%3D");
parts.push(format!("search={}", encoded));
}
format!("&{}", parts.join("&"))
}
}

View File

@@ -0,0 +1,47 @@
use api_types::HtmlPageContext;
use askama::Template;
#[derive(Template)]
#[template(path = "import_upload.html")]
pub struct ImportUploadTemplate<'a> {
pub ctx: &'a HtmlPageContext,
pub profiles: &'a [ImportProfileView],
pub error: Option<&'a str>,
}
pub struct ImportProfileView {
pub id: String,
pub name: String,
}
#[derive(Template)]
#[template(path = "import_mapping.html")]
pub struct ImportMappingTemplate<'a> {
pub ctx: &'a HtmlPageContext,
pub session_id: &'a str,
pub columns: &'a [String],
pub sample_rows: &'a [Vec<String>],
pub domain_fields: &'a [(&'static str, &'static str)],
pub error: Option<&'a str>,
}
#[derive(Template)]
#[template(path = "import_preview.html")]
pub struct ImportPreviewTemplate<'a> {
pub ctx: &'a HtmlPageContext,
pub session_id: &'a str,
pub columns: &'a [String],
pub rows: &'a [ImportPreviewRow],
}
pub struct ImportPreviewRow {
pub index: usize,
pub status: ImportRowStatus,
pub cells: Vec<String>,
}
pub enum ImportRowStatus {
Valid,
Duplicate,
Invalid(String),
}

View File

@@ -0,0 +1,36 @@
use api_types::HtmlPageContext;
use askama::Template;
#[derive(Template)]
#[template(path = "integrations.html")]
pub struct IntegrationsTemplate<'a> {
pub ctx: &'a HtmlPageContext,
pub tokens: &'a [WebhookTokenView],
pub webhook_base_url: &'a str,
pub new_token: Option<&'a str>,
}
pub struct WebhookTokenView {
pub id: String,
pub provider: String,
pub label: Option<String>,
pub created_at: String,
pub last_used_at: Option<String>,
}
#[derive(Template)]
#[template(path = "watch_queue.html")]
pub struct WatchQueueTemplate<'a> {
pub ctx: &'a HtmlPageContext,
pub entries: &'a [WatchQueueDisplayEntry],
pub error: Option<&'a str>,
}
pub struct WatchQueueDisplayEntry {
pub id: String,
pub title: String,
pub year: Option<u16>,
pub source: String,
pub watched_at: String,
pub movie_url: Option<String>,
}

View File

@@ -0,0 +1,36 @@
mod auth;
mod common;
mod diary;
mod import;
mod integrations;
mod movies;
mod social;
mod users;
mod watchlist;
mod wrapup;
pub use auth::*;
pub use common::*;
pub use diary::*;
pub use import::*;
pub use integrations::*;
pub use movies::*;
pub use social::*;
pub use users::*;
pub use watchlist::*;
pub use wrapup::*;
pub(super) mod filters {
#[askama::filter_fn]
pub fn poster_src<T: std::fmt::Display>(
path: T,
_env: &dyn askama::Values,
) -> askama::Result<String> {
let p = path.to_string();
if p.starts_with("http://") || p.starts_with("https://") {
Ok(p)
} else {
Ok(format!("/images/{}", p))
}
}
}

View File

@@ -0,0 +1,19 @@
use super::filters;
use api_types::HtmlPageContext;
use askama::Template;
use domain::models::ReviewSource;
#[derive(Template)]
#[template(path = "movie_detail.html")]
pub struct MovieDetailTemplate<'a> {
pub ctx: &'a HtmlPageContext,
pub movie: &'a domain::models::Movie,
pub stats: &'a domain::models::MovieStats,
pub profile: Option<&'a domain::models::MovieProfile>,
pub reviews: &'a [domain::models::FeedEntry],
pub on_watchlist: bool,
pub current_offset: u32,
pub has_more: bool,
pub limit: u32,
pub histogram_max: u64,
}

View File

@@ -0,0 +1,55 @@
use api_types::HtmlPageContext;
use askama::Template;
pub struct RemoteActorData {
pub handle: String,
pub display_name: Option<String>,
pub url: String,
pub avatar_url: Option<String>,
}
#[derive(Template)]
#[template(path = "following.html")]
pub struct FollowingTemplate {
pub ctx: HtmlPageContext,
pub user_id: uuid::Uuid,
pub actors: Vec<RemoteActorData>,
pub pending_actors: Vec<RemoteActorData>,
pub error: Option<String>,
}
#[derive(Template)]
#[template(path = "followers.html")]
pub struct FollowersTemplate {
pub ctx: HtmlPageContext,
pub user_id: uuid::Uuid,
pub actors: Vec<RemoteActorData>,
pub error: Option<String>,
}
#[derive(Template)]
#[template(path = "blocked_domains.html")]
pub struct BlockedDomainsTemplate<'a> {
pub ctx: &'a HtmlPageContext,
pub domains: &'a [BlockedDomainEntry],
}
#[derive(Template)]
#[template(path = "blocked_actors.html")]
pub struct BlockedActorsTemplate<'a> {
pub ctx: &'a HtmlPageContext,
pub actors: &'a [BlockedActorEntry],
}
pub struct BlockedDomainEntry {
pub domain: String,
pub reason: Option<String>,
pub blocked_at: String,
}
pub struct BlockedActorEntry {
pub url: String,
pub handle: String,
pub display_name: Option<String>,
pub avatar_url: Option<String>,
}

View File

@@ -0,0 +1,193 @@
use super::{PageItem, RemoteActorData, filters};
use api_types::HtmlPageContext;
use askama::Template;
use chrono::Datelike;
use domain::models::{
DiaryEntry, MonthActivity, MonthlyRating, UserStats, UserTrends, collections::Paginated,
};
pub struct RemoteActorDisplay {
pub handle: String,
pub display_name: String,
pub initial: char,
pub url: String,
}
pub struct UserSummaryView {
pub user_id: uuid::Uuid,
pub display_name: String,
pub initial: char,
pub avg_rating_display: String,
pub total_movies: i64,
pub avatar_url: Option<String>,
}
#[derive(Template)]
#[template(path = "users.html")]
pub struct UsersTemplate<'a> {
pub users: Vec<UserSummaryView>,
pub ctx: &'a HtmlPageContext,
pub remote_actors: Vec<RemoteActorDisplay>,
}
pub struct MonthlyRatingRow<'a> {
pub rating: &'a MonthlyRating,
pub bar_height_px: i64,
}
#[derive(Template)]
#[template(path = "profile.html")]
pub struct ProfileTemplate<'a> {
pub ctx: &'a HtmlPageContext,
pub profile_display_name: String,
pub profile_user_id: uuid::Uuid,
pub stats: &'a UserStats,
pub avg_rating_display: String,
pub favorite_director_display: String,
pub most_active_month_display: String,
pub view: &'a str,
pub entries: Option<&'a Paginated<DiaryEntry>>,
pub current_offset: u32,
pub has_more: bool,
pub limit: u32,
pub history: Option<&'a Vec<MonthActivity>>,
pub trends: Option<&'a UserTrends>,
pub monthly_rating_rows: Vec<MonthlyRatingRow<'a>>,
pub heatmap: Vec<HeatmapCell>,
pub page_items: Vec<PageItem>,
pub is_own_profile: bool,
pub error: Option<String>,
pub following_count: usize,
pub followers_count: usize,
pub pending_followers: Vec<RemoteActorData>,
pub sort_by: String,
pub search: String,
pub goals: Vec<GoalViewData>,
}
pub struct GoalViewData {
pub year: u16,
pub target_count: u32,
pub current_count: u32,
pub percentage: f64,
pub is_complete: bool,
}
impl<'a> ProfileTemplate<'a> {
pub fn filter_qs(&self) -> String {
let mut parts = vec![
format!("view={}", self.view),
format!("sort_by={}", self.sort_by),
];
if !self.search.is_empty() {
let encoded = self
.search
.replace(' ', "+")
.replace('#', "%23")
.replace('&', "%26")
.replace('=', "%3D");
parts.push(format!("search={}", encoded));
}
format!("&{}", parts.join("&"))
}
}
#[derive(Template)]
#[template(path = "embed_profile.html")]
pub struct EmbedProfileTemplate<'a> {
pub profile_display_name: String,
pub profile_user_id: uuid::Uuid,
pub profile_url: String,
pub stats: &'a UserStats,
pub avg_rating_display: String,
pub favorite_director_display: String,
pub most_active_month_display: String,
pub view: &'a str,
pub entries: Option<&'a Paginated<DiaryEntry>>,
pub current_offset: u32,
pub has_more: bool,
pub limit: u32,
pub history: Option<&'a Vec<MonthActivity>>,
pub trends: Option<&'a UserTrends>,
pub monthly_rating_rows: Vec<MonthlyRatingRow<'a>>,
pub heatmap: Vec<HeatmapCell>,
pub page_items: Vec<PageItem>,
pub sort_by: String,
}
impl<'a> EmbedProfileTemplate<'a> {
pub fn filter_qs(&self) -> String {
let parts = [
format!("view={}", self.view),
format!("sort_by={}", self.sort_by),
"embed=true".to_string(),
];
format!("&{}", parts.join("&"))
}
}
pub struct HeatmapCell {
pub month_label: String,
pub count: i64,
pub alpha: f64,
}
pub fn build_heatmap(history: &[MonthActivity]) -> Vec<HeatmapCell> {
let current_year = chrono::Utc::now().year();
let count_for = |m: &str| -> i64 {
history
.iter()
.find(|a| a.year_month == format!("{}-{}", current_year, m))
.map(|a| a.count)
.unwrap_or(0)
};
let months = [
("01", "Jan"),
("02", "Feb"),
("03", "Mar"),
("04", "Apr"),
("05", "May"),
("06", "Jun"),
("07", "Jul"),
("08", "Aug"),
("09", "Sep"),
("10", "Oct"),
("11", "Nov"),
("12", "Dec"),
];
let counts: Vec<i64> = months.iter().map(|(m, _)| count_for(m)).collect();
let max = counts.iter().copied().max().unwrap_or(0).max(1);
months
.iter()
.zip(counts.iter())
.map(|((_, label), &count)| {
let alpha = if count == 0 {
0.05
} else {
0.15 + 0.75 * (count as f64 / max as f64)
};
HeatmapCell {
month_label: label.to_string(),
count,
alpha,
}
})
.collect()
}
pub fn bar_height_px(avg_rating: f64) -> i64 {
(avg_rating / 5.0 * 60.0) as i64
}
#[derive(Template)]
#[template(path = "profile_settings.html")]
pub struct ProfileSettingsTemplate<'a> {
pub ctx: &'a HtmlPageContext,
pub bio: Option<&'a str>,
pub avatar_url: Option<&'a str>,
pub banner_url: Option<&'a str>,
pub also_known_as: Option<&'a str>,
pub profile_fields: &'a [(String, String)],
pub saved: bool,
pub embed_url: String,
}

View File

@@ -0,0 +1,25 @@
use api_types::HtmlPageContext;
use askama::Template;
#[derive(Clone, Debug)]
pub struct WatchlistDisplayEntry {
pub poster_url: Option<String>,
pub movie_title: String,
pub release_year: u16,
pub movie_url: Option<String>,
pub added_at: String,
pub remove_url: Option<String>,
}
#[derive(Template)]
#[template(path = "watchlist.html")]
pub struct WatchlistTemplate<'a> {
pub ctx: &'a HtmlPageContext,
pub owner_id: uuid::Uuid,
pub display_entries: &'a [WatchlistDisplayEntry],
pub current_offset: u32,
pub has_more: bool,
pub limit: u32,
pub is_owner: bool,
pub error: Option<String>,
}

View File

@@ -0,0 +1,16 @@
use super::filters;
use api_types::HtmlPageContext;
use askama::Template;
#[derive(Template)]
#[template(path = "wrapup.html")]
pub struct WrapUpPageTemplate<'a> {
pub ctx: &'a HtmlPageContext,
pub report: &'a domain::models::wrapup::WrapUpReport,
pub year_label: String,
pub watch_time_display: String,
pub rating_max: u32,
pub genre_max: u32,
pub rating_pcts: [f64; 5],
pub genre_pcts: Vec<f64>,
}

View File

@@ -0,0 +1,179 @@
use crate::html::helpers::build_page_context;
use crate::html::templates::{
ProfileSettingsTemplate, RemoteActorDisplay, UserSummaryView, UsersTemplate,
};
use crate::{
extractors::{OptionalCookieUser, RequiredCookieUser},
html::csrf::CsrfToken,
html::render::render_page,
state::AppState,
};
use application::users::{
get_profile_settings as get_profile_settings_uc, resolve_username_to_id, update_profile,
update_profile_fields,
};
use axum::{
extract::{Extension, Multipart, Path, Query, State},
http::StatusCode,
response::IntoResponse,
};
use domain::{errors::DomainError, value_objects::Username};
pub async fn get_users_list(
OptionalCookieUser(user_id): OptionalCookieUser,
State(state): State<AppState>,
Extension(csrf): Extension<CsrfToken>,
) -> impl IntoResponse {
let mut ctx = build_page_context(&state, user_id, csrf.0).await;
ctx.page_title = "Members — Movies Diary".to_string();
ctx.canonical_url = format!("{}/users", state.app_ctx.config.base_url);
match application::users::get_users::execute(
&state.app_ctx.deps.users.get_users_list,
application::users::queries::GetUsersQuery,
)
.await
{
Ok(result) => {
let users: Vec<UserSummaryView> = result
.users
.iter()
.map(crate::html::mappers::users::user_summary_view)
.collect();
let remote_actors: Vec<RemoteActorDisplay> = result
.remote_actors
.iter()
.map(crate::html::mappers::users::remote_actor_display)
.collect();
render_page(UsersTemplate {
users,
ctx: &ctx,
remote_actors,
})
.into_response()
}
Err(e) => crate::errors::domain_error_response(e),
}
}
pub async fn get_user_by_username(
State(state): State<AppState>,
Path(username): Path<String>,
) -> impl IntoResponse {
let uname = match Username::new(username) {
Ok(u) => u,
Err(_) => return StatusCode::NOT_FOUND.into_response(),
};
match resolve_username_to_id::execute(&state.app_ctx.deps.users.resolve_username, &uname).await
{
Ok(Some(uid)) => {
axum::response::Redirect::permanent(&format!("/users/{}", uid.value())).into_response()
}
_ => StatusCode::NOT_FOUND.into_response(),
}
}
#[derive(serde::Deserialize, Default)]
pub struct SavedQuery {
pub saved: Option<String>,
}
pub async fn get_profile_settings(
RequiredCookieUser(user_id): RequiredCookieUser,
State(state): State<AppState>,
Query(params): Query<SavedQuery>,
Extension(csrf): Extension<CsrfToken>,
) -> impl IntoResponse {
let mut ctx = build_page_context(&state, Some(user_id.clone()), csrf.0).await;
ctx.page_title = "Profile Settings — Movies Diary".to_string();
ctx.canonical_url = format!("{}/settings/profile", state.app_ctx.config.base_url);
let settings = match get_profile_settings_uc::execute(
&state.app_ctx.deps.users.get_profile_settings,
user_id.value(),
)
.await
{
Ok(s) => s,
Err(DomainError::NotFound(_)) => return StatusCode::NOT_FOUND.into_response(),
Err(e) => return crate::errors::domain_error_response(e),
};
let saved = params.saved.as_deref() == Some("1");
render_page(ProfileSettingsTemplate {
ctx: &ctx,
bio: settings.bio.as_deref(),
avatar_url: settings.avatar_url.as_deref(),
banner_url: settings.banner_url.as_deref(),
also_known_as: settings.also_known_as.as_deref(),
profile_fields: &settings.fields,
saved,
embed_url: format!(
"{}/users/{}?embed=true",
state.app_ctx.config.base_url,
user_id.value()
),
})
.into_response()
}
pub async fn post_profile_settings(
RequiredCookieUser(user_id): RequiredCookieUser,
State(state): State<AppState>,
multipart: Multipart,
) -> impl IntoResponse {
let data = crate::support::parse_profile_multipart(multipart).await;
let cmd = application::users::commands::UpdateProfileCommand {
user_id: user_id.value(),
display_name: data.display_name,
bio: data.bio,
avatar_bytes: data.avatar_bytes,
avatar_content_type: data.avatar_content_type,
banner_bytes: data.banner_bytes,
banner_content_type: data.banner_content_type,
also_known_as: data.also_known_as,
};
if let Err(e) = update_profile::execute(&state.app_ctx.deps.users.update_profile, cmd).await {
tracing::error!("update_profile error: {:?}", e);
return axum::response::Redirect::to(&format!(
"/settings/profile?error={}",
crate::html::helpers::encode_domain_error(&e)
))
.into_response();
}
let fields: Vec<domain::models::ProfileField> = (0..4)
.filter_map(|i| {
data.profile_field_names
.get(&i)
.map(|name| domain::models::ProfileField {
name: name.clone(),
value: data
.profile_field_values
.get(&i)
.cloned()
.unwrap_or_default(),
})
})
.collect();
let fields_cmd = application::users::commands::UpdateProfileFieldsCommand {
user_id: user_id.value(),
fields,
};
if let Err(e) =
update_profile_fields::execute(&state.app_ctx.deps.users.update_profile_fields, fields_cmd)
.await
{
tracing::error!("update_profile_fields error: {:?}", e);
return axum::response::Redirect::to(&format!(
"/settings/profile?error={}",
crate::html::helpers::encode_domain_error(&e)
))
.into_response();
}
axum::response::Redirect::to("/settings/profile?saved=1").into_response()
}

View File

@@ -0,0 +1,171 @@
use crate::html::helpers::{build_page_context, encode_error};
use crate::html::templates::WatchlistTemplate;
use crate::{
extractors::{OptionalCookieUser, RequiredCookieUser},
html::csrf::CsrfToken,
html::render::render_page,
state::AppState,
};
use application::{
diary::commands::MovieInput,
watchlist::{
add as add_to_watchlist,
commands::{AddToWatchlistCommand, RemoveFromWatchlistCommand},
get_watchlist_for_owner, remove as remove_from_watchlist,
},
};
use axum::{
Form,
extract::{Extension, Path, Query, State},
http::StatusCode,
response::{IntoResponse, Redirect},
};
use domain::errors::DomainError;
pub async fn get_watchlist_page(
OptionalCookieUser(viewer_id): OptionalCookieUser,
State(state): State<AppState>,
Path(owner_id): Path<uuid::Uuid>,
Query(params): Query<crate::html::forms::WatchlistQuery>,
Extension(csrf): Extension<CsrfToken>,
) -> impl IntoResponse {
let ctx = build_page_context(&state, viewer_id.clone(), csrf.0).await;
let is_owner = viewer_id.map(|u| u.value() == owner_id).unwrap_or(false);
let view = match get_watchlist_for_owner::execute(
&state.app_ctx.deps.watchlist.get_watchlist_for_owner,
owner_id,
params.limit.or(Some(20)),
params.offset.or(Some(0)),
)
.await
{
Ok(view) => view,
Err(e) => return crate::errors::domain_error_response(e),
};
let result = match view {
get_watchlist_for_owner::WatchlistView::Local(page) => {
crate::html::mappers::watchlist::build_watchlist_page(page, is_owner)
}
get_watchlist_for_owner::WatchlistView::Remote(entries) => {
crate::html::mappers::watchlist::build_remote_watchlist_page(entries)
}
};
render_page(WatchlistTemplate {
ctx: &ctx,
owner_id,
display_entries: &result.display_entries,
current_offset: result.current_offset,
has_more: result.has_more,
limit: result.limit,
is_owner,
error: params.error,
})
.into_response()
}
pub async fn post_watchlist_add_html(
State(state): State<AppState>,
RequiredCookieUser(user_id): RequiredCookieUser,
Extension(csrf): Extension<CsrfToken>,
Form(form): Form<crate::html::forms::WatchlistAddForm>,
) -> impl IntoResponse {
if crate::html::csrf::mismatch(&csrf, &form.csrf_token) {
return StatusCode::FORBIDDEN.into_response();
}
let redirect_base = form
.redirect_after
.as_deref()
.filter(|u| u.starts_with('/') && !u.starts_with("//"))
.unwrap_or("/")
.to_string();
let input = if let Some(id) = form.movie_id {
MovieInput {
movie_id: Some(id),
external_metadata_id: None,
manual_title: None,
manual_release_year: None,
manual_director: None,
}
} else {
let query = form.query.as_deref().unwrap_or("").trim().to_string();
let is_external_id = query.starts_with("tmdb:")
|| (query.starts_with("tt")
&& query.len() > 2
&& query[2..].chars().all(|c| c.is_ascii_digit()));
if is_external_id {
MovieInput {
movie_id: None,
external_metadata_id: Some(query),
manual_title: None,
manual_release_year: None,
manual_director: None,
}
} else {
MovieInput {
movie_id: None,
external_metadata_id: None,
manual_title: if query.is_empty() { None } else { Some(query) },
manual_release_year: form.year,
manual_director: None,
}
}
};
match add_to_watchlist::execute(
&state.app_ctx.deps.watchlist.add,
AddToWatchlistCommand {
user_id: user_id.value(),
input,
},
)
.await
{
Ok(()) => Redirect::to(&redirect_base).into_response(),
Err(DomainError::NotFound(_)) => Redirect::to(&redirect_base).into_response(),
Err(DomainError::ValidationError(msg)) => {
let sep = if redirect_base.contains('?') {
'&'
} else {
'?'
};
let url = format!("{}{}error={}", redirect_base, sep, encode_error(&msg));
Redirect::to(&url).into_response()
}
Err(e) => crate::errors::domain_error_response(e),
}
}
pub async fn post_watchlist_remove_html(
State(state): State<AppState>,
RequiredCookieUser(user_id): RequiredCookieUser,
Extension(csrf): Extension<CsrfToken>,
Path(movie_id): Path<uuid::Uuid>,
Form(form): Form<crate::html::forms::DeleteRedirectForm>,
) -> impl IntoResponse {
if crate::html::csrf::mismatch(&csrf, &form.csrf_token) {
return StatusCode::FORBIDDEN.into_response();
}
match remove_from_watchlist::execute(
&state.app_ctx.deps.watchlist.remove_from_watchlist,
RemoveFromWatchlistCommand {
user_id: user_id.value(),
movie_id,
},
)
.await
{
Ok(()) | Err(DomainError::NotFound(_)) => {
let redirect_url = form
.redirect_after
.filter(|u| u.starts_with('/') && !u.starts_with("//"))
.unwrap_or_else(|| "/".to_string());
Redirect::to(&redirect_url).into_response()
}
Err(e) => crate::errors::domain_error_response(e),
}
}

View File

@@ -0,0 +1,106 @@
use crate::{
extractors::OptionalCookieUser, html::csrf::CsrfToken, html::render::render_page,
state::AppState,
};
use application::wrapup::get_ready_report;
use axum::{
extract::{Extension, Path, State},
http::StatusCode,
response::IntoResponse,
};
use domain::errors::DomainError;
use domain::models::wrapup::{WrapUpReport, WrapUpScope};
use uuid::Uuid;
fn format_watch_time(minutes: u32) -> String {
let h = minutes / 60;
let m = minutes % 60;
if h > 0 && m > 0 {
format!("{}h {}m", h, m)
} else if h > 0 {
format!("{}h", h)
} else {
format!("{}m", m)
}
}
fn render_wrapup(
report: &WrapUpReport,
year: i32,
ctx: &api_types::HtmlPageContext,
) -> axum::response::Response {
let rating_max = report
.rating_distribution
.iter()
.copied()
.max()
.unwrap_or(1)
.max(1);
let rating_pcts: [f64; 5] =
std::array::from_fn(|i| report.rating_distribution[i] as f64 / rating_max as f64 * 100.0);
let genre_max = report
.top_genres
.first()
.map(|g| g.count)
.unwrap_or(1)
.max(1);
let genre_pcts: Vec<f64> = report
.top_genres
.iter()
.take(8)
.map(|g| g.count as f64 / genre_max as f64 * 100.0)
.collect();
let tmpl = crate::html::templates::WrapUpPageTemplate {
ctx,
report,
year_label: year.to_string(),
watch_time_display: format_watch_time(report.total_watch_time_minutes),
rating_max,
genre_max,
rating_pcts,
genre_pcts,
};
render_page(tmpl)
}
pub async fn get_user_wrapup_html(
OptionalCookieUser(viewer): OptionalCookieUser,
State(state): State<AppState>,
Path((user_id, year)): Path<(Uuid, i32)>,
Extension(csrf): Extension<CsrfToken>,
) -> impl IntoResponse {
let scope = WrapUpScope::User(user_id);
let report =
match get_ready_report::execute(&state.app_ctx.deps.wrapup.get_ready_report, scope, year)
.await
{
Ok(report) => report,
Err(DomainError::ValidationError(_)) => return StatusCode::BAD_REQUEST.into_response(),
Err(_) => return StatusCode::NOT_FOUND.into_response(),
};
let ctx = crate::html::helpers::build_page_context(&state, viewer, csrf.0).await;
render_wrapup(&report, year, &ctx)
}
pub async fn get_global_wrapup_html(
OptionalCookieUser(viewer): OptionalCookieUser,
State(state): State<AppState>,
Path(year): Path<i32>,
Extension(csrf): Extension<CsrfToken>,
) -> impl IntoResponse {
let report = match get_ready_report::execute(
&state.app_ctx.deps.wrapup.get_ready_report,
WrapUpScope::Global,
year,
)
.await
{
Ok(report) => report,
Err(DomainError::ValidationError(_)) => return StatusCode::BAD_REQUEST.into_response(),
Err(_) => return StatusCode::NOT_FOUND.into_response(),
};
let ctx = crate::html::helpers::build_page_context(&state, viewer, csrf.0).await;
render_wrapup(&report, year, &ctx)
}