federation refinement
This commit is contained in:
38
.sqlx/query-0e36417429360e7e332f60768c2283a78b18c57cb72978921ccc0df963a756ba.json
generated
Normal file
38
.sqlx/query-0e36417429360e7e332f60768c2283a78b18c57cb72978921ccc0df963a756ba.json
generated
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT id, email, username, password_hash FROM users WHERE username = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "email",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "username",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "password_hash",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "0e36417429360e7e332f60768c2283a78b18c57cb72978921ccc0df963a756ba"
|
||||||
|
}
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
{
|
|
||||||
"db_name": "SQLite",
|
|
||||||
"query": "INSERT OR IGNORE INTO users (id, email, password_hash, created_at) VALUES (?, ?, ?, ?)",
|
|
||||||
"describe": {
|
|
||||||
"columns": [],
|
|
||||||
"parameters": {
|
|
||||||
"Right": 4
|
|
||||||
},
|
|
||||||
"nullable": []
|
|
||||||
},
|
|
||||||
"hash": "18de90feb13b9f467f06d0ce25332d9ea7eabc99d9f1a44694e5d10762606f82"
|
|
||||||
}
|
|
||||||
12
.sqlx/query-21751a2efb5fc58f5c1057f332f537419b7067ff665a03e248e6ea0fe7b6919b.json
generated
Normal file
12
.sqlx/query-21751a2efb5fc58f5c1057f332f537419b7067ff665a03e248e6ea0fe7b6919b.json
generated
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "INSERT INTO users (id, email, username, password_hash, created_at) VALUES (?, ?, ?, ?, ?)",
|
||||||
|
"describe": {
|
||||||
|
"columns": [],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 5
|
||||||
|
},
|
||||||
|
"nullable": []
|
||||||
|
},
|
||||||
|
"hash": "21751a2efb5fc58f5c1057f332f537419b7067ff665a03e248e6ea0fe7b6919b"
|
||||||
|
}
|
||||||
38
.sqlx/query-2c7353f34c4748d4d4be6abbf343fa7ea30eeb985c4bfd12b0fc3997d1ba03bb.json
generated
Normal file
38
.sqlx/query-2c7353f34c4748d4d4be6abbf343fa7ea30eeb985c4bfd12b0fc3997d1ba03bb.json
generated
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT u.id AS \"id!: String\",\n u.email AS \"email!: String\",\n COUNT(DISTINCT r.movie_id) AS \"total_movies!: i64\",\n AVG(CAST(r.rating AS REAL)) AS avg_rating\n FROM users u\n LEFT JOIN reviews r ON r.user_id = u.id AND r.remote_actor_url IS NULL\n GROUP BY u.id, u.email\n ORDER BY u.email ASC",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id!: String",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "email!: String",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "total_movies!: i64",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "avg_rating",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Float"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 0
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "2c7353f34c4748d4d4be6abbf343fa7ea30eeb985c4bfd12b0fc3997d1ba03bb"
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"db_name": "SQLite",
|
"db_name": "SQLite",
|
||||||
"query": "SELECT id, email, password_hash FROM users WHERE id = ?",
|
"query": "SELECT id, email, username, password_hash FROM users WHERE email = ?",
|
||||||
"describe": {
|
"describe": {
|
||||||
"columns": [
|
"columns": [
|
||||||
{
|
{
|
||||||
@@ -14,19 +14,25 @@
|
|||||||
"type_info": "Text"
|
"type_info": "Text"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "password_hash",
|
"name": "username",
|
||||||
"ordinal": 2,
|
"ordinal": 2,
|
||||||
"type_info": "Text"
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "password_hash",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Text"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"parameters": {
|
"parameters": {
|
||||||
"Right": 1
|
"Right": 1
|
||||||
},
|
},
|
||||||
"nullable": [
|
"nullable": [
|
||||||
|
true,
|
||||||
false,
|
false,
|
||||||
false,
|
false,
|
||||||
false
|
false
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"hash": "1bc5a51762717e45292626052f0a65ac0b8a001798a2476ea86143c5565df399"
|
"hash": "4eeae6aa887319cab4a9fd673c3a75dec1e6681739d722481233a3d9e7a01955"
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"db_name": "SQLite",
|
"db_name": "SQLite",
|
||||||
"query": "SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,\n 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,\n u.email AS user_email\n FROM reviews r\n INNER JOIN movies m ON m.id = r.movie_id\n INNER JOIN users u ON u.id = r.user_id\n ORDER BY r.watched_at DESC\n LIMIT ? OFFSET ?",
|
"query": "SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,\n 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,\n COALESCE(u.email, r.remote_actor_url) AS \"user_email!: String\"\n FROM reviews r\n INNER JOIN movies m ON m.id = r.movie_id\n LEFT JOIN users u ON u.id = r.user_id\n ORDER BY r.watched_at DESC\n LIMIT ? OFFSET ?",
|
||||||
"describe": {
|
"describe": {
|
||||||
"columns": [
|
"columns": [
|
||||||
{
|
{
|
||||||
@@ -74,7 +74,7 @@
|
|||||||
"type_info": "Text"
|
"type_info": "Text"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "user_email",
|
"name": "user_email!: String",
|
||||||
"ordinal": 14,
|
"ordinal": 14,
|
||||||
"type_info": "Text"
|
"type_info": "Text"
|
||||||
}
|
}
|
||||||
@@ -97,8 +97,8 @@
|
|||||||
false,
|
false,
|
||||||
false,
|
false,
|
||||||
true,
|
true,
|
||||||
false
|
true
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"hash": "1d62f367cd14f6fa82aff8aa289e499a56832d1c90eac2f5ba06b019c3f86541"
|
"hash": "70843058606802f0958d216a47473f78b29854518c48c2da3cc11a94d6d37bb1"
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"db_name": "SQLite",
|
"db_name": "SQLite",
|
||||||
"query": "SELECT id, email, password_hash FROM users WHERE email = ?",
|
"query": "SELECT id, email, username, password_hash FROM users WHERE id = ?",
|
||||||
"describe": {
|
"describe": {
|
||||||
"columns": [
|
"columns": [
|
||||||
{
|
{
|
||||||
@@ -14,19 +14,25 @@
|
|||||||
"type_info": "Text"
|
"type_info": "Text"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "password_hash",
|
"name": "username",
|
||||||
"ordinal": 2,
|
"ordinal": 2,
|
||||||
"type_info": "Text"
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "password_hash",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Text"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"parameters": {
|
"parameters": {
|
||||||
"Right": 1
|
"Right": 1
|
||||||
},
|
},
|
||||||
"nullable": [
|
"nullable": [
|
||||||
|
true,
|
||||||
false,
|
false,
|
||||||
false,
|
false,
|
||||||
false
|
false
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"hash": "167481bb1692cc81531d9a5cd85425e43d09a6df97c335ac347f7cfd61acd171"
|
"hash": "e51c6da943bd326a09632aa0cfd30c4f15ca554e229778b6cfa04889b7231b36"
|
||||||
}
|
}
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
{
|
|
||||||
"db_name": "SQLite",
|
|
||||||
"query": "SELECT u.id,\n u.email,\n COUNT(DISTINCT r.movie_id) AS \"total_movies!: i64\",\n AVG(CAST(r.rating AS REAL)) AS avg_rating\n FROM users u\n LEFT JOIN reviews r ON r.user_id = u.id\n GROUP BY u.id, u.email\n ORDER BY u.email ASC",
|
|
||||||
"describe": {
|
|
||||||
"columns": [
|
|
||||||
{
|
|
||||||
"name": "id",
|
|
||||||
"ordinal": 0,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "email",
|
|
||||||
"ordinal": 1,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "total_movies!: i64",
|
|
||||||
"ordinal": 2,
|
|
||||||
"type_info": "Integer"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "avg_rating",
|
|
||||||
"ordinal": 3,
|
|
||||||
"type_info": "Float"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"parameters": {
|
|
||||||
"Right": 0
|
|
||||||
},
|
|
||||||
"nullable": [
|
|
||||||
false,
|
|
||||||
false,
|
|
||||||
false,
|
|
||||||
true
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"hash": "f259059d76f29cade94e249735d37ef4993fe5bff095dc43e681b848a398f318"
|
|
||||||
}
|
|
||||||
@@ -7,6 +7,7 @@ WORKDIR /build
|
|||||||
|
|
||||||
# Cache dependency compilation separately from source
|
# Cache dependency compilation separately from source
|
||||||
COPY Cargo.toml Cargo.lock ./
|
COPY Cargo.toml Cargo.lock ./
|
||||||
|
COPY crates/adapters/activitypub/Cargo.toml crates/adapters/activitypub/Cargo.toml
|
||||||
COPY crates/adapters/auth/Cargo.toml crates/adapters/auth/Cargo.toml
|
COPY crates/adapters/auth/Cargo.toml crates/adapters/auth/Cargo.toml
|
||||||
COPY crates/adapters/event-publisher/Cargo.toml crates/adapters/event-publisher/Cargo.toml
|
COPY crates/adapters/event-publisher/Cargo.toml crates/adapters/event-publisher/Cargo.toml
|
||||||
COPY crates/adapters/metadata/Cargo.toml crates/adapters/metadata/Cargo.toml
|
COPY crates/adapters/metadata/Cargo.toml crates/adapters/metadata/Cargo.toml
|
||||||
@@ -33,7 +34,9 @@ COPY crates ./crates
|
|||||||
RUN sqlite3 /build/dev.db \
|
RUN sqlite3 /build/dev.db \
|
||||||
< crates/adapters/sqlite/migrations/0001_initial.sql && \
|
< crates/adapters/sqlite/migrations/0001_initial.sql && \
|
||||||
sqlite3 /build/dev.db \
|
sqlite3 /build/dev.db \
|
||||||
< crates/adapters/sqlite/migrations/0002_users.sql
|
< crates/adapters/sqlite/migrations/0002_users.sql && \
|
||||||
|
sqlite3 /build/dev.db \
|
||||||
|
< crates/adapters/sqlite/migrations/0003_activitypub.sql
|
||||||
|
|
||||||
ENV DATABASE_URL=sqlite:///build/dev.db
|
ENV DATABASE_URL=sqlite:///build/dev.db
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
use activitypub_federation::{
|
use activitypub_federation::{
|
||||||
config::Data,
|
config::Data,
|
||||||
fetch::object_id::ObjectId,
|
fetch::object_id::ObjectId,
|
||||||
kinds::activity::{AcceptType, CreateType, DeleteType, FollowType, RejectType, UndoType},
|
kinds::activity::{AcceptType, CreateType, DeleteType, FollowType, RejectType, UndoType, UpdateType},
|
||||||
traits::{Activity, Actor, Object},
|
traits::{Activity, Object},
|
||||||
};
|
};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use url::Url;
|
use url::Url;
|
||||||
@@ -11,7 +11,7 @@ use crate::actors::DbActor;
|
|||||||
use crate::data::FederationData;
|
use crate::data::FederationData;
|
||||||
use crate::error::Error;
|
use crate::error::Error;
|
||||||
use crate::objects::{DbReview, ReviewObject};
|
use crate::objects::{DbReview, ReviewObject};
|
||||||
use crate::repository::FollowerStatus;
|
use crate::repository::{FollowerStatus, FollowingStatus};
|
||||||
|
|
||||||
// --- Follow ---
|
// --- Follow ---
|
||||||
|
|
||||||
@@ -19,7 +19,7 @@ use crate::repository::FollowerStatus;
|
|||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct FollowActivity {
|
pub struct FollowActivity {
|
||||||
pub(crate) id: Url,
|
pub(crate) id: Url,
|
||||||
#[serde(rename = "type")]
|
#[serde(rename = "type", default)]
|
||||||
pub(crate) kind: FollowType,
|
pub(crate) kind: FollowType,
|
||||||
pub(crate) actor: ObjectId<DbActor>,
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
pub(crate) object: ObjectId<DbActor>,
|
pub(crate) object: ObjectId<DbActor>,
|
||||||
@@ -39,56 +39,36 @@ impl Activity for FollowActivity {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn verify(&self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
async fn verify(&self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
// Verify the target is a local actor
|
|
||||||
let target_url = self.object.inner();
|
let target_url = self.object.inner();
|
||||||
if target_url.domain() != Some(&data.domain) {
|
// Url::domain() strips the port, so build host:port explicitly
|
||||||
return Err(Error(anyhow::anyhow!(
|
let target_domain = match (target_url.host_str(), target_url.port()) {
|
||||||
"follow target is not a local actor"
|
(Some(host), Some(port)) => format!("{}:{}", host, port),
|
||||||
)));
|
(Some(host), None) => host.to_string(),
|
||||||
|
_ => return Err(Error::bad_request(anyhow::anyhow!("invalid follow target URL"))),
|
||||||
|
};
|
||||||
|
if target_domain != data.domain {
|
||||||
|
return Err(Error::bad_request(anyhow::anyhow!("follow target is not a local actor")));
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
let follower = self.actor.dereference(data).await?;
|
let _follower = self.actor.dereference(data).await?;
|
||||||
let local_actor = self.object.dereference(data).await?;
|
let local_actor = self.object.dereference(data).await?;
|
||||||
|
|
||||||
data.federation_repo
|
data.federation_repo
|
||||||
.add_follower(
|
.add_follower(
|
||||||
local_actor.user_id.clone(),
|
local_actor.user_id.clone(),
|
||||||
self.actor.inner().as_str(),
|
self.actor.inner().as_str(),
|
||||||
FollowerStatus::Accepted,
|
FollowerStatus::Pending,
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
// Send Accept back
|
|
||||||
let accept_id =
|
|
||||||
Url::parse(&format!("{}/activities/{}", data.base_url, uuid::Uuid::new_v4()))
|
|
||||||
.expect("valid url");
|
|
||||||
let accept = AcceptActivity {
|
|
||||||
id: accept_id,
|
|
||||||
kind: Default::default(),
|
|
||||||
actor: self.object.clone(),
|
|
||||||
object: self.clone(),
|
|
||||||
};
|
|
||||||
|
|
||||||
use activitypub_federation::activity_sending::SendActivityTask;
|
|
||||||
use activitypub_federation::protocol::context::WithContext;
|
|
||||||
|
|
||||||
let accept_with_ctx = WithContext::new_default(accept);
|
|
||||||
let sends =
|
|
||||||
SendActivityTask::prepare(&accept_with_ctx, &local_actor, vec![follower.inbox()], data)
|
|
||||||
.await?;
|
|
||||||
for send in sends {
|
|
||||||
send.sign_and_send(data).await?;
|
|
||||||
}
|
|
||||||
|
|
||||||
tracing::info!(
|
tracing::info!(
|
||||||
follower = %self.actor.inner(),
|
follower = %self.actor.inner(),
|
||||||
local_user = %local_actor.user_id.value(),
|
local_user = %local_actor.user_id.value(),
|
||||||
"accepted follow"
|
"follow request pending approval"
|
||||||
);
|
);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -99,7 +79,7 @@ impl Activity for FollowActivity {
|
|||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct AcceptActivity {
|
pub struct AcceptActivity {
|
||||||
pub(crate) id: Url,
|
pub(crate) id: Url,
|
||||||
#[serde(rename = "type")]
|
#[serde(rename = "type", default)]
|
||||||
pub(crate) kind: AcceptType,
|
pub(crate) kind: AcceptType,
|
||||||
pub(crate) actor: ObjectId<DbActor>,
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
pub(crate) object: FollowActivity,
|
pub(crate) object: FollowActivity,
|
||||||
@@ -122,10 +102,17 @@ impl Activity for AcceptActivity {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn receive(self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
let remote_actor_url = self.actor.into_inner().to_string();
|
let local_user_id = crate::urls::extract_user_id_from_url(self.object.actor.inner())
|
||||||
tracing::info!(remote_actor_url = %remote_actor_url, "Follow accepted by remote instance");
|
.ok_or_else(|| Error::bad_request(anyhow::anyhow!("invalid actor URL in Follow")))?;
|
||||||
// TODO(ap): update ap_following to track accepted status
|
let remote_actor_url = self.actor.inner().as_str();
|
||||||
|
data.federation_repo
|
||||||
|
.update_following_status(local_user_id, remote_actor_url, FollowingStatus::Accepted)
|
||||||
|
.await?;
|
||||||
|
tracing::info!(
|
||||||
|
remote_actor = %self.actor.inner(),
|
||||||
|
"follow accepted by remote"
|
||||||
|
);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -136,7 +123,7 @@ impl Activity for AcceptActivity {
|
|||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct RejectActivity {
|
pub struct RejectActivity {
|
||||||
pub(crate) id: Url,
|
pub(crate) id: Url,
|
||||||
#[serde(rename = "type")]
|
#[serde(rename = "type", default)]
|
||||||
pub(crate) kind: RejectType,
|
pub(crate) kind: RejectType,
|
||||||
pub(crate) actor: ObjectId<DbActor>,
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
pub(crate) object: FollowActivity,
|
pub(crate) object: FollowActivity,
|
||||||
@@ -162,14 +149,10 @@ impl Activity for RejectActivity {
|
|||||||
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
// The actor rejected our follow. Extract the local user from the original Follow's actor.
|
// The actor rejected our follow. Extract the local user from the original Follow's actor.
|
||||||
let local_user_url = self.object.actor.inner();
|
let local_user_url = self.object.actor.inner();
|
||||||
let path = local_user_url.path();
|
if let Some(user_id) = crate::urls::extract_user_id_from_url(local_user_url) {
|
||||||
if let Some(uid_str) = path.strip_prefix("/users/").and_then(|s| s.split('/').next()) {
|
data.federation_repo
|
||||||
if let Ok(uuid) = uuid::Uuid::parse_str(uid_str) {
|
.remove_following(user_id, self.actor.inner().as_str())
|
||||||
let user_id = domain::value_objects::UserId::from_uuid(uuid);
|
.await?;
|
||||||
data.federation_repo
|
|
||||||
.remove_following(user_id, self.actor.inner().as_str())
|
|
||||||
.await?;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
tracing::info!(actor = %self.actor.inner(), "follow rejected");
|
tracing::info!(actor = %self.actor.inner(), "follow rejected");
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -182,7 +165,7 @@ impl Activity for RejectActivity {
|
|||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct UndoActivity {
|
pub struct UndoActivity {
|
||||||
pub(crate) id: Url,
|
pub(crate) id: Url,
|
||||||
#[serde(rename = "type")]
|
#[serde(rename = "type", default)]
|
||||||
pub(crate) kind: UndoType,
|
pub(crate) kind: UndoType,
|
||||||
pub(crate) actor: ObjectId<DbActor>,
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
pub(crate) object: FollowActivity,
|
pub(crate) object: FollowActivity,
|
||||||
@@ -208,14 +191,10 @@ impl Activity for UndoActivity {
|
|||||||
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
// Remote actor is unfollowing a local user
|
// Remote actor is unfollowing a local user
|
||||||
let local_user_url = self.object.object.inner();
|
let local_user_url = self.object.object.inner();
|
||||||
let path = local_user_url.path();
|
if let Some(user_id) = crate::urls::extract_user_id_from_url(local_user_url) {
|
||||||
if let Some(uid_str) = path.strip_prefix("/users/").and_then(|s| s.split('/').next()) {
|
data.federation_repo
|
||||||
if let Ok(uuid) = uuid::Uuid::parse_str(uid_str) {
|
.remove_follower(user_id, self.actor.inner().as_str())
|
||||||
let user_id = domain::value_objects::UserId::from_uuid(uuid);
|
.await?;
|
||||||
data.federation_repo
|
|
||||||
.remove_follower(user_id, self.actor.inner().as_str())
|
|
||||||
.await?;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
tracing::info!(actor = %self.actor.inner(), "unfollowed");
|
tracing::info!(actor = %self.actor.inner(), "unfollowed");
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -228,7 +207,7 @@ impl Activity for UndoActivity {
|
|||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct CreateActivity {
|
pub struct CreateActivity {
|
||||||
pub(crate) id: Url,
|
pub(crate) id: Url,
|
||||||
#[serde(rename = "type")]
|
#[serde(rename = "type", default)]
|
||||||
pub(crate) kind: CreateType,
|
pub(crate) kind: CreateType,
|
||||||
pub(crate) actor: ObjectId<DbActor>,
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
pub(crate) object: ReviewObject,
|
pub(crate) object: ReviewObject,
|
||||||
@@ -248,6 +227,11 @@ impl Activity for CreateActivity {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
if self.object.attributed_to.inner() != self.actor.inner() {
|
||||||
|
return Err(Error::bad_request(anyhow::anyhow!(
|
||||||
|
"activity actor does not match object attributed_to"
|
||||||
|
)));
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -264,7 +248,7 @@ impl Activity for CreateActivity {
|
|||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct DeleteActivity {
|
pub struct DeleteActivity {
|
||||||
pub(crate) id: Url,
|
pub(crate) id: Url,
|
||||||
#[serde(rename = "type")]
|
#[serde(rename = "type", default)]
|
||||||
pub(crate) kind: DeleteType,
|
pub(crate) kind: DeleteType,
|
||||||
pub(crate) actor: ObjectId<DbActor>,
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
pub(crate) object: Url,
|
pub(crate) object: Url,
|
||||||
@@ -287,8 +271,61 @@ impl Activity for DeleteActivity {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn receive(self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
tracing::info!(actor = %self.actor.inner(), object = %self.object, "delete received (no-op)");
|
data.federation_repo
|
||||||
|
.delete_remote_review_by_ap_id(
|
||||||
|
self.object.as_str(),
|
||||||
|
self.actor.inner().as_str(),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
tracing::info!(object = %self.object, "remote review deleted");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Update ---
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct UpdateActivity {
|
||||||
|
pub(crate) id: Url,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub(crate) kind: UpdateType,
|
||||||
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
|
pub(crate) object: ReviewObject,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Activity for UpdateActivity {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actor(&self) -> &Url {
|
||||||
|
self.actor.inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
if self.object.attributed_to.inner() != self.actor.inner() {
|
||||||
|
return Err(Error::bad_request(anyhow::anyhow!(
|
||||||
|
"update actor does not match object attributed_to"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
let ap_id = self.object.id.inner().as_str();
|
||||||
|
let rating = self.object.rating.min(5);
|
||||||
|
let comment = self.object.comment.as_deref();
|
||||||
|
let watched_at = self.object.watched_at.naive_utc();
|
||||||
|
data.federation_repo
|
||||||
|
.update_remote_review(ap_id, self.actor.inner().as_str(), rating, comment, watched_at)
|
||||||
|
.await?;
|
||||||
|
tracing::info!(actor = %self.actor.inner(), ap_id = %ap_id, "remote review updated");
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -311,4 +348,6 @@ pub enum InboxActivities {
|
|||||||
Create(CreateActivity),
|
Create(CreateActivity),
|
||||||
#[serde(rename = "Delete")]
|
#[serde(rename = "Delete")]
|
||||||
Delete(DeleteActivity),
|
Delete(DeleteActivity),
|
||||||
|
#[serde(rename = "Update")]
|
||||||
|
Update(UpdateActivity),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ pub async fn actor_handler(
|
|||||||
data: Data<FederationData>,
|
data: Data<FederationData>,
|
||||||
) -> Result<FederationJson<WithContext<Person>>, Error> {
|
) -> Result<FederationJson<WithContext<Person>>, Error> {
|
||||||
let uuid = uuid::Uuid::parse_str(&user_id_str)
|
let uuid = uuid::Uuid::parse_str(&user_id_str)
|
||||||
.map_err(|_| Error(anyhow::anyhow!("invalid user id")))?;
|
.map_err(|_| Error::bad_request(anyhow::anyhow!("invalid user id")))?;
|
||||||
let user_id = UserId::from_uuid(uuid);
|
let user_id = UserId::from_uuid(uuid);
|
||||||
|
|
||||||
let db_actor = get_local_actor(user_id, &data).await?;
|
let db_actor = get_local_actor(user_id, &data).await?;
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ use crate::repository::RemoteActor;
|
|||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct DbActor {
|
pub struct DbActor {
|
||||||
pub user_id: UserId,
|
pub user_id: UserId,
|
||||||
pub email: String,
|
pub username: String,
|
||||||
pub public_key_pem: String,
|
pub public_key_pem: String,
|
||||||
pub private_key_pem: Option<String>,
|
pub private_key_pem: Option<String>,
|
||||||
pub inbox_url: Url,
|
pub inbox_url: Url,
|
||||||
@@ -45,10 +45,6 @@ pub struct Person {
|
|||||||
name: Option<String>,
|
name: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn actor_url(base_url: &str, user_id: &UserId) -> Url {
|
|
||||||
Url::parse(&format!("{}/users/{}", base_url, user_id.value())).expect("valid actor url")
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn get_local_actor(
|
pub async fn get_local_actor(
|
||||||
user_id: UserId,
|
user_id: UserId,
|
||||||
data: &Data<FederationData>,
|
data: &Data<FederationData>,
|
||||||
@@ -57,8 +53,8 @@ pub async fn get_local_actor(
|
|||||||
.user_repo
|
.user_repo
|
||||||
.find_by_id(&user_id)
|
.find_by_id(&user_id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| Error(e.into()))?
|
.map_err(Error::from)?
|
||||||
.ok_or_else(|| Error(anyhow::anyhow!("user not found: {}", user_id.value())))?;
|
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found: {}", user_id.value())))?;
|
||||||
|
|
||||||
let (public_key, private_key) = match data
|
let (public_key, private_key) = match data
|
||||||
.federation_repo
|
.federation_repo
|
||||||
@@ -79,7 +75,7 @@ pub async fn get_local_actor(
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let ap_id = actor_url(&data.base_url, user.id());
|
let ap_id = crate::urls::actor_url(&data.base_url, user.id());
|
||||||
let inbox_url = Url::parse(&format!("{}/inbox", &ap_id)).expect("valid inbox url");
|
let inbox_url = Url::parse(&format!("{}/inbox", &ap_id)).expect("valid inbox url");
|
||||||
let outbox_url = Url::parse(&format!("{}/outbox", &ap_id)).expect("valid outbox url");
|
let outbox_url = Url::parse(&format!("{}/outbox", &ap_id)).expect("valid outbox url");
|
||||||
let followers_url = Url::parse(&format!("{}/followers", &ap_id)).expect("valid followers url");
|
let followers_url = Url::parse(&format!("{}/followers", &ap_id)).expect("valid followers url");
|
||||||
@@ -87,7 +83,7 @@ pub async fn get_local_actor(
|
|||||||
|
|
||||||
Ok(DbActor {
|
Ok(DbActor {
|
||||||
user_id: user.id().clone(),
|
user_id: user.id().clone(),
|
||||||
email: user.email().value().to_string(),
|
username: user.username().value().to_string(),
|
||||||
public_key_pem: public_key,
|
public_key_pem: public_key,
|
||||||
private_key_pem: Some(private_key),
|
private_key_pem: Some(private_key),
|
||||||
inbox_url,
|
inbox_url,
|
||||||
@@ -118,22 +114,10 @@ impl Object for DbActor {
|
|||||||
data: &Data<Self::DataType>,
|
data: &Data<Self::DataType>,
|
||||||
) -> Result<Option<Self>, Self::Error> {
|
) -> Result<Option<Self>, Self::Error> {
|
||||||
// Extract user_id from URL path: /users/{uuid}
|
// Extract user_id from URL path: /users/{uuid}
|
||||||
let path = object_id.path();
|
let user_id = match crate::urls::extract_user_id_from_url(&object_id) {
|
||||||
let user_id_str = path
|
Some(id) => id,
|
||||||
.strip_prefix("/users/")
|
|
||||||
.and_then(|s| s.split('/').next());
|
|
||||||
|
|
||||||
let user_id_str = match user_id_str {
|
|
||||||
Some(s) => s,
|
|
||||||
None => return Ok(None),
|
None => return Ok(None),
|
||||||
};
|
};
|
||||||
|
|
||||||
let uuid = match uuid::Uuid::parse_str(user_id_str) {
|
|
||||||
Ok(u) => u,
|
|
||||||
Err(_) => return Ok(None),
|
|
||||||
};
|
|
||||||
|
|
||||||
let user_id = UserId::from_uuid(uuid);
|
|
||||||
let user = match data.user_repo.find_by_id(&user_id).await {
|
let user = match data.user_repo.find_by_id(&user_id).await {
|
||||||
Ok(Some(u)) => u,
|
Ok(Some(u)) => u,
|
||||||
_ => return Ok(None),
|
_ => return Ok(None),
|
||||||
@@ -149,7 +133,7 @@ impl Object for DbActor {
|
|||||||
None => return Ok(None),
|
None => return Ok(None),
|
||||||
};
|
};
|
||||||
|
|
||||||
let ap_id = actor_url(&data.base_url, user.id());
|
let ap_id = crate::urls::actor_url(&data.base_url, user.id());
|
||||||
let inbox_url = Url::parse(&format!("{}/inbox", &ap_id)).expect("valid url");
|
let inbox_url = Url::parse(&format!("{}/inbox", &ap_id)).expect("valid url");
|
||||||
let outbox_url = Url::parse(&format!("{}/outbox", &ap_id)).expect("valid url");
|
let outbox_url = Url::parse(&format!("{}/outbox", &ap_id)).expect("valid url");
|
||||||
let followers_url = Url::parse(&format!("{}/followers", &ap_id)).expect("valid url");
|
let followers_url = Url::parse(&format!("{}/followers", &ap_id)).expect("valid url");
|
||||||
@@ -157,7 +141,7 @@ impl Object for DbActor {
|
|||||||
|
|
||||||
Ok(Some(DbActor {
|
Ok(Some(DbActor {
|
||||||
user_id: user.id().clone(),
|
user_id: user.id().clone(),
|
||||||
email: user.email().value().to_string(),
|
username: user.username().value().to_string(),
|
||||||
public_key_pem: public_key,
|
public_key_pem: public_key,
|
||||||
private_key_pem: private_key,
|
private_key_pem: private_key,
|
||||||
inbox_url,
|
inbox_url,
|
||||||
@@ -179,18 +163,13 @@ impl Object for DbActor {
|
|||||||
Ok(Person {
|
Ok(Person {
|
||||||
kind: Default::default(),
|
kind: Default::default(),
|
||||||
id: self.ap_id.clone().into(),
|
id: self.ap_id.clone().into(),
|
||||||
preferred_username: self
|
preferred_username: self.username.clone(),
|
||||||
.email
|
|
||||||
.split('@')
|
|
||||||
.next()
|
|
||||||
.unwrap_or(&self.email)
|
|
||||||
.to_string(),
|
|
||||||
inbox: self.inbox_url.clone(),
|
inbox: self.inbox_url.clone(),
|
||||||
outbox: self.outbox_url.clone(),
|
outbox: self.outbox_url.clone(),
|
||||||
followers: self.followers_url.clone(),
|
followers: self.followers_url.clone(),
|
||||||
following: self.following_url.clone(),
|
following: self.following_url.clone(),
|
||||||
public_key,
|
public_key,
|
||||||
name: Some(self.email.clone()),
|
name: Some(self.username.clone()),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -228,9 +207,7 @@ impl Object for DbActor {
|
|||||||
|
|
||||||
Ok(DbActor {
|
Ok(DbActor {
|
||||||
user_id,
|
user_id,
|
||||||
email: json
|
username: json.preferred_username.clone(),
|
||||||
.name
|
|
||||||
.unwrap_or_else(|| json.preferred_username.clone()),
|
|
||||||
public_key_pem: json.public_key.public_key_pem,
|
public_key_pem: json.public_key.public_key_pem,
|
||||||
private_key_pem: None,
|
private_key_pem: None,
|
||||||
inbox_url,
|
inbox_url,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use domain::ports::UserRepository;
|
use domain::ports::{MovieRepository, UserRepository};
|
||||||
|
|
||||||
use crate::repository::FederationRepository;
|
use crate::repository::FederationRepository;
|
||||||
|
|
||||||
@@ -8,6 +8,7 @@ use crate::repository::FederationRepository;
|
|||||||
pub struct FederationData {
|
pub struct FederationData {
|
||||||
pub(crate) federation_repo: Arc<dyn FederationRepository>,
|
pub(crate) federation_repo: Arc<dyn FederationRepository>,
|
||||||
pub(crate) user_repo: Arc<dyn UserRepository>,
|
pub(crate) user_repo: Arc<dyn UserRepository>,
|
||||||
|
pub(crate) movie_repo: Arc<dyn MovieRepository>,
|
||||||
pub(crate) base_url: String,
|
pub(crate) base_url: String,
|
||||||
pub(crate) domain: String,
|
pub(crate) domain: String,
|
||||||
}
|
}
|
||||||
@@ -16,6 +17,7 @@ impl FederationData {
|
|||||||
pub fn new(
|
pub fn new(
|
||||||
federation_repo: Arc<dyn FederationRepository>,
|
federation_repo: Arc<dyn FederationRepository>,
|
||||||
user_repo: Arc<dyn UserRepository>,
|
user_repo: Arc<dyn UserRepository>,
|
||||||
|
movie_repo: Arc<dyn MovieRepository>,
|
||||||
base_url: String,
|
base_url: String,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let domain = base_url
|
let domain = base_url
|
||||||
@@ -28,6 +30,7 @@ impl FederationData {
|
|||||||
Self {
|
Self {
|
||||||
federation_repo,
|
federation_repo,
|
||||||
user_repo,
|
user_repo,
|
||||||
|
movie_repo,
|
||||||
base_url,
|
base_url,
|
||||||
domain,
|
domain,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,20 @@
|
|||||||
use std::fmt::{Display, Formatter};
|
use std::fmt::{Display, Formatter};
|
||||||
|
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Error(pub(crate) anyhow::Error);
|
pub struct Error(pub(crate) anyhow::Error, pub(crate) StatusCode);
|
||||||
|
|
||||||
|
impl Error {
|
||||||
|
pub fn not_found(e: impl Into<anyhow::Error>) -> Self {
|
||||||
|
Self(e.into(), StatusCode::NOT_FOUND)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn bad_request(e: impl Into<anyhow::Error>) -> Self {
|
||||||
|
Self(e.into(), StatusCode::BAD_REQUEST)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
impl Display for Error {
|
impl Display for Error {
|
||||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||||
@@ -14,23 +27,23 @@ where
|
|||||||
T: Into<anyhow::Error>,
|
T: Into<anyhow::Error>,
|
||||||
{
|
{
|
||||||
fn from(t: T) -> Self {
|
fn from(t: T) -> Self {
|
||||||
Error(t.into())
|
Error(t.into(), StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl axum::response::IntoResponse for Error {
|
impl axum::response::IntoResponse for Error {
|
||||||
fn into_response(self) -> axum::response::Response {
|
fn into_response(self) -> axum::response::Response {
|
||||||
let msg = self.0.to_string();
|
let status = self.1;
|
||||||
let status = if msg.contains("not found") {
|
if status.is_server_error() {
|
||||||
tracing::debug!(error = %msg, "AP: not found");
|
tracing::error!(error = %self.0, status = status.as_u16(), "federation error");
|
||||||
(axum::http::StatusCode::NOT_FOUND, "Not found")
|
|
||||||
} else if msg.contains("invalid") || msg.contains("bad") {
|
|
||||||
tracing::debug!(error = %msg, "AP: bad request");
|
|
||||||
(axum::http::StatusCode::BAD_REQUEST, "Bad request")
|
|
||||||
} else {
|
} else {
|
||||||
tracing::error!(error = %msg, "AP: internal error");
|
tracing::debug!(error = %self.0, status = status.as_u16(), "federation response");
|
||||||
(axum::http::StatusCode::INTERNAL_SERVER_ERROR, "Internal server error")
|
}
|
||||||
|
let body = if status.is_server_error() {
|
||||||
|
"internal server error".to_string()
|
||||||
|
} else {
|
||||||
|
self.0.to_string()
|
||||||
};
|
};
|
||||||
status.into_response()
|
(status, body).into_response()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,9 +2,9 @@ use activitypub_federation::{
|
|||||||
activity_sending::SendActivityTask,
|
activity_sending::SendActivityTask,
|
||||||
fetch::object_id::ObjectId,
|
fetch::object_id::ObjectId,
|
||||||
protocol::context::WithContext,
|
protocol::context::WithContext,
|
||||||
|
traits::Object,
|
||||||
};
|
};
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use chrono::{DateTime, Utc};
|
|
||||||
use domain::{
|
use domain::{
|
||||||
errors::DomainError,
|
errors::DomainError,
|
||||||
events::DomainEvent,
|
events::DomainEvent,
|
||||||
@@ -15,9 +15,9 @@ use url::Url;
|
|||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
activities::CreateActivity,
|
activities::CreateActivity,
|
||||||
actors::{actor_url, get_local_actor},
|
actors::get_local_actor,
|
||||||
federation::ApFederationConfig,
|
federation::ApFederationConfig,
|
||||||
objects::{review_url, ReviewObject},
|
objects::DbReview,
|
||||||
repository::FollowerStatus,
|
repository::FollowerStatus,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -42,11 +42,9 @@ impl EventHandler for ActivityPubEventHandler {
|
|||||||
DomainEvent::ReviewLogged {
|
DomainEvent::ReviewLogged {
|
||||||
review_id,
|
review_id,
|
||||||
user_id,
|
user_id,
|
||||||
rating,
|
|
||||||
watched_at,
|
|
||||||
..
|
..
|
||||||
} => self
|
} => self
|
||||||
.on_review_logged(user_id, review_id, rating.value(), *watched_at)
|
.on_review_logged(user_id, review_id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string())),
|
.map_err(|e| DomainError::InfrastructureError(e.to_string())),
|
||||||
_ => Ok(()),
|
_ => Ok(()),
|
||||||
@@ -59,47 +57,42 @@ impl ActivityPubEventHandler {
|
|||||||
&self,
|
&self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
review_id: &ReviewId,
|
review_id: &ReviewId,
|
||||||
rating: u8,
|
|
||||||
watched_at: chrono::NaiveDateTime,
|
|
||||||
) -> anyhow::Result<()> {
|
) -> anyhow::Result<()> {
|
||||||
let data = self.federation_config.to_request_data();
|
let data = self.federation_config.to_request_data();
|
||||||
|
|
||||||
let followers = data.federation_repo.get_followers(user_id.clone()).await?;
|
let followers = data.federation_repo.get_followers(user_id.clone()).await?;
|
||||||
|
tracing::debug!(user_id = %user_id.value(), count = followers.len(), "AP: got followers for review");
|
||||||
|
|
||||||
let accepted: Vec<_> = followers
|
let accepted: Vec<_> = followers
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter(|f| f.status == FollowerStatus::Accepted)
|
.filter(|f| f.status == FollowerStatus::Accepted)
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
|
tracing::debug!(accepted = accepted.len(), "AP: accepted followers");
|
||||||
|
|
||||||
if accepted.is_empty() {
|
if accepted.is_empty() {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let review = match data.movie_repo.get_review_by_id(review_id).await? {
|
||||||
|
Some(r) => r,
|
||||||
|
None => return Ok(()),
|
||||||
|
};
|
||||||
|
|
||||||
let local_actor = get_local_actor(user_id.clone(), &data)
|
let local_actor = get_local_actor(user_id.clone(), &data)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
let review_id_url = review_url(&self.base_url, review_id);
|
let activity_id = crate::urls::activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
let actor_id = actor_url(&self.base_url, user_id);
|
|
||||||
let activity_id = Url::parse(&format!(
|
|
||||||
"{}/activities/{}",
|
|
||||||
self.base_url,
|
|
||||||
uuid::Uuid::new_v4()
|
|
||||||
))?;
|
|
||||||
|
|
||||||
let stars = "\u{2B50}".repeat(rating as usize);
|
let db_review = DbReview {
|
||||||
let now = DateTime::from_naive_utc_and_offset(watched_at, Utc);
|
ap_id: crate::urls::review_url(&self.base_url, review_id),
|
||||||
|
review,
|
||||||
let object = ReviewObject {
|
|
||||||
kind: "Review".to_string(),
|
|
||||||
id: review_id_url.into(),
|
|
||||||
attributed_to: actor_id.into(),
|
|
||||||
content: format!("{} (movie review)", stars),
|
|
||||||
published: Utc::now(),
|
|
||||||
movie_title: "Unknown".to_string(), // TODO: fetch from MovieRepository
|
|
||||||
rating,
|
|
||||||
comment: None,
|
|
||||||
watched_at: now,
|
|
||||||
};
|
};
|
||||||
|
let object = db_review
|
||||||
|
.into_json(&data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
let create = CreateActivity {
|
let create = CreateActivity {
|
||||||
id: activity_id,
|
id: activity_id,
|
||||||
@@ -111,15 +104,23 @@ impl ActivityPubEventHandler {
|
|||||||
|
|
||||||
let inboxes: Vec<Url> = accepted
|
let inboxes: Vec<Url> = accepted
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|f| Url::parse(&f.actor.inbox_url).ok())
|
.filter_map(|f| {
|
||||||
|
let url = Url::parse(&f.actor.inbox_url);
|
||||||
|
if url.is_err() {
|
||||||
|
tracing::warn!(inbox = %f.actor.inbox_url, "AP: invalid inbox URL, skipping follower");
|
||||||
|
}
|
||||||
|
url.ok()
|
||||||
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
|
tracing::debug!(inboxes = inboxes.len(), "AP: delivering to inboxes");
|
||||||
|
|
||||||
let sends =
|
let sends =
|
||||||
SendActivityTask::prepare(&create_with_ctx, &local_actor, inboxes, &data).await?;
|
SendActivityTask::prepare(&create_with_ctx, &local_actor, inboxes, &data).await?;
|
||||||
for send in sends {
|
tracing::debug!(sends = sends.len(), "AP: prepared sends");
|
||||||
if let Err(e) = send.sign_and_send(&data).await {
|
let failures = crate::service::send_with_retry(sends, &data).await;
|
||||||
tracing::warn!(error = %e, "failed to deliver activity to follower");
|
if !failures.is_empty() {
|
||||||
}
|
tracing::warn!(count = failures.len(), "some activity deliveries failed permanently");
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -1,18 +1,42 @@
|
|||||||
use activitypub_federation::config::{Data, FederationConfig, FederationMiddleware};
|
use activitypub_federation::config::{Data, FederationConfig, FederationMiddleware, UrlVerifier};
|
||||||
|
use activitypub_federation::error::Error as FedError;
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
use crate::data::FederationData;
|
use crate::data::FederationData;
|
||||||
|
|
||||||
|
// In debug mode, allow all URLs (including http://localhost:3000 where the
|
||||||
|
// port colon would otherwise fail the default domain character check).
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct PermissiveVerifier;
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl UrlVerifier for PermissiveVerifier {
|
||||||
|
async fn verify(&self, _url: &Url) -> Result<(), FedError> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct ApFederationConfig(pub FederationConfig<FederationData>);
|
pub struct ApFederationConfig(pub FederationConfig<FederationData>);
|
||||||
|
|
||||||
impl ApFederationConfig {
|
impl ApFederationConfig {
|
||||||
pub async fn new(data: FederationData, debug: bool) -> anyhow::Result<Self> {
|
pub async fn new(data: FederationData, debug: bool) -> anyhow::Result<Self> {
|
||||||
let config = FederationConfig::builder()
|
let config = if debug {
|
||||||
.domain(&data.domain)
|
FederationConfig::builder()
|
||||||
.app_data(data)
|
.domain(&data.domain)
|
||||||
.debug(debug)
|
.app_data(data)
|
||||||
.build()
|
.debug(true)
|
||||||
.await?;
|
.url_verifier(Box::new(PermissiveVerifier))
|
||||||
|
.build()
|
||||||
|
.await?
|
||||||
|
} else {
|
||||||
|
FederationConfig::builder()
|
||||||
|
.domain(&data.domain)
|
||||||
|
.app_data(data)
|
||||||
|
.debug(false)
|
||||||
|
.build()
|
||||||
|
.await?
|
||||||
|
};
|
||||||
Ok(Self(config))
|
Ok(Self(config))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,17 @@ use domain::value_objects::UserId;
|
|||||||
|
|
||||||
use crate::data::FederationData;
|
use crate::data::FederationData;
|
||||||
use crate::error::Error;
|
use crate::error::Error;
|
||||||
|
use crate::repository::FollowerStatus;
|
||||||
|
|
||||||
|
fn ordered_collection(id: String, total: usize, items: Vec<String>) -> serde_json::Value {
|
||||||
|
json!({
|
||||||
|
"@context": "https://www.w3.org/ns/activitystreams",
|
||||||
|
"type": "OrderedCollection",
|
||||||
|
"id": id,
|
||||||
|
"totalItems": total,
|
||||||
|
"orderedItems": items,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn followers_handler(
|
pub async fn followers_handler(
|
||||||
Path(user_id_str): Path<String>,
|
Path(user_id_str): Path<String>,
|
||||||
@@ -13,25 +24,29 @@ pub async fn followers_handler(
|
|||||||
) -> Result<FederationJson<serde_json::Value>, Error> {
|
) -> Result<FederationJson<serde_json::Value>, Error> {
|
||||||
let user_id = UserId::from_uuid(
|
let user_id = UserId::from_uuid(
|
||||||
uuid::Uuid::parse_str(&user_id_str)
|
uuid::Uuid::parse_str(&user_id_str)
|
||||||
.map_err(|_| Error(anyhow::anyhow!("invalid user id")))?,
|
.map_err(|_| Error::bad_request(anyhow::anyhow!("invalid user id")))?,
|
||||||
);
|
);
|
||||||
|
|
||||||
// verify user exists
|
|
||||||
data.user_repo
|
data.user_repo
|
||||||
.find_by_id(&user_id)
|
.find_by_id(&user_id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| Error(e.into()))?
|
.map_err(Error::from)?
|
||||||
.ok_or_else(|| Error(anyhow::anyhow!("user not found")))?;
|
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found")))?;
|
||||||
|
|
||||||
|
let followers = data
|
||||||
|
.federation_repo
|
||||||
|
.get_followers(user_id)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)?;
|
||||||
|
|
||||||
|
let items: Vec<String> = followers
|
||||||
|
.into_iter()
|
||||||
|
.filter(|f| f.status == FollowerStatus::Accepted)
|
||||||
|
.map(|f| f.actor.url)
|
||||||
|
.collect();
|
||||||
|
|
||||||
let id = format!("{}/users/{}/followers", data.base_url, user_id_str);
|
let id = format!("{}/users/{}/followers", data.base_url, user_id_str);
|
||||||
// TODO(ap): implement pagination
|
Ok(FederationJson(ordered_collection(id, items.len(), items)))
|
||||||
Ok(FederationJson(json!({
|
|
||||||
"@context": "https://www.w3.org/ns/activitystreams",
|
|
||||||
"type": "OrderedCollection",
|
|
||||||
"id": id,
|
|
||||||
"totalItems": 0,
|
|
||||||
"orderedItems": []
|
|
||||||
})))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn following_handler(
|
pub async fn following_handler(
|
||||||
@@ -40,23 +55,26 @@ pub async fn following_handler(
|
|||||||
) -> Result<FederationJson<serde_json::Value>, Error> {
|
) -> Result<FederationJson<serde_json::Value>, Error> {
|
||||||
let user_id = UserId::from_uuid(
|
let user_id = UserId::from_uuid(
|
||||||
uuid::Uuid::parse_str(&user_id_str)
|
uuid::Uuid::parse_str(&user_id_str)
|
||||||
.map_err(|_| Error(anyhow::anyhow!("invalid user id")))?,
|
.map_err(|_| Error::bad_request(anyhow::anyhow!("invalid user id")))?,
|
||||||
);
|
);
|
||||||
|
|
||||||
// verify user exists
|
|
||||||
data.user_repo
|
data.user_repo
|
||||||
.find_by_id(&user_id)
|
.find_by_id(&user_id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| Error(e.into()))?
|
.map_err(Error::from)?
|
||||||
.ok_or_else(|| Error(anyhow::anyhow!("user not found")))?;
|
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found")))?;
|
||||||
|
|
||||||
|
let following = data
|
||||||
|
.federation_repo
|
||||||
|
.get_following(user_id)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)?;
|
||||||
|
|
||||||
|
let items: Vec<String> = following
|
||||||
|
.into_iter()
|
||||||
|
.map(|a| a.url)
|
||||||
|
.collect();
|
||||||
|
|
||||||
let id = format!("{}/users/{}/following", data.base_url, user_id_str);
|
let id = format!("{}/users/{}/following", data.base_url, user_id_str);
|
||||||
// TODO(ap): implement pagination
|
Ok(FederationJson(ordered_collection(id, items.len(), items)))
|
||||||
Ok(FederationJson(json!({
|
|
||||||
"@context": "https://www.w3.org/ns/activitystreams",
|
|
||||||
"type": "OrderedCollection",
|
|
||||||
"id": id,
|
|
||||||
"totalItems": 0,
|
|
||||||
"orderedItems": []
|
|
||||||
})))
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ pub mod objects;
|
|||||||
pub mod outbox;
|
pub mod outbox;
|
||||||
pub mod repository;
|
pub mod repository;
|
||||||
pub mod service;
|
pub mod service;
|
||||||
|
pub(crate) mod urls;
|
||||||
pub mod webfinger;
|
pub mod webfinger;
|
||||||
|
|
||||||
pub use data::FederationData;
|
pub use data::FederationData;
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
use activitypub_federation::{
|
use activitypub_federation::{
|
||||||
config::Data,
|
config::Data,
|
||||||
fetch::object_id::ObjectId,
|
fetch::object_id::ObjectId,
|
||||||
|
kinds::object::NoteType,
|
||||||
protocol::verification::verify_domains_match,
|
protocol::verification::verify_domains_match,
|
||||||
traits::Object,
|
traits::Object,
|
||||||
};
|
};
|
||||||
@@ -19,12 +20,16 @@ use crate::error::Error;
|
|||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct ReviewObject {
|
pub struct ReviewObject {
|
||||||
#[serde(rename = "type")]
|
#[serde(rename = "type")]
|
||||||
pub(crate) kind: String,
|
pub(crate) kind: NoteType,
|
||||||
pub(crate) id: ObjectId<DbReview>,
|
pub(crate) id: ObjectId<DbReview>,
|
||||||
pub(crate) attributed_to: ObjectId<DbActor>,
|
pub(crate) attributed_to: ObjectId<DbActor>,
|
||||||
pub(crate) content: String,
|
pub(crate) content: String,
|
||||||
pub(crate) published: DateTime<Utc>,
|
pub(crate) published: DateTime<Utc>,
|
||||||
pub(crate) movie_title: String,
|
pub(crate) movie_title: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub(crate) release_year: u16, // 0 = unknown; default for old AP messages
|
||||||
|
#[serde(default)]
|
||||||
|
pub(crate) poster_url: Option<String>,
|
||||||
pub(crate) rating: u8,
|
pub(crate) rating: u8,
|
||||||
pub(crate) comment: Option<String>,
|
pub(crate) comment: Option<String>,
|
||||||
pub(crate) watched_at: DateTime<Utc>,
|
pub(crate) watched_at: DateTime<Utc>,
|
||||||
@@ -36,10 +41,6 @@ pub struct DbReview {
|
|||||||
pub ap_id: Url,
|
pub ap_id: Url,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn review_url(base_url: &str, review_id: &ReviewId) -> Url {
|
|
||||||
Url::parse(&format!("{}/reviews/{}", base_url, review_id.value())).expect("valid review url")
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl Object for DbReview {
|
impl Object for DbReview {
|
||||||
type DataType = FederationData;
|
type DataType = FederationData;
|
||||||
@@ -60,26 +61,39 @@ impl Object for DbReview {
|
|||||||
|
|
||||||
async fn into_json(self, data: &Data<Self::DataType>) -> Result<Self::Kind, Self::Error> {
|
async fn into_json(self, data: &Data<Self::DataType>) -> Result<Self::Kind, Self::Error> {
|
||||||
let r = &self.review;
|
let r = &self.review;
|
||||||
let ap_id = review_url(&data.base_url, r.id());
|
let ap_id = crate::urls::review_url(&data.base_url, r.id());
|
||||||
let actor_url = crate::actors::actor_url(&data.base_url, r.user_id());
|
let actor_url = crate::urls::actor_url(&data.base_url, r.user_id());
|
||||||
|
|
||||||
|
let movie = data.movie_repo.get_movie_by_id(r.movie_id()).await
|
||||||
|
.ok().flatten();
|
||||||
|
let movie_title = movie.as_ref()
|
||||||
|
.map(|m| m.title().value().to_string())
|
||||||
|
.unwrap_or_else(|| "Unknown".to_string());
|
||||||
|
let release_year = movie.as_ref()
|
||||||
|
.map(|m| m.release_year().value())
|
||||||
|
.unwrap_or(0);
|
||||||
|
let poster_url = movie.as_ref()
|
||||||
|
.and_then(|m| m.poster_path())
|
||||||
|
.map(|p| format!("{}/posters/{}", data.base_url, p.value()));
|
||||||
|
|
||||||
let stars: String = "\u{2B50}".repeat(r.rating().value() as usize);
|
let stars: String = "\u{2B50}".repeat(r.rating().value() as usize);
|
||||||
let comment_text = r.comment().map(|c| c.value().to_string());
|
let comment_text = r.comment().map(|c| c.value().to_string());
|
||||||
// TODO(ap): fetch movie title from MovieRepository via FederationData
|
let year_str = if release_year > 0 { format!(" ({})", release_year) } else { String::new() };
|
||||||
let movie_title = "Unknown".to_string();
|
let watched_str = format!("Watched: {}", r.watched_at().format("%b %-d, %Y"));
|
||||||
|
let content = match &comment_text {
|
||||||
let fallback = match &comment_text {
|
Some(c) => format!("{} {}{}\n{}\n{}", stars, movie_title, year_str, c, watched_str),
|
||||||
Some(c) => format!("{} Watched '{}': {}", stars, movie_title, c),
|
None => format!("{} {}{}\n{}", stars, movie_title, year_str, watched_str),
|
||||||
None => format!("{} Watched '{}'", stars, movie_title),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(ReviewObject {
|
Ok(ReviewObject {
|
||||||
kind: "Review".to_string(),
|
kind: NoteType::default(),
|
||||||
id: ap_id.into(),
|
id: ap_id.into(),
|
||||||
attributed_to: actor_url.into(),
|
attributed_to: actor_url.into(),
|
||||||
content: fallback,
|
content,
|
||||||
published: DateTime::from_naive_utc_and_offset(*r.created_at(), Utc),
|
published: DateTime::from_naive_utc_and_offset(*r.created_at(), Utc),
|
||||||
movie_title,
|
movie_title,
|
||||||
|
release_year,
|
||||||
|
poster_url,
|
||||||
rating: r.rating().value(),
|
rating: r.rating().value(),
|
||||||
comment: comment_text,
|
comment: comment_text,
|
||||||
watched_at: DateTime::from_naive_utc_and_offset(*r.watched_at(), Utc),
|
watched_at: DateTime::from_naive_utc_and_offset(*r.watched_at(), Utc),
|
||||||
@@ -102,19 +116,17 @@ impl Object for DbReview {
|
|||||||
let actor_url = json.attributed_to.inner().to_string();
|
let actor_url = json.attributed_to.inner().to_string();
|
||||||
|
|
||||||
let review_id = ReviewId::generate();
|
let review_id = ReviewId::generate();
|
||||||
// TODO(ap): create stub movie/user entries in DB so feed JOIN queries work.
|
|
||||||
// For now, use deterministic UUIDs from content hash; reviews will be orphaned in JOINs.
|
|
||||||
let movie_id_uuid = uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_URL, json.movie_title.as_bytes());
|
let movie_id_uuid = uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_URL, json.movie_title.as_bytes());
|
||||||
let movie_id = domain::value_objects::MovieId::from_uuid(movie_id_uuid);
|
let movie_id = domain::value_objects::MovieId::from_uuid(movie_id_uuid);
|
||||||
let user_id_uuid = uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_URL, actor_url.as_bytes());
|
let user_id_uuid = uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_URL, actor_url.as_bytes());
|
||||||
let user_id = domain::value_objects::UserId::from_uuid(user_id_uuid);
|
let user_id = domain::value_objects::UserId::from_uuid(user_id_uuid);
|
||||||
let rating = domain::value_objects::Rating::new(json.rating.min(5))
|
let rating = domain::value_objects::Rating::new(json.rating.min(5))
|
||||||
.map_err(|e| Error(anyhow::anyhow!("{}", e)))?;
|
.map_err(|e| Error::bad_request(anyhow::anyhow!("{}", e)))?;
|
||||||
let comment = json
|
let comment = json
|
||||||
.comment
|
.comment
|
||||||
.map(|c| domain::value_objects::Comment::new(c))
|
.map(|c| domain::value_objects::Comment::new(c))
|
||||||
.transpose()
|
.transpose()
|
||||||
.map_err(|e| Error(anyhow::anyhow!("{}", e)))?;
|
.map_err(|e| Error::bad_request(anyhow::anyhow!("{}", e)))?;
|
||||||
let watched_at = json.watched_at.naive_utc();
|
let watched_at = json.watched_at.naive_utc();
|
||||||
let created_at = json.published.naive_utc();
|
let created_at = json.published.naive_utc();
|
||||||
|
|
||||||
@@ -129,9 +141,9 @@ impl Object for DbReview {
|
|||||||
ReviewSource::Remote { actor_url },
|
ReviewSource::Remote { actor_url },
|
||||||
);
|
);
|
||||||
|
|
||||||
let ap_id = review_url(&data.base_url, review.id());
|
let ap_id_url = json.id.into_inner();
|
||||||
data.federation_repo.save_remote_review(&review).await?;
|
data.federation_repo.save_remote_review(&review, ap_id_url.as_str(), &json.movie_title, json.release_year, json.poster_url.as_deref()).await?;
|
||||||
|
|
||||||
Ok(DbReview { review, ap_id })
|
Ok(DbReview { review, ap_id: ap_id_url })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ use activitypub_federation::{axum::json::FederationJson, config::Data};
|
|||||||
use axum::extract::Path;
|
use axum::extract::Path;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use domain::value_objects::UserId;
|
use domain::{models::ReviewSource, value_objects::UserId};
|
||||||
|
|
||||||
use crate::data::FederationData;
|
use crate::data::FederationData;
|
||||||
use crate::error::Error;
|
use crate::error::Error;
|
||||||
@@ -24,15 +24,25 @@ pub async fn outbox_handler(
|
|||||||
data: Data<FederationData>,
|
data: Data<FederationData>,
|
||||||
) -> Result<FederationJson<OrderedCollection>, Error> {
|
) -> Result<FederationJson<OrderedCollection>, Error> {
|
||||||
let uuid = uuid::Uuid::parse_str(&user_id_str)
|
let uuid = uuid::Uuid::parse_str(&user_id_str)
|
||||||
.map_err(|_| Error(anyhow::anyhow!("invalid user id")))?;
|
.map_err(|_| Error::bad_request(anyhow::anyhow!("invalid user id")))?;
|
||||||
let user_id = UserId::from_uuid(uuid);
|
let user_id = UserId::from_uuid(uuid);
|
||||||
|
|
||||||
// verify user exists
|
|
||||||
data.user_repo
|
data.user_repo
|
||||||
.find_by_id(&user_id)
|
.find_by_id(&user_id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| Error(e.into()))?
|
.map_err(Error::from)?
|
||||||
.ok_or_else(|| Error(anyhow::anyhow!("user not found")))?;
|
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found")))?;
|
||||||
|
|
||||||
|
let history = data
|
||||||
|
.movie_repo
|
||||||
|
.get_user_history(&user_id)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)?;
|
||||||
|
|
||||||
|
let local_count = history
|
||||||
|
.iter()
|
||||||
|
.filter(|e| matches!(e.review().source(), ReviewSource::Local))
|
||||||
|
.count();
|
||||||
|
|
||||||
let outbox_url = format!("{}/users/{}/outbox", data.base_url, user_id_str);
|
let outbox_url = format!("{}/users/{}/outbox", data.base_url, user_id_str);
|
||||||
|
|
||||||
@@ -40,7 +50,7 @@ pub async fn outbox_handler(
|
|||||||
context: "https://www.w3.org/ns/activitystreams".to_string(),
|
context: "https://www.w3.org/ns/activitystreams".to_string(),
|
||||||
kind: "OrderedCollection".to_string(),
|
kind: "OrderedCollection".to_string(),
|
||||||
id: outbox_url,
|
id: outbox_url,
|
||||||
total_items: 0,
|
total_items: local_count as u64,
|
||||||
ordered_items: vec![],
|
ordered_items: vec![],
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
|
use chrono::NaiveDateTime;
|
||||||
use domain::models::Review;
|
use domain::models::Review;
|
||||||
use domain::value_objects::UserId;
|
use domain::value_objects::UserId;
|
||||||
|
|
||||||
@@ -10,6 +11,12 @@ pub enum FollowerStatus {
|
|||||||
Rejected,
|
Rejected,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum FollowingStatus {
|
||||||
|
Pending,
|
||||||
|
Accepted,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct RemoteActor {
|
pub struct RemoteActor {
|
||||||
pub url: String,
|
pub url: String,
|
||||||
@@ -31,13 +38,38 @@ pub trait FederationRepository: Send + Sync {
|
|||||||
async fn remove_follower(&self, local_user_id: UserId, remote_actor_url: &str) -> Result<()>;
|
async fn remove_follower(&self, local_user_id: UserId, remote_actor_url: &str) -> Result<()>;
|
||||||
async fn get_followers(&self, local_user_id: UserId) -> Result<Vec<Follower>>;
|
async fn get_followers(&self, local_user_id: UserId) -> Result<Vec<Follower>>;
|
||||||
async fn update_follower_status(&self, local_user_id: UserId, remote_actor_url: &str, status: FollowerStatus) -> Result<()>;
|
async fn update_follower_status(&self, local_user_id: UserId, remote_actor_url: &str, status: FollowerStatus) -> Result<()>;
|
||||||
async fn add_following(&self, local_user_id: UserId, actor: RemoteActor) -> Result<()>;
|
async fn add_following(&self, local_user_id: UserId, actor: RemoteActor, follow_activity_id: &str) -> Result<()>;
|
||||||
|
async fn get_follow_activity_id(&self, local_user_id: UserId, remote_actor_url: &str) -> Result<Option<String>>;
|
||||||
async fn remove_following(&self, local_user_id: UserId, actor_url: &str) -> Result<()>;
|
async fn remove_following(&self, local_user_id: UserId, actor_url: &str) -> Result<()>;
|
||||||
async fn get_following(&self, local_user_id: UserId) -> Result<Vec<RemoteActor>>;
|
async fn get_following(&self, local_user_id: UserId) -> Result<Vec<RemoteActor>>;
|
||||||
async fn count_following(&self, local_user_id: UserId) -> Result<usize>;
|
async fn count_following(&self, local_user_id: UserId) -> Result<usize>;
|
||||||
async fn upsert_remote_actor(&self, actor: RemoteActor) -> Result<()>;
|
async fn upsert_remote_actor(&self, actor: RemoteActor) -> Result<()>;
|
||||||
async fn get_remote_actor(&self, actor_url: &str) -> Result<Option<RemoteActor>>;
|
async fn get_remote_actor(&self, actor_url: &str) -> Result<Option<RemoteActor>>;
|
||||||
async fn save_remote_review(&self, review: &Review) -> Result<()>;
|
async fn save_remote_review(
|
||||||
|
&self,
|
||||||
|
review: &Review,
|
||||||
|
ap_id: &str,
|
||||||
|
movie_title: &str,
|
||||||
|
release_year: u16,
|
||||||
|
poster_url: Option<&str>,
|
||||||
|
) -> Result<()>;
|
||||||
|
async fn delete_remote_review_by_ap_id(&self, ap_id: &str, actor_url: &str) -> Result<()>;
|
||||||
|
async fn update_remote_review(
|
||||||
|
&self,
|
||||||
|
ap_id: &str,
|
||||||
|
actor_url: &str,
|
||||||
|
rating: u8,
|
||||||
|
comment: Option<&str>,
|
||||||
|
watched_at: NaiveDateTime,
|
||||||
|
) -> Result<()>;
|
||||||
async fn get_local_actor_keypair(&self, user_id: UserId) -> Result<Option<(String, String)>>;
|
async fn get_local_actor_keypair(&self, user_id: UserId) -> Result<Option<(String, String)>>;
|
||||||
async fn save_local_actor_keypair(&self, user_id: UserId, public_key: String, private_key: String) -> Result<()>;
|
async fn save_local_actor_keypair(&self, user_id: UserId, public_key: String, private_key: String) -> Result<()>;
|
||||||
|
async fn delete_remote_reviews_by_actor(&self, actor_url: &str) -> Result<()>;
|
||||||
|
async fn get_pending_followers(&self, local_user_id: UserId) -> Result<Vec<RemoteActor>>;
|
||||||
|
async fn update_following_status(
|
||||||
|
&self,
|
||||||
|
local_user_id: UserId,
|
||||||
|
remote_actor_url: &str,
|
||||||
|
status: FollowingStatus,
|
||||||
|
) -> Result<()>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ use domain::{ports::UserRepository, value_objects::UserId};
|
|||||||
use url::Url;
|
use url::Url;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
activities::{FollowActivity, UndoActivity},
|
activities::{AcceptActivity, CreateActivity, FollowActivity, RejectActivity, UndoActivity},
|
||||||
actor_handler::actor_handler,
|
actor_handler::actor_handler,
|
||||||
actors::{get_local_actor, DbActor},
|
actors::{get_local_actor, DbActor},
|
||||||
data::FederationData,
|
data::FederationData,
|
||||||
@@ -21,10 +21,37 @@ use crate::{
|
|||||||
followers_handler::{followers_handler, following_handler},
|
followers_handler::{followers_handler, following_handler},
|
||||||
inbox::inbox_handler,
|
inbox::inbox_handler,
|
||||||
outbox::outbox_handler,
|
outbox::outbox_handler,
|
||||||
repository::{FederationRepository, RemoteActor},
|
repository::{FederationRepository, FollowerStatus, RemoteActor},
|
||||||
webfinger::webfinger_handler,
|
webfinger::webfinger_handler,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
pub(crate) async fn send_with_retry(
|
||||||
|
sends: Vec<SendActivityTask>,
|
||||||
|
data: &Data<FederationData>,
|
||||||
|
) -> Vec<anyhow::Error> {
|
||||||
|
let mut failures = vec![];
|
||||||
|
for send in sends {
|
||||||
|
let mut delay = std::time::Duration::from_secs(1);
|
||||||
|
for attempt in 1..=3u32 {
|
||||||
|
match send.clone().sign_and_send(data).await {
|
||||||
|
Ok(()) => {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Err(e) if attempt < 3 => {
|
||||||
|
tracing::warn!(attempt, error = %e, "delivery failed, retrying");
|
||||||
|
tokio::time::sleep(delay).await;
|
||||||
|
delay *= 2;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!(attempt, error = %e, "delivery failed permanently");
|
||||||
|
failures.push(anyhow::anyhow!(e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
failures
|
||||||
|
}
|
||||||
|
|
||||||
pub struct ActivityPubService {
|
pub struct ActivityPubService {
|
||||||
federation_config: ApFederationConfig,
|
federation_config: ApFederationConfig,
|
||||||
base_url: String,
|
base_url: String,
|
||||||
@@ -34,10 +61,11 @@ impl ActivityPubService {
|
|||||||
pub async fn new(
|
pub async fn new(
|
||||||
repo: Arc<dyn FederationRepository>,
|
repo: Arc<dyn FederationRepository>,
|
||||||
user_repo: Arc<dyn UserRepository>,
|
user_repo: Arc<dyn UserRepository>,
|
||||||
|
movie_repo: Arc<dyn domain::ports::MovieRepository>,
|
||||||
base_url: String,
|
base_url: String,
|
||||||
debug: bool,
|
debug: bool,
|
||||||
) -> anyhow::Result<Self> {
|
) -> anyhow::Result<Self> {
|
||||||
let data = FederationData::new(repo, user_repo, base_url.clone());
|
let data = FederationData::new(repo, user_repo, movie_repo, base_url.clone());
|
||||||
let federation_config = ApFederationConfig::new(data, debug).await?;
|
let federation_config = ApFederationConfig::new(data, debug).await?;
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
federation_config,
|
federation_config,
|
||||||
@@ -53,6 +81,22 @@ impl ActivityPubService {
|
|||||||
self.federation_config.to_request_data()
|
self.federation_config.to_request_data()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Returns the AP actor document JSON for a local user.
|
||||||
|
// Used for content negotiation in the HTML profile handler.
|
||||||
|
pub async fn actor_json(&self, user_id_str: &str) -> anyhow::Result<String> {
|
||||||
|
use activitypub_federation::traits::Object;
|
||||||
|
use crate::actors::get_local_actor;
|
||||||
|
let uuid = uuid::Uuid::parse_str(user_id_str)?;
|
||||||
|
let user_id = UserId::from_uuid(uuid);
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
let actor = get_local_actor(user_id, &data).await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
let person = actor.into_json(&data).await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
let with_context = WithContext::new_default(person);
|
||||||
|
Ok(serde_json::to_string(&with_context)?)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn router(&self) -> Router {
|
pub fn router(&self) -> Router {
|
||||||
Router::new()
|
Router::new()
|
||||||
.route("/.well-known/webfinger", get(webfinger_handler))
|
.route("/.well-known/webfinger", get(webfinger_handler))
|
||||||
@@ -79,11 +123,8 @@ impl ActivityPubService {
|
|||||||
.await
|
.await
|
||||||
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
let follow_id = Url::parse(&format!(
|
let follow_id = crate::urls::activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
"{}/activities/{}",
|
let follow_id_str = follow_id.to_string();
|
||||||
self.base_url,
|
|
||||||
uuid::Uuid::new_v4()
|
|
||||||
))?;
|
|
||||||
let follow = FollowActivity {
|
let follow = FollowActivity {
|
||||||
id: follow_id,
|
id: follow_id,
|
||||||
kind: Default::default(),
|
kind: Default::default(),
|
||||||
@@ -99,24 +140,20 @@ impl ActivityPubService {
|
|||||||
&data,
|
&data,
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
for send in sends {
|
let failures = send_with_retry(sends, &data).await;
|
||||||
send.sign_and_send(&data).await?;
|
if !failures.is_empty() {
|
||||||
|
tracing::warn!(count = failures.len(), "some activity deliveries failed permanently");
|
||||||
}
|
}
|
||||||
|
|
||||||
let remote = RemoteActor {
|
let remote = RemoteActor {
|
||||||
url: remote_actor.ap_id.to_string(),
|
url: remote_actor.ap_id.to_string(),
|
||||||
handle: remote_actor
|
handle: remote_actor.username.clone(),
|
||||||
.email
|
|
||||||
.split('@')
|
|
||||||
.next()
|
|
||||||
.unwrap_or(&remote_actor.email)
|
|
||||||
.to_string(),
|
|
||||||
inbox_url: remote_actor.inbox_url.to_string(),
|
inbox_url: remote_actor.inbox_url.to_string(),
|
||||||
shared_inbox_url: None,
|
shared_inbox_url: None,
|
||||||
display_name: Some(remote_actor.email.clone()),
|
display_name: Some(remote_actor.username.clone()),
|
||||||
};
|
};
|
||||||
data.federation_repo
|
data.federation_repo
|
||||||
.add_following(local_user_id, remote)
|
.add_following(local_user_id, remote, &follow_id_str)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -138,11 +175,14 @@ impl ActivityPubService {
|
|||||||
let remote_ap_id = Url::parse(actor_url_str)?;
|
let remote_ap_id = Url::parse(actor_url_str)?;
|
||||||
let inbox = Url::parse(&remote.inbox_url)?;
|
let inbox = Url::parse(&remote.inbox_url)?;
|
||||||
|
|
||||||
let follow_id = Url::parse(&format!(
|
let follow_activity_id_str = data
|
||||||
"{}/activities/{}",
|
.federation_repo
|
||||||
self.base_url,
|
.get_follow_activity_id(local_user_id.clone(), actor_url_str)
|
||||||
uuid::Uuid::new_v4()
|
.await?;
|
||||||
))?;
|
let follow_id = match follow_activity_id_str {
|
||||||
|
Some(id) => Url::parse(&id)?,
|
||||||
|
None => crate::urls::activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?,
|
||||||
|
};
|
||||||
let follow = FollowActivity {
|
let follow = FollowActivity {
|
||||||
id: follow_id,
|
id: follow_id,
|
||||||
kind: Default::default(),
|
kind: Default::default(),
|
||||||
@@ -150,11 +190,7 @@ impl ActivityPubService {
|
|||||||
object: ObjectId::from(remote_ap_id),
|
object: ObjectId::from(remote_ap_id),
|
||||||
};
|
};
|
||||||
|
|
||||||
let undo_id = Url::parse(&format!(
|
let undo_id = crate::urls::activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
"{}/activities/{}",
|
|
||||||
self.base_url,
|
|
||||||
uuid::Uuid::new_v4()
|
|
||||||
))?;
|
|
||||||
let undo = UndoActivity {
|
let undo = UndoActivity {
|
||||||
id: undo_id,
|
id: undo_id,
|
||||||
kind: Default::default(),
|
kind: Default::default(),
|
||||||
@@ -165,14 +201,20 @@ impl ActivityPubService {
|
|||||||
|
|
||||||
let sends =
|
let sends =
|
||||||
SendActivityTask::prepare(&undo_with_ctx, &local_actor, vec![inbox], &data).await?;
|
SendActivityTask::prepare(&undo_with_ctx, &local_actor, vec![inbox], &data).await?;
|
||||||
for send in sends {
|
let failures = send_with_retry(sends, &data).await;
|
||||||
send.sign_and_send(&data).await?;
|
if !failures.is_empty() {
|
||||||
|
tracing::warn!(count = failures.len(), "some activity deliveries failed permanently");
|
||||||
}
|
}
|
||||||
|
|
||||||
data.federation_repo
|
data.federation_repo
|
||||||
.remove_following(local_user_id, actor_url_str)
|
.remove_following(local_user_id, actor_url_str)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
|
data.federation_repo
|
||||||
|
.delete_remote_reviews_by_actor(actor_url_str)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,4 +227,220 @@ impl ActivityPubService {
|
|||||||
let data = self.federation_config.to_request_data();
|
let data = self.federation_config.to_request_data();
|
||||||
data.federation_repo.count_following(local_user_id).await
|
data.federation_repo.count_following(local_user_id).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn accept_follower(
|
||||||
|
&self,
|
||||||
|
local_user_id: UserId,
|
||||||
|
remote_actor_url: &str,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
let local_actor = get_local_actor(local_user_id.clone(), &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
|
let remote_actor = data
|
||||||
|
.federation_repo
|
||||||
|
.get_remote_actor(remote_actor_url)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("remote actor not found"))?;
|
||||||
|
|
||||||
|
let follow_id = crate::urls::activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
let follow = FollowActivity {
|
||||||
|
id: follow_id,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(Url::parse(remote_actor_url)?),
|
||||||
|
object: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
};
|
||||||
|
let accept = AcceptActivity {
|
||||||
|
id: crate::urls::activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
object: follow,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Update status first so local state is correct even if delivery fails
|
||||||
|
data.federation_repo
|
||||||
|
.update_follower_status(local_user_id.clone(), remote_actor_url, FollowerStatus::Accepted)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let inbox = Url::parse(&remote_actor.inbox_url)?;
|
||||||
|
let sends = SendActivityTask::prepare(
|
||||||
|
&WithContext::new_default(accept),
|
||||||
|
&local_actor,
|
||||||
|
vec![inbox.clone()],
|
||||||
|
&data,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let failures = send_with_retry(sends, &data).await;
|
||||||
|
if !failures.is_empty() {
|
||||||
|
tracing::warn!("failed to deliver Accept activity, but follower is marked accepted locally");
|
||||||
|
}
|
||||||
|
|
||||||
|
self.spawn_backfill(local_user_id, remote_actor.inbox_url.clone());
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn reject_follower(
|
||||||
|
&self,
|
||||||
|
local_user_id: UserId,
|
||||||
|
remote_actor_url: &str,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
let local_actor = get_local_actor(local_user_id.clone(), &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
|
let remote_actor = data
|
||||||
|
.federation_repo
|
||||||
|
.get_remote_actor(remote_actor_url)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("remote actor not found"))?;
|
||||||
|
|
||||||
|
let follow_id = crate::urls::activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
let follow = FollowActivity {
|
||||||
|
id: follow_id,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(Url::parse(remote_actor_url)?),
|
||||||
|
object: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
};
|
||||||
|
let reject = RejectActivity {
|
||||||
|
id: crate::urls::activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
object: follow,
|
||||||
|
};
|
||||||
|
|
||||||
|
let inbox = Url::parse(&remote_actor.inbox_url)?;
|
||||||
|
let sends = SendActivityTask::prepare(
|
||||||
|
&WithContext::new_default(reject),
|
||||||
|
&local_actor,
|
||||||
|
vec![inbox],
|
||||||
|
&data,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let failures = send_with_retry(sends, &data).await;
|
||||||
|
if !failures.is_empty() {
|
||||||
|
tracing::warn!(count = failures.len(), "some activity deliveries failed permanently");
|
||||||
|
}
|
||||||
|
|
||||||
|
data.federation_repo
|
||||||
|
.remove_follower(local_user_id, remote_actor_url)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_pending_followers(
|
||||||
|
&self,
|
||||||
|
local_user_id: UserId,
|
||||||
|
) -> anyhow::Result<Vec<RemoteActor>> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
data.federation_repo
|
||||||
|
.get_pending_followers(local_user_id)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spawn_backfill(&self, owner_user_id: UserId, follower_inbox_url: String) {
|
||||||
|
let config = self.federation_config.clone();
|
||||||
|
let base_url = self.base_url.clone();
|
||||||
|
|
||||||
|
tokio::spawn(async move {
|
||||||
|
if let Err(e) = ActivityPubService::run_backfill(
|
||||||
|
config, base_url, owner_user_id, follower_inbox_url,
|
||||||
|
).await {
|
||||||
|
tracing::warn!(error = %e, "backfill: task failed");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run_backfill(
|
||||||
|
config: ApFederationConfig,
|
||||||
|
base_url: String,
|
||||||
|
owner_user_id: UserId,
|
||||||
|
follower_inbox_url: String,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
const BATCH_SIZE: usize = 20;
|
||||||
|
|
||||||
|
let data = config.to_request_data();
|
||||||
|
let local_actor = get_local_actor(owner_user_id.clone(), &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
let inbox = Url::parse(&follower_inbox_url)?;
|
||||||
|
|
||||||
|
let history = data.movie_repo.get_user_history(&owner_user_id).await?;
|
||||||
|
let local_reviews: Vec<_> = history
|
||||||
|
.into_iter()
|
||||||
|
.filter(|e| matches!(e.review().source(), domain::models::ReviewSource::Local))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let total = local_reviews.len();
|
||||||
|
|
||||||
|
let mut success_count = 0usize;
|
||||||
|
let mut failure_count = 0usize;
|
||||||
|
|
||||||
|
for chunk in local_reviews.chunks(BATCH_SIZE) {
|
||||||
|
for entry in chunk {
|
||||||
|
match ActivityPubService::deliver_review_to_inbox(
|
||||||
|
entry.review().clone(),
|
||||||
|
&local_actor,
|
||||||
|
inbox.clone(),
|
||||||
|
&data,
|
||||||
|
&base_url,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(_) => success_count += 1,
|
||||||
|
Err(_) => failure_count += 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
user_id = %owner_user_id.value(),
|
||||||
|
follower = %follower_inbox_url,
|
||||||
|
sent = success_count,
|
||||||
|
failed = failure_count,
|
||||||
|
total = total,
|
||||||
|
"backfill complete"
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn deliver_review_to_inbox(
|
||||||
|
review: domain::models::Review,
|
||||||
|
local_actor: &DbActor,
|
||||||
|
inbox: Url,
|
||||||
|
data: &Data<FederationData>,
|
||||||
|
base_url: &str,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
use activitypub_federation::traits::Object;
|
||||||
|
use crate::objects::DbReview;
|
||||||
|
|
||||||
|
let ap_id = crate::urls::review_url(base_url, review.id());
|
||||||
|
let db_review = DbReview { review, ap_id };
|
||||||
|
let object = db_review.into_json(data).await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
|
let activity_id = crate::urls::activity_url(base_url).map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
let create = CreateActivity {
|
||||||
|
id: activity_id,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
object,
|
||||||
|
};
|
||||||
|
|
||||||
|
let sends = SendActivityTask::prepare(
|
||||||
|
&WithContext::new_default(create),
|
||||||
|
local_actor,
|
||||||
|
vec![inbox],
|
||||||
|
data,
|
||||||
|
).await?;
|
||||||
|
let failures = send_with_retry(sends, data).await;
|
||||||
|
if let Some(e) = failures.into_iter().next() {
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
31
crates/adapters/activitypub/src/urls.rs
Normal file
31
crates/adapters/activitypub/src/urls.rs
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
use url::Url;
|
||||||
|
use uuid::Uuid;
|
||||||
|
use domain::value_objects::{UserId, ReviewId};
|
||||||
|
use crate::error::Error;
|
||||||
|
|
||||||
|
/// Extracts a UserId from a URL like `https://example.com/users/{uuid}[/...]`
|
||||||
|
pub fn extract_user_id_from_url(url: &Url) -> Option<UserId> {
|
||||||
|
let path = url.path();
|
||||||
|
path.strip_prefix("/users/")
|
||||||
|
.and_then(|s| s.split('/').next())
|
||||||
|
.and_then(|uid_str| Uuid::parse_str(uid_str).ok())
|
||||||
|
.map(UserId::from_uuid)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generates a fresh activity URL: `{base_url}/activities/{uuid}`
|
||||||
|
pub fn activity_url(base_url: &str) -> Result<Url, Error> {
|
||||||
|
Url::parse(&format!("{}/activities/{}", base_url, Uuid::new_v4()))
|
||||||
|
.map_err(|e| Error::bad_request(anyhow::anyhow!(e)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds the canonical actor URL: `{base_url}/users/{user_id}`
|
||||||
|
pub fn actor_url(base_url: &str, user_id: &UserId) -> Url {
|
||||||
|
Url::parse(&format!("{}/users/{}", base_url, user_id.value()))
|
||||||
|
.expect("base_url is always a valid URL prefix")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds the canonical review URL: `{base_url}/reviews/{review_id}`
|
||||||
|
pub fn review_url(base_url: &str, review_id: &ReviewId) -> Url {
|
||||||
|
Url::parse(&format!("{}/reviews/{}", base_url, review_id.value()))
|
||||||
|
.expect("base_url is always a valid URL prefix")
|
||||||
|
}
|
||||||
@@ -9,7 +9,8 @@ use axum::{
|
|||||||
};
|
};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
use crate::actors::actor_url;
|
use domain::value_objects::Username;
|
||||||
|
|
||||||
use crate::data::FederationData;
|
use crate::data::FederationData;
|
||||||
use crate::error::Error;
|
use crate::error::Error;
|
||||||
|
|
||||||
@@ -24,19 +25,16 @@ pub async fn webfinger_handler(
|
|||||||
) -> Result<Response, Error> {
|
) -> Result<Response, Error> {
|
||||||
let name = extract_webfinger_name(&query.resource, &data)?;
|
let name = extract_webfinger_name(&query.resource, &data)?;
|
||||||
|
|
||||||
// Look up user by email username@domain
|
let username = Username::new(name.to_string())
|
||||||
let email_str = format!("{}@{}", name, data.domain);
|
.map_err(|e| Error::bad_request(anyhow::anyhow!(e.to_string())))?;
|
||||||
let email = domain::value_objects::Email::new(email_str)
|
|
||||||
.map_err(|e| Error(anyhow::anyhow!("{}", e)))?;
|
|
||||||
|
|
||||||
let user = data
|
let user = data
|
||||||
.user_repo
|
.user_repo
|
||||||
.find_by_email(&email)
|
.find_by_username(&username)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| Error(e.into()))?
|
.map_err(Error::from)?
|
||||||
.ok_or_else(|| Error(anyhow::anyhow!("user not found")))?;
|
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found")))?;
|
||||||
|
|
||||||
let ap_id = actor_url(&data.base_url, user.id());
|
let ap_id = crate::urls::actor_url(&data.base_url, user.id());
|
||||||
|
|
||||||
let wf: Webfinger = build_webfinger_response(query.resource, ap_id);
|
let wf: Webfinger = build_webfinger_response(query.resource, ap_id);
|
||||||
let body = serde_json::to_string(&wf)
|
let body = serde_json::to_string(&wf)
|
||||||
|
|||||||
@@ -60,6 +60,22 @@ impl EventWorker {
|
|||||||
"event: review_logged"
|
"event: review_logged"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
DomainEvent::ReviewUpdated {
|
||||||
|
review_id,
|
||||||
|
movie_id,
|
||||||
|
user_id,
|
||||||
|
rating,
|
||||||
|
watched_at,
|
||||||
|
} => {
|
||||||
|
tracing::info!(
|
||||||
|
review_id = %review_id.value(),
|
||||||
|
movie_id = %movie_id.value(),
|
||||||
|
user_id = %user_id.value(),
|
||||||
|
rating = rating.value(),
|
||||||
|
watched_at = %watched_at,
|
||||||
|
"event: review_updated"
|
||||||
|
);
|
||||||
|
}
|
||||||
DomainEvent::MovieDiscovered {
|
DomainEvent::MovieDiscovered {
|
||||||
movie_id,
|
movie_id,
|
||||||
external_metadata_id,
|
external_metadata_id,
|
||||||
@@ -122,8 +138,9 @@ mod tests {
|
|||||||
impl EventHandler for RecordingHandler {
|
impl EventHandler for RecordingHandler {
|
||||||
async fn handle(&self, event: &DomainEvent) -> Result<(), DomainError> {
|
async fn handle(&self, event: &DomainEvent) -> Result<(), DomainError> {
|
||||||
let label = match event {
|
let label = match event {
|
||||||
DomainEvent::MovieDiscovered { .. } => "movie_discovered",
|
|
||||||
DomainEvent::ReviewLogged { .. } => "review_logged",
|
DomainEvent::ReviewLogged { .. } => "review_logged",
|
||||||
|
DomainEvent::ReviewUpdated { .. } => "review_updated",
|
||||||
|
DomainEvent::MovieDiscovered { .. } => "movie_discovered",
|
||||||
};
|
};
|
||||||
self.calls.lock().unwrap().push(label.to_string());
|
self.calls.lock().unwrap().push(label.to_string());
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -56,9 +56,9 @@ impl MetadataProvider for OmdbProvider {
|
|||||||
params.append_pair("i", id.value());
|
params.append_pair("i", id.value());
|
||||||
}
|
}
|
||||||
MetadataSearchCriteria::Title { title, year } => {
|
MetadataSearchCriteria::Title { title, year } => {
|
||||||
params.append_pair("t", title);
|
params.append_pair("t", title.value());
|
||||||
if let Some(y) = year {
|
if let Some(y) = year {
|
||||||
params.append_pair("y", &y.to_string());
|
params.append_pair("y", &y.value().to_string());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
33
crates/adapters/sqlite/migrations/0004_username.sql
Normal file
33
crates/adapters/sqlite/migrations/0004_username.sql
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
-- Recreate users table with username column
|
||||||
|
CREATE TABLE users_new (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
email TEXT NOT NULL UNIQUE,
|
||||||
|
username TEXT NOT NULL UNIQUE,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
created_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Derive username from email local part, sanitising common invalid chars.
|
||||||
|
-- REPLACE chains handle the most common email chars. The NOT NULL UNIQUE
|
||||||
|
-- constraint will surface any remaining collision (rare for personal instances).
|
||||||
|
INSERT INTO users_new (id, email, username, password_hash, created_at)
|
||||||
|
SELECT
|
||||||
|
id,
|
||||||
|
email,
|
||||||
|
CASE
|
||||||
|
WHEN LENGTH(REPLACE(REPLACE(REPLACE(REPLACE(
|
||||||
|
LOWER(SUBSTR(email, 1, INSTR(email, '@') - 1)),
|
||||||
|
'.', '_'), '+', '_'), '-', '-'), ' ', '_')) < 2
|
||||||
|
THEN REPLACE(REPLACE(REPLACE(REPLACE(
|
||||||
|
LOWER(SUBSTR(email, 1, INSTR(email, '@') - 1)),
|
||||||
|
'.', '_'), '+', '_'), '-', '-'), ' ', '_') || '_x'
|
||||||
|
ELSE REPLACE(REPLACE(REPLACE(REPLACE(
|
||||||
|
LOWER(SUBSTR(email, 1, INSTR(email, '@') - 1)),
|
||||||
|
'.', '_'), '+', '_'), '-', '-'), ' ', '_')
|
||||||
|
END,
|
||||||
|
password_hash,
|
||||||
|
created_at
|
||||||
|
FROM users;
|
||||||
|
|
||||||
|
DROP TABLE users;
|
||||||
|
ALTER TABLE users_new RENAME TO users;
|
||||||
11
crates/adapters/sqlite/migrations/0005_activitypub_v2.sql
Normal file
11
crates/adapters/sqlite/migrations/0005_activitypub_v2.sql
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
-- Store the original Follow activity URL so Undo/Reject can reference it correctly
|
||||||
|
ALTER TABLE ap_following ADD COLUMN follow_activity_id TEXT;
|
||||||
|
|
||||||
|
-- Track whether our outbound follow was accepted by the remote server
|
||||||
|
ALTER TABLE ap_following ADD COLUMN status TEXT NOT NULL DEFAULT 'pending';
|
||||||
|
|
||||||
|
-- Store the AP object URL on reviews so DeleteActivity can target by ID
|
||||||
|
ALTER TABLE reviews ADD COLUMN ap_id TEXT;
|
||||||
|
|
||||||
|
-- Partial unique index: ap_id is only set on remote reviews; local reviews have NULL
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_reviews_ap_id ON reviews (ap_id) WHERE ap_id IS NOT NULL;
|
||||||
@@ -3,7 +3,7 @@ use async_trait::async_trait;
|
|||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
use sqlx::{Row, SqlitePool};
|
use sqlx::{Row, SqlitePool};
|
||||||
|
|
||||||
use activitypub::repository::{FederationRepository, Follower, FollowerStatus, RemoteActor};
|
use activitypub::repository::{FederationRepository, Follower, FollowerStatus, FollowingStatus, RemoteActor};
|
||||||
use domain::models::{Review, ReviewSource};
|
use domain::models::{Review, ReviewSource};
|
||||||
use domain::value_objects::UserId;
|
use domain::value_objects::UserId;
|
||||||
|
|
||||||
@@ -146,7 +146,7 @@ impl FederationRepository for SqliteFederationRepository {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn add_following(&self, local_user_id: UserId, actor: RemoteActor) -> Result<()> {
|
async fn add_following(&self, local_user_id: UserId, actor: RemoteActor, follow_activity_id: &str) -> Result<()> {
|
||||||
let uid = local_user_id.value().to_string();
|
let uid = local_user_id.value().to_string();
|
||||||
let now = Utc::now().naive_utc();
|
let now = Utc::now().naive_utc();
|
||||||
let created_at = datetime_to_str(&now);
|
let created_at = datetime_to_str(&now);
|
||||||
@@ -154,11 +154,12 @@ impl FederationRepository for SqliteFederationRepository {
|
|||||||
self.upsert_remote_actor(actor.clone()).await?;
|
self.upsert_remote_actor(actor.clone()).await?;
|
||||||
|
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"INSERT OR IGNORE INTO ap_following (local_user_id, remote_actor_url, created_at)
|
"INSERT OR IGNORE INTO ap_following (local_user_id, remote_actor_url, follow_activity_id, created_at)
|
||||||
VALUES (?, ?, ?)",
|
VALUES (?, ?, ?, ?)",
|
||||||
)
|
)
|
||||||
.bind(&uid)
|
.bind(&uid)
|
||||||
.bind(&actor.url)
|
.bind(&actor.url)
|
||||||
|
.bind(follow_activity_id)
|
||||||
.bind(&created_at)
|
.bind(&created_at)
|
||||||
.execute(&self.pool)
|
.execute(&self.pool)
|
||||||
.await?;
|
.await?;
|
||||||
@@ -166,6 +167,18 @@ impl FederationRepository for SqliteFederationRepository {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn get_follow_activity_id(&self, local_user_id: UserId, remote_actor_url: &str) -> Result<Option<String>> {
|
||||||
|
let uid = local_user_id.value().to_string();
|
||||||
|
let row: Option<Option<String>> = sqlx::query_scalar(
|
||||||
|
"SELECT follow_activity_id FROM ap_following WHERE local_user_id = ? AND remote_actor_url = ?",
|
||||||
|
)
|
||||||
|
.bind(&uid)
|
||||||
|
.bind(remote_actor_url)
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await?;
|
||||||
|
Ok(row.flatten())
|
||||||
|
}
|
||||||
|
|
||||||
async fn remove_following(&self, local_user_id: UserId, actor_url: &str) -> Result<()> {
|
async fn remove_following(&self, local_user_id: UserId, actor_url: &str) -> Result<()> {
|
||||||
let uid = local_user_id.value().to_string();
|
let uid = local_user_id.value().to_string();
|
||||||
|
|
||||||
@@ -187,7 +200,7 @@ impl FederationRepository for SqliteFederationRepository {
|
|||||||
"SELECT a.url, a.handle, a.inbox_url, a.shared_inbox_url, a.display_name
|
"SELECT a.url, a.handle, a.inbox_url, a.shared_inbox_url, a.display_name
|
||||||
FROM ap_following f
|
FROM ap_following f
|
||||||
INNER JOIN ap_remote_actors a ON a.url = f.remote_actor_url
|
INNER JOIN ap_remote_actors a ON a.url = f.remote_actor_url
|
||||||
WHERE f.local_user_id = ?",
|
WHERE f.local_user_id = ? AND f.status = 'accepted'",
|
||||||
)
|
)
|
||||||
.bind(&uid)
|
.bind(&uid)
|
||||||
.fetch_all(&self.pool)
|
.fetch_all(&self.pool)
|
||||||
@@ -210,7 +223,7 @@ impl FederationRepository for SqliteFederationRepository {
|
|||||||
async fn count_following(&self, local_user_id: UserId) -> Result<usize> {
|
async fn count_following(&self, local_user_id: UserId) -> Result<usize> {
|
||||||
let uid = local_user_id.value().to_string();
|
let uid = local_user_id.value().to_string();
|
||||||
let count: i64 = sqlx::query_scalar(
|
let count: i64 = sqlx::query_scalar(
|
||||||
"SELECT COUNT(*) FROM ap_following WHERE local_user_id = ?",
|
"SELECT COUNT(*) FROM ap_following WHERE local_user_id = ? AND status = 'accepted'",
|
||||||
)
|
)
|
||||||
.bind(&uid)
|
.bind(&uid)
|
||||||
.fetch_one(&self.pool)
|
.fetch_one(&self.pool)
|
||||||
@@ -296,7 +309,7 @@ impl FederationRepository for SqliteFederationRepository {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn save_remote_review(&self, review: &Review) -> Result<()> {
|
async fn save_remote_review(&self, review: &Review, ap_id: &str, movie_title: &str, release_year: u16, poster_url: Option<&str>) -> Result<()> {
|
||||||
let actor_url = match review.source() {
|
let actor_url = match review.source() {
|
||||||
ReviewSource::Remote { actor_url } => actor_url.clone(),
|
ReviewSource::Remote { actor_url } => actor_url.clone(),
|
||||||
ReviewSource::Local => {
|
ReviewSource::Local => {
|
||||||
@@ -304,8 +317,25 @@ impl FederationRepository for SqliteFederationRepository {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let id = review.id().value().to_string();
|
|
||||||
let movie_id = review.movie_id().value().to_string();
|
let movie_id = review.movie_id().value().to_string();
|
||||||
|
|
||||||
|
// Stub movie so the feed INNER JOIN on movies always resolves.
|
||||||
|
// release_year 0 means unknown — clamp to 1888 (valid ReleaseYear range: 1888-2200).
|
||||||
|
// ON CONFLICT updates poster_path if a newer review carries one.
|
||||||
|
let _ = sqlx::query(
|
||||||
|
"INSERT INTO movies (id, external_metadata_id, title, release_year, director, poster_path)
|
||||||
|
VALUES (?, NULL, ?, ?, NULL, ?)
|
||||||
|
ON CONFLICT(id) DO UPDATE SET
|
||||||
|
poster_path = COALESCE(excluded.poster_path, movies.poster_path)",
|
||||||
|
)
|
||||||
|
.bind(&movie_id)
|
||||||
|
.bind(movie_title)
|
||||||
|
.bind(release_year.max(1888) as i64) // ReleaseYear requires >= 1888
|
||||||
|
.bind(poster_url)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let id = review.id().value().to_string();
|
||||||
let user_id = review.user_id().value().to_string();
|
let user_id = review.user_id().value().to_string();
|
||||||
let rating = review.rating().value() as i64;
|
let rating = review.rating().value() as i64;
|
||||||
let comment = review.comment().map(|c| c.value().to_string());
|
let comment = review.comment().map(|c| c.value().to_string());
|
||||||
@@ -313,8 +343,8 @@ impl FederationRepository for SqliteFederationRepository {
|
|||||||
let created_at = datetime_to_str(review.created_at());
|
let created_at = datetime_to_str(review.created_at());
|
||||||
|
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"INSERT OR IGNORE INTO reviews (id, movie_id, user_id, rating, comment, watched_at, created_at, remote_actor_url)
|
"INSERT OR IGNORE INTO reviews (id, movie_id, user_id, rating, comment, watched_at, created_at, remote_actor_url, ap_id)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||||
)
|
)
|
||||||
.bind(&id)
|
.bind(&id)
|
||||||
.bind(&movie_id)
|
.bind(&movie_id)
|
||||||
@@ -324,9 +354,105 @@ impl FederationRepository for SqliteFederationRepository {
|
|||||||
.bind(&watched_at)
|
.bind(&watched_at)
|
||||||
.bind(&created_at)
|
.bind(&created_at)
|
||||||
.bind(&actor_url)
|
.bind(&actor_url)
|
||||||
|
.bind(ap_id)
|
||||||
.execute(&self.pool)
|
.execute(&self.pool)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn delete_remote_review_by_ap_id(&self, ap_id: &str, actor_url: &str) -> Result<()> {
|
||||||
|
sqlx::query("DELETE FROM reviews WHERE ap_id = ? AND remote_actor_url = ?")
|
||||||
|
.bind(ap_id)
|
||||||
|
.bind(actor_url)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn update_remote_review(
|
||||||
|
&self,
|
||||||
|
ap_id: &str,
|
||||||
|
actor_url: &str,
|
||||||
|
rating: u8,
|
||||||
|
comment: Option<&str>,
|
||||||
|
watched_at: chrono::NaiveDateTime,
|
||||||
|
) -> Result<()> {
|
||||||
|
let watched_at_str = datetime_to_str(&watched_at);
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE reviews SET rating = ?, comment = ?, watched_at = ?
|
||||||
|
WHERE ap_id = ? AND remote_actor_url = ?",
|
||||||
|
)
|
||||||
|
.bind(rating as i64)
|
||||||
|
.bind(comment)
|
||||||
|
.bind(&watched_at_str)
|
||||||
|
.bind(ap_id)
|
||||||
|
.bind(actor_url)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn delete_remote_reviews_by_actor(&self, actor_url: &str) -> Result<()> {
|
||||||
|
sqlx::query("DELETE FROM reviews WHERE remote_actor_url = ?")
|
||||||
|
.bind(actor_url)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn update_following_status(
|
||||||
|
&self,
|
||||||
|
local_user_id: UserId,
|
||||||
|
remote_actor_url: &str,
|
||||||
|
status: FollowingStatus,
|
||||||
|
) -> Result<()> {
|
||||||
|
let uid = local_user_id.value().to_string();
|
||||||
|
let status_str = match status {
|
||||||
|
FollowingStatus::Pending => "pending",
|
||||||
|
FollowingStatus::Accepted => "accepted",
|
||||||
|
};
|
||||||
|
|
||||||
|
let result = sqlx::query(
|
||||||
|
"UPDATE ap_following SET status = ? WHERE local_user_id = ? AND remote_actor_url = ?",
|
||||||
|
)
|
||||||
|
.bind(status_str)
|
||||||
|
.bind(&uid)
|
||||||
|
.bind(remote_actor_url)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
if result.rows_affected() == 0 {
|
||||||
|
tracing::warn!(
|
||||||
|
local_user_id = %local_user_id.value(),
|
||||||
|
remote_actor_url = remote_actor_url,
|
||||||
|
"update_following_status: no row found"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_pending_followers(&self, local_user_id: UserId) -> Result<Vec<RemoteActor>> {
|
||||||
|
let uid = local_user_id.value().to_string();
|
||||||
|
|
||||||
|
let rows = sqlx::query(
|
||||||
|
"SELECT f.remote_actor_url,
|
||||||
|
a.handle, a.inbox_url, a.shared_inbox_url, a.display_name
|
||||||
|
FROM ap_followers f
|
||||||
|
LEFT JOIN ap_remote_actors a ON a.url = f.remote_actor_url
|
||||||
|
WHERE f.local_user_id = ? AND f.status = 'pending'",
|
||||||
|
)
|
||||||
|
.bind(&uid)
|
||||||
|
.fetch_all(&self.pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(rows.into_iter().map(|row| RemoteActor {
|
||||||
|
url: row.get("remote_actor_url"),
|
||||||
|
handle: row.try_get("handle").unwrap_or_default(),
|
||||||
|
inbox_url: row.try_get("inbox_url").unwrap_or_default(),
|
||||||
|
shared_inbox_url: row.try_get("shared_inbox_url").ok().flatten(),
|
||||||
|
display_name: row.try_get("display_name").ok().flatten(),
|
||||||
|
}).collect())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -224,14 +224,14 @@ impl SqliteMovieRepository {
|
|||||||
) -> Result<Vec<FeedRow>, DomainError> {
|
) -> Result<Vec<FeedRow>, DomainError> {
|
||||||
sqlx::query_as!(
|
sqlx::query_as!(
|
||||||
FeedRow,
|
FeedRow,
|
||||||
"SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,
|
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,
|
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,
|
||||||
u.email AS user_email
|
COALESCE(u.email, r.remote_actor_url) AS "user_email!: String"
|
||||||
FROM reviews r
|
FROM reviews r
|
||||||
INNER JOIN movies m ON m.id = r.movie_id
|
INNER JOIN movies m ON m.id = r.movie_id
|
||||||
INNER JOIN users u ON u.id = r.user_id
|
LEFT JOIN users u ON u.id = r.user_id
|
||||||
ORDER BY r.watched_at DESC
|
ORDER BY r.watched_at DESC
|
||||||
LIMIT ? OFFSET ?",
|
LIMIT ? OFFSET ?"#,
|
||||||
limit, offset
|
limit, offset
|
||||||
)
|
)
|
||||||
.fetch_all(&self.pool)
|
.fetch_all(&self.pool)
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ use domain::{
|
|||||||
errors::DomainError,
|
errors::DomainError,
|
||||||
models::{DiaryEntry, FeedEntry, Movie, Review, ReviewSource, UserSummary},
|
models::{DiaryEntry, FeedEntry, Movie, Review, ReviewSource, UserSummary},
|
||||||
value_objects::{
|
value_objects::{
|
||||||
Comment, ExternalMetadataId, MovieId, MovieTitle, PosterPath, Rating, ReleaseYear,
|
Comment, Email, ExternalMetadataId, MovieId, MovieTitle, PosterPath, Rating, ReleaseYear,
|
||||||
ReviewId, UserId,
|
ReviewId, UserId,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -171,12 +171,12 @@ pub(crate) struct UserSummaryRow {
|
|||||||
|
|
||||||
impl UserSummaryRow {
|
impl UserSummaryRow {
|
||||||
pub fn to_domain(self) -> Result<UserSummary, DomainError> {
|
pub fn to_domain(self) -> Result<UserSummary, DomainError> {
|
||||||
Ok(UserSummary {
|
Ok(UserSummary::new(
|
||||||
user_id: UserId::from_uuid(parse_uuid(&self.id)?),
|
UserId::from_uuid(parse_uuid(&self.id)?),
|
||||||
email: self.email,
|
Email::new(self.email)?,
|
||||||
total_movies: self.total_movies,
|
self.total_movies,
|
||||||
avg_rating: self.avg_rating,
|
self.avg_rating,
|
||||||
})
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ use domain::{
|
|||||||
errors::DomainError,
|
errors::DomainError,
|
||||||
models::User,
|
models::User,
|
||||||
ports::UserRepository,
|
ports::UserRepository,
|
||||||
value_objects::{Email, PasswordHash, UserId},
|
value_objects::{Email, PasswordHash, UserId, Username},
|
||||||
};
|
};
|
||||||
use super::models::UserSummaryRow;
|
use super::models::UserSummaryRow;
|
||||||
|
|
||||||
@@ -15,14 +15,29 @@ pub struct SqliteUserRepository {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl SqliteUserRepository {
|
impl SqliteUserRepository {
|
||||||
pub fn new(pool: SqlitePool) -> Self {
|
pub fn new(pool: SqlitePool) -> Self { Self { pool } }
|
||||||
Self { pool }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn map_err(e: sqlx::Error) -> DomainError {
|
fn map_err(e: sqlx::Error) -> DomainError {
|
||||||
tracing::error!("Database error: {:?}", e);
|
tracing::error!("Database error: {:?}", e);
|
||||||
DomainError::InfrastructureError("Database operation failed".into())
|
DomainError::InfrastructureError("Database operation failed".into())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn row_to_user(
|
||||||
|
id_str: String,
|
||||||
|
email_str: String,
|
||||||
|
username_str: String,
|
||||||
|
hash_str: String,
|
||||||
|
) -> Result<User, DomainError> {
|
||||||
|
let id = uuid::Uuid::parse_str(&id_str)
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
|
||||||
|
let email = Email::new(email_str)
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
|
||||||
|
let username = Username::new(username_str)
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
|
||||||
|
let hash = PasswordHash::new(hash_str)
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
|
||||||
|
Ok(User::from_persistence(UserId::from_uuid(id), email, username, hash))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
@@ -30,84 +45,81 @@ impl UserRepository for SqliteUserRepository {
|
|||||||
async fn find_by_email(&self, email: &Email) -> Result<Option<User>, DomainError> {
|
async fn find_by_email(&self, email: &Email) -> Result<Option<User>, DomainError> {
|
||||||
let email_str = email.value();
|
let email_str = email.value();
|
||||||
let row = sqlx::query!(
|
let row = sqlx::query!(
|
||||||
"SELECT id, email, password_hash FROM users WHERE email = ?",
|
"SELECT id, email, username, password_hash FROM users WHERE email = ?",
|
||||||
email_str
|
email_str
|
||||||
)
|
)
|
||||||
.fetch_optional(&self.pool)
|
.fetch_optional(&self.pool)
|
||||||
.await
|
.await
|
||||||
.map_err(Self::map_err)?;
|
.map_err(Self::map_err)?;
|
||||||
|
|
||||||
match row {
|
row.map(|r| Self::row_to_user(r.id.unwrap_or_default(), r.email, r.username, r.password_hash))
|
||||||
None => Ok(None),
|
.transpose()
|
||||||
Some(r) => {
|
}
|
||||||
let id = uuid::Uuid::parse_str(&r.id)
|
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
|
async fn find_by_username(&self, username: &Username) -> Result<Option<User>, DomainError> {
|
||||||
let email = Email::new(r.email)
|
let username_str = username.value();
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
|
let row = sqlx::query!(
|
||||||
let hash = PasswordHash::new(r.password_hash)
|
"SELECT id, email, username, password_hash FROM users WHERE username = ?",
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
|
username_str
|
||||||
Ok(Some(User::from_persistence(UserId::from_uuid(id), email, hash)))
|
)
|
||||||
}
|
.fetch_optional(&self.pool)
|
||||||
}
|
.await
|
||||||
|
.map_err(Self::map_err)?;
|
||||||
|
|
||||||
|
row.map(|r| Self::row_to_user(r.id.unwrap_or_default(), r.email, r.username, r.password_hash))
|
||||||
|
.transpose()
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn save(&self, user: &User) -> Result<(), DomainError> {
|
async fn save(&self, user: &User) -> Result<(), DomainError> {
|
||||||
|
// Check email uniqueness first (clearer error than INSERT OR IGNORE)
|
||||||
|
if self.find_by_email(user.email()).await?.is_some() {
|
||||||
|
return Err(DomainError::ValidationError("Email already registered".into()));
|
||||||
|
}
|
||||||
|
// Check username uniqueness
|
||||||
|
if self.find_by_username(user.username()).await?.is_some() {
|
||||||
|
return Err(DomainError::ValidationError("Username already taken".into()));
|
||||||
|
}
|
||||||
|
|
||||||
let id = user.id().value().to_string();
|
let id = user.id().value().to_string();
|
||||||
let email = user.email().value();
|
let email = user.email().value();
|
||||||
|
let username = user.username().value();
|
||||||
let hash = user.password_hash().value();
|
let hash = user.password_hash().value();
|
||||||
let created_at = Utc::now().to_rfc3339();
|
let created_at = Utc::now().to_rfc3339();
|
||||||
|
|
||||||
let result = sqlx::query!(
|
sqlx::query!(
|
||||||
"INSERT OR IGNORE INTO users (id, email, password_hash, created_at) VALUES (?, ?, ?, ?)",
|
"INSERT INTO users (id, email, username, password_hash, created_at) VALUES (?, ?, ?, ?, ?)",
|
||||||
id,
|
id, email, username, hash, created_at
|
||||||
email,
|
|
||||||
hash,
|
|
||||||
created_at
|
|
||||||
)
|
)
|
||||||
.execute(&self.pool)
|
.execute(&self.pool)
|
||||||
.await
|
.await
|
||||||
.map_err(Self::map_err)?;
|
.map_err(Self::map_err)?;
|
||||||
|
|
||||||
if result.rows_affected() == 0 {
|
|
||||||
return Err(DomainError::ValidationError("Email already registered".into()));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn find_by_id(&self, id: &UserId) -> Result<Option<User>, DomainError> {
|
async fn find_by_id(&self, id: &UserId) -> Result<Option<User>, DomainError> {
|
||||||
let id_str = id.value().to_string();
|
let id_str = id.value().to_string();
|
||||||
let row = sqlx::query!(
|
let row = sqlx::query!(
|
||||||
"SELECT id, email, password_hash FROM users WHERE id = ?",
|
"SELECT id, email, username, password_hash FROM users WHERE id = ?",
|
||||||
id_str
|
id_str
|
||||||
)
|
)
|
||||||
.fetch_optional(&self.pool)
|
.fetch_optional(&self.pool)
|
||||||
.await
|
.await
|
||||||
.map_err(Self::map_err)?;
|
.map_err(Self::map_err)?;
|
||||||
|
|
||||||
match row {
|
row.map(|r| Self::row_to_user(r.id.unwrap_or_default(), r.email, r.username, r.password_hash))
|
||||||
None => Ok(None),
|
.transpose()
|
||||||
Some(r) => {
|
|
||||||
let uuid = uuid::Uuid::parse_str(&r.id)
|
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
|
|
||||||
let email = Email::new(r.email)
|
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
|
|
||||||
let hash = PasswordHash::new(r.password_hash)
|
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
|
|
||||||
Ok(Some(User::from_persistence(UserId::from_uuid(uuid), email, hash)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn list_with_stats(&self) -> Result<Vec<domain::models::UserSummary>, DomainError> {
|
async fn list_with_stats(&self) -> Result<Vec<domain::models::UserSummary>, DomainError> {
|
||||||
sqlx::query_as!(
|
sqlx::query_as!(
|
||||||
UserSummaryRow,
|
UserSummaryRow,
|
||||||
r#"SELECT u.id,
|
r#"SELECT u.id AS "id!: String",
|
||||||
u.email,
|
u.email AS "email!: String",
|
||||||
COUNT(DISTINCT r.movie_id) AS "total_movies!: i64",
|
COUNT(DISTINCT r.movie_id) AS "total_movies!: i64",
|
||||||
AVG(CAST(r.rating AS REAL)) AS avg_rating
|
AVG(CAST(r.rating AS REAL)) AS avg_rating
|
||||||
FROM users u
|
FROM users u
|
||||||
LEFT JOIN reviews r ON r.user_id = u.id
|
LEFT JOIN reviews r ON r.user_id = u.id AND r.remote_actor_url IS NULL
|
||||||
GROUP BY u.id, u.email
|
GROUP BY u.id, u.email
|
||||||
ORDER BY u.email ASC"#
|
ORDER BY u.email ASC"#
|
||||||
)
|
)
|
||||||
@@ -128,7 +140,7 @@ mod tests {
|
|||||||
async fn setup() -> (SqlitePool, SqliteUserRepository) {
|
async fn setup() -> (SqlitePool, SqliteUserRepository) {
|
||||||
let pool = SqlitePool::connect(":memory:").await.unwrap();
|
let pool = SqlitePool::connect(":memory:").await.unwrap();
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"CREATE TABLE users (id TEXT PRIMARY KEY, email TEXT NOT NULL UNIQUE, password_hash TEXT NOT NULL, created_at TEXT NOT NULL)"
|
"CREATE TABLE users (id TEXT PRIMARY KEY, email TEXT NOT NULL UNIQUE, username TEXT NOT NULL UNIQUE, password_hash TEXT NOT NULL, created_at TEXT NOT NULL)"
|
||||||
)
|
)
|
||||||
.execute(&pool)
|
.execute(&pool)
|
||||||
.await
|
.await
|
||||||
@@ -152,10 +164,11 @@ mod tests {
|
|||||||
let (pool, repo) = setup().await;
|
let (pool, repo) = setup().await;
|
||||||
let id = uuid::Uuid::new_v4();
|
let id = uuid::Uuid::new_v4();
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"INSERT INTO users (id, email, password_hash, created_at) VALUES (?, ?, ?, ?)"
|
"INSERT INTO users (id, email, username, password_hash, created_at) VALUES (?, ?, ?, ?, ?)"
|
||||||
)
|
)
|
||||||
.bind(id.to_string())
|
.bind(id.to_string())
|
||||||
.bind("test@example.com")
|
.bind("test@example.com")
|
||||||
|
.bind("test")
|
||||||
.bind("$argon2id$v=19$m=65536,t=2,p=1$fakesalt$fakehash")
|
.bind("$argon2id$v=19$m=65536,t=2,p=1$fakesalt$fakehash")
|
||||||
.bind("2026-01-01T00:00:00Z")
|
.bind("2026-01-01T00:00:00Z")
|
||||||
.execute(&pool)
|
.execute(&pool)
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use application::ports::{
|
|||||||
NewReviewPageData, ProfilePageData, RegisterPageData, UsersPageData,
|
NewReviewPageData, ProfilePageData, RegisterPageData, UsersPageData,
|
||||||
};
|
};
|
||||||
use domain::models::{
|
use domain::models::{
|
||||||
DiaryEntry, FeedEntry, MonthActivity, MonthlyRating, ReviewSource, UserStats, UserSummary,
|
DiaryEntry, FeedEntry, MonthActivity, MonthlyRating, ReviewSource, UserStats,
|
||||||
UserTrends, collections::Paginated,
|
UserTrends, collections::Paginated,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -81,10 +81,18 @@ struct ActivityFeedTemplate<'a> {
|
|||||||
page_items: Vec<PageItem>,
|
page_items: Vec<PageItem>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct UserSummaryView {
|
||||||
|
user_id: uuid::Uuid,
|
||||||
|
display_name: String,
|
||||||
|
initial: char,
|
||||||
|
avg_rating_display: String,
|
||||||
|
total_movies: i64,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Template)]
|
#[derive(Template)]
|
||||||
#[template(path = "users.html")]
|
#[template(path = "users.html")]
|
||||||
struct UsersTemplate<'a> {
|
struct UsersTemplate<'a> {
|
||||||
users: &'a [UserSummary],
|
users: Vec<UserSummaryView>,
|
||||||
ctx: &'a HtmlPageContext,
|
ctx: &'a HtmlPageContext,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,6 +108,9 @@ struct ProfileTemplate<'a> {
|
|||||||
profile_display_name: String,
|
profile_display_name: String,
|
||||||
profile_user_id: uuid::Uuid,
|
profile_user_id: uuid::Uuid,
|
||||||
stats: &'a UserStats,
|
stats: &'a UserStats,
|
||||||
|
avg_rating_display: String,
|
||||||
|
favorite_director_display: String,
|
||||||
|
most_active_month_display: String,
|
||||||
view: &'a str,
|
view: &'a str,
|
||||||
entries: Option<&'a Paginated<DiaryEntry>>,
|
entries: Option<&'a Paginated<DiaryEntry>>,
|
||||||
current_offset: u32,
|
current_offset: u32,
|
||||||
@@ -113,6 +124,7 @@ struct ProfileTemplate<'a> {
|
|||||||
is_own_profile: bool,
|
is_own_profile: bool,
|
||||||
error: Option<String>,
|
error: Option<String>,
|
||||||
following_count: usize,
|
following_count: usize,
|
||||||
|
pending_followers: Vec<RemoteActorData>,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct RemoteActorData {
|
struct RemoteActorData {
|
||||||
@@ -255,8 +267,23 @@ impl HtmlRenderer for AskamaHtmlRenderer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn render_users_page(&self, data: UsersPageData) -> Result<String, String> {
|
fn render_users_page(&self, data: UsersPageData) -> Result<String, String> {
|
||||||
|
let users: Vec<UserSummaryView> = data.users.iter().map(|u| {
|
||||||
|
let email = u.email();
|
||||||
|
let display_name = email.split('@').next().unwrap_or(email).to_string();
|
||||||
|
let initial = display_name.chars().next().unwrap_or('?').to_ascii_uppercase();
|
||||||
|
let avg_rating_display = u.avg_rating
|
||||||
|
.map(|r| format!("{:.1}", r))
|
||||||
|
.unwrap_or_else(|| "—".to_string());
|
||||||
|
UserSummaryView {
|
||||||
|
user_id: u.user_id.value(),
|
||||||
|
display_name,
|
||||||
|
initial,
|
||||||
|
avg_rating_display,
|
||||||
|
total_movies: u.total_movies,
|
||||||
|
}
|
||||||
|
}).collect();
|
||||||
UsersTemplate {
|
UsersTemplate {
|
||||||
users: &data.users,
|
users,
|
||||||
ctx: &data.ctx,
|
ctx: &data.ctx,
|
||||||
}
|
}
|
||||||
.render()
|
.render()
|
||||||
@@ -279,11 +306,25 @@ impl HtmlRenderer for AskamaHtmlRenderer {
|
|||||||
.map(|e| if e.limit > 0 { ((e.total_count + e.limit as u64 - 1) / e.limit as u64) as u32 } else { 0 })
|
.map(|e| if e.limit > 0 { ((e.total_count + e.limit as u64 - 1) / e.limit as u64) as u32 } else { 0 })
|
||||||
.unwrap_or(0);
|
.unwrap_or(0);
|
||||||
let current_page = if data.limit > 0 { data.current_offset / data.limit } else { 0 };
|
let current_page = if data.limit > 0 { data.current_offset / data.limit } else { 0 };
|
||||||
|
let avg_rating_display = data.stats.avg_rating
|
||||||
|
.map(|r| format!("{:.1}", r))
|
||||||
|
.unwrap_or_else(|| "—".to_string());
|
||||||
|
let favorite_director_display = data.stats.favorite_director
|
||||||
|
.as_deref()
|
||||||
|
.unwrap_or("—")
|
||||||
|
.to_string();
|
||||||
|
let most_active_month_display = data.stats.most_active_month
|
||||||
|
.as_deref()
|
||||||
|
.unwrap_or("—")
|
||||||
|
.to_string();
|
||||||
ProfileTemplate {
|
ProfileTemplate {
|
||||||
ctx: &data.ctx,
|
ctx: &data.ctx,
|
||||||
profile_display_name,
|
profile_display_name,
|
||||||
profile_user_id: data.profile_user_id,
|
profile_user_id: data.profile_user_id,
|
||||||
stats: &data.stats,
|
stats: &data.stats,
|
||||||
|
avg_rating_display,
|
||||||
|
favorite_director_display,
|
||||||
|
most_active_month_display,
|
||||||
view: &data.view,
|
view: &data.view,
|
||||||
entries: data.entries.as_ref(),
|
entries: data.entries.as_ref(),
|
||||||
current_offset: data.current_offset,
|
current_offset: data.current_offset,
|
||||||
@@ -297,6 +338,11 @@ impl HtmlRenderer for AskamaHtmlRenderer {
|
|||||||
is_own_profile: data.is_own_profile,
|
is_own_profile: data.is_own_profile,
|
||||||
error: data.error,
|
error: data.error,
|
||||||
following_count: data.following_count,
|
following_count: data.following_count,
|
||||||
|
pending_followers: data.pending_followers.into_iter().map(|a| RemoteActorData {
|
||||||
|
handle: a.handle,
|
||||||
|
url: a.url,
|
||||||
|
display_name: a.display_name,
|
||||||
|
}).collect(),
|
||||||
}
|
}
|
||||||
.render()
|
.render()
|
||||||
.map_err(|e| e.to_string())
|
.map_err(|e| e.to_string())
|
||||||
|
|||||||
@@ -25,12 +25,14 @@
|
|||||||
<div class="comment">{{ comment.value() }}</div>
|
<div class="comment">{{ comment.value() }}</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
<div class="feed-meta">
|
<div class="feed-meta">
|
||||||
<a href="/users/{{ entry.review().user_id().value() }}" class="feed-user">{{ entry.user_display_name() }}</a>
|
|
||||||
<span class="feed-time">{{ entry.review().watched_at().format("%b %-d, %Y") }}</span>
|
|
||||||
{% match entry.review().source() %}
|
{% match entry.review().source() %}
|
||||||
{% when ReviewSource::Remote with { actor_url } %}
|
{% when ReviewSource::Remote with { actor_url } %}
|
||||||
<span class="remote-badge" title="{{ actor_url }}">↗ federated</span>
|
<a href="{{ actor_url }}" class="feed-user" target="_blank" rel="noopener noreferrer">{{ entry.user_display_name() }}</a>
|
||||||
|
<span class="feed-time">{{ entry.review().watched_at().format("%b %-d, %Y") }}</span>
|
||||||
|
<span class="remote-badge">↗ federated</span>
|
||||||
{% when ReviewSource::Local %}
|
{% when ReviewSource::Local %}
|
||||||
|
<a href="/users/{{ entry.review().user_id().value() }}" class="feed-user">{{ entry.user_display_name() }}</a>
|
||||||
|
<span class="feed-time">{{ entry.review().watched_at().format("%b %-d, %Y") }}</span>
|
||||||
{% endmatch %}
|
{% endmatch %}
|
||||||
</div>
|
</div>
|
||||||
{% if ctx.is_current_user(entry.review().user_id().value()) %}
|
{% if ctx.is_current_user(entry.review().user_id().value()) %}
|
||||||
|
|||||||
@@ -10,15 +10,15 @@
|
|||||||
<div class="stat-label">movies</div>
|
<div class="stat-label">movies</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="stat-tile">
|
<div class="stat-tile">
|
||||||
<div class="stat-value">{{ stats.avg_rating_display() }}★</div>
|
<div class="stat-value">{{ avg_rating_display }}★</div>
|
||||||
<div class="stat-label">avg rating</div>
|
<div class="stat-label">avg rating</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="stat-tile">
|
<div class="stat-tile">
|
||||||
<div class="stat-value">{{ stats.favorite_director_display() }}</div>
|
<div class="stat-value">{{ favorite_director_display }}</div>
|
||||||
<div class="stat-label">fav director</div>
|
<div class="stat-label">fav director</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="stat-tile">
|
<div class="stat-tile">
|
||||||
<div class="stat-value">{{ stats.most_active_month_display() }}</div>
|
<div class="stat-value">{{ most_active_month_display }}</div>
|
||||||
<div class="stat-label">most active</div>
|
<div class="stat-label">most active</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -36,6 +36,27 @@
|
|||||||
{% endif %}
|
{% endif %}
|
||||||
</section>
|
</section>
|
||||||
<a href="/users/{{ profile_user_id }}/following-list">View following ({{ following_count }})</a>
|
<a href="/users/{{ profile_user_id }}/following-list">View following ({{ following_count }})</a>
|
||||||
|
{% if !pending_followers.is_empty() %}
|
||||||
|
<section class="pending-followers">
|
||||||
|
<h3>Pending follow requests ({{ pending_followers.len() }})</h3>
|
||||||
|
<ul class="pending-list">
|
||||||
|
{% for actor in pending_followers %}
|
||||||
|
<li class="pending-item">
|
||||||
|
<span class="pending-handle"><strong>{{ actor.handle }}</strong></span>
|
||||||
|
<a href="{{ actor.url }}" class="pending-url" target="_blank" rel="noopener noreferrer">{{ actor.url }}</a>
|
||||||
|
<form method="POST" action="/users/{{ profile_user_id }}/followers/accept" class="inline-form">
|
||||||
|
<input type="hidden" name="actor_url" value="{{ actor.url }}">
|
||||||
|
<button type="submit" class="btn-accept">Accept</button>
|
||||||
|
</form>
|
||||||
|
<form method="POST" action="/users/{{ profile_user_id }}/followers/reject" class="inline-form">
|
||||||
|
<input type="hidden" name="actor_url" value="{{ actor.url }}">
|
||||||
|
<button type="submit" class="btn-reject">Reject</button>
|
||||||
|
</form>
|
||||||
|
</li>
|
||||||
|
{% endfor %}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
{% endif %}
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
<div class="view-tabs">
|
<div class="view-tabs">
|
||||||
|
|||||||
@@ -5,6 +5,12 @@
|
|||||||
<p class="error">{{ err }}</p>
|
<p class="error">{{ err }}</p>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
<form method="POST" action="/register">
|
<form method="POST" action="/register">
|
||||||
|
<label>
|
||||||
|
Username<br>
|
||||||
|
<small>2–30 chars: letters, digits, underscores, hyphens. This becomes your ActivityPub handle.</small><br>
|
||||||
|
<input type="text" name="username" required autocomplete="username"
|
||||||
|
pattern="[a-z0-9_\-]{2,30}" title="2–30 lowercase letters, digits, underscores or hyphens">
|
||||||
|
</label>
|
||||||
<label>
|
<label>
|
||||||
Email<br>
|
Email<br>
|
||||||
<input type="email" name="email" required autocomplete="email">
|
<input type="email" name="email" required autocomplete="email">
|
||||||
|
|||||||
@@ -4,12 +4,12 @@
|
|||||||
<h2 class="page-title">Members</h2>
|
<h2 class="page-title">Members</h2>
|
||||||
{% for user in users %}
|
{% for user in users %}
|
||||||
<div class="user-row">
|
<div class="user-row">
|
||||||
<div class="user-avatar">{{ user.initial() }}</div>
|
<div class="user-avatar">{{ user.initial }}</div>
|
||||||
<div class="user-info">
|
<div class="user-info">
|
||||||
<div class="user-name">{{ user.display_name() }}</div>
|
<div class="user-name">{{ user.display_name }}</div>
|
||||||
<div class="user-meta">{{ user.total_movies }} movies · avg {{ user.avg_rating_display() }}★</div>
|
<div class="user-meta">{{ user.total_movies }} movies · avg {{ user.avg_rating_display }}★</div>
|
||||||
</div>
|
</div>
|
||||||
<a href="/users/{{ user.user_id.value() }}" class="btn-secondary">View profile →</a>
|
<a href="/users/{{ user.user_id }}" class="btn-secondary">View profile →</a>
|
||||||
</div>
|
</div>
|
||||||
{% else %}
|
{% else %}
|
||||||
<p class="empty">No users yet.</p>
|
<p class="empty">No users yet.</p>
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ pub struct LoginCommand {
|
|||||||
|
|
||||||
pub struct RegisterCommand {
|
pub struct RegisterCommand {
|
||||||
pub email: String,
|
pub email: String,
|
||||||
|
pub username: String,
|
||||||
pub password: String,
|
pub password: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -108,8 +108,8 @@ impl ResolutionStrategy for TitleSearchStrategy {
|
|||||||
) -> Result<Option<(Movie, bool)>, DomainError> {
|
) -> Result<Option<(Movie, bool)>, DomainError> {
|
||||||
let title = cmd.manual_title.as_deref().unwrap();
|
let title = cmd.manual_title.as_deref().unwrap();
|
||||||
let criteria = MetadataSearchCriteria::Title {
|
let criteria = MetadataSearchCriteria::Title {
|
||||||
title: title.to_string(),
|
title: MovieTitle::new(title.to_string())?,
|
||||||
year: cmd.manual_release_year,
|
year: cmd.manual_release_year.map(ReleaseYear::new).transpose()?,
|
||||||
};
|
};
|
||||||
match deps.metadata_client.fetch_movie_metadata(&criteria).await {
|
match deps.metadata_client.fetch_movie_metadata(&criteria).await {
|
||||||
Ok(m) => Ok(Some((m, true))),
|
Ok(m) => Ok(Some((m, true))),
|
||||||
|
|||||||
@@ -66,6 +66,7 @@ pub struct ProfilePageData {
|
|||||||
pub is_own_profile: bool,
|
pub is_own_profile: bool,
|
||||||
pub error: Option<String>,
|
pub error: Option<String>,
|
||||||
pub following_count: usize,
|
pub following_count: usize,
|
||||||
|
pub pending_followers: Vec<RemoteActorView>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct FollowingPageData {
|
pub struct FollowingPageData {
|
||||||
|
|||||||
@@ -20,9 +20,42 @@ pub struct GetActivityFeedQuery {
|
|||||||
|
|
||||||
pub struct GetUsersQuery;
|
pub struct GetUsersQuery;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, Default)]
|
||||||
|
pub enum ProfileView {
|
||||||
|
History,
|
||||||
|
Trends,
|
||||||
|
Ratings,
|
||||||
|
#[default]
|
||||||
|
Recent,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProfileView {
|
||||||
|
pub fn as_str(&self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::History => "history",
|
||||||
|
Self::Trends => "trends",
|
||||||
|
Self::Ratings => "ratings",
|
||||||
|
Self::Recent => "recent",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::str::FromStr for ProfileView {
|
||||||
|
type Err = String;
|
||||||
|
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||||
|
match s {
|
||||||
|
"history" => Ok(Self::History),
|
||||||
|
"trends" => Ok(Self::Trends),
|
||||||
|
"ratings" => Ok(Self::Ratings),
|
||||||
|
"recent" => Ok(Self::Recent),
|
||||||
|
other => Err(format!("unknown profile view: {other}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub struct GetUserProfileQuery {
|
pub struct GetUserProfileQuery {
|
||||||
pub user_id: Uuid,
|
pub user_id: Uuid,
|
||||||
pub view: String,
|
pub view: ProfileView,
|
||||||
pub limit: Option<u32>,
|
pub limit: Option<u32>,
|
||||||
pub offset: Option<u32>,
|
pub offset: Option<u32>,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
use chrono::Datelike;
|
||||||
use domain::{
|
use domain::{
|
||||||
errors::DomainError,
|
errors::DomainError,
|
||||||
models::{
|
models::{
|
||||||
@@ -6,7 +7,7 @@ use domain::{
|
|||||||
},
|
},
|
||||||
value_objects::UserId,
|
value_objects::UserId,
|
||||||
};
|
};
|
||||||
use crate::{context::AppContext, queries::GetUserProfileQuery};
|
use crate::{context::AppContext, queries::{GetUserProfileQuery, ProfileView}};
|
||||||
|
|
||||||
pub struct UserProfileData {
|
pub struct UserProfileData {
|
||||||
pub stats: UserStats,
|
pub stats: UserStats,
|
||||||
@@ -22,62 +23,62 @@ pub async fn execute(
|
|||||||
let user_id = UserId::from_uuid(query.user_id);
|
let user_id = UserId::from_uuid(query.user_id);
|
||||||
let stats = ctx.repository.get_user_stats(&user_id).await?;
|
let stats = ctx.repository.get_user_stats(&user_id).await?;
|
||||||
|
|
||||||
match query.view.as_str() {
|
match query.view {
|
||||||
"history" => {
|
ProfileView::History => {
|
||||||
// V1: loads all entries into memory. Personal diaries are bounded in size;
|
// V1: loads all entries into memory. Personal diaries are bounded in size;
|
||||||
// spec calls for showing every movie grouped by month, so full load is intentional.
|
// spec calls for showing every movie grouped by month, so full load is intentional.
|
||||||
let all_entries = ctx.repository.get_user_history(&user_id).await?;
|
let all_entries = ctx.repository.get_user_history(&user_id).await?;
|
||||||
let history = group_by_month(all_entries);
|
let history = group_by_month(all_entries);
|
||||||
Ok(UserProfileData { stats, entries: None, history: Some(history), trends: None })
|
Ok(UserProfileData { stats, entries: None, history: Some(history), trends: None })
|
||||||
}
|
}
|
||||||
"trends" => {
|
ProfileView::Trends => {
|
||||||
let trends = ctx.repository.get_user_trends(&user_id).await?;
|
let trends = ctx.repository.get_user_trends(&user_id).await?;
|
||||||
Ok(UserProfileData { stats, entries: None, history: None, trends: Some(trends) })
|
Ok(UserProfileData { stats, entries: None, history: None, trends: Some(trends) })
|
||||||
}
|
}
|
||||||
"ratings" => {
|
ProfileView::Ratings => {
|
||||||
let page = PageParams::new(query.limit, query.offset)?;
|
let filter = paged_user_filter(user_id, SortDirection::ByRatingDesc, query.limit, query.offset)?;
|
||||||
let filter = DiaryFilter {
|
|
||||||
sort_by: SortDirection::ByRatingDesc,
|
|
||||||
page,
|
|
||||||
movie_id: None,
|
|
||||||
user_id: Some(user_id),
|
|
||||||
};
|
|
||||||
let entries = ctx.repository.query_diary(&filter).await?;
|
let entries = ctx.repository.query_diary(&filter).await?;
|
||||||
Ok(UserProfileData { stats, entries: Some(entries), history: None, trends: None })
|
Ok(UserProfileData { stats, entries: Some(entries), history: None, trends: None })
|
||||||
}
|
}
|
||||||
"recent" => {
|
ProfileView::Recent => {
|
||||||
let page = PageParams::new(query.limit, query.offset)?;
|
let filter = paged_user_filter(user_id, SortDirection::Descending, query.limit, query.offset)?;
|
||||||
let filter = DiaryFilter {
|
|
||||||
sort_by: SortDirection::Descending,
|
|
||||||
page,
|
|
||||||
movie_id: None,
|
|
||||||
user_id: Some(user_id),
|
|
||||||
};
|
|
||||||
let entries = ctx.repository.query_diary(&filter).await?;
|
let entries = ctx.repository.query_diary(&filter).await?;
|
||||||
Ok(UserProfileData { stats, entries: Some(entries), history: None, trends: None })
|
Ok(UserProfileData { stats, entries: Some(entries), history: None, trends: None })
|
||||||
}
|
}
|
||||||
other => Err(DomainError::ValidationError(format!("unknown view: {}", other))),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn paged_user_filter(user_id: UserId, sort_by: SortDirection, limit: Option<u32>, offset: Option<u32>) -> Result<DiaryFilter, DomainError> {
|
||||||
|
let page = PageParams::new(limit, offset)?;
|
||||||
|
Ok(DiaryFilter {
|
||||||
|
sort_by,
|
||||||
|
page,
|
||||||
|
movie_id: None,
|
||||||
|
user_id: Some(user_id),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
fn group_by_month(entries: Vec<DiaryEntry>) -> Vec<MonthActivity> {
|
fn group_by_month(entries: Vec<DiaryEntry>) -> Vec<MonthActivity> {
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
let mut map: BTreeMap<String, Vec<DiaryEntry>> = BTreeMap::new();
|
let mut map: BTreeMap<(i32, u32), Vec<DiaryEntry>> = BTreeMap::new();
|
||||||
for entry in entries {
|
for entry in entries {
|
||||||
let ym = entry.review().watched_at().format("%Y-%m").to_string();
|
let watched_at = entry.review().watched_at();
|
||||||
map.entry(ym).or_default().push(entry);
|
let year = watched_at.year();
|
||||||
|
let month = watched_at.month();
|
||||||
|
map.entry((year, month)).or_default().push(entry);
|
||||||
}
|
}
|
||||||
let mut result: Vec<MonthActivity> = map
|
map.into_iter()
|
||||||
.into_iter()
|
.rev()
|
||||||
.map(|(ym, entries)| MonthActivity {
|
.map(|((year, month), entries)| {
|
||||||
month_label: format_year_month_long(&ym),
|
let year_month = format!("{:04}-{:02}", year, month);
|
||||||
count: entries.len() as i64,
|
MonthActivity {
|
||||||
entries,
|
month_label: format_year_month_long(&year_month),
|
||||||
year_month: ym,
|
count: entries.len() as i64,
|
||||||
|
entries,
|
||||||
|
year_month,
|
||||||
|
}
|
||||||
})
|
})
|
||||||
.collect();
|
.collect()
|
||||||
result.reverse();
|
|
||||||
result
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn format_year_month_long(ym: &str) -> String {
|
fn format_year_month_long(ym: &str) -> String {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use domain::{errors::DomainError, models::User, value_objects::Email};
|
use domain::{errors::DomainError, models::User, value_objects::{Email, Username}};
|
||||||
|
|
||||||
use crate::{commands::RegisterCommand, context::AppContext};
|
use crate::{commands::RegisterCommand, context::AppContext};
|
||||||
|
|
||||||
@@ -16,13 +16,16 @@ pub async fn execute(ctx: &AppContext, cmd: RegisterCommand) -> Result<(), Domai
|
|||||||
}
|
}
|
||||||
|
|
||||||
let email = Email::new(cmd.email)?;
|
let email = Email::new(cmd.email)?;
|
||||||
|
let username = Username::new(cmd.username)?;
|
||||||
|
|
||||||
if ctx.user_repository.find_by_email(&email).await?.is_some() {
|
if ctx.user_repository.find_by_email(&email).await?.is_some() {
|
||||||
return Err(DomainError::ValidationError(
|
return Err(DomainError::ValidationError("Email already registered".into()));
|
||||||
"Email already registered".into(),
|
}
|
||||||
));
|
|
||||||
|
if ctx.user_repository.find_by_username(&username).await?.is_some() {
|
||||||
|
return Err(DomainError::ValidationError("Username already taken".into()));
|
||||||
}
|
}
|
||||||
|
|
||||||
let hash = ctx.password_hasher.hash(&cmd.password).await?;
|
let hash = ctx.password_hasher.hash(&cmd.password).await?;
|
||||||
ctx.user_repository.save(&User::new(email, hash)).await
|
ctx.user_repository.save(&User::new(email, username, hash)).await
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,13 @@ pub enum DomainEvent {
|
|||||||
rating: Rating,
|
rating: Rating,
|
||||||
watched_at: NaiveDateTime,
|
watched_at: NaiveDateTime,
|
||||||
},
|
},
|
||||||
|
ReviewUpdated {
|
||||||
|
review_id: ReviewId,
|
||||||
|
movie_id: MovieId,
|
||||||
|
user_id: UserId,
|
||||||
|
rating: Rating,
|
||||||
|
watched_at: NaiveDateTime,
|
||||||
|
},
|
||||||
MovieDiscovered {
|
MovieDiscovered {
|
||||||
movie_id: MovieId,
|
movie_id: MovieId,
|
||||||
external_metadata_id: ExternalMetadataId,
|
external_metadata_id: ExternalMetadataId,
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use crate::{
|
|||||||
models::collections::PageParams,
|
models::collections::PageParams,
|
||||||
value_objects::{
|
value_objects::{
|
||||||
Comment, Email, ExternalMetadataId, MovieId, MovieTitle, PasswordHash, PosterPath, Rating,
|
Comment, Email, ExternalMetadataId, MovieId, MovieTitle, PasswordHash, PosterPath, Rating,
|
||||||
ReleaseYear, ReviewId, UserId,
|
ReleaseYear, ReviewId, UserId, Username,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
pub mod collections;
|
pub mod collections;
|
||||||
@@ -247,8 +247,8 @@ impl ReviewHistory {
|
|||||||
pub fn viewings(&self) -> &[Review] {
|
pub fn viewings(&self) -> &[Review] {
|
||||||
&self.viewings
|
&self.viewings
|
||||||
}
|
}
|
||||||
pub fn viewings_mut(&mut self) -> &mut Vec<Review> {
|
pub fn sort_by_date(&mut self) {
|
||||||
&mut self.viewings
|
self.viewings.sort_by_key(|r| *r.watched_at());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -256,37 +256,32 @@ impl ReviewHistory {
|
|||||||
pub struct User {
|
pub struct User {
|
||||||
id: UserId,
|
id: UserId,
|
||||||
email: Email,
|
email: Email,
|
||||||
|
username: Username,
|
||||||
password_hash: PasswordHash,
|
password_hash: PasswordHash,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl User {
|
impl User {
|
||||||
pub fn new(email: Email, password_hash: PasswordHash) -> Self {
|
pub fn new(email: Email, username: Username, password_hash: PasswordHash) -> Self {
|
||||||
Self {
|
Self { id: UserId::generate(), email, username, password_hash }
|
||||||
id: UserId::generate(),
|
|
||||||
email,
|
|
||||||
password_hash,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn from_persistence(id: UserId, email: Email, password_hash: PasswordHash) -> Self {
|
pub fn from_persistence(
|
||||||
Self { id, email, password_hash }
|
id: UserId,
|
||||||
|
email: Email,
|
||||||
|
username: Username,
|
||||||
|
password_hash: PasswordHash,
|
||||||
|
) -> Self {
|
||||||
|
Self { id, email, username, password_hash }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn update_password(&mut self, new_hash: PasswordHash) {
|
pub fn update_password(&mut self, new_hash: PasswordHash) {
|
||||||
self.password_hash = new_hash;
|
self.password_hash = new_hash;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn email(&self) -> &Email {
|
pub fn email(&self) -> &Email { &self.email }
|
||||||
&self.email
|
pub fn username(&self) -> &Username { &self.username }
|
||||||
}
|
pub fn id(&self) -> &UserId { &self.id }
|
||||||
|
pub fn password_hash(&self) -> &PasswordHash { &self.password_hash }
|
||||||
pub fn id(&self) -> &UserId {
|
|
||||||
&self.id
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn password_hash(&self) -> &PasswordHash {
|
|
||||||
&self.password_hash
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
@@ -310,21 +305,16 @@ impl FeedEntry {
|
|||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct UserSummary {
|
pub struct UserSummary {
|
||||||
pub user_id: UserId,
|
pub user_id: UserId,
|
||||||
pub email: String,
|
email: Email,
|
||||||
pub total_movies: i64,
|
pub total_movies: i64,
|
||||||
pub avg_rating: Option<f64>,
|
pub avg_rating: Option<f64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl UserSummary {
|
impl UserSummary {
|
||||||
pub fn display_name(&self) -> &str {
|
pub fn new(user_id: UserId, email: Email, total_movies: i64, avg_rating: Option<f64>) -> Self {
|
||||||
self.email.split('@').next().unwrap_or(&self.email)
|
Self { user_id, email, total_movies, avg_rating }
|
||||||
}
|
|
||||||
pub fn avg_rating_display(&self) -> String {
|
|
||||||
self.avg_rating.map(|r| format!("{:.1}", r)).unwrap_or_else(|| "—".to_string())
|
|
||||||
}
|
|
||||||
pub fn initial(&self) -> char {
|
|
||||||
self.display_name().chars().next().unwrap_or('?').to_ascii_uppercase()
|
|
||||||
}
|
}
|
||||||
|
pub fn email(&self) -> &str { self.email.value() }
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
@@ -335,17 +325,6 @@ pub struct UserStats {
|
|||||||
pub most_active_month: Option<String>,
|
pub most_active_month: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl UserStats {
|
|
||||||
pub fn avg_rating_display(&self) -> String {
|
|
||||||
self.avg_rating.map(|r| format!("{:.1}", r)).unwrap_or_else(|| "—".to_string())
|
|
||||||
}
|
|
||||||
pub fn favorite_director_display(&self) -> &str {
|
|
||||||
self.favorite_director.as_deref().unwrap_or("—")
|
|
||||||
}
|
|
||||||
pub fn most_active_month_display(&self) -> &str {
|
|
||||||
self.most_active_month.as_deref().unwrap_or("—")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct MonthActivity {
|
pub struct MonthActivity {
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ use crate::{
|
|||||||
},
|
},
|
||||||
value_objects::{
|
value_objects::{
|
||||||
Email, ExternalMetadataId, MovieId, MovieTitle, PasswordHash, PosterPath, PosterUrl,
|
Email, ExternalMetadataId, MovieId, MovieTitle, PasswordHash, PosterPath, PosterUrl,
|
||||||
ReleaseYear, ReviewId, UserId,
|
ReleaseYear, ReviewId, UserId, Username,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -57,7 +57,7 @@ pub trait MovieRepository: Send + Sync {
|
|||||||
|
|
||||||
pub enum MetadataSearchCriteria {
|
pub enum MetadataSearchCriteria {
|
||||||
ImdbId(ExternalMetadataId),
|
ImdbId(ExternalMetadataId),
|
||||||
Title { title: String, year: Option<u16> },
|
Title { title: MovieTitle, year: Option<ReleaseYear> },
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
@@ -102,9 +102,9 @@ pub trait AuthService: Send + Sync {
|
|||||||
#[async_trait]
|
#[async_trait]
|
||||||
pub trait UserRepository: Send + Sync {
|
pub trait UserRepository: Send + Sync {
|
||||||
async fn find_by_email(&self, email: &Email) -> Result<Option<User>, DomainError>;
|
async fn find_by_email(&self, email: &Email) -> Result<Option<User>, DomainError>;
|
||||||
|
async fn find_by_username(&self, username: &Username) -> Result<Option<User>, DomainError>;
|
||||||
async fn save(&self, user: &User) -> Result<(), DomainError>;
|
async fn save(&self, user: &User) -> Result<(), DomainError>;
|
||||||
async fn find_by_id(&self, id: &UserId) -> Result<Option<User>, DomainError>;
|
async fn find_by_id(&self, id: &UserId) -> Result<Option<User>, DomainError>;
|
||||||
|
|
||||||
async fn list_with_stats(&self) -> Result<Vec<UserSummary>, DomainError>;
|
async fn list_with_stats(&self) -> Result<Vec<UserSummary>, DomainError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,9 +11,7 @@ pub enum Trend {
|
|||||||
|
|
||||||
impl ReviewHistoryAnalyzer {
|
impl ReviewHistoryAnalyzer {
|
||||||
pub fn sort_chronologically(history: &mut ReviewHistory) {
|
pub fn sort_chronologically(history: &mut ReviewHistory) {
|
||||||
history
|
history.sort_by_date();
|
||||||
.viewings_mut()
|
|
||||||
.sort_by(|a, b| a.watched_at().cmp(&b.watched_at()));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_latest_rating(history: &ReviewHistory) -> Option<&Rating> {
|
pub fn get_latest_rating(history: &ReviewHistory) -> Option<&Rating> {
|
||||||
@@ -29,18 +27,20 @@ impl ReviewHistoryAnalyzer {
|
|||||||
return Ok(Trend::Neutral);
|
return Ok(Trend::Neutral);
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut sorted_history = history.clone();
|
let latest_review = history
|
||||||
Self::sort_chronologically(&mut sorted_history);
|
|
||||||
|
|
||||||
let latest_review = sorted_history.viewings().last().unwrap();
|
|
||||||
let latest_rating = latest_review.rating().value() as f32;
|
|
||||||
|
|
||||||
let previous_sum: u32 = sorted_history
|
|
||||||
.viewings()
|
.viewings()
|
||||||
.iter()
|
.iter()
|
||||||
.map(|r| r.rating().value() as u32)
|
.max_by_key(|r| r.watched_at())
|
||||||
|
.unwrap();
|
||||||
|
let latest_rating = latest_review.rating().value() as f32;
|
||||||
|
|
||||||
|
let count = history.viewings().len() as f32;
|
||||||
|
let total: f32 = history
|
||||||
|
.viewings()
|
||||||
|
.iter()
|
||||||
|
.map(|r| r.rating().value() as f32)
|
||||||
.sum();
|
.sum();
|
||||||
let historical_average = previous_sum as f32 / sorted_history.viewings().len() as f32;
|
let historical_average = total / count;
|
||||||
|
|
||||||
if latest_rating > historical_average {
|
if latest_rating > historical_average {
|
||||||
Ok(Trend::Improved)
|
Ok(Trend::Improved)
|
||||||
|
|||||||
@@ -1,50 +1,28 @@
|
|||||||
use crate::errors::DomainError;
|
use crate::errors::DomainError;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
macro_rules! uuid_id {
|
||||||
pub struct MovieId(Uuid);
|
($name:ident) => {
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct $name(Uuid);
|
||||||
|
|
||||||
impl MovieId {
|
impl $name {
|
||||||
pub fn generate() -> Self {
|
pub fn generate() -> Self {
|
||||||
Self(Uuid::new_v4())
|
Self(Uuid::new_v4())
|
||||||
}
|
}
|
||||||
pub fn from_uuid(uuid: Uuid) -> Self {
|
pub fn from_uuid(uuid: Uuid) -> Self {
|
||||||
Self(uuid)
|
Self(uuid)
|
||||||
}
|
}
|
||||||
pub fn value(&self) -> Uuid {
|
pub fn value(&self) -> Uuid {
|
||||||
self.0
|
self.0
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
uuid_id!(MovieId);
|
||||||
pub struct ReviewId(Uuid);
|
uuid_id!(ReviewId);
|
||||||
|
uuid_id!(UserId);
|
||||||
impl ReviewId {
|
|
||||||
pub fn generate() -> Self {
|
|
||||||
Self(Uuid::new_v4())
|
|
||||||
}
|
|
||||||
pub fn from_uuid(uuid: Uuid) -> Self {
|
|
||||||
Self(uuid)
|
|
||||||
}
|
|
||||||
pub fn value(&self) -> Uuid {
|
|
||||||
self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub struct UserId(Uuid);
|
|
||||||
|
|
||||||
impl UserId {
|
|
||||||
pub fn generate() -> Self {
|
|
||||||
Self(Uuid::new_v4())
|
|
||||||
}
|
|
||||||
pub fn from_uuid(uuid: Uuid) -> Self {
|
|
||||||
Self(uuid)
|
|
||||||
}
|
|
||||||
pub fn value(&self) -> Uuid {
|
|
||||||
self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub struct ExternalMetadataId(String);
|
pub struct ExternalMetadataId(String);
|
||||||
@@ -90,15 +68,17 @@ impl PosterPath {
|
|||||||
pub struct MovieTitle(String);
|
pub struct MovieTitle(String);
|
||||||
|
|
||||||
impl MovieTitle {
|
impl MovieTitle {
|
||||||
|
const MAX_LENGTH: usize = 255;
|
||||||
|
|
||||||
pub fn new(title: String) -> Result<Self, DomainError> {
|
pub fn new(title: String) -> Result<Self, DomainError> {
|
||||||
let trimmed = title.trim();
|
let trimmed = title.trim();
|
||||||
if trimmed.is_empty() {
|
if trimmed.is_empty() {
|
||||||
Err(DomainError::ValidationError(
|
Err(DomainError::ValidationError(
|
||||||
"Movie title cannot be empty".into(),
|
"Movie title cannot be empty".into(),
|
||||||
))
|
))
|
||||||
} else if trimmed.len() > 255 {
|
} else if trimmed.len() > Self::MAX_LENGTH {
|
||||||
Err(DomainError::ValidationError(
|
Err(DomainError::ValidationError(
|
||||||
"Movie title exceeds 255 characters".into(),
|
format!("Movie title exceeds {} characters", Self::MAX_LENGTH).into(),
|
||||||
))
|
))
|
||||||
} else {
|
} else {
|
||||||
Ok(Self(trimmed.to_string()))
|
Ok(Self(trimmed.to_string()))
|
||||||
@@ -114,11 +94,13 @@ impl MovieTitle {
|
|||||||
pub struct Comment(String);
|
pub struct Comment(String);
|
||||||
|
|
||||||
impl Comment {
|
impl Comment {
|
||||||
|
const MAX_LENGTH: usize = 10_000;
|
||||||
|
|
||||||
pub fn new(comment: String) -> Result<Self, DomainError> {
|
pub fn new(comment: String) -> Result<Self, DomainError> {
|
||||||
let trimmed = comment.trim();
|
let trimmed = comment.trim();
|
||||||
if trimmed.len() > 10_000 {
|
if trimmed.len() > Self::MAX_LENGTH {
|
||||||
Err(DomainError::ValidationError(
|
Err(DomainError::ValidationError(
|
||||||
"Comment exceeds 10,000 characters".into(),
|
format!("Comment exceeds {} characters", Self::MAX_LENGTH).into(),
|
||||||
))
|
))
|
||||||
} else {
|
} else {
|
||||||
Ok(Self(trimmed.to_string()))
|
Ok(Self(trimmed.to_string()))
|
||||||
@@ -189,6 +171,35 @@ impl Email {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct Username(String);
|
||||||
|
|
||||||
|
impl Username {
|
||||||
|
const MIN_LENGTH: usize = 2;
|
||||||
|
const MAX_LENGTH: usize = 30;
|
||||||
|
|
||||||
|
/// Accepts 2–30 chars: lowercase letters, digits, underscores, hyphens.
|
||||||
|
/// Lowercases input automatically.
|
||||||
|
pub fn new(raw: String) -> Result<Self, DomainError> {
|
||||||
|
let s = raw.trim().to_lowercase();
|
||||||
|
if s.len() < Self::MIN_LENGTH || s.len() > Self::MAX_LENGTH {
|
||||||
|
return Err(DomainError::ValidationError(
|
||||||
|
format!("Username must be {}–{} characters", Self::MIN_LENGTH, Self::MAX_LENGTH).into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if !s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') {
|
||||||
|
return Err(DomainError::ValidationError(
|
||||||
|
"Username may only contain letters, digits, underscores, and hyphens".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(Self(s))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn value(&self) -> &str {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub struct PasswordHash(String);
|
pub struct PasswordHash(String);
|
||||||
|
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ pub struct LoginForm {
|
|||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
pub struct RegisterForm {
|
pub struct RegisterForm {
|
||||||
pub email: String,
|
pub email: String,
|
||||||
|
pub username: String,
|
||||||
pub password: String,
|
pub password: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -131,6 +132,7 @@ pub struct LoginResponse {
|
|||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
pub struct RegisterRequest {
|
pub struct RegisterRequest {
|
||||||
pub email: String,
|
pub email: String,
|
||||||
|
pub username: String,
|
||||||
pub password: String,
|
pub password: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -244,6 +246,11 @@ pub struct UnfollowForm {
|
|||||||
pub actor_url: String,
|
pub actor_url: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct FollowerActionForm {
|
||||||
|
pub actor_url: String,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(serde::Deserialize, Default)]
|
#[derive(serde::Deserialize, Default)]
|
||||||
pub struct ProfileQueryParams {
|
pub struct ProfileQueryParams {
|
||||||
pub view: Option<String>,
|
pub view: Option<String>,
|
||||||
|
|||||||
@@ -142,6 +142,7 @@ mod tests {
|
|||||||
async fn find_by_email(&self, _: &Email) -> Result<Option<User>, DomainError> { panic!("unexpected") }
|
async fn find_by_email(&self, _: &Email) -> Result<Option<User>, DomainError> { panic!("unexpected") }
|
||||||
async fn save(&self, _: &User) -> Result<(), DomainError> { panic!("unexpected") }
|
async fn save(&self, _: &User) -> Result<(), DomainError> { panic!("unexpected") }
|
||||||
async fn find_by_id(&self, _: &domain::value_objects::UserId) -> Result<Option<User>, DomainError> { panic!("unexpected") }
|
async fn find_by_id(&self, _: &domain::value_objects::UserId) -> Result<Option<User>, DomainError> { panic!("unexpected") }
|
||||||
|
async fn find_by_username(&self, _: &domain::value_objects::Username) -> Result<Option<User>, DomainError> { panic!("unexpected") }
|
||||||
async fn list_with_stats(&self) -> Result<Vec<domain::models::UserSummary>, DomainError> { panic!("unexpected") }
|
async fn list_with_stats(&self) -> Result<Vec<domain::models::UserSummary>, DomainError> { panic!("unexpected") }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -164,7 +164,7 @@ mod tests {
|
|||||||
#[async_trait::async_trait] impl domain::ports::EventPublisher for PanicEvent { async fn publish(&self, _: &domain::events::DomainEvent) -> Result<(), domain::errors::DomainError> { panic!() } }
|
#[async_trait::async_trait] impl domain::ports::EventPublisher for PanicEvent { async fn publish(&self, _: &domain::events::DomainEvent) -> Result<(), domain::errors::DomainError> { panic!() } }
|
||||||
#[async_trait::async_trait] impl domain::ports::PasswordHasher for PanicHasher { async fn hash(&self, _: &str) -> Result<domain::value_objects::PasswordHash, domain::errors::DomainError> { panic!() } async fn verify(&self, _: &str, _: &domain::value_objects::PasswordHash) -> Result<bool, domain::errors::DomainError> { panic!() } }
|
#[async_trait::async_trait] impl domain::ports::PasswordHasher for PanicHasher { async fn hash(&self, _: &str) -> Result<domain::value_objects::PasswordHash, domain::errors::DomainError> { panic!() } async fn verify(&self, _: &str, _: &domain::value_objects::PasswordHash) -> Result<bool, domain::errors::DomainError> { panic!() } }
|
||||||
#[async_trait::async_trait] impl domain::ports::AuthService for PanicAuth { async fn generate_token(&self, _: &domain::value_objects::UserId) -> Result<domain::ports::GeneratedToken, domain::errors::DomainError> { panic!() } async fn validate_token(&self, _: &str) -> Result<domain::value_objects::UserId, domain::errors::DomainError> { panic!() } }
|
#[async_trait::async_trait] impl domain::ports::AuthService for PanicAuth { async fn generate_token(&self, _: &domain::value_objects::UserId) -> Result<domain::ports::GeneratedToken, domain::errors::DomainError> { panic!() } async fn validate_token(&self, _: &str) -> Result<domain::value_objects::UserId, domain::errors::DomainError> { panic!() } }
|
||||||
#[async_trait::async_trait] impl domain::ports::UserRepository for PanicUserRepo { async fn find_by_email(&self, _: &domain::value_objects::Email) -> Result<Option<domain::models::User>, domain::errors::DomainError> { panic!() } async fn save(&self, _: &domain::models::User) -> Result<(), domain::errors::DomainError> { panic!() } async fn find_by_id(&self, _: &domain::value_objects::UserId) -> Result<Option<domain::models::User>, domain::errors::DomainError> { panic!() } async fn list_with_stats(&self) -> Result<Vec<domain::models::UserSummary>, domain::errors::DomainError> { panic!() } }
|
#[async_trait::async_trait] impl domain::ports::UserRepository for PanicUserRepo { async fn find_by_email(&self, _: &domain::value_objects::Email) -> Result<Option<domain::models::User>, domain::errors::DomainError> { panic!() } async fn save(&self, _: &domain::models::User) -> Result<(), domain::errors::DomainError> { panic!() } async fn find_by_id(&self, _: &domain::value_objects::UserId) -> Result<Option<domain::models::User>, domain::errors::DomainError> { panic!() } async fn find_by_username(&self, _: &domain::value_objects::Username) -> Result<Option<domain::models::User>, domain::errors::DomainError> { panic!() } async fn list_with_stats(&self) -> Result<Vec<domain::models::UserSummary>, domain::errors::DomainError> { panic!() } }
|
||||||
|
|
||||||
let state = crate::state::AppState {
|
let state = crate::state::AppState {
|
||||||
app_ctx: AppContext {
|
app_ctx: AppContext {
|
||||||
@@ -247,10 +247,28 @@ mod tests {
|
|||||||
async fn find_by_email(&self, _: &domain::value_objects::Email) -> Result<Option<domain::models::User>, domain::errors::DomainError> { Ok(None) }
|
async fn find_by_email(&self, _: &domain::value_objects::Email) -> Result<Option<domain::models::User>, domain::errors::DomainError> { Ok(None) }
|
||||||
async fn save(&self, _: &domain::models::User) -> Result<(), domain::errors::DomainError> { Ok(()) }
|
async fn save(&self, _: &domain::models::User) -> Result<(), domain::errors::DomainError> { Ok(()) }
|
||||||
async fn find_by_id(&self, _: &domain::value_objects::UserId) -> Result<Option<domain::models::User>, domain::errors::DomainError> { Ok(None) }
|
async fn find_by_id(&self, _: &domain::value_objects::UserId) -> Result<Option<domain::models::User>, domain::errors::DomainError> { Ok(None) }
|
||||||
|
async fn find_by_username(&self, _: &domain::value_objects::Username) -> Result<Option<domain::models::User>, domain::errors::DomainError> { Ok(None) }
|
||||||
async fn list_with_stats(&self) -> Result<Vec<domain::models::UserSummary>, domain::errors::DomainError> { Ok(vec![]) }
|
async fn list_with_stats(&self) -> Result<Vec<domain::models::UserSummary>, domain::errors::DomainError> { Ok(vec![]) }
|
||||||
}
|
}
|
||||||
|
struct DummyMovieRepo;
|
||||||
|
#[async_trait::async_trait] impl domain::ports::MovieRepository for DummyMovieRepo {
|
||||||
|
async fn get_movie_by_external_id(&self, _: &domain::value_objects::ExternalMetadataId) -> Result<Option<domain::models::Movie>, domain::errors::DomainError> { Ok(None) }
|
||||||
|
async fn get_movie_by_id(&self, _: &domain::value_objects::MovieId) -> Result<Option<domain::models::Movie>, domain::errors::DomainError> { Ok(None) }
|
||||||
|
async fn get_movies_by_title_and_year(&self, _: &domain::value_objects::MovieTitle, _: &domain::value_objects::ReleaseYear) -> Result<Vec<domain::models::Movie>, domain::errors::DomainError> { Ok(vec![]) }
|
||||||
|
async fn upsert_movie(&self, _: &domain::models::Movie) -> Result<(), domain::errors::DomainError> { Ok(()) }
|
||||||
|
async fn save_review(&self, _: &domain::models::Review) -> Result<domain::events::DomainEvent, domain::errors::DomainError> { panic!() }
|
||||||
|
async fn query_diary(&self, _: &domain::models::DiaryFilter) -> Result<domain::models::collections::Paginated<domain::models::DiaryEntry>, domain::errors::DomainError> { panic!() }
|
||||||
|
async fn get_review_history(&self, _: &domain::value_objects::MovieId) -> Result<domain::models::ReviewHistory, domain::errors::DomainError> { panic!() }
|
||||||
|
async fn get_review_by_id(&self, _: &domain::value_objects::ReviewId) -> Result<Option<domain::models::Review>, domain::errors::DomainError> { Ok(None) }
|
||||||
|
async fn delete_review(&self, _: &domain::value_objects::ReviewId) -> Result<(), domain::errors::DomainError> { Ok(()) }
|
||||||
|
async fn delete_movie(&self, _: &domain::value_objects::MovieId) -> Result<(), domain::errors::DomainError> { Ok(()) }
|
||||||
|
async fn query_activity_feed(&self, _: &domain::models::collections::PageParams) -> Result<domain::models::collections::Paginated<domain::models::FeedEntry>, domain::errors::DomainError> { panic!() }
|
||||||
|
async fn get_user_stats(&self, _: &domain::value_objects::UserId) -> Result<domain::models::UserStats, domain::errors::DomainError> { panic!() }
|
||||||
|
async fn get_user_history(&self, _: &domain::value_objects::UserId) -> Result<Vec<domain::models::DiaryEntry>, domain::errors::DomainError> { Ok(vec![]) }
|
||||||
|
async fn get_user_trends(&self, _: &domain::value_objects::UserId) -> Result<domain::models::UserTrends, domain::errors::DomainError> { panic!() }
|
||||||
|
}
|
||||||
Arc::new(
|
Arc::new(
|
||||||
activitypub::ActivityPubService::new(fed_repo, Arc::new(DummyUserRepo), "http://localhost:3000".to_string(), true)
|
activitypub::ActivityPubService::new(fed_repo, Arc::new(DummyUserRepo), Arc::new(DummyMovieRepo), "http://localhost:3000".to_string(), true)
|
||||||
.await
|
.await
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
)
|
)
|
||||||
@@ -284,7 +302,7 @@ mod tests {
|
|||||||
#[async_trait::async_trait] impl domain::ports::EventPublisher for PanicEvent2 { async fn publish(&self, _: &domain::events::DomainEvent) -> Result<(), domain::errors::DomainError> { panic!() } }
|
#[async_trait::async_trait] impl domain::ports::EventPublisher for PanicEvent2 { async fn publish(&self, _: &domain::events::DomainEvent) -> Result<(), domain::errors::DomainError> { panic!() } }
|
||||||
#[async_trait::async_trait] impl domain::ports::PasswordHasher for PanicHasher2 { async fn hash(&self, _: &str) -> Result<domain::value_objects::PasswordHash, domain::errors::DomainError> { panic!() } async fn verify(&self, _: &str, _: &domain::value_objects::PasswordHash) -> Result<bool, domain::errors::DomainError> { panic!() } }
|
#[async_trait::async_trait] impl domain::ports::PasswordHasher for PanicHasher2 { async fn hash(&self, _: &str) -> Result<domain::value_objects::PasswordHash, domain::errors::DomainError> { panic!() } async fn verify(&self, _: &str, _: &domain::value_objects::PasswordHash) -> Result<bool, domain::errors::DomainError> { panic!() } }
|
||||||
#[async_trait::async_trait] impl domain::ports::AuthService for PanicAuth2 { async fn generate_token(&self, _: &domain::value_objects::UserId) -> Result<domain::ports::GeneratedToken, domain::errors::DomainError> { panic!() } async fn validate_token(&self, _: &str) -> Result<domain::value_objects::UserId, domain::errors::DomainError> { panic!() } }
|
#[async_trait::async_trait] impl domain::ports::AuthService for PanicAuth2 { async fn generate_token(&self, _: &domain::value_objects::UserId) -> Result<domain::ports::GeneratedToken, domain::errors::DomainError> { panic!() } async fn validate_token(&self, _: &str) -> Result<domain::value_objects::UserId, domain::errors::DomainError> { panic!() } }
|
||||||
#[async_trait::async_trait] impl domain::ports::UserRepository for PanicUserRepo2 { async fn find_by_email(&self, _: &domain::value_objects::Email) -> Result<Option<domain::models::User>, domain::errors::DomainError> { panic!() } async fn save(&self, _: &domain::models::User) -> Result<(), domain::errors::DomainError> { panic!() } async fn find_by_id(&self, _: &domain::value_objects::UserId) -> Result<Option<domain::models::User>, domain::errors::DomainError> { panic!() } async fn list_with_stats(&self) -> Result<Vec<domain::models::UserSummary>, domain::errors::DomainError> { panic!() } }
|
#[async_trait::async_trait] impl domain::ports::UserRepository for PanicUserRepo2 { async fn find_by_email(&self, _: &domain::value_objects::Email) -> Result<Option<domain::models::User>, domain::errors::DomainError> { panic!() } async fn save(&self, _: &domain::models::User) -> Result<(), domain::errors::DomainError> { panic!() } async fn find_by_id(&self, _: &domain::value_objects::UserId) -> Result<Option<domain::models::User>, domain::errors::DomainError> { panic!() } async fn find_by_username(&self, _: &domain::value_objects::Username) -> Result<Option<domain::models::User>, domain::errors::DomainError> { panic!() } async fn list_with_stats(&self) -> Result<Vec<domain::models::UserSummary>, domain::errors::DomainError> { panic!() } }
|
||||||
struct PanicRenderer2;
|
struct PanicRenderer2;
|
||||||
impl crate::ports::HtmlRenderer for PanicRenderer2 {
|
impl crate::ports::HtmlRenderer for PanicRenderer2 {
|
||||||
fn render_diary_page(&self, _: &domain::models::collections::Paginated<domain::models::DiaryEntry>, _: application::ports::HtmlPageContext) -> Result<String, String> { panic!() }
|
fn render_diary_page(&self, _: &domain::models::collections::Paginated<domain::models::DiaryEntry>, _: application::ports::HtmlPageContext) -> Result<String, String> { panic!() }
|
||||||
@@ -346,7 +364,7 @@ mod tests {
|
|||||||
#[async_trait::async_trait] impl domain::ports::PosterStorage for PanicStorage3 { async fn store_poster(&self, _: &domain::value_objects::MovieId, _: &[u8]) -> Result<domain::value_objects::PosterPath, domain::errors::DomainError> { panic!() } async fn get_poster(&self, _: &domain::value_objects::PosterPath) -> Result<Vec<u8>, domain::errors::DomainError> { panic!() } }
|
#[async_trait::async_trait] impl domain::ports::PosterStorage for PanicStorage3 { async fn store_poster(&self, _: &domain::value_objects::MovieId, _: &[u8]) -> Result<domain::value_objects::PosterPath, domain::errors::DomainError> { panic!() } async fn get_poster(&self, _: &domain::value_objects::PosterPath) -> Result<Vec<u8>, domain::errors::DomainError> { panic!() } }
|
||||||
#[async_trait::async_trait] impl domain::ports::EventPublisher for PanicEvent3 { async fn publish(&self, _: &domain::events::DomainEvent) -> Result<(), domain::errors::DomainError> { panic!() } }
|
#[async_trait::async_trait] impl domain::ports::EventPublisher for PanicEvent3 { async fn publish(&self, _: &domain::events::DomainEvent) -> Result<(), domain::errors::DomainError> { panic!() } }
|
||||||
#[async_trait::async_trait] impl domain::ports::PasswordHasher for PanicHasher3 { async fn hash(&self, _: &str) -> Result<domain::value_objects::PasswordHash, domain::errors::DomainError> { panic!() } async fn verify(&self, _: &str, _: &domain::value_objects::PasswordHash) -> Result<bool, domain::errors::DomainError> { panic!() } }
|
#[async_trait::async_trait] impl domain::ports::PasswordHasher for PanicHasher3 { async fn hash(&self, _: &str) -> Result<domain::value_objects::PasswordHash, domain::errors::DomainError> { panic!() } async fn verify(&self, _: &str, _: &domain::value_objects::PasswordHash) -> Result<bool, domain::errors::DomainError> { panic!() } }
|
||||||
#[async_trait::async_trait] impl domain::ports::UserRepository for PanicUserRepo3 { async fn find_by_email(&self, _: &domain::value_objects::Email) -> Result<Option<domain::models::User>, domain::errors::DomainError> { panic!() } async fn save(&self, _: &domain::models::User) -> Result<(), domain::errors::DomainError> { panic!() } async fn find_by_id(&self, _: &domain::value_objects::UserId) -> Result<Option<domain::models::User>, domain::errors::DomainError> { panic!() } async fn list_with_stats(&self) -> Result<Vec<domain::models::UserSummary>, domain::errors::DomainError> { panic!() } }
|
#[async_trait::async_trait] impl domain::ports::UserRepository for PanicUserRepo3 { async fn find_by_email(&self, _: &domain::value_objects::Email) -> Result<Option<domain::models::User>, domain::errors::DomainError> { panic!() } async fn save(&self, _: &domain::models::User) -> Result<(), domain::errors::DomainError> { panic!() } async fn find_by_id(&self, _: &domain::value_objects::UserId) -> Result<Option<domain::models::User>, domain::errors::DomainError> { panic!() } async fn find_by_username(&self, _: &domain::value_objects::Username) -> Result<Option<domain::models::User>, domain::errors::DomainError> { panic!() } async fn list_with_stats(&self) -> Result<Vec<domain::models::UserSummary>, domain::errors::DomainError> { panic!() } }
|
||||||
struct PanicRenderer3;
|
struct PanicRenderer3;
|
||||||
impl crate::ports::HtmlRenderer for PanicRenderer3 {
|
impl crate::ports::HtmlRenderer for PanicRenderer3 {
|
||||||
fn render_diary_page(&self, _: &domain::models::collections::Paginated<domain::models::DiaryEntry>, _: application::ports::HtmlPageContext) -> Result<String, String> { panic!() }
|
fn render_diary_page(&self, _: &domain::models::collections::Paginated<domain::models::DiaryEntry>, _: application::ports::HtmlPageContext) -> Result<String, String> { panic!() }
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ const DEFAULT_PAGE_LIMIT: u32 = 5;
|
|||||||
const RSS_FEED_LIMIT: u32 = 50;
|
const RSS_FEED_LIMIT: u32 = 50;
|
||||||
|
|
||||||
pub mod html {
|
pub mod html {
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
use axum::{
|
use axum::{
|
||||||
extract::{Path, Query, State},
|
extract::{Path, Query, State},
|
||||||
http::{HeaderValue, StatusCode, header::SET_COOKIE},
|
http::{HeaderValue, StatusCode, header::SET_COOKIE},
|
||||||
@@ -19,7 +21,7 @@ pub mod html {
|
|||||||
use domain::{errors::DomainError, value_objects::UserId};
|
use domain::{errors::DomainError, value_objects::UserId};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
dtos::{DiaryQueryParams, ErrorQuery, FollowForm, LoginForm, LogReviewData, LogReviewForm, RegisterForm, UnfollowForm},
|
dtos::{DiaryQueryParams, ErrorQuery, FollowForm, FollowerActionForm, LoginForm, LogReviewData, LogReviewForm, RegisterForm, UnfollowForm},
|
||||||
extractors::{OptionalCookieUser, RequiredCookieUser},
|
extractors::{OptionalCookieUser, RequiredCookieUser},
|
||||||
state::AppState,
|
state::AppState,
|
||||||
};
|
};
|
||||||
@@ -153,6 +155,7 @@ pub mod html {
|
|||||||
&state.app_ctx,
|
&state.app_ctx,
|
||||||
RegisterCommand {
|
RegisterCommand {
|
||||||
email: form.email,
|
email: form.email,
|
||||||
|
username: form.username,
|
||||||
password: form.password,
|
password: form.password,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -294,10 +297,29 @@ pub mod html {
|
|||||||
OptionalCookieUser(user_id): OptionalCookieUser,
|
OptionalCookieUser(user_id): OptionalCookieUser,
|
||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
Path(profile_user_uuid): Path<Uuid>,
|
Path(profile_user_uuid): Path<Uuid>,
|
||||||
|
headers: axum::http::HeaderMap,
|
||||||
Query(params): Query<crate::dtos::ProfileQueryParams>,
|
Query(params): Query<crate::dtos::ProfileQueryParams>,
|
||||||
) -> impl IntoResponse {
|
) -> impl IntoResponse {
|
||||||
|
// Content negotiation: AP clients request application/activity+json
|
||||||
|
let accept = headers.get(axum::http::header::ACCEPT)
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.unwrap_or("");
|
||||||
|
if accept.contains("application/activity+json") || accept.contains("application/ld+json") {
|
||||||
|
return match state.ap_service.actor_json(&profile_user_uuid.to_string()).await {
|
||||||
|
Ok(json) => (
|
||||||
|
[(axum::http::header::CONTENT_TYPE, "application/activity+json")],
|
||||||
|
json,
|
||||||
|
).into_response(),
|
||||||
|
Err(_) => StatusCode::NOT_FOUND.into_response(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
let mut ctx = build_page_context(&state, user_id.clone()).await;
|
let mut ctx = build_page_context(&state, user_id.clone()).await;
|
||||||
let view = params.view.unwrap_or_else(|| "recent".to_string());
|
let view_str = params.view.as_deref().unwrap_or("recent");
|
||||||
|
let profile_view = match application::queries::ProfileView::from_str(view_str) {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(_) => return (axum::http::StatusCode::BAD_REQUEST, "invalid view parameter").into_response(),
|
||||||
|
};
|
||||||
|
|
||||||
let profile_user = match state.app_ctx.user_repository
|
let profile_user = match state.app_ctx.user_repository
|
||||||
.find_by_id(&domain::value_objects::UserId::from_uuid(profile_user_uuid))
|
.find_by_id(&domain::value_objects::UserId::from_uuid(profile_user_uuid))
|
||||||
@@ -308,8 +330,7 @@ pub mod html {
|
|||||||
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
|
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
|
||||||
};
|
};
|
||||||
|
|
||||||
let display_name = profile_user.email().value()
|
let display_name = profile_user.username().value();
|
||||||
.split('@').next().unwrap_or("User");
|
|
||||||
ctx.page_title = format!("{}'s Diary — Movies Diary", display_name);
|
ctx.page_title = format!("{}'s Diary — Movies Diary", display_name);
|
||||||
ctx.canonical_url = format!("{}/users/{}", state.app_ctx.config.base_url, profile_user_uuid);
|
ctx.canonical_url = format!("{}/users/{}", state.app_ctx.config.base_url, profile_user_uuid);
|
||||||
|
|
||||||
@@ -328,9 +349,25 @@ pub mod html {
|
|||||||
0
|
0
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let pending_followers = if is_own_profile {
|
||||||
|
state.ap_service
|
||||||
|
.get_pending_followers(domain::value_objects::UserId::from_uuid(profile_user_uuid))
|
||||||
|
.await
|
||||||
|
.unwrap_or_default()
|
||||||
|
.into_iter()
|
||||||
|
.map(|a| application::ports::RemoteActorView {
|
||||||
|
handle: a.handle,
|
||||||
|
url: a.url,
|
||||||
|
display_name: a.display_name,
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
} else {
|
||||||
|
vec![]
|
||||||
|
};
|
||||||
|
|
||||||
let query = application::queries::GetUserProfileQuery {
|
let query = application::queries::GetUserProfileQuery {
|
||||||
user_id: profile_user_uuid,
|
user_id: profile_user_uuid,
|
||||||
view: view.clone(),
|
view: profile_view,
|
||||||
limit: params.limit,
|
limit: params.limit,
|
||||||
offset: params.offset,
|
offset: params.offset,
|
||||||
};
|
};
|
||||||
@@ -349,7 +386,7 @@ pub mod html {
|
|||||||
profile_user_id: profile_user_uuid,
|
profile_user_id: profile_user_uuid,
|
||||||
profile_user_email: profile_user.email().value().to_string(),
|
profile_user_email: profile_user.email().value().to_string(),
|
||||||
stats: profile.stats,
|
stats: profile.stats,
|
||||||
view,
|
view: profile_view.as_str().to_string(),
|
||||||
entries: profile.entries,
|
entries: profile.entries,
|
||||||
current_offset: offset,
|
current_offset: offset,
|
||||||
has_more,
|
has_more,
|
||||||
@@ -359,6 +396,7 @@ pub mod html {
|
|||||||
is_own_profile,
|
is_own_profile,
|
||||||
error: params.error,
|
error: params.error,
|
||||||
following_count,
|
following_count,
|
||||||
|
pending_followers,
|
||||||
};
|
};
|
||||||
match state.html_renderer.render_profile_page(data) {
|
match state.html_renderer.render_profile_page(data) {
|
||||||
Ok(html) => Html(html).into_response(),
|
Ok(html) => Html(html).into_response(),
|
||||||
@@ -406,6 +444,42 @@ pub mod html {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn accept_follower(
|
||||||
|
RequiredCookieUser(user_id): RequiredCookieUser,
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(profile_user_uuid): Path<Uuid>,
|
||||||
|
Form(form): Form<FollowerActionForm>,
|
||||||
|
) -> impl IntoResponse {
|
||||||
|
if user_id.value() != profile_user_uuid {
|
||||||
|
return StatusCode::FORBIDDEN.into_response();
|
||||||
|
}
|
||||||
|
match state.ap_service.accept_follower(user_id, &form.actor_url).await {
|
||||||
|
Ok(_) => Redirect::to(&format!("/users/{}", profile_user_uuid)).into_response(),
|
||||||
|
Err(e) => {
|
||||||
|
let msg = encode_error(&e.to_string());
|
||||||
|
Redirect::to(&format!("/users/{}?error={}", profile_user_uuid, msg)).into_response()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn reject_follower(
|
||||||
|
RequiredCookieUser(user_id): RequiredCookieUser,
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(profile_user_uuid): Path<Uuid>,
|
||||||
|
Form(form): Form<FollowerActionForm>,
|
||||||
|
) -> impl IntoResponse {
|
||||||
|
if user_id.value() != profile_user_uuid {
|
||||||
|
return StatusCode::FORBIDDEN.into_response();
|
||||||
|
}
|
||||||
|
match state.ap_service.reject_follower(user_id, &form.actor_url).await {
|
||||||
|
Ok(_) => Redirect::to(&format!("/users/{}", profile_user_uuid)).into_response(),
|
||||||
|
Err(e) => {
|
||||||
|
let msg = encode_error(&e.to_string());
|
||||||
|
Redirect::to(&format!("/users/{}?error={}", profile_user_uuid, msg)).into_response()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn get_following_page(
|
pub async fn get_following_page(
|
||||||
RequiredCookieUser(user_id): RequiredCookieUser,
|
RequiredCookieUser(user_id): RequiredCookieUser,
|
||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
@@ -459,6 +533,11 @@ pub mod posters {
|
|||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
Path(path): Path<String>,
|
Path(path): Path<String>,
|
||||||
) -> impl IntoResponse {
|
) -> impl IntoResponse {
|
||||||
|
// If path is a remote URL, redirect directly instead of serving from local storage.
|
||||||
|
if path.starts_with("http://") || path.starts_with("https://") {
|
||||||
|
return axum::response::Redirect::temporary(&path).into_response();
|
||||||
|
}
|
||||||
|
|
||||||
let poster_path = match PosterPath::new(path) {
|
let poster_path = match PosterPath::new(path) {
|
||||||
Ok(p) => p,
|
Ok(p) => p,
|
||||||
Err(_) => return StatusCode::BAD_REQUEST.into_response(),
|
Err(_) => return StatusCode::BAD_REQUEST.into_response(),
|
||||||
@@ -672,6 +751,7 @@ pub mod api {
|
|||||||
) -> Result<StatusCode, ApiError> {
|
) -> Result<StatusCode, ApiError> {
|
||||||
register_uc::execute(&state.app_ctx, RegisterCommand {
|
register_uc::execute(&state.app_ctx, RegisterCommand {
|
||||||
email: req.email,
|
email: req.email,
|
||||||
|
username: req.username,
|
||||||
password: req.password,
|
password: req.password,
|
||||||
})
|
})
|
||||||
.await?;
|
.await?;
|
||||||
|
|||||||
@@ -98,6 +98,7 @@ async fn wire_dependencies() -> anyhow::Result<AppState> {
|
|||||||
ActivityPubService::new(
|
ActivityPubService::new(
|
||||||
federation_repo,
|
federation_repo,
|
||||||
Arc::clone(&user_repository),
|
Arc::clone(&user_repository),
|
||||||
|
Arc::clone(&repository),
|
||||||
app_config.base_url.clone(),
|
app_config.base_url.clone(),
|
||||||
cfg!(debug_assertions),
|
cfg!(debug_assertions),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -112,6 +112,14 @@ fn html_routes(rate_limit: u64) -> Router<AppState> {
|
|||||||
"/users/{id}/unfollow",
|
"/users/{id}/unfollow",
|
||||||
routing::post(handlers::html::unfollow_remote_user),
|
routing::post(handlers::html::unfollow_remote_user),
|
||||||
)
|
)
|
||||||
|
.route(
|
||||||
|
"/users/{id}/followers/accept",
|
||||||
|
routing::post(handlers::html::accept_follower),
|
||||||
|
)
|
||||||
|
.route(
|
||||||
|
"/users/{id}/followers/reject",
|
||||||
|
routing::post(handlers::html::reject_follower),
|
||||||
|
)
|
||||||
.route(
|
.route(
|
||||||
"/users/{id}/following-list",
|
"/users/{id}/following-list",
|
||||||
routing::get(handlers::html::get_following_page),
|
routing::get(handlers::html::get_following_page),
|
||||||
@@ -127,7 +135,7 @@ fn html_routes(rate_limit: u64) -> Router<AppState> {
|
|||||||
routing::post(handlers::html::post_delete_review),
|
routing::post(handlers::html::post_delete_review),
|
||||||
)
|
)
|
||||||
.route(
|
.route(
|
||||||
"/posters/{path}",
|
"/posters/{*path}",
|
||||||
routing::get(handlers::posters::get_poster),
|
routing::get(handlers::posters::get_poster),
|
||||||
)
|
)
|
||||||
.route("/feed.rss", routing::get(handlers::rss::get_feed))
|
.route("/feed.rss", routing::get(handlers::rss::get_feed))
|
||||||
|
|||||||
@@ -83,6 +83,7 @@ struct NobodyUserRepo;
|
|||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl UserRepository for NobodyUserRepo {
|
impl UserRepository for NobodyUserRepo {
|
||||||
async fn find_by_email(&self, _: &Email) -> Result<Option<User>, DomainError> { Ok(None) }
|
async fn find_by_email(&self, _: &Email) -> Result<Option<User>, DomainError> { Ok(None) }
|
||||||
|
async fn find_by_username(&self, _: &domain::value_objects::Username) -> Result<Option<User>, DomainError> { Ok(None) }
|
||||||
async fn save(&self, _: &User) -> Result<(), DomainError> { panic!() }
|
async fn save(&self, _: &User) -> Result<(), DomainError> { panic!() }
|
||||||
async fn find_by_id(&self, _: &UserId) -> Result<Option<User>, DomainError> { panic!() }
|
async fn find_by_id(&self, _: &UserId) -> Result<Option<User>, DomainError> { panic!() }
|
||||||
async fn list_with_stats(&self) -> Result<Vec<domain::models::UserSummary>, DomainError> { panic!() }
|
async fn list_with_stats(&self) -> Result<Vec<domain::models::UserSummary>, DomainError> { panic!() }
|
||||||
@@ -103,12 +104,15 @@ async fn test_ap_service() -> Arc<activitypub::ActivityPubService> {
|
|||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl UserRepository for DummyUserRepo {
|
impl UserRepository for DummyUserRepo {
|
||||||
async fn find_by_email(&self, _: &Email) -> Result<Option<User>, DomainError> { Ok(None) }
|
async fn find_by_email(&self, _: &Email) -> Result<Option<User>, DomainError> { Ok(None) }
|
||||||
|
async fn find_by_username(&self, _: &domain::value_objects::Username) -> Result<Option<User>, DomainError> { Ok(None) }
|
||||||
async fn save(&self, _: &User) -> Result<(), DomainError> { Ok(()) }
|
async fn save(&self, _: &User) -> Result<(), DomainError> { Ok(()) }
|
||||||
async fn find_by_id(&self, _: &UserId) -> Result<Option<User>, DomainError> { Ok(None) }
|
async fn find_by_id(&self, _: &UserId) -> Result<Option<User>, DomainError> { Ok(None) }
|
||||||
async fn list_with_stats(&self) -> Result<Vec<domain::models::UserSummary>, DomainError> { Ok(vec![]) }
|
async fn list_with_stats(&self) -> Result<Vec<domain::models::UserSummary>, DomainError> { Ok(vec![]) }
|
||||||
}
|
}
|
||||||
|
let movie_pool = SqlitePool::connect("sqlite::memory:").await.unwrap();
|
||||||
|
let movie_repo = Arc::new(sqlite::SqliteMovieRepository::new(movie_pool));
|
||||||
Arc::new(
|
Arc::new(
|
||||||
activitypub::ActivityPubService::new(fed_repo, Arc::new(DummyUserRepo), "http://localhost:3000".to_string(), true)
|
activitypub::ActivityPubService::new(fed_repo, Arc::new(DummyUserRepo), movie_repo, "http://localhost:3000".to_string(), true)
|
||||||
.await
|
.await
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -549,3 +549,72 @@ form button[type="submit"]:hover {
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 0.5rem;
|
gap: 0.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Pending follow requests */
|
||||||
|
.pending-followers {
|
||||||
|
margin-top: 1.5rem;
|
||||||
|
padding-top: 1rem;
|
||||||
|
border-top: 1px solid rgba(255,255,255,0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pending-list {
|
||||||
|
list-style: none;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pending-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
padding: 0.4rem 0;
|
||||||
|
border-bottom: 1px solid rgba(255,255,255,0.07);
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pending-url {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
flex: 1;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
|
||||||
|
.inline-form {
|
||||||
|
display: inline;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-accept {
|
||||||
|
background: rgba(60, 180, 80, 0.65);
|
||||||
|
backdrop-filter: blur(4px);
|
||||||
|
-webkit-backdrop-filter: blur(4px);
|
||||||
|
color: #fff;
|
||||||
|
border: 1px solid rgba(80, 200, 100, 0.3);
|
||||||
|
border-radius: 16px;
|
||||||
|
padding: 0.2rem 0.6rem;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
font-weight: 600;
|
||||||
|
transition: background 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-accept:hover {
|
||||||
|
background: rgba(60, 200, 80, 0.85);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-reject {
|
||||||
|
background: rgba(200, 60, 60, 0.65);
|
||||||
|
backdrop-filter: blur(4px);
|
||||||
|
-webkit-backdrop-filter: blur(4px);
|
||||||
|
color: #fff;
|
||||||
|
border: 1px solid rgba(220, 80, 80, 0.3);
|
||||||
|
border-radius: 16px;
|
||||||
|
padding: 0.2rem 0.6rem;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
font-weight: 600;
|
||||||
|
transition: background 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-reject:hover {
|
||||||
|
background: rgba(220, 60, 60, 0.85);
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user