Compare commits

...

40 Commits

Author SHA1 Message Date
4d221e60de feat: favorite actors top-5 stat in profile trends
All checks were successful
CI / Check / Test (push) Successful in 1h5m14s
2026-08-09 20:59:18 +02:00
d282e8ea7e fix: correct order of weekdays and ensure week starts on Monday 2026-08-09 15:00:39 +02:00
c9715baab8 structural refactor and codebase improvements 2026-08-09 14:58:14 +02:00
22b1dd3f56 fix: portal wrapup share card to escape transform stacking context
All checks were successful
CI / Check / Test (push) Successful in 1h5m29s
2026-07-27 14:07:36 +02:00
813778dc7e fix: users table has avatar_path not avatar_url, resolve to full URL
Some checks failed
CI / Check / Test (push) Has been cancelled
2026-07-27 13:08:45 +02:00
063bab910b ADR-0003: local follows bypass AP, unified FollowCommand/FollowQuery ports, FederationRepos struct, base_url normalization
Some checks failed
CI / Check / Test (push) Has been cancelled
2026-07-27 12:56:30 +02:00
839cababe4 bump k-ap 0.5.0, decompose repo traits, LocalObject, ActivityStreamsType enum, split follow modules
Some checks failed
CI / Check / Test (push) Has been cancelled
2026-07-27 11:46:24 +02:00
fdf286ca94 fix: remove split-debuginfo option from dev profile in Cargo.toml
Some checks failed
CI / Check / Test (push) Has been cancelled
2026-07-27 11:19:54 +02:00
e30e785936 bump k-ap to 0.4.6, add nodeinfo metadata 2026-07-16 09:56:54 +02:00
10be024bdf fix: update k-ap dependency version to 0.4.4
All checks were successful
CI / Check / Test (push) Successful in 1h5m51s
2026-07-11 10:45:43 +02:00
1e33c6d184 fix: update k-ap dependency version to 0.4.4
Some checks failed
CI / Check / Test (push) Has been cancelled
2026-07-11 10:40:53 +02:00
96168cfc7b fix: update k-ap dependency version to 0.4.3
Some checks failed
CI / Check / Test (push) Has been cancelled
2026-07-11 10:21:28 +02:00
95b839355f fix: portal search overlay to escape transform stacking context, auto-fill IMDB from ttXXXX input
All checks were successful
CI / Check / Test (push) Successful in 1h12m50s
2026-07-11 01:44:08 +02:00
85285b2a52 github ci fix
All checks were successful
CI / Check / Test (push) Successful in 1h9m41s
2026-07-10 23:29:17 +02:00
c3d8bcad29 fix: collapse nested if for clippy
Some checks failed
CI / Check / Test (push) Has been cancelled
2026-07-10 23:20:49 +02:00
8aa64ab174 fix: restrict swipe-tabs drag to touch-only, prevent ghost swipe after drawer close
Some checks failed
CI / Check / Test (push) Failing after 8m25s
2026-07-10 22:52:50 +02:00
d84c54bb30 feat: page transitions, poster hover, star bounce, reveal scale-up 2026-07-10 22:51:09 +02:00
41bed3583d feat: calendar diary view on profile (#15)
Some checks failed
CI / Check / Test (push) Failing after 8m29s
2026-07-10 22:32:47 +02:00
0a8b52514d feat: calendar diary view on profile (#15) 2026-07-10 22:22:13 +02:00
a0c0ba1c5d rename profile Trends tab to Stats
Some checks failed
CI / Check / Test (push) Failing after 8m35s
2026-07-10 22:01:56 +02:00
94cab1ea7c fix: lock body scroll + remove scrollbar on wrapup share card
Some checks failed
CI / Check / Test (push) Has been cancelled
2026-07-10 21:58:38 +02:00
3dde0d13db docs: sync README + architecture diagram with current codebase 2026-07-10 21:56:16 +02:00
1c81d7768c fix: duplicate count in wrapup watch medium display 2026-07-10 21:53:21 +02:00
07df6fe207 review detail sheet on diary/profile/community, wrapup period presets 2026-07-10 21:51:42 +02:00
1a7448fd3d fix: use strict > for min-count filters in wrapup stats
Some checks failed
CI / Check / Test (push) Failing after 8m38s
2026-07-10 21:42:29 +02:00
587dcc04de feat: richer profile stats, wrapup min-count filter, watch medium distribution
Some checks failed
CI / Check / Test (push) Has been cancelled
- filter wrapup top directors/actors with count < 2
- add watch_medium to wrapup report + adapters
- profile trends: genre breakdown, rating histogram, watch medium dist
- fix unused StarDisplay import in movie detail
2026-07-10 21:38:08 +02:00
498f3b1818 edit sheet delete btn, fix medium icons, 44px touch targets, fix drag leak on drawer close
Some checks failed
CI / Check / Test (push) Failing after 8m44s
2026-07-10 17:46:56 +02:00
0ee2e04fe5 refactor(spa): collapse api/hooks telescope, merge review sheets, extract tab+list modules
- merge lib/api/* + hooks/use-* → features/* domain modules
- log-sheet + edit-review-sheet → review-sheet with mode discriminant
- index.tsx → feed-tab, watchlist-tab, queue-tab
- social actor-list pattern → ActorList component
- movie detail inline sections → community-reviews, viewing-history
2026-07-10 17:38:58 +02:00
89045414cf fmt
Some checks failed
CI / Check / Test (push) Failing after 9m15s
2026-07-10 17:10:59 +02:00
2de6690401 fix: import remote outbox on outbound follow accept (k-ap 0.4.2)
k-ap now emits OutboundFollowAccepted when remote accepts our follow.
Bridge maps it to FollowAccepted domain event. Worker handler looks up
the actor's outbox URL and calls import_remote_outbox. Previously the
accept was silent — no backfill happened, feed stayed empty.
2026-07-10 17:02:14 +02:00
12378c3649 fmt 2026-07-10 16:32:07 +02:00
46b8488b09 refactor: Feed uses SocialIdentity matching, deps From impl, remove get_accepted_following_urls
Feed builds FollowingFilter by matching SocialIdentity::Local/Remote
instead of URL-prefix heuristic. Removed get_accepted_following_urls
from SocialQuery (no longer needed). Added From<&AppState> for deps
structs — 20 construction sites collapsed to one-liners.
2026-07-10 16:31:05 +02:00
7e02f15a85 refactor: consolidate 11 social use cases → SocialCmd/SocialQry enum dispatch
-280 net lines. 11 one-file use cases replaced by execute_command/
execute_query with enum dispatch. Added FollowRejected event (reject
was silently dropping). Command→event mapping now explicit in one match.
2026-07-10 16:26:57 +02:00
d60c47199c fix: FollowTarget enum — actor_url no longer lies about holding a handle
FollowCommand.target is now FollowTarget (Identity|Handle) instead of
SocialIdentity. actor_url field always holds a URL; handles go through
FollowTarget::Handle. Adapter resolves handles explicitly. Type system
prevents misuse in future commands.
2026-07-10 16:18:57 +02:00
2484f1e603 fmt 2026-07-10 16:03:36 +02:00
44d7df33a2 refactor: remove SocialQueryPort — replaced by SocialQuery + FederationAdminQuery
-319 lines. Legacy SocialQueryPort trait, NoopSocialQueryPort,
PanicSocialQueryPort all deleted. Federation repos now implement
FederationAdminQuery (single method). get_users uses FederationAdminQuery.
All other consumers use unified SocialQuery.
2026-07-10 16:02:27 +02:00
7cfa234902 refactor: SocialActor rich queries, migrate remaining handlers, slim SocialQueryPort
SocialQuery returns SocialActor (identity+handle+display_name+avatar_url)
instead of bare SocialIdentity. Migrated get_following_page,
get_followers_page, get_blocked_actors_page to use cases. Moved
get_activity_feed + get_profile from SocialQueryPort to SocialQuery.
Legacy SocialQueryPort remains only for get_users listing.
2026-07-10 15:52:37 +02:00
3ee75305a9 refactor: move ap_service from AppState to AppContext.Services 2026-07-10 15:34:23 +02:00
322e9ee81a feat: unified social identity layer — SocialIdentity, ports, use cases, adapter
SocialIdentity value object (Local|Remote), SocialCommand/SocialQuery
domain ports, 11 CQRS use cases w/ 14 tests, CompositeSocialAdapter
wrapping k_ap, 6 new domain events, handlers migrated from ap_service
to use cases. Closes #12 foundation — AP handlers + legacy cleanup TBD.
2026-07-10 15:29:46 +02:00
96ce5f7d26 docs: domain glossary (16 terms) + ADR-0002 unified social identity
CONTEXT.md expanded with Movie, Person, Review, Rating, WatchMedium,
Watchlist, Goal, WrapUp, User, Follow, Feed, WatchEvent, Import,
ImportProfile, SocialIdentity. ADR-0002 documents wrap-k_ap decision.
2026-07-10 15:29:31 +02:00
361 changed files with 17398 additions and 5723 deletions

View File

@@ -45,7 +45,9 @@ ALLOW_REGISTRATION=true
# PORT=3000
# RATE_LIMIT=60
# SECURE_COOKIES=true
# RUST_LOG=presentation=info,tower_http=info,worker=info
# Handler-level logs come from the `presentation` crate; startup/wiring logs come
# from `server`. Include both — `server=info` alone silently drops handler logs.
# RUST_LOG=server=info,presentation=info,tower_http=info,worker=info
# CORS (for SPA development only)
# CORS_ORIGINS=http://localhost:5173

View File

@@ -40,3 +40,8 @@ jobs:
- name: test
run: cargo test
# Layering guards. These live in the Makefile and were previously local-only,
# so a PR could go green in CI while violating them.
- name: guards
run: make check-appcontext check-handler-deps check-handler-repos check-presentation-adapters check-federation-off-social check-social-crates-are-ap-free

View File

@@ -41,6 +41,11 @@ jobs:
- name: test
run: cargo test
# Layering guards. These live in the Makefile and were previously local-only,
# so a PR could go green in CI while violating them.
- name: guards
run: make check-appcontext check-handler-deps check-handler-repos check-presentation-adapters check-federation-off-social check-social-crates-are-ap-free
docker:
name: Build & Push Docker Image
runs-on: ubuntu-latest
@@ -57,8 +62,8 @@ jobs:
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
username: ${{ github.repository_owner }}
password: ${{ secrets.GHCR_TOKEN || github.token }}
- name: Docker metadata
id: meta

3
.gitignore vendored
View File

@@ -13,7 +13,8 @@
.worktrees/
.superpowers/
docs/
docs/*
!docs/adr/
imgs/
.sqlx/

View File

@@ -40,6 +40,10 @@ _Avoid_: Stats page, recap, summary
A registered account with a username, email, and profile (display name, bio, avatar, banner). Can be Standard or Admin.
_Avoid_: Account, member, profile (as a synonym for the whole User)
**SocialIdentity**:
The uniform identifier for anyone involved in a social interaction — either a local User or a remote federated actor. Social commands and queries operate on SocialIdentity so the domain never branches on local vs remote.
_Avoid_: Actor, participant, social user
**Follow**:
A social relationship where one user subscribes to another's activity. Always requires acceptance by the target user. Works identically for local and federated (ActivityPub) users. Once accepted, the followed user's reviews appear in the follower's Feed.
_Avoid_: Subscribe, connect, friend

View File

@@ -10,7 +10,7 @@ Thanks for your interest in Movies Diary! This is a personal project but contrib
4. Run the backend and worker:
```bash
cargo run -p presentation # HTTP server on :3000
cargo run -p server # HTTP server on :3000
cargo run -p worker # event worker (separate terminal)
```
@@ -44,7 +44,7 @@ The project follows hexagonal (ports & adapters) architecture. See `architecture
**Key rules:**
- Presentation handlers never touch repositories directly — all domain logic goes through use cases in the `application` crate
- Application use cases return raw domain data — URL formatting, date display, and view model assembly belong in presentation mappers (`presentation/src/mappers/`)
- Use cases called from presentation handlers take `&AppContext`. Functions called from adapter event handlers take individual `Arc<dyn Trait>` params to keep adapter dependencies explicit
- Use cases called from presentation handlers take a `&FooDeps` struct (registered in `application::Deps`, built by `composition::build_deps`) — never `&AppContext` itself, which `application` cannot even depend on. A few keep individual `Arc<dyn Trait>` params instead: `enrich_movie` and `request_enrichment` because they are called from adapters rather than handlers, and `diary::log_review` because its one extra dependency comes from `Services` rather than a repository. `wrapup::compute`, `import::cleanup` and `integrations::cleanup` also take individual params, but they are only ever called from jobs. See ADR-0007 for the exact list and why each is legitimate
```
domain → pure types, traits (ports), zero deps

140
Cargo.lock generated
View File

@@ -306,6 +306,7 @@ version = "0.1.0"
dependencies = [
"domain",
"serde",
"serde_json",
"utoipa",
"uuid",
]
@@ -1118,6 +1119,39 @@ dependencies = [
"static_assertions",
]
[[package]]
name = "composition"
version = "0.1.0"
dependencies = [
"activitypub",
"anyhow",
"application",
"async-trait",
"auth",
"chrono",
"domain",
"infra-wiring",
"jellyfin",
"metadata",
"nats",
"object-storage",
"plex",
"poster-fetcher",
"postgres",
"postgres-event-queue",
"postgres-federation",
"postgres-search",
"postgres-social",
"sqlite",
"sqlite-event-queue",
"sqlite-federation",
"sqlite-search",
"sqlite-social",
"sqlx",
"tokio",
"uuid",
]
[[package]]
name = "concurrent-queue"
version = "2.5.0"
@@ -1621,6 +1655,7 @@ dependencies = [
"serde",
"serde_json",
"thiserror 2.0.18",
"tokio",
"uuid",
]
@@ -2892,9 +2927,9 @@ dependencies = [
[[package]]
name = "k-ap"
version = "0.4.1"
version = "0.5.0"
source = "sparse+https://git.gabrielkaszewski.dev/api/packages/GKaszewski/cargo/"
checksum = "03e39c04075b39960c329feba896a16aba37f0863669c28e7106b7cc45a9988d"
checksum = "ab6066cccc6ae8aaa2f6262ac7d471e58930a04be3266a2e367d6bdd8aaaba29"
dependencies = [
"activitypub_federation",
"anyhow",
@@ -2903,9 +2938,11 @@ dependencies = [
"chrono",
"enum_delegate",
"futures",
"paste",
"reqwest 0.13.3",
"serde",
"serde_json",
"thiserror 2.0.18",
"tokio",
"tracing",
"url",
@@ -3903,7 +3940,7 @@ dependencies = [
"chrono",
"domain",
"futures",
"postgres-federation",
"postgres-social",
"serde",
"serde_json",
"sqlx",
@@ -3938,6 +3975,7 @@ dependencies = [
"chrono",
"domain",
"k-ap",
"postgres-social",
"serde_json",
"sqlx",
"tracing",
@@ -3955,6 +3993,18 @@ dependencies = [
"uuid",
]
[[package]]
name = "postgres-social"
version = "0.1.0"
dependencies = [
"adapter-common",
"async-trait",
"chrono",
"domain",
"sqlx",
"uuid",
]
[[package]]
name = "potential_utf"
version = "0.1.5"
@@ -3989,43 +4039,22 @@ checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
name = "presentation"
version = "0.1.0"
dependencies = [
"activitypub",
"anyhow",
"api-types",
"application",
"async-trait",
"auth",
"axum",
"axum-governor",
"bytes",
"chrono",
"composition",
"domain",
"dotenvy",
"export",
"futures",
"http-body-util",
"importer",
"infer",
"infra-wiring",
"jellyfin",
"metadata",
"nats",
"object-storage",
"percent-encoding",
"plex",
"poster-fetcher",
"postgres",
"postgres-event-queue",
"postgres-federation",
"postgres-search",
"rss 0.1.0",
"serde",
"serde_json",
"sqlite",
"sqlite-event-queue",
"sqlite-federation",
"sqlite-search",
"sqlx",
"template-askama",
"tokio",
"tower",
@@ -4945,6 +4974,50 @@ dependencies = [
"serde",
]
[[package]]
name = "server"
version = "0.1.0"
dependencies = [
"activitypub",
"anyhow",
"application",
"async-trait",
"auth",
"axum",
"bytes",
"composition",
"domain",
"dotenvy",
"export",
"futures",
"http-body-util",
"importer",
"infra-wiring",
"metadata",
"nats",
"object-storage",
"poster-fetcher",
"postgres",
"postgres-event-queue",
"postgres-federation",
"postgres-search",
"postgres-social",
"presentation",
"rss 0.1.0",
"serde_json",
"sqlite",
"sqlite-event-queue",
"sqlite-federation",
"sqlite-search",
"sqlite-social",
"sqlx",
"tokio",
"tower",
"tracing",
"tracing-subscriber",
"uuid",
]
[[package]]
name = "sha1"
version = "0.10.6"
@@ -5188,7 +5261,7 @@ dependencies = [
"futures",
"serde",
"serde_json",
"sqlite-federation",
"sqlite-social",
"sqlx",
"tokio",
"tracing",
@@ -5222,6 +5295,7 @@ dependencies = [
"domain",
"k-ap",
"serde_json",
"sqlite-social",
"sqlx",
"tokio",
"tracing",
@@ -5240,6 +5314,19 @@ dependencies = [
"uuid",
]
[[package]]
name = "sqlite-social"
version = "0.1.0"
dependencies = [
"adapter-common",
"async-trait",
"chrono",
"domain",
"sqlx",
"tokio",
"uuid",
]
[[package]]
name = "sqlx"
version = "0.8.6"
@@ -7149,6 +7236,7 @@ dependencies = [
"application",
"async-trait",
"auth",
"composition",
"domain",
"dotenvy",
"export",

View File

@@ -10,7 +10,9 @@ members = [
"crates/adapters/sqlite",
"crates/adapters/postgres",
"crates/adapters/sqlite-federation",
"crates/adapters/sqlite-social",
"crates/adapters/postgres-federation",
"crates/adapters/postgres-social",
"crates/adapters/sqlite-event-queue",
"crates/adapters/postgres-event-queue",
"crates/adapters/template-askama",
@@ -23,7 +25,9 @@ members = [
"crates/adapters/tmdb-enrichment",
"crates/adapters/image-converter",
"crates/domain",
"crates/composition",
"crates/presentation",
"crates/server",
"crates/tui",
"crates/worker",
"crates/adapters/importer",
@@ -68,6 +72,7 @@ api-types = { path = "crates/api-types" }
domain = { path = "crates/domain" }
tmdb-enrichment = { path = "crates/adapters/tmdb-enrichment" }
application = { path = "crates/application" }
composition = { path = "crates/composition" }
presentation = { path = "crates/presentation" }
auth = { path = "crates/adapters/auth" }
metadata = { path = "crates/adapters/metadata" }
@@ -79,8 +84,10 @@ rss = { path = "crates/adapters/rss" }
export = { path = "crates/adapters/export" }
sqlite = { path = "crates/adapters/sqlite" }
sqlite-federation = { path = "crates/adapters/sqlite-federation" }
sqlite-social = { path = "crates/adapters/sqlite-social" }
postgres = { path = "crates/adapters/postgres" }
postgres-federation = { path = "crates/adapters/postgres-federation" }
postgres-social = { path = "crates/adapters/postgres-social" }
template-askama = { path = "crates/adapters/template-askama" }
activitypub = { path = "crates/adapters/activitypub" }
event-payload = { path = "crates/adapters/event-payload" }
@@ -98,7 +105,6 @@ infra-wiring = { path = "crates/infra-wiring" }
[profile.dev]
debug = 1 # line tables only — still debuggable, much faster linking
split-debuginfo = "unpacked" # macOS: skip dsymutil on every link
[profile.dev.package."*"]
opt-level = 2 # compile deps faster at runtime; paid once, cached after

View File

@@ -12,6 +12,10 @@ FROM rust:slim-bookworm AS builder
WORKDIR /build
# Cache dependency compilation separately from source
#
# Every workspace member's Cargo.toml must be listed here by hand — `cargo fetch`
# below reads the whole workspace graph, so a missing manifest fails the build with
# "failed to read .../Cargo.toml". Adding a crate to crates/ means adding a line here.
COPY Cargo.toml Cargo.lock ./
COPY .cargo ./.cargo
COPY crates/adapters/activitypub/Cargo.toml crates/adapters/activitypub/Cargo.toml
@@ -30,16 +34,20 @@ COPY crates/adapters/plex/Cargo.toml crates/adapters/plex/Cargo.tom
COPY crates/adapters/rss/Cargo.toml crates/adapters/rss/Cargo.toml
COPY crates/adapters/sqlite/Cargo.toml crates/adapters/sqlite/Cargo.toml
COPY crates/adapters/sqlite-federation/Cargo.toml crates/adapters/sqlite-federation/Cargo.toml
COPY crates/adapters/sqlite-social/Cargo.toml crates/adapters/sqlite-social/Cargo.toml
COPY crates/adapters/sqlite-event-queue/Cargo.toml crates/adapters/sqlite-event-queue/Cargo.toml
COPY crates/adapters/postgres/Cargo.toml crates/adapters/postgres/Cargo.toml
COPY crates/adapters/postgres-federation/Cargo.toml crates/adapters/postgres-federation/Cargo.toml
COPY crates/adapters/postgres-social/Cargo.toml crates/adapters/postgres-social/Cargo.toml
COPY crates/adapters/postgres-event-queue/Cargo.toml crates/adapters/postgres-event-queue/Cargo.toml
COPY crates/adapters/template-askama/Cargo.toml crates/adapters/template-askama/Cargo.toml
COPY crates/api-types/Cargo.toml crates/api-types/Cargo.toml
COPY crates/application/Cargo.toml crates/application/Cargo.toml
COPY crates/adapters/tmdb-enrichment/Cargo.toml crates/adapters/tmdb-enrichment/Cargo.toml
COPY crates/domain/Cargo.toml crates/domain/Cargo.toml
COPY crates/composition/Cargo.toml crates/composition/Cargo.toml
COPY crates/presentation/Cargo.toml crates/presentation/Cargo.toml
COPY crates/server/Cargo.toml crates/server/Cargo.toml
COPY crates/tui/Cargo.toml crates/tui/Cargo.toml
COPY crates/adapters/image-converter/Cargo.toml crates/adapters/image-converter/Cargo.toml
COPY crates/adapters/sqlite-search/Cargo.toml crates/adapters/sqlite-search/Cargo.toml
@@ -71,7 +79,7 @@ COPY crates ./crates
# To add NATS support (EVENT_BUS_BACKEND=nats):
# --build-arg FEATURES=sqlite,sqlite-federation,nats
ARG FEATURES=sqlite,sqlite-federation
RUN cargo build --release -p presentation -p worker --no-default-features --features "${FEATURES}"
RUN cargo build --release -p server -p worker --no-default-features --features "${FEATURES}"
# ----- runtime -----
FROM debian:bookworm-slim
@@ -85,13 +93,13 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
WORKDIR /app
COPY --from=builder /build/target/release/presentation ./presentation
COPY --from=builder /build/target/release/server ./server
COPY --from=builder /build/target/release/worker ./worker
COPY static ./static
COPY --from=spa-builder /spa/dist ./spa/dist
EXPOSE 3000
ENV RUST_LOG=presentation=info,tower_http=info
ENV RUST_LOG=server=info,tower_http=info
CMD ["./presentation"]
CMD ["./server"]

160
Makefile
View File

@@ -1,7 +1,7 @@
.DEFAULT_GOAL := check
# Run the full local check suite — same order as CI would.
check: fmt-check clippy test check-appcontext
check: fmt-check clippy test check-appcontext check-handler-deps check-handler-repos check-presentation-adapters check-federation-off-social check-social-crates-are-ap-free
@echo "✅ All checks passed"
# Enforce that no application use case imports AppContext (god-object guard).
@@ -13,6 +13,162 @@ check-appcontext:
fi
@echo "✅ No AppContext in application crate"
# Enforce that presentation never hand-builds a deps struct (composition-root guard).
# Catches struct literals (`FooDeps { ... }`) and conversions (`FooDeps::from(...)`) —
# both are the composition-root pattern that belongs in crates/composition.
#
# Scope is the whole crate, not just handlers/, so that factoring a
# `fn build_login_deps(state) -> LoginDeps { .. }` helper into a sibling module
# does not slip past the guard. One exclusion:
# src/tests/ — test fixtures legitimately assemble their own state
# `src/main.rs` used to be excluded too ("the binary IS the wiring root") before
# crates/server took over the binary (ADR-0006) — presentation is lib-only now, has no
# main.rs, and the exclusion was dropped rather than left pointing at a file that no
# longer exists.
# NOTE: `\s` is a GNU grep extension, not POSIX ERE. Fine on GNU/Ubuntu runners;
# would need `[[:space:]]` if this ever runs under BusyBox/Alpine grep.
check-handler-deps:
@if grep -rnE "[A-Za-z0-9_]*Deps(\s*\{|::from\()" crates/presentation/src --include="*.rs" --exclude-dir=tests | grep -q .; then \
echo "❌ hand-built deps struct found in presentation:"; \
grep -rnE "[A-Za-z0-9_]*Deps(\s*\{|::from\()" crates/presentation/src --include="*.rs" --exclude-dir=tests; \
exit 1; \
fi
@echo "✅ No hand-built deps structs in presentation"
# Enforce that presentation calls use cases only, never repository methods directly
# (ADR-0006's guard; ADR-0007 records the widening below).
#
# Was: two shape-matching grep passes for `repos.<field>.<method>(` and
# `repos.<field>.clone().<method>(`, needed because `AppContext.repos` was still a
# legitimate way to reach a repository — ~40 sites cloned an Arc out of it to pass
# positionally into a use case, so the guard had to distinguish that legal shape
# from an illegal direct call. That shape-matching was demonstrably incomplete: it
# matches `repos.<field>.<method>(` textually, so it cannot see a bare reference
# pass (`&repos.diary`, no call at all at the read site) or a `let`-bound access
# (`if let Some(x) = repos.federated_profile` then `x.method()` on the *binding*,
# not on `repos` itself). Both shapes existed in production code — Plan C2's Task 6
# review caught it, Task 7 fixed both — while the two-pass guard printed a clean
# ✅ the whole time. ADR-0006's "handlers call use cases only" was false at that
# line for as long as the hole existed.
#
# Now: Plan C2 deleted `AppContext.repos` entirely (ADR-0007), so there is no
# longer any legitimate reason for the substring `app_ctx.repos` to appear in
# production code — not a call, not a clone, not a reference, not a let-binding.
# That makes the rule trivial and unevadeable: any mention at all is an offender.
# No shape to match means no shape to miss.
#
# One exclusion: src/tests/ — test helpers still legitimately build a
# `Repositories` and call `composition::build_deps` to produce test state.
check-handler-repos:
@if grep -rn "app_ctx\.repos" crates/presentation/src --include="*.rs" --exclude-dir=tests | grep -q .; then \
echo "❌ app_ctx.repos referenced in presentation:"; \
grep -rn "app_ctx\.repos" crates/presentation/src --include="*.rs" --exclude-dir=tests; \
exit 1; \
fi
@echo "✅ No app_ctx.repos references in presentation"
# Enforce that presentation depends on at most one adapter crate.
#
# Presentation may name things that RENDER OUTPUT; it may not name things that
# REACH external systems or storage. `template-askama` is the HTML template
# engine, so it stays. See ADR-0008.
#
# This checks Cargo.toml rather than grepping src/, deliberately: `<crate>::`
# greps collide with same-named modules inside `application` and `presentation`
# (`auth::logout` is `application::auth`; `rss::get_user_feed` is
# `handlers::rss`), so the source-level grep cannot decide this. Every directory
# under crates/adapters/ is named exactly like its package, so directory names
# are a safe source of truth.
PRESENTATION_ALLOWED_ADAPTERS := template-askama
check-presentation-adapters:
@deps=$$(awk '/^\[dependencies\]/{f=1;next} /^\[/{f=0} f' crates/presentation/Cargo.toml \
| sed -n 's/^\([A-Za-z0-9_-]\{1,\}\)[[:space:]]*=.*/\1/p'); \
bad=""; \
for a in $$(ls crates/adapters); do \
case " $(PRESENTATION_ALLOWED_ADAPTERS) " in *" $$a "*) continue;; esac; \
if echo "$$deps" | grep -qx "$$a"; then bad="$$bad $$a"; fi; \
done; \
if [ -n "$$bad" ]; then \
echo "❌ presentation depends on adapter crate(s):$$bad"; \
echo " presentation may name renderers, not reachers — see ADR-0008."; \
exit 1; \
fi; \
echo "✅ presentation depends on no adapter crate but $(PRESENTATION_ALLOWED_ADAPTERS)"
# Enforce that the federation-off build wires real social behavior, not silent noops.
#
# With federation off, `NoopSocialCommand::follow` returns Ok(()) and writes nothing,
# and `NoopSocialQuery` always answers zero/empty. The write side is currently
# unreachable over HTTP (the social routes are federation-gated in presentation), but
# the query side is not: `get_local_profile`, `get_page_viewer` and `get_activity_feed`
# read it through fully ungated routes, so a noop there means a federation-off
# instance lies about its own follow graph on every profile view and activity feed
# request — contradicting ADR-0003, which established that local follows bypass
# ActivityPub entirely. `application::social::LocalSocialService` is what must be
# wired instead. See ADR-0009.
#
# Two checks, not one: absence of the noops is necessary but not sufficient — deleting
# the whole `#[cfg(not(feature = "federation"))]` wiring block would also make the
# first check pass, leaving federation-off with nothing wired at all, which is worse
# than the noops. So this also asserts `LocalSocialService` is present — and it must
# be present in the federation-OFF region specifically, not merely anywhere in the
# file: `LocalSocialService` is also constructed inside the federation-ON branch
# (feeding `CompositeSocialAdapter`), so a bare file-wide grep is satisfied by that
# occurrence alone and would not catch the federation-off block being deleted. The
# awk carves out the region from the first `#[cfg(not(feature = "federation"))]` to
# the next `#[cfg(feature = "federation")]` — the same kind of range
# `check-presentation-adapters` uses for `[dependencies]` — and greps only inside it.
# Not an occurrence count: that would work today but break the moment the two
# `LocalSocialService` constructions in `main.rs` are deduplicated (a recorded
# follow-up), which could legitimately drop the total to one.
#
# A grep rather than a test because the decision lives in `wire_dependencies()`, a
# private fn in a binary crate, unreachable from integration tests.
#
# Scope is the single file `crates/server/src/main.rs`, not the whole crate: it is the
# sole wiring site for these ports. `worker` and `tui` never name SocialCommand /
# FollowGraphQuery / BlockQuery at all, so there is nowhere else for the noops to
# reappear. Relocating the wiring out of main.rs would move it out of the guard's
# scope — widen this to `crates/server/src` if that ever happens.
check-federation-off-social:
@if grep -n "NoopSocialCommand\|NoopSocialQuery" crates/server/src/main.rs | grep -q .; then \
echo "❌ server wires social noops — federation-off would report an empty follow graph:"; \
grep -n "NoopSocialCommand\|NoopSocialQuery" crates/server/src/main.rs; \
exit 1; \
fi
@if ! awk '/cfg\(not\(feature = "federation"\)\)/ && !started {started=1} started && /cfg\(feature = "federation"\)/ {exit} started {print}' crates/server/src/main.rs | grep -q "LocalSocialService"; then \
echo "❌ LocalSocialService not wired in the federation-off region of crates/server/src/main.rs — federation-off has no social behavior wired at all, not even noops"; \
exit 1; \
fi
@echo "✅ server wires real social behavior in every configuration"
# Enforce that `<backend>-social` crates never depend on ActivityPub.
#
# ADR-0009's whole federation-optional property rests on one invariant: a
# `<backend>-social` crate speaks only `domain::ports`; a `<backend>-federation` crate
# speaks ActivityPub; the former must never depend on the latter. It holds today, and
# nothing but this guard enforces it. One manifest line —
# `k-ap = { version = "0.5.0", registry = "gitea" }` in a `-social` crate's Cargo.toml,
# the obvious move when someone wants to reuse a helper like `status_to_str` from
# `sqlite-federation/src/lib.rs` — would silently restore all 76 crates and 19MB that
# federation-off exists to shed, while `make check`, `cargo test` and CI all stay green
# without this guard to catch it. Matches `activitypub` with any suffix, so
# `activitypub_federation = "0.6"` (the upstream crate carrying all 76 transitives) is
# caught too, not just the local `activitypub` crate.
#
# Known gap: a dependency renamed via a `package = "k-ap"` key (`foo = { package =
# "k-ap", ... }`), or declared with a `[dependencies.k-ap]` table header instead of the
# inline form, would not match this line-level regex. Not attempted — nothing in the
# workspace does either today.
check-social-crates-are-ap-free:
@if grep -nE '^[[:space:]]*(k-ap|activitypub[A-Za-z0-9_-]*|[A-Za-z0-9_-]+-federation)[[:space:]]*=' crates/adapters/*-social/Cargo.toml | grep -q .; then \
echo "❌ social crate depends on ActivityPub:"; \
grep -nE '^[[:space:]]*(k-ap|activitypub[A-Za-z0-9_-]*|[A-Za-z0-9_-]+-federation)[[:space:]]*=' crates/adapters/*-social/Cargo.toml; \
exit 1; \
fi
@echo "✅ social crates depend on no k-ap, activitypub, or *-federation crate"
# Apply rustfmt to all files.
fmt:
cargo fmt
@@ -34,4 +190,4 @@ fix:
cargo fmt
cargo clippy --fix --allow-dirty --allow-staged
.PHONY: check fmt fmt-check clippy test fix
.PHONY: check fmt fmt-check clippy test fix check-appcontext check-handler-deps check-handler-repos check-presentation-adapters check-federation-off-social check-social-crates-are-ap-free

View File

@@ -47,7 +47,7 @@ Open `http://localhost:3000`. The HTTP server and background worker start togeth
## Features
- Log movies with a TMDB/OMDb ID or manual title/year/director, with a 05 rating and optional watch medium (cinema, streaming, TV, physical media, download, media server)
- Log movies with a TMDB/OMDb ID or manual title/year/director, with a 15 rating and optional watch medium (cinema, streaming, TV, physical media, download, media server)
- Edit reviews after the fact — update rating, comment, date, or watch medium via partial PATCH; each watch is still a separate record (re-watches tracked)
- Background poster fetching and storage (local filesystem or S3-compatible)
- Movie enrichment via TMDb — full cast, crew, genres, keywords, runtime, budget/revenue, ratings; fetched automatically on movie discovery and refreshed every 30 days; exposed via `GET /api/v1/movies/{id}/profile`
@@ -60,8 +60,9 @@ Open `http://localhost:3000`. The HTTP server and background worker start togeth
- Watchlist — add movies to watch later, per-user; federated watchlist entries visible for remote actors
- User profiles — display name, bio, avatar, banner, custom profile fields; editable via HTML settings page or REST API; account deletion broadcasts AP `Delete` actor activity; `alsoKnownAs` change triggers AP `Move` for account migration
- Jellyfin/Plex auto-import — media server sends a webhook on playback stop, movies land in a watch queue; review and confirm with a rating to create diary entries; per-user webhook tokens with SHA-256 auth; setup UI at `/settings/integrations`
- Annual Wrap-Up — Spotify Wrapped for movies: per-user and instance-wide year-in-review with stats (top directors, actors, genres, rating distribution, watch time, rewatches, budget analysis), shareable HTML page at `/wrapups/{user_id}/{year}`; admin-triggered or auto-generated in January
- Annual Wrap-Up — Spotify Wrapped for movies: per-user and instance-wide year-in-review with stats (top directors, actors, genres, rating distribution, watch time, watch medium breakdown, rewatches, budget analysis); directors/actors filtered by minimum watch count for statistical relevance; shareable HTML page at `/wrapups/{user_id}/{year}`; admin-triggered or auto-generated in January
- Goals — set a "watch N movies in YEAR" target with a progress bar; progress computed from existing reviews (backwards compatible); per-user federation toggle in settings; displayed on profile (SPA: interactive with create/edit/delete, classic HTML: read-only glassmorphic card)
- Profile trends — top directors, genre breakdown, rating distribution histogram, watch medium breakdown, monthly activity chart; all computed from the user's review history
- CSV and JSON diary export
- File importer: upload CSV, TSV, JSON, or XLSX from any source (Letterboxd, IMDb, etc.), map columns to domain fields via a step-by-step wizard or REST API, save mapping profiles for repeat imports
- REST API v1 (`/api/v1/`) with full feature parity with the HTML interface
@@ -89,10 +90,11 @@ Hexagonal (Ports & Adapters) with Domain-Driven Design:
```
api-types — shared REST API request/response DTOs (Serialize/Deserialize + utoipa schemas) + HtmlPageContext; used by presentation, tui, and template adapters
infra-wiring — shared infrastructure types (DbPool, EventBusBackend, AppConfig) used by both presentation and worker binaries
domain — pure types and CQRS port traits (MovieCommand/MovieQuery, WatchEventCommand/WatchEventQuery, GoalCommand/GoalQuery, DiaryQuery, PersonCommand/PersonQuery, SearchCommand/SearchPort, ImageFetcher, RssFeedRenderer), no external deps except serde
application — use cases (commands + queries), business logic orchestration; handlers delegate here for all domain logic
presentation — Axum HTTP router, OpenAPI spec assembly, Swagger UI + Scalar serving, composition root for the HTTP process
infra-wiring — shared infrastructure types (DbPool, EventBusBackend, AppConfig) used by both server and worker binaries
domain — pure types and CQRS port traits (MovieCommand/MovieQuery, WatchEventCommand/WatchEventQuery, GoalCommand/GoalQuery, DiaryQuery, PersonCommand/PersonQuery, SearchCommand/SearchPort, SocialCommand/SocialQuery, ImageFetcher, RssFeedRenderer), no external deps except serde
application — use cases (commands + queries), business logic orchestration; handlers delegate here for all domain logic; modules: auth, diary, goals, import, integrations, movies, person, search, social, users, watchlist, wrapup
presentation — Axum HTTP router, OpenAPI spec assembly, Swagger UI + Scalar serving; library crate, no binary of its own
server — owns the HTTP binary, backend-selection features (sqlite/postgres, federation), boots presentation's router
worker — standalone worker binary (event consumer, poster sync, federation)
adapters/
adapter-common — shared row-to-domain conversions, sqlx error mapping, date/uuid parsing utils
@@ -101,7 +103,7 @@ adapters/
postgres — PostgreSQL repository + connection factory
metadata — TMDB / OMDb HTTP client
poster-fetcher — downloads poster images
image-storage — stores images (posters + user avatars) on local filesystem or S3-compatible storage
object-storage — stores images (posters + user avatars) on local filesystem or S3-compatible storage
poster-sync — event handler: triggers poster fetch+store on MovieDiscovered
image-converter — optional background worker: converts stored images to AVIF or WebP; backfills existing images via a 24h periodic job
tmdb-enrichment — TMDb HTTP client implementing MovieEnrichmentClient and PersonEnrichmentClient; event handlers (MovieEnrichmentHandler, PersonEnrichmentHandler) live in the application layer
@@ -114,6 +116,7 @@ adapters/
event-payload — shared event serialization DTOs (used by all event bus adapters)
sqlite-event-queue — durable polling event queue backed by SQLite
postgres-event-queue — durable polling event queue backed by PostgreSQL
event-publisher — in-memory event channel (used in tests)
nats — NATS Core / JetStream event publisher and consumer
event-publisher — in-memory event channel (used in tests)
activitypub — ActivityPub federation adapter (follow, inbox/outbox, actor); delegates to k-ap for protocol internals
@@ -157,12 +160,12 @@ Copy `.env.example` to `.env` and set the values below. Required fields must be
| `RATE_LIMIT` | `60` | No | Requests per minute per IP |
| `ALLOW_REGISTRATION` | `true` | No | Set `false` to disable new sign-ups |
| `SECURE_COOKIES` | `true` | No | Must be `true` when serving over HTTPS |
| `RUST_LOG` | — | No | Log verbosity (e.g. `presentation=info,worker=info`) |
| `RUST_LOG` | — | No | Log verbosity (e.g. `server=info,worker=info`) |
| `CORS_ORIGINS` | `*` | No | Comma-separated allowed origins for SPA dev |
| `EVENT_BUS_BACKEND` | `db` | No | `db` (default) or `nats` |
| `NATS_URL` | — | NATS only | NATS connection URL (e.g. `nats://localhost:4222`) |
The `worker` binary must run alongside `presentation` to process events:
The `worker` binary must run alongside `server` to process events:
```bash
cargo run -p worker
@@ -171,11 +174,11 @@ cargo run -p worker
## Run
```bash
cargo run -p presentation # HTTP server (0.0.0.0:3000)
cargo run -p server # HTTP server (0.0.0.0:3000)
cargo run -p worker # event worker (poster sync, in a separate terminal)
```
The worker polls the event queue and must run alongside the presentation to process background tasks like poster fetching. Both processes share the same database.
The worker polls the event queue and must run alongside the server to process background tasks like poster fetching. Both processes share the same database.
## API
@@ -247,7 +250,7 @@ This builds and starts the HTTP server (port 3000) and event worker. Data is per
### Manual docker run
The image contains both `presentation` and `worker` binaries. Run them as separate containers sharing the same data volume:
The image contains both `server` and `worker` binaries. Run them as separate containers sharing the same data volume:
```bash
docker build -t movies-diary .

View File

@@ -24,6 +24,7 @@ graph TB
UC_INTEGRATIONS["integrations<br/>webhooks, watch_queue,<br/>confirm, dismiss"]
UC_SEARCH["search<br/>execute"]
UC_PERSON["person<br/>get, get_credits"]
UC_SOCIAL["social<br/>follow, unfollow,<br/>accept, reject, block"]
end
subgraph EventHandlers["Event Handlers"]
EH_MOVIE["MovieEnrichmentHandler<br/><i>on MovieEnrichmentRequested</i>"]
@@ -59,10 +60,10 @@ graph TB
M_SEARCH["SearchQuery,<br/>SearchResults"]
end
subgraph Ports["Port Traits (Interfaces)"]
P_REPOS["MovieCommand / MovieQuery<br/>ReviewRepository<br/>DiaryQuery / StatsRepository<br/>UserRepository<br/>WatchlistRepository<br/>WatchEventCommand / WatchEventQuery<br/>WebhookTokenRepository<br/>ImportSessionRepository<br/>MovieProfileRepository<br/>WrapUpRepository<br/>GoalCommand / GoalQuery<br/>UserSettingsRepository<br/>MovieDeduplicator"]
P_SERVICES["AuthService<br/>MetadataClient<br/>PosterFetcherClient<br/>ImageFetcher<br/>ObjectStorage<br/>EventPublisher<br/>EventConsumer<br/>PasswordHasher<br/>DiaryExporter<br/>DocumentParser<br/>RssFeedRenderer"]
P_SEARCH["SearchPort<br/>SearchCommand<br/>PersonQuery<br/>PersonCommand"]
P_FEDERATION["SocialQueryPort<br/>LocalApContentQuery<br/>RemoteWatchlistRepository<br/>RemoteGoalRepository"]
P_REPOS["MovieCommand / MovieQuery<br/>ReviewRepository<br/>DiaryQuery / StatsRepository<br/>UserRepository / UserProfileFieldsRepository<br/>WatchlistRepository<br/>WatchEventCommand / WatchEventQuery<br/>WebhookTokenRepository<br/>ImportSessionRepository / ImportProfileRepository<br/>MovieProfileRepository<br/>WrapUpRepository / WrapUpStatsQuery<br/>GoalCommand / GoalQuery<br/>UserSettingsRepository / RefreshSessionRepository<br/>MovieDeduplicator"]
P_SERVICES["AuthService<br/>MetadataClient / MovieEnrichmentClient<br/>PersonEnrichmentClient<br/>PosterFetcherClient<br/>ImageFetcher / ObjectStorage<br/>EventPublisher / EventConsumer<br/>PasswordHasher<br/>DiaryExporter / DocumentParser<br/>RssFeedRenderer / MediaServerParser"]
P_SEARCH["SearchPort / SearchCommand<br/>PersonQuery / PersonCommand<br/>FederatedProfileQuery"]
P_FEDERATION["SocialCommand / SocialQuery<br/>FederationAdminQuery<br/>LocalApContentQuery<br/>RemoteWatchlistRepository<br/>RemoteGoalRepository"]
end
subgraph DomainServices["Services (pure, no I/O)"]
DS_WRAPUP["WrapUpAnalyzer<br/><i>build_report, compute_*</i>"]
@@ -92,7 +93,9 @@ graph TB
end
subgraph Messaging["Messaging"]
A_NATS["nats<br/><i>JetStream / Core</i>"]
A_SQLITE_QUEUE["sqlite-event-queue<br/><i>Polling, dead-letter</i>"]
A_PG_QUEUE["postgres-event-queue<br/><i>Polling, dead-letter</i>"]
A_EVT_PUB["event-publisher<br/><i>In-memory (tests)</i>"]
A_PAYLOAD["event-payload<br/><i>Serde (de)serialization</i>"]
end
subgraph External["External Services"]

View File

@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2024"
[dependencies]
k-ap = { version = "0.4.1", registry = "gitea" }
k-ap = { version = "0.5.0", registry = "gitea" }
domain = { workspace = true }
axum = { workspace = true }
serde = { workspace = true }

View File

@@ -1,8 +1,7 @@
use std::sync::Arc;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use k_ap::{ApContentReader, ApObjectHandler};
use k_ap::{ApContentReader, ApObjectHandler, LocalObject};
use url::Url;
use crate::{
@@ -21,10 +20,9 @@ impl ApContentReader for CompositeObjectHandler {
async fn get_local_objects_page(
&self,
user_id: uuid::Uuid,
before: Option<DateTime<Utc>>,
before: Option<chrono::DateTime<chrono::Utc>>,
limit: usize,
) -> anyhow::Result<Vec<(Url, serde_json::Value, DateTime<Utc>)>> {
// Fetch from all three sources (watchlist/goals return all, reviews use DB pagination)
) -> anyhow::Result<Vec<LocalObject>> {
let fetch_limit = limit * 3;
let reviews = self
.review
@@ -39,16 +37,15 @@ impl ApContentReader for CompositeObjectHandler {
.get_local_objects_page(user_id, None, usize::MAX)
.await?;
let mut all: Vec<(Url, serde_json::Value, DateTime<Utc>)> = Vec::new();
let mut all: Vec<LocalObject> = Vec::new();
all.extend(reviews);
all.extend(watchlist);
all.extend(goals);
// Apply before filter and sort descending by timestamp
if let Some(before_ts) = before {
all.retain(|(_, _, ts)| *ts < before_ts);
all.retain(|obj| obj.published_at < before_ts);
}
all.sort_by_key(|b| std::cmp::Reverse(b.2));
all.sort_by_key(|obj| std::cmp::Reverse(obj.published_at));
all.truncate(limit);
Ok(all)
}

View File

@@ -8,7 +8,7 @@ use domain::{
GoalQuery, LocalApContentQuery, MovieQuery, ReviewRepository, StatsRepository,
UserFederationSettingsQuery,
},
value_objects::{MovieId, ReviewId, UserId},
value_objects::{InstanceIdentity, MovieId, ReviewId, UserId},
};
use std::sync::Arc;
@@ -25,7 +25,7 @@ pub struct ActivityPubEventHandler {
goal_repo: Arc<dyn GoalQuery>,
stats_repo: Arc<dyn StatsRepository>,
federation_settings: Arc<dyn UserFederationSettingsQuery>,
base_url: String,
instance: InstanceIdentity,
}
impl ActivityPubEventHandler {
@@ -38,7 +38,7 @@ impl ActivityPubEventHandler {
goal_repo: Arc<dyn GoalQuery>,
stats_repo: Arc<dyn StatsRepository>,
federation_settings: Arc<dyn UserFederationSettingsQuery>,
base_url: String,
instance: InstanceIdentity,
) -> Self {
Self {
ap_service,
@@ -48,7 +48,7 @@ impl ActivityPubEventHandler {
goal_repo,
stats_repo,
federation_settings,
base_url,
instance,
}
}
}
@@ -140,7 +140,7 @@ impl EventHandler for ActivityPubEventHandler {
.await
.map_err(|e| DomainError::InfrastructureError(e.to_string())),
DomainEvent::UserDeleted { user_id } => {
let ap_id = actor_url(&self.base_url, user_id.value());
let ap_id = actor_url(&self.instance, user_id.value());
self.ap_service
.broadcast_delete_to_followers(user_id.value(), ap_id)
.await
@@ -179,8 +179,8 @@ impl ActivityPubEventHandler {
None => return Ok(()),
};
let ap_id = review_url(&self.base_url, review_id);
let actor = actor_url(&self.base_url, user_id.value());
let ap_id = review_url(&self.instance, review_id);
let actor = actor_url(&self.instance, user_id.value());
let movie = self
.movie_repo
@@ -210,14 +210,14 @@ impl ActivityPubEventHandler {
poster_url: movie
.as_ref()
.and_then(|m| m.poster_path())
.map(|p| format!("{}/images/{}", self.base_url, p.value())),
base_url: self.base_url.clone(),
.map(|p| self.instance.image_url_for(p.value())),
base_url: self.instance.base_url().to_string(),
},
);
let json = serde_json::to_value(obj)?;
self.ap_service
.broadcast_create_note(user_id.value(), json, ApVisibility::Public, vec![])
.broadcast_create(user_id.value(), json, ApVisibility::Public, vec![])
.await?;
let year = review.watched_at().year() as u16;
@@ -245,8 +245,8 @@ impl ActivityPubEventHandler {
None => return Ok(()),
};
let ap_id = review_url(&self.base_url, review_id);
let actor = actor_url(&self.base_url, user_id.value());
let ap_id = review_url(&self.instance, review_id);
let actor = actor_url(&self.instance, user_id.value());
let movie = self
.movie_repo
@@ -276,14 +276,14 @@ impl ActivityPubEventHandler {
poster_url: movie
.as_ref()
.and_then(|m| m.poster_path())
.map(|p| format!("{}/images/{}", self.base_url, p.value())),
base_url: self.base_url.clone(),
.map(|p| self.instance.image_url_for(p.value())),
base_url: self.instance.base_url().to_string(),
},
);
let json = serde_json::to_value(obj)?;
self.ap_service
.broadcast_update_note(user_id.value(), json, ApVisibility::Public, vec![])
.broadcast_update(user_id.value(), json, ApVisibility::Public, vec![])
.await?;
Ok(())
@@ -294,7 +294,7 @@ impl ActivityPubEventHandler {
user_id: &UserId,
review_id: &ReviewId,
) -> anyhow::Result<()> {
let ap_id = review_url(&self.base_url, review_id);
let ap_id = review_url(&self.instance, review_id);
self.ap_service
.broadcast_delete_to_followers(user_id.value(), ap_id)
.await?;
@@ -320,8 +320,8 @@ impl ActivityPubEventHandler {
}
use crate::urls::watchlist_entry_url;
let ap_id = watchlist_entry_url(&self.base_url, user_id.value(), movie_id.value());
let actor = actor_url(&self.base_url, user_id.value());
let ap_id = watchlist_entry_url(&self.instance, user_id.value(), movie_id.value());
let actor = actor_url(&self.instance, user_id.value());
let poster_url = self
.movie_repo
@@ -331,7 +331,7 @@ impl ActivityPubEventHandler {
.flatten()
.and_then(|m| {
m.poster_path()
.map(|p| format!("{}/images/{}", self.base_url, p.value()))
.map(|p| self.instance.image_url_for(p.value()))
});
let added_at_utc =
@@ -344,12 +344,12 @@ impl ActivityPubEventHandler {
external_metadata_id: external_metadata_id.clone(),
poster_url,
added_at: added_at_utc,
base_url: self.base_url.clone(),
base_url: self.instance.base_url().to_string(),
});
let json = serde_json::to_value(obj)?;
self.ap_service
.broadcast_create_note(user_id.value(), json, ApVisibility::Public, vec![])
.broadcast_create(user_id.value(), json, ApVisibility::Public, vec![])
.await?;
Ok(())
}
@@ -360,7 +360,7 @@ impl ActivityPubEventHandler {
movie_id: &domain::value_objects::MovieId,
) -> anyhow::Result<()> {
use crate::urls::watchlist_entry_url;
let ap_id = watchlist_entry_url(&self.base_url, user_id.value(), movie_id.value());
let ap_id = watchlist_entry_url(&self.instance, user_id.value(), movie_id.value());
self.ap_service
.broadcast_delete_to_followers(user_id.value(), ap_id)
.await?;
@@ -383,7 +383,7 @@ impl ActivityPubEventHandler {
.map(|id| id.value().to_string());
let poster_url = movie
.poster_path()
.map(|p| format!("{}/images/{}", self.base_url, p.value()));
.map(|p| self.instance.image_url_for(p.value()));
for entry in entries {
let review = entry.review();
@@ -398,8 +398,8 @@ impl ActivityPubEventHandler {
continue;
}
let ap_id = review_url(&self.base_url, review.id());
let actor = actor_url(&self.base_url, user_id.value());
let ap_id = review_url(&self.instance, review.id());
let actor = actor_url(&self.instance, user_id.value());
let obj = review_to_ap_object(
review,
@@ -410,13 +410,13 @@ impl ActivityPubEventHandler {
release_year: movie.release_year().value(),
external_metadata_id: external_metadata_id.clone(),
poster_url: poster_url.clone(),
base_url: self.base_url.clone(),
base_url: self.instance.base_url().to_string(),
},
);
let json = serde_json::to_value(obj)?;
self.ap_service
.broadcast_update_note(user_id.value(), json, ApVisibility::Public, vec![])
.broadcast_update(user_id.value(), json, ApVisibility::Public, vec![])
.await?;
}
@@ -450,19 +450,19 @@ impl ActivityPubEventHandler {
.count_reviews_in_year(user_id, year)
.await
.unwrap_or(0);
let ap_id = goal_url(&self.base_url, user_id.value(), year);
let actor = actor_url(&self.base_url, user_id.value());
let ap_id = goal_url(&self.instance, user_id.value(), year);
let actor = actor_url(&self.instance, user_id.value());
let obj = goal_to_ap_object(
ap_id,
actor,
year,
goal.target_count(),
current,
&self.base_url,
self.instance.base_url(),
);
let json = serde_json::to_value(obj)?;
self.ap_service
.broadcast_update_note(user_id.value(), json, ApVisibility::Public, vec![])
.broadcast_update(user_id.value(), json, ApVisibility::Public, vec![])
.await?;
Ok(())
}
@@ -488,17 +488,24 @@ impl ActivityPubEventHandler {
.await
.unwrap_or(0);
let ap_id = goal_url(&self.base_url, user_id.value(), year);
let actor = actor_url(&self.base_url, user_id.value());
let obj = goal_to_ap_object(ap_id, actor, year, target_count, current, &self.base_url);
let ap_id = goal_url(&self.instance, user_id.value(), year);
let actor = actor_url(&self.instance, user_id.value());
let obj = goal_to_ap_object(
ap_id,
actor,
year,
target_count,
current,
self.instance.base_url(),
);
let json = serde_json::to_value(obj)?;
if is_create {
self.ap_service
.broadcast_create_note(user_id.value(), json, ApVisibility::Public, vec![])
.broadcast_create(user_id.value(), json, ApVisibility::Public, vec![])
.await?;
} else {
self.ap_service
.broadcast_update_note(user_id.value(), json, ApVisibility::Public, vec![])
.broadcast_update(user_id.value(), json, ApVisibility::Public, vec![])
.await?;
}
Ok(())
@@ -513,7 +520,7 @@ impl ActivityPubEventHandler {
if !flags.goals {
return Ok(());
}
let ap_id = goal_url(&self.base_url, user_id.value(), year);
let ap_id = goal_url(&self.instance, user_id.value(), year);
self.ap_service
.broadcast_delete_to_followers(user_id.value(), ap_id)
.await?;

View File

@@ -46,6 +46,28 @@ impl k_ap::EventPublisher for FederationEventBridge {
tracing::warn!(inbox = %inbox, error = %error, "federation delivery failed permanently");
Ok(())
}
FederationEvent::OutboundFollowAccepted {
local_user_id,
remote_actor_url,
outbox_url,
} => {
let identity = domain::value_objects::SocialIdentity::Remote {
actor_url: remote_actor_url,
};
self.domain_publisher
.publish(&DomainEvent::FollowAccepted {
owner: UserId::from_uuid(local_user_id),
requester: identity,
})
.await
.map_err(|e| anyhow::anyhow!(e.to_string()))?;
if let Some(outbox) = outbox_url {
tracing::info!(outbox = %outbox, "importing remote outbox after follow accepted");
// Handled by FollowBackfillHandler reacting to FollowAccepted
}
Ok(())
}
}
}
}

View File

@@ -0,0 +1,137 @@
use std::sync::Arc;
use async_trait::async_trait;
use domain::{
errors::DomainError,
models::{BlockedDomainInfo, FollowedActorInfo},
ports::{ApBackfillPort, ApDocumentPort, InstanceBlocklistPort},
};
use k_ap::ActivityPubService;
use uuid::Uuid;
/// Adapts the federation library's service to the three domain-owned ports.
///
/// A wrapper rather than a bare `impl ... for ActivityPubService` because the
/// orphan rule forbids implementing a foreign trait for a foreign type, and
/// from this crate both `ApDocumentPort` (owned by `domain`) and
/// `ActivityPubService` (owned by the external `k-ap` crate) are foreign.
///
/// One type carrying all three impls mirrors `CompositeSocialAdapter`, which
/// serves `SocialCommand`, `FollowGraphQuery`, and `BlockQuery` the same way.
pub struct ApServiceAdapter {
service: Arc<ActivityPubService>,
}
impl ApServiceAdapter {
pub fn new(service: Arc<ActivityPubService>) -> Self {
Self { service }
}
}
/// Single conversion point from the federation library's `anyhow` errors to
/// `DomainError`. The log line and the resulting error string reproduce what
/// `presentation::handlers::social::ap_to_domain` produced before the port
/// inversion moved the boundary here.
fn ap_err(e: anyhow::Error) -> DomainError {
tracing::error!("ActivityPub error: {:?}", e);
DomainError::InfrastructureError(e.to_string())
}
#[async_trait]
impl ApDocumentPort for ApServiceAdapter {
async fn actor_json(&self, user_id: &str) -> Result<String, DomainError> {
self.service.actor_json(user_id).await.map_err(ap_err)
}
async fn followers_collection_json(
&self,
user_id: Uuid,
page: Option<u32>,
) -> Result<String, DomainError> {
self.service
.followers_collection_json(user_id, page)
.await
.map_err(ap_err)
}
async fn following_collection_json(
&self,
user_id: Uuid,
page: Option<u32>,
) -> Result<String, DomainError> {
self.service
.following_collection_json(user_id, page)
.await
.map_err(ap_err)
}
}
#[async_trait]
impl InstanceBlocklistPort for ApServiceAdapter {
async fn get_blocked_domains(&self) -> Result<Vec<BlockedDomainInfo>, DomainError> {
let domains = self.service.get_blocked_domains().await.map_err(ap_err)?;
Ok(domains
.into_iter()
.map(|d| BlockedDomainInfo {
domain: d.domain,
reason: d.reason,
blocked_at: d.blocked_at,
})
.collect())
}
async fn add_blocked_domain(
&self,
domain: &str,
reason: Option<&str>,
) -> Result<(), DomainError> {
self.service
.add_blocked_domain(domain, reason)
.await
.map_err(ap_err)
}
async fn remove_blocked_domain(&self, domain: &str) -> Result<(), DomainError> {
self.service
.remove_blocked_domain(domain)
.await
.map_err(ap_err)
}
}
#[async_trait]
impl ApBackfillPort for ApServiceAdapter {
async fn get_following(
&self,
local_user_id: Uuid,
) -> Result<Vec<FollowedActorInfo>, DomainError> {
let actors = self
.service
.get_following(local_user_id)
.await
.map_err(ap_err)?;
Ok(actors
.into_iter()
.map(|a| FollowedActorInfo {
url: a.url,
outbox_url: a.outbox_url,
})
.collect())
}
async fn import_remote_outbox(
&self,
outbox_url: &str,
actor_url: &str,
) -> Result<(), DomainError> {
self.service
.import_remote_outbox(outbox_url, actor_url)
.await
.map_err(ap_err)
}
async fn run_backfill_for_follower(
&self,
owner_user_id: Uuid,
follower_inbox_url: String,
) -> Result<(), DomainError> {
self.service
.run_backfill_for_follower(owner_user_id, follower_inbox_url)
.await
.map_err(ap_err)
}
}

View File

@@ -5,9 +5,9 @@ use chrono::DateTime;
use domain::{
models::RemoteGoalEntry,
ports::{GoalQuery, RemoteGoalRepository},
value_objects::UserId,
value_objects::{InstanceIdentity, UserId},
};
use k_ap::{ApContentReader, ApObjectHandler};
use k_ap::{AS_PUBLIC, ApContentReader, ApObjectHandler, LocalObject};
use url::Url;
use crate::objects::{GoalObject, goal_to_ap_object};
@@ -16,7 +16,7 @@ use crate::urls::{actor_url, goal_url};
pub struct GoalObjectHandler {
pub remote_goal_repo: Arc<dyn RemoteGoalRepository>,
pub goal_repo: Arc<dyn GoalQuery>,
pub base_url: String,
pub instance: InstanceIdentity,
}
#[async_trait]
@@ -26,7 +26,7 @@ impl ApContentReader for GoalObjectHandler {
user_id: uuid::Uuid,
_before: Option<DateTime<chrono::Utc>>,
_limit: usize,
) -> anyhow::Result<Vec<(Url, serde_json::Value, DateTime<chrono::Utc>)>> {
) -> anyhow::Result<Vec<LocalObject>> {
let uid = UserId::from_uuid(user_id);
let goals = self
.goal_repo
@@ -34,10 +34,11 @@ impl ApContentReader for GoalObjectHandler {
.await
.map_err(|e| anyhow::anyhow!(e.to_string()))?;
let actor = actor_url(&self.base_url, user_id);
let actor = actor_url(&self.instance, user_id);
let follower_cc = format!("{}/followers", actor);
let mut results = Vec::new();
for goal in goals {
let ap_id = goal_url(&self.base_url, user_id, goal.year());
let ap_id = goal_url(&self.instance, user_id, goal.year());
let published = DateTime::from_naive_utc_and_offset(*goal.created_at(), chrono::Utc);
let obj = goal_to_ap_object(
ap_id.clone(),
@@ -45,9 +46,17 @@ impl ApContentReader for GoalObjectHandler {
goal.year(),
goal.target_count(),
0,
&self.base_url,
self.instance.base_url(),
);
results.push((ap_id, serde_json::to_value(obj)?, published));
results.push(LocalObject {
ap_id,
object: serde_json::to_value(obj)?,
published_at: published,
to: vec![AS_PUBLIC.to_string()],
cc: vec![follower_cc.clone()],
bto: vec![],
bcc: vec![],
});
}
Ok(results)
}

View File

@@ -1,11 +1,12 @@
pub mod composite_handler;
pub mod event_handler;
pub mod federation_event_bridge;
pub mod federation_ports;
pub mod goal_handler;
pub mod objects;
pub mod port;
pub mod remote_review_repository;
pub mod review_handler;
pub mod social_adapter;
pub(crate) mod urls;
pub mod user_adapter;
pub mod watchlist_handler;
@@ -17,27 +18,39 @@ pub const INSTANCE_ACTOR_ID: uuid::Uuid =
pub use k_ap::{
ActivityPubService, ActivityRepository, ActorRepository, ApContentReader, ApFederationConfig,
ApObjectHandler, ApUser, ApUserRepository, BlocklistRepository, FederationData,
FollowRepository, Follower, FollowerStatus, FollowingStatus, RemoteActor,
FollowRepository, Follower, FollowerStatus, FollowingStatus, LocalObject, RemoteActor,
};
pub use event_handler::ActivityPubEventHandler;
pub use port::{ActivityPubPort, NoopActivityPubService};
pub use federation_ports::ApServiceAdapter;
pub use remote_review_repository::{RemoteReviewRepository, RemoteReviewUpdate};
pub use review_handler::ReviewObjectHandler;
pub use social_adapter::CompositeSocialAdapter;
pub use user_adapter::DomainUserRepoAdapter;
pub type FederationRepos = (
std::sync::Arc<dyn ActivityRepository>,
std::sync::Arc<dyn FollowRepository>,
std::sync::Arc<dyn ActorRepository>,
std::sync::Arc<dyn BlocklistRepository>,
std::sync::Arc<dyn domain::ports::SocialQueryPort>,
std::sync::Arc<dyn RemoteReviewRepository>,
std::sync::Arc<dyn domain::ports::RemoteWatchlistRepository>,
);
pub struct FederationRepos {
pub activity: std::sync::Arc<dyn ActivityRepository>,
pub follow: std::sync::Arc<dyn FollowRepository>,
pub actor: std::sync::Arc<dyn ActorRepository>,
pub blocklist: std::sync::Arc<dyn BlocklistRepository>,
pub admin_query: std::sync::Arc<dyn domain::ports::FederationAdminQuery>,
pub review_store: std::sync::Arc<dyn RemoteReviewRepository>,
pub remote_watchlist: std::sync::Arc<dyn domain::ports::RemoteWatchlistRepository>,
pub follow_command: std::sync::Arc<dyn domain::ports::FollowCommand>,
pub follow_query: std::sync::Arc<dyn domain::ports::FollowQuery>,
}
pub struct ActivityPubWire {
pub service: std::sync::Arc<dyn ActivityPubPort>,
/// AP document serving. Prefer this over `service` from outside this crate.
pub document: std::sync::Arc<dyn domain::ports::ApDocumentPort>,
/// Instance domain blocklist. Prefer this over `service` from outside this crate.
pub blocklist: std::sync::Arc<dyn domain::ports::InstanceBlocklistPort>,
/// Post-follow content backfill. Prefer this over `service` from outside this crate.
pub backfill: std::sync::Arc<dyn domain::ports::ApBackfillPort>,
/// The concrete service, consumed by `crates/server` to construct
/// `CompositeSocialAdapter`. Everything else should use
/// `document`/`blocklist`/`backfill`.
pub service: std::sync::Arc<ActivityPubService>,
pub router: axum::Router,
pub event_handler: std::sync::Arc<dyn domain::ports::EventHandler>,
}
@@ -58,7 +71,9 @@ pub struct ActivityPubDeps {
pub stats_repo: std::sync::Arc<dyn domain::ports::StatsRepository>,
pub user_repo: std::sync::Arc<dyn domain::ports::UserRepository>,
pub federation_settings: std::sync::Arc<dyn domain::ports::UserFederationSettingsQuery>,
pub base_url: String,
pub follow_command: std::sync::Arc<dyn domain::ports::FollowCommand>,
pub follow_query: std::sync::Arc<dyn domain::ports::FollowQuery>,
pub instance: domain::value_objects::InstanceIdentity,
pub allow_registration: bool,
pub event_publisher: std::sync::Arc<dyn domain::ports::EventPublisher>,
}
@@ -80,7 +95,9 @@ pub async fn wire(deps: ActivityPubDeps) -> anyhow::Result<ActivityPubWire> {
stats_repo,
user_repo,
federation_settings,
base_url,
follow_command: _,
follow_query: _,
instance,
allow_registration,
event_publisher,
} = deps;
@@ -90,17 +107,17 @@ pub async fn wire(deps: ActivityPubDeps) -> anyhow::Result<ActivityPubWire> {
diary_repo,
review_store,
event_publisher: std::sync::Arc::clone(&event_publisher),
base_url: base_url.clone(),
instance: instance.clone(),
});
let watchlist_handler = std::sync::Arc::new(watchlist_handler::WatchlistObjectHandler {
remote_watchlist_repo,
content_query: std::sync::Arc::clone(&local_ap_content),
base_url: base_url.clone(),
instance: instance.clone(),
});
let goal_handler = std::sync::Arc::new(goal_handler::GoalObjectHandler {
remote_goal_repo,
goal_repo: std::sync::Arc::clone(&goal_repo),
base_url: base_url.clone(),
instance: instance.clone(),
});
let composite = std::sync::Arc::new(composite_handler::CompositeObjectHandler {
review: review_handler,
@@ -124,14 +141,14 @@ pub async fn wire(deps: ActivityPubDeps) -> anyhow::Result<ActivityPubWire> {
);
let concrete = std::sync::Arc::new(
ActivityPubService::builder(base_url.clone())
ActivityPubService::builder(instance.base_url().to_string())
.activity_repo(activity_repo)
.follow_repo(follow_repo)
.actor_repo(actor_repo)
.blocklist_repo(blocklist_repo)
.user_repo(std::sync::Arc::new(DomainUserRepoAdapter::new(
user_repo,
base_url.clone(),
instance.clone(),
)))
.signed_fetch_actor_id(INSTANCE_ACTOR_ID)
.content_reader(composite.clone() as std::sync::Arc<dyn ApContentReader>)
@@ -139,6 +156,10 @@ pub async fn wire(deps: ActivityPubDeps) -> anyhow::Result<ActivityPubWire> {
.event_publisher(fed_event_bridge)
.allow_registration(allow_registration)
.software_name("movies-diary")
.nodeinfo_metadata(serde_json::json!({
"nodeName": "movies-diary",
"nodeDescription": "A federated movie diary"
}))
.debug(federation_debug)
.build()
.await?,
@@ -153,11 +174,20 @@ pub async fn wire(deps: ActivityPubDeps) -> anyhow::Result<ActivityPubWire> {
goal_repo,
stats_repo,
federation_settings,
base_url,
instance,
)) as std::sync::Arc<dyn domain::ports::EventHandler>;
let ports = std::sync::Arc::new(federation_ports::ApServiceAdapter::new(
std::sync::Arc::clone(&concrete),
));
Ok(ActivityPubWire {
service: concrete as std::sync::Arc<dyn ActivityPubPort>,
document: std::sync::Arc::clone(&ports)
as std::sync::Arc<dyn domain::ports::ApDocumentPort>,
blocklist: std::sync::Arc::clone(&ports)
as std::sync::Arc<dyn domain::ports::InstanceBlocklistPort>,
backfill: ports as std::sync::Arc<dyn domain::ports::ApBackfillPort>,
service: concrete,
router,
event_handler,
})

View File

@@ -1,11 +1,17 @@
use chrono::{DateTime, Utc};
use k_ap::AS_PUBLIC;
use k_ap::NoteType;
use serde::{Deserialize, Serialize};
use url::Url;
use domain::models::Review;
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub(crate) enum ActivityStreamsType {
#[default]
Note,
Article,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApAttachment {
@@ -34,7 +40,7 @@ pub(crate) fn normalize_hashtag(title: &str) -> String {
#[serde(rename_all = "camelCase")]
pub struct ReviewObject {
#[serde(rename = "type")]
pub(crate) kind: NoteType,
pub(crate) kind: ActivityStreamsType,
pub(crate) id: Url,
pub(crate) attributed_to: Url,
pub(crate) content: String,
@@ -125,7 +131,7 @@ pub fn review_to_ap_object(review: &Review, input: ReviewApInput) -> ReviewObjec
};
ReviewObject {
kind: NoteType::default(),
kind: ActivityStreamsType::default(),
id: ap_id,
attributed_to: actor_url.clone(),
content,
@@ -150,7 +156,7 @@ pub fn review_to_ap_object(review: &Review, input: ReviewApInput) -> ReviewObjec
#[serde(rename_all = "camelCase")]
pub struct WatchlistObject {
#[serde(rename = "type")]
pub(crate) kind: NoteType,
pub(crate) kind: ActivityStreamsType,
pub(crate) id: Url,
pub(crate) attributed_to: Url,
pub(crate) content: String,
@@ -218,7 +224,7 @@ pub fn watchlist_to_ap_object(input: WatchlistApInput) -> WatchlistObject {
];
WatchlistObject {
kind: NoteType::default(),
kind: ActivityStreamsType::default(),
id: ap_id,
attributed_to: actor_url.clone(),
content,
@@ -240,7 +246,7 @@ pub fn watchlist_to_ap_object(input: WatchlistApInput) -> WatchlistObject {
#[serde(rename_all = "camelCase")]
pub struct GoalObject {
#[serde(rename = "type")]
pub(crate) kind: NoteType,
pub(crate) kind: ActivityStreamsType,
pub(crate) id: Url,
pub(crate) attributed_to: Url,
pub(crate) content: String,
@@ -277,7 +283,7 @@ pub fn goal_to_ap_object(
}];
GoalObject {
kind: NoteType::default(),
kind: ActivityStreamsType::default(),
id: ap_id,
attributed_to: actor_url.clone(),
content,

View File

@@ -1,210 +0,0 @@
use async_trait::async_trait;
use uuid::Uuid;
use k_ap::{ActivityPubService, BlockedDomain, RemoteActor};
#[async_trait]
pub trait ActivityPubPort: Send + Sync {
async fn actor_json(&self, user_id: &str) -> anyhow::Result<String>;
async fn count_following(&self, local_user_id: Uuid) -> anyhow::Result<usize>;
async fn count_accepted_followers(&self, local_user_id: Uuid) -> anyhow::Result<usize>;
async fn get_pending_followers(&self, local_user_id: Uuid) -> anyhow::Result<Vec<RemoteActor>>;
async fn follow(&self, local_user_id: Uuid, handle: &str) -> anyhow::Result<()>;
async fn unfollow(&self, local_user_id: Uuid, actor_url: &str) -> anyhow::Result<()>;
async fn accept_follower(
&self,
local_user_id: Uuid,
remote_actor_url: &str,
) -> anyhow::Result<()>;
async fn reject_follower(
&self,
local_user_id: Uuid,
remote_actor_url: &str,
) -> anyhow::Result<()>;
async fn get_following(&self, local_user_id: Uuid) -> anyhow::Result<Vec<RemoteActor>>;
async fn get_accepted_followers(&self, local_user_id: Uuid)
-> anyhow::Result<Vec<RemoteActor>>;
async fn remove_follower(&self, local_user_id: Uuid, actor_url: &str) -> anyhow::Result<()>;
async fn block_actor(&self, local_user_id: Uuid, actor_url: &str) -> anyhow::Result<()>;
async fn unblock_actor(&self, local_user_id: Uuid, actor_url: &str) -> anyhow::Result<()>;
async fn get_blocked_actors(&self, local_user_id: Uuid) -> anyhow::Result<Vec<RemoteActor>>;
async fn add_blocked_domain(&self, domain: &str, reason: Option<&str>) -> anyhow::Result<()>;
async fn remove_blocked_domain(&self, domain: &str) -> anyhow::Result<()>;
async fn get_blocked_domains(&self) -> anyhow::Result<Vec<BlockedDomain>>;
async fn import_remote_outbox(&self, outbox_url: &str, actor_url: &str) -> anyhow::Result<()>;
async fn followers_collection_json(
&self,
user_id: Uuid,
page: Option<u32>,
) -> anyhow::Result<String>;
async fn following_collection_json(
&self,
user_id: Uuid,
page: Option<u32>,
) -> anyhow::Result<String>;
async fn run_backfill_for_follower(
&self,
owner_user_id: Uuid,
follower_inbox_url: String,
) -> anyhow::Result<()>;
}
#[async_trait]
impl ActivityPubPort for ActivityPubService {
async fn actor_json(&self, user_id: &str) -> anyhow::Result<String> {
self.actor_json(user_id).await
}
async fn count_following(&self, local_user_id: Uuid) -> anyhow::Result<usize> {
self.count_following(local_user_id).await
}
async fn count_accepted_followers(&self, local_user_id: Uuid) -> anyhow::Result<usize> {
self.count_accepted_followers(local_user_id).await
}
async fn get_pending_followers(&self, local_user_id: Uuid) -> anyhow::Result<Vec<RemoteActor>> {
self.get_pending_followers(local_user_id).await
}
async fn follow(&self, local_user_id: Uuid, handle: &str) -> anyhow::Result<()> {
self.follow(local_user_id, handle).await
}
async fn unfollow(&self, local_user_id: Uuid, actor_url: &str) -> anyhow::Result<()> {
self.unfollow(local_user_id, actor_url).await
}
async fn accept_follower(
&self,
local_user_id: Uuid,
remote_actor_url: &str,
) -> anyhow::Result<()> {
self.accept_follower(local_user_id, remote_actor_url).await
}
async fn reject_follower(
&self,
local_user_id: Uuid,
remote_actor_url: &str,
) -> anyhow::Result<()> {
self.reject_follower(local_user_id, remote_actor_url).await
}
async fn get_following(&self, local_user_id: Uuid) -> anyhow::Result<Vec<RemoteActor>> {
self.get_following(local_user_id).await
}
async fn get_accepted_followers(
&self,
local_user_id: Uuid,
) -> anyhow::Result<Vec<RemoteActor>> {
self.get_accepted_followers(local_user_id).await
}
async fn remove_follower(&self, local_user_id: Uuid, actor_url: &str) -> anyhow::Result<()> {
self.remove_follower(local_user_id, actor_url).await
}
async fn block_actor(&self, local_user_id: Uuid, actor_url: &str) -> anyhow::Result<()> {
self.block_actor(local_user_id, actor_url).await
}
async fn unblock_actor(&self, local_user_id: Uuid, actor_url: &str) -> anyhow::Result<()> {
self.unblock_actor(local_user_id, actor_url).await
}
async fn get_blocked_actors(&self, local_user_id: Uuid) -> anyhow::Result<Vec<RemoteActor>> {
self.get_blocked_actors(local_user_id).await
}
async fn add_blocked_domain(&self, domain: &str, reason: Option<&str>) -> anyhow::Result<()> {
self.add_blocked_domain(domain, reason).await
}
async fn remove_blocked_domain(&self, domain: &str) -> anyhow::Result<()> {
self.remove_blocked_domain(domain).await
}
async fn get_blocked_domains(&self) -> anyhow::Result<Vec<BlockedDomain>> {
self.get_blocked_domains().await
}
async fn import_remote_outbox(&self, outbox_url: &str, actor_url: &str) -> anyhow::Result<()> {
self.import_remote_outbox(outbox_url, actor_url).await
}
async fn followers_collection_json(
&self,
user_id: Uuid,
page: Option<u32>,
) -> anyhow::Result<String> {
self.followers_collection_json(user_id, page).await
}
async fn following_collection_json(
&self,
user_id: Uuid,
page: Option<u32>,
) -> anyhow::Result<String> {
self.following_collection_json(user_id, page).await
}
async fn run_backfill_for_follower(
&self,
owner_user_id: Uuid,
follower_inbox_url: String,
) -> anyhow::Result<()> {
self.run_backfill_for_follower(owner_user_id, follower_inbox_url)
.await
}
}
pub struct NoopActivityPubService;
#[async_trait]
impl ActivityPubPort for NoopActivityPubService {
async fn actor_json(&self, _: &str) -> anyhow::Result<String> {
Ok(String::new())
}
async fn count_following(&self, _: Uuid) -> anyhow::Result<usize> {
Ok(0)
}
async fn count_accepted_followers(&self, _: Uuid) -> anyhow::Result<usize> {
Ok(0)
}
async fn get_pending_followers(&self, _: Uuid) -> anyhow::Result<Vec<RemoteActor>> {
Ok(vec![])
}
async fn follow(&self, _: Uuid, _: &str) -> anyhow::Result<()> {
Ok(())
}
async fn unfollow(&self, _: Uuid, _: &str) -> anyhow::Result<()> {
Ok(())
}
async fn accept_follower(&self, _: Uuid, _: &str) -> anyhow::Result<()> {
Ok(())
}
async fn reject_follower(&self, _: Uuid, _: &str) -> anyhow::Result<()> {
Ok(())
}
async fn get_following(&self, _: Uuid) -> anyhow::Result<Vec<RemoteActor>> {
Ok(vec![])
}
async fn get_accepted_followers(&self, _: Uuid) -> anyhow::Result<Vec<RemoteActor>> {
Ok(vec![])
}
async fn remove_follower(&self, _: Uuid, _: &str) -> anyhow::Result<()> {
Ok(())
}
async fn block_actor(&self, _: Uuid, _: &str) -> anyhow::Result<()> {
Ok(())
}
async fn unblock_actor(&self, _: Uuid, _: &str) -> anyhow::Result<()> {
Ok(())
}
async fn get_blocked_actors(&self, _: Uuid) -> anyhow::Result<Vec<RemoteActor>> {
Ok(vec![])
}
async fn add_blocked_domain(&self, _: &str, _: Option<&str>) -> anyhow::Result<()> {
Ok(())
}
async fn remove_blocked_domain(&self, _: &str) -> anyhow::Result<()> {
Ok(())
}
async fn get_blocked_domains(&self) -> anyhow::Result<Vec<BlockedDomain>> {
Ok(vec![])
}
async fn import_remote_outbox(&self, _: &str, _: &str) -> anyhow::Result<()> {
Ok(())
}
async fn followers_collection_json(&self, _: Uuid, _: Option<u32>) -> anyhow::Result<String> {
Ok(String::new())
}
async fn following_collection_json(&self, _: Uuid, _: Option<u32>) -> anyhow::Result<String> {
Ok(String::new())
}
async fn run_backfill_for_follower(&self, _: Uuid, _: String) -> anyhow::Result<()> {
Ok(())
}
}

View File

@@ -5,9 +5,11 @@ use domain::{
events::DomainEvent,
models::ReviewSource,
ports::{DiaryQuery, EventPublisher, LocalApContentQuery, MovieQuery},
value_objects::{Comment, ExternalMetadataId, MovieId, Rating, ReviewId, UserId},
value_objects::{
Comment, ExternalMetadataId, InstanceIdentity, MovieId, Rating, ReviewId, UserId,
},
};
use k_ap::{ApContentReader, ApObjectHandler};
use k_ap::{AS_PUBLIC, ApContentReader, ApObjectHandler, LocalObject};
use url::Url;
use crate::objects::{ReviewApInput, ReviewObject, review_to_ap_object};
@@ -20,7 +22,7 @@ pub struct ReviewObjectHandler {
pub diary_repo: Arc<dyn DiaryQuery>,
pub review_store: Arc<dyn RemoteReviewRepository>,
pub event_publisher: Arc<dyn EventPublisher>,
pub base_url: String,
pub instance: InstanceIdentity,
}
#[async_trait]
@@ -30,7 +32,7 @@ impl ApContentReader for ReviewObjectHandler {
user_id: uuid::Uuid,
before: Option<chrono::DateTime<chrono::Utc>>,
limit: usize,
) -> anyhow::Result<Vec<(url::Url, serde_json::Value, chrono::DateTime<chrono::Utc>)>> {
) -> anyhow::Result<Vec<LocalObject>> {
let domain_user_id = UserId::from_uuid(user_id);
let before_naive = before.map(|dt| dt.naive_utc());
let entries = self
@@ -39,17 +41,17 @@ impl ApContentReader for ReviewObjectHandler {
.await
.map_err(|e| anyhow::anyhow!(e.to_string()))?;
let actor = actor_url(&self.base_url, user_id);
let actor = actor_url(&self.instance, user_id);
let mut results = Vec::new();
for entry in entries {
let review = entry.review();
let published =
chrono::DateTime::from_naive_utc_and_offset(*review.watched_at(), chrono::Utc);
let movie = entry.movie();
let ap_id = review_url(&self.base_url, review.id());
let ap_id = review_url(&self.instance, review.id());
let poster_url = movie
.poster_path()
.map(|p| format!("{}/images/{}", self.base_url, p.value()));
.map(|p| self.instance.image_url_for(p.value()));
let obj = review_to_ap_object(
review,
@@ -62,10 +64,19 @@ impl ApContentReader for ReviewObjectHandler {
.external_metadata_id()
.map(|id| id.value().to_string()),
poster_url,
base_url: self.base_url.clone(),
base_url: self.instance.base_url().to_string(),
},
);
results.push((ap_id, serde_json::to_value(obj)?, published));
let follower_cc = format!("{}/followers", actor);
results.push(LocalObject {
ap_id,
object: serde_json::to_value(obj)?,
published_at: published,
to: vec![AS_PUBLIC.to_string()],
cc: vec![follower_cc],
bto: vec![],
bcc: vec![],
});
}
Ok(results)
}

View File

@@ -0,0 +1,207 @@
use std::sync::Arc;
use async_trait::async_trait;
use domain::{
errors::DomainError,
ports::{BlockQuery, FollowGraphQuery, LocalSocial, SocialCommand, UserRepository},
value_objects::{
FollowRelation, FollowTarget, InstanceIdentity, SocialActor, SocialIdentity, UserId,
},
};
use k_ap::ActivityPubService;
pub struct CompositeSocialAdapter {
local: Arc<dyn LocalSocial>,
ap_service: Arc<ActivityPubService>,
user_repo: Arc<dyn UserRepository>,
instance: InstanceIdentity,
}
impl CompositeSocialAdapter {
pub fn new(
local: Arc<dyn LocalSocial>,
ap_service: Arc<ActivityPubService>,
user_repo: Arc<dyn UserRepository>,
instance: InstanceIdentity,
) -> Self {
Self {
local,
ap_service,
user_repo,
instance,
}
}
}
fn ap_err(e: anyhow::Error) -> DomainError {
DomainError::InfrastructureError(e.to_string())
}
#[async_trait]
impl SocialCommand for CompositeSocialAdapter {
async fn follow(&self, follower: &UserId, target: &FollowTarget) -> Result<(), DomainError> {
let identity = self.local.resolve_target(target).await?;
if let SocialIdentity::Local(_) = identity {
return self.local.follow_resolved(follower, &identity).await;
}
let handle = match target {
FollowTarget::Handle(h) => h.clone(),
FollowTarget::Identity(id) => match id {
SocialIdentity::Local(uid) => {
let user = self
.user_repo
.find_by_id(uid)
.await?
.ok_or_else(|| DomainError::NotFound("User not found".into()))?;
self.instance.handle_for(user.username().value())
}
SocialIdentity::Remote { actor_url } => actor_url.clone(),
},
};
self.ap_service
.follow(follower.value(), &handle)
.await
.map_err(ap_err)
}
async fn unfollow(
&self,
follower: &UserId,
target: &SocialIdentity,
) -> Result<(), DomainError> {
match target {
SocialIdentity::Local(_) => self.local.unfollow(follower, target).await,
SocialIdentity::Remote { .. } => self
.ap_service
.unfollow(follower.value(), &self.instance.actor_url_of(target))
.await
.map_err(ap_err),
}
}
async fn accept_follow(
&self,
owner: &UserId,
requester: &SocialIdentity,
) -> Result<(), DomainError> {
match requester {
SocialIdentity::Local(_) => self.local.accept_follow(owner, requester).await,
SocialIdentity::Remote { .. } => self
.ap_service
.accept_follower(owner.value(), &self.instance.actor_url_of(requester))
.await
.map_err(ap_err),
}
}
async fn reject_follow(
&self,
owner: &UserId,
requester: &SocialIdentity,
) -> Result<(), DomainError> {
match requester {
SocialIdentity::Local(_) => self.local.reject_follow(owner, requester).await,
SocialIdentity::Remote { .. } => self
.ap_service
.reject_follower(owner.value(), &self.instance.actor_url_of(requester))
.await
.map_err(ap_err),
}
}
async fn remove_follower(
&self,
owner: &UserId,
follower: &SocialIdentity,
) -> Result<(), DomainError> {
match follower {
SocialIdentity::Local(_) => self.local.remove_follower(owner, follower).await,
SocialIdentity::Remote { .. } => self
.ap_service
.remove_follower(owner.value(), &self.instance.actor_url_of(follower))
.await
.map_err(ap_err),
}
}
async fn block(&self, blocker: &UserId, target: &SocialIdentity) -> Result<(), DomainError> {
let actor_url = self.instance.actor_url_of(target);
self.ap_service
.block_actor(blocker.value(), &actor_url)
.await
.map_err(ap_err)
}
async fn unblock(&self, blocker: &UserId, target: &SocialIdentity) -> Result<(), DomainError> {
let actor_url = self.instance.actor_url_of(target);
self.ap_service
.unblock_actor(blocker.value(), &actor_url)
.await
.map_err(ap_err)
}
}
#[async_trait]
impl FollowGraphQuery for CompositeSocialAdapter {
async fn get_following(&self, user: &UserId) -> Result<Vec<SocialActor>, DomainError> {
self.local.get_following(user).await
}
async fn get_followers(&self, user: &UserId) -> Result<Vec<SocialActor>, DomainError> {
self.local.get_followers(user).await
}
async fn get_pending_followers(&self, user: &UserId) -> Result<Vec<SocialActor>, DomainError> {
self.local.get_pending_followers(user).await
}
async fn get_pending_following(&self, user: &UserId) -> Result<Vec<SocialActor>, DomainError> {
self.local.get_pending_following(user).await
}
async fn count_following(&self, user: &UserId) -> Result<usize, DomainError> {
self.local.count_following(user).await
}
async fn count_followers(&self, user: &UserId) -> Result<usize, DomainError> {
self.local.count_followers(user).await
}
async fn count_pending_followers(&self, user: &UserId) -> Result<usize, DomainError> {
self.local.count_pending_followers(user).await
}
async fn get_relation(
&self,
viewer: &UserId,
target: &SocialIdentity,
) -> Result<FollowRelation, DomainError> {
self.local.get_relation(viewer, target).await
}
}
#[async_trait]
impl BlockQuery for CompositeSocialAdapter {
async fn get_blocked(&self, user: &UserId) -> Result<Vec<SocialActor>, DomainError> {
let actors = self
.ap_service
.get_blocked_actors(user.value())
.await
.map_err(ap_err)?;
Ok(actors
.into_iter()
.map(|a| {
let identity = self.instance.identify(&a.url);
SocialActor {
identity,
handle: a.handle,
display_name: a.display_name,
avatar_url: a.avatar_url,
}
})
.collect())
}
}

View File

@@ -1,28 +1,43 @@
use domain::value_objects::ReviewId;
use domain::value_objects::{InstanceIdentity, ReviewId, UserId};
use url::Url;
/// Builds the canonical actor URL: `{base_url}/users/{user_id}`
pub fn actor_url(base_url: &str, user_id: uuid::Uuid) -> Url {
Url::parse(&format!("{}/users/{}", base_url, user_id))
pub fn actor_url(instance: &InstanceIdentity, user_id: uuid::Uuid) -> Url {
Url::parse(&instance.actor_url_for(&UserId::from_uuid(user_id)))
.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")
}
pub fn goal_url(base_url: &str, user_id: uuid::Uuid, year: u16) -> Url {
Url::parse(&format!("{}/users/{}/goals/{}", base_url, user_id, year))
.expect("base_url is always a valid URL prefix")
}
/// Builds the canonical watchlist entry URL: `{base_url}/users/{user_id}/watchlist/{movie_id}`
pub fn watchlist_entry_url(base_url: &str, user_id: uuid::Uuid, movie_id: uuid::Uuid) -> Url {
pub fn review_url(instance: &InstanceIdentity, review_id: &ReviewId) -> Url {
Url::parse(&format!(
"{}/users/{}/watchlist/{}",
base_url, user_id, movie_id
"{}/reviews/{}",
instance.base_url(),
review_id.value()
))
.expect("base_url is always a valid URL prefix")
}
pub fn goal_url(instance: &InstanceIdentity, user_id: uuid::Uuid, year: u16) -> Url {
Url::parse(&format!(
"{}/users/{}/goals/{}",
instance.base_url(),
user_id,
year
))
.expect("base_url is always a valid URL prefix")
}
/// Builds the canonical watchlist entry URL: `{base_url}/users/{user_id}/watchlist/{movie_id}`
pub fn watchlist_entry_url(
instance: &InstanceIdentity,
user_id: uuid::Uuid,
movie_id: uuid::Uuid,
) -> Url {
Url::parse(&format!(
"{}/users/{}/watchlist/{}",
instance.base_url(),
user_id,
movie_id
))
.expect("base_url is always a valid URL prefix")
}

View File

@@ -1,28 +1,36 @@
use std::sync::Arc;
use async_trait::async_trait;
use domain::{ports::UserRepository, value_objects::UserId};
use domain::{
ports::UserRepository,
value_objects::{InstanceIdentity, UserId},
};
use k_ap::{ApProfileField, ApUser, ApUserRepository};
use url::Url;
pub struct DomainUserRepoAdapter {
pub repo: Arc<dyn UserRepository>,
pub base_url: String,
pub instance: InstanceIdentity,
}
impl DomainUserRepoAdapter {
pub fn new(repo: Arc<dyn UserRepository>, base_url: String) -> Self {
Self { repo, base_url }
pub fn new(repo: Arc<dyn UserRepository>, instance: InstanceIdentity) -> Self {
Self { repo, instance }
}
fn build_user(&self, u: &domain::models::User) -> ApUser {
let avatar_url = u
.avatar_path()
.and_then(|p| Url::parse(&format!("{}/images/{}", self.base_url, p)).ok());
.and_then(|p| Url::parse(&self.instance.image_url_for(p)).ok());
let banner_url = u
.banner_path()
.and_then(|p| Url::parse(&format!("{}/images/{}", self.base_url, p)).ok());
let profile_url = Url::parse(&format!("{}/u/{}", self.base_url, u.username().value())).ok();
.and_then(|p| Url::parse(&self.instance.image_url_for(p)).ok());
let profile_url = Url::parse(&format!(
"{}/u/{}",
self.instance.base_url(),
u.username().value()
))
.ok();
ApUser {
id: u.id().value(),
username: u.username().value().to_string(),
@@ -46,12 +54,8 @@ impl DomainUserRepoAdapter {
manually_approves_followers: true,
discoverable: true,
actor_type: Default::default(),
featured_url: Url::parse(&format!(
"{}/users/{}/featured",
self.base_url,
u.id().value()
))
.ok(),
featured_url: Url::parse(&format!("{}/featured", self.instance.actor_url_for(u.id())))
.ok(),
}
}
}

View File

@@ -5,9 +5,9 @@ use chrono::DateTime;
use domain::{
models::{RemoteWatchlistEntry, WatchlistWithMovie},
ports::{LocalApContentQuery, RemoteWatchlistRepository},
value_objects::UserId,
value_objects::{InstanceIdentity, UserId},
};
use k_ap::{ApContentReader, ApObjectHandler};
use k_ap::{AS_PUBLIC, ApContentReader, ApObjectHandler, LocalObject};
use url::Url;
use crate::objects::{WatchlistApInput, WatchlistObject, watchlist_to_ap_object};
@@ -16,7 +16,7 @@ use crate::urls::{actor_url, watchlist_entry_url};
pub struct WatchlistObjectHandler {
pub remote_watchlist_repo: Arc<dyn RemoteWatchlistRepository>,
pub content_query: Arc<dyn LocalApContentQuery>,
pub base_url: String,
pub instance: InstanceIdentity,
}
#[async_trait]
@@ -26,7 +26,7 @@ impl ApContentReader for WatchlistObjectHandler {
user_id: uuid::Uuid,
_before: Option<DateTime<chrono::Utc>>,
_limit: usize,
) -> anyhow::Result<Vec<(Url, serde_json::Value, DateTime<chrono::Utc>)>> {
) -> anyhow::Result<Vec<LocalObject>> {
let uid = UserId::from_uuid(user_id);
let entries = self
.content_query
@@ -34,14 +34,15 @@ impl ApContentReader for WatchlistObjectHandler {
.await
.map_err(|e| anyhow::anyhow!(e.to_string()))?;
let actor = actor_url(&self.base_url, user_id);
let actor = actor_url(&self.instance, user_id);
let follower_cc = format!("{}/followers", actor);
let mut results = Vec::new();
for WatchlistWithMovie { entry, movie } in entries {
let ap_id = watchlist_entry_url(&self.base_url, user_id, entry.movie_id.value());
let ap_id = watchlist_entry_url(&self.instance, user_id, entry.movie_id.value());
let published = DateTime::from_naive_utc_and_offset(entry.added_at, chrono::Utc);
let poster_url = movie
.poster_path()
.map(|p| format!("{}/images/{}", self.base_url, p.value()));
.map(|p| self.instance.image_url_for(p.value()));
let obj = watchlist_to_ap_object(WatchlistApInput {
ap_id: ap_id.clone(),
actor_url: actor.clone(),
@@ -52,9 +53,17 @@ impl ApContentReader for WatchlistObjectHandler {
.map(|id| id.value().to_string()),
poster_url,
added_at: published,
base_url: self.base_url.clone(),
base_url: self.instance.base_url().to_string(),
});
results.push(LocalObject {
ap_id,
object: serde_json::to_value(obj)?,
published_at: published,
to: vec![AS_PUBLIC.to_string()],
cc: vec![follower_cc.clone()],
bto: vec![],
bcc: vec![],
});
results.push((ap_id, serde_json::to_value(obj)?, published));
}
Ok(results)
}

View File

@@ -4,7 +4,8 @@ use domain::{
events::DomainEvent,
models::{ExternalPersonId, PersonId},
value_objects::{
ExternalMetadataId, GoalId, MovieId, PosterPath, Rating, ReviewId, UserId, WrapUpId,
ExternalMetadataId, GoalId, MovieId, PosterPath, Rating, ReviewId, SocialIdentity, UserId,
WrapUpId,
},
};
use serde::{Deserialize, Serialize};
@@ -61,10 +62,40 @@ pub enum EventPayload {
user_id: String,
movie_id: String,
},
FollowRequested {
follower_id: String,
target_kind: String,
target_id: String,
},
FollowAccepted {
local_user_id: String,
remote_actor_url: String,
outbox_url: String,
owner_id: String,
requester_kind: String,
requester_id: String,
},
FollowRejected {
owner_id: String,
requester_kind: String,
requester_id: String,
},
Unfollowed {
follower_id: String,
target_kind: String,
target_id: String,
},
FollowerRemoved {
owner_id: String,
follower_kind: String,
follower_id: String,
},
ActorBlocked {
blocker_id: String,
target_kind: String,
target_id: String,
},
ActorUnblocked {
blocker_id: String,
target_kind: String,
target_id: String,
},
BackfillFollower {
owner_user_id: String,
@@ -136,7 +167,13 @@ impl EventPayload {
EventPayload::ImageStored { .. } => "ImageStored",
EventPayload::WatchlistEntryAdded { .. } => "WatchlistEntryAdded",
EventPayload::WatchlistEntryRemoved { .. } => "WatchlistEntryRemoved",
EventPayload::FollowRequested { .. } => "FollowRequested",
EventPayload::FollowAccepted { .. } => "FollowAccepted",
EventPayload::FollowRejected { .. } => "FollowRejected",
EventPayload::Unfollowed { .. } => "Unfollowed",
EventPayload::FollowerRemoved { .. } => "FollowerRemoved",
EventPayload::ActorBlocked { .. } => "ActorBlocked",
EventPayload::ActorUnblocked { .. } => "ActorUnblocked",
EventPayload::BackfillFollower { .. } => "BackfillFollower",
EventPayload::FederationDeliveryRequested { .. } => "FederationDeliveryRequested",
EventPayload::WatchEventIngested { .. } => "WatchEventIngested",
@@ -158,6 +195,44 @@ fn parse_uuid(s: &str, field: &str) -> Result<Uuid, DomainError> {
Uuid::parse_str(s).map_err(|e| DomainError::InfrastructureError(format!("{field}: {e}")))
}
fn identity_to_payload(id: &SocialIdentity) -> (String, String) {
match id {
SocialIdentity::Local(uid) => ("local".into(), uid.value().to_string()),
SocialIdentity::Remote { actor_url } => ("remote".into(), actor_url.clone()),
}
}
fn follow_target_to_payload(target: &domain::value_objects::FollowTarget) -> (String, String) {
match target {
domain::value_objects::FollowTarget::Identity(id) => identity_to_payload(id),
domain::value_objects::FollowTarget::Handle(h) => ("handle".into(), h.clone()),
}
}
fn payload_to_identity(kind: &str, id: String) -> Result<SocialIdentity, DomainError> {
match kind {
"local" => Ok(SocialIdentity::Local(UserId::from_uuid(parse_uuid(
&id, "user_id",
)?))),
"remote" => Ok(SocialIdentity::Remote { actor_url: id }),
other => Err(DomainError::InfrastructureError(format!(
"unknown identity kind: {other}"
))),
}
}
fn payload_to_follow_target(
kind: &str,
id: String,
) -> Result<domain::value_objects::FollowTarget, DomainError> {
match kind {
"handle" => Ok(domain::value_objects::FollowTarget::Handle(id)),
other => Ok(domain::value_objects::FollowTarget::Identity(
payload_to_identity(other, id)?,
)),
}
}
fn parse_ts(ts: i64) -> Result<NaiveDateTime, DomainError> {
chrono::DateTime::from_timestamp(ts, 0)
.map(|dt| dt.naive_utc())
@@ -243,15 +318,62 @@ impl From<&DomainEvent> for EventPayload {
movie_id: movie_id.value().to_string(),
}
}
DomainEvent::FollowAccepted {
local_user_id,
remote_actor_url,
outbox_url,
} => EventPayload::FollowAccepted {
local_user_id: local_user_id.value().to_string(),
remote_actor_url: remote_actor_url.clone(),
outbox_url: outbox_url.clone(),
},
DomainEvent::FollowRequested { follower, target } => {
let (kind, id) = follow_target_to_payload(target);
EventPayload::FollowRequested {
follower_id: follower.value().to_string(),
target_kind: kind,
target_id: id,
}
}
DomainEvent::FollowAccepted { owner, requester } => {
let (kind, id) = identity_to_payload(requester);
EventPayload::FollowAccepted {
owner_id: owner.value().to_string(),
requester_kind: kind,
requester_id: id,
}
}
DomainEvent::FollowRejected { owner, requester } => {
let (kind, id) = identity_to_payload(requester);
EventPayload::FollowRejected {
owner_id: owner.value().to_string(),
requester_kind: kind,
requester_id: id,
}
}
DomainEvent::Unfollowed { follower, target } => {
let (kind, id) = identity_to_payload(target);
EventPayload::Unfollowed {
follower_id: follower.value().to_string(),
target_kind: kind,
target_id: id,
}
}
DomainEvent::FollowerRemoved { owner, follower } => {
let (kind, id) = identity_to_payload(follower);
EventPayload::FollowerRemoved {
owner_id: owner.value().to_string(),
follower_kind: kind,
follower_id: id,
}
}
DomainEvent::ActorBlocked { blocker, target } => {
let (kind, id) = identity_to_payload(target);
EventPayload::ActorBlocked {
blocker_id: blocker.value().to_string(),
target_kind: kind,
target_id: id,
}
}
DomainEvent::ActorUnblocked { blocker, target } => {
let (kind, id) = identity_to_payload(target);
EventPayload::ActorUnblocked {
blocker_id: blocker.value().to_string(),
target_kind: kind,
target_id: id,
}
}
DomainEvent::BackfillFollower {
owner_user_id,
follower_inbox_url,
@@ -435,14 +557,61 @@ impl TryFrom<EventPayload> for DomainEvent {
movie_id: MovieId::from_uuid(parse_uuid(&movie_id, "movie_id")?),
})
}
EventPayload::FollowRequested {
follower_id,
target_kind,
target_id,
} => Ok(DomainEvent::FollowRequested {
follower: UserId::from_uuid(parse_uuid(&follower_id, "follower_id")?),
target: payload_to_follow_target(&target_kind, target_id)?,
}),
EventPayload::FollowAccepted {
local_user_id,
remote_actor_url,
outbox_url,
owner_id,
requester_kind,
requester_id,
} => Ok(DomainEvent::FollowAccepted {
local_user_id: UserId::from_uuid(parse_uuid(&local_user_id, "local_user_id")?),
remote_actor_url,
outbox_url,
owner: UserId::from_uuid(parse_uuid(&owner_id, "owner_id")?),
requester: payload_to_identity(&requester_kind, requester_id)?,
}),
EventPayload::FollowRejected {
owner_id,
requester_kind,
requester_id,
} => Ok(DomainEvent::FollowRejected {
owner: UserId::from_uuid(parse_uuid(&owner_id, "owner_id")?),
requester: payload_to_identity(&requester_kind, requester_id)?,
}),
EventPayload::Unfollowed {
follower_id,
target_kind,
target_id,
} => Ok(DomainEvent::Unfollowed {
follower: UserId::from_uuid(parse_uuid(&follower_id, "follower_id")?),
target: payload_to_identity(&target_kind, target_id)?,
}),
EventPayload::FollowerRemoved {
owner_id,
follower_kind,
follower_id,
} => Ok(DomainEvent::FollowerRemoved {
owner: UserId::from_uuid(parse_uuid(&owner_id, "owner_id")?),
follower: payload_to_identity(&follower_kind, follower_id)?,
}),
EventPayload::ActorBlocked {
blocker_id,
target_kind,
target_id,
} => Ok(DomainEvent::ActorBlocked {
blocker: UserId::from_uuid(parse_uuid(&blocker_id, "blocker_id")?),
target: payload_to_identity(&target_kind, target_id)?,
}),
EventPayload::ActorUnblocked {
blocker_id,
target_kind,
target_id,
} => Ok(DomainEvent::ActorUnblocked {
blocker: UserId::from_uuid(parse_uuid(&blocker_id, "blocker_id")?),
target: payload_to_identity(&target_kind, target_id)?,
}),
EventPayload::BackfillFollower {
owner_user_id,

View File

@@ -12,7 +12,13 @@ pub fn event_to_subject(prefix: &str, event: &DomainEvent) -> String {
DomainEvent::ImageStored { .. } => "image.stored",
DomainEvent::WatchlistEntryAdded { .. } => "watchlist.entry.added",
DomainEvent::WatchlistEntryRemoved { .. } => "watchlist.entry.removed",
DomainEvent::FollowRequested { .. } => "follow.requested",
DomainEvent::FollowAccepted { .. } => "follow.accepted",
DomainEvent::FollowRejected { .. } => "follow.rejected",
DomainEvent::Unfollowed { .. } => "follow.unfollowed",
DomainEvent::FollowerRemoved { .. } => "follower.removed",
DomainEvent::ActorBlocked { .. } => "actor.blocked",
DomainEvent::ActorUnblocked { .. } => "actor.unblocked",
DomainEvent::BackfillFollower { .. } => "backfill.follower",
DomainEvent::FederationDeliveryRequested { .. } => "federation.delivery.requested",
DomainEvent::WatchEventIngested { .. } => "watch.event.ingested",

View File

@@ -13,7 +13,8 @@ sqlx = { version = "0.8.6", features = [
] }
activitypub = { workspace = true }
adapter-common = { workspace = true }
k-ap = { version = "0.4.1", registry = "gitea" }
k-ap = { version = "0.5.0", registry = "gitea" }
postgres-social = { workspace = true }
domain = { workspace = true }
uuid = { workspace = true }
chrono = { workspace = true }

View File

@@ -1,43 +1,41 @@
use anyhow::Result;
use async_trait::async_trait;
use chrono::Utc;
use k_ap::{ActorRepository, RemoteActor};
use k_ap::{AnnounceRepository, Keypair, KeypairRepository, RemoteActor, RemoteActorCache};
use sqlx::Row;
use super::{PG_ACTOR_COLS, PostgresFederationRepository, pg_remote_actor};
use adapter_common::datetime_to_str;
#[async_trait]
impl ActorRepository for PostgresFederationRepository {
async fn get_local_actor_keypair(
&self,
user_id: uuid::Uuid,
) -> Result<Option<(String, String)>> {
impl KeypairRepository for PostgresFederationRepository {
async fn get_local_actor_keypair(&self, user_id: uuid::Uuid) -> Result<Option<Keypair>> {
let uid = user_id.to_string();
let row =
sqlx::query("SELECT public_key, private_key FROM ap_local_actors WHERE user_id = $1")
.bind(&uid)
.fetch_optional(&self.pool)
.await?;
Ok(row.map(|r| (r.get("public_key"), r.get("private_key"))))
Ok(row.map(|r| Keypair {
public_key: r.get("public_key"),
private_key: r.get("private_key"),
}))
}
async fn save_local_actor_keypair(
&self,
user_id: uuid::Uuid,
public_key: String,
private_key: String,
) -> Result<()> {
async fn save_local_actor_keypair(&self, user_id: uuid::Uuid, keypair: Keypair) -> Result<()> {
let uid = user_id.to_string();
let now = Utc::now().naive_utc();
let created_at = datetime_to_str(&now);
sqlx::query(
"INSERT INTO ap_local_actors (user_id, public_key, private_key, created_at) VALUES ($1, $2, $3, $4::timestamptz)
ON CONFLICT(user_id) DO UPDATE SET public_key = EXCLUDED.public_key, private_key = EXCLUDED.private_key",
).bind(&uid).bind(&public_key).bind(&private_key).bind(&created_at).execute(&self.pool).await?;
).bind(&uid).bind(&keypair.public_key).bind(&keypair.private_key).bind(&created_at).execute(&self.pool).await?;
Ok(())
}
}
#[async_trait]
impl RemoteActorCache for PostgresFederationRepository {
async fn upsert_remote_actor(&self, actor: RemoteActor) -> Result<()> {
let now = Utc::now().naive_utc();
let fetched_at = datetime_to_str(&now);
@@ -68,7 +66,10 @@ impl ActorRepository for PostgresFederationRepository {
.await?;
Ok(row.as_ref().map(|r| pg_remote_actor(r, "url")))
}
}
#[async_trait]
impl AnnounceRepository for PostgresFederationRepository {
async fn add_announce(
&self,
activity_id: &str,

View File

@@ -1,14 +1,14 @@
use anyhow::Result;
use async_trait::async_trait;
use chrono::Utc;
use k_ap::{BlockedDomain, BlocklistRepository};
use k_ap::{ActorBlocklist, BlockedDomain, DomainBlocklist};
use sqlx::Row;
use super::PostgresFederationRepository;
use adapter_common::datetime_to_str;
#[async_trait]
impl BlocklistRepository for PostgresFederationRepository {
impl DomainBlocklist for PostgresFederationRepository {
async fn add_blocked_domain(&self, domain: &str, reason: Option<&str>) -> Result<()> {
let ts = datetime_to_str(&Utc::now().naive_utc());
sqlx::query("INSERT INTO blocked_domains (domain, reason, blocked_at) VALUES ($1, $2, $3) ON CONFLICT(domain) DO UPDATE SET reason = EXCLUDED.reason")
@@ -48,7 +48,10 @@ impl BlocklistRepository for PostgresFederationRepository {
.await?;
Ok(count > 0)
}
}
#[async_trait]
impl ActorBlocklist for PostgresFederationRepository {
async fn add_blocked_actor(&self, local_user_id: uuid::Uuid, actor_url: &str) -> Result<()> {
let uid = local_user_id.to_string();
let ts = datetime_to_str(&Utc::now().naive_utc());

View File

@@ -1,18 +1,16 @@
use anyhow::Result;
use async_trait::async_trait;
use chrono::Utc;
use k_ap::{
ActorRepository, FollowRepository, Follower, FollowerStatus, FollowingStatus, RemoteActor,
};
use k_ap::{Follower, FollowerReader, FollowerStatus, FollowerWriter, RemoteActor};
use sqlx::Row;
use super::{
use crate::{
PG_ACTOR_COLS, PostgresFederationRepository, pg_remote_actor, status_to_str, str_to_status,
};
use adapter_common::datetime_to_str;
#[async_trait]
impl FollowRepository for PostgresFederationRepository {
impl FollowerWriter for PostgresFederationRepository {
async fn add_follower(
&self,
local_user_id: uuid::Uuid,
@@ -59,6 +57,25 @@ impl FollowRepository for PostgresFederationRepository {
Ok(())
}
async fn update_follower_status(
&self,
local_user_id: uuid::Uuid,
remote_actor_url: &str,
status: FollowerStatus,
) -> Result<()> {
let uid = local_user_id.to_string();
let status_str = status_to_str(&status);
let result = sqlx::query("UPDATE ap_followers SET status = $1 WHERE local_user_id = $2 AND remote_actor_url = $3")
.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, remote_actor_url, "update_follower_status: no row found");
}
Ok(())
}
}
#[async_trait]
impl FollowerReader for PostgresFederationRepository {
async fn get_followers(&self, local_user_id: uuid::Uuid) -> Result<Vec<Follower>> {
let uid = local_user_id.to_string();
let q = format!(
@@ -116,22 +133,6 @@ impl FollowRepository for PostgresFederationRepository {
Ok(count as usize)
}
async fn update_follower_status(
&self,
local_user_id: uuid::Uuid,
remote_actor_url: &str,
status: FollowerStatus,
) -> Result<()> {
let uid = local_user_id.to_string();
let status_str = status_to_str(&status);
let result = sqlx::query("UPDATE ap_followers SET status = $1 WHERE local_user_id = $2 AND remote_actor_url = $3")
.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, remote_actor_url, "update_follower_status: no row found");
}
Ok(())
}
async fn get_pending_followers(&self, local_user_id: uuid::Uuid) -> Result<Vec<RemoteActor>> {
let uid = local_user_id.to_string();
let q = format!(
@@ -193,129 +194,4 @@ impl FollowRepository for PostgresFederationRepository {
.map(|row| pg_remote_actor(row, "remote_actor_url"))
.collect())
}
async fn add_following(
&self,
local_user_id: uuid::Uuid,
actor: RemoteActor,
follow_activity_id: &str,
) -> Result<()> {
let uid = local_user_id.to_string();
let now = Utc::now().naive_utc();
let created_at = datetime_to_str(&now);
ActorRepository::upsert_remote_actor(self, actor.clone()).await?;
sqlx::query("INSERT INTO ap_following (local_user_id, remote_actor_url, follow_activity_id, created_at) VALUES ($1, $2, $3, $4::timestamptz) ON CONFLICT DO NOTHING")
.bind(&uid).bind(&actor.url).bind(follow_activity_id).bind(&created_at).execute(&self.pool).await?;
Ok(())
}
async fn get_follow_activity_id(
&self,
local_user_id: uuid::Uuid,
remote_actor_url: &str,
) -> Result<Option<String>> {
let uid = local_user_id.to_string();
let row: Option<String> = sqlx::query_scalar("SELECT follow_activity_id FROM ap_following WHERE local_user_id = $1 AND remote_actor_url = $2")
.bind(&uid).bind(remote_actor_url).fetch_optional(&self.pool).await?;
Ok(row)
}
async fn remove_following(&self, local_user_id: uuid::Uuid, actor_url: &str) -> Result<()> {
let uid = local_user_id.to_string();
sqlx::query("DELETE FROM ap_following WHERE local_user_id = $1 AND remote_actor_url = $2")
.bind(&uid)
.bind(actor_url)
.execute(&self.pool)
.await?;
Ok(())
}
async fn get_following(&self, local_user_id: uuid::Uuid) -> Result<Vec<RemoteActor>> {
let uid = local_user_id.to_string();
let q = format!(
"SELECT a.url, {PG_ACTOR_COLS} FROM ap_following f INNER JOIN ap_remote_actors a ON a.url = f.remote_actor_url WHERE f.local_user_id = $1 AND f.status = 'accepted'"
);
let rows = sqlx::query(&q).bind(&uid).fetch_all(&self.pool).await?;
Ok(rows.iter().map(|row| pg_remote_actor(row, "url")).collect())
}
async fn count_following(&self, local_user_id: uuid::Uuid) -> Result<usize> {
let uid = local_user_id.to_string();
let count: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM ap_following WHERE local_user_id = $1 AND status = 'accepted'",
)
.bind(&uid)
.fetch_one(&self.pool)
.await?;
Ok(count as usize)
}
async fn get_following_page(
&self,
local_user_id: uuid::Uuid,
offset: u32,
limit: usize,
) -> Result<Vec<RemoteActor>> {
let uid = local_user_id.to_string();
let q = format!(
"SELECT a.url, {PG_ACTOR_COLS} FROM ap_following f INNER JOIN ap_remote_actors a ON a.url = f.remote_actor_url WHERE f.local_user_id = $1 AND f.status = 'accepted' ORDER BY f.created_at ASC LIMIT $2 OFFSET $3"
);
let rows = sqlx::query(&q)
.bind(&uid)
.bind(limit as i64)
.bind(offset as i64)
.fetch_all(&self.pool)
.await?;
Ok(rows.iter().map(|row| pg_remote_actor(row, "url")).collect())
}
async fn update_following_status(
&self,
local_user_id: uuid::Uuid,
remote_actor_url: &str,
status: FollowingStatus,
) -> Result<()> {
let uid = local_user_id.to_string();
let status_str = match status {
FollowingStatus::Pending => "pending",
FollowingStatus::Accepted => "accepted",
};
let result = sqlx::query("UPDATE ap_following SET status = $1 WHERE local_user_id = $2 AND remote_actor_url = $3")
.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, remote_actor_url, "update_following_status: no row found");
}
Ok(())
}
async fn get_following_outbox_url(
&self,
local_user_id: uuid::Uuid,
remote_actor_url: &str,
) -> Result<Option<String>> {
let uid = local_user_id.to_string();
let row: Option<Option<String>> = sqlx::query_scalar(
"SELECT a.outbox_url FROM ap_following f INNER JOIN ap_remote_actors a ON a.url = f.remote_actor_url WHERE f.local_user_id = $1 AND f.remote_actor_url = $2",
).bind(&uid).bind(remote_actor_url).fetch_optional(&self.pool).await?;
Ok(row.flatten())
}
async fn migrate_follower_actor(
&self,
old_actor_url: &str,
new_actor_url: &str,
) -> Result<Vec<uuid::Uuid>> {
let candidates: Vec<String> = sqlx::query_scalar(
"SELECT local_user_id FROM ap_following WHERE remote_actor_url = $1 AND local_user_id NOT IN (SELECT local_user_id FROM ap_following WHERE remote_actor_url = $2)",
).bind(old_actor_url).bind(new_actor_url).fetch_all(&self.pool).await?;
if candidates.is_empty() {
return Ok(vec![]);
}
sqlx::query("UPDATE ap_following SET remote_actor_url = $1 WHERE remote_actor_url = $2 AND local_user_id NOT IN (SELECT local_user_id FROM ap_following WHERE remote_actor_url = $1)")
.bind(new_actor_url).bind(old_actor_url).execute(&self.pool).await?;
candidates
.into_iter()
.map(|s| uuid::Uuid::parse_str(&s).map_err(|e| anyhow::anyhow!(e)))
.collect()
}
}

View File

@@ -0,0 +1,106 @@
use crate::{PG_ACTOR_COLS, PostgresFederationRepository, pg_remote_actor};
use adapter_common::datetime_to_str;
use anyhow::Result;
use async_trait::async_trait;
use chrono::Utc;
use k_ap::{FollowingReader, FollowingStatus, FollowingWriter, RemoteActor, RemoteActorCache};
#[async_trait]
impl FollowingWriter for PostgresFederationRepository {
async fn add_following(
&self,
local_user_id: uuid::Uuid,
actor: RemoteActor,
follow_activity_id: &str,
) -> Result<()> {
let uid = local_user_id.to_string();
let now = Utc::now().naive_utc();
let created_at = datetime_to_str(&now);
RemoteActorCache::upsert_remote_actor(self, actor.clone()).await?;
sqlx::query("INSERT INTO ap_following (local_user_id, remote_actor_url, follow_activity_id, created_at) VALUES ($1, $2, $3, $4::timestamptz) ON CONFLICT DO NOTHING")
.bind(&uid).bind(&actor.url).bind(follow_activity_id).bind(&created_at).execute(&self.pool).await?;
Ok(())
}
async fn get_follow_activity_id(
&self,
local_user_id: uuid::Uuid,
remote_actor_url: &str,
) -> Result<Option<String>> {
let uid = local_user_id.to_string();
let row: Option<String> = sqlx::query_scalar("SELECT follow_activity_id FROM ap_following WHERE local_user_id = $1 AND remote_actor_url = $2")
.bind(&uid).bind(remote_actor_url).fetch_optional(&self.pool).await?;
Ok(row)
}
async fn remove_following(&self, local_user_id: uuid::Uuid, actor_url: &str) -> Result<()> {
let uid = local_user_id.to_string();
sqlx::query("DELETE FROM ap_following WHERE local_user_id = $1 AND remote_actor_url = $2")
.bind(&uid)
.bind(actor_url)
.execute(&self.pool)
.await?;
Ok(())
}
async fn update_following_status(
&self,
local_user_id: uuid::Uuid,
remote_actor_url: &str,
status: FollowingStatus,
) -> Result<()> {
let uid = local_user_id.to_string();
let status_str = match status {
FollowingStatus::Pending => "pending",
FollowingStatus::Accepted => "accepted",
};
let result = sqlx::query("UPDATE ap_following SET status = $1 WHERE local_user_id = $2 AND remote_actor_url = $3")
.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, remote_actor_url, "update_following_status: no row found");
}
Ok(())
}
}
#[async_trait]
impl FollowingReader for PostgresFederationRepository {
async fn get_following(&self, local_user_id: uuid::Uuid) -> Result<Vec<RemoteActor>> {
let uid = local_user_id.to_string();
let q = format!(
"SELECT a.url, {PG_ACTOR_COLS} FROM ap_following f INNER JOIN ap_remote_actors a ON a.url = f.remote_actor_url WHERE f.local_user_id = $1 AND f.status = 'accepted'"
);
let rows = sqlx::query(&q).bind(&uid).fetch_all(&self.pool).await?;
Ok(rows.iter().map(|row| pg_remote_actor(row, "url")).collect())
}
async fn count_following(&self, local_user_id: uuid::Uuid) -> Result<usize> {
let uid = local_user_id.to_string();
let count: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM ap_following WHERE local_user_id = $1 AND status = 'accepted'",
)
.bind(&uid)
.fetch_one(&self.pool)
.await?;
Ok(count as usize)
}
async fn get_following_page(
&self,
local_user_id: uuid::Uuid,
offset: u32,
limit: usize,
) -> Result<Vec<RemoteActor>> {
let uid = local_user_id.to_string();
let q = format!(
"SELECT a.url, {PG_ACTOR_COLS} FROM ap_following f INNER JOIN ap_remote_actors a ON a.url = f.remote_actor_url WHERE f.local_user_id = $1 AND f.status = 'accepted' ORDER BY f.created_at ASC LIMIT $2 OFFSET $3"
);
let rows = sqlx::query(&q)
.bind(&uid)
.bind(limit as i64)
.bind(offset as i64)
.fetch_all(&self.pool)
.await?;
Ok(rows.iter().map(|row| pg_remote_actor(row, "url")).collect())
}
}

View File

@@ -0,0 +1,27 @@
use anyhow::Result;
use async_trait::async_trait;
use k_ap::FollowMigration;
use crate::PostgresFederationRepository;
#[async_trait]
impl FollowMigration for PostgresFederationRepository {
async fn migrate_follower_actor(
&self,
old_actor_url: &str,
new_actor_url: &str,
) -> Result<Vec<uuid::Uuid>> {
let candidates: Vec<String> = sqlx::query_scalar(
"SELECT local_user_id FROM ap_following WHERE remote_actor_url = $1 AND local_user_id NOT IN (SELECT local_user_id FROM ap_following WHERE remote_actor_url = $2)",
).bind(old_actor_url).bind(new_actor_url).fetch_all(&self.pool).await?;
if candidates.is_empty() {
return Ok(vec![]);
}
sqlx::query("UPDATE ap_following SET remote_actor_url = $1 WHERE remote_actor_url = $2 AND local_user_id NOT IN (SELECT local_user_id FROM ap_following WHERE remote_actor_url = $1)")
.bind(new_actor_url).bind(old_actor_url).execute(&self.pool).await?;
candidates
.into_iter()
.map(|s| uuid::Uuid::parse_str(&s).map_err(|e| anyhow::anyhow!(e)))
.collect()
}
}

View File

@@ -0,0 +1,3 @@
mod followers;
mod following;
mod migration;

View File

@@ -1,16 +1,8 @@
mod activity;
mod actor;
pub mod ap_content;
mod blocklist;
mod federated_profile;
mod follow;
pub mod remote_goals;
mod review;
mod social;
mod watchlist;
pub use ap_content::PostgresApContentQuery;
pub use remote_goals::PostgresRemoteGoalRepository;
use k_ap::{FollowerStatus, RemoteActor};
use sqlx::{PgPool, Row};
@@ -71,21 +63,23 @@ impl PostgresFederationRepository {
}
}
pub fn create_federated_profile_query(
pub fn wire(
pool: PgPool,
) -> std::sync::Arc<dyn domain::ports::FederatedProfileQuery> {
std::sync::Arc::new(PostgresFederationRepository::new(pool))
}
pub fn wire(pool: PgPool) -> activitypub::FederationRepos {
let fed = std::sync::Arc::new(PostgresFederationRepository::new(pool));
(
std::sync::Arc::clone(&fed) as _,
std::sync::Arc::clone(&fed) as _,
std::sync::Arc::clone(&fed) as _,
std::sync::Arc::clone(&fed) as _,
std::sync::Arc::clone(&fed) as _,
std::sync::Arc::clone(&fed) as _,
fed as _,
)
instance: domain::value_objects::InstanceIdentity,
) -> activitypub::FederationRepos {
let fed = std::sync::Arc::new(PostgresFederationRepository::new(pool.clone()));
let social = std::sync::Arc::new(postgres_social::PostgresSocialRepository::new(
pool, instance,
));
activitypub::FederationRepos {
activity: std::sync::Arc::clone(&fed) as _,
follow: std::sync::Arc::clone(&fed) as _,
actor: std::sync::Arc::clone(&fed) as _,
blocklist: std::sync::Arc::clone(&fed) as _,
review_store: fed as _,
admin_query: std::sync::Arc::clone(&social) as _,
remote_watchlist: std::sync::Arc::clone(&social) as _,
follow_command: std::sync::Arc::clone(&social) as _,
follow_query: social as _,
}
}

View File

@@ -1,82 +0,0 @@
use async_trait::async_trait;
use domain::{
errors::DomainError,
models::{PendingFollowerInfo, RemoteActorInfo},
ports::SocialQueryPort,
value_objects::UserId,
};
use super::PostgresFederationRepository;
#[async_trait]
impl SocialQueryPort for PostgresFederationRepository {
async fn get_accepted_following_urls(
&self,
user_id: &UserId,
) -> Result<Vec<String>, DomainError> {
let user_id_str = user_id.value().to_string();
sqlx::query_scalar::<_, String>(
"SELECT remote_actor_url FROM ap_following WHERE local_user_id = $1 AND status = 'accepted'",
).bind(&user_id_str).fetch_all(&self.pool).await
.map_err(|e| DomainError::InfrastructureError(e.to_string()))
}
async fn list_all_followed_remote_actors(&self) -> Result<Vec<RemoteActorInfo>, DomainError> {
let rows = sqlx::query_as::<_, (String, String, Option<String>)>(
"SELECT DISTINCT ar.url, ar.handle, ar.display_name FROM ap_remote_actors ar JOIN ap_following f ON f.remote_actor_url = ar.url WHERE f.status = 'accepted'",
).fetch_all(&self.pool).await.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
Ok(rows
.into_iter()
.map(|(url, handle, display_name)| RemoteActorInfo {
url,
handle,
display_name,
})
.collect())
}
async fn count_following(&self, user_id: &UserId) -> Result<usize, DomainError> {
let uid = user_id.value().to_string();
let count: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM ap_following WHERE local_user_id = $1 AND status = 'accepted'",
)
.bind(&uid)
.fetch_one(&self.pool)
.await
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
Ok(count as usize)
}
async fn count_accepted_followers(&self, user_id: &UserId) -> Result<usize, DomainError> {
let uid = user_id.value().to_string();
let count: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM ap_followers WHERE local_user_id = $1 AND status = 'accepted'",
)
.bind(&uid)
.fetch_one(&self.pool)
.await
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
Ok(count as usize)
}
async fn get_pending_followers(
&self,
user_id: &UserId,
) -> Result<Vec<PendingFollowerInfo>, DomainError> {
let uid = user_id.value().to_string();
let rows = sqlx::query_as::<_, (String, String, Option<String>, Option<String>)>(
"SELECT ar.url, ar.handle, ar.display_name, ar.avatar_url FROM ap_followers f JOIN ap_remote_actors ar ON ar.url = f.remote_actor_url WHERE f.local_user_id = $1 AND f.status = 'pending'",
).bind(&uid).fetch_all(&self.pool).await.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
Ok(rows
.into_iter()
.map(
|(url, handle, display_name, avatar_url)| PendingFollowerInfo {
url,
handle,
display_name,
avatar_url,
},
)
.collect())
}
}

View File

@@ -0,0 +1,18 @@
[package]
name = "postgres-social"
version = "0.1.0"
edition = "2024"
[dependencies]
sqlx = { version = "0.8.6", features = [
"runtime-tokio-rustls",
"postgres",
"uuid",
"macros",
"chrono",
] }
adapter-common = { workspace = true }
domain = { workspace = true }
uuid = { workspace = true }
chrono = { workspace = true }
async-trait = { workspace = true }

View File

@@ -2,10 +2,10 @@ use async_trait::async_trait;
use domain::{errors::DomainError, models::FederatedProfile, ports::FederatedProfileQuery};
use sqlx::Row;
use super::PostgresFederationRepository;
use super::PostgresSocialRepository;
#[async_trait]
impl FederatedProfileQuery for PostgresFederationRepository {
impl FederatedProfileQuery for PostgresSocialRepository {
async fn get_federated_profile(
&self,
synthetic_user_id: uuid::Uuid,

View File

@@ -0,0 +1,354 @@
use async_trait::async_trait;
use chrono::Utc;
use domain::{
errors::DomainError,
value_objects::{FollowRelation, FollowStatus, InstanceIdentity, SocialActor, SocialIdentity},
};
use sqlx::Row;
use crate::PostgresSocialRepository;
use adapter_common::datetime_to_str;
fn follow_status_to_str(status: &FollowStatus) -> &'static str {
match status {
FollowStatus::Pending => "pending",
FollowStatus::Accepted => "accepted",
FollowStatus::Rejected => "rejected",
}
}
fn infra_err(e: impl std::fmt::Display) -> DomainError {
DomainError::InfrastructureError(e.to_string())
}
fn follow_status_from_str(status: &str) -> Option<FollowStatus> {
match status {
"pending" => Some(FollowStatus::Pending),
"accepted" => Some(FollowStatus::Accepted),
"rejected" => Some(FollowStatus::Rejected),
_ => None,
}
}
#[async_trait]
impl domain::ports::FollowCommand for PostgresSocialRepository {
async fn add_follow(
&self,
follower_id: uuid::Uuid,
target_actor_url: &str,
status: FollowStatus,
) -> Result<(), DomainError> {
let uid = follower_id.to_string();
let status_str = follow_status_to_str(&status);
let now = datetime_to_str(&Utc::now().naive_utc());
sqlx::query(
"INSERT INTO ap_following (local_user_id, remote_actor_url, follow_activity_id, created_at, status)
VALUES ($1, $2, '', $3::timestamptz, $4)
ON CONFLICT(local_user_id, remote_actor_url) DO UPDATE SET status = EXCLUDED.status",
)
.bind(&uid)
.bind(target_actor_url)
.bind(&now)
.bind(status_str)
.execute(&self.pool)
.await
.map_err(infra_err)?;
Ok(())
}
async fn update_follow_status(
&self,
follower_id: uuid::Uuid,
target_actor_url: &str,
status: FollowStatus,
) -> Result<(), DomainError> {
let uid = follower_id.to_string();
let status_str = follow_status_to_str(&status);
sqlx::query(
"UPDATE ap_following SET status = $1 WHERE local_user_id = $2 AND remote_actor_url = $3",
)
.bind(status_str)
.bind(&uid)
.bind(target_actor_url)
.execute(&self.pool)
.await
.map_err(infra_err)?;
Ok(())
}
async fn remove_follow(
&self,
follower_id: uuid::Uuid,
target_actor_url: &str,
) -> Result<(), DomainError> {
let uid = follower_id.to_string();
sqlx::query("DELETE FROM ap_following WHERE local_user_id = $1 AND remote_actor_url = $2")
.bind(&uid)
.bind(target_actor_url)
.execute(&self.pool)
.await
.map_err(infra_err)?;
Ok(())
}
async fn add_follower(
&self,
local_user_id: uuid::Uuid,
follower_actor_url: &str,
status: FollowStatus,
) -> Result<(), DomainError> {
let uid = local_user_id.to_string();
let status_str = follow_status_to_str(&status);
let now = datetime_to_str(&Utc::now().naive_utc());
sqlx::query(
"INSERT INTO ap_followers (local_user_id, remote_actor_url, status, created_at, follow_activity_id)
VALUES ($1, $2, $3, $4::timestamptz, '')
ON CONFLICT(local_user_id, remote_actor_url) DO UPDATE SET status = EXCLUDED.status",
)
.bind(&uid)
.bind(follower_actor_url)
.bind(status_str)
.bind(&now)
.execute(&self.pool)
.await
.map_err(infra_err)?;
Ok(())
}
async fn update_follower_status(
&self,
local_user_id: uuid::Uuid,
follower_actor_url: &str,
status: FollowStatus,
) -> Result<(), DomainError> {
let uid = local_user_id.to_string();
let status_str = follow_status_to_str(&status);
sqlx::query(
"UPDATE ap_followers SET status = $1 WHERE local_user_id = $2 AND remote_actor_url = $3",
)
.bind(status_str)
.bind(&uid)
.bind(follower_actor_url)
.execute(&self.pool)
.await
.map_err(infra_err)?;
Ok(())
}
async fn remove_follower_record(
&self,
local_user_id: uuid::Uuid,
follower_actor_url: &str,
) -> Result<(), DomainError> {
let uid = local_user_id.to_string();
sqlx::query("DELETE FROM ap_followers WHERE local_user_id = $1 AND remote_actor_url = $2")
.bind(&uid)
.bind(follower_actor_url)
.execute(&self.pool)
.await
.map_err(infra_err)?;
Ok(())
}
}
fn social_actor_from_row(row: &sqlx::postgres::PgRow, instance: &InstanceIdentity) -> SocialActor {
let actor_url: String = row.get("remote_actor_url");
let identity = instance.identify(&actor_url);
let (handle, display_name, avatar_url) = match &identity {
SocialIdentity::Local(_) => {
let username: Option<String> = row.try_get("local_username").ok().flatten();
let display: Option<String> = row.try_get("local_display").ok().flatten();
let avatar: Option<String> = row
.try_get::<Option<String>, _>("local_avatar_path")
.ok()
.flatten()
.map(|p| instance.image_url_for(&p));
let handle = username
.as_deref()
.map(|u| instance.handle_for(u))
.unwrap_or_else(|| actor_url.clone());
(handle, display, avatar)
}
SocialIdentity::Remote { .. } => {
let handle: String = row
.try_get::<Option<String>, _>("remote_handle")
.ok()
.flatten()
.unwrap_or_else(|| actor_url.clone());
let display: Option<String> = row.try_get("remote_display").ok().flatten();
let avatar: Option<String> = row.try_get("remote_avatar").ok().flatten();
(handle, display, avatar)
}
};
SocialActor {
identity,
handle,
display_name,
avatar_url,
}
}
#[async_trait]
impl domain::ports::FollowQuery for PostgresSocialRepository {
async fn get_following(&self, user_id: uuid::Uuid) -> Result<Vec<SocialActor>, DomainError> {
let uid = user_id.to_string();
let rows = sqlx::query(
"SELECT f.remote_actor_url,
u.username AS local_username, u.display_name AS local_display, u.avatar_path AS local_avatar_path,
a.handle AS remote_handle, a.display_name AS remote_display, a.avatar_url AS remote_avatar
FROM ap_following f
LEFT JOIN users u ON f.remote_actor_url = $1 || '/users/' || u.id
LEFT JOIN ap_remote_actors a ON a.url = f.remote_actor_url
WHERE f.local_user_id = $2 AND f.status = 'accepted'",
)
.bind(self.instance.base_url())
.bind(&uid)
.fetch_all(&self.pool)
.await
.map_err(infra_err)?;
Ok(rows
.iter()
.map(|r| social_actor_from_row(r, &self.instance))
.collect())
}
async fn get_followers(&self, user_id: uuid::Uuid) -> Result<Vec<SocialActor>, DomainError> {
let uid = user_id.to_string();
let rows = sqlx::query(
"SELECT f.remote_actor_url,
u.username AS local_username, u.display_name AS local_display, u.avatar_path AS local_avatar_path,
a.handle AS remote_handle, a.display_name AS remote_display, a.avatar_url AS remote_avatar
FROM ap_followers f
LEFT JOIN users u ON f.remote_actor_url = $1 || '/users/' || u.id
LEFT JOIN ap_remote_actors a ON a.url = f.remote_actor_url
WHERE f.local_user_id = $2 AND f.status = 'accepted'",
)
.bind(self.instance.base_url())
.bind(&uid)
.fetch_all(&self.pool)
.await
.map_err(infra_err)?;
Ok(rows
.iter()
.map(|r| social_actor_from_row(r, &self.instance))
.collect())
}
async fn get_pending_followers(
&self,
user_id: uuid::Uuid,
) -> Result<Vec<SocialActor>, DomainError> {
let uid = user_id.to_string();
let rows = sqlx::query(
"SELECT f.remote_actor_url,
u.username AS local_username, u.display_name AS local_display, u.avatar_path AS local_avatar_path,
a.handle AS remote_handle, a.display_name AS remote_display, a.avatar_url AS remote_avatar
FROM ap_followers f
LEFT JOIN users u ON f.remote_actor_url = $1 || '/users/' || u.id
LEFT JOIN ap_remote_actors a ON a.url = f.remote_actor_url
WHERE f.local_user_id = $2 AND f.status = 'pending'",
)
.bind(self.instance.base_url())
.bind(&uid)
.fetch_all(&self.pool)
.await
.map_err(infra_err)?;
Ok(rows
.iter()
.map(|r| social_actor_from_row(r, &self.instance))
.collect())
}
async fn get_pending_following(
&self,
user_id: uuid::Uuid,
) -> Result<Vec<SocialActor>, DomainError> {
let uid = user_id.to_string();
let rows = sqlx::query(
"SELECT f.remote_actor_url,
u.username AS local_username, u.display_name AS local_display, u.avatar_path AS local_avatar_path,
a.handle AS remote_handle, a.display_name AS remote_display, a.avatar_url AS remote_avatar
FROM ap_following f
LEFT JOIN users u ON f.remote_actor_url = $1 || '/users/' || u.id
LEFT JOIN ap_remote_actors a ON a.url = f.remote_actor_url
WHERE f.local_user_id = $2 AND f.status = 'pending'",
)
.bind(self.instance.base_url())
.bind(&uid)
.fetch_all(&self.pool)
.await
.map_err(infra_err)?;
Ok(rows
.iter()
.map(|r| social_actor_from_row(r, &self.instance))
.collect())
}
async fn count_following(&self, user_id: uuid::Uuid) -> Result<usize, DomainError> {
let uid = user_id.to_string();
let count: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM ap_following WHERE local_user_id = $1 AND status = 'accepted'",
)
.bind(&uid)
.fetch_one(&self.pool)
.await
.map_err(infra_err)?;
Ok(count as usize)
}
async fn count_followers(&self, user_id: uuid::Uuid) -> Result<usize, DomainError> {
let uid = user_id.to_string();
let count: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM ap_followers WHERE local_user_id = $1 AND status = 'accepted'",
)
.bind(&uid)
.fetch_one(&self.pool)
.await
.map_err(infra_err)?;
Ok(count as usize)
}
async fn count_pending_followers(&self, user_id: uuid::Uuid) -> Result<usize, DomainError> {
let uid = user_id.to_string();
let count: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM ap_followers WHERE local_user_id = $1 AND status = 'pending'",
)
.bind(&uid)
.fetch_one(&self.pool)
.await
.map_err(infra_err)?;
Ok(count as usize)
}
async fn get_relation(
&self,
viewer_id: uuid::Uuid,
target_actor_url: &str,
) -> Result<FollowRelation, DomainError> {
let uid = viewer_id.to_string();
let row = sqlx::query(
"SELECT (SELECT status FROM ap_following WHERE local_user_id = $1 AND remote_actor_url = $2) AS following,
(SELECT status FROM ap_followers WHERE local_user_id = $1 AND remote_actor_url = $2) AS followed_by",
)
.bind(&uid)
.bind(target_actor_url)
.fetch_one(&self.pool)
.await
.map_err(infra_err)?;
Ok(FollowRelation {
following: row
.try_get::<Option<String>, _>("following")
.map_err(infra_err)?
.as_deref()
.and_then(follow_status_from_str),
followed_by: row
.try_get::<Option<String>, _>("followed_by")
.map_err(infra_err)?
.as_deref()
.and_then(follow_status_from_str),
})
}
}

View File

@@ -0,0 +1,38 @@
mod federated_profile;
mod follow_repository;
mod social;
mod watchlist;
pub mod ap_content;
pub mod remote_goals;
pub use ap_content::PostgresApContentQuery;
pub use remote_goals::PostgresRemoteGoalRepository;
use sqlx::PgPool;
/// Postgres-backed implementations of the *domain* social ports.
///
/// Deliberately separate from `postgres-federation`: this crate knows nothing
/// about ActivityPub, which is what allows a build with the `federation`
/// feature off to exclude the federation stack entirely. See ADR-0009.
///
/// Shares the `ap_followers` / `ap_following` tables with
/// `postgres-federation`; neither crate owns migrations.
pub struct PostgresSocialRepository {
pub(crate) pool: PgPool,
pub(crate) instance: domain::value_objects::InstanceIdentity,
}
impl PostgresSocialRepository {
pub fn new(pool: PgPool, instance: domain::value_objects::InstanceIdentity) -> Self {
Self { pool, instance }
}
}
pub fn create_federated_profile_query(
pool: PgPool,
instance: domain::value_objects::InstanceIdentity,
) -> std::sync::Arc<dyn domain::ports::FederatedProfileQuery> {
std::sync::Arc::new(PostgresSocialRepository::new(pool, instance))
}

View File

@@ -0,0 +1,21 @@
use async_trait::async_trait;
use domain::{errors::DomainError, models::RemoteActorInfo, ports::FederationAdminQuery};
use super::PostgresSocialRepository;
#[async_trait]
impl FederationAdminQuery for PostgresSocialRepository {
async fn list_all_followed_remote_actors(&self) -> Result<Vec<RemoteActorInfo>, DomainError> {
let rows = sqlx::query_as::<_, (String, String, Option<String>)>(
"SELECT DISTINCT ar.url, ar.handle, ar.display_name FROM ap_remote_actors ar JOIN ap_following f ON f.remote_actor_url = ar.url WHERE f.status = 'accepted'",
).fetch_all(&self.pool).await.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
Ok(rows
.into_iter()
.map(|(url, handle, display_name)| RemoteActorInfo {
url,
handle,
display_name,
})
.collect())
}
}

View File

@@ -2,10 +2,10 @@ use async_trait::async_trait;
use domain::{errors::DomainError, models::RemoteWatchlistEntry, ports::RemoteWatchlistRepository};
use sqlx::Row;
use super::PostgresFederationRepository;
use super::PostgresSocialRepository;
#[async_trait]
impl RemoteWatchlistRepository for PostgresFederationRepository {
impl RemoteWatchlistRepository for PostgresSocialRepository {
async fn save(&self, entry: RemoteWatchlistEntry) -> Result<(), DomainError> {
sqlx::query(
"INSERT INTO ap_remote_watchlist_entries \

View File

@@ -13,7 +13,7 @@ sqlx = { version = "0.8.6", features = [
] }
adapter-common = { workspace = true }
domain = { workspace = true }
postgres-federation = { workspace = true }
postgres-social = { workspace = true }
anyhow = { workspace = true }
uuid = { workspace = true }
chrono = { workspace = true }

View File

@@ -28,7 +28,7 @@ pub use import_session::PostgresImportSessionRepository;
pub use movie::PostgresMovieRepository;
pub use movie_dedup::PostgresMovieDeduplicator;
pub use persons::{PostgresPersonAdapter, create_person_adapter};
pub use postgres_federation::PostgresApContentQuery;
pub use postgres_social::PostgresApContentQuery;
pub use profile::PostgresMovieProfileRepository;
pub use profile_fields::PostgresProfileFieldsRepository;
pub use refresh_sessions::PostgresRefreshSessionAdapter;
@@ -115,7 +115,7 @@ pub async fn wire(database_url: &str) -> anyhow::Result<PostgresWireOutput> {
goal_query: std::sync::Arc::new(goals::PostgresGoalRepository::new(pool.clone())) as _,
user_settings: std::sync::Arc::clone(&user_settings_repo) as _,
federation_settings: user_settings_repo as _,
remote_goal: std::sync::Arc::new(postgres_federation::PostgresRemoteGoalRepository::new(
remote_goal: std::sync::Arc::new(postgres_social::PostgresRemoteGoalRepository::new(
pool.clone(),
)) as _,
deduplicator: std::sync::Arc::new(PostgresMovieDeduplicator::new(pool)) as _,

View File

@@ -257,3 +257,30 @@ pub(crate) struct MonthlyRatingRow {
pub avg_rating: f64,
pub count: i64,
}
#[derive(sqlx::FromRow)]
pub(crate) struct GenreCountRow {
pub genre: String,
pub count: i64,
}
#[derive(sqlx::FromRow)]
pub(crate) struct RatingDistRow {
pub rating: i64,
pub count: i64,
}
#[derive(sqlx::FromRow)]
pub(crate) struct WatchMediumCountRow {
pub watch_medium: String,
pub count: i64,
}
#[derive(sqlx::FromRow)]
pub(crate) struct ActorAppearanceRow {
pub tmdb_person_id: i64,
pub name: String,
pub profile_path: Option<String>,
pub billing_order: i32,
pub movie_id: String,
}

View File

@@ -192,7 +192,10 @@ impl MovieProfileRepository for PostgresMovieProfileRepository {
name: r.try_get("name").unwrap_or_default(),
character: r.try_get("character").unwrap_or_default(),
billing_order: r.try_get::<i32, _>("billing_order").unwrap_or(0) as u32,
profile_path: r.try_get("profile_path").ok(),
profile_path: r
.try_get::<Option<String>, _>("profile_path")
.ok()
.flatten(),
})
.collect();
@@ -210,31 +213,40 @@ impl MovieProfileRepository for PostgresMovieProfileRepository {
name: r.try_get("name").unwrap_or_default(),
job: r.try_get("job").unwrap_or_default(),
department: r.try_get("department").unwrap_or_default(),
profile_path: r.try_get("profile_path").ok(),
profile_path: r
.try_get::<Option<String>, _>("profile_path")
.ok()
.flatten(),
})
.collect();
Ok(Some(MovieProfile {
movie_id: id.clone(),
tmdb_id: row.try_get::<i64, _>("tmdb_id").unwrap_or(0) as u64,
imdb_id: row.try_get("imdb_id").ok(),
overview: row.try_get("overview").ok(),
tagline: row.try_get("tagline").ok(),
imdb_id: row.try_get::<Option<String>, _>("imdb_id").ok().flatten(),
overview: row.try_get::<Option<String>, _>("overview").ok().flatten(),
tagline: row.try_get::<Option<String>, _>("tagline").ok().flatten(),
runtime_minutes: row
.try_get::<Option<i32>, _>("runtime_minutes")
.ok()
.flatten()
.map(|v| v as u32),
budget_usd: row.try_get("budget_usd").ok(),
revenue_usd: row.try_get("revenue_usd").ok(),
vote_average: row.try_get("vote_average").ok(),
budget_usd: row.try_get::<Option<i64>, _>("budget_usd").ok().flatten(),
revenue_usd: row.try_get::<Option<i64>, _>("revenue_usd").ok().flatten(),
vote_average: row.try_get::<Option<f64>, _>("vote_average").ok().flatten(),
vote_count: row
.try_get::<Option<i32>, _>("vote_count")
.ok()
.flatten()
.map(|v| v as u32),
original_language: row.try_get("original_language").ok(),
collection_name: row.try_get("collection_name").ok(),
original_language: row
.try_get::<Option<String>, _>("original_language")
.ok()
.flatten(),
collection_name: row
.try_get::<Option<String>, _>("collection_name")
.ok()
.flatten(),
genres,
keywords,
cast,

View File

@@ -1,13 +1,18 @@
use async_trait::async_trait;
use domain::{
errors::DomainError,
models::{DirectorStat, MonthlyRating, UserStats, UserTrends},
models::{
ActorAppearance, DirectorStat, MonthlyRating, UserStats, UserTrends, compute_top_actors,
},
ports::StatsRepository,
value_objects::UserId,
};
use sqlx::PgPool;
use crate::models::{DirectorCountRow, MonthlyRatingRow, UserTotalsRow};
use crate::models::{
ActorAppearanceRow, DirectorCountRow, GenreCountRow, MonthlyRatingRow, RatingDistRow,
UserTotalsRow, WatchMediumCountRow,
};
use adapter_common::format_year_month;
pub struct PostgresStatsRepository {
@@ -97,31 +102,71 @@ impl StatsRepository for PostgresStatsRepository {
async fn get_user_trends(&self, user_id: &UserId) -> Result<UserTrends, DomainError> {
let uid = user_id.value().to_string();
let (rating_rows, director_rows) = tokio::try_join!(
sqlx::query_as::<_, MonthlyRatingRow>(
"SELECT to_char(watched_at AT TIME ZONE 'UTC', 'YYYY-MM') AS month,
let (rating_rows, director_rows, genre_rows, rating_dist_rows, medium_rows, actor_rows) =
tokio::try_join!(
sqlx::query_as::<_, MonthlyRatingRow>(
"SELECT to_char(watched_at AT TIME ZONE 'UTC', 'YYYY-MM') AS month,
AVG(rating::float) AS avg_rating,
COUNT(*) AS count
FROM reviews
WHERE user_id = $1 AND watched_at >= NOW() - INTERVAL '12 months'
GROUP BY to_char(watched_at AT TIME ZONE 'UTC', 'YYYY-MM')
ORDER BY to_char(watched_at AT TIME ZONE 'UTC', 'YYYY-MM') ASC"
)
.bind(&uid)
.fetch_all(&self.pool),
sqlx::query_as::<_, DirectorCountRow>(
"SELECT m.director AS director, COUNT(*) AS count
)
.bind(&uid)
.fetch_all(&self.pool),
sqlx::query_as::<_, DirectorCountRow>(
"SELECT m.director AS director, COUNT(*) AS count
FROM reviews r
INNER JOIN movies m ON m.id = r.movie_id
WHERE r.user_id = $1 AND m.director IS NOT NULL
GROUP BY m.director
ORDER BY COUNT(*) DESC
LIMIT 5"
)
.bind(&uid)
.fetch_all(&self.pool),
sqlx::query_as::<_, GenreCountRow>(
"SELECT mg.name AS genre, COUNT(*) AS count
FROM reviews r
INNER JOIN movie_genres mg ON mg.movie_id = r.movie_id
WHERE r.user_id = $1
GROUP BY mg.name
ORDER BY COUNT(*) DESC
LIMIT 5"
)
.bind(&uid)
.fetch_all(&self.pool),
sqlx::query_as::<_, RatingDistRow>(
"SELECT rating, COUNT(*) AS count
FROM reviews
WHERE user_id = $1
GROUP BY rating
ORDER BY rating ASC"
)
.bind(&uid)
.fetch_all(&self.pool),
sqlx::query_as::<_, WatchMediumCountRow>(
"SELECT watch_medium, COUNT(*) AS count
FROM reviews
WHERE user_id = $1 AND watch_medium IS NOT NULL
GROUP BY watch_medium
ORDER BY COUNT(*) DESC"
)
.bind(&uid)
.fetch_all(&self.pool),
sqlx::query_as::<_, ActorAppearanceRow>(
"SELECT mc.tmdb_person_id, mc.name, mc.profile_path,
mc.billing_order, mc.movie_id
FROM reviews r
INNER JOIN movie_cast mc ON mc.movie_id = r.movie_id
WHERE r.user_id = $1
GROUP BY mc.tmdb_person_id, mc.movie_id, mc.name, mc.profile_path, mc.billing_order"
)
.bind(&uid)
.fetch_all(&self.pool)
)
.bind(&uid)
.fetch_all(&self.pool)
)
.map_err(adapter_common::map_sqlx_error)?;
.map_err(adapter_common::map_sqlx_error)?;
let max_director_count = director_rows.iter().map(|d| d.count).max().unwrap_or(1);
@@ -143,10 +188,52 @@ impl StatsRepository for PostgresStatsRepository {
})
.collect();
let top_genres = genre_rows
.into_iter()
.map(|g| domain::models::stats::GenreStat {
genre: g.genre,
count: g.count,
})
.collect();
let rating_distribution = {
let mut dist = [0i64; 5];
for r in &rating_dist_rows {
let idx = (r.rating as usize).saturating_sub(1).min(4);
dist[idx] = r.count;
}
dist
};
let watch_medium_distribution = medium_rows
.into_iter()
.map(|m| domain::models::stats::WatchMediumStat {
medium: m.watch_medium,
count: m.count,
})
.collect();
let top_actors = compute_top_actors(
actor_rows
.into_iter()
.map(|r| ActorAppearance {
tmdb_person_id: r.tmdb_person_id as u64,
name: r.name,
profile_path: r.profile_path,
billing_order: r.billing_order as u32,
movie_id: r.movie_id,
})
.collect(),
);
Ok(UserTrends {
monthly_ratings,
top_directors,
max_director_count,
top_genres,
rating_distribution,
watch_medium_distribution,
top_actors,
})
}
}

View File

@@ -289,7 +289,7 @@ impl WrapUpStatsQuery for PostgresWrapUpStatsQuery {
"SELECT r.movie_id, m.title, m.release_year, m.director, m.poster_path, \
r.rating, \
to_char(r.watched_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') AS watched_at, \
r.user_id, \
r.user_id, r.watch_medium, \
p.runtime_minutes, p.budget_usd, p.original_language \
FROM reviews r \
INNER JOIN movies m ON m.id = r.movie_id \
@@ -367,6 +367,9 @@ impl WrapUpStatsQuery for PostgresWrapUpStatsQuery {
let original_language: Option<String> = row
.try_get("original_language")
.map_err(adapter_common::map_sqlx_error)?;
let watch_medium: Option<String> = row
.try_get("watch_medium")
.map_err(adapter_common::map_sqlx_error)?;
let genres = genres_map.get(&movie_id_str).cloned().unwrap_or_default();
let keywords = keywords_map.get(&movie_id_str).cloned().unwrap_or_default();
@@ -391,6 +394,7 @@ impl WrapUpStatsQuery for PostgresWrapUpStatsQuery {
runtime_minutes: runtime_minutes.map(|v| v as u32),
budget_usd,
original_language,
watch_medium,
genres,
keywords,
cast_names,

View File

@@ -7,7 +7,8 @@ edition = "2024"
sqlx = { workspace = true }
activitypub = { workspace = true }
adapter-common = { workspace = true }
k-ap = { version = "0.4.1", registry = "gitea" }
k-ap = { version = "0.5.0", registry = "gitea" }
sqlite-social = { workspace = true }
domain = { workspace = true }
anyhow = { workspace = true }
serde_json = { workspace = true }

View File

@@ -1,33 +1,28 @@
use anyhow::Result;
use async_trait::async_trait;
use chrono::Utc;
use k_ap::{ActorRepository, RemoteActor};
use k_ap::{AnnounceRepository, Keypair, KeypairRepository, RemoteActor, RemoteActorCache};
use sqlx::Row;
use super::{SqliteFederationRepository, remote_actor_from_row};
use adapter_common::datetime_to_str;
#[async_trait]
impl ActorRepository for SqliteFederationRepository {
async fn get_local_actor_keypair(
&self,
user_id: uuid::Uuid,
) -> Result<Option<(String, String)>> {
impl KeypairRepository for SqliteFederationRepository {
async fn get_local_actor_keypair(&self, user_id: uuid::Uuid) -> Result<Option<Keypair>> {
let uid = user_id.to_string();
let row =
sqlx::query("SELECT public_key, private_key FROM ap_local_actors WHERE user_id = ?")
.bind(&uid)
.fetch_optional(&self.pool)
.await?;
Ok(row.map(|r| (r.get("public_key"), r.get("private_key"))))
Ok(row.map(|r| Keypair {
public_key: r.get("public_key"),
private_key: r.get("private_key"),
}))
}
async fn save_local_actor_keypair(
&self,
user_id: uuid::Uuid,
public_key: String,
private_key: String,
) -> Result<()> {
async fn save_local_actor_keypair(&self, user_id: uuid::Uuid, keypair: Keypair) -> Result<()> {
let uid = user_id.to_string();
let now = Utc::now().naive_utc();
let created_at = datetime_to_str(&now);
@@ -39,14 +34,17 @@ impl ActorRepository for SqliteFederationRepository {
private_key = excluded.private_key",
)
.bind(&uid)
.bind(&public_key)
.bind(&private_key)
.bind(&keypair.public_key)
.bind(&keypair.private_key)
.bind(&created_at)
.execute(&self.pool)
.await?;
Ok(())
}
}
#[async_trait]
impl RemoteActorCache for SqliteFederationRepository {
async fn upsert_remote_actor(&self, actor: RemoteActor) -> Result<()> {
let now = Utc::now().naive_utc();
let fetched_at = datetime_to_str(&now);
@@ -84,7 +82,10 @@ impl ActorRepository for SqliteFederationRepository {
).bind(actor_url).fetch_optional(&self.pool).await?;
Ok(row.as_ref().map(|r| remote_actor_from_row(r, "url")))
}
}
#[async_trait]
impl AnnounceRepository for SqliteFederationRepository {
async fn add_announce(
&self,
activity_id: &str,

View File

@@ -1,14 +1,14 @@
use anyhow::Result;
use async_trait::async_trait;
use chrono::Utc;
use k_ap::{BlockedDomain, BlocklistRepository};
use k_ap::{ActorBlocklist, BlockedDomain, DomainBlocklist};
use sqlx::Row;
use super::SqliteFederationRepository;
use adapter_common::datetime_to_str;
#[async_trait]
impl BlocklistRepository for SqliteFederationRepository {
impl DomainBlocklist for SqliteFederationRepository {
async fn add_blocked_domain(&self, domain: &str, reason: Option<&str>) -> Result<()> {
let now = Utc::now().naive_utc();
let ts = datetime_to_str(&now);
@@ -56,7 +56,10 @@ impl BlocklistRepository for SqliteFederationRepository {
.await?;
Ok(count > 0)
}
}
#[async_trait]
impl ActorBlocklist for SqliteFederationRepository {
async fn add_blocked_actor(&self, local_user_id: uuid::Uuid, actor_url: &str) -> Result<()> {
let uid = local_user_id.to_string();
let ts = datetime_to_str(&Utc::now().naive_utc());

View File

@@ -1,16 +1,14 @@
use anyhow::Result;
use async_trait::async_trait;
use chrono::Utc;
use k_ap::{
ActorRepository, FollowRepository, Follower, FollowerStatus, FollowingStatus, RemoteActor,
};
use k_ap::{Follower, FollowerReader, FollowerStatus, FollowerWriter, RemoteActor};
use sqlx::Row;
use super::{SqliteFederationRepository, remote_actor_from_row, status_to_str, str_to_status};
use crate::{SqliteFederationRepository, remote_actor_from_row, status_to_str, str_to_status};
use adapter_common::datetime_to_str;
#[async_trait]
impl FollowRepository for SqliteFederationRepository {
impl FollowerWriter for SqliteFederationRepository {
async fn add_follower(
&self,
local_user_id: uuid::Uuid,
@@ -69,6 +67,31 @@ impl FollowRepository for SqliteFederationRepository {
Ok(())
}
async fn update_follower_status(
&self,
local_user_id: uuid::Uuid,
remote_actor_url: &str,
status: FollowerStatus,
) -> Result<()> {
let uid = local_user_id.to_string();
let status_str = status_to_str(&status);
let result = sqlx::query(
"UPDATE ap_followers 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, remote_actor_url, "update_follower_status: no row found");
}
Ok(())
}
}
#[async_trait]
impl FollowerReader for SqliteFederationRepository {
async fn get_followers(&self, local_user_id: uuid::Uuid) -> Result<Vec<Follower>> {
let uid = local_user_id.to_string();
let rows = sqlx::query(
@@ -138,28 +161,6 @@ impl FollowRepository for SqliteFederationRepository {
Ok(count as usize)
}
async fn update_follower_status(
&self,
local_user_id: uuid::Uuid,
remote_actor_url: &str,
status: FollowerStatus,
) -> Result<()> {
let uid = local_user_id.to_string();
let status_str = status_to_str(&status);
let result = sqlx::query(
"UPDATE ap_followers 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, remote_actor_url, "update_follower_status: no row found");
}
Ok(())
}
async fn get_pending_followers(&self, local_user_id: uuid::Uuid) -> Result<Vec<RemoteActor>> {
let uid = local_user_id.to_string();
let rows = sqlx::query(
@@ -232,173 +233,4 @@ impl FollowRepository for SqliteFederationRepository {
.map(|row| remote_actor_from_row(row, "remote_actor_url"))
.collect())
}
async fn add_following(
&self,
local_user_id: uuid::Uuid,
actor: RemoteActor,
follow_activity_id: &str,
) -> Result<()> {
let uid = local_user_id.to_string();
let now = Utc::now().naive_utc();
let created_at = datetime_to_str(&now);
ActorRepository::upsert_remote_actor(self, actor.clone()).await?;
sqlx::query(
"INSERT OR IGNORE INTO ap_following (local_user_id, remote_actor_url, follow_activity_id, created_at)
VALUES (?, ?, ?, ?)",
).bind(&uid).bind(&actor.url).bind(follow_activity_id).bind(&created_at).execute(&self.pool).await?;
Ok(())
}
async fn get_follow_activity_id(
&self,
local_user_id: uuid::Uuid,
remote_actor_url: &str,
) -> Result<Option<String>> {
let uid = local_user_id.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: uuid::Uuid, actor_url: &str) -> Result<()> {
let uid = local_user_id.to_string();
sqlx::query("DELETE FROM ap_following WHERE local_user_id = ? AND remote_actor_url = ?")
.bind(&uid)
.bind(actor_url)
.execute(&self.pool)
.await?;
Ok(())
}
async fn get_following(&self, local_user_id: uuid::Uuid) -> Result<Vec<RemoteActor>> {
let uid = local_user_id.to_string();
let rows = sqlx::query(
"SELECT a.url, a.handle, a.inbox_url, a.shared_inbox_url, a.display_name, a.avatar_url,
a.outbox_url, a.bio, a.banner_url, a.followers_url, a.following_url, a.also_known_as, a.fetched_at
FROM ap_following f
INNER JOIN ap_remote_actors a ON a.url = f.remote_actor_url
WHERE f.local_user_id = ? AND f.status = 'accepted'",
).bind(&uid).fetch_all(&self.pool).await?;
Ok(rows
.iter()
.map(|row| remote_actor_from_row(row, "url"))
.collect())
}
async fn count_following(&self, local_user_id: uuid::Uuid) -> Result<usize> {
let uid = local_user_id.to_string();
let count: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM ap_following WHERE local_user_id = ? AND status = 'accepted'",
)
.bind(&uid)
.fetch_one(&self.pool)
.await?;
Ok(count as usize)
}
async fn get_following_page(
&self,
local_user_id: uuid::Uuid,
offset: u32,
limit: usize,
) -> Result<Vec<RemoteActor>> {
let uid = local_user_id.to_string();
let rows = sqlx::query(
"SELECT a.url, a.handle, a.inbox_url, a.shared_inbox_url, a.display_name, a.avatar_url,
a.outbox_url, a.bio, a.banner_url, a.followers_url, a.following_url, a.also_known_as, a.fetched_at
FROM ap_following f
INNER JOIN ap_remote_actors a ON a.url = f.remote_actor_url
WHERE f.local_user_id = ? AND f.status = 'accepted'
ORDER BY f.created_at ASC LIMIT ? OFFSET ?",
).bind(&uid).bind(limit as i64).bind(offset as i64).fetch_all(&self.pool).await?;
Ok(rows
.iter()
.map(|row| remote_actor_from_row(row, "url"))
.collect())
}
async fn update_following_status(
&self,
local_user_id: uuid::Uuid,
remote_actor_url: &str,
status: FollowingStatus,
) -> Result<()> {
let uid = local_user_id.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, remote_actor_url, "update_following_status: no row found");
}
Ok(())
}
async fn get_following_outbox_url(
&self,
local_user_id: uuid::Uuid,
remote_actor_url: &str,
) -> Result<Option<String>> {
let uid = local_user_id.to_string();
let row: Option<Option<String>> = sqlx::query_scalar(
"SELECT a.outbox_url
FROM ap_following f
INNER JOIN ap_remote_actors a ON a.url = f.remote_actor_url
WHERE f.local_user_id = ? AND f.remote_actor_url = ?",
)
.bind(&uid)
.bind(remote_actor_url)
.fetch_optional(&self.pool)
.await?;
Ok(row.flatten())
}
async fn migrate_follower_actor(
&self,
old_actor_url: &str,
new_actor_url: &str,
) -> Result<Vec<uuid::Uuid>> {
let candidates: Vec<String> = sqlx::query_scalar(
"SELECT local_user_id FROM ap_following
WHERE remote_actor_url = ?1
AND local_user_id NOT IN (
SELECT local_user_id FROM ap_following WHERE remote_actor_url = ?2
)",
)
.bind(old_actor_url)
.bind(new_actor_url)
.fetch_all(&self.pool)
.await?;
if candidates.is_empty() {
return Ok(vec![]);
}
sqlx::query(
"UPDATE ap_following SET remote_actor_url = ?1
WHERE remote_actor_url = ?2
AND local_user_id NOT IN (
SELECT local_user_id FROM ap_following WHERE remote_actor_url = ?1
)",
)
.bind(new_actor_url)
.bind(old_actor_url)
.execute(&self.pool)
.await?;
candidates
.into_iter()
.map(|s| uuid::Uuid::parse_str(&s).map_err(|e| anyhow::anyhow!(e)))
.collect()
}
}

View File

@@ -0,0 +1,124 @@
use anyhow::Result;
use async_trait::async_trait;
use chrono::Utc;
use k_ap::{FollowingReader, FollowingStatus, FollowingWriter, RemoteActor, RemoteActorCache};
use crate::{SqliteFederationRepository, remote_actor_from_row};
use adapter_common::datetime_to_str;
#[async_trait]
impl FollowingWriter for SqliteFederationRepository {
async fn add_following(
&self,
local_user_id: uuid::Uuid,
actor: RemoteActor,
follow_activity_id: &str,
) -> Result<()> {
let uid = local_user_id.to_string();
let now = Utc::now().naive_utc();
let created_at = datetime_to_str(&now);
RemoteActorCache::upsert_remote_actor(self, actor.clone()).await?;
sqlx::query(
"INSERT OR IGNORE INTO ap_following (local_user_id, remote_actor_url, follow_activity_id, created_at)
VALUES (?, ?, ?, ?)",
).bind(&uid).bind(&actor.url).bind(follow_activity_id).bind(&created_at).execute(&self.pool).await?;
Ok(())
}
async fn get_follow_activity_id(
&self,
local_user_id: uuid::Uuid,
remote_actor_url: &str,
) -> Result<Option<String>> {
let uid = local_user_id.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: uuid::Uuid, actor_url: &str) -> Result<()> {
let uid = local_user_id.to_string();
sqlx::query("DELETE FROM ap_following WHERE local_user_id = ? AND remote_actor_url = ?")
.bind(&uid)
.bind(actor_url)
.execute(&self.pool)
.await?;
Ok(())
}
async fn update_following_status(
&self,
local_user_id: uuid::Uuid,
remote_actor_url: &str,
status: FollowingStatus,
) -> Result<()> {
let uid = local_user_id.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, remote_actor_url, "update_following_status: no row found");
}
Ok(())
}
}
#[async_trait]
impl FollowingReader for SqliteFederationRepository {
async fn get_following(&self, local_user_id: uuid::Uuid) -> Result<Vec<RemoteActor>> {
let uid = local_user_id.to_string();
let rows = sqlx::query(
"SELECT a.url, a.handle, a.inbox_url, a.shared_inbox_url, a.display_name, a.avatar_url,
a.outbox_url, a.bio, a.banner_url, a.followers_url, a.following_url, a.also_known_as, a.fetched_at
FROM ap_following f
INNER JOIN ap_remote_actors a ON a.url = f.remote_actor_url
WHERE f.local_user_id = ? AND f.status = 'accepted'",
).bind(&uid).fetch_all(&self.pool).await?;
Ok(rows
.iter()
.map(|row| remote_actor_from_row(row, "url"))
.collect())
}
async fn count_following(&self, local_user_id: uuid::Uuid) -> Result<usize> {
let uid = local_user_id.to_string();
let count: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM ap_following WHERE local_user_id = ? AND status = 'accepted'",
)
.bind(&uid)
.fetch_one(&self.pool)
.await?;
Ok(count as usize)
}
async fn get_following_page(
&self,
local_user_id: uuid::Uuid,
offset: u32,
limit: usize,
) -> Result<Vec<RemoteActor>> {
let uid = local_user_id.to_string();
let rows = sqlx::query(
"SELECT a.url, a.handle, a.inbox_url, a.shared_inbox_url, a.display_name, a.avatar_url,
a.outbox_url, a.bio, a.banner_url, a.followers_url, a.following_url, a.also_known_as, a.fetched_at
FROM ap_following f
INNER JOIN ap_remote_actors a ON a.url = f.remote_actor_url
WHERE f.local_user_id = ? AND f.status = 'accepted'
ORDER BY f.created_at ASC LIMIT ? OFFSET ?",
).bind(&uid).bind(limit as i64).bind(offset as i64).fetch_all(&self.pool).await?;
Ok(rows
.iter()
.map(|row| remote_actor_from_row(row, "url"))
.collect())
}
}

View File

@@ -0,0 +1,47 @@
use anyhow::Result;
use async_trait::async_trait;
use k_ap::FollowMigration;
use crate::SqliteFederationRepository;
#[async_trait]
impl FollowMigration for SqliteFederationRepository {
async fn migrate_follower_actor(
&self,
old_actor_url: &str,
new_actor_url: &str,
) -> Result<Vec<uuid::Uuid>> {
let candidates: Vec<String> = sqlx::query_scalar(
"SELECT local_user_id FROM ap_following
WHERE remote_actor_url = ?1
AND local_user_id NOT IN (
SELECT local_user_id FROM ap_following WHERE remote_actor_url = ?2
)",
)
.bind(old_actor_url)
.bind(new_actor_url)
.fetch_all(&self.pool)
.await?;
if candidates.is_empty() {
return Ok(vec![]);
}
sqlx::query(
"UPDATE ap_following SET remote_actor_url = ?1
WHERE remote_actor_url = ?2
AND local_user_id NOT IN (
SELECT local_user_id FROM ap_following WHERE remote_actor_url = ?1
)",
)
.bind(new_actor_url)
.bind(old_actor_url)
.execute(&self.pool)
.await?;
candidates
.into_iter()
.map(|s| uuid::Uuid::parse_str(&s).map_err(|e| anyhow::anyhow!(e)))
.collect()
}
}

View File

@@ -0,0 +1,3 @@
mod followers;
mod following;
mod migration;

View File

@@ -1,17 +1,8 @@
mod activity;
mod actor;
mod blocklist;
mod federated_profile;
mod follow;
mod review;
mod social;
mod watchlist;
pub mod ap_content;
pub mod remote_goals;
pub use ap_content::SqliteApContentQuery;
pub use remote_goals::SqliteRemoteGoalRepository;
use k_ap::{FollowerStatus, RemoteActor};
use sqlx::SqlitePool;
@@ -83,29 +74,25 @@ impl SqliteFederationRepository {
}
}
pub fn create_federated_profile_query(
pub fn wire(
pool: SqlitePool,
) -> std::sync::Arc<dyn domain::ports::FederatedProfileQuery> {
std::sync::Arc::new(SqliteFederationRepository::new(pool))
instance: domain::value_objects::InstanceIdentity,
) -> activitypub::FederationRepos {
let fed = std::sync::Arc::new(SqliteFederationRepository::new(pool.clone()));
let social = std::sync::Arc::new(sqlite_social::SqliteSocialRepository::new(pool, instance));
activitypub::FederationRepos {
activity: std::sync::Arc::clone(&fed) as _,
follow: std::sync::Arc::clone(&fed) as _,
actor: std::sync::Arc::clone(&fed) as _,
blocklist: std::sync::Arc::clone(&fed) as _,
review_store: fed as _,
admin_query: std::sync::Arc::clone(&social) as _,
remote_watchlist: std::sync::Arc::clone(&social) as _,
follow_command: std::sync::Arc::clone(&social) as _,
follow_query: social as _,
}
}
pub fn wire(pool: SqlitePool) -> activitypub::FederationRepos {
let fed = std::sync::Arc::new(SqliteFederationRepository::new(pool));
(
std::sync::Arc::clone(&fed) as _,
std::sync::Arc::clone(&fed) as _,
std::sync::Arc::clone(&fed) as _,
std::sync::Arc::clone(&fed) as _,
std::sync::Arc::clone(&fed) as _,
std::sync::Arc::clone(&fed) as _,
fed as _,
)
}
#[cfg(test)]
#[path = "tests/outbox_url.rs"]
mod outbox_url_tests;
#[cfg(test)]
#[path = "tests/actor_block_tests.rs"]
mod actor_block_tests;

View File

@@ -1,95 +0,0 @@
use async_trait::async_trait;
use domain::{
errors::DomainError,
models::{PendingFollowerInfo, RemoteActorInfo},
ports::SocialQueryPort,
value_objects::UserId,
};
use super::SqliteFederationRepository;
#[async_trait]
impl SocialQueryPort for SqliteFederationRepository {
async fn get_accepted_following_urls(
&self,
user_id: &UserId,
) -> Result<Vec<String>, DomainError> {
let user_id_str = user_id.value().to_string();
sqlx::query_scalar::<_, String>(
"SELECT remote_actor_url FROM ap_following WHERE local_user_id = ? AND status = 'accepted'",
).bind(&user_id_str).fetch_all(&self.pool).await
.map_err(|e| DomainError::InfrastructureError(e.to_string()))
}
async fn list_all_followed_remote_actors(&self) -> Result<Vec<RemoteActorInfo>, DomainError> {
let rows = sqlx::query_as::<_, (String, String, Option<String>)>(
"SELECT DISTINCT ar.url, ar.handle, ar.display_name
FROM ap_remote_actors ar
JOIN ap_following f ON f.remote_actor_url = ar.url
WHERE f.status = 'accepted'",
)
.fetch_all(&self.pool)
.await
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
Ok(rows
.into_iter()
.map(|(url, handle, display_name)| RemoteActorInfo {
url,
handle,
display_name,
})
.collect())
}
async fn count_following(&self, user_id: &UserId) -> Result<usize, DomainError> {
let uid = user_id.value().to_string();
let count: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM ap_following WHERE local_user_id = ? AND status = 'accepted'",
)
.bind(&uid)
.fetch_one(&self.pool)
.await
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
Ok(count as usize)
}
async fn count_accepted_followers(&self, user_id: &UserId) -> Result<usize, DomainError> {
let uid = user_id.value().to_string();
let count: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM ap_followers WHERE local_user_id = ? AND status = 'accepted'",
)
.bind(&uid)
.fetch_one(&self.pool)
.await
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
Ok(count as usize)
}
async fn get_pending_followers(
&self,
user_id: &UserId,
) -> Result<Vec<PendingFollowerInfo>, DomainError> {
let uid = user_id.value().to_string();
let rows = sqlx::query_as::<_, (String, String, Option<String>, Option<String>)>(
"SELECT ar.url, ar.handle, ar.display_name, ar.avatar_url
FROM ap_followers f
JOIN ap_remote_actors ar ON ar.url = f.remote_actor_url
WHERE f.local_user_id = ? AND f.status = 'pending'",
)
.bind(&uid)
.fetch_all(&self.pool)
.await
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
Ok(rows
.into_iter()
.map(
|(url, handle, display_name, avatar_url)| PendingFollowerInfo {
url,
handle,
display_name,
avatar_url,
},
)
.collect())
}
}

View File

@@ -1,5 +1,5 @@
use super::*;
use k_ap::BlocklistRepository;
use k_ap::ActorBlocklist;
use sqlx::SqlitePool;
async fn test_pool() -> SqlitePool {

View File

@@ -1,5 +1,5 @@
use super::*;
use k_ap::BlocklistRepository;
use k_ap::DomainBlocklist;
use sqlx::SqlitePool;
async fn test_pool() -> SqlitePool {

View File

@@ -1,7 +1,6 @@
use super::*;
use chrono::Utc;
use domain::ports::SocialQueryPort;
use k_ap::ActorRepository;
use k_ap::AnnounceRepository;
use sqlx::SqlitePool;
async fn test_pool() -> SqlitePool {
@@ -48,89 +47,3 @@ async fn duplicate_announce_is_ignored() {
.unwrap();
assert_eq!(repo.count_announces("https://local/r/1").await.unwrap(), 1);
}
async fn setup_db(pool: &SqlitePool) {
sqlx::query(
"CREATE TABLE IF NOT EXISTS ap_remote_actors (
url TEXT PRIMARY KEY,
handle TEXT NOT NULL,
inbox_url TEXT NOT NULL,
shared_inbox_url TEXT,
display_name TEXT,
avatar_url TEXT,
fetched_at TEXT NOT NULL
)",
)
.execute(pool)
.await
.unwrap();
sqlx::query(
"CREATE TABLE IF NOT EXISTS ap_following (
local_user_id TEXT NOT NULL,
remote_actor_url TEXT NOT NULL,
follow_activity_id TEXT NOT NULL,
status TEXT NOT NULL,
PRIMARY KEY (local_user_id, remote_actor_url)
)",
)
.execute(pool)
.await
.unwrap();
}
#[tokio::test]
async fn test_get_accepted_following_urls_returns_only_accepted() {
let pool = SqlitePool::connect(":memory:").await.unwrap();
setup_db(&pool).await;
let repo = SqliteFederationRepository::new(pool.clone());
let user_id = uuid::Uuid::new_v4();
sqlx::query(
"INSERT INTO ap_following (local_user_id, remote_actor_url, follow_activity_id, status)
VALUES (?, 'https://other.social/users/alice', 'act1', 'accepted'),
(?, 'https://other.social/users/bob', 'act2', 'pending')",
)
.bind(user_id.to_string())
.bind(user_id.to_string())
.execute(&pool)
.await
.unwrap();
let uid = domain::value_objects::UserId::from_uuid(user_id);
let urls = repo.get_accepted_following_urls(&uid).await.unwrap();
assert_eq!(urls.len(), 1);
assert_eq!(urls[0], "https://other.social/users/alice");
}
#[tokio::test]
async fn test_list_all_followed_remote_actors_deduplicates() {
let pool = SqlitePool::connect(":memory:").await.unwrap();
setup_db(&pool).await;
let repo = SqliteFederationRepository::new(pool.clone());
let user1 = uuid::Uuid::new_v4();
let user2 = uuid::Uuid::new_v4();
sqlx::query(
"INSERT INTO ap_remote_actors (url, handle, inbox_url, fetched_at, display_name)
VALUES ('https://other.social/users/alice', 'alice@other.social', 'https://other.social/inbox', '2024-01-01', 'Alice')",
)
.execute(&pool)
.await
.unwrap();
sqlx::query(
"INSERT INTO ap_following (local_user_id, remote_actor_url, follow_activity_id, status)
VALUES (?, 'https://other.social/users/alice', 'act1', 'accepted'),
(?, 'https://other.social/users/alice', 'act2', 'accepted')",
)
.bind(user1.to_string())
.bind(user2.to_string())
.execute(&pool)
.await
.unwrap();
let actors = repo.list_all_followed_remote_actors().await.unwrap();
assert_eq!(actors.len(), 1);
assert_eq!(actors[0].handle, "alice@other.social");
}

View File

@@ -1,76 +0,0 @@
use super::*;
use k_ap::{FollowRepository, FollowingStatus, RemoteActor};
async fn setup_pool() -> SqlitePool {
let pool = SqlitePool::connect(":memory:").await.unwrap();
sqlx::query(
"CREATE TABLE ap_remote_actors (
url TEXT PRIMARY KEY, handle TEXT NOT NULL, inbox_url TEXT NOT NULL,
shared_inbox_url TEXT, display_name TEXT, avatar_url TEXT,
outbox_url TEXT, bio TEXT, banner_url TEXT, followers_url TEXT,
following_url TEXT, also_known_as TEXT, fetched_at TEXT NOT NULL
);
CREATE TABLE ap_following (
local_user_id TEXT NOT NULL, remote_actor_url TEXT NOT NULL,
follow_activity_id TEXT, created_at TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
PRIMARY KEY (local_user_id, remote_actor_url)
);",
)
.execute(&pool)
.await
.unwrap();
pool
}
#[tokio::test]
async fn get_following_outbox_url_returns_stored_url() {
let pool = setup_pool().await;
let repo = SqliteFederationRepository::new(pool);
let local_user = uuid::Uuid::new_v4();
let actor = RemoteActor {
url: "https://remote.example/users/alice".to_string(),
handle: "alice@remote.example".to_string(),
inbox_url: "https://remote.example/users/alice/inbox".to_string(),
shared_inbox_url: None,
display_name: None,
avatar_url: None,
outbox_url: Some("https://remote.example/users/alice/outbox".to_string()),
bio: None,
banner_url: None,
followers_url: None,
following_url: None,
also_known_as: vec![],
fetched_at: None,
};
repo.add_following(local_user, actor, "https://local/activities/1")
.await
.unwrap();
repo.update_following_status(
local_user,
"https://remote.example/users/alice",
FollowingStatus::Accepted,
)
.await
.unwrap();
let result = repo
.get_following_outbox_url(local_user, "https://remote.example/users/alice")
.await
.unwrap();
assert_eq!(
result,
Some("https://remote.example/users/alice/outbox".to_string())
);
}
#[tokio::test]
async fn get_following_outbox_url_returns_none_when_not_following() {
let pool = setup_pool().await;
let repo = SqliteFederationRepository::new(pool);
let result = repo
.get_following_outbox_url(uuid::Uuid::new_v4(), "https://remote.example/users/alice")
.await
.unwrap();
assert_eq!(result, None);
}

View File

@@ -0,0 +1,15 @@
[package]
name = "sqlite-social"
version = "0.1.0"
edition = "2024"
[dependencies]
sqlx = { workspace = true }
adapter-common = { workspace = true }
domain = { workspace = true }
uuid = { workspace = true }
chrono = { workspace = true }
async-trait = { workspace = true }
[dev-dependencies]
tokio = { workspace = true }

View File

@@ -2,10 +2,10 @@ use async_trait::async_trait;
use domain::{errors::DomainError, models::FederatedProfile, ports::FederatedProfileQuery};
use sqlx::Row;
use super::SqliteFederationRepository;
use super::SqliteSocialRepository;
#[async_trait]
impl FederatedProfileQuery for SqliteFederationRepository {
impl FederatedProfileQuery for SqliteSocialRepository {
async fn get_federated_profile(
&self,
synthetic_user_id: uuid::Uuid,

View File

@@ -0,0 +1,357 @@
use async_trait::async_trait;
use chrono::Utc;
use domain::{
errors::DomainError,
value_objects::{FollowRelation, FollowStatus, InstanceIdentity, SocialActor, SocialIdentity},
};
use sqlx::Row;
use crate::SqliteSocialRepository;
use adapter_common::datetime_to_str;
fn follow_status_to_str(status: &FollowStatus) -> &'static str {
match status {
FollowStatus::Pending => "pending",
FollowStatus::Accepted => "accepted",
FollowStatus::Rejected => "rejected",
}
}
fn infra_err(e: impl std::fmt::Display) -> DomainError {
DomainError::InfrastructureError(e.to_string())
}
fn follow_status_from_str(status: &str) -> Option<FollowStatus> {
match status {
"pending" => Some(FollowStatus::Pending),
"accepted" => Some(FollowStatus::Accepted),
"rejected" => Some(FollowStatus::Rejected),
_ => None,
}
}
#[async_trait]
impl domain::ports::FollowCommand for SqliteSocialRepository {
async fn add_follow(
&self,
follower_id: uuid::Uuid,
target_actor_url: &str,
status: FollowStatus,
) -> Result<(), DomainError> {
let uid = follower_id.to_string();
let status_str = follow_status_to_str(&status);
let now = datetime_to_str(&Utc::now().naive_utc());
sqlx::query(
"INSERT INTO ap_following (local_user_id, remote_actor_url, follow_activity_id, created_at, status)
VALUES (?1, ?2, '', ?3, ?4)
ON CONFLICT(local_user_id, remote_actor_url) DO UPDATE SET status = excluded.status",
)
.bind(&uid)
.bind(target_actor_url)
.bind(&now)
.bind(status_str)
.execute(&self.pool)
.await
.map_err(infra_err)?;
Ok(())
}
async fn update_follow_status(
&self,
follower_id: uuid::Uuid,
target_actor_url: &str,
status: FollowStatus,
) -> Result<(), DomainError> {
let uid = follower_id.to_string();
let status_str = follow_status_to_str(&status);
sqlx::query(
"UPDATE ap_following SET status = ?1 WHERE local_user_id = ?2 AND remote_actor_url = ?3",
)
.bind(status_str)
.bind(&uid)
.bind(target_actor_url)
.execute(&self.pool)
.await
.map_err(infra_err)?;
Ok(())
}
async fn remove_follow(
&self,
follower_id: uuid::Uuid,
target_actor_url: &str,
) -> Result<(), DomainError> {
let uid = follower_id.to_string();
sqlx::query("DELETE FROM ap_following WHERE local_user_id = ?1 AND remote_actor_url = ?2")
.bind(&uid)
.bind(target_actor_url)
.execute(&self.pool)
.await
.map_err(infra_err)?;
Ok(())
}
async fn add_follower(
&self,
local_user_id: uuid::Uuid,
follower_actor_url: &str,
status: FollowStatus,
) -> Result<(), DomainError> {
let uid = local_user_id.to_string();
let status_str = follow_status_to_str(&status);
let now = datetime_to_str(&Utc::now().naive_utc());
sqlx::query(
"INSERT INTO ap_followers (local_user_id, remote_actor_url, status, created_at, follow_activity_id)
VALUES (?1, ?2, ?3, ?4, '')
ON CONFLICT(local_user_id, remote_actor_url) DO UPDATE SET status = excluded.status",
)
.bind(&uid)
.bind(follower_actor_url)
.bind(status_str)
.bind(&now)
.execute(&self.pool)
.await
.map_err(infra_err)?;
Ok(())
}
async fn update_follower_status(
&self,
local_user_id: uuid::Uuid,
follower_actor_url: &str,
status: FollowStatus,
) -> Result<(), DomainError> {
let uid = local_user_id.to_string();
let status_str = follow_status_to_str(&status);
sqlx::query(
"UPDATE ap_followers SET status = ?1 WHERE local_user_id = ?2 AND remote_actor_url = ?3",
)
.bind(status_str)
.bind(&uid)
.bind(follower_actor_url)
.execute(&self.pool)
.await
.map_err(infra_err)?;
Ok(())
}
async fn remove_follower_record(
&self,
local_user_id: uuid::Uuid,
follower_actor_url: &str,
) -> Result<(), DomainError> {
let uid = local_user_id.to_string();
sqlx::query("DELETE FROM ap_followers WHERE local_user_id = ?1 AND remote_actor_url = ?2")
.bind(&uid)
.bind(follower_actor_url)
.execute(&self.pool)
.await
.map_err(infra_err)?;
Ok(())
}
}
fn social_actor_from_row(
row: &sqlx::sqlite::SqliteRow,
instance: &InstanceIdentity,
) -> SocialActor {
let actor_url: String = row.get("remote_actor_url");
let identity = instance.identify(&actor_url);
let (handle, display_name, avatar_url) = match &identity {
SocialIdentity::Local(_) => {
let username: Option<String> = row.try_get("local_username").ok().flatten();
let display: Option<String> = row.try_get("local_display").ok().flatten();
let avatar: Option<String> = row
.try_get::<Option<String>, _>("local_avatar_path")
.ok()
.flatten()
.map(|p| instance.image_url_for(&p));
let handle = username
.as_deref()
.map(|u| instance.handle_for(u))
.unwrap_or_else(|| actor_url.clone());
(handle, display, avatar)
}
SocialIdentity::Remote { .. } => {
let handle: String = row
.try_get::<Option<String>, _>("remote_handle")
.ok()
.flatten()
.unwrap_or_else(|| actor_url.clone());
let display: Option<String> = row.try_get("remote_display").ok().flatten();
let avatar: Option<String> = row.try_get("remote_avatar").ok().flatten();
(handle, display, avatar)
}
};
SocialActor {
identity,
handle,
display_name,
avatar_url,
}
}
#[async_trait]
impl domain::ports::FollowQuery for SqliteSocialRepository {
async fn get_following(&self, user_id: uuid::Uuid) -> Result<Vec<SocialActor>, DomainError> {
let uid = user_id.to_string();
let rows = sqlx::query(
"SELECT f.remote_actor_url,
u.username AS local_username, u.display_name AS local_display, u.avatar_path AS local_avatar_path,
a.handle AS remote_handle, a.display_name AS remote_display, a.avatar_url AS remote_avatar
FROM ap_following f
LEFT JOIN users u ON f.remote_actor_url = ?1 || '/users/' || u.id
LEFT JOIN ap_remote_actors a ON a.url = f.remote_actor_url
WHERE f.local_user_id = ?2 AND f.status = 'accepted'",
)
.bind(self.instance.base_url())
.bind(&uid)
.fetch_all(&self.pool)
.await
.map_err(infra_err)?;
Ok(rows
.iter()
.map(|r| social_actor_from_row(r, &self.instance))
.collect())
}
async fn get_followers(&self, user_id: uuid::Uuid) -> Result<Vec<SocialActor>, DomainError> {
let uid = user_id.to_string();
let rows = sqlx::query(
"SELECT f.remote_actor_url,
u.username AS local_username, u.display_name AS local_display, u.avatar_path AS local_avatar_path,
a.handle AS remote_handle, a.display_name AS remote_display, a.avatar_url AS remote_avatar
FROM ap_followers f
LEFT JOIN users u ON f.remote_actor_url = ?1 || '/users/' || u.id
LEFT JOIN ap_remote_actors a ON a.url = f.remote_actor_url
WHERE f.local_user_id = ?2 AND f.status = 'accepted'",
)
.bind(self.instance.base_url())
.bind(&uid)
.fetch_all(&self.pool)
.await
.map_err(infra_err)?;
Ok(rows
.iter()
.map(|r| social_actor_from_row(r, &self.instance))
.collect())
}
async fn get_pending_followers(
&self,
user_id: uuid::Uuid,
) -> Result<Vec<SocialActor>, DomainError> {
let uid = user_id.to_string();
let rows = sqlx::query(
"SELECT f.remote_actor_url,
u.username AS local_username, u.display_name AS local_display, u.avatar_path AS local_avatar_path,
a.handle AS remote_handle, a.display_name AS remote_display, a.avatar_url AS remote_avatar
FROM ap_followers f
LEFT JOIN users u ON f.remote_actor_url = ?1 || '/users/' || u.id
LEFT JOIN ap_remote_actors a ON a.url = f.remote_actor_url
WHERE f.local_user_id = ?2 AND f.status = 'pending'",
)
.bind(self.instance.base_url())
.bind(&uid)
.fetch_all(&self.pool)
.await
.map_err(infra_err)?;
Ok(rows
.iter()
.map(|r| social_actor_from_row(r, &self.instance))
.collect())
}
async fn get_pending_following(
&self,
user_id: uuid::Uuid,
) -> Result<Vec<SocialActor>, DomainError> {
let uid = user_id.to_string();
let rows = sqlx::query(
"SELECT f.remote_actor_url,
u.username AS local_username, u.display_name AS local_display, u.avatar_path AS local_avatar_path,
a.handle AS remote_handle, a.display_name AS remote_display, a.avatar_url AS remote_avatar
FROM ap_following f
LEFT JOIN users u ON f.remote_actor_url = ?1 || '/users/' || u.id
LEFT JOIN ap_remote_actors a ON a.url = f.remote_actor_url
WHERE f.local_user_id = ?2 AND f.status = 'pending'",
)
.bind(self.instance.base_url())
.bind(&uid)
.fetch_all(&self.pool)
.await
.map_err(infra_err)?;
Ok(rows
.iter()
.map(|r| social_actor_from_row(r, &self.instance))
.collect())
}
async fn count_following(&self, user_id: uuid::Uuid) -> Result<usize, DomainError> {
let uid = user_id.to_string();
let count: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM ap_following WHERE local_user_id = ? AND status = 'accepted'",
)
.bind(&uid)
.fetch_one(&self.pool)
.await
.map_err(infra_err)?;
Ok(count as usize)
}
async fn count_followers(&self, user_id: uuid::Uuid) -> Result<usize, DomainError> {
let uid = user_id.to_string();
let count: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM ap_followers WHERE local_user_id = ? AND status = 'accepted'",
)
.bind(&uid)
.fetch_one(&self.pool)
.await
.map_err(infra_err)?;
Ok(count as usize)
}
async fn count_pending_followers(&self, user_id: uuid::Uuid) -> Result<usize, DomainError> {
let uid = user_id.to_string();
let count: i64 = sqlx::query_scalar(
"SELECT COUNT(*) FROM ap_followers WHERE local_user_id = ? AND status = 'pending'",
)
.bind(&uid)
.fetch_one(&self.pool)
.await
.map_err(infra_err)?;
Ok(count as usize)
}
async fn get_relation(
&self,
viewer_id: uuid::Uuid,
target_actor_url: &str,
) -> Result<FollowRelation, DomainError> {
let uid = viewer_id.to_string();
let row = sqlx::query(
"SELECT (SELECT status FROM ap_following WHERE local_user_id = ?1 AND remote_actor_url = ?2) AS following,
(SELECT status FROM ap_followers WHERE local_user_id = ?1 AND remote_actor_url = ?2) AS followed_by",
)
.bind(&uid)
.bind(target_actor_url)
.fetch_one(&self.pool)
.await
.map_err(infra_err)?;
Ok(FollowRelation {
following: row
.try_get::<Option<String>, _>("following")
.map_err(infra_err)?
.as_deref()
.and_then(follow_status_from_str),
followed_by: row
.try_get::<Option<String>, _>("followed_by")
.map_err(infra_err)?
.as_deref()
.and_then(follow_status_from_str),
})
}
}

View File

@@ -0,0 +1,42 @@
mod federated_profile;
mod follow_repository;
mod social;
mod watchlist;
pub mod ap_content;
pub mod remote_goals;
pub use ap_content::SqliteApContentQuery;
pub use remote_goals::SqliteRemoteGoalRepository;
use sqlx::SqlitePool;
/// SQLite-backed implementations of the *domain* social ports.
///
/// Deliberately separate from `sqlite-federation`: this crate knows nothing
/// about ActivityPub, which is what allows a build with the `federation`
/// feature off to exclude the federation stack entirely. See ADR-0009.
///
/// Shares the `ap_followers` / `ap_following` tables with
/// `sqlite-federation`; neither crate owns migrations.
pub struct SqliteSocialRepository {
pub(crate) pool: SqlitePool,
pub(crate) instance: domain::value_objects::InstanceIdentity,
}
impl SqliteSocialRepository {
pub fn new(pool: SqlitePool, instance: domain::value_objects::InstanceIdentity) -> Self {
Self { pool, instance }
}
}
pub fn create_federated_profile_query(
pool: SqlitePool,
instance: domain::value_objects::InstanceIdentity,
) -> std::sync::Arc<dyn domain::ports::FederatedProfileQuery> {
std::sync::Arc::new(SqliteSocialRepository::new(pool, instance))
}
#[cfg(test)]
#[path = "tests/follow_relation_tests.rs"]
mod follow_relation_tests;

View File

@@ -0,0 +1,27 @@
use async_trait::async_trait;
use domain::{errors::DomainError, models::RemoteActorInfo, ports::FederationAdminQuery};
use super::SqliteSocialRepository;
#[async_trait]
impl FederationAdminQuery for SqliteSocialRepository {
async fn list_all_followed_remote_actors(&self) -> Result<Vec<RemoteActorInfo>, DomainError> {
let rows = sqlx::query_as::<_, (String, String, Option<String>)>(
"SELECT DISTINCT ar.url, ar.handle, ar.display_name
FROM ap_remote_actors ar
JOIN ap_following f ON f.remote_actor_url = ar.url
WHERE f.status = 'accepted'",
)
.fetch_all(&self.pool)
.await
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
Ok(rows
.into_iter()
.map(|(url, handle, display_name)| RemoteActorInfo {
url,
handle,
display_name,
})
.collect())
}
}

View File

@@ -0,0 +1,253 @@
use super::*;
use domain::ports::{FederationAdminQuery, FollowQuery};
use domain::value_objects::{FollowStatus, InstanceIdentity, SocialIdentity};
use sqlx::SqlitePool;
async fn test_pool() -> SqlitePool {
let pool = SqlitePool::connect("sqlite::memory:").await.unwrap();
for ddl in [
"CREATE TABLE ap_following (local_user_id TEXT NOT NULL, remote_actor_url TEXT NOT NULL,
follow_activity_id TEXT NOT NULL, created_at TEXT, status TEXT NOT NULL,
PRIMARY KEY (local_user_id, remote_actor_url))",
"CREATE TABLE ap_followers (local_user_id TEXT NOT NULL, remote_actor_url TEXT NOT NULL,
follow_activity_id TEXT NOT NULL, created_at TEXT, status TEXT NOT NULL,
PRIMARY KEY (local_user_id, remote_actor_url))",
"CREATE TABLE users (id TEXT PRIMARY KEY, username TEXT NOT NULL,
display_name TEXT, avatar_path TEXT)",
"CREATE TABLE ap_remote_actors (url TEXT PRIMARY KEY, handle TEXT NOT NULL,
display_name TEXT, avatar_url TEXT)",
] {
sqlx::query(ddl).execute(&pool).await.unwrap();
}
pool
}
fn repo(pool: SqlitePool) -> SqliteSocialRepository {
SqliteSocialRepository::new(pool, InstanceIdentity::new("https://md.example"))
}
#[tokio::test]
async fn get_relation_returns_no_edges_for_strangers() {
let r = repo(test_pool().await);
let rel = r
.get_relation(uuid::Uuid::new_v4(), "https://other.example/users/bob")
.await
.unwrap();
assert_eq!(rel.following, None);
assert_eq!(rel.followed_by, None);
}
#[tokio::test]
async fn get_relation_reads_following_direction_only_from_ap_following() {
let pool = test_pool().await;
let viewer = uuid::Uuid::new_v4();
let target = "https://other.example/users/bob";
sqlx::query(
"INSERT INTO ap_following (local_user_id, remote_actor_url, follow_activity_id, status)
VALUES (?1, ?2, '', 'pending')",
)
.bind(viewer.to_string())
.bind(target)
.execute(&pool)
.await
.unwrap();
let rel = repo(pool).get_relation(viewer, target).await.unwrap();
assert_eq!(rel.following, Some(FollowStatus::Pending));
assert_eq!(
rel.followed_by, None,
"an ap_following row must not populate followed_by"
);
}
#[tokio::test]
async fn get_relation_reads_followed_by_from_ap_followers_including_rejected() {
let pool = test_pool().await;
let owner = uuid::Uuid::new_v4();
let requester = "https://other.example/users/carol";
sqlx::query(
"INSERT INTO ap_followers (local_user_id, remote_actor_url, follow_activity_id, status)
VALUES (?1, ?2, '', 'rejected')",
)
.bind(owner.to_string())
.bind(requester)
.execute(&pool)
.await
.unwrap();
let rel = repo(pool).get_relation(owner, requester).await.unwrap();
assert_eq!(rel.followed_by, Some(FollowStatus::Rejected));
assert_eq!(rel.following, None);
}
#[tokio::test]
async fn get_relation_treats_unknown_status_as_no_edge() {
let pool = test_pool().await;
let viewer = uuid::Uuid::new_v4();
let target = "https://other.example/users/dave";
sqlx::query(
"INSERT INTO ap_following (local_user_id, remote_actor_url, follow_activity_id, status)
VALUES (?1, ?2, '', 'not-a-real-status')",
)
.bind(viewer.to_string())
.bind(target)
.execute(&pool)
.await
.unwrap();
let rel = repo(pool).get_relation(viewer, target).await.unwrap();
assert_eq!(rel.following, None);
}
#[tokio::test]
async fn get_pending_following_returns_only_pending_rows() {
let pool = test_pool().await;
let viewer = uuid::Uuid::new_v4();
sqlx::query(
"INSERT INTO ap_following (local_user_id, remote_actor_url, follow_activity_id, status)
VALUES (?1, 'https://other.example/users/pending', '', 'pending'),
(?1, 'https://other.example/users/accepted', '', 'accepted')",
)
.bind(viewer.to_string())
.execute(&pool)
.await
.unwrap();
let actors = FollowQuery::get_pending_following(&repo(pool), viewer)
.await
.unwrap();
assert_eq!(
actors.len(),
1,
"accepted rows must not appear in pending_following"
);
// The handle-fallback-on-join-miss behavior is covered by
// `remote_actor_with_no_cached_row_falls_back_to_its_actor_url`; this test
// only needs to check pending-row filtering, so it asserts on identity.
assert_eq!(
actors[0].identity,
SocialIdentity::Remote {
actor_url: "https://other.example/users/pending".to_string()
}
);
}
#[tokio::test]
async fn remote_actor_with_no_cached_row_falls_back_to_its_actor_url() {
let pool = test_pool().await;
let viewer = uuid::Uuid::new_v4();
let orphan = "https://other.example/users/uncached";
sqlx::query(
"INSERT INTO ap_following (local_user_id, remote_actor_url, follow_activity_id, status)
VALUES (?1, ?2, '', 'pending')",
)
.bind(viewer.to_string())
.bind(orphan)
.execute(&pool)
.await
.unwrap();
// deliberately NO ap_remote_actors row for `orphan`
let actors = FollowQuery::get_pending_following(&repo(pool), viewer)
.await
.unwrap();
assert_eq!(actors.len(), 1);
assert_eq!(
actors[0].handle, orphan,
"with no cached actor, handle must fall back to the actor url, not render empty"
);
}
#[tokio::test]
async fn count_pending_followers_counts_only_pending() {
let pool = test_pool().await;
let owner = uuid::Uuid::new_v4();
sqlx::query(
"INSERT INTO ap_followers (local_user_id, remote_actor_url, follow_activity_id, status)
VALUES (?1, 'https://other.example/users/a', '', 'pending'),
(?1, 'https://other.example/users/b', '', 'pending'),
(?1, 'https://other.example/users/c', '', 'accepted'),
(?1, 'https://other.example/users/d', '', 'rejected')",
)
.bind(owner.to_string())
.execute(&pool)
.await
.unwrap();
let n = FollowQuery::count_pending_followers(&repo(pool), owner)
.await
.unwrap();
assert_eq!(
n, 2,
"only pending rows count; accepted and rejected must not"
);
}
async fn setup_admin_query_db(pool: &SqlitePool) {
sqlx::query(
"CREATE TABLE IF NOT EXISTS ap_remote_actors (
url TEXT PRIMARY KEY,
handle TEXT NOT NULL,
inbox_url TEXT NOT NULL,
shared_inbox_url TEXT,
display_name TEXT,
avatar_url TEXT,
fetched_at TEXT NOT NULL
)",
)
.execute(pool)
.await
.unwrap();
sqlx::query(
"CREATE TABLE IF NOT EXISTS ap_following (
local_user_id TEXT NOT NULL,
remote_actor_url TEXT NOT NULL,
follow_activity_id TEXT NOT NULL,
status TEXT NOT NULL,
PRIMARY KEY (local_user_id, remote_actor_url)
)",
)
.execute(pool)
.await
.unwrap();
}
#[tokio::test]
async fn test_list_all_followed_remote_actors_deduplicates() {
let pool = SqlitePool::connect(":memory:").await.unwrap();
setup_admin_query_db(&pool).await;
let repo =
SqliteSocialRepository::new(pool.clone(), InstanceIdentity::new("https://localhost"));
let user1 = uuid::Uuid::new_v4();
let user2 = uuid::Uuid::new_v4();
sqlx::query(
"INSERT INTO ap_remote_actors (url, handle, inbox_url, fetched_at, display_name)
VALUES ('https://other.social/users/alice', 'alice@other.social', 'https://other.social/inbox', '2024-01-01', 'Alice')",
)
.execute(&pool)
.await
.unwrap();
sqlx::query(
"INSERT INTO ap_following (local_user_id, remote_actor_url, follow_activity_id, status)
VALUES (?, 'https://other.social/users/alice', 'act1', 'accepted'),
(?, 'https://other.social/users/alice', 'act2', 'accepted')",
)
.bind(user1.to_string())
.bind(user2.to_string())
.execute(&pool)
.await
.unwrap();
let actors = repo.list_all_followed_remote_actors().await.unwrap();
assert_eq!(actors.len(), 1);
assert_eq!(actors[0].handle, "alice@other.social");
}

View File

@@ -2,10 +2,10 @@ use async_trait::async_trait;
use domain::{errors::DomainError, models::RemoteWatchlistEntry, ports::RemoteWatchlistRepository};
use sqlx::Row;
use super::SqliteFederationRepository;
use super::SqliteSocialRepository;
#[async_trait]
impl RemoteWatchlistRepository for SqliteFederationRepository {
impl RemoteWatchlistRepository for SqliteSocialRepository {
async fn save(&self, entry: RemoteWatchlistEntry) -> Result<(), DomainError> {
sqlx::query(
"INSERT INTO ap_remote_watchlist_entries \

View File

@@ -13,7 +13,7 @@ sqlx = { version = "0.8.6", features = [
adapter-common = { workspace = true }
domain = { workspace = true }
sqlite-federation = { workspace = true }
sqlite-social = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
anyhow = { workspace = true }

View File

@@ -32,7 +32,7 @@ pub use profile::SqliteMovieProfileRepository;
pub use profile_fields::SqliteProfileFieldsRepository;
pub use refresh_sessions::SqliteRefreshSessionAdapter;
pub use review::SqliteReviewRepository;
pub use sqlite_federation::SqliteApContentQuery;
pub use sqlite_social::SqliteApContentQuery;
pub use stats::SqliteStatsRepository;
pub use users::SqliteUserRepository;
pub use watch_event::{SqliteWatchEventRepository, SqliteWebhookTokenRepository};
@@ -118,7 +118,7 @@ pub async fn wire(database_url: &str) -> anyhow::Result<SqliteWireOutput> {
goal_query: std::sync::Arc::new(goals::SqliteGoalRepository::new(pool.clone())) as _,
user_settings: std::sync::Arc::clone(&user_settings_repo) as _,
federation_settings: user_settings_repo as _,
remote_goal: std::sync::Arc::new(sqlite_federation::SqliteRemoteGoalRepository::new(
remote_goal: std::sync::Arc::new(sqlite_social::SqliteRemoteGoalRepository::new(
pool.clone(),
)) as _,
deduplicator: std::sync::Arc::new(SqliteMovieDeduplicator::new(pool)) as _,

View File

@@ -264,6 +264,33 @@ pub(crate) struct MonthlyRatingRow {
pub count: i64,
}
#[derive(sqlx::FromRow)]
pub(crate) struct GenreCountRow {
pub genre: String,
pub count: i64,
}
#[derive(sqlx::FromRow)]
pub(crate) struct RatingDistRow {
pub rating: i64,
pub count: i64,
}
#[derive(sqlx::FromRow)]
pub(crate) struct WatchMediumCountRow {
pub watch_medium: String,
pub count: i64,
}
#[derive(sqlx::FromRow)]
pub(crate) struct ActorAppearanceRow {
pub tmdb_person_id: i64,
pub name: String,
pub profile_path: Option<String>,
pub billing_order: i32,
pub movie_id: String,
}
#[derive(sqlx::FromRow)]
pub(crate) struct WatchlistRow {
pub id: String,

View File

@@ -208,7 +208,10 @@ impl MovieProfileRepository for SqliteMovieProfileRepository {
name: r.try_get("name").unwrap_or_default(),
character: r.try_get("character").unwrap_or_default(),
billing_order: r.try_get::<i64, _>("billing_order").unwrap_or(0) as u32,
profile_path: r.try_get("profile_path").ok(),
profile_path: r
.try_get::<Option<String>, _>("profile_path")
.ok()
.flatten(),
})
.collect();
@@ -226,31 +229,40 @@ impl MovieProfileRepository for SqliteMovieProfileRepository {
name: r.try_get("name").unwrap_or_default(),
job: r.try_get("job").unwrap_or_default(),
department: r.try_get("department").unwrap_or_default(),
profile_path: r.try_get("profile_path").ok(),
profile_path: r
.try_get::<Option<String>, _>("profile_path")
.ok()
.flatten(),
})
.collect();
Ok(Some(MovieProfile {
movie_id: id.clone(),
tmdb_id: row.try_get::<i64, _>("tmdb_id").unwrap_or(0) as u64,
imdb_id: row.try_get("imdb_id").ok(),
overview: row.try_get("overview").ok(),
tagline: row.try_get("tagline").ok(),
imdb_id: row.try_get::<Option<String>, _>("imdb_id").ok().flatten(),
overview: row.try_get::<Option<String>, _>("overview").ok().flatten(),
tagline: row.try_get::<Option<String>, _>("tagline").ok().flatten(),
runtime_minutes: row
.try_get::<Option<i64>, _>("runtime_minutes")
.ok()
.flatten()
.map(|v| v as u32),
budget_usd: row.try_get("budget_usd").ok(),
revenue_usd: row.try_get("revenue_usd").ok(),
vote_average: row.try_get("vote_average").ok(),
budget_usd: row.try_get::<Option<i64>, _>("budget_usd").ok().flatten(),
revenue_usd: row.try_get::<Option<i64>, _>("revenue_usd").ok().flatten(),
vote_average: row.try_get::<Option<f64>, _>("vote_average").ok().flatten(),
vote_count: row
.try_get::<Option<i64>, _>("vote_count")
.ok()
.flatten()
.map(|v| v as u32),
original_language: row.try_get("original_language").ok(),
collection_name: row.try_get("collection_name").ok(),
original_language: row
.try_get::<Option<String>, _>("original_language")
.ok()
.flatten(),
collection_name: row
.try_get::<Option<String>, _>("collection_name")
.ok()
.flatten(),
genres,
keywords,
cast,
@@ -286,3 +298,7 @@ impl MovieProfileRepository for SqliteMovieProfileRepository {
.collect())
}
}
#[cfg(test)]
#[path = "tests/profile.rs"]
mod tests;

View File

@@ -1,13 +1,18 @@
use async_trait::async_trait;
use domain::{
errors::DomainError,
models::{DirectorStat, MonthlyRating, UserStats, UserTrends},
models::{
ActorAppearance, DirectorStat, MonthlyRating, UserStats, UserTrends, compute_top_actors,
},
ports::StatsRepository,
value_objects::UserId,
};
use sqlx::SqlitePool;
use crate::models::{DirectorCountRow, MonthlyRatingRow, UserTotalsRow};
use crate::models::{
ActorAppearanceRow, DirectorCountRow, GenreCountRow, MonthlyRatingRow, RatingDistRow,
UserTotalsRow, WatchMediumCountRow,
};
pub struct SqliteStatsRepository {
pool: SqlitePool,
@@ -98,20 +103,21 @@ impl StatsRepository for SqliteStatsRepository {
async fn get_user_trends(&self, user_id: &UserId) -> Result<UserTrends, DomainError> {
let uid = user_id.value().to_string();
let (rating_rows, director_rows) = tokio::try_join!(
sqlx::query_as::<_, MonthlyRatingRow>(
"SELECT strftime('%Y-%m', watched_at) AS month,
let (rating_rows, director_rows, genre_rows, rating_dist_rows, medium_rows, actor_rows) =
tokio::try_join!(
sqlx::query_as::<_, MonthlyRatingRow>(
"SELECT strftime('%Y-%m', watched_at) AS month,
AVG(CAST(rating AS REAL)) AS avg_rating,
COUNT(*) AS count
FROM reviews
WHERE user_id = ? AND watched_at >= datetime('now', '-12 months')
GROUP BY month
ORDER BY month ASC",
)
.bind(&uid)
.fetch_all(&self.pool),
sqlx::query_as::<_, DirectorCountRow>(
"SELECT m.director,
)
.bind(&uid)
.fetch_all(&self.pool),
sqlx::query_as::<_, DirectorCountRow>(
"SELECT m.director,
COUNT(*) AS count
FROM reviews r
INNER JOIN movies m ON m.id = r.movie_id
@@ -119,11 +125,50 @@ impl StatsRepository for SqliteStatsRepository {
GROUP BY m.director
ORDER BY COUNT(*) DESC
LIMIT 5",
)
.bind(&uid)
.fetch_all(&self.pool),
sqlx::query_as::<_, GenreCountRow>(
"SELECT mg.name AS genre, COUNT(*) AS count
FROM reviews r
INNER JOIN movie_genres mg ON mg.movie_id = r.movie_id
WHERE r.user_id = ?
GROUP BY mg.name
ORDER BY COUNT(*) DESC
LIMIT 5",
)
.bind(&uid)
.fetch_all(&self.pool),
sqlx::query_as::<_, RatingDistRow>(
"SELECT rating, COUNT(*) AS count
FROM reviews
WHERE user_id = ?
GROUP BY rating
ORDER BY rating ASC",
)
.bind(&uid)
.fetch_all(&self.pool),
sqlx::query_as::<_, WatchMediumCountRow>(
"SELECT watch_medium, COUNT(*) AS count
FROM reviews
WHERE user_id = ? AND watch_medium IS NOT NULL
GROUP BY watch_medium
ORDER BY COUNT(*) DESC",
)
.bind(&uid)
.fetch_all(&self.pool),
sqlx::query_as::<_, ActorAppearanceRow>(
"SELECT mc.tmdb_person_id, mc.name, mc.profile_path,
mc.billing_order, mc.movie_id
FROM reviews r
INNER JOIN movie_cast mc ON mc.movie_id = r.movie_id
WHERE r.user_id = ?
GROUP BY mc.tmdb_person_id, mc.movie_id",
)
.bind(&uid)
.fetch_all(&self.pool)
)
.bind(&uid)
.fetch_all(&self.pool)
)
.map_err(adapter_common::map_sqlx_error)?;
.map_err(adapter_common::map_sqlx_error)?;
let max_director_count = director_rows.iter().map(|d| d.count).max().unwrap_or(1);
@@ -145,10 +190,52 @@ impl StatsRepository for SqliteStatsRepository {
})
.collect();
let top_genres = genre_rows
.into_iter()
.map(|g| domain::models::stats::GenreStat {
genre: g.genre,
count: g.count,
})
.collect();
let rating_distribution = {
let mut dist = [0i64; 5];
for r in &rating_dist_rows {
let idx = (r.rating as usize).saturating_sub(1).min(4);
dist[idx] = r.count;
}
dist
};
let watch_medium_distribution = medium_rows
.into_iter()
.map(|m| domain::models::stats::WatchMediumStat {
medium: m.watch_medium,
count: m.count,
})
.collect();
let top_actors = compute_top_actors(
actor_rows
.into_iter()
.map(|r| ActorAppearance {
tmdb_person_id: r.tmdb_person_id as u64,
name: r.name,
profile_path: r.profile_path,
billing_order: r.billing_order as u32,
movie_id: r.movie_id,
})
.collect(),
);
Ok(UserTrends {
monthly_ratings,
top_directors,
max_director_count,
top_genres,
rating_distribution,
watch_medium_distribution,
top_actors,
})
}
}

View File

@@ -0,0 +1,95 @@
use super::super::profile::SqliteMovieProfileRepository;
use domain::{ports::MovieProfileRepository, value_objects::MovieId};
use sqlx::SqlitePool;
async fn pool_with_schema() -> SqlitePool {
let pool = SqlitePool::connect("sqlite::memory:").await.unwrap();
sqlx::query(
"CREATE TABLE movie_profiles (
movie_id TEXT PRIMARY KEY, tmdb_id INTEGER, imdb_id TEXT,
overview TEXT, tagline TEXT, runtime_minutes INTEGER,
budget_usd INTEGER, revenue_usd INTEGER, vote_average REAL,
vote_count INTEGER, original_language TEXT, collection_name TEXT,
enriched_at TEXT NOT NULL
)",
)
.execute(&pool)
.await
.unwrap();
sqlx::query("CREATE TABLE movie_genres (movie_id TEXT, tmdb_id INTEGER, name TEXT)")
.execute(&pool)
.await
.unwrap();
sqlx::query("CREATE TABLE movie_keywords (movie_id TEXT, tmdb_id INTEGER, name TEXT)")
.execute(&pool)
.await
.unwrap();
sqlx::query(
"CREATE TABLE movie_cast (movie_id TEXT, tmdb_person_id INTEGER,
name TEXT, character TEXT, billing_order INTEGER, profile_path TEXT)",
)
.execute(&pool)
.await
.unwrap();
sqlx::query(
"CREATE TABLE movie_crew (movie_id TEXT, tmdb_person_id INTEGER,
name TEXT, job TEXT, department TEXT, profile_path TEXT)",
)
.execute(&pool)
.await
.unwrap();
pool
}
async fn insert_bare_profile(pool: &SqlitePool, movie_id: &str) {
sqlx::query("INSERT INTO movie_profiles (movie_id, tmdb_id, enriched_at) VALUES (?, 1, ?)")
.bind(movie_id)
.bind(chrono::Utc::now().to_rfc3339())
.execute(pool)
.await
.unwrap();
}
#[tokio::test]
async fn null_cast_profile_path_becomes_none_not_empty_string() {
let pool = pool_with_schema().await;
let movie_id = MovieId::generate();
let movie_id_str = movie_id.value().to_string();
insert_bare_profile(&pool, &movie_id_str).await;
sqlx::query(
"INSERT INTO movie_cast (movie_id, tmdb_person_id, name, character, billing_order, profile_path)
VALUES (?, 1, 'Alice', 'Hero', 0, NULL)",
)
.bind(&movie_id_str)
.execute(&pool)
.await
.unwrap();
let adapter = SqliteMovieProfileRepository::new(pool);
let profile = adapter.get_by_movie_id(&movie_id).await.unwrap().unwrap();
assert_eq!(profile.cast.len(), 1);
assert_eq!(
profile.cast[0].profile_path, None,
"NULL profile_path must decode to None, not Some(\"\")"
);
}
#[tokio::test]
async fn null_budget_usd_becomes_none_not_some_zero() {
let pool = pool_with_schema().await;
let movie_id = MovieId::generate();
let movie_id_str = movie_id.value().to_string();
insert_bare_profile(&pool, &movie_id_str).await;
let adapter = SqliteMovieProfileRepository::new(pool);
let profile = adapter.get_by_movie_id(&movie_id).await.unwrap().unwrap();
assert_eq!(
profile.budget_usd, None,
"NULL budget_usd must decode to None, not Some(0)"
);
}

View File

@@ -301,7 +301,7 @@ impl WrapUpStatsQuery for SqliteWrapUpStatsQuery {
let sql = format!(
"SELECT r.movie_id, m.title, m.release_year, m.director, m.poster_path, \
r.rating, r.watched_at, r.user_id, \
r.rating, r.watched_at, r.user_id, r.watch_medium, \
p.runtime_minutes, p.budget_usd, p.original_language \
FROM reviews r \
INNER JOIN movies m ON m.id = r.movie_id \
@@ -379,6 +379,9 @@ impl WrapUpStatsQuery for SqliteWrapUpStatsQuery {
let original_language: Option<String> = row
.try_get("original_language")
.map_err(adapter_common::map_sqlx_error)?;
let watch_medium: Option<String> = row
.try_get("watch_medium")
.map_err(adapter_common::map_sqlx_error)?;
let genres = genres_map.get(&movie_id_str).cloned().unwrap_or_default();
let keywords = keywords_map.get(&movie_id_str).cloned().unwrap_or_default();
@@ -403,6 +406,7 @@ impl WrapUpStatsQuery for SqliteWrapUpStatsQuery {
runtime_minutes: runtime_minutes.map(|v| v as u32),
budget_usd,
original_language,
watch_medium,
genres,
keywords,
cast_names,

View File

@@ -296,6 +296,7 @@ pub struct FollowingTemplate {
pub ctx: HtmlPageContext,
pub user_id: uuid::Uuid,
pub actors: Vec<RemoteActorData>,
pub pending_actors: Vec<RemoteActorData>,
pub error: Option<String>,
}

View File

@@ -34,7 +34,7 @@
<a href="/">Feed</a>
<a href="/users">Users</a>
{% if let Some(uid) = ctx.user_id %}
<a href="/users/{{ uid }}">Profile</a>
<a href="/users/{{ uid }}">Profile{% if ctx.pending_follow_count > 0 %} ({{ ctx.pending_follow_count }}){% endif %}</a>
<a href="/reviews/new">Add Review</a>
<a href="/import">Import</a>
<a href="/watch-queue">Queue</a>

View File

@@ -10,6 +10,28 @@
<input type="text" name="handle" placeholder="@user@instance.tld" required>
<button type="submit">Follow</button>
</form>
{% if !pending_actors.is_empty() %}
<h3>Requested ({{ pending_actors.len() }})</h3>
<ul class="following-list">
{% for actor in pending_actors %}
<li class="following-item">
{% if let Some(avatar) = actor.avatar_url %}
<img src="{{ avatar }}" alt="" style="width:32px;height:32px;border-radius:50%;vertical-align:middle;margin-right:6px" />
{% endif %}
<strong>{{ actor.handle }}</strong>
{% if let Some(name) = actor.display_name %}
({{ name }})
{% endif %}
<a href="{{ actor.url }}" target="_blank" rel="noopener noreferrer">View profile ↗</a>
<form method="POST" action="/users/{{ user_id }}/unfollow" style="display:inline">
<input type="hidden" name="actor_url" value="{{ actor.url }}">
<input type="hidden" name="_csrf" value="{{ ctx.csrf_token }}">
<button type="submit">Cancel request</button>
</form>
</li>
{% endfor %}
</ul>
{% endif %}
{% if actors.is_empty() %}
<p>Not following anyone yet. Follow remote users from your <a href="/users/{{ user_id }}">profile page</a>.</p>
{% else %}

View File

@@ -8,3 +8,6 @@ serde = { workspace = true }
uuid = { workspace = true }
utoipa = { version = "5.5.0", features = ["axum_extras", "uuid"] }
domain = { path = "../domain" }
[dev-dependencies]
serde_json = { workspace = true }

View File

@@ -10,6 +10,7 @@ pub struct HtmlPageContext {
pub canonical_url: String,
pub csrf_token: String,
pub page_rss_url: Option<String>,
pub pending_follow_count: usize,
}
impl HtmlPageContext {

View File

@@ -1,4 +1,5 @@
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct FollowRequest {
@@ -15,6 +16,9 @@ pub struct RemoteActorDto {
pub handle: String,
pub display_name: Option<String>,
pub url: String,
/// `Some` for local actors, so the SPA can link internally to `/users/{id}`.
pub user_id: Option<Uuid>,
pub avatar_url: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
@@ -42,3 +46,62 @@ pub struct BlockedActorResponse {
pub display_name: Option<String>,
pub avatar_url: Option<String>,
}
#[derive(Serialize, Deserialize, utoipa::ToSchema, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum FollowStateDto {
None,
Pending,
Accepted,
Rejected,
}
impl From<Option<domain::value_objects::FollowStatus>> for FollowStateDto {
fn from(s: Option<domain::value_objects::FollowStatus>) -> Self {
use domain::value_objects::FollowStatus as F;
match s {
None => Self::None,
Some(F::Pending) => Self::Pending,
Some(F::Accepted) => Self::Accepted,
Some(F::Rejected) => Self::Rejected,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct FollowRelationResponse {
pub following: FollowStateDto,
pub followed_by: FollowStateDto,
}
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct PendingCountResponse {
pub count: usize,
}
#[cfg(test)]
mod tests {
use super::*;
/// Task 7's SPA zod schema parses these exact lowercase literals —
/// a casing or naming drift here breaks the SPA at runtime.
#[test]
fn follow_state_dto_serializes_to_lowercase_strings() {
assert_eq!(
serde_json::to_string(&FollowStateDto::None).unwrap(),
"\"none\""
);
assert_eq!(
serde_json::to_string(&FollowStateDto::Pending).unwrap(),
"\"pending\""
);
assert_eq!(
serde_json::to_string(&FollowStateDto::Accepted).unwrap(),
"\"accepted\""
);
assert_eq!(
serde_json::to_string(&FollowStateDto::Rejected).unwrap(),
"\"rejected\""
);
}
}

View File

@@ -60,11 +60,36 @@ pub struct DirectorStatDto {
pub count: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct ActorStatDto {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_path: Option<String>,
pub movie_count: u32,
pub score: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct GenreStatDto {
pub genre: String,
pub count: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct WatchMediumStatDto {
pub medium: String,
pub count: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct UserTrendsDto {
pub monthly_ratings: Vec<MonthlyRatingDto>,
pub top_directors: Vec<DirectorStatDto>,
pub max_director_count: i64,
pub top_genres: Vec<GenreStatDto>,
pub rating_distribution: [i64; 5],
pub watch_medium_distribution: Vec<WatchMediumStatDto>,
pub top_actors: Vec<ActorStatDto>,
}
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]

View File

@@ -31,3 +31,7 @@ pub struct RegisterAndLoginDeps {
pub refresh_session: Arc<dyn RefreshSessionRepository>,
pub config: AppConfig,
}
pub struct LogoutDeps {
pub refresh_session: Arc<dyn RefreshSessionRepository>,
}

View File

@@ -1,12 +1,9 @@
use std::sync::Arc;
use domain::errors::DomainError;
use domain::{errors::DomainError, ports::RefreshSessionRepository};
use crate::auth::deps::LogoutDeps;
pub async fn execute(
refresh_session: Arc<dyn RefreshSessionRepository>,
refresh_token: &str,
) -> Result<(), DomainError> {
refresh_session.revoke(refresh_token).await
pub async fn execute(deps: &LogoutDeps, refresh_token: &str) -> Result<(), DomainError> {
deps.refresh_session.revoke(refresh_token).await
}
#[cfg(test)]

View File

@@ -6,7 +6,7 @@ use domain::testing::InMemoryUserRepository;
use crate::{
auth::{
commands::RegisterCommand,
deps::{LoginDeps, RefreshDeps, RegisterDeps},
deps::{LoginDeps, LogoutDeps, RefreshDeps, RegisterDeps},
login, logout,
queries::LoginCommand,
refresh, register,
@@ -53,7 +53,10 @@ async fn logout_revokes_refresh_token() {
.await
.unwrap();
logout::execute(b.refresh_session_repo.clone(), &login_result.refresh_token)
let logout_deps = LogoutDeps {
refresh_session: b.refresh_session_repo.clone(),
};
logout::execute(&logout_deps, &login_result.refresh_token)
.await
.unwrap();
@@ -69,6 +72,9 @@ async fn logout_revokes_refresh_token() {
#[tokio::test]
async fn logout_with_unknown_token_succeeds() {
let b = TestContextBuilder::new();
let result = logout::execute(b.refresh_session_repo.clone(), "nonexistent-token").await;
let logout_deps = LogoutDeps {
refresh_session: b.refresh_session_repo.clone(),
};
let result = logout::execute(&logout_deps, "nonexistent-token").await;
assert!(result.is_ok());
}

View File

@@ -0,0 +1,194 @@
use std::sync::Arc;
use domain::ports::{EventPublisher, MediaServerParser, ObjectStorage, PersonEnrichmentClient};
use crate::auth::deps::{LoginDeps, LogoutDeps, RefreshDeps, RegisterAndLoginDeps, RegisterDeps};
use crate::diary::deps::{
DeleteReviewDeps, EditReviewDeps, ExportDiaryDeps, GetActivityFeedDeps, GetDiaryDeps,
GetMovieSocialPageDeps, GetReviewHistoryDeps, GetUserFeedDeps,
};
use crate::goals::deps::{GoalCommandDeps, GoalQueryDeps};
use crate::import::deps::{
ApplyMappingDeps, ApplyProfileAndMapDeps, ApplyProfileDeps, CreateSessionDeps,
DeleteImportProfileDeps, ExecuteImportDeps, GetMappingStageDeps, GetPreviewStageDeps,
GetSessionStateDeps, ListImportProfilesDeps, SaveProfileDeps,
};
use crate::integrations::deps::{
ConfirmWatchEventsDeps, DismissWatchEventsDeps, GenerateWebhookTokenDeps, GetWatchQueueDeps,
GetWebhookTokensDeps, IngestWatchEventDeps, RevokeWebhookTokenDeps,
};
use crate::movies::deps::{
EnrichMovieDeps, GetMovieProfileDeps, GetMoviesDeps, ReindexSearchDeps, SyncPosterDeps,
};
use crate::movies::merge_duplicates::MergeDuplicatesDeps;
use crate::person::deps::{EnrichPersonDeps, GetPersonDeps};
use crate::search::deps::SearchDeps;
use crate::social::deps::{SocialCommandDeps, SocialQueryDeps};
use crate::users::deps::{
AuthorizeAdminDeps, DeleteAccountDeps, GetCurrentProfileDeps, GetFederatedProfileDeps,
GetFederatedProfileStatsDeps, GetLocalProfileDeps, GetPageViewerDeps, GetProfileSettingsDeps,
GetSettingsDeps, GetUsersListDeps, ResolveUsernameDeps, UpdateProfileDeps,
UpdateProfileFieldsDeps, UpdateSettingsDeps,
};
use crate::watchlist::deps::{
GetWatchlistDeps, GetWatchlistForOwnerDeps, IsOnWatchlistDeps, RemoveFromWatchlistDeps,
WatchlistAddDeps,
};
use crate::wrapup::deps::{
DeleteWrapUpDeps, GenerateWrapUpDeps, GetReadyReportDeps, GetWrapUpDeps,
HandleWrapUpRequestedDeps, ListWrapUpsDeps,
};
pub struct AuthGroup {
pub login: LoginDeps,
pub register: RegisterDeps,
pub refresh: RefreshDeps,
pub register_and_login: RegisterAndLoginDeps,
pub logout: LogoutDeps,
}
pub struct DiaryGroup {
pub delete_review: DeleteReviewDeps,
pub edit_review: EditReviewDeps,
pub get_movie_social_page: GetMovieSocialPageDeps,
pub get_activity_feed: GetActivityFeedDeps,
pub get_user_feed: GetUserFeedDeps,
pub get_diary: GetDiaryDeps,
pub get_review_history: GetReviewHistoryDeps,
pub export_diary: ExportDiaryDeps,
}
pub struct GoalsGroup {
pub command: GoalCommandDeps,
pub query: GoalQueryDeps,
}
pub struct ImportGroup {
pub create_session: CreateSessionDeps,
pub apply_mapping: ApplyMappingDeps,
pub apply_profile: ApplyProfileDeps,
pub execute_import: ExecuteImportDeps,
pub save_profile: SaveProfileDeps,
pub get_mapping_stage: GetMappingStageDeps,
pub get_preview_stage: GetPreviewStageDeps,
pub get_session_state: GetSessionStateDeps,
pub apply_profile_and_map: ApplyProfileAndMapDeps,
pub delete_profile: DeleteImportProfileDeps,
pub list_profiles: ListImportProfilesDeps,
}
pub struct IntegrationsGroup {
pub ingest_watch_event: IngestWatchEventDeps,
pub confirm_watch_events: ConfirmWatchEventsDeps,
pub dismiss_watch_events: DismissWatchEventsDeps,
pub generate_webhook_token: GenerateWebhookTokenDeps,
pub get_watch_queue: GetWatchQueueDeps,
pub get_webhook_tokens: GetWebhookTokensDeps,
pub revoke_webhook_token: RevokeWebhookTokenDeps,
/// Webhook payload parsers. Held on the group rather than inside
/// `IngestWatchEventDeps` because `ingest::execute` takes the parser as an
/// argument — the caller picks which one per route.
pub jellyfin_parser: Arc<dyn MediaServerParser>,
pub plex_parser: Arc<dyn MediaServerParser>,
}
pub struct MoviesGroup {
pub sync_poster: SyncPosterDeps,
pub get_movie_profile: GetMovieProfileDeps,
pub get_movies: GetMoviesDeps,
}
pub struct PersonGroup {
pub get_person: GetPersonDeps,
}
pub struct SearchGroup {
pub execute: SearchDeps,
}
pub struct SocialGroup {
pub command: SocialCommandDeps,
pub query: SocialQueryDeps,
}
pub struct UsersGroup {
pub get_local_profile: GetLocalProfileDeps,
pub get_federated_profile_stats: GetFederatedProfileStatsDeps,
pub get_page_viewer: GetPageViewerDeps,
pub resolve_username: ResolveUsernameDeps,
pub get_profile_settings: GetProfileSettingsDeps,
pub get_users_list: GetUsersListDeps,
pub update_profile: UpdateProfileDeps,
/// Not reachable from the server binary; see the `Deps`-level note above. Pre-existing dead use case: `users::delete_account::execute` has zero callers anywhere in the workspace, worker included.
pub delete_account: DeleteAccountDeps,
pub get_current_profile: GetCurrentProfileDeps,
pub update_profile_fields: UpdateProfileFieldsDeps,
pub get_settings: GetSettingsDeps,
pub update_settings: UpdateSettingsDeps,
pub authorize_admin: AuthorizeAdminDeps,
pub get_federated_profile: GetFederatedProfileDeps,
}
pub struct WatchlistGroup {
pub add: WatchlistAddDeps,
pub get_watchlist_for_owner: GetWatchlistForOwnerDeps,
pub get_watchlist: GetWatchlistDeps,
pub is_on_watchlist: IsOnWatchlistDeps,
pub remove_from_watchlist: RemoveFromWatchlistDeps,
}
pub struct WrapupGroup {
pub get_ready_report: GetReadyReportDeps,
pub delete_wrapup: DeleteWrapUpDeps,
pub generate: GenerateWrapUpDeps,
pub get_wrapup: GetWrapUpDeps,
pub list_wrapups: ListWrapUpsDeps,
}
/// Every deps struct a handler can need, built once by the composition root.
/// Use cases still receive only their own narrow struct — nothing takes `&Deps`.
///
/// `composition::build_deps` is called only from `crates/presentation/src/main.rs`.
/// The worker-only groups this used to also carry now live in `WorkerDeps`, built by
/// `composition::build_worker_deps` and consumed by `crates/worker/src/main.rs` —
/// `crates/worker` no longer wires its own deps (its former `db.rs` is gone). Nothing
/// in `Deps` below is worker-only anymore, except one field with no consumer anywhere
/// in the workspace — see its comment.
pub struct Deps {
pub auth: AuthGroup,
pub diary: DiaryGroup,
pub goals: GoalsGroup,
pub import: ImportGroup,
pub integrations: IntegrationsGroup,
pub movies: MoviesGroup,
pub person: PersonGroup,
pub search: SearchGroup,
pub social: SocialGroup,
pub users: UsersGroup,
pub watchlist: WatchlistGroup,
pub wrapup: WrapupGroup,
}
/// Ports the worker binary can actually construct — a strict subset of
/// `Services`. The worker has no `auth`, `password_hasher`, `diary_exporter`,
/// `document_parser`, or `review_logger`; those ports have no worker-side use case,
/// so `WorkerServices` simply does not carry them (see ADR / task-2 brief for why
/// this is a separate struct rather than an `Option`-riddled `Services`).
pub struct WorkerServices {
pub object_storage: Arc<dyn ObjectStorage>,
pub event_publisher: Arc<dyn EventPublisher>,
/// `Option` here mirrors `Services::person_enrichment` — genuine optional
/// configuration, not a container-shape workaround.
pub person_enrichment: Option<Arc<dyn PersonEnrichmentClient>>,
}
/// The deps structs the worker binary needs, built by `composition::build_worker_deps`.
/// These are the five groups that moved out of `Deps` during worker unification —
/// they have no consumer the server binary can ever reach.
pub struct WorkerDeps {
pub enrich_movie: EnrichMovieDeps,
pub reindex_search: ReindexSearchDeps,
pub merge_duplicates: MergeDuplicatesDeps,
pub enrich_person: EnrichPersonDeps,
pub handle_requested: HandleWrapUpRequestedDeps,
}

View File

@@ -1,8 +1,8 @@
use std::sync::Arc;
use domain::ports::{
DiaryQuery, EventPublisher, MovieCommand, MovieProfileRepository, MovieQuery, ReviewRepository,
SocialQueryPort,
DiaryExporter, DiaryQuery, EventPublisher, FollowGraphQuery, MovieCommand,
MovieProfileRepository, MovieQuery, ReviewRepository, UserRepository,
};
use crate::config::AppConfig;
@@ -27,6 +27,24 @@ pub struct GetMovieSocialPageDeps {
pub struct GetActivityFeedDeps {
pub diary: Arc<dyn DiaryQuery>,
pub social_query: Arc<dyn SocialQueryPort>,
pub social_query: Arc<dyn FollowGraphQuery>,
pub config: AppConfig,
}
pub struct GetUserFeedDeps {
pub user: Arc<dyn UserRepository>,
pub diary: Arc<dyn DiaryQuery>,
}
pub struct GetDiaryDeps {
pub diary: Arc<dyn DiaryQuery>,
}
pub struct GetReviewHistoryDeps {
pub diary: Arc<dyn DiaryQuery>,
}
pub struct ExportDiaryDeps {
pub diary: Arc<dyn DiaryQuery>,
pub diary_exporter: Arc<dyn DiaryExporter>,
}

View File

@@ -1,21 +1,16 @@
use std::sync::Arc;
use bytes::Bytes;
use domain::{
errors::DomainError,
ports::{DiaryExporter, DiaryQuery},
value_objects::UserId,
};
use domain::{errors::DomainError, value_objects::UserId};
use futures::stream::BoxStream;
use crate::diary::deps::ExportDiaryDeps;
use crate::diary::queries::ExportQuery;
pub fn execute(
diary: &Arc<dyn DiaryQuery>,
diary_exporter: &Arc<dyn DiaryExporter>,
deps: &ExportDiaryDeps,
query: ExportQuery,
) -> BoxStream<'static, Result<Bytes, DomainError>> {
let user_id = UserId::from_uuid(query.user_id);
let entry_stream = diary.stream_user_history(user_id);
diary_exporter.stream_entries(entry_stream, query.format)
let entry_stream = deps.diary.stream_user_history(user_id);
deps.diary_exporter
.stream_entries(entry_stream, query.format)
}

View File

@@ -6,7 +6,7 @@ use domain::{
FeedEntry,
collections::{PageParams, Paginated},
},
value_objects::UserId,
value_objects::{SocialIdentity, UserId},
};
pub async fn execute(
@@ -36,28 +36,24 @@ async fn build_following_filter(
}
let viewer_id = query.viewer_user_id?;
let viewer = UserId::from_uuid(viewer_id);
let urls = deps
let actors = deps
.social_query
.get_accepted_following_urls(&viewer)
.get_following(&viewer)
.await
.unwrap_or_default();
if urls.is_empty() {
if actors.is_empty() {
return Some(FollowingFilter {
local_user_ids: vec![viewer_id],
remote_actor_urls: vec![],
});
}
let base_url = &deps.config.base_url;
let mut local_ids = vec![viewer_id];
let mut remote_urls = Vec::new();
for url in urls {
if let Some(suffix) = url.strip_prefix(&format!("{}/users/", base_url))
&& let Ok(parsed_id) = uuid::Uuid::parse_str(suffix)
{
local_ids.push(parsed_id);
continue;
for actor in actors {
match actor.identity {
SocialIdentity::Local(uid) => local_ids.push(uid.value()),
SocialIdentity::Remote { actor_url } => remote_urls.push(actor_url),
}
remote_urls.push(url);
}
Some(FollowingFilter {
local_user_ids: local_ids,

View File

@@ -1,19 +1,17 @@
use std::sync::Arc;
use domain::{
errors::DomainError,
models::{
DiaryEntry, DiaryFilter, ReviewSortBy,
collections::{PageParams, Paginated},
},
ports::DiaryQuery,
value_objects::{MovieId, UserId},
};
use crate::diary::deps::GetDiaryDeps;
use crate::diary::queries::GetDiaryQuery;
pub async fn execute(
diary: &Arc<dyn DiaryQuery>,
deps: &GetDiaryDeps,
query: GetDiaryQuery,
) -> Result<Paginated<DiaryEntry>, DomainError> {
let page = PageParams::new(query.limit, query.offset)?;
@@ -29,7 +27,7 @@ pub async fn execute(
include_remote: user_id.is_some(),
};
diary.query_diary(&filter).await
deps.diary.query_diary(&filter).await
}
#[cfg(test)]

View File

@@ -1,22 +1,20 @@
use std::sync::Arc;
use domain::{
errors::DomainError,
models::ReviewHistory,
ports::DiaryQuery,
services::review_history::{ReviewHistoryAnalyzer, Trend},
value_objects::MovieId,
};
use crate::diary::deps::GetReviewHistoryDeps;
use crate::diary::queries::GetReviewHistoryQuery;
pub async fn execute(
diary: &Arc<dyn DiaryQuery>,
deps: &GetReviewHistoryDeps,
query: GetReviewHistoryQuery,
) -> Result<(ReviewHistory, Trend), DomainError> {
let movie_id = MovieId::from_uuid(query.movie_id);
let mut history = diary.get_review_history(&movie_id).await?;
let mut history = deps.diary.get_review_history(&movie_id).await?;
let trend = ReviewHistoryAnalyzer::rating_trend(&history)?;

View File

@@ -0,0 +1,61 @@
use domain::{
errors::DomainError, models::DiaryEntry, models::ReviewSortBy, value_objects::UserId,
};
use uuid::Uuid;
use crate::diary::deps::{GetDiaryDeps, GetUserFeedDeps};
use crate::diary::get_diary;
use crate::diary::queries::GetDiaryQuery;
/// The RSS feed's author line — derived the same way the deleted handler code
/// derived its page title: from the local part of the user's email, not their
/// username.
pub struct FeedAuthor {
pub display_name: String,
}
pub struct UserFeed {
pub author: FeedAuthor,
pub entries: Vec<DiaryEntry>,
}
pub async fn execute(
deps: &GetUserFeedDeps,
user_id: Uuid,
limit: u32,
) -> Result<UserFeed, DomainError> {
let user = deps
.user
.find_by_id(&UserId::from_uuid(user_id))
.await?
.ok_or_else(|| DomainError::NotFound(format!("User {user_id}")))?;
let query = GetDiaryQuery {
limit: Some(limit),
offset: Some(0),
sort_by: Some(ReviewSortBy::Descending),
movie_id: None,
user_id: Some(user_id),
};
let get_diary_deps = GetDiaryDeps {
diary: deps.diary.clone(),
};
let page = get_diary::execute(&get_diary_deps, query).await?;
let display_name = user
.email()
.value()
.split('@')
.next()
.unwrap_or("User")
.to_string();
Ok(UserFeed {
author: FeedAuthor { display_name },
entries: page.items,
})
}
#[cfg(test)]
#[path = "tests/get_user_feed.rs"]
mod tests;

View File

@@ -7,6 +7,7 @@ pub mod get_activity_feed;
pub mod get_diary;
pub mod get_movie_social_page;
pub mod get_review_history;
pub mod get_user_feed;
pub mod log_review;
pub mod movie_resolver;
pub mod queries;

View File

@@ -2,7 +2,8 @@ use std::sync::Arc;
use async_trait::async_trait;
use domain::errors::DomainError;
use domain::testing::{FakeDiaryQuery, NoopSocialQueryPort};
use domain::testing::InMemorySocialRepository;
use domain::value_objects::{FollowRelation, SocialActor, SocialIdentity, UserId};
use crate::{
config::AppConfig, diary::deps::GetActivityFeedDeps, diary::get_activity_feed,
@@ -11,8 +12,8 @@ use crate::{
fn default_deps() -> GetActivityFeedDeps {
GetActivityFeedDeps {
diary: FakeDiaryQuery::new() as _,
social_query: Arc::new(NoopSocialQueryPort),
diary: domain::testing::FakeDiaryQuery::new() as _,
social_query: InMemorySocialRepository::new() as _,
config: TestContextBuilder::new().config,
}
}
@@ -59,60 +60,69 @@ async fn returns_feed_with_following_filter() {
.await
.unwrap();
// NoopSocialQueryPort returns empty following, so FollowingFilter
// contains only the viewer's id. Feed is empty but the code path is hit.
assert!(result.items.is_empty());
}
struct FakeSocialWithFollowing(Vec<String>);
struct FakeSocialWithFollowing(Vec<SocialActor>);
#[async_trait]
impl domain::ports::SocialQueryPort for FakeSocialWithFollowing {
async fn get_accepted_following_urls(
&self,
_: &domain::value_objects::UserId,
) -> Result<Vec<String>, DomainError> {
impl domain::ports::FollowGraphQuery for FakeSocialWithFollowing {
async fn get_following(&self, _: &UserId) -> Result<Vec<SocialActor>, DomainError> {
Ok(self.0.clone())
}
async fn count_following(
&self,
_: &domain::value_objects::UserId,
) -> Result<usize, DomainError> {
Ok(0)
}
async fn count_accepted_followers(
&self,
_: &domain::value_objects::UserId,
) -> Result<usize, DomainError> {
Ok(0)
}
async fn get_pending_followers(
&self,
_: &domain::value_objects::UserId,
) -> Result<Vec<domain::models::PendingFollowerInfo>, DomainError> {
async fn get_followers(&self, _: &UserId) -> Result<Vec<SocialActor>, DomainError> {
Ok(vec![])
}
async fn list_all_followed_remote_actors(
&self,
) -> Result<Vec<domain::models::RemoteActorInfo>, DomainError> {
async fn get_pending_followers(&self, _: &UserId) -> Result<Vec<SocialActor>, DomainError> {
Ok(vec![])
}
async fn get_pending_following(&self, _: &UserId) -> Result<Vec<SocialActor>, DomainError> {
Ok(vec![])
}
async fn count_following(&self, _: &UserId) -> Result<usize, DomainError> {
Ok(0)
}
async fn count_followers(&self, _: &UserId) -> Result<usize, DomainError> {
Ok(0)
}
async fn count_pending_followers(&self, _: &UserId) -> Result<usize, DomainError> {
Ok(0)
}
async fn get_relation(
&self,
_: &UserId,
_: &SocialIdentity,
) -> Result<FollowRelation, DomainError> {
Ok(FollowRelation::default())
}
}
#[tokio::test]
async fn following_filter_parses_local_and_remote_urls() {
async fn following_filter_separates_local_and_remote() {
let viewer = uuid::Uuid::new_v4();
let local_friend = uuid::Uuid::new_v4();
let following_urls = vec![
format!("http://localhost:3000/users/{}", local_friend),
"https://remote.example/actor/1".to_string(),
let following = vec![
SocialActor {
identity: SocialIdentity::Local(UserId::from_uuid(local_friend)),
handle: "friend".into(),
display_name: None,
avatar_url: None,
},
SocialActor {
identity: SocialIdentity::Remote {
actor_url: "https://remote.example/actor/1".into(),
},
handle: "@alice@remote.example".into(),
display_name: None,
avatar_url: None,
},
];
let social = Arc::new(FakeSocialWithFollowing(following_urls));
let social = Arc::new(FakeSocialWithFollowing(following));
let deps = GetActivityFeedDeps {
diary: FakeDiaryQuery::new() as _,
diary: domain::testing::FakeDiaryQuery::new() as _,
social_query: social as _,
config: AppConfig {
allow_registration: true,
@@ -141,8 +151,6 @@ async fn following_filter_parses_local_and_remote_urls() {
.await
.unwrap();
// Feed is empty (no data seeded), but the build_following_filter code path
// with actual URL parsing ran without errors.
assert!(result.items.is_empty());
}
@@ -164,6 +172,5 @@ async fn following_filter_without_viewer_returns_none() {
.await
.unwrap();
// filter_following=true but viewer_user_id=None → build_following_filter returns None
assert!(result.items.is_empty());
}

View File

@@ -1,14 +1,15 @@
use domain::testing::FakeDiaryQuery;
use std::sync::Arc;
use crate::{diary::get_diary, diary::queries::GetDiaryQuery};
use crate::{diary::deps::GetDiaryDeps, diary::get_diary, diary::queries::GetDiaryQuery};
#[tokio::test]
async fn returns_empty_page() {
let diary = FakeDiaryQuery::new() as Arc<dyn domain::ports::DiaryQuery>;
let deps = GetDiaryDeps { diary };
let result = get_diary::execute(
&diary,
&deps,
GetDiaryQuery {
limit: None,
offset: None,

Some files were not shown because too many files have changed in this diff Show More