Compare commits
163 Commits
master
...
2da2075d03
| Author | SHA1 | Date | |
|---|---|---|---|
| 2da2075d03 | |||
| f23392751d | |||
| 51f4770c23 | |||
| 5da979649b | |||
| 000c74d3b3 | |||
| 3ba5d61d5b | |||
| 63746ade50 | |||
| f2761b8e97 | |||
| 08d0734d03 | |||
| 595460373b | |||
| 3714b6d7a7 | |||
| 660a8d618d | |||
| 126ab43287 | |||
| 44273457ae | |||
| 4b9fd8168d | |||
| d9613308a3 | |||
| 1f5c05a5a2 | |||
| 3342905e22 | |||
| c8fe4a77d1 | |||
| ed8ca1d220 | |||
| fdd5dbc935 | |||
| 6cab2166a7 | |||
| 5bf750e0fc | |||
| 3d905fc39b | |||
| 35fffeef67 | |||
| d668d54cc3 | |||
| 0d32de993b | |||
| 8d78babda0 | |||
| cf99332dc4 | |||
| 0b1824d874 | |||
| e445a5eaf4 | |||
| a714c53a07 | |||
| ae7ff757d0 | |||
| 6323322d97 | |||
| fe55d694f9 | |||
| dda8b32e6a | |||
| d75db17ece | |||
| 642d7ef3d0 | |||
| 5df26b69a0 | |||
| c3af91ea7b | |||
| 4425c72f36 | |||
| e7e5d9935d | |||
| 6d2b415075 | |||
| 87cb36f9fe | |||
| bacf7b7252 | |||
| c4b6d52196 | |||
| ffb323dbbf | |||
| 0a18992a73 | |||
| b0ce316c30 | |||
| 0d3c2c937d | |||
| 86909ecede | |||
| 482575aed0 | |||
| 377ee1d176 | |||
| 9cda5b4681 | |||
| 74fb893751 | |||
| 32b114cecd | |||
| bd571b3b51 | |||
| f226071cbd | |||
| aaa9cb0a1e | |||
| 31dba4ca95 | |||
| 1b3f906312 | |||
| 465d233ae9 | |||
| 1f03889b30 | |||
| 4159e60148 | |||
| d66a89059d | |||
| b3c243257d | |||
| e1f2442e77 | |||
| 7a66661932 | |||
| b30a6a102b | |||
| 38a3aa6bbf | |||
| 3135a15cb3 | |||
| d083f8ae3d | |||
| 874c406d4a | |||
| 78e1f4ef72 | |||
| cf74b06b4a | |||
| 317898d51b | |||
| 790bb6fbb5 | |||
| 658df38788 | |||
| cff0f854fa | |||
| 66ade70273 | |||
| cbd2ac5b3e | |||
| 0433cd4d9b | |||
| b5a8ea2395 | |||
| 49b79799c1 | |||
| f4aba551a2 | |||
| 91df35dbd3 | |||
| 623f90e43f | |||
| e28f628c80 | |||
| 60c25d4c24 | |||
| 22aafe99be | |||
| 0ff22cca5f | |||
| ccc39e27e4 | |||
| 76319756f4 | |||
| 7703227970 | |||
| b9933bb48d | |||
| 0c48708ce6 | |||
| a2a889bced | |||
| a4846f3bea | |||
| 27be840faa | |||
| 965fc0eda8 | |||
| d700b85337 | |||
| ffbab75910 | |||
| dda7c40f7f | |||
| 1b827b1bdd | |||
| 1ee6873a60 | |||
| 7352b533ff | |||
| 85e254fee2 | |||
| fa8221322d | |||
| 38da37de55 | |||
| f3dedbad8a | |||
| d468ce131f | |||
| d034af9e9c | |||
| 59d308f41b | |||
| bbb2ee00d6 | |||
| 5dd9aac68d | |||
| 6dcc4c8317 | |||
| e31d99a240 | |||
| 41fec1efa5 | |||
| 160c08d1c4 | |||
| 7aa6d7bf4d | |||
| 144f2f8e0c | |||
| cff64f7a6b | |||
| 5baff54cb9 | |||
| f94d2db8b1 | |||
| 48875a6e86 | |||
| 9387ae705b | |||
| 9871e21bc0 | |||
| fa8efbaa23 | |||
| d769a5b55c | |||
| 8e1fb1a974 | |||
| 6145b873f5 | |||
| cc668ae44d | |||
| e5097c22dd | |||
| 450468ef3d | |||
| 6e7c6467a7 | |||
| 7f815f8207 | |||
| 5df89200d4 | |||
| eb273dc277 | |||
| 5689db0ad7 | |||
| 5c70b8b8be | |||
| 4c547df04e | |||
| 602df8df22 | |||
| 5b69a3a7c0 | |||
| a38f78d261 | |||
| 17f90726e8 | |||
| 563f33212e | |||
| 8e5ac9f433 | |||
| f790fa2a0f | |||
| edcf3c1170 | |||
| 1985d2c57f | |||
| f0b3d8ad90 | |||
| da72ab1446 | |||
| 93c65cd155 | |||
| ba42d3d445 | |||
| 819332522a | |||
| 79a06e6844 | |||
| 97a496553a | |||
| 5a58625265 | |||
| 6d9ac07dfc | |||
| b6a7cf9417 | |||
| c4b39c9410 | |||
| f60cc368b6 | |||
| 65bab7fd44 |
@@ -1,2 +1,2 @@
|
|||||||
[registries.gitea]
|
[env]
|
||||||
index = "sparse+https://git.gabrielkaszewski.dev/api/packages/GKaszewski/cargo/"
|
SQLX_OFFLINE = "true"
|
||||||
|
|||||||
@@ -4,20 +4,6 @@ target/
|
|||||||
*.db
|
*.db
|
||||||
*.db-shm
|
*.db-shm
|
||||||
*.db-wal
|
*.db-wal
|
||||||
# .cargo is needed at build time (registry config)
|
# .cargo and .sqlx are needed at build time (SQLX_OFFLINE mode)
|
||||||
docs/
|
docs/
|
||||||
dev.db
|
dev.db
|
||||||
spa/node_modules/
|
|
||||||
spa/dist/
|
|
||||||
spa/.env
|
|
||||||
spa/.env.local
|
|
||||||
.sqlx/
|
|
||||||
.superpowers/
|
|
||||||
.worktrees/
|
|
||||||
.claude/
|
|
||||||
.github/
|
|
||||||
.gitea/
|
|
||||||
imgs/
|
|
||||||
screenshots/
|
|
||||||
test_data/
|
|
||||||
*.md
|
|
||||||
|
|||||||
86
.env.example
86
.env.example
@@ -1,60 +1,60 @@
|
|||||||
# ── Required ──────────────────────────────────────────────────
|
# Database backend — "sqlite" (default) or "postgres"
|
||||||
|
DATABASE_BACKEND=sqlite
|
||||||
|
|
||||||
# Database (SQLite — file auto-created on first run)
|
# Option A: SQLite (default, zero external dependencies)
|
||||||
DATABASE_URL=sqlite:///data/movies.db
|
DATABASE_URL=sqlite://movies.db
|
||||||
|
|
||||||
|
# Option B: PostgreSQL
|
||||||
|
# DATABASE_BACKEND=postgres
|
||||||
|
# DATABASE_URL=postgres://user:password@localhost:5432/movies_diary
|
||||||
|
|
||||||
# Authentication
|
# Authentication
|
||||||
JWT_SECRET=change-me-to-a-random-string
|
JWT_SECRET=change-me
|
||||||
|
JWT_TTL_SECONDS=86400
|
||||||
|
|
||||||
# Movie metadata — one of these is required (TMDB preferred)
|
# OMDb/TMDB metadata
|
||||||
# TMDB_API_KEY=your-tmdb-key
|
OMDB_API_KEY=your-key
|
||||||
OMDB_API_KEY=your-omdb-key
|
TMDB_API_KEY=your-key
|
||||||
|
|
||||||
# ── Recommended ──────────────────────────────────────────────
|
# Poster storage — Option A (local) is active. To use S3, comment it out and uncomment Option B:
|
||||||
|
|
||||||
# Public URL (used for ActivityPub federation and canonical links)
|
# Option A: local filesystem (zero external dependencies)
|
||||||
BASE_URL=https://yourdomain.example.com
|
POSTER_STORAGE_BACKEND=local
|
||||||
|
POSTER_STORAGE_PATH=./posters
|
||||||
|
|
||||||
# Enable sign-ups (default: false — set true so you can register)
|
# Option B: S3-compatible (MinIO, AWS S3, etc.)
|
||||||
ALLOW_REGISTRATION=true
|
# POSTER_STORAGE_BACKEND=s3
|
||||||
|
|
||||||
# ── Image Storage (defaults to local filesystem) ─────────────
|
|
||||||
|
|
||||||
# IMAGE_STORAGE_BACKEND=local # default
|
|
||||||
# IMAGE_STORAGE_PATH=./images # default
|
|
||||||
|
|
||||||
# S3-compatible alternative (MinIO, AWS S3, etc.):
|
|
||||||
# IMAGE_STORAGE_BACKEND=s3
|
|
||||||
# MINIO_ENDPOINT=http://localhost:9000
|
# MINIO_ENDPOINT=http://localhost:9000
|
||||||
# MINIO_BUCKET=posters
|
# MINIO_BUCKET=posters
|
||||||
# MINIO_REGION=minio
|
# MINIO_REGION=minio
|
||||||
# MINIO_ACCESS_KEY_ID=minioadmin
|
# MINIO_ACCESS_KEY_ID=minioadmin
|
||||||
# MINIO_SECRET_ACCESS_KEY=minioadmin
|
# MINIO_SECRET_ACCESS_KEY=minioadmin
|
||||||
|
|
||||||
# ── Optional ─────────────────────────────────────────────────
|
# Optional
|
||||||
|
HOST=0.0.0.0
|
||||||
|
PORT=3000
|
||||||
|
BASE_URL=http://localhost:3000
|
||||||
|
SECURE_COOKIES=false
|
||||||
|
ALLOW_REGISTRATION=false
|
||||||
|
RATE_LIMIT=20
|
||||||
|
POSTER_FETCH_TIMEOUT_SECONDS=30
|
||||||
|
|
||||||
# TMDb enrichment (cast, crew, genres — separate from search metadata above)
|
# Event bus — "db" (default) or "nats"
|
||||||
# TMDB_API_KEY=your-tmdb-key
|
# The worker binary must run alongside the presentation to process events.
|
||||||
|
EVENT_BUS_BACKEND=db
|
||||||
|
|
||||||
# Image conversion (converts uploaded posters to AVIF or WebP)
|
# Option A: DB queue (default — no extra infrastructure needed)
|
||||||
# IMAGE_CONVERSION_ENABLED=false
|
# Events are persisted in the same database as the app and polled by the worker.
|
||||||
# IMAGE_CONVERSION_FORMAT=avif
|
# EVENT_QUEUE_POLL_INTERVAL_MS=500 # polling interval (default: 500ms)
|
||||||
|
# EVENT_QUEUE_BATCH_SIZE=10 # rows claimed per poll cycle (default: 10)
|
||||||
|
# EVENT_QUEUE_MAX_ATTEMPTS=5 # retries before dead-lettering (default: 5)
|
||||||
|
|
||||||
# Server
|
# Option B: NATS (at-least-once delivery, recommended for higher throughput)
|
||||||
# HOST=0.0.0.0
|
# EVENT_BUS_BACKEND=nats
|
||||||
# PORT=3000
|
|
||||||
# RATE_LIMIT=60
|
|
||||||
# SECURE_COOKIES=true
|
|
||||||
# Handler-level logs come from the `http_axum` crate; startup/wiring logs come
|
|
||||||
# from `bootstrap`; config-load logs come from `config`. Include all three —
|
|
||||||
# `server=info` alone silently drops them.
|
|
||||||
# Crates not named here (adapters, etc.) still log warnings and errors unless
|
|
||||||
# you set a bare level yourself (e.g. `info,http_axum=debug`).
|
|
||||||
# RUST_LOG=server=info,worker=info,bootstrap=info,config=info,http_axum=info,tower_http=info
|
|
||||||
|
|
||||||
# CORS (for SPA development only)
|
|
||||||
# CORS_ORIGINS=http://localhost:5173
|
|
||||||
|
|
||||||
# Event bus — "db" (default, uses same database) or "nats"
|
|
||||||
# EVENT_BUS_BACKEND=db
|
|
||||||
# NATS_URL=nats://localhost:4222
|
# NATS_URL=nats://localhost:4222
|
||||||
|
# NATS_MODE=jetstream # "jetstream" (default, at-least-once) or "core" (fire-and-forget)
|
||||||
|
# NATS_SUBJECT_PREFIX=movies-diary.events
|
||||||
|
# NATS_STREAM_NAME=MOVIES_DIARY_EVENTS
|
||||||
|
# NATS_CONSUMER_NAME=worker
|
||||||
|
|
||||||
|
RUST_LOG=presentation=debug,tower_http=debug,worker=info,application=info
|
||||||
|
|||||||
@@ -1,43 +0,0 @@
|
|||||||
name: CI
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: ["**"]
|
|
||||||
pull_request:
|
|
||||||
|
|
||||||
env:
|
|
||||||
CARGO_TERM_COLOR: always
|
|
||||||
RUST_BACKTRACE: 1
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
ci:
|
|
||||||
name: Check / Test
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Install Rust stable
|
|
||||||
uses: dtolnay/rust-toolchain@stable
|
|
||||||
with:
|
|
||||||
components: rustfmt, clippy
|
|
||||||
|
|
||||||
- name: Cache cargo
|
|
||||||
uses: Swatinem/rust-cache@v2
|
|
||||||
|
|
||||||
- name: fmt
|
|
||||||
run: cargo fmt --all -- --check
|
|
||||||
|
|
||||||
- name: clippy
|
|
||||||
run: cargo clippy --workspace --all-targets -- -D warnings
|
|
||||||
|
|
||||||
- name: test
|
|
||||||
run: cargo test --workspace
|
|
||||||
|
|
||||||
- name: test (federation off)
|
|
||||||
run: cargo test --workspace --no-default-features
|
|
||||||
|
|
||||||
# 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-handler-services check-http-adapter-deps check-federation-off-social check-sqlite-is-ap-free check-binaries-are-thin check-federation-off-deps check-nats-isolated check-no-second-web-stack
|
|
||||||
87
.github/workflows/ci.yml
vendored
87
.github/workflows/ci.yml
vendored
@@ -1,87 +0,0 @@
|
|||||||
name: CI
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: ["**"]
|
|
||||||
pull_request:
|
|
||||||
|
|
||||||
env:
|
|
||||||
CARGO_TERM_COLOR: always
|
|
||||||
RUST_BACKTRACE: 1
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
ci:
|
|
||||||
name: Check / Test
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Install Rust stable
|
|
||||||
uses: dtolnay/rust-toolchain@stable
|
|
||||||
with:
|
|
||||||
components: rustfmt, clippy
|
|
||||||
|
|
||||||
- name: Cache cargo
|
|
||||||
uses: Swatinem/rust-cache@v2
|
|
||||||
|
|
||||||
- name: fmt
|
|
||||||
run: cargo fmt --all -- --check
|
|
||||||
|
|
||||||
- name: clippy
|
|
||||||
run: cargo clippy --workspace --all-targets -- -D warnings
|
|
||||||
|
|
||||||
- name: test
|
|
||||||
run: cargo test --workspace
|
|
||||||
|
|
||||||
- name: test (federation off)
|
|
||||||
run: cargo test --workspace --no-default-features
|
|
||||||
|
|
||||||
# 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-handler-services check-http-adapter-deps check-federation-off-social check-sqlite-is-ap-free check-binaries-are-thin check-federation-off-deps check-nats-isolated check-no-second-web-stack
|
|
||||||
|
|
||||||
docker:
|
|
||||||
name: Build & Push Docker Image
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: ci
|
|
||||||
if: github.ref == 'refs/heads/master' || startsWith(github.ref, 'refs/tags/v')
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
packages: write
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Set up Buildx
|
|
||||||
uses: docker/setup-buildx-action@v3
|
|
||||||
|
|
||||||
- name: Log in to GHCR
|
|
||||||
uses: docker/login-action@v3
|
|
||||||
with:
|
|
||||||
registry: ghcr.io
|
|
||||||
username: ${{ github.repository_owner }}
|
|
||||||
password: ${{ secrets.GHCR_TOKEN || github.token }}
|
|
||||||
|
|
||||||
- name: Docker metadata
|
|
||||||
id: meta
|
|
||||||
uses: docker/metadata-action@v5
|
|
||||||
with:
|
|
||||||
images: ghcr.io/${{ github.repository }}
|
|
||||||
tags: |
|
|
||||||
type=raw,value=latest,enable={{is_default_branch}}
|
|
||||||
type=semver,pattern={{version}}
|
|
||||||
type=semver,pattern={{major}}.{{minor}}
|
|
||||||
type=sha,prefix=
|
|
||||||
|
|
||||||
- name: Build and push
|
|
||||||
uses: docker/build-push-action@v6
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
push: true
|
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
|
||||||
build-args: FEATURES=federation
|
|
||||||
cache-from: type=gha
|
|
||||||
cache-to: type=gha,mode=max
|
|
||||||
7
.gitignore
vendored
7
.gitignore
vendored
@@ -13,9 +13,4 @@
|
|||||||
|
|
||||||
.worktrees/
|
.worktrees/
|
||||||
.superpowers/
|
.superpowers/
|
||||||
docs/*
|
docs/
|
||||||
!docs/adr/
|
|
||||||
|
|
||||||
imgs/
|
|
||||||
.sqlx/
|
|
||||||
!crates/adapters/sqlite/tests/fixtures/*.db
|
|
||||||
|
|||||||
98
.sqlx/query-05d958c1fa38095ae2b5b81ede48fc85702d8c39c6301839de7b4d27f4a4d41b.json
generated
Normal file
98
.sqlx/query-05d958c1fa38095ae2b5b81ede48fc85702d8c39c6301839de7b4d27f4a4d41b.json
generated
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,\n r.id AS review_id, r.movie_id, r.user_id, r.rating, r.comment, r.watched_at, r.created_at, r.remote_actor_url\n FROM reviews r\n INNER JOIN movies m ON m.id = r.movie_id\n WHERE r.movie_id = ?\n ORDER BY r.watched_at DESC\n LIMIT ? OFFSET ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "external_metadata_id",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "title",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "release_year",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "director",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "poster_path",
|
||||||
|
"ordinal": 5,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "review_id",
|
||||||
|
"ordinal": 6,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "movie_id",
|
||||||
|
"ordinal": 7,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "user_id",
|
||||||
|
"ordinal": 8,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "rating",
|
||||||
|
"ordinal": 9,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "comment",
|
||||||
|
"ordinal": 10,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "watched_at",
|
||||||
|
"ordinal": 11,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_at",
|
||||||
|
"ordinal": 12,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "remote_actor_url",
|
||||||
|
"ordinal": 13,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 3
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "05d958c1fa38095ae2b5b81ede48fc85702d8c39c6301839de7b4d27f4a4d41b"
|
||||||
|
}
|
||||||
20
.sqlx/query-0963b9661182e139cd760bbabb0d6ea3a301a2a3adbdfdda4a88f333a1144c77.json
generated
Normal file
20
.sqlx/query-0963b9661182e139cd760bbabb0d6ea3a301a2a3adbdfdda4a88f333a1144c77.json
generated
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT COUNT(*) FROM reviews",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "COUNT(*)",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Integer"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 0
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "0963b9661182e139cd760bbabb0d6ea3a301a2a3adbdfdda4a88f333a1144c77"
|
||||||
|
}
|
||||||
12
.sqlx/query-0acf3515a4d1bef7a2458d878481ba3b11c9f252311579f7daba335f70d78f07.json
generated
Normal file
12
.sqlx/query-0acf3515a4d1bef7a2458d878481ba3b11c9f252311579f7daba335f70d78f07.json
generated
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "INSERT INTO users (id, email, username, password_hash, created_at, role) VALUES (?, ?, ?, ?, ?, ?)",
|
||||||
|
"describe": {
|
||||||
|
"columns": [],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 6
|
||||||
|
},
|
||||||
|
"nullable": []
|
||||||
|
},
|
||||||
|
"hash": "0acf3515a4d1bef7a2458d878481ba3b11c9f252311579f7daba335f70d78f07"
|
||||||
|
}
|
||||||
98
.sqlx/query-106b5b65162314c47217c26b7e89194094e10122ea596e8d9323968e600635a9.json
generated
Normal file
98
.sqlx/query-106b5b65162314c47217c26b7e89194094e10122ea596e8d9323968e600635a9.json
generated
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,\n r.id AS review_id, r.movie_id, r.user_id, r.rating, r.comment, r.watched_at, r.created_at, r.remote_actor_url\n FROM reviews r\n INNER JOIN movies m ON m.id = r.movie_id\n WHERE r.user_id = ?\n ORDER BY r.watched_at DESC",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "external_metadata_id",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "title",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "release_year",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "director",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "poster_path",
|
||||||
|
"ordinal": 5,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "review_id",
|
||||||
|
"ordinal": 6,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "movie_id",
|
||||||
|
"ordinal": 7,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "user_id",
|
||||||
|
"ordinal": 8,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "rating",
|
||||||
|
"ordinal": 9,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "comment",
|
||||||
|
"ordinal": 10,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "watched_at",
|
||||||
|
"ordinal": 11,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_at",
|
||||||
|
"ordinal": 12,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "remote_actor_url",
|
||||||
|
"ordinal": 13,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "106b5b65162314c47217c26b7e89194094e10122ea596e8d9323968e600635a9"
|
||||||
|
}
|
||||||
12
.sqlx/query-1c70d5d455e5ab3dfb68d35ce5255c7e0e86b9f6549ae8ae09247806f1321086.json
generated
Normal file
12
.sqlx/query-1c70d5d455e5ab3dfb68d35ce5255c7e0e86b9f6549ae8ae09247806f1321086.json
generated
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "DELETE FROM import_sessions WHERE expires_at < datetime('now')",
|
||||||
|
"describe": {
|
||||||
|
"columns": [],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 0
|
||||||
|
},
|
||||||
|
"nullable": []
|
||||||
|
},
|
||||||
|
"hash": "1c70d5d455e5ab3dfb68d35ce5255c7e0e86b9f6549ae8ae09247806f1321086"
|
||||||
|
}
|
||||||
98
.sqlx/query-25fd01355c929a83daf2c802b8ae3adaa4ce73fc037e2bf2a87d60187aeb7361.json
generated
Normal file
98
.sqlx/query-25fd01355c929a83daf2c802b8ae3adaa4ce73fc037e2bf2a87d60187aeb7361.json
generated
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,\n r.id AS review_id, r.movie_id, r.user_id, r.rating, r.comment, r.watched_at, r.created_at, r.remote_actor_url\n FROM reviews r\n INNER JOIN movies m ON m.id = r.movie_id\n ORDER BY r.watched_at ASC\n LIMIT ? OFFSET ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "external_metadata_id",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "title",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "release_year",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "director",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "poster_path",
|
||||||
|
"ordinal": 5,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "review_id",
|
||||||
|
"ordinal": 6,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "movie_id",
|
||||||
|
"ordinal": 7,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "user_id",
|
||||||
|
"ordinal": 8,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "rating",
|
||||||
|
"ordinal": 9,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "comment",
|
||||||
|
"ordinal": 10,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "watched_at",
|
||||||
|
"ordinal": 11,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_at",
|
||||||
|
"ordinal": 12,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "remote_actor_url",
|
||||||
|
"ordinal": 13,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 2
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "25fd01355c929a83daf2c802b8ae3adaa4ce73fc037e2bf2a87d60187aeb7361"
|
||||||
|
}
|
||||||
38
.sqlx/query-2c7353f34c4748d4d4be6abbf343fa7ea30eeb985c4bfd12b0fc3997d1ba03bb.json
generated
Normal file
38
.sqlx/query-2c7353f34c4748d4d4be6abbf343fa7ea30eeb985c4bfd12b0fc3997d1ba03bb.json
generated
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT u.id AS \"id!: String\",\n u.email AS \"email!: String\",\n COUNT(DISTINCT r.movie_id) AS \"total_movies!: i64\",\n AVG(CAST(r.rating AS REAL)) AS avg_rating\n FROM users u\n LEFT JOIN reviews r ON r.user_id = u.id AND r.remote_actor_url IS NULL\n GROUP BY u.id, u.email\n ORDER BY u.email ASC",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id!: String",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "email!: String",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "total_movies!: i64",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "avg_rating",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Float"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 0
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "2c7353f34c4748d4d4be6abbf343fa7ea30eeb985c4bfd12b0fc3997d1ba03bb"
|
||||||
|
}
|
||||||
50
.sqlx/query-3047579c6ed13ce87aad9b9ce6300c02f0df3516979518976e13f9d9abc6a403.json
generated
Normal file
50
.sqlx/query-3047579c6ed13ce87aad9b9ce6300c02f0df3516979518976e13f9d9abc6a403.json
generated
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT id, external_metadata_id, title, release_year, director, poster_path\n FROM movies WHERE title = ? AND release_year = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "external_metadata_id",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "title",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "release_year",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "director",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "poster_path",
|
||||||
|
"ordinal": 5,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 2
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "3047579c6ed13ce87aad9b9ce6300c02f0df3516979518976e13f9d9abc6a403"
|
||||||
|
}
|
||||||
44
.sqlx/query-319b5d09824809a971f6c9546dde6389a0aca5a732531bb9ca9b99675d0a89f4.json
generated
Normal file
44
.sqlx/query-319b5d09824809a971f6c9546dde6389a0aca5a732531bb9ca9b99675d0a89f4.json
generated
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT id, email, username, password_hash, role FROM users WHERE username = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "email",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "username",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "password_hash",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "role",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "319b5d09824809a971f6c9546dde6389a0aca5a732531bb9ca9b99675d0a89f4"
|
||||||
|
}
|
||||||
50
.sqlx/query-33d0dae7d16b0635c1c7eb5afd10824bb55af7cc7a854f590d326622863759d1.json
generated
Normal file
50
.sqlx/query-33d0dae7d16b0635c1c7eb5afd10824bb55af7cc7a854f590d326622863759d1.json
generated
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT id, external_metadata_id, title, release_year, director, poster_path\n FROM movies WHERE id = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "external_metadata_id",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "title",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "release_year",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "director",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "poster_path",
|
||||||
|
"ordinal": 5,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "33d0dae7d16b0635c1c7eb5afd10824bb55af7cc7a854f590d326622863759d1"
|
||||||
|
}
|
||||||
12
.sqlx/query-34a0a7b5e6a7f2b97b59e9de6a34b41a7128a465c0957915c7ed7031c6b83fb0.json
generated
Normal file
12
.sqlx/query-34a0a7b5e6a7f2b97b59e9de6a34b41a7128a465c0957915c7ed7031c6b83fb0.json
generated
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "DELETE FROM import_sessions WHERE user_id = ? AND expires_at < datetime('now')",
|
||||||
|
"describe": {
|
||||||
|
"columns": [],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": []
|
||||||
|
},
|
||||||
|
"hash": "34a0a7b5e6a7f2b97b59e9de6a34b41a7128a465c0957915c7ed7031c6b83fb0"
|
||||||
|
}
|
||||||
20
.sqlx/query-4b3074b532342c6356ee0e8e4d8c4a830f016234bb690e1f6240f02824d6d84f.json
generated
Normal file
20
.sqlx/query-4b3074b532342c6356ee0e8e4d8c4a830f016234bb690e1f6240f02824d6d84f.json
generated
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT COUNT(*) FROM reviews WHERE movie_id = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "COUNT(*)",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Integer"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "4b3074b532342c6356ee0e8e4d8c4a830f016234bb690e1f6240f02824d6d84f"
|
||||||
|
}
|
||||||
20
.sqlx/query-4d85f0ff9732576bba77dc84d3885a0002c2b600c34ba4d99f1e1c5e99f35e75.json
generated
Normal file
20
.sqlx/query-4d85f0ff9732576bba77dc84d3885a0002c2b600c34ba4d99f1e1c5e99f35e75.json
generated
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT strftime('%Y-%m', watched_at) AS month\n FROM reviews\n WHERE user_id = ?\n GROUP BY month\n ORDER BY COUNT(*) DESC\n LIMIT 1",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "month",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "4d85f0ff9732576bba77dc84d3885a0002c2b600c34ba4d99f1e1c5e99f35e75"
|
||||||
|
}
|
||||||
12
.sqlx/query-6638569b8759b965f8919f4998a8665b15c14fc0b4f6018e548b76474254073e.json
generated
Normal file
12
.sqlx/query-6638569b8759b965f8919f4998a8665b15c14fc0b4f6018e548b76474254073e.json
generated
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "INSERT OR REPLACE INTO import_profiles (id, user_id, name, field_mappings, created_at)\n VALUES (?, ?, ?, ?, ?)",
|
||||||
|
"describe": {
|
||||||
|
"columns": [],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 5
|
||||||
|
},
|
||||||
|
"nullable": []
|
||||||
|
},
|
||||||
|
"hash": "6638569b8759b965f8919f4998a8665b15c14fc0b4f6018e548b76474254073e"
|
||||||
|
}
|
||||||
12
.sqlx/query-759b45ac8426d93d4668e208003d52957f2f52d8a021cc6f117cb6f241689a07.json
generated
Normal file
12
.sqlx/query-759b45ac8426d93d4668e208003d52957f2f52d8a021cc6f117cb6f241689a07.json
generated
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "UPDATE import_sessions SET field_mappings = ?, row_results = ? WHERE id = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 3
|
||||||
|
},
|
||||||
|
"nullable": []
|
||||||
|
},
|
||||||
|
"hash": "759b45ac8426d93d4668e208003d52957f2f52d8a021cc6f117cb6f241689a07"
|
||||||
|
}
|
||||||
44
.sqlx/query-79af0324db4d0b8e4bd66e12816583598865630241deffbb8b4175fa7a755099.json
generated
Normal file
44
.sqlx/query-79af0324db4d0b8e4bd66e12816583598865630241deffbb8b4175fa7a755099.json
generated
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT id, email, username, password_hash, role FROM users WHERE id = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "email",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "username",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "password_hash",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "role",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "79af0324db4d0b8e4bd66e12816583598865630241deffbb8b4175fa7a755099"
|
||||||
|
}
|
||||||
50
.sqlx/query-7bc4aebcb94547976d3d7e063e4e908fc22b977b3cbf063ee93ffe4648c42011.json
generated
Normal file
50
.sqlx/query-7bc4aebcb94547976d3d7e063e4e908fc22b977b3cbf063ee93ffe4648c42011.json
generated
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT id, external_metadata_id, title, release_year, director, poster_path\n FROM movies WHERE external_metadata_id = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "external_metadata_id",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "title",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "release_year",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "director",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "poster_path",
|
||||||
|
"ordinal": 5,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "7bc4aebcb94547976d3d7e063e4e908fc22b977b3cbf063ee93ffe4648c42011"
|
||||||
|
}
|
||||||
12
.sqlx/query-7d7e23355ee0e442f2aa27e898dcfa40bdc4b09391afe04325f076157d9d84aa.json
generated
Normal file
12
.sqlx/query-7d7e23355ee0e442f2aa27e898dcfa40bdc4b09391afe04325f076157d9d84aa.json
generated
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "INSERT INTO movies (id, external_metadata_id, title, release_year, director, poster_path)\n VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n external_metadata_id = excluded.external_metadata_id,\n title = excluded.title,\n release_year = excluded.release_year,\n director = excluded.director,\n poster_path = excluded.poster_path",
|
||||||
|
"describe": {
|
||||||
|
"columns": [],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 6
|
||||||
|
},
|
||||||
|
"nullable": []
|
||||||
|
},
|
||||||
|
"hash": "7d7e23355ee0e442f2aa27e898dcfa40bdc4b09391afe04325f076157d9d84aa"
|
||||||
|
}
|
||||||
44
.sqlx/query-7fa9ce795286905f4b6c3d5a8975fabd813a2b39652dd7e18f03f5b10a4beaca.json
generated
Normal file
44
.sqlx/query-7fa9ce795286905f4b6c3d5a8975fabd813a2b39652dd7e18f03f5b10a4beaca.json
generated
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT id, user_id, name, field_mappings, created_at FROM import_profiles WHERE id = ? AND user_id = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "user_id",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "name",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "field_mappings",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_at",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 2
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "7fa9ce795286905f4b6c3d5a8975fabd813a2b39652dd7e18f03f5b10a4beaca"
|
||||||
|
}
|
||||||
62
.sqlx/query-7ff439f22f880f999a72aad1359eb8fec11fe868b940faee5a351795caaa2357.json
generated
Normal file
62
.sqlx/query-7ff439f22f880f999a72aad1359eb8fec11fe868b940faee5a351795caaa2357.json
generated
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT id, movie_id, user_id, rating, comment, watched_at, created_at, remote_actor_url\n FROM reviews WHERE movie_id = ? ORDER BY watched_at ASC",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "movie_id",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "user_id",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "rating",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "comment",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "watched_at",
|
||||||
|
"ordinal": 5,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_at",
|
||||||
|
"ordinal": 6,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "remote_actor_url",
|
||||||
|
"ordinal": 7,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "7ff439f22f880f999a72aad1359eb8fec11fe868b940faee5a351795caaa2357"
|
||||||
|
}
|
||||||
98
.sqlx/query-8a70f21c39d203867c06dc0bf74a54745b3331b84ce9a2178f7812f1ed7262cc.json
generated
Normal file
98
.sqlx/query-8a70f21c39d203867c06dc0bf74a54745b3331b84ce9a2178f7812f1ed7262cc.json
generated
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,\n r.id AS review_id, r.movie_id, r.user_id, r.rating, r.comment, r.watched_at, r.created_at, r.remote_actor_url\n FROM reviews r\n INNER JOIN movies m ON m.id = r.movie_id\n WHERE r.movie_id = ?\n ORDER BY r.watched_at ASC\n LIMIT ? OFFSET ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "external_metadata_id",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "title",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "release_year",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "director",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "poster_path",
|
||||||
|
"ordinal": 5,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "review_id",
|
||||||
|
"ordinal": 6,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "movie_id",
|
||||||
|
"ordinal": 7,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "user_id",
|
||||||
|
"ordinal": 8,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "rating",
|
||||||
|
"ordinal": 9,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "comment",
|
||||||
|
"ordinal": 10,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "watched_at",
|
||||||
|
"ordinal": 11,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_at",
|
||||||
|
"ordinal": 12,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "remote_actor_url",
|
||||||
|
"ordinal": 13,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 3
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "8a70f21c39d203867c06dc0bf74a54745b3331b84ce9a2178f7812f1ed7262cc"
|
||||||
|
}
|
||||||
12
.sqlx/query-9024c2b533d0100f18d5a5550220a148d8dc29bbf0df715f895fa4248d83785f.json
generated
Normal file
12
.sqlx/query-9024c2b533d0100f18d5a5550220a148d8dc29bbf0df715f895fa4248d83785f.json
generated
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "DELETE FROM import_profiles WHERE id = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": []
|
||||||
|
},
|
||||||
|
"hash": "9024c2b533d0100f18d5a5550220a148d8dc29bbf0df715f895fa4248d83785f"
|
||||||
|
}
|
||||||
26
.sqlx/query-a01336632a54099e31686a9cbe6fc53fef1299fc7c7b52be44f99c2302490a22.json
generated
Normal file
26
.sqlx/query-a01336632a54099e31686a9cbe6fc53fef1299fc7c7b52be44f99c2302490a22.json
generated
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT COUNT(DISTINCT movie_id) AS \"total!: i64\",\n AVG(CAST(rating AS REAL)) AS avg_rating\n FROM reviews WHERE user_id = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "total!: i64",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "avg_rating",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Float"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "a01336632a54099e31686a9cbe6fc53fef1299fc7c7b52be44f99c2302490a22"
|
||||||
|
}
|
||||||
98
.sqlx/query-a7c424c26663e4e51b1c563fa977f28e1d55234a242a7ddba50db13cf73b488d.json
generated
Normal file
98
.sqlx/query-a7c424c26663e4e51b1c563fa977f28e1d55234a242a7ddba50db13cf73b488d.json
generated
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,\n r.id AS review_id, r.movie_id, r.user_id, r.rating, r.comment, r.watched_at, r.created_at, r.remote_actor_url\n FROM reviews r\n INNER JOIN movies m ON m.id = r.movie_id\n ORDER BY r.watched_at DESC\n LIMIT ? OFFSET ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "external_metadata_id",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "title",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "release_year",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "director",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "poster_path",
|
||||||
|
"ordinal": 5,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "review_id",
|
||||||
|
"ordinal": 6,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "movie_id",
|
||||||
|
"ordinal": 7,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "user_id",
|
||||||
|
"ordinal": 8,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "rating",
|
||||||
|
"ordinal": 9,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "comment",
|
||||||
|
"ordinal": 10,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "watched_at",
|
||||||
|
"ordinal": 11,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_at",
|
||||||
|
"ordinal": 12,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "remote_actor_url",
|
||||||
|
"ordinal": 13,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 2
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "a7c424c26663e4e51b1c563fa977f28e1d55234a242a7ddba50db13cf73b488d"
|
||||||
|
}
|
||||||
26
.sqlx/query-aca9e7aaa32c23b4de3f5048d60340e978d31a36be9121da3c59378f2fc1ed8e.json
generated
Normal file
26
.sqlx/query-aca9e7aaa32c23b4de3f5048d60340e978d31a36be9121da3c59378f2fc1ed8e.json
generated
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT m.director AS \"director!\",\n COUNT(*) AS \"count!: i64\"\n FROM reviews r\n INNER JOIN movies m ON m.id = r.movie_id\n WHERE r.user_id = ? AND m.director IS NOT NULL\n GROUP BY m.director\n ORDER BY COUNT(*) DESC\n LIMIT 5",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "director!",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "count!: i64",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Integer"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
true,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "aca9e7aaa32c23b4de3f5048d60340e978d31a36be9121da3c59378f2fc1ed8e"
|
||||||
|
}
|
||||||
62
.sqlx/query-ae983138ad90fda3794b784fbf62c31fddcf182850782e9bfbc4ff3ee8b7d4bb.json
generated
Normal file
62
.sqlx/query-ae983138ad90fda3794b784fbf62c31fddcf182850782e9bfbc4ff3ee8b7d4bb.json
generated
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT id, movie_id, user_id, rating, comment, watched_at, created_at, remote_actor_url\n FROM reviews WHERE id = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "movie_id",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "user_id",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "rating",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "comment",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "watched_at",
|
||||||
|
"ordinal": 5,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_at",
|
||||||
|
"ordinal": 6,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "remote_actor_url",
|
||||||
|
"ordinal": 7,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "ae983138ad90fda3794b784fbf62c31fddcf182850782e9bfbc4ff3ee8b7d4bb"
|
||||||
|
}
|
||||||
12
.sqlx/query-bf4aaf630ebefde88d87a95c257bbeafaf39e2f53611dab435d485648eb7e598.json
generated
Normal file
12
.sqlx/query-bf4aaf630ebefde88d87a95c257bbeafaf39e2f53611dab435d485648eb7e598.json
generated
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "DELETE FROM import_sessions WHERE id = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": []
|
||||||
|
},
|
||||||
|
"hash": "bf4aaf630ebefde88d87a95c257bbeafaf39e2f53611dab435d485648eb7e598"
|
||||||
|
}
|
||||||
44
.sqlx/query-c43249558d535343e387586fa00499fe813b18b9e7d8d241462f0689969dc64f.json
generated
Normal file
44
.sqlx/query-c43249558d535343e387586fa00499fe813b18b9e7d8d241462f0689969dc64f.json
generated
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT id, email, username, password_hash, role FROM users WHERE email = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "email",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "username",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "password_hash",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "role",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "c43249558d535343e387586fa00499fe813b18b9e7d8d241462f0689969dc64f"
|
||||||
|
}
|
||||||
56
.sqlx/query-ca7c29f4c80cee4877625a259edef662b169377c5bafdd03583645a39368c910.json
generated
Normal file
56
.sqlx/query-ca7c29f4c80cee4877625a259edef662b169377c5bafdd03583645a39368c910.json
generated
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT id, user_id, parsed_data, field_mappings, row_results, created_at, expires_at\n FROM import_sessions WHERE id = ? AND user_id = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "user_id",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "parsed_data",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "field_mappings",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "row_results",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_at",
|
||||||
|
"ordinal": 5,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "expires_at",
|
||||||
|
"ordinal": 6,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 2
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "ca7c29f4c80cee4877625a259edef662b169377c5bafdd03583645a39368c910"
|
||||||
|
}
|
||||||
12
.sqlx/query-cca022ac6275f2b1aaf63a14420897074c8ff4cdd1d3e9a13ef4b9dd5346d12a.json
generated
Normal file
12
.sqlx/query-cca022ac6275f2b1aaf63a14420897074c8ff4cdd1d3e9a13ef4b9dd5346d12a.json
generated
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "INSERT INTO reviews (id, movie_id, user_id, rating, comment, watched_at, created_at, remote_actor_url)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||||
|
"describe": {
|
||||||
|
"columns": [],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 8
|
||||||
|
},
|
||||||
|
"nullable": []
|
||||||
|
},
|
||||||
|
"hash": "cca022ac6275f2b1aaf63a14420897074c8ff4cdd1d3e9a13ef4b9dd5346d12a"
|
||||||
|
}
|
||||||
20
.sqlx/query-d5d2a81306488a8cee5654cea7e14d76d76ecc7d2190ffb73d12bec2874111d2.json
generated
Normal file
20
.sqlx/query-d5d2a81306488a8cee5654cea7e14d76d76ecc7d2190ffb73d12bec2874111d2.json
generated
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT m.director\n FROM reviews r\n INNER JOIN movies m ON m.id = r.movie_id\n WHERE r.user_id = ? AND m.director IS NOT NULL\n GROUP BY m.director\n ORDER BY COUNT(*) DESC\n LIMIT 1",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "director",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "d5d2a81306488a8cee5654cea7e14d76d76ecc7d2190ffb73d12bec2874111d2"
|
||||||
|
}
|
||||||
12
.sqlx/query-e3a3b56d63df433339bd8183f20ef33ded742ef03df885686cd5198f9f8e1c01.json
generated
Normal file
12
.sqlx/query-e3a3b56d63df433339bd8183f20ef33ded742ef03df885686cd5198f9f8e1c01.json
generated
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "INSERT INTO import_sessions (id, user_id, parsed_data, field_mappings, row_results, created_at, expires_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||||
|
"describe": {
|
||||||
|
"columns": [],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 7
|
||||||
|
},
|
||||||
|
"nullable": []
|
||||||
|
},
|
||||||
|
"hash": "e3a3b56d63df433339bd8183f20ef33ded742ef03df885686cd5198f9f8e1c01"
|
||||||
|
}
|
||||||
12
.sqlx/query-e431381ad41c1c2f7b9c89509d5e3f4c19cb52dcfff66772145cd80c53c16883.json
generated
Normal file
12
.sqlx/query-e431381ad41c1c2f7b9c89509d5e3f4c19cb52dcfff66772145cd80c53c16883.json
generated
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "DELETE FROM movies WHERE id = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": []
|
||||||
|
},
|
||||||
|
"hash": "e431381ad41c1c2f7b9c89509d5e3f4c19cb52dcfff66772145cd80c53c16883"
|
||||||
|
}
|
||||||
12
.sqlx/query-f84e5483ca4210aec67b38cc1a9de4a42c12891025236abc48ea4f175292a6cc.json
generated
Normal file
12
.sqlx/query-f84e5483ca4210aec67b38cc1a9de4a42c12891025236abc48ea4f175292a6cc.json
generated
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "DELETE FROM reviews WHERE id = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": []
|
||||||
|
},
|
||||||
|
"hash": "f84e5483ca4210aec67b38cc1a9de4a42c12891025236abc48ea4f175292a6cc"
|
||||||
|
}
|
||||||
44
.sqlx/query-f8559923b7a885fb0d4938479f11bd97708b401a6a2290abe6df49fcb7f28a8d.json
generated
Normal file
44
.sqlx/query-f8559923b7a885fb0d4938479f11bd97708b401a6a2290abe6df49fcb7f28a8d.json
generated
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT id, user_id, name, field_mappings, created_at FROM import_profiles WHERE user_id = ? ORDER BY created_at DESC",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "user_id",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "name",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "field_mappings",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_at",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "f8559923b7a885fb0d4938479f11bd97708b401a6a2290abe6df49fcb7f28a8d"
|
||||||
|
}
|
||||||
32
.sqlx/query-fdd5b522f26b5e0ce62f76c774fbb606fd9ee9884f4457831f693a0df3609317.json
generated
Normal file
32
.sqlx/query-fdd5b522f26b5e0ce62f76c774fbb606fd9ee9884f4457831f693a0df3609317.json
generated
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT strftime('%Y-%m', watched_at) AS \"month!\",\n AVG(CAST(rating AS REAL)) AS \"avg_rating!: f64\",\n COUNT(*) AS \"count!: i64\"\n FROM reviews\n WHERE user_id = ? AND watched_at >= datetime('now', '-12 months')\n GROUP BY \"month!\"\n ORDER BY \"month!\" ASC",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "month!",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "avg_rating!: f64",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Float"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "count!: i64",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Integer"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "fdd5b522f26b5e0ce62f76c774fbb606fd9ee9884f4457831f693a0df3609317"
|
||||||
|
}
|
||||||
295
CODE_STYLE.md
295
CODE_STYLE.md
@@ -1,295 +0,0 @@
|
|||||||
# Code Style Guide
|
|
||||||
|
|
||||||
This document defines the coding standards for this project. All contributors (human and agent) must follow these rules. When in doubt, prefer clarity and correctness over cleverness and speed.
|
|
||||||
|
|
||||||
## Philosophy
|
|
||||||
|
|
||||||
- Code reads like prose
|
|
||||||
- Do things properly — no shortcuts
|
|
||||||
- SOLID principles — always, no exceptions
|
|
||||||
- KISS — simplest solution that solves the problem **correctly and properly**. KISS means no unnecessary complexity, NOT skipping proper architecture. If the design calls for a trait, a newtype, or a pattern — that IS the simple solution. When in doubt, follow the architecture (CONTEXT.md, ADRs) over perceived simplicity.
|
|
||||||
- DRY — one source of truth for every piece of knowledge
|
|
||||||
- Use design patterns where they fit (Strategy, Observer, Builder, etc.) — name them in code so intent is clear
|
|
||||||
- Single responsibility everywhere: files, functions, types, modules
|
|
||||||
- Single point of entry, single control flow — no parallel data/control paths
|
|
||||||
- Open/Closed — extend via new types, don't modify existing ones
|
|
||||||
- Depend on abstractions (traits), not concretions
|
|
||||||
- Keep things as private as possible
|
|
||||||
- Zero magic numbers, strings, or unnamed constants
|
|
||||||
- Newtypes for self-documenting code
|
|
||||||
- Descriptive variable names — `review_rating`, not `rr`. `watched_on`, not `wd`. `poster_url`, not `pu`. No abbreviations unless universally understood (e.g., `id`, `url`, `i` for a trivial loop index).
|
|
||||||
|
|
||||||
## Project Structure
|
|
||||||
|
|
||||||
### Module Organization
|
|
||||||
|
|
||||||
Deep module hierarchy, grouped by concern. No flat file dumps. Each file is its own small, enclosed thing.
|
|
||||||
|
|
||||||
```
|
|
||||||
crates/domain/src/
|
|
||||||
├── models/
|
|
||||||
│ ├── review.rs
|
|
||||||
│ ├── diary_entry.rs
|
|
||||||
│ └── movie.rs
|
|
||||||
├── value_objects/
|
|
||||||
│ ├── movie_id.rs
|
|
||||||
│ ├── rating.rs
|
|
||||||
│ └── watched_on.rs
|
|
||||||
├── ports/
|
|
||||||
│ ├── review_repository.rs
|
|
||||||
│ └── event_publisher.rs
|
|
||||||
└── ...
|
|
||||||
```
|
|
||||||
|
|
||||||
### File Size
|
|
||||||
|
|
||||||
Small files with a single concern. If a file grows past ~100-150 lines, it's probably doing too much — split it.
|
|
||||||
|
|
||||||
### Tests
|
|
||||||
|
|
||||||
Tests live outside production files, apart from the few exceptions listed below. Each crate keeps its tests in `crates/<crate>/tests/`, one file per unit under test, grouped by the same module as the production code. Cargo builds each top-level `tests/<group>.rs` as one integration-test binary; the group file lists its members with `#[path]`:
|
|
||||||
|
|
||||||
```
|
|
||||||
crates/application/src/diary/log_review.rs
|
|
||||||
crates/application/tests/diary.rs # mod support; + #[path] list of the group
|
|
||||||
crates/application/tests/diary/log_review_test.rs
|
|
||||||
crates/application/tests/support/ # shared contexts and command builders
|
|
||||||
```
|
|
||||||
|
|
||||||
Adapters follow the same layout (`crates/adapters/sqlite/tests/repositories/diary_repository_test.rs`). Route smoke, API and handler tests run against the real composition and live in `crates/bootstrap/tests/`; http-axum also has integration tests in `crates/adapters/http-axum/tests/` (`log_review_form_test.rs`, `openapi_contract_test.rs`).
|
|
||||||
|
|
||||||
Inline `#[cfg(test)]` tests remain only where they must reach private items:
|
|
||||||
|
|
||||||
- `crates/adapters/http-axum`: the `api/social`, `federation/blocklist_api` and `html/social` mapper tests (`tests.rs` beside each; shared fixtures in `src/test_support.rs`) and the rate-limit tests in `router.rs`
|
|
||||||
- `crates/application/src/users/diary_filter.rs`
|
|
||||||
- `crates/adapters/nats/src/subject.rs`
|
|
||||||
- `crates/tui/src/client.rs`
|
|
||||||
|
|
||||||
## Naming
|
|
||||||
|
|
||||||
### Conventions
|
|
||||||
|
|
||||||
- Files and modules: `snake_case`
|
|
||||||
- Types: `PascalCase` with semantic suffixes for clarity and navigation
|
|
||||||
- Functions and methods: `snake_case`, verb-first, descriptive
|
|
||||||
|
|
||||||
### Type Suffixes
|
|
||||||
|
|
||||||
| Suffix | Usage | Example |
|
|
||||||
|---|---|---|
|
|
||||||
| (none) | Value objects, entities | `Review`, `Movie`, `DiaryEntry` |
|
|
||||||
| `Id` | Identity newtypes | `MovieId`, `ReviewId`, `UserId` |
|
|
||||||
| `Config` | Configuration data | `ServerConfig`, `StorageConfig` |
|
|
||||||
| `Service` | Domain services | `LocalSocialService` |
|
|
||||||
| `Error` | Error types | `DomainError`, `AuthError` |
|
|
||||||
| `UseCase` | Application use cases | `LogReviewUseCase`, `GetDiaryUseCase` |
|
|
||||||
| `Strategy` | Strategy trait/impls | `RatingAggregationStrategy` |
|
|
||||||
|
|
||||||
Ports are named for the capability they provide (`ReviewRepository`, `EventPublisher`); their implementations are named for the technology (`SqliteReviewRepository`).
|
|
||||||
|
|
||||||
### Newtypes
|
|
||||||
|
|
||||||
Use newtypes everywhere a primitive carries domain meaning:
|
|
||||||
|
|
||||||
```rust
|
|
||||||
// YES
|
|
||||||
struct MovieId(Uuid);
|
|
||||||
struct ReviewId(Uuid);
|
|
||||||
struct Rating(u8);
|
|
||||||
struct PosterUrl(Url);
|
|
||||||
|
|
||||||
// NO
|
|
||||||
type MovieId = String;
|
|
||||||
fn log_review(movie: &str, rating: u8, watched_on: &str) -> ...
|
|
||||||
```
|
|
||||||
|
|
||||||
Newtypes are self-documenting and prevent accidental misuse (can't pass a `MovieId` where a `ReviewId` is expected).
|
|
||||||
|
|
||||||
## Functions and Methods
|
|
||||||
|
|
||||||
### Single Responsibility
|
|
||||||
|
|
||||||
Each function does ONE thing. Compose small functions into larger behaviors.
|
|
||||||
|
|
||||||
```rust
|
|
||||||
// YES
|
|
||||||
fn resolve_movie(...) -> Movie { ... }
|
|
||||||
fn build_review(movie: &Movie, draft: ReviewDraft) -> Review { ... }
|
|
||||||
fn record_diary_entry(review: &Review) -> DiaryEntry { ... }
|
|
||||||
|
|
||||||
// NO
|
|
||||||
fn log_review(...) -> DiaryEntry {
|
|
||||||
// 80 lines doing movie resolution, review construction and diary recording
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Visibility
|
|
||||||
|
|
||||||
Default to private. Only `pub` what the module's consumers actually need. Use `pub(crate)` for intra-crate sharing that shouldn't leak outside.
|
|
||||||
|
|
||||||
### impl Blocks
|
|
||||||
|
|
||||||
Split by concern:
|
|
||||||
|
|
||||||
```rust
|
|
||||||
// Construction
|
|
||||||
impl Review {
|
|
||||||
pub fn new(movie: MovieId, rating: Rating, watched_on: WatchedOn) -> Self { ... }
|
|
||||||
}
|
|
||||||
|
|
||||||
// Queries
|
|
||||||
impl Review {
|
|
||||||
pub fn is_rewatch(&self) -> bool { ... }
|
|
||||||
pub fn rating(&self) -> Rating { ... }
|
|
||||||
}
|
|
||||||
|
|
||||||
// Mutations
|
|
||||||
impl Review {
|
|
||||||
pub fn revise_rating(&mut self, rating: Rating) { ... }
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Error Handling
|
|
||||||
|
|
||||||
### Domain and Application: `thiserror`
|
|
||||||
|
|
||||||
Typed, matchable error enums. Every error variant is meaningful.
|
|
||||||
|
|
||||||
```rust
|
|
||||||
#[derive(Debug, thiserror::Error)]
|
|
||||||
pub enum DiaryError {
|
|
||||||
#[error("movie {0} not found")]
|
|
||||||
MovieNotFound(MovieId),
|
|
||||||
#[error("review rejected: {0}")]
|
|
||||||
ReviewRejected(String),
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Adapters and Bootstrap: `anyhow`
|
|
||||||
|
|
||||||
Pragmatic error handling. Context strings for debugging.
|
|
||||||
|
|
||||||
```rust
|
|
||||||
fn fetch_poster_blob(poster_url: &PosterUrl) -> anyhow::Result<Bytes> {
|
|
||||||
let data = http_client.get(poster_url)
|
|
||||||
.context("failed to fetch poster")?;
|
|
||||||
// ...
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Never `unwrap` or `expect` in production code
|
|
||||||
|
|
||||||
Errors propagate with `?` and bubble up to a single handler. No scattered panic points.
|
|
||||||
|
|
||||||
`unwrap` is allowed **only** in test code.
|
|
||||||
|
|
||||||
## Configuration
|
|
||||||
|
|
||||||
Secrets (API keys, JWT secrets) and deployment settings are read once at startup by the `config` crate into a typed `AppConfig`: built-in defaults, then `config.toml` (or the file named by `CONFIG_FILE`), then environment variables. Malformed values fail startup; empty values count as unset. Only the binaries load configuration; everything else receives typed config values.
|
|
||||||
|
|
||||||
Zero magic numbers or strings. Everything named, everything explained by its name.
|
|
||||||
|
|
||||||
```rust
|
|
||||||
// YES
|
|
||||||
const MAX_REVIEW_BODY_LENGTH: usize = 10_000;
|
|
||||||
|
|
||||||
// NO
|
|
||||||
if body.len() > 10_000 { ... }
|
|
||||||
```
|
|
||||||
|
|
||||||
Constants are only for true invariants that never change. Tunable values belong in config.
|
|
||||||
|
|
||||||
## Comments
|
|
||||||
|
|
||||||
Comments only where a name, test or ADR cannot carry the reason. A comment is noise that drifts out of date while the code moves on, so prefer to put the reason somewhere that cannot rot silently:
|
|
||||||
|
|
||||||
- **A name.** Rename the function, the variable, or the type until the reason is visible in the code.
|
|
||||||
- **A test.** A constraint worth a comment is worth a test that fails when someone breaks it. `media_is_resolved_before_the_cascade_runs` outlives any note explaining why the order matters.
|
|
||||||
- **An ADR.** Architectural reasoning belongs in `docs/adr/`, where it is versioned and discoverable.
|
|
||||||
|
|
||||||
When none of those can carry it, a short comment stating the reason (never restating the code) is acceptable.
|
|
||||||
|
|
||||||
## Dependencies
|
|
||||||
|
|
||||||
- Use good crates when they exist — don't reinvent
|
|
||||||
- Prefer crates with minimal transitive dependencies
|
|
||||||
- Aim for small memory footprint and executable size
|
|
||||||
- Every dependency that has a `[workspace.dependencies]` entry is declared `workspace = true`; crates inherit `edition` from `[workspace.package]`
|
|
||||||
- Domain crate: zero external dependencies beyond `thiserror`, `serde` and small value-type crates
|
|
||||||
- Application crate: depends only on domain
|
|
||||||
- Adapters: free to pull in platform crates (`axum`, `sqlx`, `nats`, etc.)
|
|
||||||
- Bootstrap: wiring only; the only crate that names adapters
|
|
||||||
- Binaries (`server`, `worker`): load config, call `bootstrap`, run — nothing else (`make check-binaries-are-thin`)
|
|
||||||
|
|
||||||
## Trait Objects for Ports
|
|
||||||
|
|
||||||
Ports are `dyn` behind `Arc`. Use cases hold their dependencies as trait objects:
|
|
||||||
|
|
||||||
```rust
|
|
||||||
pub struct Deps {
|
|
||||||
pub reviews: Arc<dyn ReviewRepository>,
|
|
||||||
pub events: Arc<dyn EventPublisher>,
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Prefer a closed enum over `dyn` only where exhaustiveness is the point — when adding a variant must force every consumer to handle it. That is a decision about compiler-enforced coverage, not about dispatch cost.
|
|
||||||
|
|
||||||
## Testing
|
|
||||||
|
|
||||||
### Test Helpers Are Gated
|
|
||||||
|
|
||||||
`domain::testing` (factories, the cascading `InMemoryStore`, noops and `Refusing*` fakes) compiles only with the `test-helpers` feature, which crates enable in their `[dev-dependencies]`. Production builds must never contain fakes. Build entities with the `domain::testing` factories instead of repeating struct literals in each test.
|
|
||||||
|
|
||||||
### Coverage Targets
|
|
||||||
|
|
||||||
| Crate | Approach | Target |
|
|
||||||
|---|---|---|
|
|
||||||
| Domain | TDD (red-green-refactor) | 100% |
|
|
||||||
| Application | TDD | High coverage |
|
|
||||||
| Adapters | Integration tests where practical | Best effort |
|
|
||||||
| Bootstrap | Route smoke, API and handler tests over the real wiring | Every route reachable |
|
|
||||||
|
|
||||||
### Fakes Must Not Be Kinder Than Production
|
|
||||||
|
|
||||||
A fake that is more forgiving than the real adapter turns a test into a lie: it passes whichever way the code is written, which is worse than having no test. Two rules follow.
|
|
||||||
|
|
||||||
**A fake must reproduce the constraints the database enforces.** SQLite removes dependent rows through `ON DELETE CASCADE`, so an in-memory store must cascade the same way, and enforce the same uniqueness constraints. Without that, an ordering requirement such as "resolve the poster before deleting the `DiaryEntry`" could not be tested at all.
|
|
||||||
|
|
||||||
**A fake must be able to fail.** Every port whose failure is meant to degrade rather than propagate needs a fake that refuses (a poster fetcher that errors, an event publisher that rejects). A best-effort path with no failing test is a path that has never run.
|
|
||||||
|
|
||||||
When a claim cannot be observed through the fake, move the test to where the real thing runs rather than asserting it against the fake's own behaviour.
|
|
||||||
|
|
||||||
### Test Naming
|
|
||||||
|
|
||||||
Tests read as specifications:
|
|
||||||
|
|
||||||
```rust
|
|
||||||
#[tokio::test]
|
|
||||||
async fn logging_review_creates_diary_entry() { ... }
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn rewatch_review_keeps_original_entry() { ... }
|
|
||||||
```
|
|
||||||
|
|
||||||
## Control Flow
|
|
||||||
|
|
||||||
### Single Point of Entry
|
|
||||||
|
|
||||||
One path through the code. No parallel flows that do similar things in different places.
|
|
||||||
|
|
||||||
```rust
|
|
||||||
// YES — one function handles movie resolution
|
|
||||||
let movie = movie_resolver.resolve(movie_id, requester);
|
|
||||||
|
|
||||||
// NO — movie resolution duplicated in two places
|
|
||||||
// diary_handler.rs: resolves movie
|
|
||||||
// import_handler.rs: also resolves movie with slightly different logic
|
|
||||||
```
|
|
||||||
|
|
||||||
### Single Call, Cascading Changes
|
|
||||||
|
|
||||||
When something changes, it should cascade from one point. Don't require updating multiple files for a single logical change.
|
|
||||||
|
|
||||||
### No God Objects
|
|
||||||
|
|
||||||
If a struct has more than 5-6 fields, question whether it's doing too much. If a function takes more than 4-5 parameters, consider grouping them into a dedicated type.
|
|
||||||
29
CONTEXT.md
29
CONTEXT.md
@@ -1,29 +0,0 @@
|
|||||||
# Movies Diary
|
|
||||||
|
|
||||||
A personal movie diary where users record each watching of a movie with a rating and an optional written review; reviews appear in diaries and social feeds shared with local and federated followers.
|
|
||||||
|
|
||||||
## Language
|
|
||||||
|
|
||||||
**Review**:
|
|
||||||
The record of a single watching of a movie: a rating, an optional written comment, when it was watched, and optionally how.
|
|
||||||
_Avoid_: Diary entry, post
|
|
||||||
|
|
||||||
**Diary Entry**:
|
|
||||||
A Review together with the Movie it is about, as it appears in a diary or a feed.
|
|
||||||
_Avoid_: Review (that is the record itself)
|
|
||||||
|
|
||||||
**Spoiler Flag**:
|
|
||||||
An author-set marker on a Review stating that its entire comment reveals plot details.
|
|
||||||
_Avoid_: Spoiler warning, spoiler tag, spoiler markup
|
|
||||||
|
|
||||||
**Account deletion**:
|
|
||||||
Two-phase removal of a user. The request tombstones the account immediately; a background purge then erases its data and notifies the fediverse.
|
|
||||||
_Avoid_: Account removal, deactivation
|
|
||||||
|
|
||||||
**Tombstone**:
|
|
||||||
The data-free users row (plus signing keypair) an Account deletion leaves behind so queued fediverse `Delete` deliveries can still be signed; removed after a retention period.
|
|
||||||
_Avoid_: Soft delete
|
|
||||||
|
|
||||||
**Retired Username**:
|
|
||||||
A username of a deleted account, refused for every future registration.
|
|
||||||
_Avoid_: Reserved username, banned username
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
# Contributing
|
|
||||||
|
|
||||||
Thanks for your interest in Movies Diary! This is a personal project but contributions are welcome — bug fixes, new features, docs improvements, or picking up the deprecated TUI.
|
|
||||||
|
|
||||||
## Getting started
|
|
||||||
|
|
||||||
1. Fork and clone the repo
|
|
||||||
2. Copy `.env.example` to `.env` and fill in at least `JWT_SECRET` and `OMDB_API_KEY`
|
|
||||||
3. Install Rust (stable, 2024 edition) and Bun (for the SPA)
|
|
||||||
4. Run the backend and worker:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cargo run -p server # HTTP server on :3000
|
|
||||||
cargo run -p worker # event worker (separate terminal)
|
|
||||||
```
|
|
||||||
|
|
||||||
5. Run the SPA dev server:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd spa && bun install && bun run dev
|
|
||||||
```
|
|
||||||
|
|
||||||
## Before submitting a PR
|
|
||||||
|
|
||||||
```bash
|
|
||||||
make check # the full gate; plain `make` runs it too
|
|
||||||
```
|
|
||||||
|
|
||||||
`make check` runs, in order: `fmt-check`, `clippy` (workspace, all targets, `-D warnings`), `test`, `test-federation-off` (workspace tests with default features off), then the layering guards (`check-appcontext`, `check-handler-deps`, `check-handler-repos`, `check-handler-services`, `check-http-adapter-deps`, `check-federation-off-social`, `check-sqlite-is-ap-free`, `check-binaries-are-thin`, `check-federation-off-deps`, `check-nats-isolated`, `check-no-second-web-stack`). CI runs the same steps.
|
|
||||||
|
|
||||||
For the SPA also run:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd spa && bunx tsc --noEmit
|
|
||||||
```
|
|
||||||
|
|
||||||
PRs with a failing gate won't be merged.
|
|
||||||
|
|
||||||
## Architecture
|
|
||||||
|
|
||||||
The project follows hexagonal (ports & adapters) architecture. See `architecture.mmd` for the full diagram.
|
|
||||||
|
|
||||||
**Key rules:**
|
|
||||||
- HTTP 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 the http-axum mappers (`crates/adapters/http-axum/src/html/mappers/` for the classic UI, the DTO conversions beside each handler under `api/`)
|
|
||||||
- Use cases called from HTTP handlers take a `&FooDeps` struct (registered in `application::Deps`, built by `bootstrap`) — 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
|
|
||||||
application → use cases, orchestration
|
|
||||||
config → typed AppConfig: defaults → config.toml / CONFIG_FILE → env
|
|
||||||
bootstrap → composition root, the only crate that names adapters
|
|
||||||
server, worker → thin binaries: load config, call bootstrap, run
|
|
||||||
adapters/* → implement domain ports (sqlite, activitypub, ...); http-axum is the HTTP driving adapter
|
|
||||||
spa/ → React SPA (TanStack Router + shadcn/ui)
|
|
||||||
```
|
|
||||||
|
|
||||||
Cargo features: `federation` (default; ActivityPub) and `nats`. `sqlite` and `sqlite-federation` remain as deprecated aliases so old build commands keep working.
|
|
||||||
|
|
||||||
**Dependencies.** Every external crate is declared once in the root `[workspace.dependencies]`, usually with `default-features = false`; member crates write `foo = { workspace = true, features = [...] }` and enable only the features they use. A new crate goes into both `members` and `default-members` in the root `Cargo.toml` (only `tui` is left out of `default-members`). `cargo machete` should stay clean, and each crate must compile on its own (`cargo check -p <crate> --all-targets`), not just through feature unification in the binaries.
|
|
||||||
|
|
||||||
### Adding a new feature
|
|
||||||
|
|
||||||
1. **Domain first** — models in `domain/src/models/`, ports in `domain/src/ports/`, events in `domain/src/events.rs`
|
|
||||||
2. **Adapters** — implement ports under `crates/adapters/sqlite/src/repositories/<aggregate>/`, add a migration
|
|
||||||
3. **Application** — use cases in `application/src/<domain>/`, add the deps struct to `application/src/deps.rs`, build it in `bootstrap`
|
|
||||||
4. **API types** — DTOs in `api-types/src/`
|
|
||||||
5. **HTTP** — JSON handlers in `crates/adapters/http-axum/src/api/<domain>.rs`, classic HTML handlers in `.../html/<domain>.rs` (templates in `html/templates/`), routes in `router.rs` / `api/mod.rs` / `html/mod.rs`
|
|
||||||
6. **SPA** — API client in `spa/src/lib/api/`, hook in `spa/src/hooks/`, components
|
|
||||||
7. **Classic HTML** — Askama template + CSS in `static/style.css`
|
|
||||||
|
|
||||||
### Tests
|
|
||||||
|
|
||||||
Tests live in `crates/<crate>/tests/`, not in the production file. A few inline tests remain where they need private items; `CODE_STYLE.md` lists them. Build fixtures with the `domain::testing` factories and use the cascading `InMemoryStore` and `Refusing*` fakes. Route smoke, API and handler tests over the real wiring are in `crates/bootstrap/tests/`.
|
|
||||||
|
|
||||||
### Database adapters
|
|
||||||
|
|
||||||
SQLite is the only supported backend (see [ADR-0012](docs/adr/0012-sqlite-is-the-only-backend.md)). Add migrations under `crates/adapters/sqlite`; SQLite uses `?` params and text datetimes.
|
|
||||||
|
|
||||||
### Federation (ActivityPub)
|
|
||||||
|
|
||||||
Events: never publish from a use case after the fact. Pass the events to the repository/command-port method that writes the data so they land in the outbox (`event_queue`) in the same transaction (ADR-0015). The worker delivers them at-least-once and a ledger skips handlers already done, so every handler must be idempotent.
|
|
||||||
|
|
||||||
Federation is feature-gated (`#[cfg(feature = "federation")]`). If your feature should federate, add domain events, handle them in `crates/adapters/activitypub/src/event_handler.rs`, and create an AP object + inbound handler.
|
|
||||||
|
|
||||||
## Code style
|
|
||||||
|
|
||||||
- No comments unless the *why* is non-obvious
|
|
||||||
- Concise commit messages
|
|
||||||
- One feature per PR — don't bundle unrelated changes
|
|
||||||
- Follow existing patterns (check a similar feature for reference)
|
|
||||||
|
|
||||||
## Areas seeking help
|
|
||||||
|
|
||||||
- **TUI** (`crates/tui`) — deprecated, needs a maintainer to bring it up to feature parity
|
|
||||||
- **Tests** — the domain and application crates have 400+ tests; more route and handler tests in `crates/bootstrap/tests/` are welcome
|
|
||||||
- **Docs** — API usage examples, deployment guides
|
|
||||||
1695
Cargo.lock
generated
1695
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
145
Cargo.toml
145
Cargo.toml
@@ -1,152 +1,79 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
default-members = [
|
|
||||||
"crates/adapters/auth",
|
|
||||||
"crates/adapters/event-publisher",
|
|
||||||
"crates/adapters/metadata",
|
|
||||||
"crates/adapters/poster-fetcher",
|
|
||||||
"crates/adapters/object-storage",
|
|
||||||
"crates/adapters/rss-adapter",
|
|
||||||
"crates/adapters/sqlite",
|
|
||||||
"crates/adapters/sqlite-federation",
|
|
||||||
"crates/adapters/activitypub",
|
|
||||||
"crates/adapters/export",
|
|
||||||
"crates/adapters/nats",
|
|
||||||
"crates/adapters/tmdb-enrichment",
|
|
||||||
"crates/adapters/image-converter",
|
|
||||||
"crates/adapters/http-axum",
|
|
||||||
"crates/adapters/importer",
|
|
||||||
"crates/adapters/media-server",
|
|
||||||
"crates/event-payload",
|
|
||||||
"crates/api-types",
|
|
||||||
"crates/application",
|
|
||||||
"crates/domain",
|
|
||||||
"crates/bootstrap",
|
|
||||||
"crates/server",
|
|
||||||
"crates/worker",
|
|
||||||
"crates/config",
|
|
||||||
]
|
|
||||||
members = [
|
members = [
|
||||||
"crates/adapters/auth",
|
"crates/adapters/auth",
|
||||||
"crates/adapters/event-publisher",
|
"crates/adapters/event-publisher",
|
||||||
"crates/adapters/metadata",
|
"crates/adapters/metadata",
|
||||||
"crates/adapters/poster-fetcher",
|
"crates/adapters/poster-fetcher",
|
||||||
"crates/adapters/object-storage",
|
"crates/adapters/image-storage",
|
||||||
"crates/adapters/rss-adapter",
|
"crates/adapters/poster-sync",
|
||||||
|
"crates/adapters/rss",
|
||||||
"crates/adapters/sqlite",
|
"crates/adapters/sqlite",
|
||||||
|
"crates/adapters/postgres",
|
||||||
"crates/adapters/sqlite-federation",
|
"crates/adapters/sqlite-federation",
|
||||||
|
"crates/adapters/postgres-federation",
|
||||||
|
"crates/adapters/sqlite-event-queue",
|
||||||
|
"crates/adapters/postgres-event-queue",
|
||||||
|
"crates/adapters/template-askama",
|
||||||
"crates/adapters/activitypub",
|
"crates/adapters/activitypub",
|
||||||
|
"crates/adapters/activitypub-base",
|
||||||
"crates/adapters/export",
|
"crates/adapters/export",
|
||||||
"crates/event-payload",
|
"crates/adapters/event-payload",
|
||||||
"crates/adapters/nats",
|
"crates/adapters/nats",
|
||||||
"crates/api-types",
|
|
||||||
"crates/application",
|
"crates/application",
|
||||||
"crates/adapters/tmdb-enrichment",
|
|
||||||
"crates/adapters/image-converter",
|
|
||||||
"crates/domain",
|
"crates/domain",
|
||||||
"crates/bootstrap",
|
"crates/presentation",
|
||||||
"crates/adapters/http-axum",
|
|
||||||
"crates/server",
|
|
||||||
"crates/tui",
|
"crates/tui",
|
||||||
|
"crates/doc",
|
||||||
"crates/worker",
|
"crates/worker",
|
||||||
"crates/adapters/importer",
|
"crates/adapters/importer",
|
||||||
"crates/adapters/media-server",
|
|
||||||
"crates/config",
|
|
||||||
]
|
]
|
||||||
resolver = "2"
|
resolver = "2"
|
||||||
|
|
||||||
[workspace.package]
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[workspace.dependencies]
|
[workspace.dependencies]
|
||||||
tokio = { version = "1.0", default-features = false }
|
tokio = { version = "1.0", features = ["full"] }
|
||||||
bytes = "1"
|
|
||||||
futures = "0.3"
|
futures = "0.3"
|
||||||
async-stream = "0.3"
|
|
||||||
dotenvy = "0.15"
|
dotenvy = "0.15"
|
||||||
serde = { version = "1.0", default-features = false, features = ["std"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
anyhow = "1.0"
|
anyhow = "1.0"
|
||||||
thiserror = "2.0"
|
thiserror = "2.0"
|
||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
tracing-subscriber = { version = "0.3.23", default-features = false }
|
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
|
||||||
async-trait = "0.1.92"
|
async-trait = "0.1"
|
||||||
uuid = { version = "1.23.0", default-features = false, features = ["std"] }
|
uuid = { version = "1.23.0", features = ["v4", "v5", "serde"] }
|
||||||
chrono = { version = "0.4", default-features = false, features = ["std"] }
|
chrono = { version = "0.4", features = ["serde"] }
|
||||||
chrono-tz = "0.10"
|
sqlx = { version = "0.8.6", features = [
|
||||||
sqlx = { version = "0.8.6", default-features = false, features = [
|
"runtime-tokio-rustls",
|
||||||
"runtime-tokio",
|
|
||||||
"sqlite",
|
"sqlite",
|
||||||
"uuid",
|
"uuid",
|
||||||
"derive",
|
"macros",
|
||||||
"migrate",
|
|
||||||
] }
|
] }
|
||||||
rand = "0.9"
|
reqwest = { version = "0.13", features = ["json", "query"] }
|
||||||
tempfile = "3"
|
object_store = { version = "0.11", features = ["aws"] }
|
||||||
reqwest = { version = "0.13", default-features = false, features = ["json", "query", "charset", "http2", "system-proxy", "rustls-no-provider"] }
|
axum = { version = "0.8.8", features = ["macros", "multipart"] }
|
||||||
sha2 = "0.10"
|
|
||||||
hex = "0.4"
|
|
||||||
object_store = { version = "0.11", default-features = false, features = ["aws"] }
|
|
||||||
axum = { version = "0.8.8", default-features = false }
|
|
||||||
csv = "1"
|
csv = "1"
|
||||||
figment = { version = "0.10", features = ["toml"] }
|
|
||||||
rustls = { version = "0.23", default-features = false }
|
|
||||||
tower = { version = "0.5", default-features = false }
|
|
||||||
tower-http = { version = "0.6.8", default-features = false }
|
|
||||||
utoipa = "5.5.0"
|
|
||||||
utoipa-swagger-ui = "9.0.2"
|
|
||||||
askama = "0.16.0"
|
|
||||||
infer = "0.19.0"
|
|
||||||
percent-encoding = "2"
|
|
||||||
axum-governor = "2"
|
|
||||||
email_address = "0.2.9"
|
|
||||||
jsonwebtoken = "9"
|
|
||||||
argon2 = { version = "0.5", default-features = false }
|
|
||||||
rand_core = { version = "0.6", default-features = false }
|
|
||||||
async-nats = "0.48.0"
|
|
||||||
k-ap = { version = "0.5.1", registry = "gitea" }
|
|
||||||
url = "2"
|
|
||||||
ammonia = "4"
|
|
||||||
calamine = "0.35"
|
|
||||||
image = { version = "0.25", default-features = false }
|
|
||||||
ravif = { version = "0.11", default-features = false }
|
|
||||||
webp = "0.3"
|
|
||||||
rss = { version = "2" }
|
|
||||||
ratatui = "0.30.0"
|
|
||||||
keyring-core = "1.0.0"
|
|
||||||
apple-native-keyring-store = { version = "1.0.0", features = ["keychain"] }
|
|
||||||
zbus-secret-service-keyring-store = { version = "1.0.0" }
|
|
||||||
windows-native-keyring-store = { version = "1.0.0" }
|
|
||||||
directories = "6"
|
|
||||||
|
|
||||||
api-types = { path = "crates/api-types" }
|
|
||||||
domain = { path = "crates/domain" }
|
domain = { path = "crates/domain" }
|
||||||
tmdb-enrichment = { path = "crates/adapters/tmdb-enrichment" }
|
|
||||||
application = { path = "crates/application" }
|
application = { path = "crates/application" }
|
||||||
bootstrap = { path = "crates/bootstrap" }
|
presentation = { path = "crates/presentation" }
|
||||||
http-axum = { path = "crates/adapters/http-axum" }
|
|
||||||
auth = { path = "crates/adapters/auth" }
|
auth = { path = "crates/adapters/auth" }
|
||||||
metadata = { path = "crates/adapters/metadata" }
|
metadata = { path = "crates/adapters/metadata" }
|
||||||
poster-fetcher = { path = "crates/adapters/poster-fetcher" }
|
poster-fetcher = { path = "crates/adapters/poster-fetcher" }
|
||||||
object-storage = { path = "crates/adapters/object-storage" }
|
image-storage = { path = "crates/adapters/image-storage" }
|
||||||
|
poster-sync = { path = "crates/adapters/poster-sync" }
|
||||||
event-publisher = { path = "crates/adapters/event-publisher" }
|
event-publisher = { path = "crates/adapters/event-publisher" }
|
||||||
rss-adapter = { path = "crates/adapters/rss-adapter" }
|
rss = { path = "crates/adapters/rss" }
|
||||||
export = { path = "crates/adapters/export" }
|
export = { path = "crates/adapters/export" }
|
||||||
sqlite = { path = "crates/adapters/sqlite" }
|
sqlite = { path = "crates/adapters/sqlite" }
|
||||||
sqlite-federation = { path = "crates/adapters/sqlite-federation" }
|
sqlite-federation = { path = "crates/adapters/sqlite-federation" }
|
||||||
|
postgres = { path = "crates/adapters/postgres" }
|
||||||
|
postgres-federation = { path = "crates/adapters/postgres-federation" }
|
||||||
|
template-askama = { path = "crates/adapters/template-askama" }
|
||||||
activitypub = { path = "crates/adapters/activitypub" }
|
activitypub = { path = "crates/adapters/activitypub" }
|
||||||
event-payload = { path = "crates/event-payload" }
|
activitypub-base = { path = "crates/adapters/activitypub-base" }
|
||||||
media-server = { path = "crates/adapters/media-server" }
|
doc = { path = "crates/doc" }
|
||||||
|
event-payload = { path = "crates/adapters/event-payload" }
|
||||||
nats = { path = "crates/adapters/nats" }
|
nats = { path = "crates/adapters/nats" }
|
||||||
|
sqlite-event-queue = { path = "crates/adapters/sqlite-event-queue" }
|
||||||
|
postgres-event-queue = { path = "crates/adapters/postgres-event-queue" }
|
||||||
importer = { path = "crates/adapters/importer" }
|
importer = { path = "crates/adapters/importer" }
|
||||||
image-converter = { path = "crates/adapters/image-converter" }
|
|
||||||
config = { path = "crates/config" }
|
|
||||||
|
|
||||||
[profile.dev]
|
|
||||||
debug = 1 # line tables only — still debuggable, much faster linking
|
|
||||||
|
|
||||||
[profile.dev.package."*"]
|
|
||||||
opt-level = 2 # compile deps faster at runtime; paid once, cached after
|
|
||||||
|
|
||||||
[profile.release]
|
|
||||||
codegen-units = 1
|
|
||||||
strip = true
|
|
||||||
|
|||||||
97
Dockerfile
97
Dockerfile
@@ -1,66 +1,73 @@
|
|||||||
# ----- spa -----
|
# ----- build -----
|
||||||
FROM node:22-slim AS spa-builder
|
FROM rust:slim-bookworm AS builder
|
||||||
WORKDIR /spa
|
|
||||||
COPY spa/package.json spa/package-lock.json ./
|
|
||||||
RUN npm ci
|
|
||||||
COPY spa/ .
|
|
||||||
RUN npm run build
|
|
||||||
|
|
||||||
# ----- chef base -----
|
|
||||||
FROM rust:slim-bookworm AS chef
|
|
||||||
# libwebp-dev: required at build time by the `webp` crate (C bindings)
|
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
|
||||||
libwebp-dev \
|
|
||||||
pkg-config \
|
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
|
||||||
RUN cargo install cargo-chef --locked --version 0.1.78
|
|
||||||
WORKDIR /build
|
WORKDIR /build
|
||||||
|
|
||||||
FROM chef AS planner
|
# Cache dependency compilation separately from source
|
||||||
COPY . .
|
|
||||||
RUN cargo chef prepare --recipe-path recipe.json
|
|
||||||
|
|
||||||
# ----- build -----
|
|
||||||
FROM chef AS builder
|
|
||||||
|
|
||||||
# Features: federation (ActivityPub), nats (EVENT_BUS_BACKEND=nats).
|
|
||||||
# Build without federation: --build-arg FEATURES=
|
|
||||||
# To add NATS support: --build-arg FEATURES=federation,nats
|
|
||||||
ARG FEATURES=federation
|
|
||||||
|
|
||||||
COPY .cargo ./.cargo
|
|
||||||
COPY --from=planner /build/recipe.json recipe.json
|
|
||||||
RUN --mount=type=cache,target=/usr/local/cargo/registry,sharing=locked \
|
|
||||||
--mount=type=cache,target=/usr/local/cargo/git,sharing=locked \
|
|
||||||
cargo chef cook --release -p server -p worker --no-default-features --features "${FEATURES}" --recipe-path recipe.json
|
|
||||||
|
|
||||||
# All sqlx queries use the runtime API (no query! macros), so no database
|
|
||||||
# or .sqlx cache is needed at compile time.
|
|
||||||
COPY Cargo.toml Cargo.lock ./
|
COPY Cargo.toml Cargo.lock ./
|
||||||
|
COPY .cargo ./.cargo
|
||||||
|
COPY .sqlx ./.sqlx
|
||||||
|
COPY crates/adapters/activitypub/Cargo.toml crates/adapters/activitypub/Cargo.toml
|
||||||
|
COPY crates/adapters/activitypub-base/Cargo.toml crates/adapters/activitypub-base/Cargo.toml
|
||||||
|
COPY crates/adapters/auth/Cargo.toml crates/adapters/auth/Cargo.toml
|
||||||
|
COPY crates/adapters/event-payload/Cargo.toml crates/adapters/event-payload/Cargo.toml
|
||||||
|
COPY crates/adapters/event-publisher/Cargo.toml crates/adapters/event-publisher/Cargo.toml
|
||||||
|
COPY crates/adapters/nats/Cargo.toml crates/adapters/nats/Cargo.toml
|
||||||
|
COPY crates/adapters/metadata/Cargo.toml crates/adapters/metadata/Cargo.toml
|
||||||
|
COPY crates/adapters/poster-fetcher/Cargo.toml crates/adapters/poster-fetcher/Cargo.toml
|
||||||
|
COPY crates/adapters/image-storage/Cargo.toml crates/adapters/image-storage/Cargo.toml
|
||||||
|
COPY crates/adapters/poster-sync/Cargo.toml crates/adapters/poster-sync/Cargo.toml
|
||||||
|
COPY crates/adapters/export/Cargo.toml crates/adapters/export/Cargo.toml
|
||||||
|
COPY crates/adapters/importer/Cargo.toml crates/adapters/importer/Cargo.toml
|
||||||
|
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-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-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/application/Cargo.toml crates/application/Cargo.toml
|
||||||
|
COPY crates/domain/Cargo.toml crates/domain/Cargo.toml
|
||||||
|
COPY crates/presentation/Cargo.toml crates/presentation/Cargo.toml
|
||||||
|
COPY crates/doc/Cargo.toml crates/doc/Cargo.toml
|
||||||
|
COPY crates/tui/Cargo.toml crates/tui/Cargo.toml
|
||||||
|
COPY crates/worker/Cargo.toml crates/worker/Cargo.toml
|
||||||
|
|
||||||
|
# Stub every crate so cargo can resolve and fetch deps
|
||||||
|
RUN find crates -name "Cargo.toml" | sed 's|/Cargo.toml||' | \
|
||||||
|
xargs -I{} sh -c 'mkdir -p {}/src && echo "fn main(){}" > {}/src/main.rs && echo "" > {}/src/lib.rs'
|
||||||
|
|
||||||
|
RUN cargo fetch
|
||||||
|
|
||||||
|
# Now copy real sources (invalidates cache only on source changes)
|
||||||
COPY crates ./crates
|
COPY crates ./crates
|
||||||
RUN --mount=type=cache,target=/usr/local/cargo/registry,sharing=locked \
|
|
||||||
--mount=type=cache,target=/usr/local/cargo/git,sharing=locked \
|
# .cargo/config.toml sets SQLX_OFFLINE=true; .sqlx contains the pre-verified query cache.
|
||||||
cargo build --release -p server -p worker --no-default-features --features "${FEATURES}"
|
# No live database needed at compile time.
|
||||||
|
#
|
||||||
|
# To build with PostgreSQL backend instead:
|
||||||
|
# --build-arg FEATURES=postgres,postgres-federation
|
||||||
|
# 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}"
|
||||||
|
|
||||||
# ----- runtime -----
|
# ----- runtime -----
|
||||||
FROM debian:bookworm-slim
|
FROM debian:bookworm-slim
|
||||||
|
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
ca-certificates \
|
ca-certificates \
|
||||||
wget \
|
|
||||||
libwebp7 \
|
|
||||||
fonts-dejavu-core \
|
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
COPY --from=builder /build/target/release/server ./server
|
COPY --from=builder /build/target/release/presentation ./presentation
|
||||||
COPY --from=builder /build/target/release/worker ./worker
|
COPY --from=builder /build/target/release/worker ./worker
|
||||||
COPY static ./static
|
COPY static ./static
|
||||||
COPY --from=spa-builder /spa/dist ./spa/dist
|
|
||||||
|
|
||||||
EXPOSE 3000
|
EXPOSE 3000
|
||||||
|
|
||||||
ENV RUST_LOG=server=info,worker=info,bootstrap=info,config=info,http_axum=info,tower_http=info
|
ENV RUST_LOG=presentation=info,tower_http=info
|
||||||
|
|
||||||
CMD ["./server"]
|
CMD ["./presentation"]
|
||||||
|
|||||||
180
Makefile
180
Makefile
@@ -1,180 +0,0 @@
|
|||||||
.DEFAULT_GOAL := check
|
|
||||||
|
|
||||||
check: fmt-check clippy test test-federation-off check-appcontext check-handler-deps check-handler-repos check-handler-services check-http-adapter-deps check-federation-off-social check-sqlite-is-ap-free check-binaries-are-thin check-federation-off-deps check-nats-isolated check-no-second-web-stack
|
|
||||||
@echo "✅ All checks passed"
|
|
||||||
|
|
||||||
check-appcontext:
|
|
||||||
@if grep -rn "AppContext" crates/application/src --include="*.rs" | grep -q .; then \
|
|
||||||
echo "❌ AppContext found in application crate:"; \
|
|
||||||
grep -rn "AppContext" crates/application/src --include="*.rs"; \
|
|
||||||
exit 1; \
|
|
||||||
fi
|
|
||||||
@echo "✅ No AppContext in application crate"
|
|
||||||
|
|
||||||
check-handler-deps:
|
|
||||||
@if grep -rnE "[A-Za-z0-9_]*Deps(\s*\{|::from\()" crates/adapters/http-axum/src --include="*.rs" --exclude-dir=tests --exclude=tests.rs | grep -q .; then \
|
|
||||||
echo "❌ hand-built deps struct found in http-axum:"; \
|
|
||||||
grep -rnE "[A-Za-z0-9_]*Deps(\s*\{|::from\()" crates/adapters/http-axum/src --include="*.rs" --exclude-dir=tests --exclude=tests.rs; \
|
|
||||||
exit 1; \
|
|
||||||
fi
|
|
||||||
@echo "✅ No hand-built deps structs in http-axum"
|
|
||||||
|
|
||||||
check-handler-repos:
|
|
||||||
@if grep -rn "app_ctx\.repos" crates/adapters/http-axum/src --include="*.rs" --exclude-dir=tests --exclude=tests.rs | grep -q .; then \
|
|
||||||
echo "❌ app_ctx.repos referenced in http-axum:"; \
|
|
||||||
grep -rn "app_ctx\.repos" crates/adapters/http-axum/src --include="*.rs" --exclude-dir=tests --exclude=tests.rs; \
|
|
||||||
exit 1; \
|
|
||||||
fi
|
|
||||||
@echo "✅ No app_ctx.repos references in http-axum"
|
|
||||||
|
|
||||||
|
|
||||||
HTTP_ADAPTER_ALLOWED_ADAPTERS :=
|
|
||||||
|
|
||||||
check-handler-services:
|
|
||||||
@hits=$$(find crates/adapters/http-axum/src -name '*.rs' -not -path '*/tests/*' -not -name tests.rs \
|
|
||||||
| xargs perl -0ne 'while (/app_ctx\s*\.\s*services\s*\.\s*([a-z_]+)/g) { print "$$ARGV: services.$$1\n" unless $$1 eq "review_logger" }'); \
|
|
||||||
if [ -n "$$hits" ]; then \
|
|
||||||
echo "❌ http-axum reaches a service port directly (call a use case instead):"; \
|
|
||||||
echo "$$hits"; \
|
|
||||||
exit 1; \
|
|
||||||
fi; \
|
|
||||||
echo "✅ No direct service-port calls in http-axum"
|
|
||||||
|
|
||||||
check-http-adapter-deps:
|
|
||||||
@deps=$$(awk '/^\[dependencies\]/{f=1;next} /^\[/{f=0} f' crates/adapters/http-axum/Cargo.toml \
|
|
||||||
| sed -n 's/^\([A-Za-z0-9_-]\{1,\}\)[[:space:]]*=.*/\1/p'); \
|
|
||||||
bad=""; \
|
|
||||||
for a in $$(ls crates/adapters); do \
|
|
||||||
case " $(HTTP_ADAPTER_ALLOWED_ADAPTERS) " in *" $$a "*) continue;; esac; \
|
|
||||||
if echo "$$deps" | grep -qx "$$a"; then bad="$$bad $$a"; fi; \
|
|
||||||
done; \
|
|
||||||
if [ -n "$$bad" ]; then \
|
|
||||||
echo "❌ http-axum depends on adapter crate(s):$$bad"; \
|
|
||||||
echo " http-axum may name renderers, not reachers — see ADR-0008."; \
|
|
||||||
exit 1; \
|
|
||||||
fi; \
|
|
||||||
echo "✅ http-axum depends on no other adapter crate"
|
|
||||||
|
|
||||||
|
|
||||||
check-federation-off-social:
|
|
||||||
@if grep -n "NoopSocialCommand\|NoopSocialQuery" crates/bootstrap/src/federation.rs | grep -q .; then \
|
|
||||||
echo "❌ bootstrap wires social noops — federation-off would report an empty follow graph:"; \
|
|
||||||
grep -n "NoopSocialCommand\|NoopSocialQuery" crates/bootstrap/src/federation.rs; \
|
|
||||||
exit 1; \
|
|
||||||
fi
|
|
||||||
@if ! awk '/cfg\(not\(feature = "federation"\)\)/ && !started {started=1} started && /cfg\(feature = "federation"\)/ {exit} started {print}' crates/bootstrap/src/federation.rs | grep -q "LocalSocialService"; then \
|
|
||||||
echo "❌ LocalSocialService not wired in the federation-off region of crates/bootstrap/src/federation.rs — federation-off has no social behavior wired at all, not even noops"; \
|
|
||||||
exit 1; \
|
|
||||||
fi
|
|
||||||
@echo "✅ bootstrap wires real social behavior in every configuration"
|
|
||||||
|
|
||||||
|
|
||||||
BINARIES_ALLOWED_DEPS := bootstrap config tokio axum anyhow dotenvy tracing
|
|
||||||
|
|
||||||
check-binaries-are-thin:
|
|
||||||
@bad=""; \
|
|
||||||
for c in server worker; do \
|
|
||||||
deps=$$(awk '/^\[dependencies\]/{f=1;next} /^\[/{f=0} f' crates/$$c/Cargo.toml \
|
|
||||||
| sed -n 's/^\([A-Za-z0-9_-]\{1,\}\)[[:space:]]*=.*/\1/p'); \
|
|
||||||
for d in $$deps; do \
|
|
||||||
case " $(BINARIES_ALLOWED_DEPS) " in *" $$d "*) continue;; esac; \
|
|
||||||
bad="$$bad $$c:$$d"; \
|
|
||||||
done; \
|
|
||||||
done; \
|
|
||||||
if [ -n "$$bad" ]; then \
|
|
||||||
echo "❌ binary [dependencies] outside {$(BINARIES_ALLOWED_DEPS)}:$$bad"; \
|
|
||||||
echo " wiring belongs in crates/bootstrap — see ADR-0013."; \
|
|
||||||
exit 1; \
|
|
||||||
fi; \
|
|
||||||
echo "✅ server and worker depend only on {$(BINARIES_ALLOWED_DEPS)}"
|
|
||||||
|
|
||||||
|
|
||||||
check-sqlite-is-ap-free:
|
|
||||||
@if grep -nE '^[[:space:]]*(k-ap|activitypub[A-Za-z0-9_-]*|[A-Za-z0-9_-]+-federation)[[:space:]]*=' crates/adapters/sqlite/Cargo.toml | grep -q .; then \
|
|
||||||
echo "❌ sqlite crate depends on ActivityPub:"; \
|
|
||||||
grep -nE '^[[:space:]]*(k-ap|activitypub[A-Za-z0-9_-]*|[A-Za-z0-9_-]+-federation)[[:space:]]*=' crates/adapters/sqlite/Cargo.toml; \
|
|
||||||
exit 1; \
|
|
||||||
fi
|
|
||||||
@echo "✅ sqlite crate depends on no k-ap, activitypub, or *-federation crate"
|
|
||||||
|
|
||||||
CARGO_TREE_NAMES := cargo tree -p server -p worker -e normal --prefix none
|
|
||||||
|
|
||||||
check-federation-off-deps:
|
|
||||||
@tree=$$($(CARGO_TREE_NAMES) --no-default-features) || exit 1; \
|
|
||||||
hits=$$(echo "$$tree" | grep -E '^(k-ap|activitypub_federation|activitypub|sqlite-federation) ' | sort -u); \
|
|
||||||
if [ -n "$$hits" ]; then \
|
|
||||||
echo "❌ federation-only crates in the --no-default-features server/worker tree:"; \
|
|
||||||
echo "$$hits"; \
|
|
||||||
exit 1; \
|
|
||||||
fi; \
|
|
||||||
echo "✅ federation-off tree has no k-ap, activitypub_federation, activitypub, or sqlite-federation"
|
|
||||||
|
|
||||||
check-nats-isolated:
|
|
||||||
@tree=$$($(CARGO_TREE_NAMES)) || exit 1; \
|
|
||||||
nats_tree=$$($(CARGO_TREE_NAMES) --features nats) || exit 1; \
|
|
||||||
if echo "$$tree" | grep -qE '^(async-nats|nats) '; then \
|
|
||||||
echo "❌ nats crates in the default server/worker tree:"; \
|
|
||||||
echo "$$tree" | grep -E '^(async-nats|nats) ' | sort -u; \
|
|
||||||
exit 1; \
|
|
||||||
fi; \
|
|
||||||
if ! echo "$$nats_tree" | grep -qE '^async-nats '; then \
|
|
||||||
echo "❌ async-nats missing from the --features nats server/worker tree — feature is not wired"; \
|
|
||||||
exit 1; \
|
|
||||||
fi; \
|
|
||||||
echo "✅ async-nats only appears with --features nats"
|
|
||||||
|
|
||||||
check-no-second-web-stack:
|
|
||||||
@for f in "" "--features nats"; do \
|
|
||||||
tree=$$($(CARGO_TREE_NAMES) $$f) || exit 1; \
|
|
||||||
hits=$$(echo "$$tree" | grep -E '^(actix|aws-lc)' | sort -u); \
|
|
||||||
if [ -n "$$hits" ]; then \
|
|
||||||
echo "❌ actix/aws-lc crates in the server/worker tree ($${f:-default}):"; \
|
|
||||||
echo "$$hits"; \
|
|
||||||
exit 1; \
|
|
||||||
fi; \
|
|
||||||
done; \
|
|
||||||
echo "✅ no actix-* or aws-lc-* in the default or nats server/worker tree"
|
|
||||||
|
|
||||||
fmt:
|
|
||||||
cargo fmt
|
|
||||||
|
|
||||||
fmt-check:
|
|
||||||
cargo fmt --check
|
|
||||||
|
|
||||||
clippy:
|
|
||||||
cargo clippy --workspace --all-targets -- -D warnings
|
|
||||||
|
|
||||||
test:
|
|
||||||
cargo test --workspace
|
|
||||||
|
|
||||||
test-federation-off:
|
|
||||||
cargo test --workspace --no-default-features
|
|
||||||
|
|
||||||
fix:
|
|
||||||
cargo fmt
|
|
||||||
cargo clippy --fix --allow-dirty --allow-staged
|
|
||||||
|
|
||||||
# Run the dev stack:
|
|
||||||
# server (:3000, in the foreground, Ctrl-C stops it)
|
|
||||||
# worker (background, log at /tmp/movies-diary-worker.log)
|
|
||||||
# spa (:5173, background, log at /tmp/movies-diary-spa.log)
|
|
||||||
# Tear down the background processes with `make dev-stop`.
|
|
||||||
# .env enables EVENT_BUS_BACKEND=nats, so both binaries are built with the nats feature.
|
|
||||||
dev: dev-worker dev-spa
|
|
||||||
cargo run -p server --features nats
|
|
||||||
|
|
||||||
dev-stop:
|
|
||||||
-pkill -f '[t]arget.debug.worker' || true
|
|
||||||
-pkill -f '[s]pa/node_modules/[.]bin/vite' || true
|
|
||||||
@echo "dev stack stopped"
|
|
||||||
|
|
||||||
dev-worker:
|
|
||||||
@bash -c 'nohup cargo run -p worker --features nats >> /tmp/movies-diary-worker.log 2>&1 & echo "worker → pid $$! (log: /tmp/movies-diary-worker.log)"'
|
|
||||||
|
|
||||||
dev-spa:
|
|
||||||
@bash -c 'nohup npm --prefix spa run dev >> /tmp/movies-diary-spa.log 2>&1 & echo "spa → pid $$! (log: /tmp/movies-diary-spa.log, http://localhost:5173)"'
|
|
||||||
|
|
||||||
spa-dev:
|
|
||||||
@npm --prefix spa run dev
|
|
||||||
|
|
||||||
.PHONY: check fmt fmt-check clippy test test-federation-off fix dev dev-stop dev-worker dev-spa spa-dev check-appcontext check-handler-deps check-handler-repos check-handler-services check-http-adapter-deps check-federation-off-social check-sqlite-is-ap-free check-binaries-are-thin check-federation-off-deps check-nats-isolated check-no-second-web-stack
|
|
||||||
336
README.md
336
README.md
@@ -1,123 +1,56 @@
|
|||||||
# Movies Diary
|
# Movies Diary
|
||||||
|
|
||||||
A self-hosted movie diary built in Rust. Ships a classic server-rendered HTML interface (no JavaScript) alongside a full React SPA, both backed by the same REST API. Federates over ActivityPub so reviews reach the Fediverse. Supports Jellyfin and Plex auto-import, full-text search, annual wrap-ups, goals, and bulk import from Letterboxd, IMDb, and other sources. Runs on SQLite.
|
A self-hosted, server-side rendered movie logging system with a full REST API. Built in Rust — no JavaScript in the HTML interface, just HTML forms and an RSS feed. Designed to run as a lightweight widget embedded on a personal site or as a backend for third-party clients.
|
||||||
|
|
||||||
[](LICENSE)
|
|
||||||
[](https://www.rust-lang.org/)
|
|
||||||
[](https://hub.docker.com/)
|
|
||||||
[](https://activitypub.rocks/)
|
|
||||||
[](https://www.sqlite.org/)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Table of Contents
|
|
||||||
|
|
||||||
- [Quick Start](#quick-start)
|
|
||||||
- [Features](#features)
|
|
||||||
- [Screenshots](#screenshots)
|
|
||||||
- [Architecture](#architecture)
|
|
||||||
- [Prerequisites](#prerequisites)
|
|
||||||
- [Configuration](#configuration)
|
|
||||||
- [Run](#run)
|
|
||||||
- [API](#api)
|
|
||||||
- [SPA](#spa)
|
|
||||||
- [Development](#development)
|
|
||||||
- [Test](#test)
|
|
||||||
- [Docker](#docker)
|
|
||||||
- [Media Server Integration](#media-server-integration)
|
|
||||||
- [Annual Wrap-Up](#annual-wrap-up)
|
|
||||||
- [Contributing](#contributing)
|
|
||||||
- [License](#license)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Quick Start
|
|
||||||
|
|
||||||
The fastest way to run Movies Diary is via Docker Compose:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cp .env.example .env
|
|
||||||
# Set JWT_SECRET and OMDB_API_KEY (or TMDB_API_KEY) in .env
|
|
||||||
docker compose up -d
|
|
||||||
```
|
|
||||||
|
|
||||||
Open `http://localhost:3000`. The HTTP server and background worker start together; data is persisted in a Docker volume.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- Log movies with a TMDB/OMDb ID or manual title/year/director, with a 1–5 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 0–5 rating
|
||||||
- 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)
|
- Immutable append-only viewing ledger (tracks re-watches)
|
||||||
- Spoiler Flag — authors mark a review as containing spoilers; the comment is veiled (blur + reveal) for every viewer except the author, withheld from RSS, and federates as `containsSpoilers` + an AP `summary` content warning so Mastodon-style clients also collapse it
|
|
||||||
- Background poster fetching and storage (local filesystem or S3-compatible)
|
- 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`
|
|
||||||
- Full-text search across movies and people via `GET /api/v1/search` — free-text query plus structured filters (genre, year, person, department, language); backed by SQLite FTS5
|
|
||||||
- People as first-class entities — browse by person via `GET /api/v1/people/{id}` and full credit history via `GET /api/v1/people/{id}/credits`; index populated automatically during TMDb enrichment
|
|
||||||
- RSS/Atom feed for public subscription (global and per-user)
|
- RSS/Atom feed for public subscription (global and per-user)
|
||||||
- JWT authentication via cookie (HTML) or Bearer token (REST API)
|
- JWT authentication via cookie (HTML) or Bearer token (REST API)
|
||||||
- ActivityPub federation — follow/unfollow remote users, accept/reject/remove followers, federated reviews broadcast as `Note` objects with movie poster image attachment, `#MoviesDiary` + `#MovieTitle` hashtags, paginated outbox (reviews, watchlist entries, goals), boost/Announce tracking, NodeInfo discovery endpoint, shared inbox delivery, actor profile sync (bio, avatar, discoverable); account migration via `Move` activity; account deletion broadcasts `Delete` actor to followers
|
- ActivityPub federation — follow/unfollow remote users, accept/reject/remove followers, federated reviews broadcast as `Note` objects with `#MoviesDiary` + `#MovieTitle` hashtags, paginated outbox, boost/Announce tracking, NodeInfo discovery endpoint, shared inbox delivery, actor profile sync (bio, avatar, discoverable)
|
||||||
- Federation moderation — instance-level domain blocking (admin-managed), per-user actor blocking with `Block` / `Undo Block` activities, delivery filter excludes blocked actors and blocked-domain inboxes
|
- Federation moderation — instance-level domain blocking (admin-managed), per-user actor blocking with `Block` activity, delivery filter excludes blocked actors and blocked-domain inboxes
|
||||||
- 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, 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
|
|
||||||
- Account deletion — self-service (own password) or admin (admin's password) from the settings page, profile page, or `DELETE /api/v1/users/me` / `DELETE /api/v1/users/{id}`; the account is tombstoned at once, then a background purge erases its data and tells the fediverse; usernames are never reused (ADR-0016)
|
|
||||||
- CSV and JSON diary export
|
- 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
|
- 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
|
- REST API v1 (`/api/v1/`) with full feature parity with the HTML interface
|
||||||
- OpenAPI documentation at `/docs` (Swagger UI)
|
- OpenAPI documentation at `/docs` (Swagger UI) and `/scalar` (Scalar)
|
||||||
- CSRF protection on all HTML form routes (double-submit cookie, defense-in-depth on top of `SameSite=Strict`)
|
- CSRF protection on all HTML form routes (double-submit cookie, defense-in-depth on top of `SameSite=Strict`)
|
||||||
- Per-IP rate limiting via token bucket (production-grade, backed by `axum-governor`)
|
- Per-IP rate limiting via token bucket (production-grade, backed by `axum-governor`)
|
||||||
- Single-page app at `/app/` — React + TanStack Router + shadcn/ui, built with Vite, served from the backend with client-side routing fallback
|
- Terminal UI client (`crates/tui`) for logging reviews, bulk CSV import, and diary browsing
|
||||||
- Terminal UI client (`crates/tui`, deprecated) for logging reviews, bulk CSV import, and diary browsing
|
|
||||||
|
|
||||||
## Screenshots
|
|
||||||
|
|
||||||
> SPA at `/app/` — React + TanStack Router + shadcn/ui
|
|
||||||
|
|
||||||
| Feed | Movie | Person |
|
|
||||||
|------|-------|--------|
|
|
||||||
|  |  |  |
|
|
||||||
|
|
||||||
| Profile | Wrap-Up | Wrap-Up card |
|
|
||||||
|---------|---------|--------------|
|
|
||||||
|  |  |  |
|
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
Hexagonal (Ports & Adapters) with Domain-Driven Design:
|
Hexagonal (Ports & Adapters) with Domain-Driven Design:
|
||||||
|
|
||||||
```
|
```
|
||||||
api-types — shared REST API request/response DTOs (Serialize/Deserialize + utoipa schemas) + HtmlPageContext; used by http-axum and tui
|
domain — pure types and trait definitions, no external deps
|
||||||
config — typed configuration (defaults, config.toml, legacy env names); loaded once by the binaries
|
application — use cases / business logic orchestration
|
||||||
bootstrap — composition root: the only crate that names adapters; builds the server router and the worker service
|
presentation — Axum HTTP router, composition root for the HTTP process
|
||||||
event-payload — serde payloads for domain events, shared by the NATS and SQLite-queue adapters
|
worker — standalone worker binary (event consumer, poster sync, federation)
|
||||||
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, insights, integrations, jobs, movies, person, search, social, users, watchlist, wrapup
|
|
||||||
server — thin HTTP binary (dotenv, config, bootstrap::build_server, axum::serve); features (federation, nats) forward to bootstrap
|
|
||||||
worker — thin worker binary (bootstrap::build_worker, run until ctrl-c)
|
|
||||||
adapters/
|
adapters/
|
||||||
http-axum — Axum HTTP adapter: JSON API, classic HTML UI (askama templates), OpenAPI spec, Swagger UI, federation-gated routes; library crate, no binary of its own
|
|
||||||
auth — JWT issuance and validation (Argon2 passwords)
|
auth — JWT issuance and validation (Argon2 passwords)
|
||||||
sqlite — SQLite repositories (one module per aggregate under repositories/), search (FTS5), social graph, durable event queue, connection factory + migrations; the only storage adapter
|
sqlite — SQLite repository + connection factory
|
||||||
|
postgres — PostgreSQL repository + connection factory
|
||||||
metadata — TMDB / OMDb HTTP client
|
metadata — TMDB / OMDb HTTP client
|
||||||
poster-fetcher — downloads poster images
|
poster-fetcher — downloads poster images
|
||||||
object-storage — stores images (posters + user avatars) on local filesystem or S3-compatible storage
|
image-storage — stores images (posters + user avatars) on local filesystem or S3-compatible storage
|
||||||
image-converter — optional background worker: converts stored images to AVIF or WebP; backfills existing images via a 24h periodic job
|
poster-sync — event handler: triggers poster fetch+store on MovieDiscovered
|
||||||
tmdb-enrichment — TMDb HTTP client implementing MovieEnrichmentClient and PersonEnrichmentClient; event handlers (MovieEnrichmentHandler, PersonEnrichmentHandler) live in the application layer
|
template-askama — Askama HTML rendering
|
||||||
rss — RSS/Atom feed generation
|
rss — RSS/Atom feed generation
|
||||||
export — CSV and JSON diary serialization
|
export — CSV and JSON diary serialization
|
||||||
importer — CSV/TSV/JSON/XLSX parser and column mapper for bulk import
|
importer — CSV/TSV/JSON/XLSX parser and column mapper for bulk import
|
||||||
media-server — Jellyfin and Plex webhook payload parsers (MediaServerParser adapter; Plex requires Plex Pass)
|
event-payload — shared event serialization DTOs (used by all event bus adapters)
|
||||||
event-publisher — in-memory event channel
|
sqlite-event-queue — durable polling event queue backed by SQLite
|
||||||
|
postgres-event-queue — durable polling event queue backed by PostgreSQL
|
||||||
nats — NATS Core / JetStream event publisher and consumer
|
nats — NATS Core / JetStream event publisher and consumer
|
||||||
activitypub — ActivityPub federation adapter (follow, inbox/outbox, actor); delegates to k-ap for protocol internals
|
event-publisher — in-memory event channel (tests only)
|
||||||
sqlite-federation — SQLite-backed federation repository (k-ap trait implementations; only built with the `federation` feature)
|
activitypub — ActivityPub federation wiring (follow, inbox/outbox, actor)
|
||||||
tui — terminal UI client (ratatui); shares api-types with http-axum for typed API access
|
activitypub-base — core ActivityPub protocol types and service
|
||||||
spa/ — React SPA (TanStack Router + shadcn/ui + Vite); served at /app/ by the backend
|
sqlite-federation — SQLite-backed federation repository
|
||||||
|
postgres-federation — PostgreSQL-backed federation repository
|
||||||
|
doc — OpenAPI spec assembly and Swagger UI / Scalar serving
|
||||||
|
tui — terminal UI client (ratatui)
|
||||||
```
|
```
|
||||||
|
|
||||||
## Prerequisites
|
## Prerequisites
|
||||||
@@ -127,61 +60,51 @@ spa/ — React SPA (TanStack Router + shadcn/ui + Vite); served a
|
|||||||
- Poster storage: local filesystem (zero deps) or an S3-compatible object store (e.g. MinIO)
|
- Poster storage: local filesystem (zero deps) or an S3-compatible object store (e.g. MinIO)
|
||||||
- An [OMDb API key](https://www.omdbapi.com/apikey.aspx)
|
- An [OMDb API key](https://www.omdbapi.com/apikey.aspx)
|
||||||
|
|
||||||
## Configuration
|
## Environment Variables
|
||||||
|
|
||||||
Settings are layered, later sources winning:
|
A `.env.example` file is provided at the repo root — copy it to `.env` and fill in your values.
|
||||||
|
|
||||||
1. built-in defaults
|
```env
|
||||||
2. `config.toml` in the working directory, or the file named by `CONFIG_FILE` (a named file that does not exist is an error; the default `config.toml` is optional)
|
# Database
|
||||||
3. environment variables (including those from `.env`), under the names in the table below
|
DATABASE_URL=sqlite://movies.db
|
||||||
|
|
||||||
Copy `.env.example` to `.env` and set the values you need. Malformed values (a non-numeric `PORT`, an unknown `EVENT_BUS_BACKEND`) fail startup with a message naming the setting. An empty value (`PORT=`) counts as unset, so the default applies. The variable names are unchanged from earlier releases; every one except `RUST_LOG` and `CONFIG_FILE` maps to a `section.field` key in `config.toml` (for example `PORT` is `server.port`, `JWT_SECRET` is `auth.jwt_secret`).
|
# Authentication
|
||||||
|
JWT_SECRET=change-me
|
||||||
|
|
||||||
| Variable | Default | Required | Description |
|
# OMDb metadata
|
||||||
|---|---|---|---|
|
OMDB_API_KEY=your-key
|
||||||
| `DATABASE_URL` | — | Yes | SQLite connection string (e.g. `sqlite://movies.db`); the only value the config loader itself requires |
|
|
||||||
| `JWT_SECRET` | — | Server | Secret for JWT signing — use a long random string. The server refuses to start without it (the worker does not need it) |
|
|
||||||
| `OMDB_API_KEY` | — | One of the two | [OMDb](https://www.omdbapi.com/apikey.aspx) key for movie metadata. Server and worker refuse to start unless `TMDB_API_KEY` or `OMDB_API_KEY` is set |
|
|
||||||
| `TMDB_API_KEY` | — | One of the two | [TMDb](https://www.themoviedb.org/settings/api) key — used for metadata when set (takes precedence over OMDb); enables cast, crew, genres, enrichment |
|
|
||||||
| `BASE_URL` | `http://localhost:3000` | No | Public URL of your instance (used for ActivityPub actor URLs); set it for any real deployment |
|
|
||||||
| `IMAGE_STORAGE_BACKEND` | `local` | No | `local` or `s3` |
|
|
||||||
| `IMAGE_STORAGE_PATH` | `./images` | No | Path for local image storage |
|
|
||||||
| `MINIO_ENDPOINT` | — | S3 only | S3-compatible endpoint (e.g. `http://localhost:9000`) |
|
|
||||||
| `MINIO_BUCKET` | — | S3 only | Bucket name |
|
|
||||||
| `MINIO_REGION` | `minio` | No | Region for S3 storage |
|
|
||||||
| `MINIO_ACCESS_KEY_ID` | — | S3 only | Access key ID |
|
|
||||||
| `MINIO_SECRET_ACCESS_KEY` | — | S3 only | Secret access key |
|
|
||||||
| `IMAGE_CONVERSION_ENABLED` | `false` | No | Set `true` to convert stored images to AVIF or WebP (only the value `true` enables it) |
|
|
||||||
| `IMAGE_CONVERSION_FORMAT` | — | When conversion is enabled | `avif` or `webp`; the worker fails at startup if conversion is enabled without it |
|
|
||||||
| `HOST` | `0.0.0.0` | No | Bind address |
|
|
||||||
| `PORT` | `3000` | No | HTTP port |
|
|
||||||
| `RATE_LIMIT` | `60` | No | Requests per minute per IP |
|
|
||||||
| `ALLOW_REGISTRATION` | `false` | No | Set `true` (or `1`) to allow new sign-ups |
|
|
||||||
| `SECURE_COOKIES` | `false` | No | Set `true` when serving over HTTPS (only the value `true` enables it) |
|
|
||||||
| `RUST_LOG` | — | No | Log verbosity (e.g. `server=info,worker=info,bootstrap=info,config=info,http_axum=info`); read by the logger, not part of `config.toml` |
|
|
||||||
| `CORS_ORIGINS` | empty | No | Comma-separated allowed origins for the API; empty or `*` allows any origin |
|
|
||||||
| `EVENT_BUS_BACKEND` | `db` | No | `db` (default) or `nats` |
|
|
||||||
| `NATS_URL` | — | NATS only | NATS connection URL (e.g. `nats://localhost:4222`) |
|
|
||||||
|
|
||||||
`DATABASE_URL` is the only setting the loader requires; the other "required" entries are enforced when the corresponding adapter is built, and failing there also stops startup. Further optional variables (`CONFIG_FILE`, `JWT_TTL_SECONDS`, `REFRESH_TTL_SECONDS`, `POSTER_FETCH_TIMEOUT_SECONDS`, `EVENT_CHANNEL_BUFFER`, `EVENT_QUEUE_*`, `NATS_MODE`, `NATS_STREAM_NAME`, `NATS_SUBJECT_PREFIX`, `NATS_CONSUMER_NAME`, `FEDERATION_DEBUG`, `WRAPUP_*`) are read by `crates/config`; see `crates/config/src/` for defaults.
|
# Public base URL (used for ActivityPub actor URLs and canonical links)
|
||||||
|
BASE_URL=https://yourdomain.example.com
|
||||||
|
|
||||||
### Cargo features
|
# Image storage — pick one backend:
|
||||||
|
|
||||||
| Feature | Default | Effect |
|
# Option A: local filesystem (zero deps)
|
||||||
|---|---|---|
|
IMAGE_STORAGE_BACKEND=local
|
||||||
| `federation` | yes | ActivityPub federation (`activitypub`, `sqlite-federation`, federation routes) |
|
IMAGE_STORAGE_PATH=./images
|
||||||
| `nats` | no | NATS event bus (`EVENT_BUS_BACKEND=nats`) |
|
|
||||||
|
|
||||||
Build without federation with `--no-default-features`. `sqlite` and `sqlite-federation` are deprecated aliases kept so old build commands still work.
|
# Option B: S3-compatible (MinIO, AWS S3, etc.)
|
||||||
|
# IMAGE_STORAGE_BACKEND=s3
|
||||||
|
# MINIO_ENDPOINT=http://localhost:9000
|
||||||
|
# MINIO_BUCKET=posters
|
||||||
|
# MINIO_REGION=minio
|
||||||
|
# MINIO_ACCESS_KEY_ID=minioadmin
|
||||||
|
# MINIO_SECRET_ACCESS_KEY=minioadmin
|
||||||
|
|
||||||
### Build notes
|
# Optional
|
||||||
|
HOST=0.0.0.0
|
||||||
|
PORT=3000
|
||||||
|
RATE_LIMIT=60 # requests per minute per IP (default: 60)
|
||||||
|
ALLOW_REGISTRATION=true # set to false to disable new sign-ups
|
||||||
|
SECURE_COOKIES=true # set when serving over HTTPS
|
||||||
|
RUST_LOG=presentation=info,tower_http=info,worker=info,application=info
|
||||||
|
|
||||||
- `cargo build` / `cargo test` build every crate except the deprecated `tui`, which sits outside `default-members`. Use `-p tui` for it; `make check` and CI use `--workspace`, so it is still linted and tested.
|
# Event bus — "db" (default, uses same database) or "nats"
|
||||||
- Release builds use `codegen-units = 1` and `strip = true` (smaller binaries; thin LTO was measured and made builds slower and binaries larger, so it is off).
|
EVENT_BUS_BACKEND=db
|
||||||
- SQLite is compiled from source (bundled `libsqlite3-sys`), so the first clean build spends about a minute on it; incremental builds and the Docker/CI caches don't repeat that.
|
# NATS_URL=nats://localhost:4222 # required when EVENT_BUS_BACKEND=nats
|
||||||
- TLS uses rustls with the `ring` provider only; `aws-lc` and `actix` are kept out of the graph by `make check-no-second-web-stack`.
|
```
|
||||||
|
|
||||||
The `worker` binary must run alongside `server` to process events:
|
The `worker` binary must run alongside `presentation` to process events:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cargo run -p worker
|
cargo run -p worker
|
||||||
@@ -190,13 +113,11 @@ cargo run -p worker
|
|||||||
## Run
|
## Run
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cargo run -p server # HTTP server (0.0.0.0:3000)
|
cargo run -p presentation # HTTP server (0.0.0.0:3000)
|
||||||
cargo run -p worker # event worker (poster sync, in a separate terminal)
|
cargo run -p worker # event worker (poster sync, in a separate terminal)
|
||||||
```
|
```
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
**Event flow.** The server never publishes events directly: every write that raises an event stores it in the `event_queue` table in the same transaction (a transactional outbox, see [ADR-0015](docs/adr/0015-transactional-outbox.md)). With `EVENT_BUS_BACKEND=db` the worker consumes those rows; with `nats` the worker relays them to JetStream (with `Nats-Msg-Id` set to the event id) and consumes them from there. Duplicates are filtered in three layers: the broker's duplicate window, a claim lease on queue rows, and a per-(event, handler) processed-event ledger. Handlers must stay idempotent.
|
|
||||||
|
|
||||||
## API
|
## API
|
||||||
|
|
||||||
@@ -205,125 +126,56 @@ All REST endpoints are under `/api/v1/`. Authentication uses `Authorization: Bea
|
|||||||
Interactive API documentation is available at runtime:
|
Interactive API documentation is available at runtime:
|
||||||
|
|
||||||
- **Swagger UI** — `http://localhost:3000/docs`
|
- **Swagger UI** — `http://localhost:3000/docs`
|
||||||
|
- **Scalar** — `http://localhost:3000/scalar`
|
||||||
|
|
||||||
An [Insomnia](https://insomnia.rest/) collection covering all endpoints is included at [`movies-diary.insomnia.json`](movies-diary.insomnia.json). Import it via **File → Import**, set `base_url` and `token` in the environment, and you're ready to go.
|
## Terminal UI
|
||||||
|
|
||||||
## SPA
|
|
||||||
|
|
||||||
The single-page app lives in `spa/` and is served at `/app/` by the backend. For local development:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd spa && bun install && bun run dev # http://localhost:5173/app/
|
|
||||||
```
|
|
||||||
|
|
||||||
Set `CORS_ORIGINS=http://localhost:5173` in the backend `.env` to allow cross-origin API calls during development.
|
|
||||||
|
|
||||||
For production, `bun run build` outputs to `spa/dist/` which the backend serves statically (included in Docker image automatically).
|
|
||||||
|
|
||||||
## Terminal UI (deprecated)
|
|
||||||
|
|
||||||
> **Note:** The TUI was an experiment with ratatui and is no longer actively maintained. It may not support newer features (goals, watchlist, federation, etc.). Contributions welcome — if you'd like to maintain it, open a PR.
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cargo run -p tui
|
cargo run -p tui
|
||||||
```
|
```
|
||||||
|
|
||||||
Supports review logging, bulk CSV import, and diary browsing.
|
Supports review logging, bulk CSV import (column order matches the export format), and diary browsing with review history.
|
||||||
|
|
||||||
## Development
|
|
||||||
|
|
||||||
A `Makefile` wraps the most common dev commands:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
make # make check: the full gate, same steps as CI
|
|
||||||
make fix # auto-apply fmt + clippy fixes
|
|
||||||
make fmt # apply rustfmt
|
|
||||||
make clippy # clippy with -D warnings
|
|
||||||
make test # cargo test --workspace
|
|
||||||
```
|
|
||||||
|
|
||||||
`make check` runs fmt-check, clippy, tests (default features and `--no-default-features`), and the layering guards (see `CONTRIBUTING.md`).
|
|
||||||
|
|
||||||
## Test
|
## Test
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cargo test --workspace # everything; needs no external services
|
cargo test
|
||||||
cargo test -p application # business logic tests only — in-memory fakes, no database
|
|
||||||
cargo test -p domain # domain model + value object tests
|
|
||||||
cargo test -p bootstrap # route smoke, API and handler tests over the real wiring
|
|
||||||
cargo llvm-cov -p application -p domain # line coverage report (requires cargo-llvm-cov)
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Tests live in `crates/<crate>/tests/`; the exceptions are listed in `CODE_STYLE.md`. The `application` and `domain` crates have 400+ tests covering all use case modules (auth, diary, goals, import, insights, integrations, movies, person, search, users, watchlist, wrapup) backed by the in-memory fakes and factories in `domain::testing` (the `test-helpers` feature). They are the fastest feedback loop for business logic changes.
|
|
||||||
|
|
||||||
## Docker
|
## Docker
|
||||||
|
|
||||||
### Quick start
|
The image contains both `presentation` (HTTP server) and `worker` (event processor). Run them as separate containers sharing the same data volume:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cp .env.example .env
|
# Build (SQLite + federation + NATS support)
|
||||||
# Edit .env — set JWT_SECRET and OMDB_API_KEY (or TMDB_API_KEY)
|
docker build -t movies-diary \
|
||||||
docker compose up -d
|
--build-arg FEATURES=sqlite,sqlite-federation,nats .
|
||||||
|
|
||||||
|
# HTTP server
|
||||||
|
docker run -p 3000:3000 \
|
||||||
|
-e DATABASE_URL=sqlite:///data/movies.db \
|
||||||
|
-e JWT_SECRET=change-me \
|
||||||
|
-e OMDB_API_KEY=your-key \
|
||||||
|
-e BASE_URL=https://yourdomain.example.com \
|
||||||
|
-e EVENT_BUS_BACKEND=nats \
|
||||||
|
-e NATS_URL=nats://nats:4222 \
|
||||||
|
-v $(pwd)/data:/data \
|
||||||
|
movies-diary
|
||||||
|
|
||||||
|
# Event worker (separate container, same image)
|
||||||
|
docker run \
|
||||||
|
-e DATABASE_URL=sqlite:///data/movies.db \
|
||||||
|
-e JWT_SECRET=change-me \
|
||||||
|
-e OMDB_API_KEY=your-key \
|
||||||
|
-e BASE_URL=https://yourdomain.example.com \
|
||||||
|
-e EVENT_BUS_BACKEND=nats \
|
||||||
|
-e NATS_URL=nats://nats:4222 \
|
||||||
|
-v $(pwd)/data:/data \
|
||||||
|
--entrypoint ./worker \
|
||||||
|
movies-diary
|
||||||
```
|
```
|
||||||
|
|
||||||
This builds and starts the HTTP server (port 3000) and event worker. Data is persisted in a Docker volume.
|
To build for PostgreSQL: `--build-arg FEATURES=postgres,postgres-federation,nats`
|
||||||
|
|
||||||
### Manual docker run
|
|
||||||
|
|
||||||
The image contains both `server` and `worker` binaries. Run them as separate containers sharing the same data volume:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker build -t movies-diary .
|
|
||||||
|
|
||||||
docker run -p 3000:3000 --env-file .env -v movies-diary-data:/data movies-diary
|
|
||||||
docker run --env-file .env -v movies-diary-data:/data --entrypoint ./worker movies-diary
|
|
||||||
```
|
|
||||||
|
|
||||||
Default build enables `federation`; add NATS with `--build-arg FEATURES=federation,nats`. The Dockerfile uses [cargo-chef](https://github.com/LukeMathWalker/cargo-chef): dependencies are compiled in their own layer keyed on the manifests, so a source-only change rebuilds just the workspace crates. BuildKit cache mounts keep the cargo registry between builds. No Dockerfile edit is needed when a crate is added. SQLite is the only database backend (see [ADR-0012](docs/adr/0012-sqlite-is-the-only-backend.md)).
|
|
||||||
|
|
||||||
## Media Server Integration
|
|
||||||
|
|
||||||
Auto-log movies you finish watching. Go to `/settings/integrations` to generate a webhook token, then configure your media server.
|
|
||||||
|
|
||||||
### Jellyfin
|
|
||||||
|
|
||||||
1. Install the **Webhook** plugin (Dashboard > Plugins > Catalog)
|
|
||||||
2. Add a **Generic** destination:
|
|
||||||
- **URL**: `https://yourdomain.example.com/api/v1/webhooks/jellyfin`
|
|
||||||
- **Header**: `Authorization` = `Bearer <your-token>`
|
|
||||||
- **Send All Properties**: enabled
|
|
||||||
- **Notification Type**: Playback Stop only
|
|
||||||
- **Item Type**: Movies only
|
|
||||||
|
|
||||||
### Plex (requires Plex Pass)
|
|
||||||
|
|
||||||
1. Go to Settings > Webhooks in your Plex server
|
|
||||||
2. Add webhook URL: `https://yourdomain.example.com/api/v1/webhooks/plex`
|
|
||||||
3. Plex does not support custom headers natively — pass the token as a query param: `https://yourdomain.example.com/api/v1/webhooks/plex?token=<your-token>`
|
|
||||||
|
|
||||||
Movies you finish watching appear in your watch queue at `/watch-queue` — rate and confirm to add to your diary.
|
|
||||||
|
|
||||||
## Annual Wrap-Up
|
|
||||||
|
|
||||||
Generate a year-in-review summary for any user — top directors, actors, genres, rating distribution, total watch time, rewatch stats, and more. Available as a shareable HTML page.
|
|
||||||
|
|
||||||
**Generate via API** (admin only):
|
|
||||||
```bash
|
|
||||||
curl -X POST http://localhost:3000/api/v1/wrapups/generate \
|
|
||||||
-H "Authorization: Bearer <admin-token>" \
|
|
||||||
-H "Content-Type: application/json" \
|
|
||||||
-d '{"user_id": "<uuid>", "start_date": "2025-01-01", "end_date": "2026-01-01"}'
|
|
||||||
```
|
|
||||||
|
|
||||||
Omit `user_id` for a global instance wrap-up. The worker computes stats in the background — poll `GET /api/v1/wrapups/{id}` for status.
|
|
||||||
|
|
||||||
**View:** `http://localhost:3000/wrapups/{user_id}/2025` (public, no login required)
|
|
||||||
|
|
||||||
**Auto-generate:** The worker runs a daily job in January that generates wrap-ups for all users with reviews in the previous year.
|
|
||||||
|
|
||||||
## Contributing
|
|
||||||
|
|
||||||
See [CONTRIBUTING.md](CONTRIBUTING.md) for setup instructions, architecture overview, and PR guidelines.
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
|||||||
161
architecture.mmd
161
architecture.mmd
@@ -1,161 +0,0 @@
|
|||||||
---
|
|
||||||
title: Movies Diary — Hexagonal Architecture
|
|
||||||
---
|
|
||||||
graph TB
|
|
||||||
subgraph Binaries["Binaries (thin: config + bootstrap + run)"]
|
|
||||||
SERVER["server<br/><i>load config, bootstrap::build_server, axum::serve</i>"]
|
|
||||||
WORKER["worker<br/><i>bootstrap::build_worker</i><br/>Concurrent dispatch, graceful shutdown"]
|
|
||||||
TUI["tui<br/><i>Terminal UI (deprecated)</i>"]
|
|
||||||
end
|
|
||||||
|
|
||||||
subgraph Config["config"]
|
|
||||||
CFG["AppConfig<br/><i>defaults, config.toml / CONFIG_FILE,<br/>legacy env names</i>"]
|
|
||||||
end
|
|
||||||
|
|
||||||
subgraph Application["Application Layer"]
|
|
||||||
direction TB
|
|
||||||
DEPS["Deps<br/><i>one narrow deps struct per use case</i>"]
|
|
||||||
APP_PORTS["ReviewLogger<br/><i>application-layer port</i>"]
|
|
||||||
subgraph UseCases["Use Cases"]
|
|
||||||
UC_AUTH["auth<br/>login, register"]
|
|
||||||
UC_DIARY["diary<br/>log_review, edit_review,<br/>get_diary, get_activity_feed,<br/>export"]
|
|
||||||
UC_MOVIES["movies<br/>get_movies, get_movie_profile,<br/>enrich_movie, request_enrichment,<br/>sync_poster, reindex_search,<br/>merge_duplicates"]
|
|
||||||
UC_IMPORT["import<br/>create_session, apply_mapping,<br/>execute, profiles"]
|
|
||||||
UC_USERS["users<br/>get_users, get_profile,<br/>update_profile, delete_account"]
|
|
||||||
UC_WATCHLIST["watchlist<br/>add, remove, get"]
|
|
||||||
UC_WRAPUP["wrapup<br/>generate, compute,<br/>list, delete"]
|
|
||||||
UC_GOALS["goals<br/>create, update, delete,<br/>get, list"]
|
|
||||||
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>"]
|
|
||||||
EH_PERSON["PersonEnrichmentHandler<br/><i>on PersonEnrichmentRequested</i>"]
|
|
||||||
EH_DISCOVER["MovieDiscoveryIndexer"]
|
|
||||||
EH_CLEANUP["SearchCleanupHandler"]
|
|
||||||
EH_REINDEX["SearchReindexHandler"]
|
|
||||||
EH_WRAPUP["WrapUpEventHandler"]
|
|
||||||
EH_POSTER["PosterSyncHandler<br/><i>poster sync</i>"]
|
|
||||||
end
|
|
||||||
subgraph Jobs["Periodic Jobs"]
|
|
||||||
JOB_IMPORT["ImportSessionCleanup"]
|
|
||||||
JOB_WATCH["WatchEventCleanup"]
|
|
||||||
JOB_STALE["EnrichmentStaleness"]
|
|
||||||
JOB_WRAPGEN["WrapUpAutoGenerate"]
|
|
||||||
JOB_WRAPCLEAN["WrapUpCleanup"]
|
|
||||||
JOB_SESSION["RefreshSessionCleanup"]
|
|
||||||
JOB_DEDUP["MovieDeduplication<br/><i>merge duplicate movie<br/>records (daily)</i>"]
|
|
||||||
end
|
|
||||||
WORKER_SVC["WorkerService<br/><i>Semaphore(8), JoinSet,<br/>shutdown signal</i>"]
|
|
||||||
end
|
|
||||||
|
|
||||||
subgraph Domain["Domain Layer (0 dependencies)"]
|
|
||||||
direction TB
|
|
||||||
subgraph Models["Models"]
|
|
||||||
M_MOVIE["Movie, MovieSummary,<br/>MovieProfile"]
|
|
||||||
M_REVIEW["Review, ReviewEdit,<br/>DiaryEntry, FeedEntry"]
|
|
||||||
M_USER["User, UserSummary"]
|
|
||||||
M_PERSON["Person, PersonId,<br/>PersonCredits"]
|
|
||||||
M_WATCHLIST["WatchlistEntry,<br/>WatchEvent"]
|
|
||||||
M_GOAL["Goal, GoalWithProgress,<br/>UserSettings, RemoteGoalEntry"]
|
|
||||||
M_WRAPUP["WrapUpReport,<br/>MovieRef, PersonStat"]
|
|
||||||
M_SEARCH["SearchQuery,<br/>SearchResults"]
|
|
||||||
end
|
|
||||||
subgraph Ports["Port Traits (Interfaces)"]
|
|
||||||
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>"]
|
|
||||||
DS_REVIEW["ReviewHistoryAnalyzer<br/><i>rating_trend</i>"]
|
|
||||||
end
|
|
||||||
EVENTS["DomainEvent enum<br/><i>ReviewLogged, MovieDiscovered,<br/>GoalCreated, GoalUpdated,<br/>UserDeleted, UserAccountMoved,<br/>SearchReindexRequested, ...</i>"]
|
|
||||||
VO["Value Objects<br/><i>MovieId, UserId, Rating,<br/>WatchMedium, Email, Username,<br/>Password, ...</i>"]
|
|
||||||
end
|
|
||||||
|
|
||||||
subgraph ApiTypes["api-types"]
|
|
||||||
DTO["DTOs<br/><i>MovieDto, ReviewDto,<br/>FeedEntryDto, UserSummaryDto,<br/>HtmlPageContext, ...</i>"]
|
|
||||||
end
|
|
||||||
|
|
||||||
subgraph Bootstrap["bootstrap"]
|
|
||||||
BS["build_server, build_worker<br/><i>Composition root: the only crate that names adapters</i>"]
|
|
||||||
end
|
|
||||||
|
|
||||||
subgraph EventPayload["event-payload"]
|
|
||||||
EP["Serde payloads for domain events"]
|
|
||||||
end
|
|
||||||
|
|
||||||
subgraph Adapters["Adapters (implement Port Traits)"]
|
|
||||||
direction TB
|
|
||||||
subgraph Http["HTTP driving adapter"]
|
|
||||||
A_HTTP["http-axum<br/><i>JSON API, classic HTML (askama),<br/>OpenAPI, federation-gated routes,<br/>one refusal shape</i>"]
|
|
||||||
end
|
|
||||||
subgraph Storage["Storage"]
|
|
||||||
A_SQLITE["sqlite<br/><i>repositories per aggregate, FTS5 search,<br/>social graph, durable event queue, migrations</i>"]
|
|
||||||
A_OBJ["object-storage<br/><i>S3 / filesystem</i>"]
|
|
||||||
end
|
|
||||||
subgraph Messaging["Messaging"]
|
|
||||||
A_NATS["nats<br/><i>JetStream / Core</i>"]
|
|
||||||
A_EVT_PUB["event-publisher<br/><i>In-memory channel</i>"]
|
|
||||||
end
|
|
||||||
subgraph External["External Services"]
|
|
||||||
A_METADATA["metadata<br/><i>TMDB / OMDb search/details</i>"]
|
|
||||||
A_TMDB["tmdb-enrichment<br/><i>Credits, keywords, cast</i>"]
|
|
||||||
A_POSTER["poster-fetcher<br/><i>TMDB image download</i>"]
|
|
||||||
A_AUTH["auth<br/><i>JWT tokens</i>"]
|
|
||||||
end
|
|
||||||
subgraph Federation["Federation (feature-gated)"]
|
|
||||||
A_AP["activitypub<br/><i>k_ap library; ActivityPubEventHandler<br/>(reviews, watchlist, goals, UserDeleted, UserAccountMoved)</i>"]
|
|
||||||
A_SQLITE_FED["sqlite-federation<br/><i>k_ap repositories</i>"]
|
|
||||||
end
|
|
||||||
subgraph Media["Media Processing"]
|
|
||||||
A_IMG["image-converter<br/><i>AVIF/WebP</i>"]
|
|
||||||
end
|
|
||||||
subgraph Formats["Formats"]
|
|
||||||
A_RSS["rss<br/><i>Feed generation</i>"]
|
|
||||||
A_EXPORT["export<br/><i>CSV/JSON diary</i>"]
|
|
||||||
A_IMPORT["importer<br/><i>CSV/JSON/XLSX parser</i>"]
|
|
||||||
A_MEDIA_SERVER["media-server<br/><i>Jellyfin + Plex webhook parsers</i>"]
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
%% Dependency arrows
|
|
||||||
SERVER -->|"loads"| Config
|
|
||||||
SERVER -->|"calls"| Bootstrap
|
|
||||||
WORKER -->|"loads"| Config
|
|
||||||
WORKER -->|"calls"| Bootstrap
|
|
||||||
Bootstrap -->|"wires"| Adapters
|
|
||||||
Bootstrap -->|"builds deps for"| Application
|
|
||||||
A_HTTP -->|"uses"| Application
|
|
||||||
A_HTTP -->|"maps to"| ApiTypes
|
|
||||||
TUI -->|"typed API access"| ApiTypes
|
|
||||||
|
|
||||||
Application -->|"depends on"| Domain
|
|
||||||
UC_WRAPUP -->|"delegates to"| DS_WRAPUP
|
|
||||||
|
|
||||||
Adapters -.->|"implements"| Ports
|
|
||||||
A_NATS -.->|"serialises with"| EventPayload
|
|
||||||
A_SQLITE -.->|"event queue serialises with"| EventPayload
|
|
||||||
|
|
||||||
%% Key data flows
|
|
||||||
A_HTTP ===|"HTTP"| DTO
|
|
||||||
WORKER ===|"Events"| EVENTS
|
|
||||||
|
|
||||||
classDef domain fill:#1a1a2e,stroke:#e94560,color:#fff
|
|
||||||
classDef app fill:#16213e,stroke:#0f3460,color:#fff
|
|
||||||
classDef adapter fill:#0f3460,stroke:#533483,color:#fff
|
|
||||||
classDef binary fill:#533483,stroke:#e94560,color:#fff
|
|
||||||
classDef api fill:#2a2a4a,stroke:#e94560,color:#fff
|
|
||||||
|
|
||||||
class Domain domain
|
|
||||||
class DomainServices domain
|
|
||||||
class Application app
|
|
||||||
class Adapters adapter
|
|
||||||
class Binaries binary
|
|
||||||
class Config app
|
|
||||||
class Bootstrap binary
|
|
||||||
class ApiTypes api
|
|
||||||
21
crates/adapters/activitypub-base/Cargo.toml
Normal file
21
crates/adapters/activitypub-base/Cargo.toml
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
[package]
|
||||||
|
name = "activitypub-base"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
tokio = { workspace = true }
|
||||||
|
serde = { workspace = true }
|
||||||
|
serde_json = { workspace = true }
|
||||||
|
reqwest = { workspace = true }
|
||||||
|
uuid = { workspace = true }
|
||||||
|
chrono = { workspace = true }
|
||||||
|
thiserror = { workspace = true }
|
||||||
|
anyhow = { workspace = true }
|
||||||
|
tracing = { workspace = true }
|
||||||
|
async-trait = { workspace = true }
|
||||||
|
axum = { workspace = true }
|
||||||
|
|
||||||
|
activitypub_federation = "0.7.0-beta.11"
|
||||||
|
url = { version = "2", features = ["serde"] }
|
||||||
|
enum_delegate = "0.2"
|
||||||
508
crates/adapters/activitypub-base/src/activities.rs
Normal file
508
crates/adapters/activitypub-base/src/activities.rs
Normal file
@@ -0,0 +1,508 @@
|
|||||||
|
use activitypub_federation::{
|
||||||
|
config::Data,
|
||||||
|
fetch::object_id::ObjectId,
|
||||||
|
kinds::activity::{
|
||||||
|
AcceptType, CreateType, DeleteType, FollowType, RejectType, UndoType, UpdateType,
|
||||||
|
},
|
||||||
|
traits::Activity,
|
||||||
|
};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
|
||||||
|
#[serde(rename = "Announce")]
|
||||||
|
pub struct AnnounceType;
|
||||||
|
|
||||||
|
use crate::actors::DbActor;
|
||||||
|
use crate::data::FederationData;
|
||||||
|
use crate::error::Error;
|
||||||
|
use crate::repository::{FollowerStatus, FollowingStatus};
|
||||||
|
|
||||||
|
// --- Follow ---
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct FollowActivity {
|
||||||
|
pub(crate) id: Url,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub(crate) kind: FollowType,
|
||||||
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
|
pub(crate) object: ObjectId<DbActor>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Activity for FollowActivity {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actor(&self) -> &Url {
|
||||||
|
self.actor.inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(&self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
let target_url = self.object.inner();
|
||||||
|
let target_domain = match (target_url.host_str(), target_url.port()) {
|
||||||
|
(Some(host), Some(port)) => format!("{}:{}", host, port),
|
||||||
|
(Some(host), None) => host.to_string(),
|
||||||
|
_ => {
|
||||||
|
return Err(Error::bad_request(anyhow::anyhow!(
|
||||||
|
"invalid follow target URL"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if target_domain != data.domain {
|
||||||
|
return Err(Error::bad_request(anyhow::anyhow!(
|
||||||
|
"follow target is not a local actor"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
let domain = self.actor().host_str().unwrap_or("");
|
||||||
|
if data.federation_repo.is_domain_blocked(domain).await? {
|
||||||
|
tracing::info!(actor = %self.actor(), "ignoring activity from blocked domain");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let _follower = self.actor.dereference(data).await?;
|
||||||
|
let local_actor = self.object.dereference(data).await?;
|
||||||
|
|
||||||
|
if data.federation_repo
|
||||||
|
.is_actor_blocked(local_actor.user_id, self.actor.inner().as_str())
|
||||||
|
.await?
|
||||||
|
{
|
||||||
|
tracing::info!(actor = %self.actor.inner(), "ignoring follow from blocked actor");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
data.federation_repo
|
||||||
|
.add_follower(
|
||||||
|
local_actor.user_id,
|
||||||
|
self.actor.inner().as_str(),
|
||||||
|
FollowerStatus::Pending,
|
||||||
|
self.id.as_str(),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
follower = %self.actor.inner(),
|
||||||
|
local_user = %local_actor.user_id,
|
||||||
|
"follow request pending approval"
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Accept ---
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct AcceptActivity {
|
||||||
|
pub(crate) id: Url,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub(crate) kind: AcceptType,
|
||||||
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
|
pub(crate) object: FollowActivity,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Activity for AcceptActivity {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actor(&self) -> &Url {
|
||||||
|
self.actor.inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
let domain = self.actor().host_str().unwrap_or("");
|
||||||
|
if data.federation_repo.is_domain_blocked(domain).await? {
|
||||||
|
tracing::info!(actor = %self.actor(), "ignoring activity from blocked domain");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let local_user_id = crate::urls::extract_user_id_from_url(self.object.actor.inner())
|
||||||
|
.ok_or_else(|| Error::bad_request(anyhow::anyhow!("invalid actor URL in Follow")))?;
|
||||||
|
data.federation_repo
|
||||||
|
.update_following_status(
|
||||||
|
local_user_id,
|
||||||
|
self.actor.inner().as_str(),
|
||||||
|
FollowingStatus::Accepted,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
tracing::info!(remote_actor = %self.actor.inner(), "follow accepted by remote");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Reject ---
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct RejectActivity {
|
||||||
|
pub(crate) id: Url,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub(crate) kind: RejectType,
|
||||||
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
|
pub(crate) object: FollowActivity,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Activity for RejectActivity {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actor(&self) -> &Url {
|
||||||
|
self.actor.inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
let domain = self.actor().host_str().unwrap_or("");
|
||||||
|
if data.federation_repo.is_domain_blocked(domain).await? {
|
||||||
|
tracing::info!(actor = %self.actor(), "ignoring activity from blocked domain");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if let Some(user_id) = crate::urls::extract_user_id_from_url(self.object.actor.inner()) {
|
||||||
|
data.federation_repo
|
||||||
|
.remove_following(user_id, self.actor.inner().as_str())
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
tracing::info!(actor = %self.actor.inner(), "follow rejected");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Undo ---
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct UndoActivity {
|
||||||
|
pub(crate) id: Url,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub(crate) kind: UndoType,
|
||||||
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
|
pub(crate) object: FollowActivity,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Activity for UndoActivity {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actor(&self) -> &Url {
|
||||||
|
self.actor.inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
let domain = self.actor().host_str().unwrap_or("");
|
||||||
|
if data.federation_repo.is_domain_blocked(domain).await? {
|
||||||
|
tracing::info!(actor = %self.actor(), "ignoring activity from blocked domain");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if let Some(user_id) = crate::urls::extract_user_id_from_url(self.object.object.inner()) {
|
||||||
|
data.federation_repo
|
||||||
|
.remove_follower(user_id, self.actor.inner().as_str())
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
data.object_handler
|
||||||
|
.on_actor_removed(self.actor.inner())
|
||||||
|
.await
|
||||||
|
.map_err(|e| Error::from(anyhow::anyhow!(e)))?;
|
||||||
|
tracing::info!(actor = %self.actor.inner(), "unfollowed");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Create ---
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct CreateActivity {
|
||||||
|
pub(crate) id: Url,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub(crate) kind: CreateType,
|
||||||
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
|
pub(crate) object: serde_json::Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Activity for CreateActivity {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actor(&self) -> &Url {
|
||||||
|
self.actor.inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
let domain = self.actor().host_str().unwrap_or("");
|
||||||
|
if data.federation_repo.is_domain_blocked(domain).await? {
|
||||||
|
tracing::info!(actor = %self.actor(), "ignoring activity from blocked domain");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let ap_id = self.id.clone();
|
||||||
|
let actor_url = self.actor.inner().clone();
|
||||||
|
data.object_handler
|
||||||
|
.on_create(&ap_id, &actor_url, self.object)
|
||||||
|
.await
|
||||||
|
.map_err(|e| Error::from(anyhow::anyhow!(e)))?;
|
||||||
|
tracing::info!(actor = %actor_url, "received create activity");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Delete ---
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct DeleteActivity {
|
||||||
|
pub(crate) id: Url,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub(crate) kind: DeleteType,
|
||||||
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
|
pub(crate) object: Url,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Activity for DeleteActivity {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actor(&self) -> &Url {
|
||||||
|
self.actor.inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
let domain = self.actor().host_str().unwrap_or("");
|
||||||
|
if data.federation_repo.is_domain_blocked(domain).await? {
|
||||||
|
tracing::info!(actor = %self.actor(), "ignoring activity from blocked domain");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let actor_url = self.actor.inner().clone();
|
||||||
|
data.object_handler
|
||||||
|
.on_delete(&self.object, &actor_url)
|
||||||
|
.await
|
||||||
|
.map_err(|e| Error::from(anyhow::anyhow!(e)))?;
|
||||||
|
tracing::info!(object = %self.object, "received delete activity");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Update ---
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct UpdateActivity {
|
||||||
|
pub(crate) id: Url,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub(crate) kind: UpdateType,
|
||||||
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
|
pub(crate) object: serde_json::Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Activity for UpdateActivity {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actor(&self) -> &Url {
|
||||||
|
self.actor.inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
let domain = self.actor().host_str().unwrap_or("");
|
||||||
|
if data.federation_repo.is_domain_blocked(domain).await? {
|
||||||
|
tracing::info!(actor = %self.actor(), "ignoring activity from blocked domain");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let ap_id = self.id.clone();
|
||||||
|
let actor_url = self.actor.inner().clone();
|
||||||
|
data.object_handler
|
||||||
|
.on_update(&ap_id, &actor_url, self.object)
|
||||||
|
.await
|
||||||
|
.map_err(|e| Error::from(anyhow::anyhow!(e)))?;
|
||||||
|
tracing::info!(actor = %actor_url, "received update activity");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Announce ---
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct AnnounceActivity {
|
||||||
|
pub(crate) id: Url,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub(crate) kind: AnnounceType,
|
||||||
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
|
pub(crate) object: Url,
|
||||||
|
pub(crate) published: Option<chrono::DateTime<chrono::Utc>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Activity for AnnounceActivity {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actor(&self) -> &Url {
|
||||||
|
self.actor.inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
let domain = self.actor().host_str().unwrap_or("");
|
||||||
|
if data.federation_repo.is_domain_blocked(domain).await? {
|
||||||
|
tracing::info!(actor = %self.actor(), "ignoring activity from blocked domain");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let object_domain = self.object.host_str().unwrap_or("");
|
||||||
|
if object_domain != data.domain {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
data.federation_repo
|
||||||
|
.add_announce(
|
||||||
|
self.id.as_str(),
|
||||||
|
self.object.as_str(),
|
||||||
|
self.actor.inner().as_str(),
|
||||||
|
self.published.unwrap_or_else(chrono::Utc::now),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
tracing::info!(actor = %self.actor.inner(), object = %self.object, "received announce");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Block ---
|
||||||
|
|
||||||
|
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
|
||||||
|
#[serde(rename = "Block")]
|
||||||
|
pub struct BlockType;
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct BlockActivity {
|
||||||
|
pub(crate) id: Url,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub(crate) kind: BlockType,
|
||||||
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
|
pub(crate) object: Url,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Activity for BlockActivity {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actor(&self) -> &Url {
|
||||||
|
self.actor.inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
let domain = self.actor().host_str().unwrap_or("");
|
||||||
|
if data.federation_repo.is_domain_blocked(domain).await? {
|
||||||
|
tracing::info!(actor = %self.actor(), "ignoring activity from blocked domain");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
// They blocked us — remove them from our following list
|
||||||
|
if let Some(local_user_id) = crate::urls::extract_user_id_from_url(&self.object) {
|
||||||
|
let _ = data
|
||||||
|
.federation_repo
|
||||||
|
.remove_following(local_user_id, self.actor.inner().as_str())
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
tracing::info!(actor = %self.actor.inner(), "received block");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Inbox dispatch enum ---
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(tag = "type")]
|
||||||
|
#[enum_delegate::implement(Activity)]
|
||||||
|
pub enum InboxActivities {
|
||||||
|
#[serde(rename = "Follow")]
|
||||||
|
Follow(FollowActivity),
|
||||||
|
#[serde(rename = "Accept")]
|
||||||
|
Accept(AcceptActivity),
|
||||||
|
#[serde(rename = "Reject")]
|
||||||
|
Reject(RejectActivity),
|
||||||
|
#[serde(rename = "Undo")]
|
||||||
|
Undo(UndoActivity),
|
||||||
|
#[serde(rename = "Create")]
|
||||||
|
Create(CreateActivity),
|
||||||
|
#[serde(rename = "Delete")]
|
||||||
|
Delete(DeleteActivity),
|
||||||
|
#[serde(rename = "Update")]
|
||||||
|
Update(UpdateActivity),
|
||||||
|
#[serde(rename = "Announce")]
|
||||||
|
Announce(AnnounceActivity),
|
||||||
|
#[serde(rename = "Block")]
|
||||||
|
Block(BlockActivity),
|
||||||
|
}
|
||||||
21
crates/adapters/activitypub-base/src/actor_handler.rs
Normal file
21
crates/adapters/activitypub-base/src/actor_handler.rs
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
use activitypub_federation::{
|
||||||
|
axum::json::FederationJson, config::Data, protocol::context::WithContext, traits::Object,
|
||||||
|
};
|
||||||
|
use axum::extract::Path;
|
||||||
|
|
||||||
|
use crate::actors::{Person, get_local_actor};
|
||||||
|
use crate::data::FederationData;
|
||||||
|
use crate::error::Error;
|
||||||
|
|
||||||
|
pub async fn actor_handler(
|
||||||
|
Path(user_id_str): Path<String>,
|
||||||
|
data: Data<FederationData>,
|
||||||
|
) -> Result<FederationJson<WithContext<Person>>, Error> {
|
||||||
|
let uuid = uuid::Uuid::parse_str(&user_id_str)
|
||||||
|
.map_err(|_| Error::bad_request(anyhow::anyhow!("invalid user id")))?;
|
||||||
|
|
||||||
|
let db_actor = get_local_actor(uuid, &data).await?;
|
||||||
|
let person = db_actor.into_json(&data).await?;
|
||||||
|
|
||||||
|
Ok(FederationJson(WithContext::new_default(person)))
|
||||||
|
}
|
||||||
300
crates/adapters/activitypub-base/src/actors.rs
Normal file
300
crates/adapters/activitypub-base/src/actors.rs
Normal file
@@ -0,0 +1,300 @@
|
|||||||
|
use activitypub_federation::{
|
||||||
|
config::Data,
|
||||||
|
fetch::object_id::ObjectId,
|
||||||
|
http_signatures::generate_actor_keypair,
|
||||||
|
kinds::actor::PersonType,
|
||||||
|
protocol::{public_key::PublicKey, verification::verify_domains_match},
|
||||||
|
traits::{Actor, Object},
|
||||||
|
};
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
use crate::data::FederationData;
|
||||||
|
use crate::error::Error;
|
||||||
|
use crate::repository::RemoteActor;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct DbActor {
|
||||||
|
pub user_id: uuid::Uuid,
|
||||||
|
pub username: String,
|
||||||
|
pub public_key_pem: String,
|
||||||
|
pub private_key_pem: Option<String>,
|
||||||
|
pub inbox_url: Url,
|
||||||
|
pub outbox_url: Url,
|
||||||
|
pub followers_url: Url,
|
||||||
|
pub following_url: Url,
|
||||||
|
pub ap_id: Url,
|
||||||
|
pub last_refreshed_at: DateTime<Utc>,
|
||||||
|
pub bio: Option<String>,
|
||||||
|
pub avatar_url: Option<Url>,
|
||||||
|
pub profile_url: Option<Url>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
|
pub struct ApImageObject {
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
pub kind: String,
|
||||||
|
pub url: Url,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct Person {
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
kind: PersonType,
|
||||||
|
id: ObjectId<DbActor>,
|
||||||
|
preferred_username: String,
|
||||||
|
inbox: Url,
|
||||||
|
outbox: Url,
|
||||||
|
followers: Url,
|
||||||
|
following: Url,
|
||||||
|
public_key: PublicKey,
|
||||||
|
name: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
summary: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
icon: Option<ApImageObject>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
url: Option<Url>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
discoverable: Option<bool>,
|
||||||
|
manually_approves_followers: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_local_actor(
|
||||||
|
user_id: uuid::Uuid,
|
||||||
|
data: &Data<FederationData>,
|
||||||
|
) -> Result<DbActor, Error> {
|
||||||
|
let user = data
|
||||||
|
.user_repo
|
||||||
|
.find_by_id(user_id)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)?
|
||||||
|
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found: {}", user_id)))?;
|
||||||
|
|
||||||
|
let (public_key, private_key) = match data
|
||||||
|
.federation_repo
|
||||||
|
.get_local_actor_keypair(user_id)
|
||||||
|
.await?
|
||||||
|
{
|
||||||
|
Some(kp) => kp,
|
||||||
|
None => {
|
||||||
|
let kp = generate_actor_keypair()?;
|
||||||
|
data.federation_repo
|
||||||
|
.save_local_actor_keypair(user_id, kp.public_key.clone(), kp.private_key.clone())
|
||||||
|
.await?;
|
||||||
|
(kp.public_key, kp.private_key)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let ap_id = crate::urls::actor_url(&data.base_url, user_id);
|
||||||
|
let inbox_url = Url::parse(&format!("{}/inbox", &ap_id)).expect("valid inbox url");
|
||||||
|
let outbox_url = Url::parse(&format!("{}/outbox", &ap_id)).expect("valid outbox url");
|
||||||
|
let followers_url = Url::parse(&format!("{}/followers", &ap_id)).expect("valid followers url");
|
||||||
|
let following_url = Url::parse(&format!("{}/following", &ap_id)).expect("valid following url");
|
||||||
|
|
||||||
|
Ok(DbActor {
|
||||||
|
user_id,
|
||||||
|
username: user.username,
|
||||||
|
public_key_pem: public_key,
|
||||||
|
private_key_pem: Some(private_key),
|
||||||
|
inbox_url,
|
||||||
|
outbox_url,
|
||||||
|
followers_url,
|
||||||
|
following_url,
|
||||||
|
ap_id,
|
||||||
|
last_refreshed_at: Utc::now(),
|
||||||
|
bio: user.bio,
|
||||||
|
avatar_url: user.avatar_url,
|
||||||
|
profile_url: user.profile_url,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Object for DbActor {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Kind = Person;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.ap_id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn last_refreshed_at(&self) -> Option<DateTime<Utc>> {
|
||||||
|
Some(self.last_refreshed_at)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn read_from_id(
|
||||||
|
object_id: Url,
|
||||||
|
data: &Data<Self::DataType>,
|
||||||
|
) -> Result<Option<Self>, Self::Error> {
|
||||||
|
let user_id = match crate::urls::extract_user_id_from_url(&object_id) {
|
||||||
|
Some(id) => id,
|
||||||
|
None => return Ok(None),
|
||||||
|
};
|
||||||
|
let user = match data.user_repo.find_by_id(user_id).await {
|
||||||
|
Ok(Some(u)) => u,
|
||||||
|
_ => return Ok(None),
|
||||||
|
};
|
||||||
|
|
||||||
|
let keypair = data
|
||||||
|
.federation_repo
|
||||||
|
.get_local_actor_keypair(user_id)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let (public_key, private_key) = match keypair {
|
||||||
|
Some(kp) => (kp.0, Some(kp.1)),
|
||||||
|
None => return Ok(None),
|
||||||
|
};
|
||||||
|
|
||||||
|
let ap_id = crate::urls::actor_url(&data.base_url, user_id);
|
||||||
|
let inbox_url = Url::parse(&format!("{}/inbox", &ap_id)).expect("valid url");
|
||||||
|
let outbox_url = Url::parse(&format!("{}/outbox", &ap_id)).expect("valid url");
|
||||||
|
let followers_url = Url::parse(&format!("{}/followers", &ap_id)).expect("valid url");
|
||||||
|
let following_url = Url::parse(&format!("{}/following", &ap_id)).expect("valid url");
|
||||||
|
|
||||||
|
Ok(Some(DbActor {
|
||||||
|
user_id,
|
||||||
|
username: user.username,
|
||||||
|
public_key_pem: public_key,
|
||||||
|
private_key_pem: private_key,
|
||||||
|
inbox_url,
|
||||||
|
outbox_url,
|
||||||
|
followers_url,
|
||||||
|
following_url,
|
||||||
|
ap_id,
|
||||||
|
last_refreshed_at: Utc::now(),
|
||||||
|
bio: None,
|
||||||
|
avatar_url: None,
|
||||||
|
profile_url: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn into_json(self, data: &Data<Self::DataType>) -> Result<Self::Kind, Self::Error> {
|
||||||
|
let public_key = PublicKey {
|
||||||
|
id: format!("{}#main-key", &self.ap_id),
|
||||||
|
owner: self.ap_id.clone(),
|
||||||
|
public_key_pem: self.public_key_pem.clone(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let icon = self.avatar_url.map(|url| ApImageObject {
|
||||||
|
kind: "Image".to_string(),
|
||||||
|
url,
|
||||||
|
});
|
||||||
|
let profile_url = self.profile_url;
|
||||||
|
|
||||||
|
Ok(Person {
|
||||||
|
kind: Default::default(),
|
||||||
|
id: self.ap_id.clone().into(),
|
||||||
|
preferred_username: self.username.clone(),
|
||||||
|
inbox: self.inbox_url.clone(),
|
||||||
|
outbox: self.outbox_url.clone(),
|
||||||
|
followers: self.followers_url.clone(),
|
||||||
|
following: self.following_url.clone(),
|
||||||
|
public_key,
|
||||||
|
name: Some(self.username.clone()),
|
||||||
|
summary: self.bio.clone(),
|
||||||
|
icon,
|
||||||
|
url: profile_url,
|
||||||
|
discoverable: Some(true),
|
||||||
|
manually_approves_followers: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(
|
||||||
|
json: &Self::Kind,
|
||||||
|
expected_domain: &Url,
|
||||||
|
_data: &Data<Self::DataType>,
|
||||||
|
) -> Result<(), Self::Error> {
|
||||||
|
verify_domains_match(json.id.inner(), expected_domain)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn from_json(json: Self::Kind, data: &Data<Self::DataType>) -> Result<Self, Self::Error> {
|
||||||
|
let actor = RemoteActor {
|
||||||
|
url: json.id.inner().to_string(),
|
||||||
|
handle: json.preferred_username.clone(),
|
||||||
|
inbox_url: json.inbox.to_string(),
|
||||||
|
shared_inbox_url: None,
|
||||||
|
display_name: json.name.clone(),
|
||||||
|
avatar_url: json.icon.as_ref().map(|i| i.url.to_string()),
|
||||||
|
};
|
||||||
|
data.federation_repo.upsert_remote_actor(actor).await?;
|
||||||
|
|
||||||
|
let url_str = json.id.inner().to_string();
|
||||||
|
let user_id = uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_URL, url_str.as_bytes());
|
||||||
|
let ap_id = json.id.inner().clone();
|
||||||
|
let inbox_url = json.inbox.clone();
|
||||||
|
let outbox_url = json.outbox.clone();
|
||||||
|
let followers_url = json.followers.clone();
|
||||||
|
let following_url = json.following.clone();
|
||||||
|
|
||||||
|
Ok(DbActor {
|
||||||
|
user_id,
|
||||||
|
username: json.preferred_username.clone(),
|
||||||
|
public_key_pem: json.public_key.public_key_pem,
|
||||||
|
private_key_pem: None,
|
||||||
|
inbox_url,
|
||||||
|
outbox_url,
|
||||||
|
followers_url,
|
||||||
|
following_url,
|
||||||
|
ap_id,
|
||||||
|
last_refreshed_at: Utc::now(),
|
||||||
|
bio: None,
|
||||||
|
avatar_url: None,
|
||||||
|
profile_url: None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Actor for DbActor {
|
||||||
|
fn public_key_pem(&self) -> &str {
|
||||||
|
&self.public_key_pem
|
||||||
|
}
|
||||||
|
|
||||||
|
fn private_key_pem(&self) -> Option<String> {
|
||||||
|
self.private_key_pem.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn inbox(&self) -> Url {
|
||||||
|
self.inbox_url.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn person_serializes_with_enriched_fields() {
|
||||||
|
let person = Person {
|
||||||
|
kind: Default::default(),
|
||||||
|
id: "https://example.com/users/1".parse::<url::Url>().unwrap().into(),
|
||||||
|
preferred_username: "alice".to_string(),
|
||||||
|
inbox: "https://example.com/users/1/inbox".parse().unwrap(),
|
||||||
|
outbox: "https://example.com/users/1/outbox".parse().unwrap(),
|
||||||
|
followers: "https://example.com/users/1/followers".parse().unwrap(),
|
||||||
|
following: "https://example.com/users/1/following".parse().unwrap(),
|
||||||
|
public_key: PublicKey {
|
||||||
|
id: "https://example.com/users/1#main-key".to_string(),
|
||||||
|
owner: "https://example.com/users/1".parse().unwrap(),
|
||||||
|
public_key_pem: "pem".to_string(),
|
||||||
|
},
|
||||||
|
name: Some("Alice".to_string()),
|
||||||
|
summary: Some("Bio text".to_string()),
|
||||||
|
icon: Some(ApImageObject {
|
||||||
|
kind: "Image".to_string(),
|
||||||
|
url: "https://example.com/images/avatars/1".parse().unwrap(),
|
||||||
|
}),
|
||||||
|
url: Some("https://example.com/u/alice".parse().unwrap()),
|
||||||
|
discoverable: Some(true),
|
||||||
|
manually_approves_followers: false,
|
||||||
|
};
|
||||||
|
let json = serde_json::to_value(&person).unwrap();
|
||||||
|
assert_eq!(json["discoverable"], true);
|
||||||
|
assert_eq!(json["summary"], "Bio text");
|
||||||
|
assert_eq!(json["icon"]["type"], "Image");
|
||||||
|
assert!(json.get("manuallyApprovesFollowers").is_some());
|
||||||
|
}
|
||||||
|
}
|
||||||
47
crates/adapters/activitypub-base/src/content.rs
Normal file
47
crates/adapters/activitypub-base/src/content.rs
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
use async_trait::async_trait;
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
pub trait ApObjectHandler: Send + Sync {
|
||||||
|
/// Returns (ap_id, serialized object) for all local content owned by this user.
|
||||||
|
/// Used by outbox (count) and backfill (delivery). Must only return locally-authored content.
|
||||||
|
async fn get_local_objects_for_user(
|
||||||
|
&self,
|
||||||
|
user_id: uuid::Uuid,
|
||||||
|
) -> anyhow::Result<Vec<(Url, serde_json::Value)>>;
|
||||||
|
|
||||||
|
/// Returns up to `limit` objects ordered newest-first, published before `before`.
|
||||||
|
/// Returns (ap_id, object_json, published_at).
|
||||||
|
async fn get_local_objects_page(
|
||||||
|
&self,
|
||||||
|
user_id: uuid::Uuid,
|
||||||
|
before: Option<DateTime<Utc>>,
|
||||||
|
limit: usize,
|
||||||
|
) -> anyhow::Result<Vec<(Url, serde_json::Value, DateTime<Utc>)>>;
|
||||||
|
|
||||||
|
/// Incoming Create activity — persist remote content.
|
||||||
|
async fn on_create(
|
||||||
|
&self,
|
||||||
|
ap_id: &Url,
|
||||||
|
actor_url: &Url,
|
||||||
|
object: serde_json::Value,
|
||||||
|
) -> anyhow::Result<()>;
|
||||||
|
|
||||||
|
/// Incoming Update activity — update existing remote content.
|
||||||
|
async fn on_update(
|
||||||
|
&self,
|
||||||
|
ap_id: &Url,
|
||||||
|
actor_url: &Url,
|
||||||
|
object: serde_json::Value,
|
||||||
|
) -> anyhow::Result<()>;
|
||||||
|
|
||||||
|
/// Incoming Delete activity — remove specific remote content.
|
||||||
|
async fn on_delete(&self, ap_id: &Url, actor_url: &Url) -> anyhow::Result<()>;
|
||||||
|
|
||||||
|
/// Actor unfollowed/was removed — clean up all their remote content.
|
||||||
|
async fn on_actor_removed(&self, actor_url: &Url) -> anyhow::Result<()>;
|
||||||
|
|
||||||
|
/// Total number of locally-authored posts across all users.
|
||||||
|
async fn count_local_posts(&self) -> anyhow::Result<u64>;
|
||||||
|
}
|
||||||
44
crates/adapters/activitypub-base/src/data.rs
Normal file
44
crates/adapters/activitypub-base/src/data.rs
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use crate::content::ApObjectHandler;
|
||||||
|
use crate::repository::FederationRepository;
|
||||||
|
use crate::user::ApUserRepository;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct FederationData {
|
||||||
|
pub(crate) federation_repo: Arc<dyn FederationRepository>,
|
||||||
|
pub(crate) user_repo: Arc<dyn ApUserRepository>,
|
||||||
|
pub(crate) object_handler: Arc<dyn ApObjectHandler>,
|
||||||
|
pub(crate) base_url: String,
|
||||||
|
pub(crate) domain: String,
|
||||||
|
pub(crate) allow_registration: bool,
|
||||||
|
pub(crate) software_name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FederationData {
|
||||||
|
pub fn new(
|
||||||
|
federation_repo: Arc<dyn FederationRepository>,
|
||||||
|
user_repo: Arc<dyn ApUserRepository>,
|
||||||
|
object_handler: Arc<dyn ApObjectHandler>,
|
||||||
|
base_url: String,
|
||||||
|
allow_registration: bool,
|
||||||
|
software_name: String,
|
||||||
|
) -> Self {
|
||||||
|
let domain = base_url
|
||||||
|
.trim_start_matches("https://")
|
||||||
|
.trim_start_matches("http://")
|
||||||
|
.split('/')
|
||||||
|
.next()
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_string();
|
||||||
|
Self {
|
||||||
|
federation_repo,
|
||||||
|
user_repo,
|
||||||
|
object_handler,
|
||||||
|
base_url,
|
||||||
|
domain,
|
||||||
|
allow_registration,
|
||||||
|
software_name,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
48
crates/adapters/activitypub-base/src/error.rs
Normal file
48
crates/adapters/activitypub-base/src/error.rs
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
use std::fmt::{Display, Formatter};
|
||||||
|
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Error(pub(crate) anyhow::Error, pub(crate) StatusCode);
|
||||||
|
|
||||||
|
impl Error {
|
||||||
|
pub fn not_found(e: impl Into<anyhow::Error>) -> Self {
|
||||||
|
Self(e.into(), StatusCode::NOT_FOUND)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn bad_request(e: impl Into<anyhow::Error>) -> Self {
|
||||||
|
Self(e.into(), StatusCode::BAD_REQUEST)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for Error {
|
||||||
|
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||||
|
std::fmt::Display::fmt(&self.0, f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> From<T> for Error
|
||||||
|
where
|
||||||
|
T: Into<anyhow::Error>,
|
||||||
|
{
|
||||||
|
fn from(t: T) -> Self {
|
||||||
|
Error(t.into(), StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl axum::response::IntoResponse for Error {
|
||||||
|
fn into_response(self) -> axum::response::Response {
|
||||||
|
let status = self.1;
|
||||||
|
if status.is_server_error() {
|
||||||
|
tracing::error!(error = %self.0, status = status.as_u16(), "federation error");
|
||||||
|
} else {
|
||||||
|
tracing::debug!(error = %self.0, status = status.as_u16(), "federation response");
|
||||||
|
}
|
||||||
|
let body = if status.is_server_error() {
|
||||||
|
"internal server error".to_string()
|
||||||
|
} else {
|
||||||
|
self.0.to_string()
|
||||||
|
};
|
||||||
|
(status, body).into_response()
|
||||||
|
}
|
||||||
|
}
|
||||||
50
crates/adapters/activitypub-base/src/federation.rs
Normal file
50
crates/adapters/activitypub-base/src/federation.rs
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
use activitypub_federation::config::{Data, FederationConfig, FederationMiddleware, UrlVerifier};
|
||||||
|
use activitypub_federation::error::Error as FedError;
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
use crate::data::FederationData;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct PermissiveVerifier;
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl UrlVerifier for PermissiveVerifier {
|
||||||
|
async fn verify(&self, _url: &Url) -> Result<(), FedError> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct ApFederationConfig(pub FederationConfig<FederationData>);
|
||||||
|
|
||||||
|
impl ApFederationConfig {
|
||||||
|
pub async fn new(data: FederationData, debug: bool) -> anyhow::Result<Self> {
|
||||||
|
let config = if debug {
|
||||||
|
FederationConfig::builder()
|
||||||
|
.domain(&data.domain)
|
||||||
|
.app_data(data)
|
||||||
|
.debug(true)
|
||||||
|
.http_signature_compat(true)
|
||||||
|
.url_verifier(Box::new(PermissiveVerifier))
|
||||||
|
.build()
|
||||||
|
.await?
|
||||||
|
} else {
|
||||||
|
FederationConfig::builder()
|
||||||
|
.domain(&data.domain)
|
||||||
|
.app_data(data)
|
||||||
|
.debug(false)
|
||||||
|
.http_signature_compat(true)
|
||||||
|
.build()
|
||||||
|
.await?
|
||||||
|
};
|
||||||
|
Ok(Self(config))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_request_data(&self) -> Data<FederationData> {
|
||||||
|
self.0.to_request_data()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn middleware(&self) -> FederationMiddleware<FederationData> {
|
||||||
|
FederationMiddleware::new(self.0.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
71
crates/adapters/activitypub-base/src/followers_handler.rs
Normal file
71
crates/adapters/activitypub-base/src/followers_handler.rs
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
use activitypub_federation::{axum::json::FederationJson, config::Data};
|
||||||
|
use axum::extract::Path;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
use crate::data::FederationData;
|
||||||
|
use crate::error::Error;
|
||||||
|
use crate::repository::FollowerStatus;
|
||||||
|
|
||||||
|
fn ordered_collection(id: String, total: usize, items: Vec<String>) -> serde_json::Value {
|
||||||
|
json!({
|
||||||
|
"@context": "https://www.w3.org/ns/activitystreams",
|
||||||
|
"type": "OrderedCollection",
|
||||||
|
"id": id,
|
||||||
|
"totalItems": total,
|
||||||
|
"orderedItems": items,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn followers_handler(
|
||||||
|
Path(user_id_str): Path<String>,
|
||||||
|
data: Data<FederationData>,
|
||||||
|
) -> Result<FederationJson<serde_json::Value>, Error> {
|
||||||
|
let user_id = uuid::Uuid::parse_str(&user_id_str)
|
||||||
|
.map_err(|_| Error::bad_request(anyhow::anyhow!("invalid user id")))?;
|
||||||
|
|
||||||
|
data.user_repo
|
||||||
|
.find_by_id(user_id)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)?
|
||||||
|
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found")))?;
|
||||||
|
|
||||||
|
let followers = data
|
||||||
|
.federation_repo
|
||||||
|
.get_followers(user_id)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)?;
|
||||||
|
|
||||||
|
let items: Vec<String> = followers
|
||||||
|
.into_iter()
|
||||||
|
.filter(|f| f.status == FollowerStatus::Accepted)
|
||||||
|
.map(|f| f.actor.url)
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let id = format!("{}/users/{}/followers", data.base_url, user_id_str);
|
||||||
|
Ok(FederationJson(ordered_collection(id, items.len(), items)))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn following_handler(
|
||||||
|
Path(user_id_str): Path<String>,
|
||||||
|
data: Data<FederationData>,
|
||||||
|
) -> Result<FederationJson<serde_json::Value>, Error> {
|
||||||
|
let user_id = uuid::Uuid::parse_str(&user_id_str)
|
||||||
|
.map_err(|_| Error::bad_request(anyhow::anyhow!("invalid user id")))?;
|
||||||
|
|
||||||
|
data.user_repo
|
||||||
|
.find_by_id(user_id)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)?
|
||||||
|
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found")))?;
|
||||||
|
|
||||||
|
let following = data
|
||||||
|
.federation_repo
|
||||||
|
.get_following(user_id)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)?;
|
||||||
|
|
||||||
|
let items: Vec<String> = following.into_iter().map(|a| a.url).collect();
|
||||||
|
|
||||||
|
let id = format!("{}/users/{}/following", data.base_url, user_id_str);
|
||||||
|
Ok(FederationJson(ordered_collection(id, items.len(), items)))
|
||||||
|
}
|
||||||
18
crates/adapters/activitypub-base/src/inbox.rs
Normal file
18
crates/adapters/activitypub-base/src/inbox.rs
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
use activitypub_federation::{
|
||||||
|
axum::inbox::{ActivityData, receive_activity},
|
||||||
|
config::Data,
|
||||||
|
protocol::context::WithContext,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::activities::InboxActivities;
|
||||||
|
use crate::actors::DbActor;
|
||||||
|
use crate::data::FederationData;
|
||||||
|
use crate::error::Error;
|
||||||
|
|
||||||
|
pub async fn inbox_handler(
|
||||||
|
data: Data<FederationData>,
|
||||||
|
activity_data: ActivityData,
|
||||||
|
) -> Result<(), Error> {
|
||||||
|
receive_activity::<WithContext<InboxActivities>, DbActor, FederationData>(activity_data, &data)
|
||||||
|
.await
|
||||||
|
}
|
||||||
26
crates/adapters/activitypub-base/src/lib.rs
Normal file
26
crates/adapters/activitypub-base/src/lib.rs
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
pub mod activities;
|
||||||
|
pub mod actor_handler;
|
||||||
|
pub mod actors;
|
||||||
|
pub mod content;
|
||||||
|
pub mod data;
|
||||||
|
pub mod error;
|
||||||
|
pub mod federation;
|
||||||
|
pub mod followers_handler;
|
||||||
|
pub mod inbox;
|
||||||
|
pub mod nodeinfo;
|
||||||
|
pub mod outbox;
|
||||||
|
pub mod repository;
|
||||||
|
pub mod service;
|
||||||
|
pub(crate) mod urls;
|
||||||
|
pub mod user;
|
||||||
|
pub mod webfinger;
|
||||||
|
|
||||||
|
pub use content::ApObjectHandler;
|
||||||
|
pub use data::FederationData;
|
||||||
|
pub use error::Error;
|
||||||
|
pub use federation::ApFederationConfig;
|
||||||
|
pub use repository::{
|
||||||
|
BlockedDomain, FederationRepository, Follower, FollowerStatus, FollowingStatus, RemoteActor,
|
||||||
|
};
|
||||||
|
pub use service::ActivityPubService;
|
||||||
|
pub use user::{ApUser, ApUserRepository};
|
||||||
119
crates/adapters/activitypub-base/src/nodeinfo.rs
Normal file
119
crates/adapters/activitypub-base/src/nodeinfo.rs
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
use activitypub_federation::config::Data;
|
||||||
|
use axum::Json;
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
use crate::data::FederationData;
|
||||||
|
use crate::error::Error;
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct NodeInfoWellKnown {
|
||||||
|
pub links: Vec<NodeInfoLink>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct NodeInfoLink {
|
||||||
|
pub rel: String,
|
||||||
|
pub href: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct NodeInfoSoftware {
|
||||||
|
pub name: String,
|
||||||
|
pub version: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct NodeInfoUsage {
|
||||||
|
pub users: NodeInfoUsers,
|
||||||
|
pub local_posts: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct NodeInfoUsers {
|
||||||
|
pub total: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct NodeInfo {
|
||||||
|
pub version: String,
|
||||||
|
pub software: NodeInfoSoftware,
|
||||||
|
pub protocols: Vec<String>,
|
||||||
|
pub usage: NodeInfoUsage,
|
||||||
|
pub open_registrations: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn nodeinfo_well_known_handler(
|
||||||
|
data: Data<FederationData>,
|
||||||
|
) -> Result<Json<NodeInfoWellKnown>, Error> {
|
||||||
|
let href = format!("{}/nodeinfo/2.0", data.base_url);
|
||||||
|
Ok(Json(NodeInfoWellKnown {
|
||||||
|
links: vec![NodeInfoLink {
|
||||||
|
rel: "http://nodeinfo.diaspora.software/ns/schema/2.0".to_string(),
|
||||||
|
href,
|
||||||
|
}],
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn nodeinfo_handler(
|
||||||
|
data: Data<FederationData>,
|
||||||
|
) -> Result<Json<NodeInfo>, Error> {
|
||||||
|
let user_count = data.user_repo.count_users().await.unwrap_or(0);
|
||||||
|
let local_posts = data.object_handler.count_local_posts().await.unwrap_or(0);
|
||||||
|
|
||||||
|
Ok(Json(NodeInfo {
|
||||||
|
version: "2.0".to_string(),
|
||||||
|
software: NodeInfoSoftware {
|
||||||
|
name: data.software_name.clone(),
|
||||||
|
version: env!("CARGO_PKG_VERSION").to_string(),
|
||||||
|
},
|
||||||
|
protocols: vec!["activitypub".to_string()],
|
||||||
|
usage: NodeInfoUsage {
|
||||||
|
users: NodeInfoUsers { total: user_count },
|
||||||
|
local_posts,
|
||||||
|
},
|
||||||
|
open_registrations: data.allow_registration,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn nodeinfo_well_known_serializes_correctly() {
|
||||||
|
let doc = NodeInfoWellKnown {
|
||||||
|
links: vec![NodeInfoLink {
|
||||||
|
rel: "http://nodeinfo.diaspora.software/ns/schema/2.0".to_string(),
|
||||||
|
href: "https://example.com/nodeinfo/2.0".to_string(),
|
||||||
|
}],
|
||||||
|
};
|
||||||
|
let json = serde_json::to_value(&doc).unwrap();
|
||||||
|
assert_eq!(json["links"][0]["rel"], "http://nodeinfo.diaspora.software/ns/schema/2.0");
|
||||||
|
assert_eq!(json["links"][0]["href"], "https://example.com/nodeinfo/2.0");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn nodeinfo_serializes_camel_case() {
|
||||||
|
let doc = NodeInfo {
|
||||||
|
version: "2.0".to_string(),
|
||||||
|
software: NodeInfoSoftware {
|
||||||
|
name: "my-app".to_string(),
|
||||||
|
version: "0.1.0".to_string(),
|
||||||
|
},
|
||||||
|
protocols: vec!["activitypub".to_string()],
|
||||||
|
usage: NodeInfoUsage {
|
||||||
|
users: NodeInfoUsers { total: 3 },
|
||||||
|
local_posts: 42,
|
||||||
|
},
|
||||||
|
open_registrations: false,
|
||||||
|
};
|
||||||
|
let json = serde_json::to_value(&doc).unwrap();
|
||||||
|
assert_eq!(json["version"], "2.0");
|
||||||
|
assert_eq!(json["software"]["name"], "my-app");
|
||||||
|
assert_eq!(json["usage"]["users"]["total"], 3);
|
||||||
|
assert_eq!(json["usage"]["localPosts"], 42);
|
||||||
|
assert_eq!(json["openRegistrations"], false);
|
||||||
|
}
|
||||||
|
}
|
||||||
135
crates/adapters/activitypub-base/src/outbox.rs
Normal file
135
crates/adapters/activitypub-base/src/outbox.rs
Normal file
@@ -0,0 +1,135 @@
|
|||||||
|
use axum::extract::{Path, Query};
|
||||||
|
use axum::response::IntoResponse;
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
use activitypub_federation::{config::Data, fetch::object_id::ObjectId, kinds::activity::CreateType};
|
||||||
|
|
||||||
|
use crate::{activities::CreateActivity, data::FederationData, error::Error};
|
||||||
|
|
||||||
|
const PAGE_SIZE: usize = 20;
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct OutboxQuery {
|
||||||
|
page: Option<bool>,
|
||||||
|
before: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct OrderedCollection {
|
||||||
|
#[serde(rename = "@context")]
|
||||||
|
context: String,
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
kind: String,
|
||||||
|
id: String,
|
||||||
|
total_items: u64,
|
||||||
|
first: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct OrderedCollectionPage {
|
||||||
|
#[serde(rename = "@context")]
|
||||||
|
context: String,
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
kind: String,
|
||||||
|
id: String,
|
||||||
|
part_of: String,
|
||||||
|
ordered_items: Vec<serde_json::Value>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
next: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn outbox_handler(
|
||||||
|
Path(user_id_str): Path<String>,
|
||||||
|
Query(query): Query<OutboxQuery>,
|
||||||
|
data: Data<FederationData>,
|
||||||
|
) -> Result<axum::response::Response, Error> {
|
||||||
|
let uuid = uuid::Uuid::parse_str(&user_id_str)
|
||||||
|
.map_err(|_| Error::bad_request(anyhow::anyhow!("invalid user id")))?;
|
||||||
|
|
||||||
|
data.user_repo
|
||||||
|
.find_by_id(uuid)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)?
|
||||||
|
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found")))?;
|
||||||
|
|
||||||
|
let outbox_url = format!("{}/users/{}/outbox", data.base_url, user_id_str);
|
||||||
|
|
||||||
|
if query.page.unwrap_or(false) {
|
||||||
|
let before: Option<DateTime<Utc>> = query.before.as_deref().and_then(|s| s.parse().ok());
|
||||||
|
|
||||||
|
let items = data
|
||||||
|
.object_handler
|
||||||
|
.get_local_objects_page(uuid, before, PAGE_SIZE)
|
||||||
|
.await
|
||||||
|
.map_err(|e| Error::from(anyhow::anyhow!("{}", e)))?;
|
||||||
|
|
||||||
|
let actor_url: Url = format!("{}/users/{}", data.base_url, user_id_str)
|
||||||
|
.parse()
|
||||||
|
.expect("valid url");
|
||||||
|
|
||||||
|
let has_more = items.len() == PAGE_SIZE;
|
||||||
|
let oldest_ts = items.last().map(|(_, _, ts)| *ts);
|
||||||
|
|
||||||
|
let ordered_items: Vec<serde_json::Value> = items
|
||||||
|
.into_iter()
|
||||||
|
.map(|(ap_id, object, _)| {
|
||||||
|
let create_id =
|
||||||
|
Url::parse(&format!("{}/activity", ap_id)).expect("valid url");
|
||||||
|
serde_json::to_value(CreateActivity {
|
||||||
|
id: create_id,
|
||||||
|
kind: CreateType::default(),
|
||||||
|
actor: ObjectId::from(actor_url.clone()),
|
||||||
|
object,
|
||||||
|
})
|
||||||
|
.expect("serializable")
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let page_id = match &query.before {
|
||||||
|
Some(b) => format!("{}?page=true&before={}", outbox_url, b),
|
||||||
|
None => format!("{}?page=true", outbox_url),
|
||||||
|
};
|
||||||
|
|
||||||
|
let next = if has_more {
|
||||||
|
oldest_ts.map(|ts| {
|
||||||
|
// Use RFC 3339 with Z suffix (no + sign) to avoid percent-encoding
|
||||||
|
let ts_str = ts
|
||||||
|
.format("%Y-%m-%dT%H:%M:%S%.3fZ")
|
||||||
|
.to_string();
|
||||||
|
format!("{}?page=true&before={}", outbox_url, ts_str)
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(axum::Json(OrderedCollectionPage {
|
||||||
|
context: "https://www.w3.org/ns/activitystreams".to_string(),
|
||||||
|
kind: "OrderedCollectionPage".to_string(),
|
||||||
|
id: page_id,
|
||||||
|
part_of: outbox_url,
|
||||||
|
ordered_items,
|
||||||
|
next,
|
||||||
|
})
|
||||||
|
.into_response())
|
||||||
|
} else {
|
||||||
|
let total = data
|
||||||
|
.object_handler
|
||||||
|
.get_local_objects_for_user(uuid)
|
||||||
|
.await
|
||||||
|
.map_err(|e| Error::from(anyhow::anyhow!("{}", e)))?
|
||||||
|
.len() as u64;
|
||||||
|
|
||||||
|
Ok(axum::Json(OrderedCollection {
|
||||||
|
context: "https://www.w3.org/ns/activitystreams".to_string(),
|
||||||
|
kind: "OrderedCollection".to_string(),
|
||||||
|
id: outbox_url.clone(),
|
||||||
|
total_items: total,
|
||||||
|
first: format!("{}?page=true", outbox_url),
|
||||||
|
})
|
||||||
|
.into_response())
|
||||||
|
}
|
||||||
|
}
|
||||||
115
crates/adapters/activitypub-base/src/repository.rs
Normal file
115
crates/adapters/activitypub-base/src/repository.rs
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
use anyhow::Result;
|
||||||
|
use async_trait::async_trait;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum FollowerStatus {
|
||||||
|
Pending,
|
||||||
|
Accepted,
|
||||||
|
Rejected,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum FollowingStatus {
|
||||||
|
Pending,
|
||||||
|
Accepted,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct RemoteActor {
|
||||||
|
pub url: String,
|
||||||
|
pub handle: String,
|
||||||
|
pub inbox_url: String,
|
||||||
|
pub shared_inbox_url: Option<String>,
|
||||||
|
pub display_name: Option<String>,
|
||||||
|
pub avatar_url: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Follower {
|
||||||
|
pub actor: RemoteActor,
|
||||||
|
pub status: FollowerStatus,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct BlockedDomain {
|
||||||
|
pub domain: String,
|
||||||
|
pub reason: Option<String>,
|
||||||
|
pub blocked_at: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
pub trait FederationRepository: Send + Sync {
|
||||||
|
async fn add_follower(
|
||||||
|
&self,
|
||||||
|
local_user_id: uuid::Uuid,
|
||||||
|
remote_actor_url: &str,
|
||||||
|
status: FollowerStatus,
|
||||||
|
follow_activity_id: &str,
|
||||||
|
) -> Result<()>;
|
||||||
|
async fn get_follower_follow_activity_id(
|
||||||
|
&self,
|
||||||
|
local_user_id: uuid::Uuid,
|
||||||
|
remote_actor_url: &str,
|
||||||
|
) -> Result<Option<String>>;
|
||||||
|
async fn remove_follower(
|
||||||
|
&self,
|
||||||
|
local_user_id: uuid::Uuid,
|
||||||
|
remote_actor_url: &str,
|
||||||
|
) -> Result<()>;
|
||||||
|
async fn get_followers(&self, local_user_id: uuid::Uuid) -> Result<Vec<Follower>>;
|
||||||
|
async fn update_follower_status(
|
||||||
|
&self,
|
||||||
|
local_user_id: uuid::Uuid,
|
||||||
|
remote_actor_url: &str,
|
||||||
|
status: FollowerStatus,
|
||||||
|
) -> Result<()>;
|
||||||
|
async fn add_following(
|
||||||
|
&self,
|
||||||
|
local_user_id: uuid::Uuid,
|
||||||
|
actor: RemoteActor,
|
||||||
|
follow_activity_id: &str,
|
||||||
|
) -> Result<()>;
|
||||||
|
async fn get_follow_activity_id(
|
||||||
|
&self,
|
||||||
|
local_user_id: uuid::Uuid,
|
||||||
|
remote_actor_url: &str,
|
||||||
|
) -> Result<Option<String>>;
|
||||||
|
async fn remove_following(&self, local_user_id: uuid::Uuid, actor_url: &str) -> Result<()>;
|
||||||
|
async fn get_following(&self, local_user_id: uuid::Uuid) -> Result<Vec<RemoteActor>>;
|
||||||
|
async fn count_following(&self, local_user_id: uuid::Uuid) -> Result<usize>;
|
||||||
|
async fn upsert_remote_actor(&self, actor: RemoteActor) -> Result<()>;
|
||||||
|
async fn get_remote_actor(&self, actor_url: &str) -> Result<Option<RemoteActor>>;
|
||||||
|
async fn get_local_actor_keypair(
|
||||||
|
&self,
|
||||||
|
user_id: uuid::Uuid,
|
||||||
|
) -> Result<Option<(String, String)>>;
|
||||||
|
async fn save_local_actor_keypair(
|
||||||
|
&self,
|
||||||
|
user_id: uuid::Uuid,
|
||||||
|
public_key: String,
|
||||||
|
private_key: String,
|
||||||
|
) -> Result<()>;
|
||||||
|
async fn get_pending_followers(&self, local_user_id: uuid::Uuid) -> Result<Vec<RemoteActor>>;
|
||||||
|
async fn update_following_status(
|
||||||
|
&self,
|
||||||
|
local_user_id: uuid::Uuid,
|
||||||
|
remote_actor_url: &str,
|
||||||
|
status: FollowingStatus,
|
||||||
|
) -> Result<()>;
|
||||||
|
async fn add_announce(
|
||||||
|
&self,
|
||||||
|
activity_id: &str,
|
||||||
|
object_url: &str,
|
||||||
|
actor_url: &str,
|
||||||
|
announced_at: chrono::DateTime<chrono::Utc>,
|
||||||
|
) -> Result<()>;
|
||||||
|
async fn count_announces(&self, object_url: &str) -> Result<usize>;
|
||||||
|
async fn add_blocked_domain(&self, domain: &str, reason: Option<&str>) -> Result<()>;
|
||||||
|
async fn remove_blocked_domain(&self, domain: &str) -> Result<()>;
|
||||||
|
async fn get_blocked_domains(&self) -> Result<Vec<BlockedDomain>>;
|
||||||
|
async fn is_domain_blocked(&self, domain: &str) -> Result<bool>;
|
||||||
|
async fn add_blocked_actor(&self, local_user_id: uuid::Uuid, actor_url: &str) -> Result<()>;
|
||||||
|
async fn remove_blocked_actor(&self, local_user_id: uuid::Uuid, actor_url: &str) -> Result<()>;
|
||||||
|
async fn get_blocked_actors(&self, local_user_id: uuid::Uuid) -> Result<Vec<String>>;
|
||||||
|
async fn is_actor_blocked(&self, local_user_id: uuid::Uuid, actor_url: &str) -> Result<bool>;
|
||||||
|
}
|
||||||
844
crates/adapters/activitypub-base/src/service.rs
Normal file
844
crates/adapters/activitypub-base/src/service.rs
Normal file
@@ -0,0 +1,844 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use activitypub_federation::{
|
||||||
|
activity_sending::SendActivityTask,
|
||||||
|
fetch::{object_id::ObjectId, webfinger::webfinger_resolve_actor},
|
||||||
|
protocol::context::WithContext,
|
||||||
|
traits::Actor,
|
||||||
|
};
|
||||||
|
use axum::{Router, routing::get, routing::post};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
activities::{AcceptActivity, CreateActivity, FollowActivity, RejectActivity, UndoActivity, UpdateActivity},
|
||||||
|
actors::{DbActor, get_local_actor},
|
||||||
|
content::ApObjectHandler,
|
||||||
|
data::FederationData,
|
||||||
|
federation::ApFederationConfig,
|
||||||
|
followers_handler::{followers_handler, following_handler},
|
||||||
|
inbox::inbox_handler,
|
||||||
|
outbox::outbox_handler,
|
||||||
|
repository::{BlockedDomain, FederationRepository, FollowerStatus, FollowingStatus, RemoteActor},
|
||||||
|
urls::activity_url,
|
||||||
|
user::ApUserRepository,
|
||||||
|
nodeinfo::{nodeinfo_handler, nodeinfo_well_known_handler},
|
||||||
|
webfinger::webfinger_handler,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn collect_inboxes(followers: &[crate::repository::Follower]) -> Vec<Url> {
|
||||||
|
let mut seen = std::collections::HashSet::new();
|
||||||
|
let mut inboxes = Vec::new();
|
||||||
|
for f in followers {
|
||||||
|
let inbox_str = f
|
||||||
|
.actor
|
||||||
|
.shared_inbox_url
|
||||||
|
.as_deref()
|
||||||
|
.unwrap_or(&f.actor.inbox_url);
|
||||||
|
if seen.insert(inbox_str.to_string()) {
|
||||||
|
if let Ok(url) = Url::parse(inbox_str) {
|
||||||
|
inboxes.push(url);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
inboxes
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn send_with_retry(
|
||||||
|
sends: Vec<SendActivityTask>,
|
||||||
|
data: &activitypub_federation::config::Data<FederationData>,
|
||||||
|
) -> Vec<anyhow::Error> {
|
||||||
|
let mut failures = vec![];
|
||||||
|
for send in sends {
|
||||||
|
let mut delay = std::time::Duration::from_secs(1);
|
||||||
|
for attempt in 1..=3u32 {
|
||||||
|
match send.clone().sign_and_send(data).await {
|
||||||
|
Ok(()) => break,
|
||||||
|
Err(e) if attempt < 3 => {
|
||||||
|
tracing::warn!(attempt, error = %e, "delivery failed, retrying");
|
||||||
|
tokio::time::sleep(delay).await;
|
||||||
|
delay *= 2;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!(attempt, error = %e, "delivery failed permanently");
|
||||||
|
failures.push(anyhow::anyhow!(e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
failures
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ActivityPubService {
|
||||||
|
federation_config: ApFederationConfig,
|
||||||
|
base_url: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActivityPubService {
|
||||||
|
pub async fn new(
|
||||||
|
repo: Arc<dyn FederationRepository>,
|
||||||
|
user_repo: Arc<dyn ApUserRepository>,
|
||||||
|
object_handler: Arc<dyn ApObjectHandler>,
|
||||||
|
base_url: String,
|
||||||
|
allow_registration: bool,
|
||||||
|
software_name: String,
|
||||||
|
debug: bool,
|
||||||
|
) -> anyhow::Result<Self> {
|
||||||
|
let data = FederationData::new(repo, user_repo, object_handler, base_url.clone(), allow_registration, software_name);
|
||||||
|
let federation_config = ApFederationConfig::new(data, debug).await?;
|
||||||
|
Ok(Self {
|
||||||
|
federation_config,
|
||||||
|
base_url,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn federation_config(&self) -> &ApFederationConfig {
|
||||||
|
&self.federation_config
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn request_data(&self) -> activitypub_federation::config::Data<FederationData> {
|
||||||
|
self.federation_config.to_request_data()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn actor_json(&self, user_id_str: &str) -> anyhow::Result<String> {
|
||||||
|
use activitypub_federation::traits::Object;
|
||||||
|
let uuid = uuid::Uuid::parse_str(user_id_str)?;
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
let actor = get_local_actor(uuid, &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
let person = actor
|
||||||
|
.into_json(&data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
Ok(serde_json::to_string(&WithContext::new_default(person))?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn router(&self) -> Router {
|
||||||
|
Router::new()
|
||||||
|
.route("/.well-known/nodeinfo", get(nodeinfo_well_known_handler))
|
||||||
|
.route("/nodeinfo/2.0", get(nodeinfo_handler))
|
||||||
|
.route("/.well-known/webfinger", get(webfinger_handler))
|
||||||
|
.route("/users/{id}/inbox", post(inbox_handler))
|
||||||
|
.route("/users/{id}/outbox", get(outbox_handler))
|
||||||
|
.route("/users/{id}/followers", get(followers_handler))
|
||||||
|
.route("/users/{id}/following", get(following_handler))
|
||||||
|
.layer(self.federation_config.middleware())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn follow(&self, local_user_id: uuid::Uuid, handle: &str) -> anyhow::Result<()> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
|
||||||
|
let normalized = handle.trim_start_matches('@');
|
||||||
|
let parts: Vec<&str> = normalized.splitn(2, '@').collect();
|
||||||
|
if parts.len() == 2 && parts[1] == data.domain {
|
||||||
|
return self.follow_local(local_user_id, parts[0], &data).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
let remote_actor: DbActor = webfinger_resolve_actor(handle, &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
|
let local_actor = get_local_actor(local_user_id, &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
|
let follow_id = activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
let follow_id_str = follow_id.to_string();
|
||||||
|
let follow = FollowActivity {
|
||||||
|
id: follow_id,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
object: ObjectId::from(remote_actor.ap_id.clone()),
|
||||||
|
};
|
||||||
|
let follow_with_ctx = WithContext::new_default(follow);
|
||||||
|
|
||||||
|
let sends = SendActivityTask::prepare(
|
||||||
|
&follow_with_ctx,
|
||||||
|
&local_actor,
|
||||||
|
vec![remote_actor.inbox()],
|
||||||
|
&data,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let failures = send_with_retry(sends, &data).await;
|
||||||
|
if !failures.is_empty() {
|
||||||
|
tracing::warn!(
|
||||||
|
count = failures.len(),
|
||||||
|
"some activity deliveries failed permanently"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let remote = RemoteActor {
|
||||||
|
url: remote_actor.ap_id.to_string(),
|
||||||
|
handle: remote_actor.username.clone(),
|
||||||
|
inbox_url: remote_actor.inbox_url.to_string(),
|
||||||
|
shared_inbox_url: None,
|
||||||
|
display_name: Some(remote_actor.username.clone()),
|
||||||
|
avatar_url: None,
|
||||||
|
};
|
||||||
|
data.federation_repo
|
||||||
|
.add_following(local_user_id, remote, &follow_id_str)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn unfollow(
|
||||||
|
&self,
|
||||||
|
local_user_id: uuid::Uuid,
|
||||||
|
actor_url_str: &str,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
|
||||||
|
if actor_url_str.starts_with(&self.base_url) {
|
||||||
|
return self
|
||||||
|
.unfollow_local(local_user_id, actor_url_str, &data)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
|
||||||
|
let remote = data
|
||||||
|
.federation_repo
|
||||||
|
.get_remote_actor(actor_url_str)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("remote actor not found: {}", actor_url_str))?;
|
||||||
|
|
||||||
|
let local_actor = get_local_actor(local_user_id, &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
|
let remote_ap_id = Url::parse(actor_url_str)?;
|
||||||
|
let inbox = Url::parse(&remote.inbox_url)?;
|
||||||
|
|
||||||
|
let follow_activity_id_str = data
|
||||||
|
.federation_repo
|
||||||
|
.get_follow_activity_id(local_user_id, actor_url_str)
|
||||||
|
.await?;
|
||||||
|
let follow_id = match follow_activity_id_str {
|
||||||
|
Some(id) => Url::parse(&id)?,
|
||||||
|
None => activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?,
|
||||||
|
};
|
||||||
|
let follow = FollowActivity {
|
||||||
|
id: follow_id,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
object: ObjectId::from(remote_ap_id),
|
||||||
|
};
|
||||||
|
|
||||||
|
let undo_id = activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
let undo = UndoActivity {
|
||||||
|
id: undo_id,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
object: follow,
|
||||||
|
};
|
||||||
|
|
||||||
|
let sends = SendActivityTask::prepare(
|
||||||
|
&WithContext::new_default(undo),
|
||||||
|
&local_actor,
|
||||||
|
vec![inbox],
|
||||||
|
&data,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let failures = send_with_retry(sends, &data).await;
|
||||||
|
if !failures.is_empty() {
|
||||||
|
tracing::warn!(
|
||||||
|
count = failures.len(),
|
||||||
|
"some activity deliveries failed permanently"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
data.federation_repo
|
||||||
|
.remove_following(local_user_id, actor_url_str)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
data.object_handler
|
||||||
|
.on_actor_removed(&Url::parse(actor_url_str)?)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn accept_follower(
|
||||||
|
&self,
|
||||||
|
local_user_id: uuid::Uuid,
|
||||||
|
remote_actor_url: &str,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
let local_actor = get_local_actor(local_user_id, &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
|
let remote_actor = data
|
||||||
|
.federation_repo
|
||||||
|
.get_remote_actor(remote_actor_url)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("remote actor not found"))?;
|
||||||
|
|
||||||
|
let follow_id_str = data
|
||||||
|
.federation_repo
|
||||||
|
.get_follower_follow_activity_id(local_user_id, remote_actor_url)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| {
|
||||||
|
anyhow::anyhow!("follow activity id not found for {}", remote_actor_url)
|
||||||
|
})?;
|
||||||
|
let follow_id = Url::parse(&follow_id_str)?;
|
||||||
|
let follow = FollowActivity {
|
||||||
|
id: follow_id,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(Url::parse(remote_actor_url)?),
|
||||||
|
object: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
};
|
||||||
|
let accept = AcceptActivity {
|
||||||
|
id: activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
object: follow,
|
||||||
|
};
|
||||||
|
|
||||||
|
data.federation_repo
|
||||||
|
.update_follower_status(local_user_id, remote_actor_url, FollowerStatus::Accepted)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let inbox = Url::parse(&remote_actor.inbox_url)?;
|
||||||
|
let sends = SendActivityTask::prepare(
|
||||||
|
&WithContext::new_default(accept),
|
||||||
|
&local_actor,
|
||||||
|
vec![inbox.clone()],
|
||||||
|
&data,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let failures = send_with_retry(sends, &data).await;
|
||||||
|
if !failures.is_empty() {
|
||||||
|
tracing::warn!(
|
||||||
|
"failed to deliver Accept activity, but follower is marked accepted locally"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let target_inbox = remote_actor
|
||||||
|
.shared_inbox_url
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_else(|| remote_actor.inbox_url.clone());
|
||||||
|
self.spawn_backfill(local_user_id, target_inbox);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn reject_follower(
|
||||||
|
&self,
|
||||||
|
local_user_id: uuid::Uuid,
|
||||||
|
remote_actor_url: &str,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
let local_actor = get_local_actor(local_user_id, &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
|
let remote_actor = data
|
||||||
|
.federation_repo
|
||||||
|
.get_remote_actor(remote_actor_url)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("remote actor not found"))?;
|
||||||
|
|
||||||
|
let follow_id = activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
let follow = FollowActivity {
|
||||||
|
id: follow_id,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(Url::parse(remote_actor_url)?),
|
||||||
|
object: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
};
|
||||||
|
let reject = RejectActivity {
|
||||||
|
id: activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
object: follow,
|
||||||
|
};
|
||||||
|
|
||||||
|
let inbox = Url::parse(&remote_actor.inbox_url)?;
|
||||||
|
let sends = SendActivityTask::prepare(
|
||||||
|
&WithContext::new_default(reject),
|
||||||
|
&local_actor,
|
||||||
|
vec![inbox],
|
||||||
|
&data,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let failures = send_with_retry(sends, &data).await;
|
||||||
|
if !failures.is_empty() {
|
||||||
|
tracing::warn!(
|
||||||
|
count = failures.len(),
|
||||||
|
"some activity deliveries failed permanently"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
data.federation_repo
|
||||||
|
.remove_follower(local_user_id, remote_actor_url)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_pending_followers(
|
||||||
|
&self,
|
||||||
|
local_user_id: uuid::Uuid,
|
||||||
|
) -> anyhow::Result<Vec<RemoteActor>> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
data.federation_repo
|
||||||
|
.get_pending_followers(local_user_id)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_accepted_followers(
|
||||||
|
&self,
|
||||||
|
local_user_id: uuid::Uuid,
|
||||||
|
) -> anyhow::Result<Vec<RemoteActor>> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
let followers = data.federation_repo.get_followers(local_user_id).await?;
|
||||||
|
Ok(followers
|
||||||
|
.into_iter()
|
||||||
|
.filter(|f| f.status == FollowerStatus::Accepted)
|
||||||
|
.map(|f| f.actor)
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn count_accepted_followers(
|
||||||
|
&self,
|
||||||
|
local_user_id: uuid::Uuid,
|
||||||
|
) -> anyhow::Result<usize> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
let followers = data.federation_repo.get_followers(local_user_id).await?;
|
||||||
|
Ok(followers
|
||||||
|
.into_iter()
|
||||||
|
.filter(|f| f.status == FollowerStatus::Accepted)
|
||||||
|
.count())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_following(
|
||||||
|
&self,
|
||||||
|
local_user_id: uuid::Uuid,
|
||||||
|
) -> anyhow::Result<Vec<RemoteActor>> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
data.federation_repo.get_following(local_user_id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn count_following(&self, local_user_id: uuid::Uuid) -> anyhow::Result<usize> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
data.federation_repo.count_following(local_user_id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn remove_follower(
|
||||||
|
&self,
|
||||||
|
local_user_id: uuid::Uuid,
|
||||||
|
actor_url: &str,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
data.federation_repo
|
||||||
|
.remove_follower(local_user_id, actor_url)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Broadcast a single object to all accepted followers as a Create activity.
|
||||||
|
/// Called by project-specific event handlers when new content is created.
|
||||||
|
pub async fn broadcast_to_followers(
|
||||||
|
&self,
|
||||||
|
local_user_id: uuid::Uuid,
|
||||||
|
ap_id: Url,
|
||||||
|
object: serde_json::Value,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
let local_actor = get_local_actor(local_user_id, &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
|
let followers = data.federation_repo.get_followers(local_user_id).await?;
|
||||||
|
let blocked = data
|
||||||
|
.federation_repo
|
||||||
|
.get_blocked_actors(local_user_id)
|
||||||
|
.await
|
||||||
|
.unwrap_or_default();
|
||||||
|
let blocked_set: std::collections::HashSet<String> = blocked.into_iter().collect();
|
||||||
|
let blocked_domains = data
|
||||||
|
.federation_repo
|
||||||
|
.get_blocked_domains()
|
||||||
|
.await
|
||||||
|
.unwrap_or_default();
|
||||||
|
let blocked_domain_set: std::collections::HashSet<String> =
|
||||||
|
blocked_domains.into_iter().map(|d| d.domain).collect();
|
||||||
|
let accepted: Vec<_> = followers
|
||||||
|
.into_iter()
|
||||||
|
.filter(|f| f.status == FollowerStatus::Accepted)
|
||||||
|
.filter(|f| !blocked_set.contains(&f.actor.url))
|
||||||
|
.filter(|f| {
|
||||||
|
let domain = url::Url::parse(&f.actor.inbox_url)
|
||||||
|
.ok()
|
||||||
|
.and_then(|u| u.host_str().map(|s| s.to_string()))
|
||||||
|
.unwrap_or_default();
|
||||||
|
!blocked_domain_set.contains(&domain)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
if accepted.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let create = CreateActivity {
|
||||||
|
id: ap_id.clone(),
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
object,
|
||||||
|
};
|
||||||
|
let create_with_ctx = WithContext::new_default(create);
|
||||||
|
|
||||||
|
let inboxes = collect_inboxes(&accepted);
|
||||||
|
|
||||||
|
let sends =
|
||||||
|
SendActivityTask::prepare(&create_with_ctx, &local_actor, inboxes, &data).await?;
|
||||||
|
let failures = send_with_retry(sends, &data).await;
|
||||||
|
if !failures.is_empty() {
|
||||||
|
tracing::warn!(
|
||||||
|
count = failures.len(),
|
||||||
|
"some activity deliveries failed permanently"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn broadcast_actor_update(&self, user_id: uuid::Uuid) -> anyhow::Result<()> {
|
||||||
|
use activitypub_federation::traits::Object;
|
||||||
|
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
let local_actor = get_local_actor(user_id, &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
|
let person = local_actor.clone().into_json(&data).await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
let person_json = serde_json::to_value(&person)?;
|
||||||
|
|
||||||
|
let update_id = Url::parse(&format!(
|
||||||
|
"{}/activities/update/{}",
|
||||||
|
self.base_url,
|
||||||
|
uuid::Uuid::new_v4()
|
||||||
|
))?;
|
||||||
|
|
||||||
|
let update = UpdateActivity {
|
||||||
|
id: update_id,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
object: person_json,
|
||||||
|
};
|
||||||
|
|
||||||
|
let followers = data.federation_repo.get_followers(user_id).await?;
|
||||||
|
let accepted: Vec<_> = followers
|
||||||
|
.into_iter()
|
||||||
|
.filter(|f| f.status == FollowerStatus::Accepted)
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
if accepted.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let inboxes = collect_inboxes(&accepted);
|
||||||
|
let sends = SendActivityTask::prepare(
|
||||||
|
&WithContext::new_default(update),
|
||||||
|
&local_actor,
|
||||||
|
inboxes,
|
||||||
|
&data,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let failures = send_with_retry(sends, &data).await;
|
||||||
|
if !failures.is_empty() {
|
||||||
|
tracing::warn!(count = failures.len(), "actor update delivery failures");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn block_actor(&self, local_user_id: uuid::Uuid, actor_url: &str) -> anyhow::Result<()> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
|
||||||
|
data.federation_repo
|
||||||
|
.add_blocked_actor(local_user_id, actor_url)
|
||||||
|
.await?;
|
||||||
|
let _ = data.federation_repo.remove_follower(local_user_id, actor_url).await;
|
||||||
|
let _ = data.federation_repo.remove_following(local_user_id, actor_url).await;
|
||||||
|
|
||||||
|
let local_actor = get_local_actor(local_user_id, &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
|
if let Ok(Some(remote_actor)) = data.federation_repo.get_remote_actor(actor_url).await {
|
||||||
|
let block_id = crate::urls::activity_url(&self.base_url)
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
let block = crate::activities::BlockActivity {
|
||||||
|
id: block_id,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
object: Url::parse(actor_url)?,
|
||||||
|
};
|
||||||
|
let inbox = Url::parse(&remote_actor.inbox_url)?;
|
||||||
|
let sends = SendActivityTask::prepare(
|
||||||
|
&WithContext::new_default(block),
|
||||||
|
&local_actor,
|
||||||
|
vec![inbox],
|
||||||
|
&data,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let failures = send_with_retry(sends, &data).await;
|
||||||
|
if !failures.is_empty() {
|
||||||
|
tracing::warn!(actor = %actor_url, "failed to deliver Block activity");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn unblock_actor(&self, local_user_id: uuid::Uuid, actor_url: &str) -> anyhow::Result<()> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
data.federation_repo
|
||||||
|
.remove_blocked_actor(local_user_id, actor_url)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_blocked_actors(&self, local_user_id: uuid::Uuid) -> anyhow::Result<Vec<RemoteActor>> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
let actor_urls = data.federation_repo.get_blocked_actors(local_user_id).await?;
|
||||||
|
let mut actors = Vec::new();
|
||||||
|
for url in actor_urls {
|
||||||
|
let actor = match data.federation_repo.get_remote_actor(&url).await {
|
||||||
|
Ok(Some(a)) => a,
|
||||||
|
_ => RemoteActor {
|
||||||
|
url: url.clone(),
|
||||||
|
handle: url.clone(),
|
||||||
|
inbox_url: url.clone(),
|
||||||
|
shared_inbox_url: None,
|
||||||
|
display_name: None,
|
||||||
|
avatar_url: None,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
actors.push(actor);
|
||||||
|
}
|
||||||
|
Ok(actors)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn add_blocked_domain(&self, domain: &str, reason: Option<&str>) -> anyhow::Result<()> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
data.federation_repo.add_blocked_domain(domain, reason).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn remove_blocked_domain(&self, domain: &str) -> anyhow::Result<()> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
data.federation_repo.remove_blocked_domain(domain).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_blocked_domains(&self) -> anyhow::Result<Vec<BlockedDomain>> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
data.federation_repo.get_blocked_domains().await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn follow_local(
|
||||||
|
&self,
|
||||||
|
local_user_id: uuid::Uuid,
|
||||||
|
target_username: &str,
|
||||||
|
data: &activitypub_federation::config::Data<FederationData>,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let target = data
|
||||||
|
.user_repo
|
||||||
|
.find_by_username(target_username)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("user not found: {}", target_username))?;
|
||||||
|
|
||||||
|
if target.id == local_user_id {
|
||||||
|
return Err(anyhow::anyhow!("cannot follow yourself"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let follower_actor_url = crate::urls::actor_url(&self.base_url, local_user_id).to_string();
|
||||||
|
let target_actor_url = crate::urls::actor_url(&self.base_url, target.id);
|
||||||
|
let target_inbox_url = format!("{}/inbox", target_actor_url);
|
||||||
|
let follow_id = activity_url(&self.base_url)
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?
|
||||||
|
.to_string();
|
||||||
|
|
||||||
|
data.federation_repo
|
||||||
|
.add_follower(
|
||||||
|
target.id,
|
||||||
|
&follower_actor_url,
|
||||||
|
FollowerStatus::Accepted,
|
||||||
|
&follow_id,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let target_as_remote = RemoteActor {
|
||||||
|
url: target_actor_url.to_string(),
|
||||||
|
handle: format!("{}@{}", target.username, data.domain),
|
||||||
|
inbox_url: target_inbox_url,
|
||||||
|
shared_inbox_url: None,
|
||||||
|
display_name: Some(target.username),
|
||||||
|
avatar_url: None,
|
||||||
|
};
|
||||||
|
data.federation_repo
|
||||||
|
.add_following(local_user_id, target_as_remote, &follow_id)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
data.federation_repo
|
||||||
|
.update_following_status(
|
||||||
|
local_user_id,
|
||||||
|
&target_actor_url.to_string(),
|
||||||
|
FollowingStatus::Accepted,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
tracing::info!(follower = %local_user_id, followee = %target.id, "local follow");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn unfollow_local(
|
||||||
|
&self,
|
||||||
|
local_user_id: uuid::Uuid,
|
||||||
|
target_actor_url: &str,
|
||||||
|
data: &activitypub_federation::config::Data<FederationData>,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let target_url = Url::parse(target_actor_url)?;
|
||||||
|
let target_user_id = crate::urls::extract_user_id_from_url(&target_url)
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("invalid local actor URL: {}", target_actor_url))?;
|
||||||
|
|
||||||
|
let local_actor_url = crate::urls::actor_url(&self.base_url, local_user_id).to_string();
|
||||||
|
|
||||||
|
data.federation_repo
|
||||||
|
.remove_follower(target_user_id, &local_actor_url)
|
||||||
|
.await?;
|
||||||
|
data.federation_repo
|
||||||
|
.remove_following(local_user_id, target_actor_url)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
tracing::info!(follower = %local_user_id, followee = %target_user_id, "local unfollow");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spawn_backfill(&self, owner_user_id: uuid::Uuid, follower_inbox_url: String) {
|
||||||
|
let config = self.federation_config.clone();
|
||||||
|
let base_url = self.base_url.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
if let Err(e) = ActivityPubService::run_backfill(
|
||||||
|
config,
|
||||||
|
base_url,
|
||||||
|
owner_user_id,
|
||||||
|
follower_inbox_url,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
tracing::warn!(error = %e, "backfill: task failed");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run_backfill(
|
||||||
|
config: ApFederationConfig,
|
||||||
|
base_url: String,
|
||||||
|
owner_user_id: uuid::Uuid,
|
||||||
|
follower_inbox_url: String,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
const BATCH_SIZE: usize = 20;
|
||||||
|
|
||||||
|
let data = config.to_request_data();
|
||||||
|
let local_actor = get_local_actor(owner_user_id, &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
let inbox = Url::parse(&follower_inbox_url)?;
|
||||||
|
|
||||||
|
let mut objects = data
|
||||||
|
.object_handler
|
||||||
|
.get_local_objects_for_user(owner_user_id)
|
||||||
|
.await?;
|
||||||
|
objects.reverse(); // oldest first → chronological feed
|
||||||
|
|
||||||
|
let total = objects.len();
|
||||||
|
let mut success_count = 0usize;
|
||||||
|
let mut failure_count = 0usize;
|
||||||
|
|
||||||
|
for chunk in objects.chunks(BATCH_SIZE) {
|
||||||
|
for (ap_id, object_json) in chunk {
|
||||||
|
// Use a stable Create activity ID derived from the object's ap_id
|
||||||
|
let create_id = Url::parse(&format!(
|
||||||
|
"{}/activities/create/{}",
|
||||||
|
base_url,
|
||||||
|
uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_URL, ap_id.as_str().as_bytes())
|
||||||
|
))?;
|
||||||
|
|
||||||
|
let create = CreateActivity {
|
||||||
|
id: create_id,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
object: object_json.clone(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let sends = SendActivityTask::prepare(
|
||||||
|
&WithContext::new_default(create),
|
||||||
|
&local_actor,
|
||||||
|
vec![inbox.clone()],
|
||||||
|
&data,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let failures = send_with_retry(sends, &data).await;
|
||||||
|
if failures.is_empty() {
|
||||||
|
success_count += 1;
|
||||||
|
} else {
|
||||||
|
failure_count += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
user_id = %owner_user_id,
|
||||||
|
follower = %follower_inbox_url,
|
||||||
|
sent = success_count,
|
||||||
|
failed = failure_count,
|
||||||
|
total = total,
|
||||||
|
"backfill complete"
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::repository::{Follower, FollowerStatus, RemoteActor};
|
||||||
|
|
||||||
|
fn make_follower(inbox: &str, shared: Option<&str>) -> Follower {
|
||||||
|
Follower {
|
||||||
|
actor: RemoteActor {
|
||||||
|
url: format!("https://remote/{}", inbox),
|
||||||
|
handle: "user".to_string(),
|
||||||
|
inbox_url: inbox.to_string(),
|
||||||
|
shared_inbox_url: shared.map(|s| s.to_string()),
|
||||||
|
display_name: None,
|
||||||
|
avatar_url: None,
|
||||||
|
},
|
||||||
|
status: FollowerStatus::Accepted,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn collect_inboxes_deduplicates_shared() {
|
||||||
|
let followers = vec![
|
||||||
|
make_follower("https://mastodon.social/users/a/inbox", Some("https://mastodon.social/inbox")),
|
||||||
|
make_follower("https://mastodon.social/users/b/inbox", Some("https://mastodon.social/inbox")),
|
||||||
|
make_follower("https://other.instance/users/c/inbox", None),
|
||||||
|
];
|
||||||
|
let inboxes = collect_inboxes(&followers);
|
||||||
|
assert_eq!(inboxes.len(), 2);
|
||||||
|
let strs: Vec<_> = inboxes.iter().map(|u| u.as_str()).collect();
|
||||||
|
assert!(strs.contains(&"https://mastodon.social/inbox"));
|
||||||
|
assert!(strs.contains(&"https://other.instance/users/c/inbox"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn collect_inboxes_falls_back_to_individual_inbox() {
|
||||||
|
let followers = vec![
|
||||||
|
make_follower("https://example.com/users/x/inbox", None),
|
||||||
|
];
|
||||||
|
let inboxes = collect_inboxes(&followers);
|
||||||
|
assert_eq!(inboxes.len(), 1);
|
||||||
|
assert_eq!(inboxes[0].as_str(), "https://example.com/users/x/inbox");
|
||||||
|
}
|
||||||
|
}
|
||||||
20
crates/adapters/activitypub-base/src/urls.rs
Normal file
20
crates/adapters/activitypub-base/src/urls.rs
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
use url::Url;
|
||||||
|
|
||||||
|
use crate::error::Error;
|
||||||
|
|
||||||
|
pub fn extract_user_id_from_url(url: &Url) -> Option<uuid::Uuid> {
|
||||||
|
let path = url.path();
|
||||||
|
path.strip_prefix("/users/")
|
||||||
|
.and_then(|s| s.split('/').next())
|
||||||
|
.and_then(|s| uuid::Uuid::parse_str(s).ok())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn activity_url(base_url: &str) -> Result<Url, Error> {
|
||||||
|
Url::parse(&format!("{}/activities/{}", base_url, uuid::Uuid::new_v4()))
|
||||||
|
.map_err(|e| Error::bad_request(anyhow::anyhow!(e)))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn actor_url(base_url: &str, user_id: uuid::Uuid) -> Url {
|
||||||
|
Url::parse(&format!("{}/users/{}", base_url, user_id))
|
||||||
|
.expect("base_url is always a valid URL prefix")
|
||||||
|
}
|
||||||
18
crates/adapters/activitypub-base/src/user.rs
Normal file
18
crates/adapters/activitypub-base/src/user.rs
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
use async_trait::async_trait;
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ApUser {
|
||||||
|
pub id: uuid::Uuid,
|
||||||
|
pub username: String,
|
||||||
|
pub bio: Option<String>,
|
||||||
|
pub avatar_url: Option<Url>,
|
||||||
|
pub profile_url: Option<Url>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
pub trait ApUserRepository: Send + Sync {
|
||||||
|
async fn find_by_id(&self, id: uuid::Uuid) -> anyhow::Result<Option<ApUser>>;
|
||||||
|
async fn find_by_username(&self, username: &str) -> anyhow::Result<Option<ApUser>>;
|
||||||
|
async fn count_users(&self) -> anyhow::Result<usize>;
|
||||||
|
}
|
||||||
38
crates/adapters/activitypub-base/src/webfinger.rs
Normal file
38
crates/adapters/activitypub-base/src/webfinger.rs
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
use activitypub_federation::{
|
||||||
|
config::Data,
|
||||||
|
fetch::webfinger::{Webfinger, build_webfinger_response, extract_webfinger_name},
|
||||||
|
};
|
||||||
|
use axum::{
|
||||||
|
extract::Query,
|
||||||
|
http::header,
|
||||||
|
response::{IntoResponse, Response},
|
||||||
|
};
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use crate::data::FederationData;
|
||||||
|
use crate::error::Error;
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct WebfingerQuery {
|
||||||
|
resource: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn webfinger_handler(
|
||||||
|
Query(query): Query<WebfingerQuery>,
|
||||||
|
data: Data<FederationData>,
|
||||||
|
) -> Result<Response, Error> {
|
||||||
|
let name = extract_webfinger_name(&query.resource, &data)?;
|
||||||
|
|
||||||
|
let user = data
|
||||||
|
.user_repo
|
||||||
|
.find_by_username(name)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)?
|
||||||
|
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found")))?;
|
||||||
|
|
||||||
|
let ap_id = crate::urls::actor_url(&data.base_url, user.id);
|
||||||
|
|
||||||
|
let wf: Webfinger = build_webfinger_response(query.resource, ap_id);
|
||||||
|
let body = serde_json::to_string(&wf).map_err(|e| Error::from(anyhow::anyhow!(e)))?;
|
||||||
|
Ok(([(header::CONTENT_TYPE, "application/jrd+json")], body).into_response())
|
||||||
|
}
|
||||||
@@ -1,26 +1,20 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "activitypub"
|
name = "activitypub"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition.workspace = true
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
config = { workspace = true }
|
activitypub-base = { workspace = true }
|
||||||
k-ap = { workspace = true }
|
|
||||||
domain = { workspace = true }
|
domain = { workspace = true }
|
||||||
axum = { workspace = true }
|
axum = { workspace = true }
|
||||||
serde = { workspace = true, features = ["derive"] }
|
tokio = { workspace = true }
|
||||||
|
serde = { workspace = true }
|
||||||
serde_json = { workspace = true }
|
serde_json = { workspace = true }
|
||||||
uuid = { workspace = true, features = ["v4", "serde"] }
|
uuid = { workspace = true }
|
||||||
chrono = { workspace = true, features = ["clock", "serde"] }
|
chrono = { workspace = true }
|
||||||
anyhow = { workspace = true }
|
anyhow = { workspace = true }
|
||||||
tracing = { workspace = true }
|
tracing = { workspace = true }
|
||||||
async-trait = { workspace = true }
|
async-trait = { workspace = true }
|
||||||
|
|
||||||
url = { workspace = true, features = ["serde"] }
|
activitypub_federation = "0.7.0-beta.11"
|
||||||
ammonia = { workspace = true }
|
url = { version = "2", features = ["serde"] }
|
||||||
|
|
||||||
tokio = { workspace = true, features = ["time", "sync"] }
|
|
||||||
|
|
||||||
[dev-dependencies]
|
|
||||||
tokio = { workspace = true, features = ["rt", "macros"] }
|
|
||||||
domain = { workspace = true, features = ["test-helpers"] }
|
|
||||||
|
|||||||
@@ -1,135 +0,0 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use k_ap::{ApContentReader, ApObjectHandler, LocalObject};
|
|
||||||
use url::Url;
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
goal_handler::GoalObjectHandler, review_handler::ReviewObjectHandler,
|
|
||||||
watchlist_handler::WatchlistObjectHandler,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub struct CompositeObjectHandler {
|
|
||||||
pub review: Arc<ReviewObjectHandler>,
|
|
||||||
pub watchlist: Arc<WatchlistObjectHandler>,
|
|
||||||
pub goal: Arc<GoalObjectHandler>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl ApContentReader for CompositeObjectHandler {
|
|
||||||
async fn get_local_objects_page(
|
|
||||||
&self,
|
|
||||||
user_id: uuid::Uuid,
|
|
||||||
before: Option<chrono::DateTime<chrono::Utc>>,
|
|
||||||
limit: usize,
|
|
||||||
) -> anyhow::Result<Vec<LocalObject>> {
|
|
||||||
let fetch_limit = limit * 3;
|
|
||||||
let reviews = self
|
|
||||||
.review
|
|
||||||
.get_local_objects_page(user_id, before, fetch_limit)
|
|
||||||
.await?;
|
|
||||||
let watchlist = self
|
|
||||||
.watchlist
|
|
||||||
.get_local_objects_page(user_id, None, usize::MAX)
|
|
||||||
.await?;
|
|
||||||
let goals = self
|
|
||||||
.goal
|
|
||||||
.get_local_objects_page(user_id, None, usize::MAX)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let mut all: Vec<LocalObject> = Vec::new();
|
|
||||||
all.extend(reviews);
|
|
||||||
all.extend(watchlist);
|
|
||||||
all.extend(goals);
|
|
||||||
|
|
||||||
if let Some(before_ts) = before {
|
|
||||||
all.retain(|obj| obj.published_at < before_ts);
|
|
||||||
}
|
|
||||||
all.sort_by_key(|obj| std::cmp::Reverse(obj.published_at));
|
|
||||||
all.truncate(limit);
|
|
||||||
Ok(all)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn count_local_posts(&self) -> anyhow::Result<u64> {
|
|
||||||
self.review.count_local_posts().await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl ApObjectHandler for CompositeObjectHandler {
|
|
||||||
async fn on_create(
|
|
||||||
&self,
|
|
||||||
ap_id: &Url,
|
|
||||||
actor_url: &Url,
|
|
||||||
object: serde_json::Value,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
let is_review = object.get("review").and_then(|v| v.as_bool()) == Some(true)
|
|
||||||
|| object.get("rating").is_some();
|
|
||||||
let is_watchlist = object.get("watchlistEntry").and_then(|v| v.as_bool()) == Some(true)
|
|
||||||
|| (object.get("movieTitle").is_some()
|
|
||||||
&& object.get("rating").is_none()
|
|
||||||
&& object.get("review").is_none());
|
|
||||||
let is_goal = object.get("goal").and_then(|v| v.as_bool()) == Some(true);
|
|
||||||
if is_review {
|
|
||||||
self.review.on_create(ap_id, actor_url, object).await
|
|
||||||
} else if is_goal {
|
|
||||||
self.goal.on_create(ap_id, actor_url, object).await
|
|
||||||
} else if is_watchlist {
|
|
||||||
self.watchlist.on_create(ap_id, actor_url, object).await
|
|
||||||
} else {
|
|
||||||
tracing::warn!(ap_id = %ap_id, "ignoring Create for unknown object type");
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_update(
|
|
||||||
&self,
|
|
||||||
ap_id: &Url,
|
|
||||||
actor_url: &Url,
|
|
||||||
object: serde_json::Value,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
let is_review = object.get("review").and_then(|v| v.as_bool()) == Some(true)
|
|
||||||
|| object.get("rating").is_some();
|
|
||||||
let is_goal = object.get("goal").and_then(|v| v.as_bool()) == Some(true);
|
|
||||||
let is_watchlist = object.get("watchlistEntry").and_then(|v| v.as_bool()) == Some(true);
|
|
||||||
if is_review {
|
|
||||||
self.review.on_update(ap_id, actor_url, object).await
|
|
||||||
} else if is_goal {
|
|
||||||
self.goal.on_update(ap_id, actor_url, object).await
|
|
||||||
} else if is_watchlist {
|
|
||||||
self.watchlist.on_update(ap_id, actor_url, object).await
|
|
||||||
} else {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_delete(&self, ap_id: &Url, actor_url: &Url) -> anyhow::Result<()> {
|
|
||||||
self.review.on_delete(ap_id, actor_url).await?;
|
|
||||||
self.watchlist.on_delete(ap_id, actor_url).await?;
|
|
||||||
self.goal.on_delete(ap_id, actor_url).await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_actor_removed(&self, actor_url: &Url) -> anyhow::Result<()> {
|
|
||||||
self.review.on_actor_removed(actor_url).await?;
|
|
||||||
self.watchlist.on_actor_removed(actor_url).await?;
|
|
||||||
self.goal.on_actor_removed(actor_url).await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_like(&self, _: &Url, _: &Url) -> anyhow::Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
async fn on_announce_received(&self, _: &Url, _: &Url) -> anyhow::Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
async fn on_announce_of_remote(&self, _: &Url, _: &Url) -> anyhow::Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
async fn on_unlike(&self, _: &Url, _: &Url) -> anyhow::Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
async fn on_mention(&self, _: &Url, _: uuid::Uuid, _: &Url) -> anyhow::Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use domain::{
|
|
||||||
errors::DomainError,
|
|
||||||
ports::FederationDeletionNotifier,
|
|
||||||
value_objects::{InstanceIdentity, UserId},
|
|
||||||
};
|
|
||||||
use k_ap::ActivityPubService;
|
|
||||||
|
|
||||||
use crate::urls::actor_url;
|
|
||||||
|
|
||||||
pub struct ApDeletionNotifier {
|
|
||||||
service: Arc<ActivityPubService>,
|
|
||||||
instance: InstanceIdentity,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ApDeletionNotifier {
|
|
||||||
pub fn new(service: Arc<ActivityPubService>, instance: InstanceIdentity) -> Self {
|
|
||||||
Self { service, instance }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl FederationDeletionNotifier for ApDeletionNotifier {
|
|
||||||
async fn notify_deleted(&self, user: &UserId) -> Result<(), DomainError> {
|
|
||||||
let ap_id = actor_url(&self.instance, user.value());
|
|
||||||
self.service
|
|
||||||
.broadcast_delete_to_followers(user.value(), ap_id)
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,74 +1,44 @@
|
|||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use chrono::Datelike;
|
|
||||||
use domain::ports::EventHandler;
|
use domain::ports::EventHandler;
|
||||||
use domain::{
|
use domain::{
|
||||||
errors::DomainError,
|
errors::DomainError,
|
||||||
events::DomainEvent,
|
events::DomainEvent,
|
||||||
ports::{
|
ports::{MovieRepository, ReviewRepository},
|
||||||
GoalQuery, LocalApContentQuery, MovieQuery, ReviewRepository, StatsRepository,
|
value_objects::{ReviewId, UserId},
|
||||||
UserFederationSettingsQuery, UserRepository,
|
|
||||||
},
|
|
||||||
value_objects::{InstanceIdentity, MovieId, ReviewId, UserId},
|
|
||||||
};
|
};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use k_ap::{ActivityPubService, ApVisibility};
|
use activitypub_base::ActivityPubService;
|
||||||
|
|
||||||
use crate::objects::{ReviewApInput, goal_to_ap_object, review_to_ap_object};
|
use crate::objects::review_to_ap_object;
|
||||||
use crate::urls::{actor_url, goal_url, review_url};
|
use crate::urls::{actor_url, review_url};
|
||||||
|
|
||||||
pub struct ActivityPubEventHandler {
|
pub struct ActivityPubEventHandler {
|
||||||
ap_service: Arc<ActivityPubService>,
|
ap_service: Arc<ActivityPubService>,
|
||||||
content_query: Arc<dyn LocalApContentQuery>,
|
movie_repository: Arc<dyn MovieRepository>,
|
||||||
review_repo: Arc<dyn ReviewRepository>,
|
review_repository: Arc<dyn ReviewRepository>,
|
||||||
movie_repo: Arc<dyn MovieQuery>,
|
base_url: String,
|
||||||
goal_repo: Arc<dyn GoalQuery>,
|
|
||||||
stats_repo: Arc<dyn StatsRepository>,
|
|
||||||
federation_settings: Arc<dyn UserFederationSettingsQuery>,
|
|
||||||
user_repo: Arc<dyn UserRepository>,
|
|
||||||
instance: InstanceIdentity,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ActivityPubEventHandler {
|
impl ActivityPubEventHandler {
|
||||||
#[allow(clippy::too_many_arguments)]
|
|
||||||
pub fn new(
|
pub fn new(
|
||||||
ap_service: Arc<ActivityPubService>,
|
ap_service: Arc<ActivityPubService>,
|
||||||
content_query: Arc<dyn LocalApContentQuery>,
|
movie_repository: Arc<dyn MovieRepository>,
|
||||||
review_repo: Arc<dyn ReviewRepository>,
|
review_repository: Arc<dyn ReviewRepository>,
|
||||||
movie_repo: Arc<dyn MovieQuery>,
|
base_url: String,
|
||||||
goal_repo: Arc<dyn GoalQuery>,
|
|
||||||
stats_repo: Arc<dyn StatsRepository>,
|
|
||||||
federation_settings: Arc<dyn UserFederationSettingsQuery>,
|
|
||||||
user_repo: Arc<dyn UserRepository>,
|
|
||||||
instance: InstanceIdentity,
|
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
ap_service,
|
ap_service,
|
||||||
content_query,
|
movie_repository,
|
||||||
review_repo,
|
review_repository,
|
||||||
movie_repo,
|
base_url,
|
||||||
goal_repo,
|
|
||||||
stats_repo,
|
|
||||||
federation_settings,
|
|
||||||
user_repo,
|
|
||||||
instance,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl EventHandler for ActivityPubEventHandler {
|
impl EventHandler for ActivityPubEventHandler {
|
||||||
fn name(&self) -> &'static str {
|
|
||||||
"activitypub"
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn handle(&self, event: &DomainEvent) -> Result<(), DomainError> {
|
async fn handle(&self, event: &DomainEvent) -> Result<(), DomainError> {
|
||||||
if let Some(author) = self.outbound_author(event)
|
|
||||||
&& self.is_tombstoned(&author).await
|
|
||||||
{
|
|
||||||
tracing::debug!(user = %author.value(), "skipping federation event of a deleted account");
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
match event {
|
match event {
|
||||||
DomainEvent::ReviewLogged {
|
DomainEvent::ReviewLogged {
|
||||||
review_id, user_id, ..
|
review_id, user_id, ..
|
||||||
@@ -76,150 +46,28 @@ impl EventHandler for ActivityPubEventHandler {
|
|||||||
.on_review_logged(user_id, review_id)
|
.on_review_logged(user_id, review_id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string())),
|
.map_err(|e| DomainError::InfrastructureError(e.to_string())),
|
||||||
DomainEvent::ReviewUpdated {
|
|
||||||
review_id, user_id, ..
|
|
||||||
} => self
|
|
||||||
.on_review_updated(user_id, review_id)
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string())),
|
|
||||||
DomainEvent::ReviewDeleted { review_id, user_id } => self
|
|
||||||
.on_review_deleted(user_id, review_id)
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string())),
|
|
||||||
DomainEvent::UserUpdated { user_id } => self
|
DomainEvent::UserUpdated { user_id } => self
|
||||||
.ap_service
|
.ap_service
|
||||||
.broadcast_actor_update(user_id.value())
|
.broadcast_actor_update(user_id.value())
|
||||||
.await
|
.await
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string())),
|
.map_err(|e| DomainError::InfrastructureError(e.to_string())),
|
||||||
DomainEvent::WatchlistEntryAdded {
|
|
||||||
user_id,
|
|
||||||
movie_id,
|
|
||||||
movie_title,
|
|
||||||
release_year,
|
|
||||||
external_metadata_id,
|
|
||||||
added_at,
|
|
||||||
} => self
|
|
||||||
.on_watchlist_added(
|
|
||||||
user_id,
|
|
||||||
movie_id,
|
|
||||||
movie_title,
|
|
||||||
*release_year,
|
|
||||||
external_metadata_id,
|
|
||||||
added_at,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string())),
|
|
||||||
DomainEvent::WatchlistEntryRemoved { user_id, movie_id } => self
|
|
||||||
.on_watchlist_removed(user_id, movie_id)
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string())),
|
|
||||||
DomainEvent::FederationDeliveryRequested {
|
|
||||||
inbox_url,
|
|
||||||
activity_json,
|
|
||||||
signing_actor_id,
|
|
||||||
} => {
|
|
||||||
let inbox: url::Url = inbox_url
|
|
||||||
.parse()
|
|
||||||
.map_err(|e| DomainError::InfrastructureError(format!("bad inbox URL: {e}")))?;
|
|
||||||
self.ap_service
|
|
||||||
.deliver_to_inbox(inbox, activity_json.clone(), *signing_actor_id)
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string()))
|
|
||||||
}
|
|
||||||
DomainEvent::PosterSynced { movie_id } => self
|
|
||||||
.on_poster_synced(movie_id)
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string())),
|
|
||||||
DomainEvent::GoalCreated {
|
|
||||||
user_id,
|
|
||||||
year,
|
|
||||||
target_count,
|
|
||||||
..
|
|
||||||
} => self
|
|
||||||
.broadcast_goal(user_id, *year, *target_count, true)
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string())),
|
|
||||||
DomainEvent::GoalUpdated {
|
|
||||||
user_id,
|
|
||||||
year,
|
|
||||||
target_count,
|
|
||||||
..
|
|
||||||
} => self
|
|
||||||
.broadcast_goal(user_id, *year, *target_count, false)
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string())),
|
|
||||||
DomainEvent::GoalDeleted { user_id, year, .. } => self
|
|
||||||
.on_goal_deleted(user_id, *year)
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string())),
|
|
||||||
DomainEvent::UserAccountMoved {
|
|
||||||
user_id,
|
|
||||||
new_actor_url,
|
|
||||||
} => {
|
|
||||||
let target = new_actor_url.parse::<url::Url>().map_err(|e| {
|
|
||||||
DomainError::InfrastructureError(format!("invalid new_actor_url: {e}"))
|
|
||||||
})?;
|
|
||||||
self.ap_service
|
|
||||||
.broadcast_move(user_id.value(), target)
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string()))
|
|
||||||
}
|
|
||||||
_ => Ok(()),
|
_ => Ok(()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ActivityPubEventHandler {
|
impl ActivityPubEventHandler {
|
||||||
fn outbound_author(&self, event: &DomainEvent) -> Option<UserId> {
|
|
||||||
match event {
|
|
||||||
DomainEvent::ReviewLogged { user_id, .. }
|
|
||||||
| DomainEvent::ReviewUpdated { user_id, .. }
|
|
||||||
| DomainEvent::ReviewDeleted { user_id, .. }
|
|
||||||
| DomainEvent::UserUpdated { user_id }
|
|
||||||
| DomainEvent::WatchlistEntryAdded { user_id, .. }
|
|
||||||
| DomainEvent::WatchlistEntryRemoved { user_id, .. }
|
|
||||||
| DomainEvent::GoalCreated { user_id, .. }
|
|
||||||
| DomainEvent::GoalUpdated { user_id, .. }
|
|
||||||
| DomainEvent::GoalDeleted { user_id, .. }
|
|
||||||
| DomainEvent::UserAccountMoved { user_id, .. } => Some(user_id.clone()),
|
|
||||||
DomainEvent::FederationDeliveryRequested {
|
|
||||||
activity_json,
|
|
||||||
signing_actor_id,
|
|
||||||
..
|
|
||||||
} if activity_json.get("type").and_then(|t| t.as_str()) != Some("Delete") => {
|
|
||||||
Some(UserId::from_uuid(*signing_actor_id))
|
|
||||||
}
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn is_tombstoned(&self, user: &UserId) -> bool {
|
|
||||||
matches!(
|
|
||||||
self.user_repo.find_tombstoned_by_id(user).await,
|
|
||||||
Ok(Some(_))
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_review_logged(&self, user_id: &UserId, review_id: &ReviewId) -> anyhow::Result<()> {
|
async fn on_review_logged(&self, user_id: &UserId, review_id: &ReviewId) -> anyhow::Result<()> {
|
||||||
let flags = self
|
let review = match self.review_repository.get_review_by_id(review_id).await? {
|
||||||
.federation_settings
|
|
||||||
.get_federation_flags(user_id)
|
|
||||||
.await
|
|
||||||
.unwrap_or_default();
|
|
||||||
if !flags.reviews {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
let review = match self.review_repo.get_review_by_id(review_id).await? {
|
|
||||||
Some(r) => r,
|
Some(r) => r,
|
||||||
None => return Ok(()),
|
None => return Ok(()),
|
||||||
};
|
};
|
||||||
|
|
||||||
let ap_id = review_url(&self.instance, review_id);
|
let ap_id = review_url(&self.base_url, review_id);
|
||||||
let actor = actor_url(&self.instance, user_id.value());
|
let actor = actor_url(&self.base_url, user_id.value());
|
||||||
|
|
||||||
let movie = self
|
let movie = self
|
||||||
.movie_repo
|
.movie_repository
|
||||||
.get_movie_by_id(review.movie_id())
|
.get_movie_by_id(review.movie_id())
|
||||||
.await
|
.await
|
||||||
.ok()
|
.ok()
|
||||||
@@ -232,334 +80,26 @@ impl ActivityPubEventHandler {
|
|||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|m| m.release_year().value())
|
.map(|m| m.release_year().value())
|
||||||
.unwrap_or(0);
|
.unwrap_or(0);
|
||||||
let obj = review_to_ap_object(
|
|
||||||
&review,
|
|
||||||
ReviewApInput {
|
|
||||||
ap_id: ap_id.clone(),
|
|
||||||
actor_url: actor,
|
|
||||||
movie_title,
|
|
||||||
release_year,
|
|
||||||
external_metadata_id: movie
|
|
||||||
.as_ref()
|
|
||||||
.and_then(|m| m.external_metadata_id())
|
|
||||||
.map(|id| id.value().to_string()),
|
|
||||||
poster_url: movie
|
|
||||||
.as_ref()
|
|
||||||
.and_then(|m| m.poster_path())
|
|
||||||
.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(user_id.value(), json, ApVisibility::Public, vec![])
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let year = review.watched_at().year() as u16;
|
|
||||||
self.broadcast_goal_progress_update(user_id, year).await?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_review_updated(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
review_id: &ReviewId,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
let flags = self
|
|
||||||
.federation_settings
|
|
||||||
.get_federation_flags(user_id)
|
|
||||||
.await
|
|
||||||
.unwrap_or_default();
|
|
||||||
if !flags.reviews {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
let review = match self.review_repo.get_review_by_id(review_id).await? {
|
|
||||||
Some(r) => r,
|
|
||||||
None => return Ok(()),
|
|
||||||
};
|
|
||||||
|
|
||||||
let ap_id = review_url(&self.instance, review_id);
|
|
||||||
let actor = actor_url(&self.instance, user_id.value());
|
|
||||||
|
|
||||||
let movie = self
|
|
||||||
.movie_repo
|
|
||||||
.get_movie_by_id(review.movie_id())
|
|
||||||
.await
|
|
||||||
.ok()
|
|
||||||
.flatten();
|
|
||||||
let movie_title = movie
|
|
||||||
.as_ref()
|
|
||||||
.map(|m| m.title().value().to_string())
|
|
||||||
.unwrap_or_else(|| "Unknown".to_string());
|
|
||||||
let release_year = movie
|
|
||||||
.as_ref()
|
|
||||||
.map(|m| m.release_year().value())
|
|
||||||
.unwrap_or(0);
|
|
||||||
let obj = review_to_ap_object(
|
|
||||||
&review,
|
|
||||||
ReviewApInput {
|
|
||||||
ap_id,
|
|
||||||
actor_url: actor,
|
|
||||||
movie_title,
|
|
||||||
release_year,
|
|
||||||
external_metadata_id: movie
|
|
||||||
.as_ref()
|
|
||||||
.and_then(|m| m.external_metadata_id())
|
|
||||||
.map(|id| id.value().to_string()),
|
|
||||||
poster_url: movie
|
|
||||||
.as_ref()
|
|
||||||
.and_then(|m| m.poster_path())
|
|
||||||
.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(user_id.value(), json, ApVisibility::Public, vec![])
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_review_deleted(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
review_id: &ReviewId,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
let ap_id = review_url(&self.instance, review_id);
|
|
||||||
self.ap_service
|
|
||||||
.broadcast_delete_to_followers(user_id.value(), ap_id)
|
|
||||||
.await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_watchlist_added(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
movie_id: &domain::value_objects::MovieId,
|
|
||||||
movie_title: &str,
|
|
||||||
release_year: u16,
|
|
||||||
external_metadata_id: &Option<String>,
|
|
||||||
added_at: &chrono::NaiveDateTime,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
let flags = self
|
|
||||||
.federation_settings
|
|
||||||
.get_federation_flags(user_id)
|
|
||||||
.await
|
|
||||||
.unwrap_or_default();
|
|
||||||
if !flags.watchlist {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
use crate::urls::watchlist_entry_url;
|
|
||||||
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
|
|
||||||
.get_movie_by_id(movie_id)
|
|
||||||
.await
|
|
||||||
.ok()
|
|
||||||
.flatten()
|
|
||||||
.and_then(|m| {
|
|
||||||
m.poster_path()
|
|
||||||
.map(|p| self.instance.image_url_for(p.value()))
|
|
||||||
});
|
|
||||||
|
|
||||||
let added_at_utc =
|
|
||||||
chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(*added_at, chrono::Utc);
|
|
||||||
let obj = crate::objects::watchlist_to_ap_object(crate::objects::WatchlistApInput {
|
|
||||||
ap_id: ap_id.clone(),
|
|
||||||
actor_url: actor,
|
|
||||||
movie_title: movie_title.to_string(),
|
|
||||||
release_year,
|
|
||||||
external_metadata_id: external_metadata_id.clone(),
|
|
||||||
poster_url,
|
|
||||||
added_at: added_at_utc,
|
|
||||||
base_url: self.instance.base_url().to_string(),
|
|
||||||
});
|
|
||||||
let json = serde_json::to_value(obj)?;
|
|
||||||
|
|
||||||
self.ap_service
|
|
||||||
.broadcast_create(user_id.value(), json, ApVisibility::Public, vec![])
|
|
||||||
.await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_watchlist_removed(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
movie_id: &domain::value_objects::MovieId,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
use crate::urls::watchlist_entry_url;
|
|
||||||
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?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_poster_synced(&self, movie_id: &MovieId) -> anyhow::Result<()> {
|
|
||||||
let entries = self
|
|
||||||
.content_query
|
|
||||||
.get_local_reviews_for_movie(movie_id)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let movie = self.movie_repo.get_movie_by_id(movie_id).await?;
|
|
||||||
let movie = match movie {
|
|
||||||
Some(m) => m,
|
|
||||||
None => return Ok(()),
|
|
||||||
};
|
|
||||||
let external_metadata_id = movie
|
|
||||||
.external_metadata_id()
|
|
||||||
.map(|id| id.value().to_string());
|
|
||||||
let poster_url = movie
|
let poster_url = movie
|
||||||
.poster_path()
|
.as_ref()
|
||||||
.map(|p| self.instance.image_url_for(p.value()));
|
.and_then(|m| m.poster_path())
|
||||||
|
.map(|p| format!("{}/images/{}", self.base_url, p.value()));
|
||||||
|
|
||||||
for entry in entries {
|
let obj = review_to_ap_object(
|
||||||
let review = entry.review();
|
&review,
|
||||||
let user_id = review.user_id();
|
ap_id.clone(),
|
||||||
|
|
||||||
let flags = self
|
|
||||||
.federation_settings
|
|
||||||
.get_federation_flags(user_id)
|
|
||||||
.await
|
|
||||||
.unwrap_or_default();
|
|
||||||
if !flags.reviews {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
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,
|
|
||||||
ReviewApInput {
|
|
||||||
ap_id,
|
|
||||||
actor_url: actor,
|
|
||||||
movie_title: movie.title().value().to_string(),
|
|
||||||
release_year: movie.release_year().value(),
|
|
||||||
external_metadata_id: external_metadata_id.clone(),
|
|
||||||
poster_url: poster_url.clone(),
|
|
||||||
base_url: self.instance.base_url().to_string(),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
let json = serde_json::to_value(obj)?;
|
|
||||||
|
|
||||||
self.ap_service
|
|
||||||
.broadcast_update(user_id.value(), json, ApVisibility::Public, vec![])
|
|
||||||
.await?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn broadcast_goal_progress_update(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
year: u16,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
let flags = self
|
|
||||||
.federation_settings
|
|
||||||
.get_federation_flags(user_id)
|
|
||||||
.await
|
|
||||||
.unwrap_or_default();
|
|
||||||
if !flags.goals {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
let Some(goal) = self
|
|
||||||
.goal_repo
|
|
||||||
.find_by_user_and_year(user_id, year)
|
|
||||||
.await
|
|
||||||
.ok()
|
|
||||||
.flatten()
|
|
||||||
else {
|
|
||||||
return Ok(());
|
|
||||||
};
|
|
||||||
let current = self
|
|
||||||
.stats_repo
|
|
||||||
.count_reviews_in_year(user_id, year)
|
|
||||||
.await
|
|
||||||
.unwrap_or(0);
|
|
||||||
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,
|
actor,
|
||||||
year,
|
movie_title,
|
||||||
goal.target_count(),
|
release_year,
|
||||||
current,
|
poster_url,
|
||||||
self.instance.base_url(),
|
&self.base_url,
|
||||||
);
|
);
|
||||||
let json = serde_json::to_value(obj)?;
|
let json = serde_json::to_value(obj)?;
|
||||||
|
|
||||||
self.ap_service
|
self.ap_service
|
||||||
.broadcast_update(user_id.value(), json, ApVisibility::Public, vec![])
|
.broadcast_to_followers(user_id.value(), ap_id, json)
|
||||||
.await?;
|
.await?;
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn broadcast_goal(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
year: u16,
|
|
||||||
target_count: u32,
|
|
||||||
is_create: bool,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
let flags = self
|
|
||||||
.federation_settings
|
|
||||||
.get_federation_flags(user_id)
|
|
||||||
.await
|
|
||||||
.unwrap_or_default();
|
|
||||||
if !flags.goals {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
let current = self
|
|
||||||
.stats_repo
|
|
||||||
.count_reviews_in_year(user_id, year)
|
|
||||||
.await
|
|
||||||
.unwrap_or(0);
|
|
||||||
|
|
||||||
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(user_id.value(), json, ApVisibility::Public, vec![])
|
|
||||||
.await?;
|
|
||||||
} else {
|
|
||||||
self.ap_service
|
|
||||||
.broadcast_update(user_id.value(), json, ApVisibility::Public, vec![])
|
|
||||||
.await?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_goal_deleted(&self, user_id: &UserId, year: u16) -> anyhow::Result<()> {
|
|
||||||
let flags = self
|
|
||||||
.federation_settings
|
|
||||||
.get_federation_flags(user_id)
|
|
||||||
.await
|
|
||||||
.unwrap_or_default();
|
|
||||||
if !flags.goals {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
let ap_id = goal_url(&self.instance, user_id.value(), year);
|
|
||||||
self.ap_service
|
|
||||||
.broadcast_delete_to_followers(user_id.value(), ap_id)
|
|
||||||
.await?;
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,72 +0,0 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use domain::events::DomainEvent;
|
|
||||||
use domain::value_objects::UserId;
|
|
||||||
use k_ap::FederationEvent;
|
|
||||||
|
|
||||||
pub struct FederationEventBridge {
|
|
||||||
domain_publisher: Arc<dyn domain::ports::EventPublisher>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FederationEventBridge {
|
|
||||||
pub fn new(domain_publisher: Arc<dyn domain::ports::EventPublisher>) -> Self {
|
|
||||||
Self { domain_publisher }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait::async_trait]
|
|
||||||
impl k_ap::EventPublisher for FederationEventBridge {
|
|
||||||
async fn publish(&self, event: FederationEvent) -> anyhow::Result<()> {
|
|
||||||
match event {
|
|
||||||
FederationEvent::BackfillRequested {
|
|
||||||
owner_user_id,
|
|
||||||
follower_inbox_url,
|
|
||||||
} => self
|
|
||||||
.domain_publisher
|
|
||||||
.publish(&DomainEvent::BackfillFollower {
|
|
||||||
owner_user_id: UserId::from_uuid(owner_user_id),
|
|
||||||
follower_inbox_url,
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.map_err(|e| anyhow::anyhow!(e.to_string())),
|
|
||||||
FederationEvent::DeliveryRequested {
|
|
||||||
inbox,
|
|
||||||
activity,
|
|
||||||
signing_actor_id,
|
|
||||||
} => self
|
|
||||||
.domain_publisher
|
|
||||||
.publish(&DomainEvent::FederationDeliveryRequested {
|
|
||||||
inbox_url: inbox.to_string(),
|
|
||||||
activity_json: activity,
|
|
||||||
signing_actor_id,
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.map_err(|e| anyhow::anyhow!(e.to_string())),
|
|
||||||
FederationEvent::DeliveryFailed { inbox, error, .. } => {
|
|
||||||
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");
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,133 +0,0 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use domain::{
|
|
||||||
errors::DomainError,
|
|
||||||
models::{BlockedDomainInfo, FollowedActorInfo},
|
|
||||||
ports::{ApBackfillPort, ApDocumentPort, InstanceBlocklistPort, UserRepository},
|
|
||||||
value_objects::UserId,
|
|
||||||
};
|
|
||||||
use k_ap::ActivityPubService;
|
|
||||||
use uuid::Uuid;
|
|
||||||
|
|
||||||
pub struct ApServiceAdapter {
|
|
||||||
service: Arc<ActivityPubService>,
|
|
||||||
users: Arc<dyn UserRepository>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ApServiceAdapter {
|
|
||||||
pub fn new(service: Arc<ActivityPubService>, users: Arc<dyn UserRepository>) -> Self {
|
|
||||||
Self { service, users }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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_is_gone(&self, user_id: Uuid) -> Result<bool, DomainError> {
|
|
||||||
Ok(self
|
|
||||||
.users
|
|
||||||
.find_tombstoned_by_id(&UserId::from_uuid(user_id))
|
|
||||||
.await?
|
|
||||||
.is_some())
|
|
||||||
}
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,150 +0,0 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use chrono::DateTime;
|
|
||||||
use domain::{
|
|
||||||
models::RemoteGoalEntry,
|
|
||||||
ports::{GoalQuery, RemoteGoalRepository},
|
|
||||||
value_objects::{InstanceIdentity, UserId},
|
|
||||||
};
|
|
||||||
use k_ap::{AS_PUBLIC, ApContentReader, ApObjectHandler, LocalObject};
|
|
||||||
use url::Url;
|
|
||||||
|
|
||||||
use crate::objects::{GoalObject, goal_to_ap_object};
|
|
||||||
use crate::urls::{actor_url, goal_url};
|
|
||||||
|
|
||||||
pub struct GoalObjectHandler {
|
|
||||||
pub remote_goal_repo: Arc<dyn RemoteGoalRepository>,
|
|
||||||
pub goal_repo: Arc<dyn GoalQuery>,
|
|
||||||
pub instance: InstanceIdentity,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl ApContentReader for GoalObjectHandler {
|
|
||||||
async fn get_local_objects_page(
|
|
||||||
&self,
|
|
||||||
user_id: uuid::Uuid,
|
|
||||||
_before: Option<DateTime<chrono::Utc>>,
|
|
||||||
_limit: usize,
|
|
||||||
) -> anyhow::Result<Vec<LocalObject>> {
|
|
||||||
let uid = UserId::from_uuid(user_id);
|
|
||||||
let goals = self
|
|
||||||
.goal_repo
|
|
||||||
.list_for_user(&uid)
|
|
||||||
.await
|
|
||||||
.map_err(|e| anyhow::anyhow!(e.to_string()))?;
|
|
||||||
|
|
||||||
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.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(),
|
|
||||||
actor.clone(),
|
|
||||||
goal.year(),
|
|
||||||
goal.target_count(),
|
|
||||||
0,
|
|
||||||
self.instance.base_url(),
|
|
||||||
);
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn count_local_posts(&self) -> anyhow::Result<u64> {
|
|
||||||
Ok(0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl ApObjectHandler for GoalObjectHandler {
|
|
||||||
async fn on_create(
|
|
||||||
&self,
|
|
||||||
ap_id: &Url,
|
|
||||||
actor_url: &Url,
|
|
||||||
object: serde_json::Value,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
let obj: GoalObject = match serde_json::from_value(object) {
|
|
||||||
Ok(o) => o,
|
|
||||||
Err(e) => {
|
|
||||||
tracing::warn!(ap_id = %ap_id, "ignoring malformed goal Create: {}", e);
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let entry = RemoteGoalEntry {
|
|
||||||
ap_id: ap_id.as_str().to_string(),
|
|
||||||
actor_url: actor_url.as_str().to_string(),
|
|
||||||
year: obj.goal_year,
|
|
||||||
target_count: obj.goal_target,
|
|
||||||
current_count: obj.goal_current,
|
|
||||||
received_at: chrono::Utc::now(),
|
|
||||||
};
|
|
||||||
self.remote_goal_repo.save(entry).await?;
|
|
||||||
tracing::info!(ap_id = %ap_id, year = obj.goal_year, "saved remote goal");
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_update(
|
|
||||||
&self,
|
|
||||||
ap_id: &Url,
|
|
||||||
actor_url: &Url,
|
|
||||||
object: serde_json::Value,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
let obj: GoalObject = match serde_json::from_value(object) {
|
|
||||||
Ok(o) => o,
|
|
||||||
Err(e) => {
|
|
||||||
tracing::warn!(ap_id = %ap_id, "ignoring malformed goal Update: {}", e);
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
};
|
|
||||||
if obj.attributed_to != *actor_url {
|
|
||||||
anyhow::bail!("goal Update actor does not match object attributed_to");
|
|
||||||
}
|
|
||||||
self.remote_goal_repo
|
|
||||||
.update_by_ap_id(ap_id.as_str(), obj.goal_target, obj.goal_current)
|
|
||||||
.await?;
|
|
||||||
tracing::info!(ap_id = %ap_id, "updated remote goal progress");
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_delete(&self, ap_id: &Url, actor_url: &Url) -> anyhow::Result<()> {
|
|
||||||
self.remote_goal_repo
|
|
||||||
.remove_by_ap_id(ap_id.as_str(), actor_url.as_str())
|
|
||||||
.await?;
|
|
||||||
tracing::info!(ap_id = %ap_id, "removed remote goal");
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_actor_removed(&self, actor_url: &Url) -> anyhow::Result<()> {
|
|
||||||
self.remote_goal_repo
|
|
||||||
.remove_all_by_actor(actor_url.as_str())
|
|
||||||
.await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_like(&self, _: &Url, _: &Url) -> anyhow::Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
async fn on_announce_received(&self, _: &Url, _: &Url) -> anyhow::Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
async fn on_announce_of_remote(&self, _: &Url, _: &Url) -> anyhow::Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
async fn on_unlike(&self, _: &Url, _: &Url) -> anyhow::Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
async fn on_mention(&self, _: &Url, _: uuid::Uuid, _: &Url) -> anyhow::Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,201 +1,68 @@
|
|||||||
pub mod composite_handler;
|
|
||||||
pub mod deletion_notifier;
|
|
||||||
pub mod event_handler;
|
pub mod event_handler;
|
||||||
pub mod federation_event_bridge;
|
|
||||||
pub mod federation_ports;
|
|
||||||
pub mod goal_handler;
|
|
||||||
pub mod objects;
|
pub mod objects;
|
||||||
|
pub mod port;
|
||||||
pub mod remote_review_repository;
|
pub mod remote_review_repository;
|
||||||
pub mod review_handler;
|
pub mod review_handler;
|
||||||
pub mod social_adapter;
|
|
||||||
pub mod tombstone_gate;
|
|
||||||
pub(crate) mod urls;
|
pub(crate) mod urls;
|
||||||
pub mod user_adapter;
|
pub mod user_adapter;
|
||||||
pub mod watchlist_handler;
|
|
||||||
|
|
||||||
pub const INSTANCE_ACTOR_ID: uuid::Uuid = domain::value_objects::SERVICE_ACTOR_UUID;
|
// Re-export the generic base types that callers need
|
||||||
|
pub use activitypub_base::{
|
||||||
pub use k_ap::{
|
ActivityPubService, ApFederationConfig, ApObjectHandler, ApUser, ApUserRepository,
|
||||||
ActivityPubService, ActivityRepository, ActorRepository, ApContentReader, ApFederationConfig,
|
FederationData, FederationRepository, Follower, FollowerStatus, FollowingStatus, RemoteActor,
|
||||||
ApObjectHandler, ApUser, ApUserRepository, BlocklistRepository, FederationData,
|
|
||||||
FollowRepository, Follower, FollowerStatus, FollowingStatus, LocalObject, RemoteActor,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub use deletion_notifier::ApDeletionNotifier;
|
|
||||||
pub use event_handler::ActivityPubEventHandler;
|
pub use event_handler::ActivityPubEventHandler;
|
||||||
pub use federation_ports::ApServiceAdapter;
|
pub use port::{ActivityPubPort, NoopActivityPubService};
|
||||||
pub use remote_review_repository::{NewRemoteReview, RemoteReviewRepository, RemoteReviewUpdate};
|
pub use remote_review_repository::RemoteReviewRepository;
|
||||||
pub use review_handler::ReviewObjectHandler;
|
pub use review_handler::ReviewObjectHandler;
|
||||||
pub use social_adapter::CompositeSocialAdapter;
|
|
||||||
pub use user_adapter::DomainUserRepoAdapter;
|
pub use user_adapter::DomainUserRepoAdapter;
|
||||||
|
|
||||||
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 struct ActivityPubWire {
|
||||||
pub document: std::sync::Arc<dyn domain::ports::ApDocumentPort>,
|
pub service: std::sync::Arc<dyn ActivityPubPort>,
|
||||||
pub blocklist: std::sync::Arc<dyn domain::ports::InstanceBlocklistPort>,
|
pub router: axum::Router,
|
||||||
pub backfill: std::sync::Arc<dyn domain::ports::ApBackfillPort>,
|
|
||||||
pub service: std::sync::Arc<ActivityPubService>,
|
|
||||||
pub router: axum::Router,
|
|
||||||
pub event_handler: std::sync::Arc<dyn domain::ports::EventHandler>,
|
pub event_handler: std::sync::Arc<dyn domain::ports::EventHandler>,
|
||||||
pub deletion_notifier: std::sync::Arc<dyn domain::ports::FederationDeletionNotifier>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct ActivityPubDeps {
|
pub async fn wire(
|
||||||
pub activity_repo: std::sync::Arc<dyn ActivityRepository>,
|
federation_repo: std::sync::Arc<dyn FederationRepository>,
|
||||||
pub follow_repo: std::sync::Arc<dyn FollowRepository>,
|
review_store: std::sync::Arc<dyn RemoteReviewRepository>,
|
||||||
pub actor_repo: std::sync::Arc<dyn ActorRepository>,
|
user_repo: std::sync::Arc<dyn domain::ports::UserRepository>,
|
||||||
pub blocklist_repo: std::sync::Arc<dyn BlocklistRepository>,
|
movie_repo: std::sync::Arc<dyn domain::ports::MovieRepository>,
|
||||||
pub review_store: std::sync::Arc<dyn RemoteReviewRepository>,
|
review_repo: std::sync::Arc<dyn domain::ports::ReviewRepository>,
|
||||||
pub remote_watchlist_repo: std::sync::Arc<dyn domain::ports::RemoteWatchlistRepository>,
|
diary_repo: std::sync::Arc<dyn domain::ports::DiaryRepository>,
|
||||||
pub remote_goal_repo: std::sync::Arc<dyn domain::ports::RemoteGoalRepository>,
|
base_url: String,
|
||||||
pub local_ap_content: std::sync::Arc<dyn domain::ports::LocalApContentQuery>,
|
allow_registration: bool,
|
||||||
pub movie_repo: std::sync::Arc<dyn domain::ports::MovieQuery>,
|
) -> anyhow::Result<ActivityPubWire> {
|
||||||
pub review_repo: std::sync::Arc<dyn domain::ports::ReviewRepository>,
|
|
||||||
pub diary_repo: std::sync::Arc<dyn domain::ports::DiaryQuery>,
|
|
||||||
pub goal_repo: std::sync::Arc<dyn domain::ports::GoalQuery>,
|
|
||||||
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 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 federation: config::FederationConfig,
|
|
||||||
pub event_publisher: std::sync::Arc<dyn domain::ports::EventPublisher>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn wire(deps: ActivityPubDeps) -> anyhow::Result<ActivityPubWire> {
|
|
||||||
let ActivityPubDeps {
|
|
||||||
activity_repo,
|
|
||||||
follow_repo,
|
|
||||||
actor_repo,
|
|
||||||
blocklist_repo,
|
|
||||||
review_store,
|
|
||||||
remote_watchlist_repo,
|
|
||||||
remote_goal_repo,
|
|
||||||
local_ap_content,
|
|
||||||
movie_repo,
|
|
||||||
review_repo,
|
|
||||||
diary_repo,
|
|
||||||
goal_repo,
|
|
||||||
stats_repo,
|
|
||||||
user_repo,
|
|
||||||
federation_settings,
|
|
||||||
follow_command: _,
|
|
||||||
follow_query: _,
|
|
||||||
instance,
|
|
||||||
allow_registration,
|
|
||||||
federation,
|
|
||||||
event_publisher,
|
|
||||||
} = deps;
|
|
||||||
let review_handler = std::sync::Arc::new(ReviewObjectHandler {
|
|
||||||
content_query: std::sync::Arc::clone(&local_ap_content),
|
|
||||||
movie_repo: std::sync::Arc::clone(&movie_repo),
|
|
||||||
diary_repo,
|
|
||||||
review_store,
|
|
||||||
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),
|
|
||||||
instance: instance.clone(),
|
|
||||||
});
|
|
||||||
let goal_handler = std::sync::Arc::new(goal_handler::GoalObjectHandler {
|
|
||||||
remote_goal_repo,
|
|
||||||
goal_repo: std::sync::Arc::clone(&goal_repo),
|
|
||||||
instance: instance.clone(),
|
|
||||||
});
|
|
||||||
let composite = std::sync::Arc::new(composite_handler::CompositeObjectHandler {
|
|
||||||
review: review_handler,
|
|
||||||
watchlist: watchlist_handler,
|
|
||||||
goal: goal_handler,
|
|
||||||
});
|
|
||||||
|
|
||||||
let federation_debug = federation.debug;
|
|
||||||
|
|
||||||
if federation_debug {
|
|
||||||
tracing::warn!(
|
|
||||||
"federation running in DEBUG mode — PermissiveVerifier active, \
|
|
||||||
no URL/signature validation. Do NOT use in production."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
let fed_event_bridge = std::sync::Arc::new(
|
|
||||||
federation_event_bridge::FederationEventBridge::new(event_publisher),
|
|
||||||
);
|
|
||||||
|
|
||||||
let concrete = std::sync::Arc::new(
|
let concrete = std::sync::Arc::new(
|
||||||
ActivityPubService::builder(instance.base_url().to_string())
|
ActivityPubService::new(
|
||||||
.activity_repo(activity_repo)
|
federation_repo,
|
||||||
.follow_repo(follow_repo)
|
std::sync::Arc::new(DomainUserRepoAdapter::new(user_repo, base_url.clone())),
|
||||||
.actor_repo(actor_repo)
|
std::sync::Arc::new(ReviewObjectHandler {
|
||||||
.blocklist_repo(blocklist_repo)
|
movie_repository: std::sync::Arc::clone(&movie_repo),
|
||||||
.user_repo(std::sync::Arc::new(DomainUserRepoAdapter::new(
|
diary_repository: diary_repo,
|
||||||
std::sync::Arc::clone(&user_repo),
|
review_store,
|
||||||
instance.clone(),
|
base_url: base_url.clone(),
|
||||||
)))
|
}),
|
||||||
.signed_fetch_actor_id(INSTANCE_ACTOR_ID)
|
base_url.clone(),
|
||||||
.content_reader(composite.clone() as std::sync::Arc<dyn ApContentReader>)
|
allow_registration,
|
||||||
.object_handler(composite as std::sync::Arc<dyn ApObjectHandler>)
|
"movies-diary".to_string(),
|
||||||
.event_publisher(fed_event_bridge)
|
cfg!(debug_assertions),
|
||||||
.allow_registration(allow_registration)
|
)
|
||||||
.software_name("movies-diary")
|
.await?,
|
||||||
.nodeinfo_metadata(serde_json::json!({
|
|
||||||
"nodeName": "movies-diary",
|
|
||||||
"nodeDescription": "A federated movie diary"
|
|
||||||
}))
|
|
||||||
.debug(federation_debug)
|
|
||||||
.build()
|
|
||||||
.await?,
|
|
||||||
);
|
);
|
||||||
|
|
||||||
let router = concrete
|
let router = concrete.router();
|
||||||
.router()
|
|
||||||
.layer(axum::middleware::from_fn_with_state(
|
|
||||||
std::sync::Arc::clone(&user_repo),
|
|
||||||
tombstone_gate::tombstone_gate,
|
|
||||||
));
|
|
||||||
let deletion_notifier = std::sync::Arc::new(ApDeletionNotifier::new(
|
|
||||||
std::sync::Arc::clone(&concrete),
|
|
||||||
instance.clone(),
|
|
||||||
)) as std::sync::Arc<dyn domain::ports::FederationDeletionNotifier>;
|
|
||||||
let event_handler = std::sync::Arc::new(ActivityPubEventHandler::new(
|
let event_handler = std::sync::Arc::new(ActivityPubEventHandler::new(
|
||||||
std::sync::Arc::clone(&concrete),
|
std::sync::Arc::clone(&concrete),
|
||||||
local_ap_content,
|
|
||||||
review_repo,
|
|
||||||
movie_repo,
|
movie_repo,
|
||||||
goal_repo,
|
review_repo,
|
||||||
stats_repo,
|
base_url,
|
||||||
federation_settings,
|
|
||||||
std::sync::Arc::clone(&user_repo),
|
|
||||||
instance,
|
|
||||||
)) as std::sync::Arc<dyn domain::ports::EventHandler>;
|
)) as std::sync::Arc<dyn domain::ports::EventHandler>;
|
||||||
|
|
||||||
let ports = std::sync::Arc::new(federation_ports::ApServiceAdapter::new(
|
|
||||||
std::sync::Arc::clone(&concrete),
|
|
||||||
std::sync::Arc::clone(&user_repo),
|
|
||||||
));
|
|
||||||
|
|
||||||
Ok(ActivityPubWire {
|
Ok(ActivityPubWire {
|
||||||
document: std::sync::Arc::clone(&ports)
|
service: concrete as std::sync::Arc<dyn ActivityPubPort>,
|
||||||
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,
|
router,
|
||||||
event_handler,
|
event_handler,
|
||||||
deletion_notifier,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,29 +1,10 @@
|
|||||||
|
use activitypub_federation::kinds::object::NoteType;
|
||||||
use chrono::{DateTime, Utc};
|
use chrono::{DateTime, Utc};
|
||||||
use k_ap::AS_PUBLIC;
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use url::Url;
|
use url::Url;
|
||||||
|
|
||||||
use domain::models::Review;
|
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 {
|
|
||||||
#[serde(rename = "type")]
|
|
||||||
pub(crate) kind: String,
|
|
||||||
pub(crate) url: String,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub(crate) media_type: Option<String>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub(crate) name: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
pub struct ApHashtag {
|
pub struct ApHashtag {
|
||||||
#[serde(rename = "type")]
|
#[serde(rename = "type")]
|
||||||
@@ -40,7 +21,7 @@ pub(crate) fn normalize_hashtag(title: &str) -> String {
|
|||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct ReviewObject {
|
pub struct ReviewObject {
|
||||||
#[serde(rename = "type")]
|
#[serde(rename = "type")]
|
||||||
pub(crate) kind: ActivityStreamsType,
|
pub(crate) kind: NoteType,
|
||||||
pub(crate) id: Url,
|
pub(crate) id: Url,
|
||||||
pub(crate) attributed_to: Url,
|
pub(crate) attributed_to: Url,
|
||||||
pub(crate) content: String,
|
pub(crate) content: String,
|
||||||
@@ -49,53 +30,25 @@ pub struct ReviewObject {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub(crate) release_year: u16,
|
pub(crate) release_year: u16,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub(crate) external_metadata_id: Option<String>,
|
|
||||||
#[serde(default)]
|
|
||||||
pub(crate) poster_url: Option<String>,
|
pub(crate) poster_url: Option<String>,
|
||||||
pub(crate) rating: u8,
|
pub(crate) rating: u8,
|
||||||
pub(crate) comment: Option<String>,
|
pub(crate) comment: Option<String>,
|
||||||
pub(crate) watched_at: DateTime<Utc>,
|
pub(crate) watched_at: DateTime<Utc>,
|
||||||
#[serde(skip_serializing_if = "Option::is_none", default)]
|
|
||||||
pub(crate) watch_medium: Option<String>,
|
|
||||||
/// Discriminator so Movies Diary instances detect this as a review Note.
|
|
||||||
#[serde(default)]
|
|
||||||
pub(crate) review: bool,
|
|
||||||
/// Spoiler Flag. Movies-Diary peers veil the comment behind this boolean;
|
|
||||||
/// other fediverse apps render `summary` as a content warning (ADR-0011).
|
|
||||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
|
||||||
pub(crate) contains_spoilers: bool,
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
pub(crate) summary: Option<String>,
|
|
||||||
#[serde(skip_serializing_if = "Vec::is_empty", default)]
|
|
||||||
pub(crate) attachment: Vec<ApAttachment>,
|
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub(crate) tag: Vec<ApHashtag>,
|
pub(crate) tag: Vec<ApHashtag>,
|
||||||
#[serde(skip_serializing_if = "Vec::is_empty", default)]
|
|
||||||
pub(crate) to: Vec<String>,
|
|
||||||
#[serde(skip_serializing_if = "Vec::is_empty", default)]
|
|
||||||
pub(crate) cc: Vec<String>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct ReviewApInput {
|
/// Serialize a local Review into a ReviewObject for AP delivery.
|
||||||
pub ap_id: Url,
|
/// Takes movie metadata explicitly since the handler fetches it separately.
|
||||||
pub actor_url: Url,
|
pub fn review_to_ap_object(
|
||||||
pub movie_title: String,
|
review: &Review,
|
||||||
pub release_year: u16,
|
ap_id: Url,
|
||||||
pub external_metadata_id: Option<String>,
|
actor_url: Url,
|
||||||
pub poster_url: Option<String>,
|
movie_title: String,
|
||||||
pub base_url: String,
|
release_year: u16,
|
||||||
}
|
poster_url: Option<String>,
|
||||||
|
base_url: &str,
|
||||||
pub fn review_to_ap_object(review: &Review, input: ReviewApInput) -> ReviewObject {
|
) -> ReviewObject {
|
||||||
let ReviewApInput {
|
|
||||||
ap_id,
|
|
||||||
actor_url,
|
|
||||||
movie_title,
|
|
||||||
release_year,
|
|
||||||
external_metadata_id,
|
|
||||||
poster_url,
|
|
||||||
base_url,
|
|
||||||
} = input;
|
|
||||||
let stars: String = "\u{2B50}".repeat(review.rating().value() as usize);
|
let stars: String = "\u{2B50}".repeat(review.rating().value() as usize);
|
||||||
let comment_text = review.comment().map(|c| c.value().to_string());
|
let comment_text = review.comment().map(|c| c.value().to_string());
|
||||||
let year_str = if release_year > 0 {
|
let year_str = if release_year > 0 {
|
||||||
@@ -104,7 +57,6 @@ pub fn review_to_ap_object(review: &Review, input: ReviewApInput) -> ReviewObjec
|
|||||||
String::new()
|
String::new()
|
||||||
};
|
};
|
||||||
let watched_str = format!("Watched: {}", review.watched_at().format("%b %-d, %Y"));
|
let watched_str = format!("Watched: {}", review.watched_at().format("%b %-d, %Y"));
|
||||||
let spoiler_flag = review.spoilers() && comment_text.is_some();
|
|
||||||
let content = match &comment_text {
|
let content = match &comment_text {
|
||||||
Some(c) => format!(
|
Some(c) => format!(
|
||||||
"{} {}{}\n{}\n{}",
|
"{} {}{}\n{}\n{}",
|
||||||
@@ -117,7 +69,8 @@ pub fn review_to_ap_object(review: &Review, input: ReviewApInput) -> ReviewObjec
|
|||||||
let tag = vec![
|
let tag = vec![
|
||||||
ApHashtag {
|
ApHashtag {
|
||||||
kind: "Hashtag".to_string(),
|
kind: "Hashtag".to_string(),
|
||||||
href: Url::parse(&format!("{}/tags/moviesdiary", base_url)).expect("valid base_url"),
|
href: Url::parse(&format!("{}/tags/moviesdiary", base_url))
|
||||||
|
.expect("valid base_url"),
|
||||||
name: "#MoviesDiary".to_string(),
|
name: "#MoviesDiary".to_string(),
|
||||||
},
|
},
|
||||||
ApHashtag {
|
ApHashtag {
|
||||||
@@ -127,182 +80,64 @@ pub fn review_to_ap_object(review: &Review, input: ReviewApInput) -> ReviewObjec
|
|||||||
name: format!("#{}", normalized),
|
name: format!("#{}", normalized),
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
let attachment = match &poster_url {
|
|
||||||
Some(url) => vec![ApAttachment {
|
|
||||||
kind: "Image".to_string(),
|
|
||||||
url: url.clone(),
|
|
||||||
media_type: Some("image/jpeg".to_string()),
|
|
||||||
name: Some(movie_title.clone()),
|
|
||||||
}],
|
|
||||||
None => vec![],
|
|
||||||
};
|
|
||||||
|
|
||||||
ReviewObject {
|
ReviewObject {
|
||||||
kind: ActivityStreamsType::default(),
|
kind: NoteType::default(),
|
||||||
id: ap_id,
|
id: ap_id,
|
||||||
attributed_to: actor_url.clone(),
|
attributed_to: actor_url,
|
||||||
content,
|
content,
|
||||||
published: DateTime::from_naive_utc_and_offset(*review.created_at(), Utc),
|
published: DateTime::from_naive_utc_and_offset(*review.created_at(), Utc),
|
||||||
movie_title,
|
movie_title,
|
||||||
release_year,
|
release_year,
|
||||||
external_metadata_id,
|
|
||||||
poster_url,
|
poster_url,
|
||||||
rating: review.rating().value(),
|
rating: review.rating().value(),
|
||||||
comment: comment_text,
|
comment: comment_text,
|
||||||
watched_at: DateTime::from_naive_utc_and_offset(*review.watched_at(), Utc),
|
watched_at: DateTime::from_naive_utc_and_offset(*review.watched_at(), Utc),
|
||||||
watch_medium: review.watch_medium().map(|wm| wm.to_string()),
|
|
||||||
review: true,
|
|
||||||
contains_spoilers: spoiler_flag,
|
|
||||||
summary: spoiler_flag.then(|| "Contains spoilers".to_string()),
|
|
||||||
attachment,
|
|
||||||
tag,
|
tag,
|
||||||
to: vec![AS_PUBLIC.to_string()],
|
|
||||||
cc: vec![format!("{}/followers", actor_url)],
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
#[cfg(test)]
|
||||||
#[serde(rename_all = "camelCase")]
|
mod tests {
|
||||||
pub struct WatchlistObject {
|
use super::*;
|
||||||
#[serde(rename = "type")]
|
|
||||||
pub(crate) kind: ActivityStreamsType,
|
|
||||||
pub(crate) id: Url,
|
|
||||||
pub(crate) attributed_to: Url,
|
|
||||||
pub(crate) content: String,
|
|
||||||
pub(crate) published: chrono::DateTime<chrono::Utc>,
|
|
||||||
pub(crate) movie_title: String,
|
|
||||||
#[serde(default)]
|
|
||||||
pub(crate) release_year: u16,
|
|
||||||
#[serde(default)]
|
|
||||||
pub(crate) external_metadata_id: Option<String>,
|
|
||||||
#[serde(default)]
|
|
||||||
pub(crate) poster_url: Option<String>,
|
|
||||||
#[serde(default)]
|
|
||||||
pub(crate) tag: Vec<ApHashtag>,
|
|
||||||
/// Discriminator so Movies Diary instances distinguish this from a review Note.
|
|
||||||
/// Non-Movies-Diary apps ignore unknown fields.
|
|
||||||
#[serde(default)]
|
|
||||||
pub(crate) watchlist_entry: bool,
|
|
||||||
#[serde(skip_serializing_if = "Vec::is_empty", default)]
|
|
||||||
pub(crate) to: Vec<String>,
|
|
||||||
#[serde(skip_serializing_if = "Vec::is_empty", default)]
|
|
||||||
pub(crate) cc: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct WatchlistApInput {
|
#[test]
|
||||||
pub ap_id: Url,
|
fn normalize_hashtag_strips_non_alphanumeric() {
|
||||||
pub actor_url: Url,
|
assert_eq!(normalize_hashtag("The Dark Knight"), "TheDarkKnight");
|
||||||
pub movie_title: String,
|
assert_eq!(normalize_hashtag("Schindler's List"), "SchindlersList");
|
||||||
pub release_year: u16,
|
assert_eq!(normalize_hashtag("2001: A Space Odyssey"), "2001ASpaceOdyssey");
|
||||||
pub external_metadata_id: Option<String>,
|
}
|
||||||
pub poster_url: Option<String>,
|
|
||||||
pub added_at: chrono::DateTime<chrono::Utc>,
|
|
||||||
pub base_url: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn watchlist_to_ap_object(input: WatchlistApInput) -> WatchlistObject {
|
#[test]
|
||||||
let WatchlistApInput {
|
fn review_to_ap_object_includes_two_hashtags() {
|
||||||
ap_id,
|
use chrono::NaiveDateTime;
|
||||||
actor_url,
|
use domain::{
|
||||||
movie_title,
|
models::{Review, ReviewSource},
|
||||||
release_year,
|
value_objects::{MovieId, Rating, ReviewId, UserId},
|
||||||
external_metadata_id,
|
};
|
||||||
poster_url,
|
|
||||||
added_at,
|
|
||||||
base_url,
|
|
||||||
} = input;
|
|
||||||
let year_str = if release_year > 0 {
|
|
||||||
format!(" ({})", release_year)
|
|
||||||
} else {
|
|
||||||
String::new()
|
|
||||||
};
|
|
||||||
let content = format!("📋 {}{} — want to watch", movie_title, year_str);
|
|
||||||
let normalized = normalize_hashtag(&movie_title);
|
|
||||||
let tag = vec![
|
|
||||||
ApHashtag {
|
|
||||||
kind: "Hashtag".to_string(),
|
|
||||||
href: Url::parse(&format!("{}/tags/moviesdiary", base_url)).expect("valid base_url"),
|
|
||||||
name: "#MoviesDiary".to_string(),
|
|
||||||
},
|
|
||||||
ApHashtag {
|
|
||||||
kind: "Hashtag".to_string(),
|
|
||||||
href: Url::parse(&format!("{}/tags/{}", base_url, normalized.to_lowercase()))
|
|
||||||
.expect("valid base_url"),
|
|
||||||
name: format!("#{}", normalized),
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
WatchlistObject {
|
let review = Review::from_persistence(
|
||||||
kind: ActivityStreamsType::default(),
|
ReviewId::generate(),
|
||||||
id: ap_id,
|
MovieId::from_uuid(uuid::Uuid::new_v4()),
|
||||||
attributed_to: actor_url.clone(),
|
UserId::from_uuid(uuid::Uuid::new_v4()),
|
||||||
content,
|
Rating::new(4).unwrap(),
|
||||||
published: added_at,
|
None,
|
||||||
movie_title,
|
NaiveDateTime::parse_from_str("2024-01-01 00:00:00", "%Y-%m-%d %H:%M:%S").unwrap(),
|
||||||
release_year,
|
NaiveDateTime::parse_from_str("2024-01-01 00:00:00", "%Y-%m-%d %H:%M:%S").unwrap(),
|
||||||
external_metadata_id,
|
ReviewSource::Local,
|
||||||
poster_url,
|
);
|
||||||
tag,
|
let obj = review_to_ap_object(
|
||||||
watchlist_entry: true,
|
&review,
|
||||||
to: vec![AS_PUBLIC.to_string()],
|
"https://example.com/reviews/1".parse().unwrap(),
|
||||||
cc: vec![format!("{}/followers", actor_url)],
|
"https://example.com/users/1".parse().unwrap(),
|
||||||
}
|
"Dune".to_string(),
|
||||||
}
|
2021,
|
||||||
|
None,
|
||||||
// ── Goal object ──────────────────────────────────────────────────────────────
|
"https://example.com",
|
||||||
|
);
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
assert_eq!(obj.tag.len(), 2);
|
||||||
#[serde(rename_all = "camelCase")]
|
let names: Vec<&str> = obj.tag.iter().map(|t| t.name.as_str()).collect();
|
||||||
pub struct GoalObject {
|
assert!(names.contains(&"#MoviesDiary"));
|
||||||
#[serde(rename = "type")]
|
assert!(names.contains(&"#Dune"));
|
||||||
pub(crate) kind: ActivityStreamsType,
|
|
||||||
pub(crate) id: Url,
|
|
||||||
pub(crate) attributed_to: Url,
|
|
||||||
pub(crate) content: String,
|
|
||||||
pub(crate) published: chrono::DateTime<chrono::Utc>,
|
|
||||||
pub(crate) goal_year: u16,
|
|
||||||
pub(crate) goal_target: u32,
|
|
||||||
pub(crate) goal_current: u32,
|
|
||||||
#[serde(default)]
|
|
||||||
pub(crate) goal: bool,
|
|
||||||
#[serde(default)]
|
|
||||||
pub(crate) tag: Vec<ApHashtag>,
|
|
||||||
#[serde(skip_serializing_if = "Vec::is_empty", default)]
|
|
||||||
pub(crate) to: Vec<String>,
|
|
||||||
#[serde(skip_serializing_if = "Vec::is_empty", default)]
|
|
||||||
pub(crate) cc: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn goal_to_ap_object(
|
|
||||||
ap_id: Url,
|
|
||||||
actor_url: Url,
|
|
||||||
year: u16,
|
|
||||||
target: u32,
|
|
||||||
current: u32,
|
|
||||||
base_url: &str,
|
|
||||||
) -> GoalObject {
|
|
||||||
let content = format!(
|
|
||||||
"🎯 Goal: Watch {} movies in {} ({}/{})",
|
|
||||||
target, year, current, target
|
|
||||||
);
|
|
||||||
let tag = vec![ApHashtag {
|
|
||||||
kind: "Hashtag".to_string(),
|
|
||||||
href: Url::parse(&format!("{}/tags/moviesdiary", base_url)).expect("valid base_url"),
|
|
||||||
name: "#MoviesDiary".to_string(),
|
|
||||||
}];
|
|
||||||
|
|
||||||
GoalObject {
|
|
||||||
kind: ActivityStreamsType::default(),
|
|
||||||
id: ap_id,
|
|
||||||
attributed_to: actor_url.clone(),
|
|
||||||
content,
|
|
||||||
published: chrono::Utc::now(),
|
|
||||||
goal_year: year,
|
|
||||||
goal_target: target,
|
|
||||||
goal_current: current,
|
|
||||||
goal: true,
|
|
||||||
tag,
|
|
||||||
to: vec![AS_PUBLIC.to_string()],
|
|
||||||
cc: vec![format!("{}/followers", actor_url)],
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
157
crates/adapters/activitypub/src/port.rs
Normal file
157
crates/adapters/activitypub/src/port.rs
Normal file
@@ -0,0 +1,157 @@
|
|||||||
|
use async_trait::async_trait;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use activitypub_base::{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_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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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![])
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,36 +1,29 @@
|
|||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use chrono::NaiveDateTime;
|
use chrono::NaiveDateTime;
|
||||||
use domain::{events::DomainEvent, models::Review};
|
use domain::models::Review;
|
||||||
|
|
||||||
pub struct RemoteReviewUpdate<'a> {
|
|
||||||
pub ap_id: &'a str,
|
|
||||||
pub actor_url: &'a str,
|
|
||||||
pub rating: u8,
|
|
||||||
pub comment: Option<&'a str>,
|
|
||||||
pub watched_at: NaiveDateTime,
|
|
||||||
pub poster_url: Option<&'a str>,
|
|
||||||
pub watch_medium: Option<&'a str>,
|
|
||||||
pub spoilers: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct NewRemoteReview<'a> {
|
|
||||||
pub review: &'a Review,
|
|
||||||
pub ap_id: &'a str,
|
|
||||||
pub movie_title: &'a str,
|
|
||||||
pub release_year: u16,
|
|
||||||
pub external_metadata_id: Option<&'a str>,
|
|
||||||
pub poster_url: Option<&'a str>,
|
|
||||||
pub events: &'a [DomainEvent],
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
pub trait RemoteReviewRepository: Send + Sync {
|
pub trait RemoteReviewRepository: Send + Sync {
|
||||||
async fn save_remote_review(&self, new: NewRemoteReview<'_>) -> Result<()>;
|
async fn save_remote_review(
|
||||||
|
&self,
|
||||||
|
review: &Review,
|
||||||
|
ap_id: &str,
|
||||||
|
movie_title: &str,
|
||||||
|
release_year: u16,
|
||||||
|
poster_url: Option<&str>,
|
||||||
|
) -> Result<()>;
|
||||||
|
|
||||||
async fn delete_remote_review(&self, ap_id: &str, actor_url: &str) -> Result<()>;
|
async fn delete_remote_review(&self, ap_id: &str, actor_url: &str) -> Result<()>;
|
||||||
|
|
||||||
async fn update_remote_review(&self, update: RemoteReviewUpdate<'_>) -> Result<()>;
|
async fn update_remote_review(
|
||||||
|
&self,
|
||||||
|
ap_id: &str,
|
||||||
|
actor_url: &str,
|
||||||
|
rating: u8,
|
||||||
|
comment: Option<&str>,
|
||||||
|
watched_at: NaiveDateTime,
|
||||||
|
) -> Result<()>;
|
||||||
|
|
||||||
async fn delete_by_actor(&self, actor_url: &str) -> Result<()>;
|
async fn delete_by_actor(&self, actor_url: &str) -> Result<()>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,187 +1,197 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use activitypub_base::ApObjectHandler;
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use domain::{
|
use domain::{
|
||||||
events::DomainEvent,
|
models::{Review, ReviewSource},
|
||||||
models::ReviewSource,
|
ports::{DiaryRepository, MovieRepository},
|
||||||
ports::{DiaryQuery, LocalApContentQuery, MovieQuery},
|
value_objects::{Comment, MovieId, Rating, ReviewId, UserId},
|
||||||
value_objects::{
|
|
||||||
Comment, ExternalMetadataId, InstanceIdentity, MovieId, Rating, ReviewId, UserId,
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
use k_ap::{AS_PUBLIC, ApContentReader, ApObjectHandler, LocalObject};
|
|
||||||
use url::Url;
|
use url::Url;
|
||||||
|
|
||||||
use crate::objects::{ReviewApInput, ReviewObject, review_to_ap_object};
|
use crate::objects::{ReviewObject, review_to_ap_object};
|
||||||
use crate::remote_review_repository::{NewRemoteReview, RemoteReviewRepository};
|
use crate::remote_review_repository::RemoteReviewRepository;
|
||||||
use crate::urls::{actor_url, review_url};
|
use crate::urls::{actor_url, review_url};
|
||||||
|
|
||||||
pub struct ReviewObjectHandler {
|
pub struct ReviewObjectHandler {
|
||||||
pub content_query: Arc<dyn LocalApContentQuery>,
|
pub movie_repository: Arc<dyn MovieRepository>,
|
||||||
pub movie_repo: Arc<dyn MovieQuery>,
|
pub diary_repository: Arc<dyn DiaryRepository>,
|
||||||
pub diary_repo: Arc<dyn DiaryQuery>,
|
|
||||||
pub review_store: Arc<dyn RemoteReviewRepository>,
|
pub review_store: Arc<dyn RemoteReviewRepository>,
|
||||||
pub instance: InstanceIdentity,
|
pub base_url: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl ApContentReader for ReviewObjectHandler {
|
impl ApObjectHandler for ReviewObjectHandler {
|
||||||
|
async fn get_local_objects_for_user(
|
||||||
|
&self,
|
||||||
|
user_id: uuid::Uuid,
|
||||||
|
) -> anyhow::Result<Vec<(Url, serde_json::Value)>> {
|
||||||
|
let domain_user_id = UserId::from_uuid(user_id);
|
||||||
|
let history = self
|
||||||
|
.diary_repository
|
||||||
|
.get_user_history(&domain_user_id)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let mut results = Vec::new();
|
||||||
|
for entry in history {
|
||||||
|
let review = entry.review();
|
||||||
|
if !matches!(review.source(), ReviewSource::Local) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let ap_id = review_url(&self.base_url, review.id());
|
||||||
|
let actor_url = actor_url(&self.base_url, user_id);
|
||||||
|
|
||||||
|
let movie = self
|
||||||
|
.movie_repository
|
||||||
|
.get_movie_by_id(review.movie_id())
|
||||||
|
.await
|
||||||
|
.ok()
|
||||||
|
.flatten();
|
||||||
|
let movie_title = movie
|
||||||
|
.as_ref()
|
||||||
|
.map(|m| m.title().value().to_string())
|
||||||
|
.unwrap_or_else(|| "Unknown".to_string());
|
||||||
|
let release_year = movie
|
||||||
|
.as_ref()
|
||||||
|
.map(|m| m.release_year().value())
|
||||||
|
.unwrap_or(0);
|
||||||
|
let poster_url = movie
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|m| m.poster_path())
|
||||||
|
.map(|p| format!("{}/images/{}", self.base_url, p.value()));
|
||||||
|
|
||||||
|
let obj = review_to_ap_object(
|
||||||
|
review,
|
||||||
|
ap_id.clone(),
|
||||||
|
actor_url,
|
||||||
|
movie_title,
|
||||||
|
release_year,
|
||||||
|
poster_url,
|
||||||
|
&self.base_url,
|
||||||
|
);
|
||||||
|
let json = serde_json::to_value(obj)?;
|
||||||
|
results.push((ap_id, json));
|
||||||
|
}
|
||||||
|
Ok(results)
|
||||||
|
}
|
||||||
|
|
||||||
async fn get_local_objects_page(
|
async fn get_local_objects_page(
|
||||||
&self,
|
&self,
|
||||||
user_id: uuid::Uuid,
|
user_id: uuid::Uuid,
|
||||||
before: Option<chrono::DateTime<chrono::Utc>>,
|
before: Option<chrono::DateTime<chrono::Utc>>,
|
||||||
limit: usize,
|
limit: usize,
|
||||||
) -> anyhow::Result<Vec<LocalObject>> {
|
) -> anyhow::Result<Vec<(url::Url, serde_json::Value, chrono::DateTime<chrono::Utc>)>> {
|
||||||
let domain_user_id = UserId::from_uuid(user_id);
|
use domain::value_objects::UserId;
|
||||||
let before_naive = before.map(|dt| dt.naive_utc());
|
|
||||||
let entries = self
|
let domain_user_id = UserId::from_uuid(user_id);
|
||||||
.content_query
|
let history = self
|
||||||
.get_local_reviews_page(&domain_user_id, before_naive, limit)
|
.diary_repository
|
||||||
.await
|
.get_user_history(&domain_user_id)
|
||||||
.map_err(|e| anyhow::anyhow!(e.to_string()))?;
|
.await?;
|
||||||
|
|
||||||
let actor = actor_url(&self.instance, user_id);
|
|
||||||
let mut results = Vec::new();
|
let mut results = Vec::new();
|
||||||
for entry in entries {
|
for entry in history {
|
||||||
let review = entry.review();
|
let review = entry.review();
|
||||||
|
if !matches!(review.source(), ReviewSource::Local) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
let published =
|
let published =
|
||||||
chrono::DateTime::from_naive_utc_and_offset(*review.watched_at(), chrono::Utc);
|
chrono::DateTime::from_naive_utc_and_offset(*review.watched_at(), chrono::Utc);
|
||||||
let movie = entry.movie();
|
|
||||||
let ap_id = review_url(&self.instance, review.id());
|
if let Some(cutoff) = before {
|
||||||
|
if published >= cutoff {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let ap_id = review_url(&self.base_url, review.id());
|
||||||
|
let actor_url = actor_url(&self.base_url, user_id);
|
||||||
|
|
||||||
|
let movie = self
|
||||||
|
.movie_repository
|
||||||
|
.get_movie_by_id(review.movie_id())
|
||||||
|
.await
|
||||||
|
.ok()
|
||||||
|
.flatten();
|
||||||
|
let movie_title = movie
|
||||||
|
.as_ref()
|
||||||
|
.map(|m| m.title().value().to_string())
|
||||||
|
.unwrap_or_else(|| "Unknown".to_string());
|
||||||
|
let release_year = movie.as_ref().map(|m| m.release_year().value()).unwrap_or(0);
|
||||||
let poster_url = movie
|
let poster_url = movie
|
||||||
.poster_path()
|
.as_ref()
|
||||||
.map(|p| self.instance.image_url_for(p.value()));
|
.and_then(|m| m.poster_path())
|
||||||
|
.map(|p| format!("{}/images/{}", self.base_url, p.value()));
|
||||||
|
|
||||||
let obj = review_to_ap_object(
|
let obj = review_to_ap_object(
|
||||||
review,
|
review,
|
||||||
ReviewApInput {
|
ap_id.clone(),
|
||||||
ap_id: ap_id.clone(),
|
actor_url,
|
||||||
actor_url: actor.clone(),
|
movie_title,
|
||||||
movie_title: movie.title().value().to_string(),
|
release_year,
|
||||||
release_year: movie.release_year().value(),
|
poster_url,
|
||||||
external_metadata_id: movie
|
&self.base_url,
|
||||||
.external_metadata_id()
|
|
||||||
.map(|id| id.value().to_string()),
|
|
||||||
poster_url,
|
|
||||||
base_url: self.instance.base_url().to_string(),
|
|
||||||
},
|
|
||||||
);
|
);
|
||||||
let follower_cc = format!("{}/followers", actor);
|
let json = serde_json::to_value(obj)?;
|
||||||
results.push(LocalObject {
|
results.push((ap_id, json, published));
|
||||||
ap_id,
|
|
||||||
object: serde_json::to_value(obj)?,
|
if results.len() >= limit {
|
||||||
published_at: published,
|
break;
|
||||||
to: vec![AS_PUBLIC.to_string()],
|
}
|
||||||
cc: vec![follower_cc],
|
|
||||||
bto: vec![],
|
|
||||||
bcc: vec![],
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
Ok(results)
|
Ok(results)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn count_local_posts(&self) -> anyhow::Result<u64> {
|
|
||||||
self.diary_repo
|
|
||||||
.count_local_posts()
|
|
||||||
.await
|
|
||||||
.map_err(|e| anyhow::anyhow!(e.to_string()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl ApObjectHandler for ReviewObjectHandler {
|
|
||||||
async fn on_create(
|
async fn on_create(
|
||||||
&self,
|
&self,
|
||||||
_ap_id: &Url,
|
_ap_id: &Url,
|
||||||
_actor_url: &Url,
|
_actor_url: &Url,
|
||||||
object: serde_json::Value,
|
object: serde_json::Value,
|
||||||
) -> anyhow::Result<()> {
|
) -> anyhow::Result<()> {
|
||||||
let mut obj: ReviewObject = match serde_json::from_value(object) {
|
let obj: ReviewObject = match serde_json::from_value(object) {
|
||||||
Ok(o) => o,
|
Ok(o) => o,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
tracing::warn!("ignoring unrecognized Create object: {}", e);
|
tracing::debug!("ignoring unrecognized Create object: {}", e);
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
obj.movie_title = ammonia::clean(&obj.movie_title);
|
|
||||||
obj.comment = obj.comment.map(|c| ammonia::clean(&c));
|
|
||||||
|
|
||||||
let actor_url_str = obj.attributed_to.to_string();
|
let actor_url_str = obj.attributed_to.to_string();
|
||||||
let review_id = ReviewId::generate();
|
let review_id = ReviewId::generate();
|
||||||
let movie_id = if let Some(ref ext_id) = obj.external_metadata_id {
|
let movie_id = MovieId::from_uuid(uuid::Uuid::new_v5(
|
||||||
let found = if let Ok(ext_meta_id) = ExternalMetadataId::new(ext_id.clone()) {
|
&uuid::Uuid::NAMESPACE_URL,
|
||||||
self.movie_repo
|
obj.movie_title.as_bytes(),
|
||||||
.get_movie_by_external_id(&ext_meta_id)
|
));
|
||||||
.await
|
|
||||||
.ok()
|
|
||||||
.flatten()
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
match found {
|
|
||||||
Some(movie) => movie.id().clone(),
|
|
||||||
None => MovieId::from_uuid(uuid::Uuid::new_v5(
|
|
||||||
&uuid::Uuid::NAMESPACE_URL,
|
|
||||||
ext_id.as_bytes(),
|
|
||||||
)),
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
MovieId::from_uuid(uuid::Uuid::new_v5(
|
|
||||||
&uuid::Uuid::NAMESPACE_URL,
|
|
||||||
format!("{}:{}", obj.movie_title, obj.release_year).as_bytes(),
|
|
||||||
))
|
|
||||||
};
|
|
||||||
let user_id = UserId::from_uuid(uuid::Uuid::new_v5(
|
let user_id = UserId::from_uuid(uuid::Uuid::new_v5(
|
||||||
&uuid::Uuid::NAMESPACE_URL,
|
&uuid::Uuid::NAMESPACE_URL,
|
||||||
actor_url_str.as_bytes(),
|
actor_url_str.as_bytes(),
|
||||||
));
|
));
|
||||||
let rating = Rating::new(obj.rating.min(5))?;
|
let rating = Rating::new(obj.rating.min(5))?;
|
||||||
let comment = obj.comment.map(Comment::new).transpose()?;
|
let comment = obj.comment.map(Comment::new).transpose()?;
|
||||||
let watch_medium = obj
|
|
||||||
.watch_medium
|
|
||||||
.as_deref()
|
|
||||||
.map(|s| s.parse())
|
|
||||||
.transpose()
|
|
||||||
.unwrap_or(None);
|
|
||||||
|
|
||||||
let review = domain::models::Review::from_persistence(domain::models::PersistedReview {
|
let review = Review::from_persistence(
|
||||||
id: review_id,
|
review_id,
|
||||||
movie_id: movie_id.clone(),
|
movie_id,
|
||||||
user_id,
|
user_id,
|
||||||
rating,
|
rating,
|
||||||
comment,
|
comment,
|
||||||
watched_at: obj.watched_at.naive_utc(),
|
obj.watched_at.naive_utc(),
|
||||||
created_at: obj.published.naive_utc(),
|
obj.published.naive_utc(),
|
||||||
source: ReviewSource::Remote {
|
ReviewSource::Remote {
|
||||||
actor_url: actor_url_str,
|
actor_url: actor_url_str,
|
||||||
},
|
},
|
||||||
watch_medium,
|
);
|
||||||
spoilers: obj.contains_spoilers,
|
|
||||||
});
|
|
||||||
|
|
||||||
let events: Vec<DomainEvent> = obj
|
|
||||||
.external_metadata_id
|
|
||||||
.as_ref()
|
|
||||||
.and_then(|ext_id| ExternalMetadataId::new(ext_id.clone()).ok())
|
|
||||||
.map(
|
|
||||||
|external_metadata_id| DomainEvent::MovieEnrichmentRequested {
|
|
||||||
movie_id: movie_id.clone(),
|
|
||||||
external_metadata_id,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.into_iter()
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
self.review_store
|
self.review_store
|
||||||
.save_remote_review(NewRemoteReview {
|
.save_remote_review(
|
||||||
review: &review,
|
&review,
|
||||||
ap_id: obj.id.as_str(),
|
obj.id.as_str(),
|
||||||
movie_title: &obj.movie_title,
|
&obj.movie_title,
|
||||||
release_year: obj.release_year,
|
obj.release_year,
|
||||||
external_metadata_id: obj.external_metadata_id.as_deref(),
|
obj.poster_url.as_deref(),
|
||||||
poster_url: obj.poster_url.as_deref(),
|
)
|
||||||
events: &events,
|
|
||||||
})
|
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -193,31 +203,26 @@ impl ApObjectHandler for ReviewObjectHandler {
|
|||||||
actor_url: &Url,
|
actor_url: &Url,
|
||||||
object: serde_json::Value,
|
object: serde_json::Value,
|
||||||
) -> anyhow::Result<()> {
|
) -> anyhow::Result<()> {
|
||||||
let mut obj: ReviewObject = match serde_json::from_value(object) {
|
let obj: ReviewObject = match serde_json::from_value(object) {
|
||||||
Ok(o) => o,
|
Ok(o) => o,
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
tracing::warn!(actor = %actor_url, "ignoring non-review Update activity");
|
tracing::debug!(actor = %actor_url, "ignoring non-review Update activity");
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
obj.movie_title = ammonia::clean(&obj.movie_title);
|
|
||||||
obj.comment = obj.comment.map(|c| ammonia::clean(&c));
|
|
||||||
|
|
||||||
if obj.attributed_to != *actor_url {
|
if obj.attributed_to != *actor_url {
|
||||||
anyhow::bail!("update actor does not match object attributed_to");
|
anyhow::bail!("update actor does not match object attributed_to");
|
||||||
}
|
}
|
||||||
|
|
||||||
self.review_store
|
self.review_store
|
||||||
.update_remote_review(crate::remote_review_repository::RemoteReviewUpdate {
|
.update_remote_review(
|
||||||
ap_id: ap_id.as_str(),
|
ap_id.as_str(),
|
||||||
actor_url: actor_url.as_str(),
|
actor_url.as_str(),
|
||||||
rating: obj.rating.min(5),
|
obj.rating.min(5),
|
||||||
comment: obj.comment.as_deref(),
|
obj.comment.as_deref(),
|
||||||
watched_at: obj.watched_at.naive_utc(),
|
obj.watched_at.naive_utc(),
|
||||||
poster_url: obj.poster_url.as_deref(),
|
)
|
||||||
watch_medium: obj.watch_medium.as_deref(),
|
|
||||||
spoilers: obj.contains_spoilers,
|
|
||||||
})
|
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -233,36 +238,10 @@ impl ApObjectHandler for ReviewObjectHandler {
|
|||||||
self.review_store.delete_by_actor(actor_url.as_str()).await
|
self.review_store.delete_by_actor(actor_url.as_str()).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn on_like(&self, _object_url: &Url, _actor_url: &Url) -> anyhow::Result<()> {
|
async fn count_local_posts(&self) -> anyhow::Result<u64> {
|
||||||
Ok(())
|
self.diary_repository
|
||||||
}
|
.count_local_posts()
|
||||||
|
.await
|
||||||
async fn on_announce_received(
|
.map_err(|e| anyhow::anyhow!(e.to_string()))
|
||||||
&self,
|
|
||||||
_object_url: &Url,
|
|
||||||
_actor_url: &Url,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_announce_of_remote(
|
|
||||||
&self,
|
|
||||||
_object_url: &Url,
|
|
||||||
_actor_url: &Url,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_unlike(&self, _object_url: &Url, _actor_url: &Url) -> anyhow::Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_mention(
|
|
||||||
&self,
|
|
||||||
_thought_ap_id: &Url,
|
|
||||||
_mentioned_user_uuid: uuid::Uuid,
|
|
||||||
_actor_url: &Url,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,261 +0,0 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use domain::{
|
|
||||||
errors::DomainError,
|
|
||||||
events::DomainEvent,
|
|
||||||
ports::{
|
|
||||||
BlockQuery, EventPublisher, 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,
|
|
||||||
event_publisher: Arc<dyn EventPublisher>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CompositeSocialAdapter {
|
|
||||||
pub fn new(
|
|
||||||
local: Arc<dyn LocalSocial>,
|
|
||||||
ap_service: Arc<ActivityPubService>,
|
|
||||||
user_repo: Arc<dyn UserRepository>,
|
|
||||||
instance: InstanceIdentity,
|
|
||||||
event_publisher: Arc<dyn EventPublisher>,
|
|
||||||
) -> Self {
|
|
||||||
Self {
|
|
||||||
local,
|
|
||||||
ap_service,
|
|
||||||
user_repo,
|
|
||||||
instance,
|
|
||||||
event_publisher,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn announce(&self, events: &[DomainEvent]) {
|
|
||||||
for event in events {
|
|
||||||
if let Err(e) = self.event_publisher.publish(event).await {
|
|
||||||
tracing::warn!("failed to publish {event:?} after k_ap write: {e}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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,
|
|
||||||
events: &[DomainEvent],
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
let identity = self.local.resolve_target(target).await?;
|
|
||||||
|
|
||||||
if let SocialIdentity::Local(_) = identity {
|
|
||||||
return self
|
|
||||||
.local
|
|
||||||
.follow_resolved(follower, &identity, events)
|
|
||||||
.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)?;
|
|
||||||
self.announce(events).await;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn unfollow(
|
|
||||||
&self,
|
|
||||||
follower: &UserId,
|
|
||||||
target: &SocialIdentity,
|
|
||||||
events: &[DomainEvent],
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
match target {
|
|
||||||
SocialIdentity::Local(_) => self.local.unfollow(follower, target, events).await,
|
|
||||||
SocialIdentity::Remote { .. } => {
|
|
||||||
self.ap_service
|
|
||||||
.unfollow(follower.value(), &self.instance.actor_url_of(target))
|
|
||||||
.await
|
|
||||||
.map_err(ap_err)?;
|
|
||||||
self.announce(events).await;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn accept_follow(
|
|
||||||
&self,
|
|
||||||
owner: &UserId,
|
|
||||||
requester: &SocialIdentity,
|
|
||||||
events: &[DomainEvent],
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
match requester {
|
|
||||||
SocialIdentity::Local(_) => self.local.accept_follow(owner, requester, events).await,
|
|
||||||
SocialIdentity::Remote { .. } => {
|
|
||||||
self.ap_service
|
|
||||||
.accept_follower(owner.value(), &self.instance.actor_url_of(requester))
|
|
||||||
.await
|
|
||||||
.map_err(ap_err)?;
|
|
||||||
self.announce(events).await;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn reject_follow(
|
|
||||||
&self,
|
|
||||||
owner: &UserId,
|
|
||||||
requester: &SocialIdentity,
|
|
||||||
events: &[DomainEvent],
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
match requester {
|
|
||||||
SocialIdentity::Local(_) => self.local.reject_follow(owner, requester, events).await,
|
|
||||||
SocialIdentity::Remote { .. } => {
|
|
||||||
self.ap_service
|
|
||||||
.reject_follower(owner.value(), &self.instance.actor_url_of(requester))
|
|
||||||
.await
|
|
||||||
.map_err(ap_err)?;
|
|
||||||
self.announce(events).await;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn remove_follower(
|
|
||||||
&self,
|
|
||||||
owner: &UserId,
|
|
||||||
follower: &SocialIdentity,
|
|
||||||
events: &[DomainEvent],
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
match follower {
|
|
||||||
SocialIdentity::Local(_) => self.local.remove_follower(owner, follower, events).await,
|
|
||||||
SocialIdentity::Remote { .. } => {
|
|
||||||
self.ap_service
|
|
||||||
.remove_follower(owner.value(), &self.instance.actor_url_of(follower))
|
|
||||||
.await
|
|
||||||
.map_err(ap_err)?;
|
|
||||||
self.announce(events).await;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn block(
|
|
||||||
&self,
|
|
||||||
blocker: &UserId,
|
|
||||||
target: &SocialIdentity,
|
|
||||||
events: &[DomainEvent],
|
|
||||||
) -> 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)?;
|
|
||||||
self.announce(events).await;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn unblock(
|
|
||||||
&self,
|
|
||||||
blocker: &UserId,
|
|
||||||
target: &SocialIdentity,
|
|
||||||
events: &[DomainEvent],
|
|
||||||
) -> 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)?;
|
|
||||||
self.announce(events).await;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use axum::{
|
|
||||||
extract::{Request, State},
|
|
||||||
http::StatusCode,
|
|
||||||
middleware::Next,
|
|
||||||
response::{IntoResponse, Response},
|
|
||||||
};
|
|
||||||
use domain::{ports::UserRepository, value_objects::UserId};
|
|
||||||
|
|
||||||
pub async fn tombstone_gate(
|
|
||||||
State(users): State<Arc<dyn UserRepository>>,
|
|
||||||
request: Request,
|
|
||||||
next: Next,
|
|
||||||
) -> Response {
|
|
||||||
if let Some(id) = gated_user(request.uri().path())
|
|
||||||
&& matches!(
|
|
||||||
users.find_tombstoned_by_id(&UserId::from_uuid(id)).await,
|
|
||||||
Ok(Some(_))
|
|
||||||
)
|
|
||||||
{
|
|
||||||
return StatusCode::GONE.into_response();
|
|
||||||
}
|
|
||||||
next.run(request).await
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn gated_user(path: &str) -> Option<uuid::Uuid> {
|
|
||||||
let rest = path.strip_prefix("/users/")?;
|
|
||||||
let (id, endpoint) = rest.split_once('/')?;
|
|
||||||
(!endpoint.is_empty()).then_some(())?;
|
|
||||||
uuid::Uuid::parse_str(id).ok()
|
|
||||||
}
|
|
||||||
@@ -1,40 +1,14 @@
|
|||||||
use domain::value_objects::{InstanceIdentity, ReviewId, UserId};
|
use domain::value_objects::ReviewId;
|
||||||
use url::Url;
|
use url::Url;
|
||||||
|
|
||||||
pub fn actor_url(instance: &InstanceIdentity, user_id: uuid::Uuid) -> Url {
|
/// Builds the canonical actor URL: `{base_url}/users/{user_id}`
|
||||||
Url::parse(&instance.actor_url_for(&UserId::from_uuid(user_id)))
|
pub fn actor_url(base_url: &str, user_id: uuid::Uuid) -> Url {
|
||||||
|
Url::parse(&format!("{}/users/{}", base_url, user_id))
|
||||||
.expect("base_url is always a valid URL prefix")
|
.expect("base_url is always a valid URL prefix")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn review_url(instance: &InstanceIdentity, review_id: &ReviewId) -> Url {
|
/// Builds the canonical review URL: `{base_url}/reviews/{review_id}`
|
||||||
Url::parse(&format!(
|
pub fn review_url(base_url: &str, review_id: &ReviewId) -> Url {
|
||||||
"{}/reviews/{}",
|
Url::parse(&format!("{}/reviews/{}", base_url, review_id.value()))
|
||||||
instance.base_url(),
|
.expect("base_url is always a valid URL prefix")
|
||||||
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")
|
|
||||||
}
|
|
||||||
|
|
||||||
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")
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,61 +1,31 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use activitypub_base::{ApUser, ApUserRepository};
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use domain::{
|
use domain::{ports::UserRepository, value_objects::UserId};
|
||||||
ports::UserRepository,
|
|
||||||
value_objects::{InstanceIdentity, UserId},
|
|
||||||
};
|
|
||||||
use k_ap::{ApProfileField, ApUser, ApUserRepository};
|
|
||||||
use url::Url;
|
use url::Url;
|
||||||
|
|
||||||
pub struct DomainUserRepoAdapter {
|
pub struct DomainUserRepoAdapter {
|
||||||
pub repo: Arc<dyn UserRepository>,
|
pub repo: Arc<dyn UserRepository>,
|
||||||
pub instance: InstanceIdentity,
|
pub base_url: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DomainUserRepoAdapter {
|
impl DomainUserRepoAdapter {
|
||||||
pub fn new(repo: Arc<dyn UserRepository>, instance: InstanceIdentity) -> Self {
|
pub fn new(repo: Arc<dyn UserRepository>, base_url: String) -> Self {
|
||||||
Self { repo, instance }
|
Self { repo, base_url }
|
||||||
}
|
}
|
||||||
|
|
||||||
fn build_user(&self, u: &domain::models::User) -> ApUser {
|
fn build_user(&self, u: &domain::models::User) -> ApUser {
|
||||||
let avatar_url = u
|
let avatar_url = u.avatar_path().and_then(|p| {
|
||||||
.avatar_path()
|
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
|
let profile_url = Url::parse(&format!("{}/u/{}", self.base_url, u.username().value())).ok();
|
||||||
.banner_path()
|
|
||||||
.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 {
|
ApUser {
|
||||||
id: u.id().value(),
|
id: u.id().value(),
|
||||||
username: u.username().value().to_string(),
|
username: u.username().value().to_string(),
|
||||||
display_name: u.display_name().map(|s| s.to_string()),
|
|
||||||
bio: u.bio().map(|s| s.to_string()),
|
bio: u.bio().map(|s| s.to_string()),
|
||||||
avatar_url,
|
avatar_url,
|
||||||
banner_url,
|
|
||||||
also_known_as: u
|
|
||||||
.also_known_as()
|
|
||||||
.map(|s| vec![s.to_string()])
|
|
||||||
.unwrap_or_default(),
|
|
||||||
profile_url,
|
profile_url,
|
||||||
attachment: u
|
|
||||||
.profile_fields()
|
|
||||||
.iter()
|
|
||||||
.map(|f| ApProfileField {
|
|
||||||
name: f.name.clone(),
|
|
||||||
value: f.value.clone(),
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
manually_approves_followers: true,
|
|
||||||
discoverable: true,
|
|
||||||
actor_type: Default::default(),
|
|
||||||
featured_url: Url::parse(&format!("{}/featured", self.instance.actor_url_for(u.id())))
|
|
||||||
.ok(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -64,32 +34,17 @@ impl DomainUserRepoAdapter {
|
|||||||
impl ApUserRepository for DomainUserRepoAdapter {
|
impl ApUserRepository for DomainUserRepoAdapter {
|
||||||
async fn find_by_id(&self, id: uuid::Uuid) -> anyhow::Result<Option<ApUser>> {
|
async fn find_by_id(&self, id: uuid::Uuid) -> anyhow::Result<Option<ApUser>> {
|
||||||
let user_id = UserId::from_uuid(id);
|
let user_id = UserId::from_uuid(id);
|
||||||
let user = match self.repo.find_by_id(&user_id).await? {
|
Ok(self.repo.find_by_id(&user_id).await?.as_ref().map(|u| self.build_user(u)))
|
||||||
Some(u) => u,
|
|
||||||
None => match self.repo.find_tombstoned_by_id(&user_id).await? {
|
|
||||||
Some(u) => u,
|
|
||||||
None => return Ok(None),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
Ok(Some(self.build_user(&user)))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn find_by_username(&self, username: &str) -> anyhow::Result<Option<ApUser>> {
|
async fn find_by_username(&self, username: &str) -> anyhow::Result<Option<ApUser>> {
|
||||||
use domain::value_objects::Username;
|
use domain::value_objects::Username;
|
||||||
let uname =
|
let uname = Username::new(username.to_string()).map_err(|e| anyhow::anyhow!(e.to_string()))?;
|
||||||
Username::new(username.to_string()).map_err(|e| anyhow::anyhow!(e.to_string()))?;
|
Ok(self.repo.find_by_username(&uname).await?.as_ref().map(|u| self.build_user(u)))
|
||||||
let user = match self.repo.find_by_username(&uname).await? {
|
|
||||||
Some(u) => u,
|
|
||||||
None => return Ok(None),
|
|
||||||
};
|
|
||||||
Ok(Some(self.build_user(&user)))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn count_users(&self) -> anyhow::Result<usize> {
|
async fn count_users(&self) -> anyhow::Result<usize> {
|
||||||
Ok(self
|
Ok(self.repo.list_with_stats().await
|
||||||
.repo
|
|
||||||
.list_with_stats()
|
|
||||||
.await
|
|
||||||
.map_err(|e| anyhow::anyhow!(e.to_string()))?
|
.map_err(|e| anyhow::anyhow!(e.to_string()))?
|
||||||
.len())
|
.len())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,168 +0,0 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use chrono::DateTime;
|
|
||||||
use domain::{
|
|
||||||
models::{RemoteWatchlistEntry, WatchlistWithMovie},
|
|
||||||
ports::{LocalApContentQuery, RemoteWatchlistRepository},
|
|
||||||
value_objects::{InstanceIdentity, UserId},
|
|
||||||
};
|
|
||||||
use k_ap::{AS_PUBLIC, ApContentReader, ApObjectHandler, LocalObject};
|
|
||||||
use url::Url;
|
|
||||||
|
|
||||||
use crate::objects::{WatchlistApInput, WatchlistObject, watchlist_to_ap_object};
|
|
||||||
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 instance: InstanceIdentity,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl ApContentReader for WatchlistObjectHandler {
|
|
||||||
async fn get_local_objects_page(
|
|
||||||
&self,
|
|
||||||
user_id: uuid::Uuid,
|
|
||||||
_before: Option<DateTime<chrono::Utc>>,
|
|
||||||
_limit: usize,
|
|
||||||
) -> anyhow::Result<Vec<LocalObject>> {
|
|
||||||
let uid = UserId::from_uuid(user_id);
|
|
||||||
let entries = self
|
|
||||||
.content_query
|
|
||||||
.get_local_watchlist_for_user(&uid)
|
|
||||||
.await
|
|
||||||
.map_err(|e| anyhow::anyhow!(e.to_string()))?;
|
|
||||||
|
|
||||||
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.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| self.instance.image_url_for(p.value()));
|
|
||||||
let obj = watchlist_to_ap_object(WatchlistApInput {
|
|
||||||
ap_id: ap_id.clone(),
|
|
||||||
actor_url: actor.clone(),
|
|
||||||
movie_title: movie.title().value().to_string(),
|
|
||||||
release_year: movie.release_year().value(),
|
|
||||||
external_metadata_id: movie
|
|
||||||
.external_metadata_id()
|
|
||||||
.map(|id| id.value().to_string()),
|
|
||||||
poster_url,
|
|
||||||
added_at: published,
|
|
||||||
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![],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
Ok(results)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn count_local_posts(&self) -> anyhow::Result<u64> {
|
|
||||||
Ok(0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl ApObjectHandler for WatchlistObjectHandler {
|
|
||||||
async fn on_create(
|
|
||||||
&self,
|
|
||||||
ap_id: &Url,
|
|
||||||
actor_url: &Url,
|
|
||||||
object: serde_json::Value,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
let mut obj: WatchlistObject = match serde_json::from_value(object) {
|
|
||||||
Ok(o) => o,
|
|
||||||
Err(e) => {
|
|
||||||
tracing::warn!(ap_id = %ap_id, "ignoring malformed watchlist Create: {}", e);
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
};
|
|
||||||
obj.movie_title = ammonia::clean(&obj.movie_title);
|
|
||||||
let added_at = obj.published;
|
|
||||||
let entry = RemoteWatchlistEntry {
|
|
||||||
ap_id: ap_id.as_str().to_string(),
|
|
||||||
actor_url: actor_url.as_str().to_string(),
|
|
||||||
movie_title: obj.movie_title,
|
|
||||||
release_year: obj.release_year,
|
|
||||||
external_metadata_id: obj.external_metadata_id,
|
|
||||||
poster_url: obj.poster_url,
|
|
||||||
added_at,
|
|
||||||
};
|
|
||||||
self.remote_watchlist_repo.save(entry).await?;
|
|
||||||
tracing::info!(ap_id = %ap_id, "saved remote watchlist entry");
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_update(
|
|
||||||
&self,
|
|
||||||
ap_id: &Url,
|
|
||||||
actor_url: &Url,
|
|
||||||
object: serde_json::Value,
|
|
||||||
) -> anyhow::Result<()> {
|
|
||||||
let mut obj: WatchlistObject = match serde_json::from_value(object) {
|
|
||||||
Ok(o) => o,
|
|
||||||
Err(e) => {
|
|
||||||
tracing::warn!(ap_id = %ap_id, "ignoring malformed watchlist Update: {}", e);
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
};
|
|
||||||
if obj.attributed_to != *actor_url {
|
|
||||||
anyhow::bail!("watchlist Update actor does not match object attributed_to");
|
|
||||||
}
|
|
||||||
obj.movie_title = ammonia::clean(&obj.movie_title);
|
|
||||||
let entry = RemoteWatchlistEntry {
|
|
||||||
ap_id: ap_id.as_str().to_string(),
|
|
||||||
actor_url: actor_url.as_str().to_string(),
|
|
||||||
movie_title: obj.movie_title,
|
|
||||||
release_year: obj.release_year,
|
|
||||||
external_metadata_id: obj.external_metadata_id,
|
|
||||||
poster_url: obj.poster_url,
|
|
||||||
added_at: obj.published,
|
|
||||||
};
|
|
||||||
self.remote_watchlist_repo.save(entry).await?;
|
|
||||||
tracing::info!(ap_id = %ap_id, "updated remote watchlist entry");
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_delete(&self, ap_id: &Url, actor_url: &Url) -> anyhow::Result<()> {
|
|
||||||
self.remote_watchlist_repo
|
|
||||||
.remove_by_ap_id(ap_id.as_str(), actor_url.as_str())
|
|
||||||
.await?;
|
|
||||||
tracing::info!(ap_id = %ap_id, "removed remote watchlist entry");
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_actor_removed(&self, actor_url: &Url) -> anyhow::Result<()> {
|
|
||||||
self.remote_watchlist_repo
|
|
||||||
.remove_all_by_actor(actor_url.as_str())
|
|
||||||
.await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_like(&self, _: &Url, _: &Url) -> anyhow::Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
async fn on_announce_received(&self, _: &Url, _: &Url) -> anyhow::Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
async fn on_announce_of_remote(&self, _: &Url, _: &Url) -> anyhow::Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
async fn on_unlike(&self, _: &Url, _: &Url) -> anyhow::Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
async fn on_mention(&self, _: &Url, _: uuid::Uuid, _: &Url) -> anyhow::Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,253 +0,0 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use activitypub::ActivityPubEventHandler;
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use chrono::NaiveDate;
|
|
||||||
use domain::{
|
|
||||||
errors::DomainError,
|
|
||||||
events::DomainEvent,
|
|
||||||
models::{DiaryEntry, WatchlistWithMovie},
|
|
||||||
ports::{
|
|
||||||
EventHandler, FederationDeletionNotifier, LocalApContentQuery, MovieCommand, UserRepository,
|
|
||||||
},
|
|
||||||
testing::{
|
|
||||||
InMemoryStore, PanicGoalQuery, PanicReviewRepository, PanicStatsRepository, test_movie,
|
|
||||||
},
|
|
||||||
value_objects::{InstanceIdentity, MovieId, UserId},
|
|
||||||
};
|
|
||||||
use k_ap::{
|
|
||||||
ActivityPubService, ApUser, FederationEvent,
|
|
||||||
testing::{MockActorRepoBuilder, MockFollowRepoBuilder, MockUserRepoBuilder},
|
|
||||||
};
|
|
||||||
use tokio::sync::mpsc;
|
|
||||||
|
|
||||||
struct NoContent;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl LocalApContentQuery for NoContent {
|
|
||||||
async fn get_local_watchlist_for_user(
|
|
||||||
&self,
|
|
||||||
_: &UserId,
|
|
||||||
) -> Result<Vec<WatchlistWithMovie>, DomainError> {
|
|
||||||
Ok(vec![])
|
|
||||||
}
|
|
||||||
async fn get_local_reviews_for_movie(
|
|
||||||
&self,
|
|
||||||
_: &MovieId,
|
|
||||||
) -> Result<Vec<DiaryEntry>, DomainError> {
|
|
||||||
Ok(vec![])
|
|
||||||
}
|
|
||||||
async fn get_local_reviews_page(
|
|
||||||
&self,
|
|
||||||
_: &UserId,
|
|
||||||
_: Option<chrono::NaiveDateTime>,
|
|
||||||
_: usize,
|
|
||||||
) -> Result<Vec<DiaryEntry>, DomainError> {
|
|
||||||
Ok(vec![])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Capture(mpsc::UnboundedSender<serde_json::Value>);
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl k_ap::EventPublisher for Capture {
|
|
||||||
async fn publish(&self, event: FederationEvent) -> anyhow::Result<()> {
|
|
||||||
if let FederationEvent::DeliveryRequested { activity, .. } = event {
|
|
||||||
let _ = self.0.send(activity);
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Harness {
|
|
||||||
handler: ActivityPubEventHandler,
|
|
||||||
delivered: mpsc::UnboundedReceiver<serde_json::Value>,
|
|
||||||
user: UserId,
|
|
||||||
movie_id: MovieId,
|
|
||||||
store: Arc<InMemoryStore>,
|
|
||||||
service: Arc<ActivityPubService>,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn harness() -> Harness {
|
|
||||||
let user = UserId::from_uuid(uuid::Uuid::new_v4());
|
|
||||||
let uid = user.value();
|
|
||||||
let (tx, rx) = mpsc::unbounded_channel();
|
|
||||||
let service = ActivityPubService::builder("https://diary.example")
|
|
||||||
.activity_repo(k_ap::testing::MockActivityRepoBuilder::new().build())
|
|
||||||
.follow_repo(
|
|
||||||
MockFollowRepoBuilder::new()
|
|
||||||
.on_get_accepted_follower_inboxes(|_| {
|
|
||||||
Ok(vec!["https://remote.example/inbox".to_string()])
|
|
||||||
})
|
|
||||||
.build(),
|
|
||||||
)
|
|
||||||
.actor_repo(MockActorRepoBuilder::new().build())
|
|
||||||
.blocklist_repo(k_ap::testing::MockBlocklistRepoBuilder::new().build())
|
|
||||||
.user_repo(
|
|
||||||
MockUserRepoBuilder::new()
|
|
||||||
.on_find_by_id(move |id| {
|
|
||||||
Ok((id == uid).then(|| ApUser {
|
|
||||||
id,
|
|
||||||
username: "alice".into(),
|
|
||||||
display_name: None,
|
|
||||||
bio: None,
|
|
||||||
avatar_url: None,
|
|
||||||
banner_url: None,
|
|
||||||
also_known_as: vec![],
|
|
||||||
profile_url: None,
|
|
||||||
attachment: vec![],
|
|
||||||
manually_approves_followers: false,
|
|
||||||
discoverable: true,
|
|
||||||
actor_type: Default::default(),
|
|
||||||
featured_url: None,
|
|
||||||
}))
|
|
||||||
})
|
|
||||||
.build(),
|
|
||||||
)
|
|
||||||
.content_reader(k_ap::testing::MockContentReaderBuilder::new().build())
|
|
||||||
.object_handler(k_ap::testing::MockObjectHandlerBuilder::new().build())
|
|
||||||
.event_publisher(Arc::new(Capture(tx)))
|
|
||||||
.build()
|
|
||||||
.await
|
|
||||||
.expect("service builds");
|
|
||||||
|
|
||||||
let store = InMemoryStore::new();
|
|
||||||
let movie = test_movie("Heat");
|
|
||||||
store.upsert_movie(&movie, &[]).await.unwrap();
|
|
||||||
let service = Arc::new(service);
|
|
||||||
store
|
|
||||||
.save(&domain::testing::test_user_with_role(
|
|
||||||
user.clone(),
|
|
||||||
domain::models::UserRole::Standard,
|
|
||||||
))
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
let handler = ActivityPubEventHandler::new(
|
|
||||||
Arc::clone(&service),
|
|
||||||
Arc::new(NoContent),
|
|
||||||
Arc::new(PanicReviewRepository),
|
|
||||||
store.clone(),
|
|
||||||
Arc::new(PanicGoalQuery),
|
|
||||||
Arc::new(PanicStatsRepository),
|
|
||||||
store.clone(),
|
|
||||||
store.clone(),
|
|
||||||
InstanceIdentity::new("https://diary.example"),
|
|
||||||
);
|
|
||||||
Harness {
|
|
||||||
handler,
|
|
||||||
delivered: rx,
|
|
||||||
user,
|
|
||||||
movie_id: movie.id().clone(),
|
|
||||||
store,
|
|
||||||
service,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Harness {
|
|
||||||
async fn next_activity_id(&mut self) -> String {
|
|
||||||
let activity = tokio::time::timeout(Duration::from_secs(5), self.delivered.recv())
|
|
||||||
.await
|
|
||||||
.expect("an activity was delivered")
|
|
||||||
.expect("channel open");
|
|
||||||
activity["id"]
|
|
||||||
.as_str()
|
|
||||||
.expect("activity has an id")
|
|
||||||
.to_string()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn activitypub_is_idempotent_when_run_twice() {
|
|
||||||
let mut h = harness().await;
|
|
||||||
let event = DomainEvent::WatchlistEntryAdded {
|
|
||||||
user_id: h.user.clone(),
|
|
||||||
movie_id: h.movie_id.clone(),
|
|
||||||
movie_title: "Heat".into(),
|
|
||||||
release_year: 1995,
|
|
||||||
external_metadata_id: None,
|
|
||||||
added_at: NaiveDate::from_ymd_opt(2026, 1, 1)
|
|
||||||
.unwrap()
|
|
||||||
.and_hms_opt(0, 0, 0)
|
|
||||||
.unwrap(),
|
|
||||||
};
|
|
||||||
|
|
||||||
h.handler.handle(&event).await.unwrap();
|
|
||||||
let first = h.next_activity_id().await;
|
|
||||||
h.handler.handle(&event).await.unwrap();
|
|
||||||
let second = h.next_activity_id().await;
|
|
||||||
|
|
||||||
assert!(first.starts_with("https://diary.example/activities/create/"));
|
|
||||||
assert_eq!(first, second, "a redelivered Create keeps its activity id");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn redelivered_delete_gets_a_fresh_activity_id_known_k_ap_limitation() {
|
|
||||||
let mut h = harness().await;
|
|
||||||
let event = DomainEvent::WatchlistEntryRemoved {
|
|
||||||
user_id: h.user.clone(),
|
|
||||||
movie_id: h.movie_id.clone(),
|
|
||||||
};
|
|
||||||
|
|
||||||
h.handler.handle(&event).await.unwrap();
|
|
||||||
let first = h.next_activity_id().await;
|
|
||||||
h.handler.handle(&event).await.unwrap();
|
|
||||||
let second = h.next_activity_id().await;
|
|
||||||
|
|
||||||
assert_ne!(first, second);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn a_deleted_account_sends_nothing_but_its_delete() {
|
|
||||||
let mut h = harness().await;
|
|
||||||
h.store.mark_deleted(&h.user, &[]).await.unwrap();
|
|
||||||
let logged = DomainEvent::ReviewLogged {
|
|
||||||
review_id: domain::value_objects::ReviewId::generate(),
|
|
||||||
user_id: h.user.clone(),
|
|
||||||
movie_id: h.movie_id.clone(),
|
|
||||||
rating: domain::value_objects::Rating::new(4).unwrap(),
|
|
||||||
watched_at: NaiveDate::from_ymd_opt(2026, 1, 1)
|
|
||||||
.unwrap()
|
|
||||||
.and_hms_opt(0, 0, 0)
|
|
||||||
.unwrap(),
|
|
||||||
};
|
|
||||||
let added = DomainEvent::WatchlistEntryAdded {
|
|
||||||
user_id: h.user.clone(),
|
|
||||||
movie_id: h.movie_id.clone(),
|
|
||||||
movie_title: "Heat".into(),
|
|
||||||
release_year: 1995,
|
|
||||||
external_metadata_id: None,
|
|
||||||
added_at: NaiveDate::from_ymd_opt(2026, 1, 1)
|
|
||||||
.unwrap()
|
|
||||||
.and_hms_opt(0, 0, 0)
|
|
||||||
.unwrap(),
|
|
||||||
};
|
|
||||||
let queued = DomainEvent::FederationDeliveryRequested {
|
|
||||||
inbox_url: "https://remote.example/inbox".into(),
|
|
||||||
activity_json: serde_json::json!({"type": "Create"}),
|
|
||||||
signing_actor_id: h.user.value(),
|
|
||||||
};
|
|
||||||
|
|
||||||
for event in [&logged, &added, &queued] {
|
|
||||||
h.handler.handle(event).await.unwrap();
|
|
||||||
}
|
|
||||||
assert!(
|
|
||||||
tokio::time::timeout(Duration::from_millis(300), h.delivered.recv())
|
|
||||||
.await
|
|
||||||
.is_err(),
|
|
||||||
"nothing is delivered for a deleted account"
|
|
||||||
);
|
|
||||||
|
|
||||||
activitypub::ApDeletionNotifier::new(
|
|
||||||
Arc::clone(&h.service),
|
|
||||||
InstanceIdentity::new("https://diary.example"),
|
|
||||||
)
|
|
||||||
.notify_deleted(&h.user)
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
let delete = tokio::time::timeout(Duration::from_secs(5), h.delivered.recv())
|
|
||||||
.await
|
|
||||||
.expect("the Delete is delivered")
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(delete["type"], "Delete");
|
|
||||||
}
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
#[path = "objects/review_object_test.rs"]
|
|
||||||
mod review_object_test;
|
|
||||||
#[path = "objects/watchlist_object_test.rs"]
|
|
||||||
mod watchlist_object_test;
|
|
||||||
@@ -1,112 +0,0 @@
|
|||||||
use activitypub::objects::{ReviewApInput, review_to_ap_object};
|
|
||||||
use chrono::NaiveDateTime;
|
|
||||||
use domain::models::{PersistedReview, Review, ReviewSource};
|
|
||||||
use domain::value_objects::{Comment, MovieId, Rating, ReviewId, UserId};
|
|
||||||
use serde_json::{Value, json};
|
|
||||||
|
|
||||||
const PUBLIC: &str = "https://www.w3.org/ns/activitystreams#Public";
|
|
||||||
|
|
||||||
fn timestamp() -> NaiveDateTime {
|
|
||||||
NaiveDateTime::parse_from_str("2024-06-01 00:00:00", "%Y-%m-%d %H:%M:%S").unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn review(rating: u8, comment: Option<&str>, spoilers: bool) -> Review {
|
|
||||||
Review::from_persistence(PersistedReview {
|
|
||||||
id: ReviewId::generate(),
|
|
||||||
movie_id: MovieId::from_uuid(uuid::Uuid::new_v4()),
|
|
||||||
user_id: UserId::from_uuid(uuid::Uuid::new_v4()),
|
|
||||||
rating: Rating::new(rating).unwrap(),
|
|
||||||
comment: comment.map(|c| Comment::new(c.into()).unwrap()),
|
|
||||||
watched_at: timestamp(),
|
|
||||||
created_at: timestamp(),
|
|
||||||
source: ReviewSource::Local,
|
|
||||||
watch_medium: None,
|
|
||||||
spoilers,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn input(movie_title: &str, actor_url: &str) -> ReviewApInput {
|
|
||||||
ReviewApInput {
|
|
||||||
ap_id: "https://example.com/reviews/1".parse().unwrap(),
|
|
||||||
actor_url: actor_url.parse().unwrap(),
|
|
||||||
movie_title: movie_title.to_string(),
|
|
||||||
release_year: 2021,
|
|
||||||
external_metadata_id: None,
|
|
||||||
poster_url: None,
|
|
||||||
base_url: "https://example.com".to_string(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn render(review: &Review, input: ReviewApInput) -> Value {
|
|
||||||
serde_json::to_value(review_to_ap_object(review, input)).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn tag_names(json: &Value) -> Vec<&str> {
|
|
||||||
json["tag"]
|
|
||||||
.as_array()
|
|
||||||
.unwrap()
|
|
||||||
.iter()
|
|
||||||
.map(|t| t["name"].as_str().unwrap())
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn review_object_tags_movie_title_with_non_alphanumerics_stripped() {
|
|
||||||
for (title, hashtag) in [
|
|
||||||
("The Dark Knight", "#TheDarkKnight"),
|
|
||||||
("Schindler's List", "#SchindlersList"),
|
|
||||||
("2001: A Space Odyssey", "#2001ASpaceOdyssey"),
|
|
||||||
] {
|
|
||||||
let json = render(
|
|
||||||
&review(4, None, false),
|
|
||||||
input(title, "https://example.com/users/1"),
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
tag_names(&json).contains(&hashtag),
|
|
||||||
"{title}: {:?}",
|
|
||||||
tag_names(&json)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn review_object_includes_two_hashtags() {
|
|
||||||
let json = render(
|
|
||||||
&review(4, None, false),
|
|
||||||
input("Dune", "https://example.com/users/1"),
|
|
||||||
);
|
|
||||||
|
|
||||||
assert_eq!(tag_names(&json), vec!["#MoviesDiary", "#Dune"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn review_object_is_publicly_addressed_with_followers_in_cc() {
|
|
||||||
let json = render(
|
|
||||||
&review(3, None, false),
|
|
||||||
input("Dune", "https://example.com/users/abc"),
|
|
||||||
);
|
|
||||||
|
|
||||||
assert_eq!(json["to"], json!([PUBLIC]));
|
|
||||||
assert_eq!(
|
|
||||||
json["cc"],
|
|
||||||
json!(["https://example.com/users/abc/followers"])
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn review_object_carries_spoiler_flag_and_summary_only_with_a_comment() {
|
|
||||||
let json = render(
|
|
||||||
&review(4, Some("the mentor is the villain"), true),
|
|
||||||
input("Dune", "https://example.com/users/1"),
|
|
||||||
);
|
|
||||||
assert_eq!(json["containsSpoilers"], Value::Bool(true));
|
|
||||||
assert_eq!(json["summary"], "Contains spoilers");
|
|
||||||
|
|
||||||
// A flag without a comment never travels: there is nothing to veil.
|
|
||||||
let json = render(
|
|
||||||
&review(4, None, true),
|
|
||||||
input("Dune", "https://example.com/users/1"),
|
|
||||||
);
|
|
||||||
assert!(json.get("containsSpoilers").is_none());
|
|
||||||
assert!(json.get("summary").is_none());
|
|
||||||
}
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
use activitypub::objects::{WatchlistApInput, watchlist_to_ap_object};
|
|
||||||
use serde_json::json;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn watchlist_object_is_publicly_addressed_with_followers_in_cc() {
|
|
||||||
let obj = watchlist_to_ap_object(WatchlistApInput {
|
|
||||||
ap_id: "https://example.com/watchlist/1".parse().unwrap(),
|
|
||||||
actor_url: "https://example.com/users/abc".parse().unwrap(),
|
|
||||||
movie_title: "Alien".to_string(),
|
|
||||||
release_year: 1979,
|
|
||||||
external_metadata_id: None,
|
|
||||||
poster_url: None,
|
|
||||||
added_at: chrono::Utc::now(),
|
|
||||||
base_url: "https://example.com".to_string(),
|
|
||||||
});
|
|
||||||
let json = serde_json::to_value(&obj).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
json["to"],
|
|
||||||
json!(["https://www.w3.org/ns/activitystreams#Public"])
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
json["cc"],
|
|
||||||
json!(["https://example.com/users/abc/followers"])
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
use domain::{
|
|
||||||
ports::UserRepository,
|
|
||||||
testing::{InMemoryStore, test_user},
|
|
||||||
value_objects::InstanceIdentity,
|
|
||||||
};
|
|
||||||
use k_ap::ApUserRepository;
|
|
||||||
|
|
||||||
use activitypub::DomainUserRepoAdapter;
|
|
||||||
|
|
||||||
async fn adapter_with_deleted_alice() -> (DomainUserRepoAdapter, uuid::Uuid) {
|
|
||||||
let store = InMemoryStore::new();
|
|
||||||
let alice = test_user("alice");
|
|
||||||
store.save(&alice).await.unwrap();
|
|
||||||
store.mark_deleted(alice.id(), &[]).await.unwrap();
|
|
||||||
let adapter = DomainUserRepoAdapter::new(store, InstanceIdentity::new("https://md.example"));
|
|
||||||
(adapter, alice.id().value())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn tombstoned_actor_can_still_sign() {
|
|
||||||
let (adapter, id) = adapter_with_deleted_alice().await;
|
|
||||||
|
|
||||||
let user = adapter.find_by_id(id).await.unwrap();
|
|
||||||
|
|
||||||
assert_eq!(user.expect("k-ap resolves the tombstone").username, "alice");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn a_tombstone_is_not_found_by_username() {
|
|
||||||
let (adapter, _) = adapter_with_deleted_alice().await;
|
|
||||||
|
|
||||||
assert!(adapter.find_by_username("alice").await.unwrap().is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn an_unknown_user_is_none() {
|
|
||||||
let (adapter, _) = adapter_with_deleted_alice().await;
|
|
||||||
|
|
||||||
assert!(
|
|
||||||
adapter
|
|
||||||
.find_by_id(uuid::Uuid::new_v4())
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
.is_none()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn every_per_user_path_is_gated() {
|
|
||||||
use activitypub::tombstone_gate::gated_user;
|
|
||||||
let id = uuid::Uuid::new_v4();
|
|
||||||
let rid = uuid::Uuid::new_v4();
|
|
||||||
for endpoint in [
|
|
||||||
"outbox",
|
|
||||||
"featured",
|
|
||||||
"inbox",
|
|
||||||
"followers",
|
|
||||||
"following",
|
|
||||||
&format!("reviews/{rid}"),
|
|
||||||
] {
|
|
||||||
assert_eq!(gated_user(&format!("/users/{id}/{endpoint}")), Some(id));
|
|
||||||
}
|
|
||||||
assert_eq!(gated_user(&format!("/users/{id}")), None);
|
|
||||||
assert_eq!(gated_user(&format!("/users/{id}/")), None);
|
|
||||||
assert_eq!(gated_user("/inbox"), None);
|
|
||||||
assert_eq!(gated_user("/users/not-a-uuid/outbox"), None);
|
|
||||||
}
|
|
||||||
@@ -1,16 +1,15 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "auth"
|
name = "auth"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition.workspace = true
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
config = { workspace = true }
|
|
||||||
async-trait = { workspace = true }
|
async-trait = { workspace = true }
|
||||||
domain = { workspace = true }
|
domain = { workspace = true }
|
||||||
anyhow = { workspace = true }
|
anyhow = { workspace = true }
|
||||||
chrono = { workspace = true, features = ["clock"] }
|
chrono = { workspace = true }
|
||||||
uuid = { workspace = true }
|
uuid = { workspace = true }
|
||||||
serde = { workspace = true, features = ["derive"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
jsonwebtoken = { workspace = true }
|
jsonwebtoken = "9"
|
||||||
argon2 = { workspace = true, features = ["std"] }
|
argon2 = { version = "0.5", features = ["std"] }
|
||||||
rand_core = { workspace = true, features = ["getrandom"] }
|
rand_core = { version = "0.6", features = ["getrandom"] }
|
||||||
|
|||||||
@@ -11,8 +11,7 @@ use uuid::Uuid;
|
|||||||
|
|
||||||
use domain::{
|
use domain::{
|
||||||
errors::DomainError,
|
errors::DomainError,
|
||||||
models::GeneratedToken,
|
ports::{AuthService, GeneratedToken, PasswordHasher},
|
||||||
ports::{AuthService, PasswordHasher},
|
|
||||||
value_objects::{PasswordHash, UserId},
|
value_objects::{PasswordHash, UserId},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -22,17 +21,19 @@ pub struct AuthConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl AuthConfig {
|
impl AuthConfig {
|
||||||
pub fn from_config(config: &config::AuthConfig) -> anyhow::Result<Self> {
|
pub fn from_env() -> anyhow::Result<Self> {
|
||||||
let secret = config
|
let secret = std::env::var("JWT_SECRET")
|
||||||
.jwt_secret
|
.map_err(|_| anyhow::anyhow!("JWT_SECRET env var is required"))?;
|
||||||
.clone()
|
|
||||||
.ok_or_else(|| anyhow::anyhow!("JWT_SECRET env var is required"))?;
|
|
||||||
if secret.is_empty() {
|
if secret.is_empty() {
|
||||||
anyhow::bail!("JWT_SECRET must not be empty");
|
anyhow::bail!("JWT_SECRET must not be empty");
|
||||||
}
|
}
|
||||||
|
let ttl_seconds = std::env::var("JWT_TTL_SECONDS")
|
||||||
|
.ok()
|
||||||
|
.and_then(|v| v.parse().ok())
|
||||||
|
.unwrap_or(86400u64);
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
secret,
|
secret,
|
||||||
ttl_seconds: config.jwt_ttl_seconds,
|
ttl_seconds,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -105,13 +106,11 @@ impl PasswordHasher for Argon2PasswordHasher {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn create(
|
pub fn create() -> anyhow::Result<(
|
||||||
config: &config::AuthConfig,
|
|
||||||
) -> anyhow::Result<(
|
|
||||||
std::sync::Arc<dyn domain::ports::AuthService>,
|
std::sync::Arc<dyn domain::ports::AuthService>,
|
||||||
std::sync::Arc<dyn domain::ports::PasswordHasher>,
|
std::sync::Arc<dyn domain::ports::PasswordHasher>,
|
||||||
)> {
|
)> {
|
||||||
let config = AuthConfig::from_config(config)?;
|
let config = AuthConfig::from_env()?;
|
||||||
Ok((
|
Ok((
|
||||||
std::sync::Arc::new(JwtAuthService::new(config)),
|
std::sync::Arc::new(JwtAuthService::new(config)),
|
||||||
std::sync::Arc::new(Argon2PasswordHasher),
|
std::sync::Arc::new(Argon2PasswordHasher),
|
||||||
|
|||||||
12
crates/adapters/event-payload/Cargo.toml
Normal file
12
crates/adapters/event-payload/Cargo.toml
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
[package]
|
||||||
|
name = "event-payload"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
domain = { workspace = true }
|
||||||
|
serde = { workspace = true }
|
||||||
|
chrono = { workspace = true }
|
||||||
|
uuid = { workspace = true }
|
||||||
|
anyhow = { workspace = true }
|
||||||
|
serde_json = { workspace = true }
|
||||||
218
crates/adapters/event-payload/src/lib.rs
Normal file
218
crates/adapters/event-payload/src/lib.rs
Normal file
@@ -0,0 +1,218 @@
|
|||||||
|
use chrono::NaiveDateTime;
|
||||||
|
use domain::{
|
||||||
|
errors::DomainError,
|
||||||
|
events::DomainEvent,
|
||||||
|
value_objects::{ExternalMetadataId, MovieId, PosterPath, Rating, ReviewId, UserId},
|
||||||
|
};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize, PartialEq)]
|
||||||
|
#[serde(tag = "type", content = "data")]
|
||||||
|
pub enum EventPayload {
|
||||||
|
ReviewLogged {
|
||||||
|
review_id: String,
|
||||||
|
movie_id: String,
|
||||||
|
user_id: String,
|
||||||
|
rating: u8,
|
||||||
|
watched_at: i64,
|
||||||
|
},
|
||||||
|
ReviewUpdated {
|
||||||
|
review_id: String,
|
||||||
|
movie_id: String,
|
||||||
|
user_id: String,
|
||||||
|
rating: u8,
|
||||||
|
watched_at: i64,
|
||||||
|
},
|
||||||
|
MovieDiscovered {
|
||||||
|
movie_id: String,
|
||||||
|
external_metadata_id: String,
|
||||||
|
},
|
||||||
|
MovieDeleted {
|
||||||
|
movie_id: String,
|
||||||
|
poster_path: Option<String>,
|
||||||
|
},
|
||||||
|
UserUpdated {
|
||||||
|
user_id: String,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventPayload {
|
||||||
|
pub fn event_type(&self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
EventPayload::ReviewLogged { .. } => "ReviewLogged",
|
||||||
|
EventPayload::ReviewUpdated { .. } => "ReviewUpdated",
|
||||||
|
EventPayload::MovieDiscovered { .. } => "MovieDiscovered",
|
||||||
|
EventPayload::MovieDeleted { .. } => "MovieDeleted",
|
||||||
|
EventPayload::UserUpdated { .. } => "UserUpdated",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_uuid(s: &str, field: &str) -> Result<Uuid, DomainError> {
|
||||||
|
Uuid::parse_str(s)
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(format!("{field}: {e}")))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_ts(ts: i64) -> Result<NaiveDateTime, DomainError> {
|
||||||
|
chrono::DateTime::from_timestamp(ts, 0)
|
||||||
|
.map(|dt| dt.naive_utc())
|
||||||
|
.ok_or_else(|| DomainError::InfrastructureError(format!("invalid timestamp: {ts}")))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&DomainEvent> for EventPayload {
|
||||||
|
fn from(event: &DomainEvent) -> Self {
|
||||||
|
match event {
|
||||||
|
DomainEvent::ReviewLogged { review_id, movie_id, user_id, rating, watched_at } => {
|
||||||
|
EventPayload::ReviewLogged {
|
||||||
|
review_id: review_id.value().to_string(),
|
||||||
|
movie_id: movie_id.value().to_string(),
|
||||||
|
user_id: user_id.value().to_string(),
|
||||||
|
rating: rating.value(),
|
||||||
|
watched_at: watched_at.and_utc().timestamp(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
DomainEvent::ReviewUpdated { review_id, movie_id, user_id, rating, watched_at } => {
|
||||||
|
EventPayload::ReviewUpdated {
|
||||||
|
review_id: review_id.value().to_string(),
|
||||||
|
movie_id: movie_id.value().to_string(),
|
||||||
|
user_id: user_id.value().to_string(),
|
||||||
|
rating: rating.value(),
|
||||||
|
watched_at: watched_at.and_utc().timestamp(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
DomainEvent::MovieDiscovered { movie_id, external_metadata_id } => {
|
||||||
|
EventPayload::MovieDiscovered {
|
||||||
|
movie_id: movie_id.value().to_string(),
|
||||||
|
external_metadata_id: external_metadata_id.value().to_owned(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
DomainEvent::MovieDeleted { movie_id, poster_path } => EventPayload::MovieDeleted {
|
||||||
|
movie_id: movie_id.value().to_string(),
|
||||||
|
poster_path: poster_path.as_ref().map(|p| p.value().to_string()),
|
||||||
|
},
|
||||||
|
DomainEvent::UserUpdated { user_id } => EventPayload::UserUpdated {
|
||||||
|
user_id: user_id.value().to_string(),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<EventPayload> for DomainEvent {
|
||||||
|
type Error = DomainError;
|
||||||
|
fn try_from(payload: EventPayload) -> Result<Self, DomainError> {
|
||||||
|
match payload {
|
||||||
|
EventPayload::ReviewLogged { review_id, movie_id, user_id, rating, watched_at } => {
|
||||||
|
Ok(DomainEvent::ReviewLogged {
|
||||||
|
review_id: ReviewId::from_uuid(parse_uuid(&review_id, "review_id")?),
|
||||||
|
movie_id: MovieId::from_uuid(parse_uuid(&movie_id, "movie_id")?),
|
||||||
|
user_id: UserId::from_uuid(parse_uuid(&user_id, "user_id")?),
|
||||||
|
rating: Rating::new(rating)?,
|
||||||
|
watched_at: parse_ts(watched_at)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
EventPayload::ReviewUpdated { review_id, movie_id, user_id, rating, watched_at } => {
|
||||||
|
Ok(DomainEvent::ReviewUpdated {
|
||||||
|
review_id: ReviewId::from_uuid(parse_uuid(&review_id, "review_id")?),
|
||||||
|
movie_id: MovieId::from_uuid(parse_uuid(&movie_id, "movie_id")?),
|
||||||
|
user_id: UserId::from_uuid(parse_uuid(&user_id, "user_id")?),
|
||||||
|
rating: Rating::new(rating)?,
|
||||||
|
watched_at: parse_ts(watched_at)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
EventPayload::MovieDiscovered { movie_id, external_metadata_id } => {
|
||||||
|
Ok(DomainEvent::MovieDiscovered {
|
||||||
|
movie_id: MovieId::from_uuid(parse_uuid(&movie_id, "movie_id")?),
|
||||||
|
external_metadata_id: ExternalMetadataId::new(external_metadata_id)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
EventPayload::MovieDeleted { movie_id, poster_path } => {
|
||||||
|
let movie_id = MovieId::from_uuid(parse_uuid(&movie_id, "movie_id")?);
|
||||||
|
let poster_path = poster_path
|
||||||
|
.map(|p| PosterPath::new(p))
|
||||||
|
.transpose()
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
|
||||||
|
Ok(DomainEvent::MovieDeleted { movie_id, poster_path })
|
||||||
|
}
|
||||||
|
EventPayload::UserUpdated { user_id } => {
|
||||||
|
Ok(DomainEvent::UserUpdated {
|
||||||
|
user_id: UserId::from_uuid(parse_uuid(&user_id, "user_id")?),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn fixed_dt() -> NaiveDateTime {
|
||||||
|
chrono::DateTime::from_timestamp(1_700_000_000, 0).unwrap().naive_utc()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn review_logged() -> DomainEvent {
|
||||||
|
DomainEvent::ReviewLogged {
|
||||||
|
review_id: ReviewId::from_uuid(Uuid::new_v4()),
|
||||||
|
movie_id: MovieId::from_uuid(Uuid::new_v4()),
|
||||||
|
user_id: UserId::from_uuid(Uuid::new_v4()),
|
||||||
|
rating: Rating::new(4).unwrap(),
|
||||||
|
watched_at: fixed_dt(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn review_updated() -> DomainEvent {
|
||||||
|
DomainEvent::ReviewUpdated {
|
||||||
|
review_id: ReviewId::from_uuid(Uuid::new_v4()),
|
||||||
|
movie_id: MovieId::from_uuid(Uuid::new_v4()),
|
||||||
|
user_id: UserId::from_uuid(Uuid::new_v4()),
|
||||||
|
rating: Rating::new(3).unwrap(),
|
||||||
|
watched_at: fixed_dt(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn movie_discovered() -> DomainEvent {
|
||||||
|
DomainEvent::MovieDiscovered {
|
||||||
|
movie_id: MovieId::from_uuid(Uuid::new_v4()),
|
||||||
|
external_metadata_id: ExternalMetadataId::new("tt1234567".into()).unwrap(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn round_trip(event: DomainEvent) {
|
||||||
|
let payload = EventPayload::from(&event);
|
||||||
|
let json = serde_json::to_string(&payload).expect("serialize");
|
||||||
|
let back: EventPayload = serde_json::from_str(&json).expect("deserialize");
|
||||||
|
let recovered = DomainEvent::try_from(back).expect("try_from");
|
||||||
|
assert_eq!(EventPayload::from(&event), EventPayload::from(&recovered));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn round_trip_review_logged() {
|
||||||
|
round_trip(review_logged());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn round_trip_review_updated() {
|
||||||
|
round_trip(review_updated());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn round_trip_movie_discovered() {
|
||||||
|
round_trip(movie_discovered());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn serialized_format_is_tagged() {
|
||||||
|
let payload = EventPayload::from(&movie_discovered());
|
||||||
|
let json = serde_json::to_string(&payload).unwrap();
|
||||||
|
assert!(json.contains(r#""type":"MovieDiscovered""#));
|
||||||
|
assert!(json.contains(r#""data":"#));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn event_type_strings() {
|
||||||
|
assert_eq!(EventPayload::from(&review_logged()).event_type(), "ReviewLogged");
|
||||||
|
assert_eq!(EventPayload::from(&review_updated()).event_type(), "ReviewUpdated");
|
||||||
|
assert_eq!(EventPayload::from(&movie_discovered()).event_type(), "MovieDiscovered");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,14 +1,11 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "event-publisher"
|
name = "event-publisher"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition.workspace = true
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
config = { workspace = true }
|
|
||||||
domain = { workspace = true }
|
domain = { workspace = true }
|
||||||
async-trait = { workspace = true }
|
async-trait = { workspace = true }
|
||||||
tokio = { workspace = true, features = ["sync"] }
|
tokio = { workspace = true }
|
||||||
|
tracing = { workspace = true }
|
||||||
futures = { workspace = true }
|
futures = { workspace = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
|
||||||
tokio = { workspace = true, features = ["rt", "macros"] }
|
|
||||||
|
|||||||
@@ -16,10 +16,12 @@ pub struct EventPublisherConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl EventPublisherConfig {
|
impl EventPublisherConfig {
|
||||||
pub fn from_config(config: &config::EventsConfig) -> Self {
|
pub fn from_env() -> Self {
|
||||||
Self {
|
let channel_buffer = std::env::var("EVENT_CHANNEL_BUFFER")
|
||||||
channel_buffer: config.channel_buffer,
|
.ok()
|
||||||
}
|
.and_then(|v| v.parse().ok())
|
||||||
|
.unwrap_or(128);
|
||||||
|
Self { channel_buffer }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,15 +43,8 @@ struct NoopAck;
|
|||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl AckHandle for NoopAck {
|
impl AckHandle for NoopAck {
|
||||||
async fn ack(&self) -> Result<(), DomainError> {
|
async fn ack(&self) -> Result<(), DomainError> { Ok(()) }
|
||||||
Ok(())
|
async fn nack(&self) -> Result<(), DomainError> { Ok(()) }
|
||||||
}
|
|
||||||
async fn nack(&self) -> Result<(), DomainError> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
async fn defer(&self, _: std::time::Duration) -> Result<(), DomainError> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct ChannelEventConsumer {
|
pub struct ChannelEventConsumer {
|
||||||
@@ -61,7 +56,7 @@ impl EventConsumer for ChannelEventConsumer {
|
|||||||
let receiver = Arc::clone(&self.receiver);
|
let receiver = Arc::clone(&self.receiver);
|
||||||
Box::pin(stream::unfold(receiver, |rx| async move {
|
Box::pin(stream::unfold(receiver, |rx| async move {
|
||||||
let event = rx.lock().await.recv().await?;
|
let event = rx.lock().await.recv().await?;
|
||||||
let envelope = EventEnvelope::new(None, event, Box::new(NoopAck));
|
let envelope = EventEnvelope::new(event, Box::new(NoopAck));
|
||||||
Some((Ok(envelope), rx))
|
Some((Ok(envelope), rx))
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
@@ -87,3 +82,61 @@ pub fn create_event_channel(
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use domain::{
|
||||||
|
events::DomainEvent,
|
||||||
|
value_objects::{ExternalMetadataId, MovieId},
|
||||||
|
};
|
||||||
|
use futures::StreamExt;
|
||||||
|
|
||||||
|
fn movie_discovered() -> DomainEvent {
|
||||||
|
DomainEvent::MovieDiscovered {
|
||||||
|
movie_id: MovieId::generate(),
|
||||||
|
external_metadata_id: ExternalMetadataId::new("tt1234567".into()).unwrap(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn consumer_yields_published_events() {
|
||||||
|
let config = EventPublisherConfig { channel_buffer: 8 };
|
||||||
|
let (publisher, consumer) = create_event_channel(config);
|
||||||
|
|
||||||
|
publisher.publish(&movie_discovered()).await.unwrap();
|
||||||
|
drop(publisher);
|
||||||
|
|
||||||
|
let mut stream = consumer.consume();
|
||||||
|
let envelope = stream.next().await.unwrap().unwrap();
|
||||||
|
assert!(matches!(envelope.event, DomainEvent::MovieDiscovered { .. }));
|
||||||
|
assert!(stream.next().await.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn consumer_yields_multiple_events_in_order() {
|
||||||
|
let config = EventPublisherConfig { channel_buffer: 8 };
|
||||||
|
let (publisher, consumer) = create_event_channel(config);
|
||||||
|
|
||||||
|
publisher.publish(&movie_discovered()).await.unwrap();
|
||||||
|
publisher.publish(&movie_discovered()).await.unwrap();
|
||||||
|
drop(publisher);
|
||||||
|
|
||||||
|
let mut stream = consumer.consume();
|
||||||
|
let first = stream.next().await.unwrap().unwrap();
|
||||||
|
let second = stream.next().await.unwrap().unwrap();
|
||||||
|
assert!(matches!(first.event, DomainEvent::MovieDiscovered { .. }));
|
||||||
|
assert!(matches!(second.event, DomainEvent::MovieDiscovered { .. }));
|
||||||
|
assert!(stream.next().await.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn stream_ends_when_publisher_dropped() {
|
||||||
|
let config = EventPublisherConfig { channel_buffer: 8 };
|
||||||
|
let (publisher, consumer) = create_event_channel(config);
|
||||||
|
drop(publisher);
|
||||||
|
|
||||||
|
let mut stream = consumer.consume();
|
||||||
|
assert!(stream.next().await.is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,58 +0,0 @@
|
|||||||
use domain::ports::{EventConsumer, EventPublisher};
|
|
||||||
use domain::{
|
|
||||||
events::DomainEvent,
|
|
||||||
value_objects::{ExternalMetadataId, MovieId},
|
|
||||||
};
|
|
||||||
use event_publisher::{EventPublisherConfig, create_event_channel};
|
|
||||||
use futures::StreamExt;
|
|
||||||
|
|
||||||
fn movie_discovered() -> DomainEvent {
|
|
||||||
DomainEvent::MovieDiscovered {
|
|
||||||
movie_id: MovieId::generate(),
|
|
||||||
external_metadata_id: ExternalMetadataId::new("tt1234567".into()).unwrap(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn consumer_yields_published_events() {
|
|
||||||
let config = EventPublisherConfig { channel_buffer: 8 };
|
|
||||||
let (publisher, consumer) = create_event_channel(config);
|
|
||||||
|
|
||||||
publisher.publish(&movie_discovered()).await.unwrap();
|
|
||||||
drop(publisher);
|
|
||||||
|
|
||||||
let mut stream = consumer.consume();
|
|
||||||
let envelope = stream.next().await.unwrap().unwrap();
|
|
||||||
assert!(matches!(
|
|
||||||
envelope.event,
|
|
||||||
DomainEvent::MovieDiscovered { .. }
|
|
||||||
));
|
|
||||||
assert!(stream.next().await.is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn consumer_yields_multiple_events_in_order() {
|
|
||||||
let config = EventPublisherConfig { channel_buffer: 8 };
|
|
||||||
let (publisher, consumer) = create_event_channel(config);
|
|
||||||
|
|
||||||
publisher.publish(&movie_discovered()).await.unwrap();
|
|
||||||
publisher.publish(&movie_discovered()).await.unwrap();
|
|
||||||
drop(publisher);
|
|
||||||
|
|
||||||
let mut stream = consumer.consume();
|
|
||||||
let first = stream.next().await.unwrap().unwrap();
|
|
||||||
let second = stream.next().await.unwrap().unwrap();
|
|
||||||
assert!(matches!(first.event, DomainEvent::MovieDiscovered { .. }));
|
|
||||||
assert!(matches!(second.event, DomainEvent::MovieDiscovered { .. }));
|
|
||||||
assert!(stream.next().await.is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn stream_ends_when_publisher_dropped() {
|
|
||||||
let config = EventPublisherConfig { channel_buffer: 8 };
|
|
||||||
let (publisher, consumer) = create_event_channel(config);
|
|
||||||
drop(publisher);
|
|
||||||
|
|
||||||
let mut stream = consumer.consume();
|
|
||||||
assert!(stream.next().await.is_none());
|
|
||||||
}
|
|
||||||
@@ -1,16 +1,14 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "export"
|
name = "export"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition.workspace = true
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
domain = { workspace = true }
|
domain = { workspace = true }
|
||||||
|
async-trait = { workspace = true }
|
||||||
serde_json = { workspace = true }
|
serde_json = { workspace = true }
|
||||||
futures = { workspace = true }
|
chrono = { workspace = true }
|
||||||
bytes = { workspace = true }
|
|
||||||
async-stream = { workspace = true }
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
domain = { workspace = true, features = ["test-helpers"] }
|
|
||||||
uuid = { workspace = true }
|
uuid = { workspace = true }
|
||||||
tokio = { workspace = true, features = ["rt", "macros"] }
|
tokio = { workspace = true }
|
||||||
|
|||||||
@@ -1,90 +1,51 @@
|
|||||||
use bytes::Bytes;
|
use async_trait::async_trait;
|
||||||
use domain::{
|
use domain::{
|
||||||
errors::DomainError,
|
errors::DomainError,
|
||||||
models::{DiaryEntry, ExportFormat},
|
models::{DiaryEntry, ExportFormat},
|
||||||
ports::DiaryExporter,
|
ports::DiaryExporter,
|
||||||
};
|
};
|
||||||
use futures::stream::BoxStream;
|
|
||||||
|
|
||||||
pub struct ExportAdapter;
|
pub struct ExportAdapter;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
impl DiaryExporter for ExportAdapter {
|
impl DiaryExporter for ExportAdapter {
|
||||||
fn stream_entries(
|
async fn serialize_entries(
|
||||||
&self,
|
&self,
|
||||||
stream: BoxStream<'static, Result<DiaryEntry, DomainError>>,
|
entries: &[DiaryEntry],
|
||||||
format: ExportFormat,
|
format: ExportFormat,
|
||||||
) -> BoxStream<'static, Result<Bytes, DomainError>> {
|
) -> Result<Vec<u8>, DomainError> {
|
||||||
match format {
|
match format {
|
||||||
ExportFormat::Csv => stream_csv(stream),
|
ExportFormat::Csv => serialize_csv(entries),
|
||||||
ExportFormat::Json => stream_json(stream),
|
ExportFormat::Json => serialize_json(entries),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn stream_csv(
|
fn serialize_csv(entries: &[DiaryEntry]) -> Result<Vec<u8>, DomainError> {
|
||||||
entries: BoxStream<'static, Result<DiaryEntry, DomainError>>,
|
let mut out =
|
||||||
) -> BoxStream<'static, Result<Bytes, DomainError>> {
|
String::from("title,year,director,rating,comment,watched_at,external_metadata_id\n");
|
||||||
use futures::StreamExt;
|
for e in entries {
|
||||||
let header = futures::stream::once(async {
|
let title = csv_escape(e.movie().title().value());
|
||||||
Ok(Bytes::from_static(
|
let year = e.movie().release_year().value();
|
||||||
b"title,year,director,rating,comment,watched_at,external_metadata_id,spoilers\n",
|
let director = e.movie().director().map(csv_escape).unwrap_or_default();
|
||||||
))
|
let rating = e.review().rating().value();
|
||||||
});
|
let comment = e
|
||||||
let rows = entries.map(|r| r.map(|e| Bytes::from(csv_row(&e))));
|
.review()
|
||||||
Box::pin(header.chain(rows))
|
.comment()
|
||||||
}
|
.map(|c| csv_escape(c.value()))
|
||||||
|
.unwrap_or_default();
|
||||||
fn stream_json(
|
let watched_at = e.review().watched_at().format("%Y-%m-%d");
|
||||||
stream: BoxStream<'static, Result<DiaryEntry, DomainError>>,
|
let ext_id = e
|
||||||
) -> BoxStream<'static, Result<Bytes, DomainError>> {
|
.movie()
|
||||||
Box::pin(async_stream::stream! {
|
.external_metadata_id()
|
||||||
futures::pin_mut!(stream);
|
.map(|id| id.value().to_string())
|
||||||
let mut is_first = true;
|
.unwrap_or_default();
|
||||||
while let Some(r) = futures::StreamExt::next(&mut stream).await {
|
out.push_str(&format!(
|
||||||
match r {
|
"{},{},{},{},{},{},{}\n",
|
||||||
Err(e) => { yield Err(e); return; }
|
title, year, director, rating, comment, watched_at, ext_id
|
||||||
Ok(entry) => {
|
));
|
||||||
let json = serde_json::to_string(&entry_to_json(&entry))
|
}
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string()));
|
Ok(out.into_bytes())
|
||||||
let json = match json {
|
|
||||||
Ok(s) => s,
|
|
||||||
Err(e) => { yield Err(e); return; }
|
|
||||||
};
|
|
||||||
let prefix = if is_first { "[" } else { "," };
|
|
||||||
is_first = false;
|
|
||||||
yield Ok(Bytes::from(format!("{}{}", prefix, json)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if is_first {
|
|
||||||
yield Ok(Bytes::from_static(b"[]"));
|
|
||||||
} else {
|
|
||||||
yield Ok(Bytes::from_static(b"]"));
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn csv_row(e: &DiaryEntry) -> String {
|
|
||||||
let title = csv_escape(e.movie().title().value());
|
|
||||||
let year = e.movie().release_year().value();
|
|
||||||
let director = e.movie().director().map(csv_escape).unwrap_or_default();
|
|
||||||
let rating = e.review().rating().value();
|
|
||||||
let comment = e
|
|
||||||
.review()
|
|
||||||
.comment()
|
|
||||||
.map(|c| csv_escape(c.value()))
|
|
||||||
.unwrap_or_default();
|
|
||||||
let watched_at = e.review().watched_at().format("%Y-%m-%d");
|
|
||||||
let ext_id = e
|
|
||||||
.movie()
|
|
||||||
.external_metadata_id()
|
|
||||||
.map(|id| id.value().to_string())
|
|
||||||
.unwrap_or_default();
|
|
||||||
let spoilers = e.review().spoilers();
|
|
||||||
format!(
|
|
||||||
"{},{},{},{},{},{},{},{}\n",
|
|
||||||
title, year, director, rating, comment, watched_at, ext_id, spoilers
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn csv_escape(s: &str) -> String {
|
fn csv_escape(s: &str) -> String {
|
||||||
@@ -95,15 +56,170 @@ fn csv_escape(s: &str) -> String {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn entry_to_json(e: &DiaryEntry) -> serde_json::Value {
|
fn serialize_json(entries: &[DiaryEntry]) -> Result<Vec<u8>, DomainError> {
|
||||||
serde_json::json!({
|
let arr: Vec<serde_json::Value> = entries
|
||||||
"title": e.movie().title().value(),
|
.iter()
|
||||||
"year": e.movie().release_year().value(),
|
.map(|e| {
|
||||||
"director": e.movie().director(),
|
serde_json::json!({
|
||||||
"rating": e.review().rating().value(),
|
"title": e.movie().title().value(),
|
||||||
"comment": e.review().comment().map(|c| c.value().to_string()),
|
"year": e.movie().release_year().value(),
|
||||||
"watched_at": e.review().watched_at().format("%Y-%m-%d").to_string(),
|
"director": e.movie().director(),
|
||||||
"external_metadata_id": e.movie().external_metadata_id().map(|id| id.value().to_string()),
|
"rating": e.review().rating().value(),
|
||||||
"spoilers": e.review().spoilers(),
|
"comment": e.review().comment().map(|c| c.value()),
|
||||||
})
|
"watched_at": e.review().watched_at().format("%Y-%m-%d").to_string(),
|
||||||
|
"external_metadata_id": e.movie().external_metadata_id().map(|id| id.value()),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
serde_json::to_vec_pretty(&arr).map_err(|e| DomainError::InfrastructureError(e.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::ExportAdapter;
|
||||||
|
use domain::{
|
||||||
|
models::{DiaryEntry, ExportFormat, Movie, Review},
|
||||||
|
ports::DiaryExporter,
|
||||||
|
value_objects::{ExternalMetadataId, MovieTitle, Rating, ReleaseYear},
|
||||||
|
};
|
||||||
|
|
||||||
|
fn make_entry(
|
||||||
|
title: &str,
|
||||||
|
year: u16,
|
||||||
|
director: Option<&str>,
|
||||||
|
rating: u8,
|
||||||
|
comment: Option<&str>,
|
||||||
|
) -> DiaryEntry {
|
||||||
|
make_entry_full(title, year, director, rating, comment, None)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn make_entry_full(
|
||||||
|
title: &str,
|
||||||
|
year: u16,
|
||||||
|
director: Option<&str>,
|
||||||
|
rating: u8,
|
||||||
|
comment: Option<&str>,
|
||||||
|
external_id: Option<&str>,
|
||||||
|
) -> DiaryEntry {
|
||||||
|
let movie = Movie::new(
|
||||||
|
external_id.map(|id| ExternalMetadataId::new(id.to_string()).unwrap()),
|
||||||
|
MovieTitle::new(title.to_string()).unwrap(),
|
||||||
|
ReleaseYear::new(year).unwrap(),
|
||||||
|
director.map(str::to_string),
|
||||||
|
None,
|
||||||
|
);
|
||||||
|
let user_id = domain::value_objects::UserId::from_uuid(uuid::Uuid::new_v4());
|
||||||
|
let review = Review::new(
|
||||||
|
movie.id().clone(),
|
||||||
|
user_id,
|
||||||
|
Rating::new(rating).unwrap(),
|
||||||
|
comment.map(|c| domain::value_objects::Comment::new(c.to_string()).unwrap()),
|
||||||
|
chrono::NaiveDate::from_ymd_opt(2024, 3, 15)
|
||||||
|
.unwrap()
|
||||||
|
.and_hms_opt(0, 0, 0)
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
DiaryEntry::new(movie, review)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn csv_has_header_and_one_row() {
|
||||||
|
let adapter = ExportAdapter;
|
||||||
|
let entry = make_entry(
|
||||||
|
"Inception",
|
||||||
|
2010,
|
||||||
|
Some("Christopher Nolan"),
|
||||||
|
5,
|
||||||
|
Some("great"),
|
||||||
|
);
|
||||||
|
let bytes = adapter
|
||||||
|
.serialize_entries(&[entry], ExportFormat::Csv)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let text = String::from_utf8(bytes).unwrap();
|
||||||
|
assert!(
|
||||||
|
text.starts_with(
|
||||||
|
"title,year,director,rating,comment,watched_at,external_metadata_id\n"
|
||||||
|
)
|
||||||
|
);
|
||||||
|
assert!(text.contains("Inception"));
|
||||||
|
assert!(text.contains("2010"));
|
||||||
|
assert!(text.contains("Christopher Nolan"));
|
||||||
|
assert!(text.contains("5"));
|
||||||
|
assert!(text.contains("great"));
|
||||||
|
assert!(text.contains("2024-03-15"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn csv_escapes_commas_in_title() {
|
||||||
|
let adapter = ExportAdapter;
|
||||||
|
let entry = make_entry("Tár, A Film", 2022, None, 4, None);
|
||||||
|
let bytes = adapter
|
||||||
|
.serialize_entries(&[entry], ExportFormat::Csv)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let text = String::from_utf8(bytes).unwrap();
|
||||||
|
assert!(text.contains("\"Tár, A Film\""));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn json_is_valid_array() {
|
||||||
|
let adapter = ExportAdapter;
|
||||||
|
let entry = make_entry("Dune", 2021, Some("Denis Villeneuve"), 5, None);
|
||||||
|
let bytes = adapter
|
||||||
|
.serialize_entries(&[entry], ExportFormat::Json)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let arr: Vec<serde_json::Value> = serde_json::from_slice(&bytes).unwrap();
|
||||||
|
assert_eq!(arr.len(), 1);
|
||||||
|
assert_eq!(arr[0]["title"], "Dune");
|
||||||
|
assert_eq!(arr[0]["year"], 2021);
|
||||||
|
assert_eq!(arr[0]["rating"], 5);
|
||||||
|
assert_eq!(arr[0]["comment"], serde_json::Value::Null);
|
||||||
|
assert_eq!(arr[0]["external_metadata_id"], serde_json::Value::Null);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn external_metadata_id_included_when_present() {
|
||||||
|
let adapter = ExportAdapter;
|
||||||
|
let entry = make_entry_full("Alien", 1979, None, 5, None, Some("tt0078748"));
|
||||||
|
let bytes = adapter
|
||||||
|
.serialize_entries(&[entry], ExportFormat::Json)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let arr: Vec<serde_json::Value> = serde_json::from_slice(&bytes).unwrap();
|
||||||
|
assert_eq!(arr[0]["external_metadata_id"], "tt0078748");
|
||||||
|
|
||||||
|
let bytes = adapter
|
||||||
|
.serialize_entries(
|
||||||
|
&[make_entry_full(
|
||||||
|
"Alien",
|
||||||
|
1979,
|
||||||
|
None,
|
||||||
|
5,
|
||||||
|
None,
|
||||||
|
Some("tt0078748"),
|
||||||
|
)],
|
||||||
|
ExportFormat::Csv,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let text = String::from_utf8(bytes).unwrap();
|
||||||
|
assert!(text.contains("tt0078748"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn empty_entries_returns_csv_header_only() {
|
||||||
|
let adapter = ExportAdapter;
|
||||||
|
let bytes = adapter
|
||||||
|
.serialize_entries(&[], ExportFormat::Csv)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let text = String::from_utf8(bytes).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
text,
|
||||||
|
"title,year,director,rating,comment,watched_at,external_metadata_id\n"
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user