feat: feed ux improvements

This commit is contained in:
2026-05-10 00:16:29 +02:00
parent f4e7d4e359
commit 9f894ebdf2
20 changed files with 1186 additions and 161 deletions

View File

@@ -13,3 +13,7 @@ uuid = { workspace = true }
chrono = { workspace = true }
tracing = { workspace = true }
async-trait = { workspace = true }
[dev-dependencies]
tokio = { workspace = true }
uuid = { workspace = true }

View File

@@ -494,3 +494,136 @@ impl RemoteReviewRepository for SqliteFederationRepository {
Ok(())
}
}
#[async_trait]
impl domain::ports::SocialQueryPort for SqliteFederationRepository {
async fn get_accepted_following_urls(
&self,
user_id: uuid::Uuid,
) -> Result<Vec<String>, domain::errors::DomainError> {
let user_id_str = user_id.to_string();
let rows = sqlx::query_scalar::<_, String>(
"SELECT remote_actor_url FROM ap_following
WHERE local_user_id = ? AND status = 'accepted'",
)
.bind(&user_id_str)
.fetch_all(&self.pool)
.await
.map_err(|e| domain::errors::DomainError::InfrastructureError(e.to_string()))?;
Ok(rows)
}
async fn list_all_followed_remote_actors(
&self,
) -> Result<Vec<domain::ports::RemoteActorInfo>, domain::errors::DomainError> {
let rows = sqlx::query_as::<_, (String, String, Option<String>)>(
"SELECT DISTINCT ar.url, ar.handle, ar.display_name
FROM ap_remote_actors ar
JOIN ap_following f ON f.remote_actor_url = ar.url
WHERE f.status = 'accepted'",
)
.fetch_all(&self.pool)
.await
.map_err(|e| domain::errors::DomainError::InfrastructureError(e.to_string()))?;
Ok(rows
.into_iter()
.map(|(url, handle, display_name)| domain::ports::RemoteActorInfo {
url,
handle,
display_name,
})
.collect())
}
}
#[cfg(test)]
mod tests {
use super::*;
use domain::ports::SocialQueryPort;
use sqlx::SqlitePool;
async fn setup_db(pool: &SqlitePool) {
sqlx::query(
"CREATE TABLE IF NOT EXISTS ap_remote_actors (
url TEXT PRIMARY KEY,
handle TEXT NOT NULL,
inbox_url TEXT NOT NULL,
shared_inbox_url TEXT,
display_name TEXT,
fetched_at TEXT NOT NULL
)",
)
.execute(pool)
.await
.unwrap();
sqlx::query(
"CREATE TABLE IF NOT EXISTS ap_following (
local_user_id TEXT NOT NULL,
remote_actor_url TEXT NOT NULL,
follow_activity_id TEXT NOT NULL,
status TEXT NOT NULL,
PRIMARY KEY (local_user_id, remote_actor_url)
)",
)
.execute(pool)
.await
.unwrap();
}
#[tokio::test]
async fn test_get_accepted_following_urls_returns_only_accepted() {
let pool = SqlitePool::connect(":memory:").await.unwrap();
setup_db(&pool).await;
let repo = SqliteFederationRepository::new(pool.clone());
let user_id = uuid::Uuid::new_v4();
sqlx::query(
"INSERT INTO ap_following (local_user_id, remote_actor_url, follow_activity_id, status)
VALUES (?, 'https://other.social/users/alice', 'act1', 'accepted'),
(?, 'https://other.social/users/bob', 'act2', 'pending')",
)
.bind(user_id.to_string())
.bind(user_id.to_string())
.execute(&pool)
.await
.unwrap();
let urls = repo.get_accepted_following_urls(user_id).await.unwrap();
assert_eq!(urls.len(), 1);
assert_eq!(urls[0], "https://other.social/users/alice");
}
#[tokio::test]
async fn test_list_all_followed_remote_actors_deduplicates() {
let pool = SqlitePool::connect(":memory:").await.unwrap();
setup_db(&pool).await;
let repo = SqliteFederationRepository::new(pool.clone());
let user1 = uuid::Uuid::new_v4();
let user2 = uuid::Uuid::new_v4();
sqlx::query(
"INSERT INTO ap_remote_actors (url, handle, inbox_url, fetched_at, display_name)
VALUES ('https://other.social/users/alice', 'alice@other.social', 'https://other.social/inbox', '2024-01-01', 'Alice')",
)
.execute(&pool)
.await
.unwrap();
sqlx::query(
"INSERT INTO ap_following (local_user_id, remote_actor_url, follow_activity_id, status)
VALUES (?, 'https://other.social/users/alice', 'act1', 'accepted'),
(?, 'https://other.social/users/alice', 'act2', 'accepted')",
)
.bind(user1.to_string())
.bind(user2.to_string())
.execute(&pool)
.await
.unwrap();
let actors = repo.list_all_followed_remote_actors().await.unwrap();
assert_eq!(actors.len(), 1);
assert_eq!(actors[0].handle, "alice@other.social");
}
}

View File

@@ -214,31 +214,6 @@ impl SqliteMovieRepository {
.map_err(Self::map_err)
}
async fn count_feed_entries(&self) -> Result<i64, DomainError> {
sqlx::query_scalar!("SELECT COUNT(*) FROM reviews")
.fetch_one(&self.pool)
.await
.map_err(Self::map_err)
}
async fn fetch_feed_rows(&self, limit: i64, offset: i64) -> Result<Vec<FeedRow>, DomainError> {
sqlx::query_as!(
FeedRow,
r#"SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,
r.id AS review_id, r.movie_id, r.user_id, r.rating, r.comment, r.watched_at, r.created_at, r.remote_actor_url,
COALESCE(u.email, r.remote_actor_url) AS "user_email!: String"
FROM reviews r
INNER JOIN movies m ON m.id = r.movie_id
LEFT JOIN users u ON u.id = r.user_id
ORDER BY r.watched_at DESC
LIMIT ? OFFSET ?"#,
limit, offset
)
.fetch_all(&self.pool)
.await
.map_err(Self::map_err)
}
async fn fetch_user_totals(&self, user_id: &str) -> Result<UserTotalsRow, DomainError> {
sqlx::query_as!(
UserTotalsRow,
@@ -520,13 +495,115 @@ impl DiaryRepository for SqliteMovieRepository {
&self,
page: &PageParams,
) -> Result<Paginated<FeedEntry>, DomainError> {
self.query_activity_feed_filtered(page, &domain::ports::FeedSortBy::Date, None, None)
.await
}
async fn query_activity_feed_filtered(
&self,
page: &PageParams,
sort_by: &domain::ports::FeedSortBy,
search: Option<&str>,
following: Option<&domain::ports::FollowingFilter>,
) -> Result<Paginated<FeedEntry>, DomainError> {
use domain::ports::FeedSortBy;
let limit = page.limit as i64;
let offset = page.offset as i64;
let has_search = search.map(|s| !s.is_empty()).unwrap_or(false);
let (total, rows) = tokio::try_join!(
self.count_feed_entries(),
self.fetch_feed_rows(limit, offset)
)?;
let mut where_parts = vec!["1=1".to_string()];
if has_search {
where_parts.push("m.title LIKE '%' || ? || '%'".to_string());
}
if let Some(f) = following {
let local_in = if f.local_user_ids.is_empty() {
"SELECT NULL WHERE 0".to_string()
} else {
f.local_user_ids
.iter()
.map(|_| "?")
.collect::<Vec<_>>()
.join(",")
};
let remote_in = if f.remote_actor_urls.is_empty() {
"SELECT NULL WHERE 0".to_string()
} else {
f.remote_actor_urls
.iter()
.map(|_| "?")
.collect::<Vec<_>>()
.join(",")
};
where_parts.push(format!(
"(r.user_id IN ({}) OR r.remote_actor_url IN ({}))",
local_in, remote_in
));
}
let order_clause = match sort_by {
FeedSortBy::Date => "r.watched_at DESC",
FeedSortBy::DateAsc => "r.watched_at ASC",
FeedSortBy::Rating => "r.rating DESC, r.watched_at DESC",
FeedSortBy::RatingAsc => "r.rating ASC, r.watched_at ASC",
};
let where_clause = where_parts.join(" AND ");
let count_sql = format!(
"SELECT COUNT(*) FROM reviews r
INNER JOIN movies m ON m.id = r.movie_id
WHERE {}",
where_clause
);
let select_sql = format!(
"SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,
r.id AS review_id, r.movie_id, r.user_id, r.rating, r.comment,
r.watched_at, r.created_at, r.remote_actor_url,
COALESCE(u.email, r.remote_actor_url) AS user_email
FROM reviews r
INNER JOIN movies m ON m.id = r.movie_id
LEFT JOIN users u ON u.id = r.user_id
WHERE {}
ORDER BY {}
LIMIT ? OFFSET ?",
where_clause, order_clause
);
macro_rules! bind_filter_params {
($q:expr) => {{
let mut q = $q;
if has_search {
q = q.bind(search.unwrap());
}
if let Some(f) = following {
for uid in &f.local_user_ids {
q = q.bind(uid.to_string());
}
for url in &f.remote_actor_urls {
q = q.bind(url.as_str());
}
}
q
}};
}
let count_q = bind_filter_params!(sqlx::query_scalar::<_, i64>(&count_sql));
let total = count_q
.fetch_one(&self.pool)
.await
.map_err(Self::map_err)?;
let rows_q = bind_filter_params!(sqlx::query_as::<_, FeedRow>(&select_sql));
let rows = rows_q
.bind(limit)
.bind(offset)
.fetch_all(&self.pool)
.await
.map_err(Self::map_err)?;
let items = rows
.into_iter()
@@ -672,3 +749,113 @@ impl StatsRepository for SqliteMovieRepository {
})
}
}
#[cfg(test)]
mod feed_filter_tests {
use super::*;
use domain::{
models::collections::PageParams,
ports::{DiaryRepository, FeedSortBy, FollowingFilter},
};
use sqlx::SqlitePool;
async fn setup(pool: &SqlitePool) {
sqlx::migrate!("./migrations").run(pool).await.unwrap();
// carol is a remote actor; we still need a non-null user_id for the schema,
// so we create a local "ghost" user and link the remote review via remote_actor_url.
sqlx::query(
"INSERT INTO users (id, email, username, password_hash, created_at) VALUES
('11111111-1111-1111-1111-111111111111', 'alice@example.com', 'alice', 'hash', '2024-01-01 00:00:00'),
('22222222-2222-2222-2222-222222222222', 'bob@example.com', 'bob', 'hash', '2024-01-01 00:00:00'),
('33333333-3333-3333-3333-333333333333', 'carol@remote.social', 'carol', 'hash', '2024-01-01 00:00:00')",
)
.execute(pool)
.await
.unwrap();
sqlx::query(
"INSERT INTO movies (id, title, release_year) VALUES
('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Inception', 2010),
('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'Interstellar', 2014),
('cccccccc-cccc-cccc-cccc-cccccccccccc', 'Dune', 2021)",
)
.execute(pool)
.await
.unwrap();
// carol's review: local user_id=33333333, remote_actor_url set → remote review
sqlx::query(
"INSERT INTO reviews (id, movie_id, user_id, rating, watched_at, created_at, remote_actor_url) VALUES
('a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '11111111-1111-1111-1111-111111111111', 5, '2024-01-01 00:00:00', '2024-01-01 00:00:00', NULL),
('b2b2b2b2-b2b2-b2b2-b2b2-b2b2b2b2b2b2', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', '22222222-2222-2222-2222-222222222222', 3, '2024-01-02 00:00:00', '2024-01-02 00:00:00', NULL),
('c3c3c3c3-c3c3-c3c3-c3c3-c3c3c3c3c3c3', 'cccccccc-cccc-cccc-cccc-cccccccccccc', '33333333-3333-3333-3333-333333333333', 4, '2024-01-03 00:00:00', '2024-01-03 00:00:00', 'https://remote.social/users/carol')",
)
.execute(pool)
.await
.unwrap();
}
#[tokio::test]
async fn test_sort_by_rating_descending() {
let pool = SqlitePool::connect(":memory:").await.unwrap();
setup(&pool).await;
let repo = SqliteMovieRepository::new(pool);
let page = PageParams::new(Some(10), Some(0)).unwrap();
let result = repo
.query_activity_feed_filtered(&page, &FeedSortBy::Rating, None, None)
.await
.unwrap();
let ratings: Vec<u8> = result
.items
.iter()
.map(|e| e.review().rating().value())
.collect();
assert_eq!(ratings, vec![5, 4, 3]);
}
#[tokio::test]
async fn test_search_by_title() {
let pool = SqlitePool::connect(":memory:").await.unwrap();
setup(&pool).await;
let repo = SqliteMovieRepository::new(pool);
let page = PageParams::new(Some(10), Some(0)).unwrap();
let result = repo
.query_activity_feed_filtered(&page, &FeedSortBy::Date, Some("Dune"), None)
.await
.unwrap();
assert_eq!(result.items.len(), 1);
assert_eq!(result.items[0].movie().title().value(), "Dune");
}
#[tokio::test]
async fn test_following_filter() {
let pool = SqlitePool::connect(":memory:").await.unwrap();
setup(&pool).await;
let repo = SqliteMovieRepository::new(pool);
let filter = FollowingFilter {
local_user_ids: vec![uuid::Uuid::parse_str("11111111-1111-1111-1111-111111111111")
.unwrap()],
remote_actor_urls: vec!["https://remote.social/users/carol".to_string()],
};
let page = PageParams::new(Some(10), Some(0)).unwrap();
let result = repo
.query_activity_feed_filtered(&page, &FeedSortBy::Date, None, Some(&filter))
.await
.unwrap();
assert_eq!(result.items.len(), 2); // alice + carol, NOT bob
let titles: Vec<String> = result
.items
.iter()
.map(|e| e.movie().title().value().to_string())
.collect();
assert!(titles.contains(&"Inception".to_string()));
assert!(titles.contains(&"Dune".to_string()));
}
}

View File

@@ -87,6 +87,34 @@ struct ActivityFeedTemplate<'a> {
has_more: bool,
ctx: &'a HtmlPageContext,
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("&"))
}
}
pub struct RemoteActorDisplay {
pub handle: String,
pub display_name: String,
pub initial: char,
pub url: String,
}
struct UserSummaryView {
@@ -102,6 +130,7 @@ struct UserSummaryView {
struct UsersTemplate<'a> {
users: Vec<UserSummaryView>,
ctx: &'a HtmlPageContext,
remote_actors: Vec<RemoteActorDisplay>,
}
struct MonthlyRatingRow<'a> {
@@ -320,6 +349,9 @@ impl HtmlRenderer for AskamaHtmlRenderer {
has_more: data.has_more,
ctx: &data.ctx,
page_items: build_page_items(total_pages, current_page),
filter: data.filter,
sort_by: data.sort_by,
search: data.search,
}
.render()
.map_err(|e| e.to_string())
@@ -350,9 +382,23 @@ impl HtmlRenderer for AskamaHtmlRenderer {
}
})
.collect();
let remote_actors = data.remote_actors
.into_iter()
.map(|a| {
let name = a.display_name.unwrap_or_else(|| a.handle.clone());
let initial = name.chars().next().unwrap_or('?');
RemoteActorDisplay {
display_name: name,
initial,
handle: a.handle,
url: a.url,
}
})
.collect();
UsersTemplate {
users,
ctx: &data.ctx,
remote_actors,
}
.render()
.map_err(|e| e.to_string())

View File

@@ -1,5 +1,35 @@
{% extends "base.html" %}
{% block content %}
<form method="get" class="feed-filters" action="/">
{% if ctx.user_email.is_some() %}
<label class="pill{% if filter == "all" %} active{% endif %}">
<input type="radio" name="filter" value="all"
{% if filter == "all" %}checked{% endif %}
onchange="this.form.submit()">
Global
</label>
<label class="pill{% if filter == "following" %} active{% endif %}">
<input type="radio" name="filter" value="following"
{% if filter == "following" %}checked{% endif %}
onchange="this.form.submit()">
Following
</label>
{% endif %}
<div class="feed-controls">
<select name="sort_by" onchange="this.form.submit()">
<option value="date"{% if sort_by == "date" %} selected{% endif %}>Date: newest first</option>
<option value="date_asc"{% if sort_by == "date_asc" %} selected{% endif %}>Date: oldest first</option>
<option value="rating"{% if sort_by == "rating" %} selected{% endif %}>Rating: highest first</option>
<option value="rating_asc"{% if sort_by == "rating_asc" %} selected{% endif %}>Rating: lowest first</option>
</select>
<input type="text" name="search" value="{{ search }}" placeholder="Search movies...">
<button type="submit" class="btn-search">Search</button>
{% if filter != "all" || sort_by != "date" || !search.is_empty() %}
<a href="/" class="clear-filters">Clear</a>
{% endif %}
</div>
<input type="hidden" name="limit" value="{{ limit }}">
</form>
<div class="diary">
{% for entry in entries %}
<article class="entry">
@@ -37,7 +67,7 @@
</div>
{% if ctx.is_current_user(entry.review().user_id().value()) %}
<form method="post" action="/reviews/{{ entry.review().id().value() }}/delete" class="delete-form">
<input type="hidden" name="redirect_after" value="/?offset={{ current_offset }}">
<input type="hidden" name="redirect_after" value="/?offset={{ current_offset }}{{ self.filter_qs() }}">
<input type="hidden" name="_csrf" value="{{ ctx.csrf_token }}">
<button type="submit">Delete</button>
</form>
@@ -50,7 +80,7 @@
</div>
<nav class="pagination">
{% if current_offset >= limit %}
<a href="/?offset={{ current_offset - limit }}" class="page-nav">&larr; Prev</a>
<a href="/?offset={{ current_offset - limit }}{{ self.filter_qs() }}" class="page-nav">&larr; Prev</a>
{% endif %}
{% for item in page_items %}
{% if item.is_ellipsis %}
@@ -58,11 +88,11 @@
{% elif item.is_current %}
<span class="page-num current">{{ item.number + 1 }}</span>
{% else %}
<a href="/?offset={{ item.number * limit }}" class="page-num">{{ item.number + 1 }}</a>
<a href="/?offset={{ item.number * limit }}{{ self.filter_qs() }}" class="page-num">{{ item.number + 1 }}</a>
{% endif %}
{% endfor %}
{% if has_more %}
<a href="/?offset={{ current_offset + limit }}" class="page-nav">Next &rarr;</a>
<a href="/?offset={{ current_offset + limit }}{{ self.filter_qs() }}" class="page-nav">Next &rarr;</a>
{% endif %}
</nav>
{% endblock %}

View File

@@ -1,43 +1,59 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ ctx.page_title }}</title>
<meta name="description" content="A personal movie diary — track what you watch, rate and review films.">
<meta property="og:type" content="website">
<meta property="og:site_name" content="Movies Diary">
<meta property="og:title" content="{{ ctx.page_title }}">
<meta property="og:url" content="{{ ctx.canonical_url }}">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="{{ ctx.page_title }}">
<link rel="canonical" href="{{ ctx.canonical_url }}">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700;800&display=swap" rel="stylesheet">
<link rel="icon" type="image/webp" href="/static/logo.webp">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<header>
<a href="/" class="site-title">Movies Diary</a>
<nav>
<a href="/">Feed</a>
<a href="/users">Users</a>
<a href="{{ ctx.rss_url }}">RSS</a>
{% if let Some(email) = ctx.user_email %}
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>{{ ctx.page_title }}</title>
<meta
name="description"
content="A personal movie diary — track what you watch, rate and review films."
/>
<meta property="og:type" content="website" />
<meta property="og:site_name" content="Movies Diary" />
<meta property="og:title" content="{{ ctx.page_title }}" />
<meta property="og:url" content="{{ ctx.canonical_url }}" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="{{ ctx.page_title }}" />
<link rel="canonical" href="{{ ctx.canonical_url }}" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700;800&display=swap"
rel="stylesheet"
/>
<link rel="icon" type="image/webp" href="/static/logo.webp" />
<link rel="stylesheet" href="/static/style.css" />
</head>
<body>
<header>
<a href="/" class="site-title">Movies Diary</a>
<nav>
<a href="/">Feed</a>
<a href="/users">Users</a>
{% if let Some(uid) = ctx.user_id %}
<a href="/users/{{ uid }}">Profile</a>
<a href="/reviews/new">Add Review</a>
<a href="/logout">Logout</a>
{% else %}
{% else %}
<a href="/login">Login</a>
{% if ctx.register_enabled %}
<a href="/register">Register</a>
{% endif %}
<a href="/register">Register</a>
{% endif %} {% endif %}
</nav>
</header>
<main>{% block content %}{% endblock %}</main>
<footer class="site-footer">
<span class="footer-made">Made with passion</span>
<span class="footer-sep">·</span>
<a href="/feed.rss" class="footer-link">RSS</a>
{% if let Some(uid) = ctx.user_id %}
<span class="footer-sep">·</span>
<a href="/users/{{ uid }}" class="footer-link">My Profile</a>
<span class="footer-sep">·</span>
<a href="/users/{{ uid }}/feed.rss" class="footer-link">My RSS</a>
{% endif %}
</nav>
</header>
<main>
{% block content %}{% endblock %}
</main>
</body>
<span class="footer-sep">·</span>
<a href="/docs" target="_blank" class="footer-link">API Docs</a>
</footer>
</body>
</html>

View File

@@ -14,5 +14,21 @@
{% else %}
<p class="empty">No users yet.</p>
{% endfor %}
{% if !remote_actors.is_empty() %}
<h2 class="page-title federated-title">Federated</h2>
{% for actor in remote_actors %}
<div class="user-row">
<div class="user-avatar federated-avatar">{{ actor.initial }}</div>
<div class="user-info">
<div class="user-name">{{ actor.display_name }}</div>
<div class="user-meta muted">{{ actor.handle }}</div>
</div>
<a href="{{ actor.url }}" target="_blank" rel="noopener noreferrer" class="btn-secondary">
View profile ↗
</a>
</div>
{% endfor %}
{% endif %}
</div>
{% endblock %}