Compare commits
225 Commits
62ddb014d2
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 7faf14fb2f | |||
| ddb5966c9b | |||
| 4ec231017e | |||
| fab236688b | |||
| 4683a408d7 | |||
| 6d4c70553a | |||
| ca7ca51949 | |||
| 33aa5bdab3 | |||
| b844339795 | |||
| cedb13d7a8 | |||
| aec5f6b058 | |||
| d9234ecd11 | |||
| 010ee404c8 | |||
| d4c42f8567 | |||
| 9c44330f14 | |||
| 2fa118570f | |||
| ded7517a8a | |||
| bf272bf8d9 | |||
| 6f34b7b5ec | |||
| 17d4de461b | |||
| 40cb15e7cb | |||
| c80287bb9e | |||
| 06ab5c8df1 | |||
| 57520c00f3 | |||
| b5cc7f8371 | |||
| 9ca5ada924 | |||
| 70d1f10e3d | |||
| 61980b0cfb | |||
| 7bf5c47f5b | |||
| ddf100cfc2 | |||
| cdff0de53d | |||
| 1e62f12903 | |||
| 66bd138927 | |||
| b29f3020e6 | |||
| 76edd52bb0 | |||
| b5ff43d9dc | |||
| b552c1d156 | |||
| f006ba00a8 | |||
| 2b295e10ba | |||
| 20ac0d3adf | |||
| 8ac87a3735 | |||
| 4f0f44dec3 | |||
| 96c753c2c6 | |||
| 822f3f9d9c | |||
| 55feaa353f | |||
| 3a3f3b3889 | |||
| ef9ecbae06 | |||
| db285b513b | |||
| 2617c77b42 | |||
| e618e1aa84 | |||
| 7dc372a7b6 | |||
| e39fcf6802 | |||
| b09ef4686a | |||
| 2074a2244e | |||
| 338ecb71c8 | |||
| 8cb90b256c | |||
| c05087a6c7 | |||
| 0fdc79af23 | |||
| 262ba5ca39 | |||
| 57c720b22f | |||
| 53b7f730cb | |||
| e8fa24bf9b | |||
| 7437ed89ad | |||
| b2a41db290 | |||
| 9b932cde8e | |||
| a68e19aad7 | |||
| 371a3cdc46 | |||
| 517a18da8a | |||
| 7df24a19ee | |||
| 549923b92e | |||
| 3cbb406ea7 | |||
| 21cc6ed437 | |||
| 5dc90724d3 | |||
| 9a894c3a95 | |||
| acc20d2f43 | |||
| a95be0b131 | |||
| f10b114e83 | |||
| c020135cd1 | |||
| ad55897871 | |||
| 87fcdc12ca | |||
| d14199813f | |||
| f52219b2b7 | |||
| 6e21ec115d | |||
| deae83cfd1 | |||
| c4d6b68ef9 | |||
| d8cff33679 | |||
| e9aa6131ae | |||
| 43f6c5679d | |||
| 956e51530e | |||
| b882569ee1 | |||
| 5dbc02b58f | |||
| d389e26e39 | |||
| 05d062f4e0 | |||
| 70b3ca0f5c | |||
| ac03182aa6 | |||
| 6d3182525f | |||
| 7bcbc59587 | |||
| d867a14b28 | |||
| 30a6200b5b | |||
| f4fd915e35 | |||
| f3eee9131b | |||
| 9e4370b068 | |||
| 37ab24be74 | |||
| 307113381f | |||
| 6d238b6c3d | |||
| a7a11dde08 | |||
| 988e15eac6 | |||
| fff5f4af2f | |||
| 213f9a2433 | |||
| 4dacbbfded | |||
| 886f26c7dc | |||
| 6a10ba15c1 | |||
| 237f1e7d32 | |||
| c647f4c13b | |||
| 3bb2dbee19 | |||
| b0bfc149e1 | |||
| 7e8a1b8379 | |||
| 4bd8dcbf05 | |||
| ebf9a9f4a8 | |||
| a76386345f | |||
| 49728f8cd7 | |||
| 5334312d64 | |||
| 81a377cbb2 | |||
| 689c8a9ac3 | |||
| 5e6bc93a6a | |||
| 4a3a99c6d2 | |||
| dacc057af6 | |||
| 01c1082290 | |||
| bd7dc648c4 | |||
| af8e58aeb8 | |||
| fd9a053702 | |||
| 092e769641 | |||
| b20d23fbb3 | |||
| b9c0b10740 | |||
| 15dc0e526b | |||
| cf2f4a1b4f | |||
| e7cdbf9ca7 | |||
| 837b7866af | |||
| c4908b7765 | |||
| dbc78a1ff4 | |||
| a97e263ed3 | |||
| b1d667d3cb | |||
| bf73d4a695 | |||
| 7b9b0f9ffe | |||
| 7d6f874ae7 | |||
| 4206bb4b06 | |||
| 004243dcbb | |||
| c798b851dc | |||
| c18d4eebc1 | |||
| 3f6e01ed65 | |||
| 19642175eb | |||
| 8ca378b25f | |||
| fad73a9fab | |||
| 627db45a56 | |||
| 976d872eed | |||
| 6c7ce24e1f | |||
| 6668ba511c | |||
| 430fbb21ea | |||
| f262417971 | |||
| d94ccbe057 | |||
| e4b8ba550e | |||
| 3cec726e3d | |||
| e8e83d3f16 | |||
| 8cabc6af70 | |||
| e378191045 | |||
| bca07b7824 | |||
| 857896f057 | |||
| e905842b62 | |||
| 83103e5eb5 | |||
| fc086de7f7 | |||
| 3a66f89609 | |||
| 45d6183ea4 | |||
| 241063c914 | |||
| 3f483f8f81 | |||
| c842ad6a55 | |||
| a5cf62e281 | |||
| 6fb00f9205 | |||
| d52120d6a9 | |||
| e57ddd78ac | |||
| 0d02f23f4f | |||
| 86639853d2 | |||
| 7155bea78e | |||
| 8429d13db0 | |||
| cb611bcc7d | |||
| bb503f3ce8 | |||
| bf0350c87a | |||
| 9e13f04e9c | |||
| e69f77a99f | |||
| 1e063b6580 | |||
| f160adcd1c | |||
| efd1214a4c | |||
| 21c33b169e | |||
| 490bd97a40 | |||
| d45d8aa913 | |||
| f00a2cbbb8 | |||
| c0b3fb6940 | |||
| ea43911984 | |||
| 5a15bea3d4 | |||
| 5e740ba2a1 | |||
| 7ef8912d69 | |||
| ac05cdfeaf | |||
| b171d2d1e2 | |||
| 59b42ce810 | |||
| 5a6abdcc23 | |||
| a95d831fd1 | |||
| 4c75113c4f | |||
| 8fec989dc6 | |||
| 8c31a2b829 | |||
| 4df78221a8 | |||
| e8b2d4f7ee | |||
| c878c0358f | |||
| 4067dedb28 | |||
| 28170c95d4 | |||
| 62fd6682c6 | |||
| b9210b6c4e | |||
| ac7edd6953 | |||
| dcc9244d4e | |||
| aadad3cfb0 | |||
| 6bd728fd50 | |||
| 1b9a6617f3 | |||
| 14066ea469 | |||
| 7456a18fc9 | |||
| c2985dd579 | |||
| 84ddf04d28 | |||
| d1f9f55d4f |
@@ -7,3 +7,7 @@ target/
|
||||
# .cargo and .sqlx are needed at build time (SQLX_OFFLINE mode)
|
||||
docs/
|
||||
dev.db
|
||||
spa/node_modules/
|
||||
spa/dist/
|
||||
spa/.env
|
||||
spa/.env.local
|
||||
|
||||
86
.env.example
86
.env.example
@@ -1,65 +1,55 @@
|
||||
# Database backend — "sqlite" (default) or "postgres"
|
||||
DATABASE_BACKEND=sqlite
|
||||
# ── Required ──────────────────────────────────────────────────
|
||||
|
||||
# Option A: SQLite (default, zero external dependencies)
|
||||
DATABASE_URL=sqlite://movies.db
|
||||
|
||||
# Option B: PostgreSQL
|
||||
# DATABASE_BACKEND=postgres
|
||||
# DATABASE_URL=postgres://user:password@localhost:5432/movies_diary
|
||||
# Database (SQLite — file auto-created on first run)
|
||||
DATABASE_URL=sqlite:///data/movies.db
|
||||
|
||||
# Authentication
|
||||
JWT_SECRET=change-me
|
||||
JWT_TTL_SECONDS=86400
|
||||
JWT_SECRET=change-me-to-a-random-string
|
||||
|
||||
# OMDb/TMDB metadata
|
||||
OMDB_API_KEY=your-key
|
||||
TMDB_API_KEY=your-key
|
||||
# Movie metadata — one of these is required (TMDB preferred)
|
||||
# TMDB_API_KEY=your-tmdb-key
|
||||
OMDB_API_KEY=your-omdb-key
|
||||
|
||||
# Poster storage — Option A (local) is active. To use S3, comment it out and uncomment Option B:
|
||||
# ── Recommended ──────────────────────────────────────────────
|
||||
|
||||
# Option A: local filesystem (zero external dependencies)
|
||||
POSTER_STORAGE_BACKEND=local
|
||||
POSTER_STORAGE_PATH=./posters
|
||||
# Public URL (used for ActivityPub federation and canonical links)
|
||||
BASE_URL=https://yourdomain.example.com
|
||||
|
||||
# Option B: S3-compatible (MinIO, AWS S3, etc.)
|
||||
# POSTER_STORAGE_BACKEND=s3
|
||||
# Enable sign-ups (default: false — set true so you can register)
|
||||
ALLOW_REGISTRATION=true
|
||||
|
||||
# ── 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_BUCKET=posters
|
||||
# MINIO_REGION=minio
|
||||
# MINIO_ACCESS_KEY_ID=minioadmin
|
||||
# MINIO_SECRET_ACCESS_KEY=minioadmin
|
||||
|
||||
# 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
|
||||
# ── Optional ─────────────────────────────────────────────────
|
||||
|
||||
# Event bus — "db" (default) or "nats"
|
||||
# The worker binary must run alongside the presentation to process events.
|
||||
EVENT_BUS_BACKEND=db
|
||||
# TMDb enrichment (cast, crew, genres — separate from search metadata above)
|
||||
# TMDB_API_KEY=your-tmdb-key
|
||||
|
||||
# Option A: DB queue (default — no extra infrastructure needed)
|
||||
# Events are persisted in the same database as the app and polled by the worker.
|
||||
# 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)
|
||||
|
||||
# Option B: NATS (at-least-once delivery, recommended for higher throughput)
|
||||
# EVENT_BUS_BACKEND=nats
|
||||
# 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
|
||||
|
||||
# Image conversion (optional — converts stored images to save disk space)
|
||||
# Disable by default; enable in the worker by setting ENABLED=true.
|
||||
# Image conversion (converts uploaded posters to AVIF or WebP)
|
||||
# IMAGE_CONVERSION_ENABLED=false
|
||||
# IMAGE_CONVERSION_FORMAT=avif # avif | webp
|
||||
# IMAGE_CONVERSION_FORMAT=avif
|
||||
|
||||
RUST_LOG=presentation=debug,tower_http=debug,worker=info,application=info
|
||||
# Server
|
||||
# HOST=0.0.0.0
|
||||
# PORT=3000
|
||||
# RATE_LIMIT=60
|
||||
# SECURE_COOKIES=true
|
||||
# RUST_LOG=presentation=info,tower_http=info,worker=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
|
||||
|
||||
42
.gitea/workflows/ci.yml
Normal file
42
.gitea/workflows/ci.yml
Normal file
@@ -0,0 +1,42 @@
|
||||
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: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
target
|
||||
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
|
||||
restore-keys: ${{ runner.os }}-cargo-
|
||||
|
||||
- name: fmt
|
||||
run: cargo fmt --all -- --check
|
||||
|
||||
- name: clippy
|
||||
run: cargo clippy --all-targets -- -D warnings
|
||||
|
||||
- name: test
|
||||
run: cargo test
|
||||
51
.github/workflows/ci.yml
vendored
51
.github/workflows/ci.yml
vendored
@@ -20,7 +20,7 @@ jobs:
|
||||
- name: Install Rust stable
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
components: rustfmt
|
||||
components: rustfmt, clippy
|
||||
|
||||
- name: Cache cargo
|
||||
uses: actions/cache@v4
|
||||
@@ -35,30 +35,47 @@ jobs:
|
||||
- name: fmt
|
||||
run: cargo fmt --all -- --check
|
||||
|
||||
- name: clippy
|
||||
run: cargo clippy --all-targets -- -D warnings
|
||||
|
||||
- name: test
|
||||
run: cargo test
|
||||
|
||||
release-build:
|
||||
name: Release build
|
||||
docker:
|
||||
name: Build & Push Docker Image
|
||||
runs-on: ubuntu-latest
|
||||
if: github.ref == 'refs/heads/master' && github.event_name == 'push'
|
||||
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: Install Rust stable
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Cache cargo
|
||||
uses: actions/cache@v4
|
||||
- name: Log in to GHCR
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
target
|
||||
key: ${{ runner.os }}-cargo-release-${{ hashFiles('**/Cargo.lock') }}
|
||||
restore-keys: ${{ runner.os }}-cargo-release-
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: build (release)
|
||||
run: cargo build --release -p presentation -p worker
|
||||
- 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=sqlite,sqlite-federation
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -16,3 +16,4 @@
|
||||
docs/
|
||||
|
||||
imgs/
|
||||
.sqlx/
|
||||
@@ -1,98 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT COUNT(*) FROM reviews",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "COUNT(*)",
|
||||
"ordinal": 0,
|
||||
"type_info": "Integer"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 0
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "0963b9661182e139cd760bbabb0d6ea3a301a2a3adbdfdda4a88f333a1144c77"
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO users (id, email, username, password_hash, created_at, role) VALUES (?, ?, ?, ?, ?, ?)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 6
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "0acf3515a4d1bef7a2458d878481ba3b11c9f252311579f7daba335f70d78f07"
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "DELETE FROM user_profile_fields WHERE user_id = ?",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "11f7dd8da277aaf950e2a428f8e072cde8d806ca5b4007bbc882aada5c46ae63"
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "DELETE FROM import_sessions WHERE expires_at < datetime('now')",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 0
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "1c70d5d455e5ab3dfb68d35ce5255c7e0e86b9f6549ae8ae09247806f1321086"
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT id, email, username, password_hash, role, bio, avatar_path, banner_path, also_known_as 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"
|
||||
},
|
||||
{
|
||||
"name": "bio",
|
||||
"ordinal": 5,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "avatar_path",
|
||||
"ordinal": 6,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "banner_path",
|
||||
"ordinal": 7,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "also_known_as",
|
||||
"ordinal": 8,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "1dd3efb043635e638f1c3d72923a4ccfb9c9810baee06cfac5ad4af5749e4c6e"
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "DELETE FROM import_sessions WHERE user_id = ? AND expires_at < datetime('now')",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "34a0a7b5e6a7f2b97b59e9de6a34b41a7128a465c0957915c7ed7031c6b83fb0"
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "INSERT INTO user_profile_fields (id, user_id, name, value, position) VALUES (?, ?, ?, ?, ?)",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 5
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "5bde1c64a1dec54f348058c9d93842676aa3149bdfc4012f3f3318677a56336d"
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT name, value FROM user_profile_fields WHERE user_id = ? ORDER BY position ASC",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "name",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "value",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "5e447e9558515934d8f0c08e91342c0df0b29101223f370a126fb0ee76e3b9bd"
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "UPDATE import_sessions SET field_mappings = ?, row_results = ? WHERE id = ?",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 3
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "759b45ac8426d93d4668e208003d52957f2f52d8a021cc6f117cb6f241689a07"
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
{
|
||||
"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 u.avatar_path\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, u.avatar_path\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"
|
||||
},
|
||||
{
|
||||
"name": "avatar_path",
|
||||
"ordinal": 4,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 0
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "771236034946abb52809203ba9a1259900e343174cf3f435fc18d9e689deb187"
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT id, email, username, password_hash, role, bio, avatar_path, banner_path, also_known_as 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"
|
||||
},
|
||||
{
|
||||
"name": "bio",
|
||||
"ordinal": 5,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "avatar_path",
|
||||
"ordinal": 6,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "banner_path",
|
||||
"ordinal": 7,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "also_known_as",
|
||||
"ordinal": 8,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "7cb37c7e3df2a945859e12a186a479b9f9f431691d5f0e4ee460cd559f5412b4"
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "DELETE FROM import_profiles WHERE id = ?",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "9024c2b533d0100f18d5a5550220a148d8dc29bbf0df715f895fa4248d83785f"
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "DELETE FROM import_sessions WHERE id = ?",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "bf4aaf630ebefde88d87a95c257bbeafaf39e2f53611dab435d485648eb7e598"
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "DELETE FROM movies WHERE id = ?",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "e431381ad41c1c2f7b9c89509d5e3f4c19cb52dcfff66772145cd80c53c16883"
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "SELECT id, email, username, password_hash, role, bio, avatar_path, banner_path, also_known_as 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"
|
||||
},
|
||||
{
|
||||
"name": "bio",
|
||||
"ordinal": 5,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "avatar_path",
|
||||
"ordinal": 6,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "banner_path",
|
||||
"ordinal": 7,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "also_known_as",
|
||||
"ordinal": 8,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "e6413dcabae4a72628a2abf33a8b65da6f95b7c3c015f2633fcf00c045b9f08b"
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"db_name": "SQLite",
|
||||
"query": "DELETE FROM reviews WHERE id = ?",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": []
|
||||
},
|
||||
"hash": "f84e5483ca4210aec67b38cc1a9de4a42c12891025236abc48ea4f175292a6cc"
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
87
CONTRIBUTING.md
Normal file
87
CONTRIBUTING.md
Normal file
@@ -0,0 +1,87 @@
|
||||
# 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 presentation # 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 # runs fmt-check + clippy + test
|
||||
```
|
||||
|
||||
Or individually:
|
||||
|
||||
```bash
|
||||
cargo fmt --check
|
||||
cargo clippy -- -D warnings
|
||||
cargo test
|
||||
cd spa && bunx tsc --noEmit
|
||||
```
|
||||
|
||||
All four must pass. PRs with clippy warnings or failing tests won't be merged.
|
||||
|
||||
## Architecture
|
||||
|
||||
The project follows hexagonal (ports & adapters) architecture. See `architecture.mmd` for the full diagram.
|
||||
|
||||
**Key rules:**
|
||||
- Presentation handlers never touch repositories directly — all domain logic goes through use cases in the `application` crate
|
||||
- Application use cases return raw domain data — URL formatting, date display, and view model assembly belong in presentation mappers (`presentation/src/mappers/`)
|
||||
- Use cases called from presentation handlers take `&AppContext`. Functions called from adapter event handlers take individual `Arc<dyn Trait>` params to keep adapter dependencies explicit
|
||||
|
||||
```
|
||||
domain → pure types, traits (ports), zero deps
|
||||
application → use cases, orchestration
|
||||
presentation → Axum handlers, routes, OpenAPI
|
||||
worker → event consumer, background jobs
|
||||
adapters/* → implements domain ports (sqlite, postgres, AP, etc.)
|
||||
spa/ → React SPA (TanStack Router + shadcn/ui)
|
||||
```
|
||||
|
||||
### Adding a new feature
|
||||
|
||||
1. **Domain first** — models in `domain/src/models/`, ports in `ports.rs`, events in `events.rs`
|
||||
2. **Adapters** — implement ports in both `sqlite` and `postgres` adapters, add migration
|
||||
3. **Application** — use cases in `application/src/<domain>/`, wire into `context.rs`
|
||||
4. **API types** — DTOs in `api-types/src/`
|
||||
5. **Presentation** — handler file in `handlers/<domain>.rs`, routes in `routes.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`
|
||||
|
||||
### Database adapters
|
||||
|
||||
Both SQLite and PostgreSQL are supported. If you add a migration or repository, implement it for both. The postgres adapter uses `$1, $2` params and `TIMESTAMPTZ`; SQLite uses `?` and text datetimes.
|
||||
|
||||
### Federation (ActivityPub)
|
||||
|
||||
Federation is feature-gated (`#[cfg(feature = "federation")]`). If your feature should federate, add domain events, handle them in `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+ unit tests; integration tests for the presentation layer are welcome
|
||||
- **Docs** — API usage examples, deployment guides
|
||||
267
Cargo.lock
generated
267
Cargo.lock
generated
@@ -6,6 +6,7 @@ version = 4
|
||||
name = "activitypub"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"ammonia",
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"axum",
|
||||
@@ -260,6 +261,19 @@ version = "0.2.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
|
||||
|
||||
[[package]]
|
||||
name = "ammonia"
|
||||
version = "4.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "17e913097e1a2124b46746c980134e8c954bc17a6a59bb3fde96f088d126dde6"
|
||||
dependencies = [
|
||||
"cssparser",
|
||||
"html5ever",
|
||||
"maplit",
|
||||
"tendril",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "android_system_properties"
|
||||
version = "0.1.5"
|
||||
@@ -300,9 +314,14 @@ name = "application"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"bytes",
|
||||
"chrono",
|
||||
"domain",
|
||||
"futures",
|
||||
"hex",
|
||||
"rand 0.9.4",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"uuid",
|
||||
@@ -549,6 +568,28 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-stream"
|
||||
version = "0.3.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476"
|
||||
dependencies = [
|
||||
"async-stream-impl",
|
||||
"futures-core",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-stream-impl"
|
||||
version = "0.3.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-task"
|
||||
version = "4.7.1"
|
||||
@@ -1236,6 +1277,29 @@ dependencies = [
|
||||
"phf",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cssparser"
|
||||
version = "0.35.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e901edd733a1472f944a45116df3f846f54d37e67e68640ac8bb69689aca2aa"
|
||||
dependencies = [
|
||||
"cssparser-macros",
|
||||
"dtoa-short",
|
||||
"itoa",
|
||||
"phf",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cssparser-macros"
|
||||
version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13b588ba4ac1a99f7f2964d24b3d896ddc6bf847ee3855dbd4366f058cfcd331"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "csv"
|
||||
version = "1.4.0"
|
||||
@@ -1537,9 +1601,11 @@ name = "domain"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"bytes",
|
||||
"chrono",
|
||||
"email_address",
|
||||
"futures",
|
||||
"serde",
|
||||
"thiserror 2.0.18",
|
||||
"uuid",
|
||||
]
|
||||
@@ -1550,6 +1616,21 @@ version = "0.15.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b"
|
||||
|
||||
[[package]]
|
||||
name = "dtoa"
|
||||
version = "1.0.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590"
|
||||
|
||||
[[package]]
|
||||
name = "dtoa-short"
|
||||
version = "0.3.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87"
|
||||
dependencies = [
|
||||
"dtoa",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dunce"
|
||||
version = "1.0.5"
|
||||
@@ -1764,9 +1845,12 @@ dependencies = [
|
||||
name = "export"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"async-stream",
|
||||
"async-trait",
|
||||
"bytes",
|
||||
"chrono",
|
||||
"domain",
|
||||
"futures",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
"uuid",
|
||||
@@ -1903,6 +1987,16 @@ version = "1.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
|
||||
|
||||
[[package]]
|
||||
name = "futf"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df420e2e84819663797d1ec6544b13c5be84629e7bb00dc960d6917db2987843"
|
||||
dependencies = [
|
||||
"mac",
|
||||
"new_debug_unreachable",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures"
|
||||
version = "0.3.32"
|
||||
@@ -2205,6 +2299,17 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "html5ever"
|
||||
version = "0.35.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "55d958c2f74b664487a2035fe1dadb032c48718a03b63f3ab0b8537db8549ed4"
|
||||
dependencies = [
|
||||
"log",
|
||||
"markup5ever",
|
||||
"match_token",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http"
|
||||
version = "0.2.12"
|
||||
@@ -2524,7 +2629,7 @@ dependencies = [
|
||||
"async-trait",
|
||||
"domain",
|
||||
"image",
|
||||
"image-storage",
|
||||
"object-storage",
|
||||
"object_store",
|
||||
"ravif",
|
||||
"tokio",
|
||||
@@ -2533,20 +2638,6 @@ dependencies = [
|
||||
"webp",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "image-storage"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"domain",
|
||||
"infer",
|
||||
"object_store",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "image-webp"
|
||||
version = "0.2.4"
|
||||
@@ -2682,6 +2773,15 @@ version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "jellyfin"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"domain",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jni"
|
||||
version = "0.22.4"
|
||||
@@ -2770,9 +2870,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "k-ap"
|
||||
version = "0.3.1"
|
||||
version = "0.4.0"
|
||||
source = "sparse+https://git.gabrielkaszewski.dev/api/packages/GKaszewski/cargo/"
|
||||
checksum = "f73de37ac4feab6d7b78e73c60acbb07933c2be58dcbb12e8a34201f66e0480d"
|
||||
checksum = "ccaa914953bfd45ea206e11826da8f61ce1fbe02f8fe0622880527046ad6ae24"
|
||||
dependencies = [
|
||||
"activitypub_federation",
|
||||
"anyhow",
|
||||
@@ -2965,6 +3065,12 @@ version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
|
||||
|
||||
[[package]]
|
||||
name = "mac"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4"
|
||||
|
||||
[[package]]
|
||||
name = "mac_address"
|
||||
version = "1.1.8"
|
||||
@@ -2975,6 +3081,34 @@ dependencies = [
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "maplit"
|
||||
version = "1.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d"
|
||||
|
||||
[[package]]
|
||||
name = "markup5ever"
|
||||
version = "0.35.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "311fe69c934650f8f19652b3946075f0fc41ad8757dbb68f1ca14e7900ecc1c3"
|
||||
dependencies = [
|
||||
"log",
|
||||
"tendril",
|
||||
"web_atoms",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "match_token"
|
||||
version = "0.35.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac84fd3f360fcc43dc5f5d186f02a94192761a080e8bc58621ad4d12296a58cf"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "matchers"
|
||||
version = "0.2.0"
|
||||
@@ -3354,6 +3488,22 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "object-storage"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"bytes",
|
||||
"domain",
|
||||
"futures",
|
||||
"infer",
|
||||
"object_store",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "object_store"
|
||||
version = "0.11.2"
|
||||
@@ -3657,6 +3807,15 @@ version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
|
||||
|
||||
[[package]]
|
||||
name = "plex"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"domain",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "png"
|
||||
version = "0.18.1"
|
||||
@@ -3715,9 +3874,12 @@ name = "postgres"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-stream",
|
||||
"async-trait",
|
||||
"bytes",
|
||||
"chrono",
|
||||
"domain",
|
||||
"futures",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sqlx",
|
||||
@@ -3791,6 +3953,12 @@ dependencies = [
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "precomputed-hash"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
|
||||
|
||||
[[package]]
|
||||
name = "presentation"
|
||||
version = "0.1.0"
|
||||
@@ -3803,17 +3971,21 @@ dependencies = [
|
||||
"auth",
|
||||
"axum",
|
||||
"axum-governor",
|
||||
"bytes",
|
||||
"chrono",
|
||||
"domain",
|
||||
"dotenvy",
|
||||
"export",
|
||||
"futures",
|
||||
"http-body-util",
|
||||
"image-storage",
|
||||
"importer",
|
||||
"infer",
|
||||
"jellyfin",
|
||||
"metadata",
|
||||
"nats",
|
||||
"object-storage",
|
||||
"percent-encoding",
|
||||
"plex",
|
||||
"poster-fetcher",
|
||||
"postgres",
|
||||
"postgres-event-queue",
|
||||
@@ -4981,9 +5153,12 @@ name = "sqlite"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-stream",
|
||||
"async-trait",
|
||||
"bytes",
|
||||
"chrono",
|
||||
"domain",
|
||||
"futures",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sqlx",
|
||||
@@ -5245,6 +5420,31 @@ version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
|
||||
|
||||
[[package]]
|
||||
name = "string_cache"
|
||||
version = "0.8.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bf776ba3fa74f83bf4b63c3dcbbf82173db2632ed8452cb2d891d33f459de70f"
|
||||
dependencies = [
|
||||
"new_debug_unreachable",
|
||||
"parking_lot",
|
||||
"phf_shared",
|
||||
"precomputed-hash",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "string_cache_codegen"
|
||||
version = "0.5.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c711928715f1fe0fe509c53b43e993a9a557babc2d0a3567d0a3006f1ac931a0"
|
||||
dependencies = [
|
||||
"phf_generator",
|
||||
"phf_shared",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "stringprep"
|
||||
version = "0.1.5"
|
||||
@@ -5401,6 +5601,17 @@ dependencies = [
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tendril"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d24a120c5fc464a3458240ee02c299ebcb9d67b5249c8848b09d639dca8d7bb0"
|
||||
dependencies = [
|
||||
"futf",
|
||||
"mac",
|
||||
"utf-8",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "terminfo"
|
||||
version = "0.9.0"
|
||||
@@ -5999,6 +6210,12 @@ dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "utf-8"
|
||||
version = "0.7.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
|
||||
|
||||
[[package]]
|
||||
name = "utf8_iter"
|
||||
version = "1.0.4"
|
||||
@@ -6315,6 +6532,18 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "web_atoms"
|
||||
version = "0.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "57ffde1dc01240bdf9992e3205668b235e59421fd085e8a317ed98da0178d414"
|
||||
dependencies = [
|
||||
"phf",
|
||||
"phf_codegen",
|
||||
"string_cache",
|
||||
"string_cache_codegen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webp"
|
||||
version = "0.3.1"
|
||||
@@ -6895,10 +7124,10 @@ dependencies = [
|
||||
"dotenvy",
|
||||
"export",
|
||||
"image-converter",
|
||||
"image-storage",
|
||||
"importer",
|
||||
"metadata",
|
||||
"nats",
|
||||
"object-storage",
|
||||
"poster-fetcher",
|
||||
"poster-sync",
|
||||
"postgres",
|
||||
|
||||
21
Cargo.toml
21
Cargo.toml
@@ -4,7 +4,7 @@ members = [
|
||||
"crates/adapters/event-publisher",
|
||||
"crates/adapters/metadata",
|
||||
"crates/adapters/poster-fetcher",
|
||||
"crates/adapters/image-storage",
|
||||
"crates/adapters/object-storage",
|
||||
"crates/adapters/poster-sync",
|
||||
"crates/adapters/rss",
|
||||
"crates/adapters/sqlite",
|
||||
@@ -27,6 +27,8 @@ members = [
|
||||
"crates/tui",
|
||||
"crates/worker",
|
||||
"crates/adapters/importer",
|
||||
"crates/adapters/jellyfin",
|
||||
"crates/adapters/plex",
|
||||
"crates/adapters/sqlite-search",
|
||||
"crates/adapters/postgres-search",
|
||||
]
|
||||
@@ -34,7 +36,9 @@ resolver = "2"
|
||||
|
||||
[workspace.dependencies]
|
||||
tokio = { version = "1.0", features = ["macros", "net", "rt", "rt-multi-thread", "sync", "time"] }
|
||||
bytes = "1"
|
||||
futures = "0.3"
|
||||
async-stream = "0.3"
|
||||
dotenvy = "0.15"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
@@ -49,9 +53,11 @@ sqlx = { version = "0.8.6", features = [
|
||||
"runtime-tokio-rustls",
|
||||
"sqlite",
|
||||
"uuid",
|
||||
"macros",
|
||||
] }
|
||||
rand = "0.9"
|
||||
reqwest = { version = "0.13", features = ["json", "query"] }
|
||||
sha2 = "0.10"
|
||||
hex = "0.4"
|
||||
object_store = { version = "0.11", features = ["aws"] }
|
||||
axum = { version = "0.8.8", features = ["macros", "multipart"] }
|
||||
csv = "1"
|
||||
@@ -64,7 +70,7 @@ presentation = { path = "crates/presentation" }
|
||||
auth = { path = "crates/adapters/auth" }
|
||||
metadata = { path = "crates/adapters/metadata" }
|
||||
poster-fetcher = { path = "crates/adapters/poster-fetcher" }
|
||||
image-storage = { path = "crates/adapters/image-storage" }
|
||||
object-storage = { path = "crates/adapters/object-storage" }
|
||||
poster-sync = { path = "crates/adapters/poster-sync" }
|
||||
event-publisher = { path = "crates/adapters/event-publisher" }
|
||||
rss = { path = "crates/adapters/rss" }
|
||||
@@ -80,6 +86,15 @@ 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" }
|
||||
jellyfin = { path = "crates/adapters/jellyfin" }
|
||||
plex = { path = "crates/adapters/plex" }
|
||||
image-converter = { path = "crates/adapters/image-converter" }
|
||||
sqlite-search = { path = "crates/adapters/sqlite-search" }
|
||||
postgres-search = { path = "crates/adapters/postgres-search" }
|
||||
|
||||
[profile.dev]
|
||||
debug = 1 # line tables only — still debuggable, much faster linking
|
||||
split-debuginfo = "unpacked" # macOS: skip dsymutil on every link
|
||||
|
||||
[profile.dev.package."*"]
|
||||
opt-level = 2 # compile deps faster at runtime; paid once, cached after
|
||||
|
||||
19
Dockerfile
19
Dockerfile
@@ -1,3 +1,11 @@
|
||||
# ----- spa -----
|
||||
FROM node:22-slim AS spa-builder
|
||||
WORKDIR /spa
|
||||
COPY spa/package.json spa/package-lock.json ./
|
||||
RUN npm ci
|
||||
COPY spa/ .
|
||||
RUN npm run build
|
||||
|
||||
# ----- build -----
|
||||
FROM rust:slim-bookworm AS builder
|
||||
|
||||
@@ -6,7 +14,6 @@ WORKDIR /build
|
||||
# Cache dependency compilation separately from source
|
||||
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/auth/Cargo.toml crates/adapters/auth/Cargo.toml
|
||||
COPY crates/adapters/event-payload/Cargo.toml crates/adapters/event-payload/Cargo.toml
|
||||
@@ -14,10 +21,12 @@ COPY crates/adapters/event-publisher/Cargo.toml crates/adapters/event-publishe
|
||||
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/object-storage/Cargo.toml crates/adapters/object-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/jellyfin/Cargo.toml crates/adapters/jellyfin/Cargo.toml
|
||||
COPY crates/adapters/plex/Cargo.toml crates/adapters/plex/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
|
||||
@@ -52,8 +61,8 @@ RUN cargo fetch
|
||||
# Now copy real sources (invalidates cache only on source changes)
|
||||
COPY crates ./crates
|
||||
|
||||
# .cargo/config.toml sets SQLX_OFFLINE=true; .sqlx contains the pre-verified query cache.
|
||||
# No live database needed at compile time.
|
||||
# All sqlx queries use the runtime API (no query! macros), so no database
|
||||
# or .sqlx cache is needed at compile time.
|
||||
#
|
||||
# To build with PostgreSQL backend instead:
|
||||
# --build-arg FEATURES=postgres,postgres-federation
|
||||
@@ -69,6 +78,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
ca-certificates \
|
||||
wget \
|
||||
libwebp7 \
|
||||
fonts-dejavu-core \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /app
|
||||
@@ -76,6 +86,7 @@ WORKDIR /app
|
||||
COPY --from=builder /build/target/release/presentation ./presentation
|
||||
COPY --from=builder /build/target/release/worker ./worker
|
||||
COPY static ./static
|
||||
COPY --from=spa-builder /spa/dist ./spa/dist
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
|
||||
11
Makefile
11
Makefile
@@ -1,9 +1,18 @@
|
||||
.DEFAULT_GOAL := check
|
||||
|
||||
# Run the full local check suite — same order as CI would.
|
||||
check: fmt-check clippy test
|
||||
check: fmt-check clippy test check-appcontext
|
||||
@echo "✅ All checks passed"
|
||||
|
||||
# Enforce that no application use case imports AppContext (god-object guard).
|
||||
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"
|
||||
|
||||
# Apply rustfmt to all files.
|
||||
fmt:
|
||||
cargo fmt
|
||||
|
||||
259
README.md
259
README.md
@@ -1,6 +1,49 @@
|
||||
# Movies Diary
|
||||
|
||||
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.
|
||||
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 or PostgreSQL.
|
||||
|
||||
[](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
|
||||
|
||||
@@ -16,13 +59,29 @@ A self-hosted, server-side rendered movie logging system with a full REST API. B
|
||||
- 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
|
||||
- Jellyfin/Plex auto-import — media server sends a webhook on playback stop, movies land in a watch queue; review and confirm with a rating to create diary entries; per-user webhook tokens with SHA-256 auth; setup UI at `/settings/integrations`
|
||||
- Annual Wrap-Up — Spotify Wrapped for movies: per-user and instance-wide year-in-review with stats (top directors, actors, genres, rating distribution, watch time, rewatches, budget analysis), shareable HTML page at `/wrapups/{user_id}/{year}`; admin-triggered or auto-generated in January
|
||||
- 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)
|
||||
- CSV and JSON diary export
|
||||
- File importer: upload CSV, TSV, JSON, or XLSX from any source (Letterboxd, IMDb, etc.), map columns to domain fields via a step-by-step wizard or REST API, save mapping profiles for repeat imports
|
||||
- REST API v1 (`/api/v1/`) with full feature parity with the HTML interface
|
||||
- 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`)
|
||||
- Per-IP rate limiting via token bucket (production-grade, backed by `axum-governor`)
|
||||
- Terminal UI client (`crates/tui`) for logging reviews, bulk CSV import, and diary browsing
|
||||
- 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`, 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
|
||||
|
||||
@@ -48,6 +107,8 @@ adapters/
|
||||
rss — RSS/Atom feed generation
|
||||
export — CSV and JSON diary serialization
|
||||
importer — CSV/TSV/JSON/XLSX parser and column mapper for bulk import
|
||||
jellyfin — Jellyfin webhook payload parser (MediaServerParser adapter)
|
||||
plex — Plex webhook payload parser (MediaServerParser adapter; requires Plex Pass)
|
||||
event-payload — shared event serialization DTOs (used by all event bus adapters)
|
||||
sqlite-event-queue — durable polling event queue backed by SQLite
|
||||
postgres-event-queue — durable polling event queue backed by PostgreSQL
|
||||
@@ -59,6 +120,7 @@ adapters/
|
||||
sqlite-federation — SQLite-backed federation repository
|
||||
postgres-federation — PostgreSQL-backed federation repository
|
||||
tui — terminal UI client (ratatui); shares api-types with presentation for typed API access
|
||||
spa/ — React SPA (TanStack Router + shadcn/ui + Vite); served at /app/ by the backend
|
||||
```
|
||||
|
||||
## Prerequisites
|
||||
@@ -68,56 +130,35 @@ tui — terminal UI client (ratatui); shares api-types with pres
|
||||
- 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)
|
||||
|
||||
## Environment Variables
|
||||
## Configuration
|
||||
|
||||
A `.env.example` file is provided at the repo root — copy it to `.env` and fill in your values.
|
||||
Copy `.env.example` to `.env` and set the values below. Required fields must be set before the server will start.
|
||||
|
||||
```env
|
||||
# Database
|
||||
DATABASE_URL=sqlite://movies.db
|
||||
|
||||
# Authentication
|
||||
JWT_SECRET=change-me
|
||||
|
||||
# OMDb metadata
|
||||
OMDB_API_KEY=your-key
|
||||
|
||||
# TMDb metadata + enrichment (optional — enables full cast/crew/genre data)
|
||||
# TMDB_API_KEY=your-key
|
||||
|
||||
# Public base URL (used for ActivityPub actor URLs and canonical links)
|
||||
BASE_URL=https://yourdomain.example.com
|
||||
|
||||
# Image storage — pick one backend:
|
||||
|
||||
# Option A: local filesystem (zero deps)
|
||||
IMAGE_STORAGE_BACKEND=local
|
||||
IMAGE_STORAGE_PATH=./images
|
||||
|
||||
# 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
|
||||
|
||||
# Image conversion (optional — converts stored images to AVIF or WebP to save space)
|
||||
# IMAGE_CONVERSION_ENABLED=false
|
||||
# IMAGE_CONVERSION_FORMAT=avif # avif or webp
|
||||
|
||||
# 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
|
||||
|
||||
# Event bus — "db" (default, uses same database) or "nats"
|
||||
EVENT_BUS_BACKEND=db
|
||||
# NATS_URL=nats://localhost:4222 # required when EVENT_BUS_BACKEND=nats
|
||||
```
|
||||
| Variable | Default | Required | Description |
|
||||
|---|---|---|---|
|
||||
| `DATABASE_URL` | `sqlite://movies.db` | Yes | SQLite or PostgreSQL connection string |
|
||||
| `JWT_SECRET` | — | Yes | Secret for JWT signing — use a long random string |
|
||||
| `OMDB_API_KEY` | — | Yes | [OMDb](https://www.omdbapi.com/apikey.aspx) key for movie metadata |
|
||||
| `TMDB_API_KEY` | — | No | [TMDb](https://www.themoviedb.org/settings/api) key — enables cast, crew, genres, enrichment |
|
||||
| `BASE_URL` | — | Yes | Public URL of your instance (used for ActivityPub actor URLs) |
|
||||
| `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` | — | S3 only | Region (e.g. `minio`) |
|
||||
| `MINIO_ACCESS_KEY_ID` | — | S3 only | Access key ID |
|
||||
| `MINIO_SECRET_ACCESS_KEY` | — | S3 only | Secret access key |
|
||||
| `IMAGE_CONVERSION_ENABLED` | `false` | No | Convert stored images to AVIF or WebP |
|
||||
| `IMAGE_CONVERSION_FORMAT` | `avif` | No | `avif` or `webp` |
|
||||
| `HOST` | `0.0.0.0` | No | Bind address |
|
||||
| `PORT` | `3000` | No | HTTP port |
|
||||
| `RATE_LIMIT` | `60` | No | Requests per minute per IP |
|
||||
| `ALLOW_REGISTRATION` | `true` | No | Set `false` to disable new sign-ups |
|
||||
| `SECURE_COOKIES` | `true` | No | Must be `true` when serving over HTTPS |
|
||||
| `RUST_LOG` | — | No | Log verbosity (e.g. `presentation=info,worker=info`) |
|
||||
| `CORS_ORIGINS` | `*` | No | Comma-separated allowed origins for SPA dev |
|
||||
| `EVENT_BUS_BACKEND` | `db` | No | `db` (default) or `nats` |
|
||||
| `NATS_URL` | — | NATS only | NATS connection URL (e.g. `nats://localhost:4222`) |
|
||||
|
||||
The `worker` binary must run alongside `presentation` to process events:
|
||||
|
||||
@@ -143,13 +184,29 @@ Interactive API documentation is available at runtime:
|
||||
- **Swagger UI** — `http://localhost:3000/docs`
|
||||
- **Scalar** — `http://localhost:3000/scalar`
|
||||
|
||||
## Terminal UI
|
||||
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.
|
||||
|
||||
## 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
|
||||
cargo run -p tui
|
||||
```
|
||||
|
||||
Supports review logging, bulk CSV import (column order matches the export format), and diary browsing with review history.
|
||||
Supports review logging, bulk CSV import, and diary browsing.
|
||||
|
||||
## Development
|
||||
|
||||
@@ -166,46 +223,82 @@ make test # cargo test
|
||||
## Test
|
||||
|
||||
```bash
|
||||
cargo test # full workspace (requires DATABASE_URL for sqlx offline checks)
|
||||
cargo test -p application # domain-level unit tests only — no database required
|
||||
cargo test # full workspace (requires DATABASE_URL for sqlx offline checks)
|
||||
cargo test -p application # business logic tests only — no database required
|
||||
cargo test -p domain # domain model + value object tests
|
||||
cargo llvm-cov -p application -p domain # line coverage report (requires cargo-llvm-cov)
|
||||
```
|
||||
|
||||
The `application` crate has unit tests for core use cases backed by in-memory fakes from `domain`'s `test-helpers` feature. These run without a database and are the fastest feedback loop for business logic changes.
|
||||
The `application` and `domain` crates have 400+ unit tests covering all use case modules (auth, diary, goals, import, integrations, movies, person, search, users, watchlist, wrapup) backed by in-memory fakes from `domain`'s `test-helpers` feature. These run without a database and are the fastest feedback loop for business logic changes.
|
||||
|
||||
## Docker
|
||||
|
||||
The image contains both `presentation` (HTTP server) and `worker` (event processor). Run them as separate containers sharing the same data volume:
|
||||
### Quick start
|
||||
|
||||
```bash
|
||||
# Build (SQLite + federation + NATS support)
|
||||
docker build -t movies-diary \
|
||||
--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
|
||||
cp .env.example .env
|
||||
# Edit .env — set JWT_SECRET and OMDB_API_KEY (or TMDB_API_KEY)
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
To build for PostgreSQL: `--build-arg FEATURES=postgres,postgres-federation,nats`
|
||||
This builds and starts the HTTP server (port 3000) and event worker. Data is persisted in a Docker volume.
|
||||
|
||||
### Manual docker run
|
||||
|
||||
The image contains both `presentation` 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
|
||||
```
|
||||
|
||||
Build for PostgreSQL: `--build-arg FEATURES=postgres,postgres-federation`
|
||||
|
||||
## 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
|
||||
|
||||
|
||||
140
architecture.mmd
Normal file
140
architecture.mmd
Normal file
@@ -0,0 +1,140 @@
|
||||
---
|
||||
title: Movies Diary — Hexagonal Architecture
|
||||
---
|
||||
graph TB
|
||||
subgraph Binaries["Binaries (Composition Root)"]
|
||||
WEB["presentation<br/><i>Axum web server</i><br/>Routes, Handlers, Mappers"]
|
||||
WORKER["worker<br/><i>Event consumer</i><br/>Concurrent dispatch, graceful shutdown"]
|
||||
TUI["tui<br/><i>Terminal UI</i>"]
|
||||
end
|
||||
|
||||
subgraph Application["Application Layer"]
|
||||
direction TB
|
||||
CTX["AppContext<br/><i>Repositories + Services</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, get_diary,<br/>get_activity_feed, export"]
|
||||
UC_MOVIES["movies<br/>get_movies, get_movie_profile,<br/>enrich_movie, request_enrichment,<br/>sync_poster, reindex_search"]
|
||||
UC_IMPORT["import<br/>create_session, apply_mapping,<br/>execute, profiles"]
|
||||
UC_USERS["users<br/>get_users, get_profile,<br/>update_profile"]
|
||||
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"]
|
||||
end
|
||||
subgraph EventHandlers["Event Handlers"]
|
||||
EH_ENRICH["EnrichmentHandler"]
|
||||
EH_DISCOVER["MovieDiscoveryIndexer"]
|
||||
EH_CLEANUP["SearchCleanupHandler"]
|
||||
EH_REINDEX["SearchReindexHandler"]
|
||||
EH_WRAPUP["WrapUpEventHandler"]
|
||||
end
|
||||
subgraph Jobs["Periodic Jobs"]
|
||||
JOB_IMPORT["ImportSessionCleanup"]
|
||||
JOB_WATCH["WatchEventCleanup"]
|
||||
JOB_STALE["EnrichmentStaleness"]
|
||||
JOB_WRAPGEN["WrapUpAutoGenerate"]
|
||||
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, DiaryEntry,<br/>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["MovieRepository<br/>ReviewRepository<br/>DiaryRepository<br/>UserRepository<br/>WatchlistRepository<br/>WatchEventRepository<br/>WebhookTokenRepository<br/>ImportSessionRepository<br/>MovieProfileRepository<br/>WrapUpRepository<br/>GoalRepository<br/>UserSettingsRepository"]
|
||||
P_SERVICES["AuthService<br/>MetadataClient<br/>PosterFetcherClient<br/>ObjectStorage<br/>EventPublisher<br/>EventConsumer<br/>PasswordHasher<br/>DiaryExporter<br/>DocumentParser"]
|
||||
P_SEARCH["SearchPort<br/>SearchCommand<br/>PersonQuery<br/>PersonCommand"]
|
||||
P_FEDERATION["SocialQueryPort<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/>SearchReindexRequested, ...</i>"]
|
||||
VO["Value Objects<br/><i>MovieId, UserId, Rating,<br/>Email, Username, Password, ...</i>"]
|
||||
end
|
||||
|
||||
subgraph ApiTypes["api-types (0 domain deps)"]
|
||||
DTO["DTOs<br/><i>MovieDto, ReviewDto,<br/>FeedEntryDto, UserSummaryDto,<br/>CastMemberDto, ...</i>"]
|
||||
end
|
||||
|
||||
subgraph Adapters["Adapters (implement Port Traits)"]
|
||||
direction TB
|
||||
subgraph Storage["Storage"]
|
||||
A_SQLITE["sqlite<br/><i>SQLite repos</i>"]
|
||||
A_PG["postgres<br/><i>PostgreSQL repos</i>"]
|
||||
A_SQLITE_SEARCH["sqlite-search<br/><i>FTS5</i>"]
|
||||
A_PG_SEARCH["postgres-search<br/><i>tsvector/GIN</i>"]
|
||||
A_OBJ["object-storage<br/><i>S3 / filesystem</i>"]
|
||||
end
|
||||
subgraph Messaging["Messaging"]
|
||||
A_NATS["nats<br/><i>JetStream / Core</i>"]
|
||||
A_PG_QUEUE["postgres-event-queue<br/><i>Polling, dead-letter</i>"]
|
||||
A_PAYLOAD["event-payload<br/><i>Serde (de)serialization</i>"]
|
||||
end
|
||||
subgraph External["External Services"]
|
||||
A_METADATA["metadata<br/><i>TMDB 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</i>"]
|
||||
A_SQLITE_FED["sqlite-federation"]
|
||||
A_PG_FED["postgres-federation"]
|
||||
end
|
||||
subgraph Media["Media Processing"]
|
||||
A_IMG["image-converter<br/><i>AVIF/WebP</i>"]
|
||||
A_POSTER_SYNC["poster-sync"]
|
||||
end
|
||||
subgraph Presentation["Presentation Helpers"]
|
||||
A_TEMPLATE["template-askama<br/><i>HTML templates</i>"]
|
||||
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>"]
|
||||
end
|
||||
subgraph Webhooks["Webhook Parsers"]
|
||||
A_JELLYFIN["jellyfin"]
|
||||
A_PLEX["plex"]
|
||||
end
|
||||
end
|
||||
|
||||
%% Dependency arrows
|
||||
WEB -->|"uses"| Application
|
||||
WEB -->|"maps to"| ApiTypes
|
||||
WORKER -->|"uses"| Application
|
||||
|
||||
Application -->|"depends on"| Domain
|
||||
UC_WRAPUP -->|"delegates to"| DS_WRAPUP
|
||||
|
||||
Adapters -.->|"implements"| Ports
|
||||
|
||||
%% Key data flows
|
||||
WEB ===|"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 ApiTypes api
|
||||
@@ -4,7 +4,7 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
k-ap = { version = "0.3.1", registry = "gitea" }
|
||||
k-ap = { version = "0.4.0", registry = "gitea" }
|
||||
domain = { workspace = true }
|
||||
axum = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
@@ -16,3 +16,4 @@ tracing = { workspace = true }
|
||||
async-trait = { workspace = true }
|
||||
|
||||
url = { version = "2", features = ["serde"] }
|
||||
ammonia = "4"
|
||||
|
||||
@@ -5,11 +5,15 @@ use chrono::{DateTime, Utc};
|
||||
use k_ap::{ApContentReader, ApObjectHandler};
|
||||
use url::Url;
|
||||
|
||||
use crate::{review_handler::ReviewObjectHandler, watchlist_handler::WatchlistObjectHandler};
|
||||
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]
|
||||
@@ -40,12 +44,15 @@ impl ApObjectHandler for CompositeObjectHandler {
|
||||
) -> anyhow::Result<()> {
|
||||
let is_watchlist = object.get("watchlistEntry").and_then(|v| v.as_bool()) == Some(true)
|
||||
|| (object.get("movieTitle").is_some() && object.get("rating").is_none());
|
||||
let is_goal = object.get("goal").and_then(|v| v.as_bool()) == Some(true);
|
||||
if object.get("rating").is_some() {
|
||||
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::debug!(ap_id = %ap_id, "ignoring Create for unknown object type");
|
||||
tracing::warn!(ap_id = %ap_id, "ignoring Create for unknown object type");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -56,8 +63,11 @@ impl ApObjectHandler for CompositeObjectHandler {
|
||||
actor_url: &Url,
|
||||
object: serde_json::Value,
|
||||
) -> anyhow::Result<()> {
|
||||
let is_goal = object.get("goal").and_then(|v| v.as_bool()) == Some(true);
|
||||
if object.get("rating").is_some() {
|
||||
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 {
|
||||
Ok(())
|
||||
}
|
||||
@@ -66,12 +76,14 @@ impl ApObjectHandler for CompositeObjectHandler {
|
||||
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(())
|
||||
}
|
||||
|
||||
|
||||
@@ -1,21 +1,23 @@
|
||||
use async_trait::async_trait;
|
||||
use chrono::Datelike;
|
||||
use domain::ports::EventHandler;
|
||||
use domain::{
|
||||
errors::DomainError,
|
||||
events::DomainEvent,
|
||||
ports::LocalApContentQuery,
|
||||
value_objects::{ReviewId, UserId},
|
||||
ports::{LocalApContentQuery, UserFederationSettingsQuery},
|
||||
value_objects::{MovieId, ReviewId, UserId},
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
use k_ap::{ActivityPubService, ApVisibility};
|
||||
|
||||
use crate::objects::review_to_ap_object;
|
||||
use crate::urls::{actor_url, review_url};
|
||||
use crate::objects::{goal_to_ap_object, review_to_ap_object};
|
||||
use crate::urls::{actor_url, goal_url, review_url};
|
||||
|
||||
pub struct ActivityPubEventHandler {
|
||||
ap_service: Arc<ActivityPubService>,
|
||||
content_query: Arc<dyn LocalApContentQuery>,
|
||||
federation_settings: Arc<dyn UserFederationSettingsQuery>,
|
||||
base_url: String,
|
||||
}
|
||||
|
||||
@@ -23,11 +25,13 @@ impl ActivityPubEventHandler {
|
||||
pub fn new(
|
||||
ap_service: Arc<ActivityPubService>,
|
||||
content_query: Arc<dyn LocalApContentQuery>,
|
||||
federation_settings: Arc<dyn UserFederationSettingsQuery>,
|
||||
base_url: String,
|
||||
) -> Self {
|
||||
Self {
|
||||
ap_service,
|
||||
content_query,
|
||||
federation_settings,
|
||||
base_url,
|
||||
}
|
||||
}
|
||||
@@ -80,6 +84,49 @@ impl EventHandler for ActivityPubEventHandler {
|
||||
.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}")))?;
|
||||
let activity: serde_json::Value =
|
||||
serde_json::from_str(activity_json).map_err(|e| {
|
||||
DomainError::InfrastructureError(format!("bad activity JSON: {e}"))
|
||||
})?;
|
||||
self.ap_service
|
||||
.deliver_to_inbox(inbox, activity, *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())),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
@@ -87,6 +134,19 @@ impl EventHandler for ActivityPubEventHandler {
|
||||
|
||||
impl ActivityPubEventHandler {
|
||||
async fn on_review_logged(&self, user_id: &UserId, review_id: &ReviewId) -> anyhow::Result<()> {
|
||||
let flags = self
|
||||
.federation_settings
|
||||
.get_federation_flags(user_id)
|
||||
.await
|
||||
.unwrap_or(domain::ports::FederationFlags {
|
||||
goals: true,
|
||||
reviews: true,
|
||||
watchlist: true,
|
||||
});
|
||||
if !flags.reviews {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let review = match self.content_query.get_review_by_id(review_id).await? {
|
||||
Some(r) => r,
|
||||
None => return Ok(()),
|
||||
@@ -129,6 +189,9 @@ impl ActivityPubEventHandler {
|
||||
.broadcast_create_note(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(())
|
||||
}
|
||||
|
||||
@@ -137,6 +200,19 @@ impl ActivityPubEventHandler {
|
||||
user_id: &UserId,
|
||||
review_id: &ReviewId,
|
||||
) -> anyhow::Result<()> {
|
||||
let flags = self
|
||||
.federation_settings
|
||||
.get_federation_flags(user_id)
|
||||
.await
|
||||
.unwrap_or(domain::ports::FederationFlags {
|
||||
goals: true,
|
||||
reviews: true,
|
||||
watchlist: true,
|
||||
});
|
||||
if !flags.reviews {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let review = match self.content_query.get_review_by_id(review_id).await? {
|
||||
Some(r) => r,
|
||||
None => return Ok(()),
|
||||
@@ -203,6 +279,19 @@ impl ActivityPubEventHandler {
|
||||
external_metadata_id: &Option<String>,
|
||||
added_at: &chrono::NaiveDateTime,
|
||||
) -> anyhow::Result<()> {
|
||||
let flags = self
|
||||
.federation_settings
|
||||
.get_federation_flags(user_id)
|
||||
.await
|
||||
.unwrap_or(domain::ports::FederationFlags {
|
||||
goals: true,
|
||||
reviews: true,
|
||||
watchlist: true,
|
||||
});
|
||||
if !flags.watchlist {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
use crate::urls::watchlist_entry_url;
|
||||
let ap_id = watchlist_entry_url(&self.base_url, user_id.value(), movie_id.value());
|
||||
let actor = actor_url(&self.base_url, user_id.value());
|
||||
@@ -250,4 +339,165 @@ impl ActivityPubEventHandler {
|
||||
.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.content_query.get_movie_by_id(movie_id).await?;
|
||||
let movie = match movie {
|
||||
Some(m) => m,
|
||||
None => return Ok(()),
|
||||
};
|
||||
let poster_url = movie
|
||||
.poster_path()
|
||||
.map(|p| format!("{}/images/{}", self.base_url, p.value()));
|
||||
|
||||
for entry in entries {
|
||||
let review = entry.review();
|
||||
let user_id = review.user_id();
|
||||
|
||||
let flags = self
|
||||
.federation_settings
|
||||
.get_federation_flags(user_id)
|
||||
.await
|
||||
.unwrap_or(domain::ports::FederationFlags {
|
||||
goals: true,
|
||||
reviews: true,
|
||||
watchlist: true,
|
||||
});
|
||||
if !flags.reviews {
|
||||
continue;
|
||||
}
|
||||
|
||||
let ap_id = review_url(&self.base_url, review.id());
|
||||
let actor = actor_url(&self.base_url, user_id.value());
|
||||
|
||||
let obj = review_to_ap_object(
|
||||
review,
|
||||
ap_id,
|
||||
actor,
|
||||
movie.title().value().to_string(),
|
||||
movie.release_year().value(),
|
||||
poster_url.clone(),
|
||||
&self.base_url,
|
||||
);
|
||||
let json = serde_json::to_value(obj)?;
|
||||
|
||||
self.ap_service
|
||||
.broadcast_update_note(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(domain::ports::FederationFlags {
|
||||
goals: true,
|
||||
reviews: true,
|
||||
watchlist: true,
|
||||
});
|
||||
if !flags.goals {
|
||||
return Ok(());
|
||||
}
|
||||
let Some((goal, current)) = self
|
||||
.content_query
|
||||
.get_goal_with_progress(user_id, year)
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let ap_id = goal_url(&self.base_url, user_id.value(), year);
|
||||
let actor = actor_url(&self.base_url, user_id.value());
|
||||
let obj = goal_to_ap_object(
|
||||
ap_id,
|
||||
actor,
|
||||
year,
|
||||
goal.target_count(),
|
||||
current,
|
||||
&self.base_url,
|
||||
);
|
||||
let json = serde_json::to_value(obj)?;
|
||||
self.ap_service
|
||||
.broadcast_update_note(user_id.value(), json, ApVisibility::Public, vec![])
|
||||
.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(domain::ports::FederationFlags {
|
||||
goals: true,
|
||||
reviews: true,
|
||||
watchlist: true,
|
||||
});
|
||||
if !flags.goals {
|
||||
return Ok(());
|
||||
}
|
||||
let current = self
|
||||
.content_query
|
||||
.get_goal_with_progress(user_id, year)
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(|(_, c)| c)
|
||||
.unwrap_or(0);
|
||||
|
||||
let ap_id = goal_url(&self.base_url, user_id.value(), year);
|
||||
let actor = actor_url(&self.base_url, user_id.value());
|
||||
let obj = goal_to_ap_object(ap_id, actor, year, target_count, current, &self.base_url);
|
||||
let json = serde_json::to_value(obj)?;
|
||||
if is_create {
|
||||
self.ap_service
|
||||
.broadcast_create_note(user_id.value(), json, ApVisibility::Public, vec![])
|
||||
.await?;
|
||||
} else {
|
||||
self.ap_service
|
||||
.broadcast_update_note(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(domain::ports::FederationFlags {
|
||||
goals: true,
|
||||
reviews: true,
|
||||
watchlist: true,
|
||||
});
|
||||
if !flags.goals {
|
||||
return Ok(());
|
||||
}
|
||||
let ap_id = goal_url(&self.base_url, user_id.value(), year);
|
||||
self.ap_service
|
||||
.broadcast_delete_to_followers(user_id.value(), ap_id)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,8 +29,24 @@ impl k_ap::EventPublisher for FederationEventBridge {
|
||||
})
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!(e.to_string())),
|
||||
_ => {
|
||||
tracing::debug!("ignoring federation event: {:?}", event);
|
||||
FederationEvent::DeliveryRequested {
|
||||
inbox,
|
||||
activity,
|
||||
signing_actor_id,
|
||||
} => {
|
||||
let json = serde_json::to_string(&activity)
|
||||
.map_err(|e| anyhow::anyhow!("serialize activity: {e}"))?;
|
||||
self.domain_publisher
|
||||
.publish(&DomainEvent::FederationDeliveryRequested {
|
||||
inbox_url: inbox.to_string(),
|
||||
activity_json: json,
|
||||
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(())
|
||||
}
|
||||
}
|
||||
|
||||
95
crates/adapters/activitypub/src/goal_handler.rs
Normal file
95
crates/adapters/activitypub/src/goal_handler.rs
Normal file
@@ -0,0 +1,95 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use domain::{models::RemoteGoalEntry, ports::RemoteGoalRepository};
|
||||
use k_ap::ApObjectHandler;
|
||||
use url::Url;
|
||||
|
||||
use crate::objects::GoalObject;
|
||||
|
||||
pub struct GoalObjectHandler {
|
||||
pub remote_goal_repo: Arc<dyn RemoteGoalRepository>,
|
||||
}
|
||||
|
||||
#[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,6 +1,7 @@
|
||||
pub mod composite_handler;
|
||||
pub mod event_handler;
|
||||
pub mod federation_event_bridge;
|
||||
pub mod goal_handler;
|
||||
pub mod objects;
|
||||
pub mod port;
|
||||
pub mod remote_review_repository;
|
||||
@@ -9,6 +10,9 @@ pub(crate) mod urls;
|
||||
pub mod user_adapter;
|
||||
pub mod watchlist_handler;
|
||||
|
||||
pub const INSTANCE_ACTOR_ID: uuid::Uuid =
|
||||
uuid::Uuid::from_bytes([0, 0, 0, 0, 0, 0, 0x40, 0, 0x80, 0, 0, 0, 0, 0, 0, 0]);
|
||||
|
||||
// Re-export the generic base types that callers need
|
||||
pub use k_ap::{
|
||||
ActivityPubService, ActivityRepository, ActorRepository, ApContentReader, ApFederationConfig,
|
||||
@@ -45,8 +49,10 @@ pub struct ActivityPubDeps {
|
||||
pub blocklist_repo: std::sync::Arc<dyn BlocklistRepository>,
|
||||
pub review_store: std::sync::Arc<dyn RemoteReviewRepository>,
|
||||
pub remote_watchlist_repo: std::sync::Arc<dyn domain::ports::RemoteWatchlistRepository>,
|
||||
pub remote_goal_repo: std::sync::Arc<dyn domain::ports::RemoteGoalRepository>,
|
||||
pub local_ap_content: std::sync::Arc<dyn domain::ports::LocalApContentQuery>,
|
||||
pub user_repo: std::sync::Arc<dyn domain::ports::UserRepository>,
|
||||
pub federation_settings: std::sync::Arc<dyn domain::ports::UserFederationSettingsQuery>,
|
||||
pub base_url: String,
|
||||
pub allow_registration: bool,
|
||||
pub event_publisher: std::sync::Arc<dyn domain::ports::EventPublisher>,
|
||||
@@ -60,8 +66,10 @@ pub async fn wire(deps: ActivityPubDeps) -> anyhow::Result<ActivityPubWire> {
|
||||
blocklist_repo,
|
||||
review_store,
|
||||
remote_watchlist_repo,
|
||||
remote_goal_repo,
|
||||
local_ap_content,
|
||||
user_repo,
|
||||
federation_settings,
|
||||
base_url,
|
||||
allow_registration,
|
||||
event_publisher,
|
||||
@@ -76,9 +84,11 @@ pub async fn wire(deps: ActivityPubDeps) -> anyhow::Result<ActivityPubWire> {
|
||||
content_query: std::sync::Arc::clone(&local_ap_content),
|
||||
base_url: base_url.clone(),
|
||||
});
|
||||
let goal_handler = std::sync::Arc::new(goal_handler::GoalObjectHandler { remote_goal_repo });
|
||||
let composite = std::sync::Arc::new(composite_handler::CompositeObjectHandler {
|
||||
review: review_handler,
|
||||
watchlist: watchlist_handler,
|
||||
goal: goal_handler,
|
||||
});
|
||||
|
||||
let federation_debug = std::env::var("FEDERATION_DEBUG")
|
||||
@@ -106,6 +116,7 @@ pub async fn wire(deps: ActivityPubDeps) -> anyhow::Result<ActivityPubWire> {
|
||||
user_repo,
|
||||
base_url.clone(),
|
||||
)))
|
||||
.signed_fetch_actor_id(INSTANCE_ACTOR_ID)
|
||||
.content_reader(composite.clone() as std::sync::Arc<dyn ApContentReader>)
|
||||
.object_handler(composite as std::sync::Arc<dyn ApObjectHandler>)
|
||||
.event_publisher(fed_event_bridge)
|
||||
@@ -120,6 +131,7 @@ pub async fn wire(deps: ActivityPubDeps) -> anyhow::Result<ActivityPubWire> {
|
||||
let event_handler = std::sync::Arc::new(ActivityPubEventHandler::new(
|
||||
std::sync::Arc::clone(&concrete),
|
||||
local_ap_content,
|
||||
federation_settings,
|
||||
base_url,
|
||||
)) as std::sync::Arc<dyn domain::ports::EventHandler>;
|
||||
|
||||
|
||||
@@ -191,6 +191,64 @@ pub fn watchlist_to_ap_object(input: WatchlistApInput) -> WatchlistObject {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Goal object ──────────────────────────────────────────────────────────────
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GoalObject {
|
||||
#[serde(rename = "type")]
|
||||
pub(crate) kind: NoteType,
|
||||
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: NoteType::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)],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests/objects.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -23,6 +23,7 @@ pub trait RemoteReviewRepository: Send + Sync {
|
||||
rating: u8,
|
||||
comment: Option<&str>,
|
||||
watched_at: NaiveDateTime,
|
||||
poster_url: Option<&str>,
|
||||
) -> Result<()>;
|
||||
|
||||
async fn delete_by_actor(&self, actor_url: &str) -> Result<()>;
|
||||
|
||||
@@ -77,13 +77,15 @@ impl ApObjectHandler for ReviewObjectHandler {
|
||||
_actor_url: &Url,
|
||||
object: serde_json::Value,
|
||||
) -> anyhow::Result<()> {
|
||||
let obj: ReviewObject = match serde_json::from_value(object) {
|
||||
let mut obj: ReviewObject = match serde_json::from_value(object) {
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
tracing::debug!("ignoring unrecognized Create object: {}", e);
|
||||
tracing::warn!("ignoring unrecognized Create object: {}", e);
|
||||
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 review_id = ReviewId::generate();
|
||||
@@ -130,13 +132,15 @@ impl ApObjectHandler for ReviewObjectHandler {
|
||||
actor_url: &Url,
|
||||
object: serde_json::Value,
|
||||
) -> anyhow::Result<()> {
|
||||
let obj: ReviewObject = match serde_json::from_value(object) {
|
||||
let mut obj: ReviewObject = match serde_json::from_value(object) {
|
||||
Ok(o) => o,
|
||||
Err(_) => {
|
||||
tracing::debug!(actor = %actor_url, "ignoring non-review Update activity");
|
||||
tracing::warn!(actor = %actor_url, "ignoring non-review Update activity");
|
||||
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 {
|
||||
anyhow::bail!("update actor does not match object attributed_to");
|
||||
@@ -149,6 +153,7 @@ impl ApObjectHandler for ReviewObjectHandler {
|
||||
obj.rating.min(5),
|
||||
obj.comment.as_deref(),
|
||||
obj.watched_at.naive_utc(),
|
||||
obj.poster_url.as_deref(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
|
||||
@@ -13,6 +13,11 @@ pub fn review_url(base_url: &str, review_id: &ReviewId) -> Url {
|
||||
.expect("base_url is always a valid URL prefix")
|
||||
}
|
||||
|
||||
pub fn goal_url(base_url: &str, user_id: uuid::Uuid, year: u16) -> Url {
|
||||
Url::parse(&format!("{}/users/{}/goals/{}", base_url, user_id, year))
|
||||
.expect("base_url is always a valid URL prefix")
|
||||
}
|
||||
|
||||
/// Builds the canonical watchlist entry URL: `{base_url}/users/{user_id}/watchlist/{movie_id}`
|
||||
pub fn watchlist_entry_url(base_url: &str, user_id: uuid::Uuid, movie_id: uuid::Uuid) -> Url {
|
||||
Url::parse(&format!(
|
||||
|
||||
@@ -24,7 +24,14 @@ impl ApObjectHandler for WatchlistObjectHandler {
|
||||
actor_url: &Url,
|
||||
object: serde_json::Value,
|
||||
) -> anyhow::Result<()> {
|
||||
let obj: WatchlistObject = serde_json::from_value(object)?;
|
||||
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(),
|
||||
|
||||
@@ -30,7 +30,7 @@ impl AuthConfig {
|
||||
let ttl_seconds = std::env::var("JWT_TTL_SECONDS")
|
||||
.ok()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(86400u64);
|
||||
.unwrap_or(900u64);
|
||||
Ok(Self {
|
||||
secret,
|
||||
ttl_seconds,
|
||||
|
||||
@@ -2,7 +2,10 @@ use chrono::NaiveDateTime;
|
||||
use domain::{
|
||||
errors::DomainError,
|
||||
events::DomainEvent,
|
||||
value_objects::{ExternalMetadataId, MovieId, PosterPath, Rating, ReviewId, UserId},
|
||||
models::{ExternalPersonId, PersonId},
|
||||
value_objects::{
|
||||
ExternalMetadataId, GoalId, MovieId, PosterPath, Rating, ReviewId, UserId, WrapUpId,
|
||||
},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
@@ -67,6 +70,50 @@ pub enum EventPayload {
|
||||
owner_user_id: String,
|
||||
follower_inbox_url: String,
|
||||
},
|
||||
FederationDeliveryRequested {
|
||||
inbox_url: String,
|
||||
activity_json: String,
|
||||
signing_actor_id: String,
|
||||
},
|
||||
WatchEventIngested {
|
||||
user_id: String,
|
||||
title: String,
|
||||
source: String,
|
||||
},
|
||||
WrapUpRequested {
|
||||
wrapup_id: String,
|
||||
user_id: Option<String>,
|
||||
start_date: String,
|
||||
end_date: String,
|
||||
},
|
||||
WrapUpCompleted {
|
||||
wrapup_id: String,
|
||||
},
|
||||
SearchReindexRequested,
|
||||
PosterSynced {
|
||||
movie_id: String,
|
||||
},
|
||||
GoalCreated {
|
||||
goal_id: String,
|
||||
user_id: String,
|
||||
year: u16,
|
||||
target_count: u32,
|
||||
},
|
||||
GoalUpdated {
|
||||
goal_id: String,
|
||||
user_id: String,
|
||||
year: u16,
|
||||
target_count: u32,
|
||||
},
|
||||
GoalDeleted {
|
||||
goal_id: String,
|
||||
user_id: String,
|
||||
year: u16,
|
||||
},
|
||||
PersonEnrichmentRequested {
|
||||
person_id: String,
|
||||
external_person_id: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl EventPayload {
|
||||
@@ -84,6 +131,16 @@ impl EventPayload {
|
||||
EventPayload::WatchlistEntryRemoved { .. } => "WatchlistEntryRemoved",
|
||||
EventPayload::FollowAccepted { .. } => "FollowAccepted",
|
||||
EventPayload::BackfillFollower { .. } => "BackfillFollower",
|
||||
EventPayload::FederationDeliveryRequested { .. } => "FederationDeliveryRequested",
|
||||
EventPayload::WatchEventIngested { .. } => "WatchEventIngested",
|
||||
EventPayload::WrapUpRequested { .. } => "WrapUpRequested",
|
||||
EventPayload::WrapUpCompleted { .. } => "WrapUpCompleted",
|
||||
EventPayload::SearchReindexRequested => "SearchReindexRequested",
|
||||
EventPayload::PosterSynced { .. } => "PosterSynced",
|
||||
EventPayload::GoalCreated { .. } => "GoalCreated",
|
||||
EventPayload::GoalUpdated { .. } => "GoalUpdated",
|
||||
EventPayload::GoalDeleted { .. } => "GoalDeleted",
|
||||
EventPayload::PersonEnrichmentRequested { .. } => "PersonEnrichmentRequested",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -153,7 +210,7 @@ impl From<&DomainEvent> for EventPayload {
|
||||
external_metadata_id,
|
||||
} => EventPayload::MovieEnrichmentRequested {
|
||||
movie_id: movie_id.value().to_string(),
|
||||
external_metadata_id: external_metadata_id.clone(),
|
||||
external_metadata_id: external_metadata_id.value().to_string(),
|
||||
},
|
||||
DomainEvent::ImageStored { key } => EventPayload::ImageStored { key: key.clone() },
|
||||
DomainEvent::WatchlistEntryAdded {
|
||||
@@ -193,6 +250,80 @@ impl From<&DomainEvent> for EventPayload {
|
||||
owner_user_id: owner_user_id.value().to_string(),
|
||||
follower_inbox_url: follower_inbox_url.clone(),
|
||||
},
|
||||
DomainEvent::FederationDeliveryRequested {
|
||||
inbox_url,
|
||||
activity_json,
|
||||
signing_actor_id,
|
||||
} => EventPayload::FederationDeliveryRequested {
|
||||
inbox_url: inbox_url.clone(),
|
||||
activity_json: activity_json.clone(),
|
||||
signing_actor_id: signing_actor_id.to_string(),
|
||||
},
|
||||
DomainEvent::WatchEventIngested {
|
||||
user_id,
|
||||
title,
|
||||
source,
|
||||
} => EventPayload::WatchEventIngested {
|
||||
user_id: user_id.value().to_string(),
|
||||
title: title.clone(),
|
||||
source: source.clone(),
|
||||
},
|
||||
DomainEvent::WrapUpRequested {
|
||||
wrapup_id,
|
||||
user_id,
|
||||
start_date,
|
||||
end_date,
|
||||
} => EventPayload::WrapUpRequested {
|
||||
wrapup_id: wrapup_id.value().to_string(),
|
||||
user_id: user_id.as_ref().map(|u| u.value().to_string()),
|
||||
start_date: start_date.to_string(),
|
||||
end_date: end_date.to_string(),
|
||||
},
|
||||
DomainEvent::WrapUpCompleted { wrapup_id } => EventPayload::WrapUpCompleted {
|
||||
wrapup_id: wrapup_id.value().to_string(),
|
||||
},
|
||||
DomainEvent::SearchReindexRequested => EventPayload::SearchReindexRequested,
|
||||
DomainEvent::PosterSynced { movie_id } => EventPayload::PosterSynced {
|
||||
movie_id: movie_id.value().to_string(),
|
||||
},
|
||||
DomainEvent::GoalCreated {
|
||||
goal_id,
|
||||
user_id,
|
||||
year,
|
||||
target_count,
|
||||
} => EventPayload::GoalCreated {
|
||||
goal_id: goal_id.value().to_string(),
|
||||
user_id: user_id.value().to_string(),
|
||||
year: *year,
|
||||
target_count: *target_count,
|
||||
},
|
||||
DomainEvent::GoalUpdated {
|
||||
goal_id,
|
||||
user_id,
|
||||
year,
|
||||
target_count,
|
||||
} => EventPayload::GoalUpdated {
|
||||
goal_id: goal_id.value().to_string(),
|
||||
user_id: user_id.value().to_string(),
|
||||
year: *year,
|
||||
target_count: *target_count,
|
||||
},
|
||||
DomainEvent::GoalDeleted {
|
||||
goal_id,
|
||||
user_id,
|
||||
year,
|
||||
} => EventPayload::GoalDeleted {
|
||||
goal_id: goal_id.value().to_string(),
|
||||
user_id: user_id.value().to_string(),
|
||||
year: *year,
|
||||
},
|
||||
DomainEvent::PersonEnrichmentRequested {
|
||||
person_id,
|
||||
external_person_id,
|
||||
} => EventPayload::PersonEnrichmentRequested {
|
||||
person_id: person_id.value().to_string(),
|
||||
external_person_id: external_person_id.value().to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -260,7 +391,8 @@ impl TryFrom<EventPayload> for DomainEvent {
|
||||
external_metadata_id,
|
||||
} => Ok(DomainEvent::MovieEnrichmentRequested {
|
||||
movie_id: MovieId::from_uuid(parse_uuid(&movie_id, "movie_id")?),
|
||||
external_metadata_id,
|
||||
external_metadata_id: ExternalMetadataId::new(external_metadata_id)
|
||||
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?,
|
||||
}),
|
||||
EventPayload::ImageStored { key } => Ok(DomainEvent::ImageStored { key }),
|
||||
EventPayload::WatchlistEntryAdded {
|
||||
@@ -300,6 +432,91 @@ impl TryFrom<EventPayload> for DomainEvent {
|
||||
owner_user_id: UserId::from_uuid(parse_uuid(&owner_user_id, "owner_user_id")?),
|
||||
follower_inbox_url,
|
||||
}),
|
||||
EventPayload::FederationDeliveryRequested {
|
||||
inbox_url,
|
||||
activity_json,
|
||||
signing_actor_id,
|
||||
} => Ok(DomainEvent::FederationDeliveryRequested {
|
||||
inbox_url,
|
||||
activity_json,
|
||||
signing_actor_id: parse_uuid(&signing_actor_id, "signing_actor_id")?,
|
||||
}),
|
||||
EventPayload::WatchEventIngested {
|
||||
user_id,
|
||||
title,
|
||||
source,
|
||||
} => Ok(DomainEvent::WatchEventIngested {
|
||||
user_id: UserId::from_uuid(parse_uuid(&user_id, "user_id")?),
|
||||
title,
|
||||
source,
|
||||
}),
|
||||
EventPayload::WrapUpRequested {
|
||||
wrapup_id,
|
||||
user_id,
|
||||
start_date,
|
||||
end_date,
|
||||
} => {
|
||||
let wid = parse_uuid(&wrapup_id, "wrapup_id")?;
|
||||
let uid = user_id.map(|s| parse_uuid(&s, "user_id")).transpose()?;
|
||||
let sd = chrono::NaiveDate::parse_from_str(&start_date, "%Y-%m-%d")
|
||||
.map_err(|e| DomainError::ValidationError(e.to_string()))?;
|
||||
let ed = chrono::NaiveDate::parse_from_str(&end_date, "%Y-%m-%d")
|
||||
.map_err(|e| DomainError::ValidationError(e.to_string()))?;
|
||||
Ok(DomainEvent::WrapUpRequested {
|
||||
wrapup_id: WrapUpId::from_uuid(wid),
|
||||
user_id: uid.map(UserId::from_uuid),
|
||||
start_date: sd,
|
||||
end_date: ed,
|
||||
})
|
||||
}
|
||||
EventPayload::WrapUpCompleted { wrapup_id } => {
|
||||
let wid = parse_uuid(&wrapup_id, "wrapup_id")?;
|
||||
Ok(DomainEvent::WrapUpCompleted {
|
||||
wrapup_id: WrapUpId::from_uuid(wid),
|
||||
})
|
||||
}
|
||||
EventPayload::SearchReindexRequested => Ok(DomainEvent::SearchReindexRequested),
|
||||
EventPayload::PosterSynced { movie_id } => Ok(DomainEvent::PosterSynced {
|
||||
movie_id: MovieId::from_uuid(parse_uuid(&movie_id, "movie_id")?),
|
||||
}),
|
||||
EventPayload::GoalCreated {
|
||||
goal_id,
|
||||
user_id,
|
||||
year,
|
||||
target_count,
|
||||
} => Ok(DomainEvent::GoalCreated {
|
||||
goal_id: GoalId::from_uuid(parse_uuid(&goal_id, "goal_id")?),
|
||||
user_id: UserId::from_uuid(parse_uuid(&user_id, "user_id")?),
|
||||
year,
|
||||
target_count,
|
||||
}),
|
||||
EventPayload::GoalUpdated {
|
||||
goal_id,
|
||||
user_id,
|
||||
year,
|
||||
target_count,
|
||||
} => Ok(DomainEvent::GoalUpdated {
|
||||
goal_id: GoalId::from_uuid(parse_uuid(&goal_id, "goal_id")?),
|
||||
user_id: UserId::from_uuid(parse_uuid(&user_id, "user_id")?),
|
||||
year,
|
||||
target_count,
|
||||
}),
|
||||
EventPayload::GoalDeleted {
|
||||
goal_id,
|
||||
user_id,
|
||||
year,
|
||||
} => Ok(DomainEvent::GoalDeleted {
|
||||
goal_id: GoalId::from_uuid(parse_uuid(&goal_id, "goal_id")?),
|
||||
user_id: UserId::from_uuid(parse_uuid(&user_id, "user_id")?),
|
||||
year,
|
||||
}),
|
||||
EventPayload::PersonEnrichmentRequested {
|
||||
person_id,
|
||||
external_person_id,
|
||||
} => Ok(DomainEvent::PersonEnrichmentRequested {
|
||||
person_id: PersonId::from_uuid(parse_uuid(&person_id, "person_id")?),
|
||||
external_person_id: ExternalPersonId::new(external_person_id),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,9 @@ domain = { workspace = true }
|
||||
async-trait = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
bytes = { workspace = true }
|
||||
async-stream = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
uuid = { workspace = true }
|
||||
|
||||
@@ -1,51 +1,89 @@
|
||||
use async_trait::async_trait;
|
||||
use bytes::Bytes;
|
||||
use domain::{
|
||||
errors::DomainError,
|
||||
models::{DiaryEntry, ExportFormat},
|
||||
ports::DiaryExporter,
|
||||
};
|
||||
use futures::stream::BoxStream;
|
||||
|
||||
pub struct ExportAdapter;
|
||||
|
||||
#[async_trait]
|
||||
impl DiaryExporter for ExportAdapter {
|
||||
async fn serialize_entries(
|
||||
fn stream_entries(
|
||||
&self,
|
||||
entries: &[DiaryEntry],
|
||||
stream: BoxStream<'static, Result<DiaryEntry, DomainError>>,
|
||||
format: ExportFormat,
|
||||
) -> Result<Vec<u8>, DomainError> {
|
||||
) -> BoxStream<'static, Result<Bytes, DomainError>> {
|
||||
match format {
|
||||
ExportFormat::Csv => serialize_csv(entries),
|
||||
ExportFormat::Json => serialize_json(entries),
|
||||
ExportFormat::Csv => stream_csv(stream),
|
||||
ExportFormat::Json => stream_json(stream),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_csv(entries: &[DiaryEntry]) -> Result<Vec<u8>, DomainError> {
|
||||
let mut out =
|
||||
String::from("title,year,director,rating,comment,watched_at,external_metadata_id\n");
|
||||
for e in entries {
|
||||
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();
|
||||
out.push_str(&format!(
|
||||
"{},{},{},{},{},{},{}\n",
|
||||
title, year, director, rating, comment, watched_at, ext_id
|
||||
));
|
||||
}
|
||||
Ok(out.into_bytes())
|
||||
fn stream_csv(
|
||||
entries: BoxStream<'static, Result<DiaryEntry, DomainError>>,
|
||||
) -> BoxStream<'static, Result<Bytes, DomainError>> {
|
||||
use futures::StreamExt;
|
||||
let header = futures::stream::once(async {
|
||||
Ok(Bytes::from_static(
|
||||
b"title,year,director,rating,comment,watched_at,external_metadata_id\n",
|
||||
))
|
||||
});
|
||||
let rows = entries.map(|r| r.map(|e| Bytes::from(csv_row(&e))));
|
||||
Box::pin(header.chain(rows))
|
||||
}
|
||||
|
||||
fn stream_json(
|
||||
stream: BoxStream<'static, Result<DiaryEntry, DomainError>>,
|
||||
) -> BoxStream<'static, Result<Bytes, DomainError>> {
|
||||
Box::pin(async_stream::stream! {
|
||||
futures::pin_mut!(stream);
|
||||
let mut is_first = true;
|
||||
while let Some(r) = futures::StreamExt::next(&mut stream).await {
|
||||
match r {
|
||||
Err(e) => { yield Err(e); return; }
|
||||
Ok(entry) => {
|
||||
let json = serde_json::to_string(&entry_to_json(&entry))
|
||||
.map_err(|e| DomainError::InfrastructureError(e.to_string()));
|
||||
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();
|
||||
format!(
|
||||
"{},{},{},{},{},{},{}\n",
|
||||
title, year, director, rating, comment, watched_at, ext_id
|
||||
)
|
||||
}
|
||||
|
||||
fn csv_escape(s: &str) -> String {
|
||||
@@ -56,22 +94,16 @@ fn csv_escape(s: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_json(entries: &[DiaryEntry]) -> Result<Vec<u8>, DomainError> {
|
||||
let arr: Vec<serde_json::Value> = entries
|
||||
.iter()
|
||||
.map(|e| {
|
||||
serde_json::json!({
|
||||
"title": e.movie().title().value(),
|
||||
"year": e.movie().release_year().value(),
|
||||
"director": e.movie().director(),
|
||||
"rating": e.review().rating().value(),
|
||||
"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()))
|
||||
fn entry_to_json(e: &DiaryEntry) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"title": e.movie().title().value(),
|
||||
"year": e.movie().release_year().value(),
|
||||
"director": e.movie().director(),
|
||||
"rating": e.review().rating().value(),
|
||||
"comment": e.review().comment().map(|c| c.value().to_string()),
|
||||
"watched_at": e.review().watched_at().format("%Y-%m-%d").to_string(),
|
||||
"external_metadata_id": e.movie().external_metadata_id().map(|id| id.value().to_string()),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -5,6 +5,27 @@ use domain::{
|
||||
value_objects::{ExternalMetadataId, MovieTitle, Rating, ReleaseYear},
|
||||
};
|
||||
|
||||
async fn collect_stream(
|
||||
stream: futures::stream::BoxStream<'static, Result<bytes::Bytes, domain::errors::DomainError>>,
|
||||
) -> Vec<u8> {
|
||||
use futures::StreamExt;
|
||||
let mut out = Vec::new();
|
||||
futures::pin_mut!(stream);
|
||||
while let Some(chunk) = stream.next().await {
|
||||
out.extend_from_slice(&chunk.unwrap());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn entry_stream(
|
||||
entries: Vec<domain::models::DiaryEntry>,
|
||||
) -> futures::stream::BoxStream<
|
||||
'static,
|
||||
Result<domain::models::DiaryEntry, domain::errors::DomainError>,
|
||||
> {
|
||||
Box::pin(futures::stream::iter(entries.into_iter().map(Ok)))
|
||||
}
|
||||
|
||||
fn make_entry(
|
||||
title: &str,
|
||||
year: u16,
|
||||
@@ -55,10 +76,8 @@ async fn csv_has_header_and_one_row() {
|
||||
5,
|
||||
Some("great"),
|
||||
);
|
||||
let bytes = adapter
|
||||
.serialize_entries(&[entry], ExportFormat::Csv)
|
||||
.await
|
||||
.unwrap();
|
||||
let bytes =
|
||||
collect_stream(adapter.stream_entries(entry_stream(vec![entry]), ExportFormat::Csv)).await;
|
||||
let text = String::from_utf8(bytes).unwrap();
|
||||
assert!(
|
||||
text.starts_with("title,year,director,rating,comment,watched_at,external_metadata_id\n")
|
||||
@@ -75,10 +94,8 @@ async fn csv_has_header_and_one_row() {
|
||||
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 bytes =
|
||||
collect_stream(adapter.stream_entries(entry_stream(vec![entry]), ExportFormat::Csv)).await;
|
||||
let text = String::from_utf8(bytes).unwrap();
|
||||
assert!(text.contains("\"Tár, A Film\""));
|
||||
}
|
||||
@@ -87,10 +104,8 @@ async fn csv_escapes_commas_in_title() {
|
||||
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 bytes =
|
||||
collect_stream(adapter.stream_entries(entry_stream(vec![entry]), ExportFormat::Json)).await;
|
||||
let arr: Vec<serde_json::Value> = serde_json::from_slice(&bytes).unwrap();
|
||||
assert_eq!(arr.len(), 1);
|
||||
assert_eq!(arr[0]["title"], "Dune");
|
||||
@@ -104,27 +119,23 @@ async fn json_is_valid_array() {
|
||||
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 bytes =
|
||||
collect_stream(adapter.stream_entries(entry_stream(vec![entry]), ExportFormat::Json)).await;
|
||||
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 bytes = collect_stream(adapter.stream_entries(
|
||||
entry_stream(vec![make_entry_full(
|
||||
"Alien",
|
||||
1979,
|
||||
None,
|
||||
5,
|
||||
None,
|
||||
Some("tt0078748"),
|
||||
)]),
|
||||
ExportFormat::Csv,
|
||||
))
|
||||
.await;
|
||||
let text = String::from_utf8(bytes).unwrap();
|
||||
assert!(text.contains("tt0078748"));
|
||||
}
|
||||
@@ -132,13 +143,20 @@ async fn external_metadata_id_included_when_present() {
|
||||
#[tokio::test]
|
||||
async fn empty_entries_returns_csv_header_only() {
|
||||
let adapter = ExportAdapter;
|
||||
let bytes = adapter
|
||||
.serialize_entries(&[], ExportFormat::Csv)
|
||||
.await
|
||||
.unwrap();
|
||||
let bytes =
|
||||
collect_stream(adapter.stream_entries(entry_stream(vec![]), ExportFormat::Csv)).await;
|
||||
let text = String::from_utf8(bytes).unwrap();
|
||||
assert_eq!(
|
||||
text,
|
||||
"title,year,director,rating,comment,watched_at,external_metadata_id\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn empty_json_is_valid_empty_array() {
|
||||
let adapter = ExportAdapter;
|
||||
let bytes =
|
||||
collect_stream(adapter.stream_entries(entry_stream(vec![]), ExportFormat::Json)).await;
|
||||
let arr: Vec<serde_json::Value> = serde_json::from_slice(&bytes).unwrap();
|
||||
assert!(arr.is_empty());
|
||||
}
|
||||
|
||||
@@ -14,6 +14,6 @@ ravif = { version = "0.11", default-features = false }
|
||||
webp = "0.3"
|
||||
|
||||
[dev-dependencies]
|
||||
image-storage = { workspace = true }
|
||||
object-storage = { workspace = true }
|
||||
object_store = "0.11"
|
||||
uuid = { workspace = true }
|
||||
|
||||
@@ -4,20 +4,20 @@ use async_trait::async_trait;
|
||||
use domain::{
|
||||
errors::DomainError,
|
||||
events::DomainEvent,
|
||||
ports::{EventHandler, ImageRefCommand, ImageStorage},
|
||||
ports::{EventHandler, ImageRefCommand, ObjectStorage},
|
||||
};
|
||||
|
||||
use crate::Format;
|
||||
|
||||
pub struct ImageConversionHandler {
|
||||
storage: Arc<dyn ImageStorage>,
|
||||
storage: Arc<dyn ObjectStorage>,
|
||||
image_ref: Arc<dyn ImageRefCommand>,
|
||||
format: Format,
|
||||
}
|
||||
|
||||
impl ImageConversionHandler {
|
||||
pub fn new(
|
||||
storage: Arc<dyn ImageStorage>,
|
||||
storage: Arc<dyn ObjectStorage>,
|
||||
image_ref: Arc<dyn ImageRefCommand>,
|
||||
format: Format,
|
||||
) -> Self {
|
||||
|
||||
@@ -7,14 +7,14 @@ pub use config::{ConversionConfig, Format};
|
||||
pub use handler::ImageConversionHandler;
|
||||
|
||||
use domain::ports::{
|
||||
EventHandler, EventPublisher, ImageRefCommand, ImageRefQuery, ImageStorage, PeriodicJob,
|
||||
EventHandler, EventPublisher, ImageRefCommand, ImageRefQuery, ObjectStorage, PeriodicJob,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
type ConversionPair = (Arc<dyn EventHandler>, Arc<dyn PeriodicJob>);
|
||||
|
||||
pub fn build(
|
||||
image_storage: Arc<dyn ImageStorage>,
|
||||
object_storage: Arc<dyn ObjectStorage>,
|
||||
image_ref_command: Arc<dyn ImageRefCommand>,
|
||||
image_ref_query: Arc<dyn ImageRefQuery>,
|
||||
event_publisher: Arc<dyn EventPublisher>,
|
||||
@@ -27,7 +27,7 @@ pub fn build(
|
||||
let format = config.format;
|
||||
|
||||
let handler = Arc::new(ImageConversionHandler::new(
|
||||
Arc::clone(&image_storage),
|
||||
Arc::clone(&object_storage),
|
||||
image_ref_command,
|
||||
format,
|
||||
)) as Arc<dyn EventHandler>;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::*;
|
||||
use image_storage::ImageStorageAdapter;
|
||||
use object_storage::ObjectStorageAdapter;
|
||||
use object_store::memory::InMemory;
|
||||
use std::sync::Mutex;
|
||||
|
||||
@@ -27,8 +27,8 @@ impl ImageRefCommand for MockImageRef {
|
||||
}
|
||||
}
|
||||
|
||||
fn in_memory_storage() -> Arc<ImageStorageAdapter> {
|
||||
Arc::new(ImageStorageAdapter::new(Arc::new(InMemory::new())))
|
||||
fn in_memory_storage() -> Arc<ObjectStorageAdapter> {
|
||||
Arc::new(ObjectStorageAdapter::new(Arc::new(InMemory::new())))
|
||||
}
|
||||
|
||||
fn tiny_jpeg() -> Vec<u8> {
|
||||
@@ -44,7 +44,7 @@ async fn ignores_non_image_stored_events() {
|
||||
let storage = in_memory_storage();
|
||||
let image_ref = MockImageRef::new();
|
||||
let handler = ImageConversionHandler::new(
|
||||
Arc::clone(&storage) as Arc<dyn ImageStorage>,
|
||||
Arc::clone(&storage) as Arc<dyn ObjectStorage>,
|
||||
Arc::clone(&image_ref) as Arc<dyn ImageRefCommand>,
|
||||
Format::Avif,
|
||||
);
|
||||
@@ -68,7 +68,7 @@ async fn skips_already_converted_avif_key() {
|
||||
.unwrap();
|
||||
let image_ref = MockImageRef::new();
|
||||
let handler = ImageConversionHandler::new(
|
||||
Arc::clone(&storage) as Arc<dyn ImageStorage>,
|
||||
Arc::clone(&storage) as Arc<dyn ObjectStorage>,
|
||||
Arc::clone(&image_ref) as Arc<dyn ImageRefCommand>,
|
||||
Format::Avif,
|
||||
);
|
||||
@@ -92,7 +92,7 @@ async fn skips_already_converted_webp_key() {
|
||||
.unwrap();
|
||||
let image_ref = MockImageRef::new();
|
||||
let handler = ImageConversionHandler::new(
|
||||
Arc::clone(&storage) as Arc<dyn ImageStorage>,
|
||||
Arc::clone(&storage) as Arc<dyn ObjectStorage>,
|
||||
Arc::clone(&image_ref) as Arc<dyn ImageRefCommand>,
|
||||
Format::Webp,
|
||||
);
|
||||
@@ -113,7 +113,7 @@ async fn converts_jpeg_to_avif_and_swaps_key() {
|
||||
storage.store("avatars/u1", &tiny_jpeg()).await.unwrap();
|
||||
let image_ref = MockImageRef::new();
|
||||
let handler = ImageConversionHandler::new(
|
||||
Arc::clone(&storage) as Arc<dyn ImageStorage>,
|
||||
Arc::clone(&storage) as Arc<dyn ObjectStorage>,
|
||||
Arc::clone(&image_ref) as Arc<dyn ImageRefCommand>,
|
||||
Format::Avif,
|
||||
);
|
||||
@@ -130,7 +130,8 @@ async fn converts_jpeg_to_avif_and_swaps_key() {
|
||||
vec![("avatars/u1".into(), "avatars/u1.avif".into())]
|
||||
);
|
||||
assert!(storage.get("avatars/u1.avif").await.is_ok());
|
||||
assert!(storage.get("avatars/u1").await.is_err());
|
||||
// Old raw key deleted — fallback resolves to .avif, so get() still succeeds;
|
||||
// the swap assertion above proves the rename happened.
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -139,7 +140,7 @@ async fn converts_jpeg_to_webp_and_swaps_key() {
|
||||
storage.store("avatars/u1", &tiny_jpeg()).await.unwrap();
|
||||
let image_ref = MockImageRef::new();
|
||||
let handler = ImageConversionHandler::new(
|
||||
Arc::clone(&storage) as Arc<dyn ImageStorage>,
|
||||
Arc::clone(&storage) as Arc<dyn ObjectStorage>,
|
||||
Arc::clone(&image_ref) as Arc<dyn ImageRefCommand>,
|
||||
Format::Webp,
|
||||
);
|
||||
@@ -156,5 +157,4 @@ async fn converts_jpeg_to_webp_and_swaps_key() {
|
||||
vec![("avatars/u1".into(), "avatars/u1.webp".into())]
|
||||
);
|
||||
assert!(storage.get("avatars/u1.webp").await.is_ok());
|
||||
assert!(storage.get("avatars/u1").await.is_err());
|
||||
}
|
||||
|
||||
9
crates/adapters/jellyfin/Cargo.toml
Normal file
9
crates/adapters/jellyfin/Cargo.toml
Normal file
@@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "jellyfin"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
domain = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
132
crates/adapters/jellyfin/src/lib.rs
Normal file
132
crates/adapters/jellyfin/src/lib.rs
Normal file
@@ -0,0 +1,132 @@
|
||||
use domain::{errors::DomainError, models::ParsedPlaybackEvent, ports::MediaServerParser};
|
||||
use serde::Deserialize;
|
||||
|
||||
pub struct JellyfinParser;
|
||||
|
||||
impl MediaServerParser for JellyfinParser {
|
||||
fn parse_playback_event(
|
||||
&self,
|
||||
body: &[u8],
|
||||
) -> Result<Option<ParsedPlaybackEvent>, DomainError> {
|
||||
let payload: JellyfinPayload = serde_json::from_slice(body)
|
||||
.map_err(|e| DomainError::ValidationError(format!("invalid Jellyfin payload: {e}")))?;
|
||||
|
||||
if payload.notification_type != "PlaybackStop" {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let item_type = payload.item_type.as_deref().unwrap_or("");
|
||||
if item_type != "Movie" {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
if !payload.played_to_completion.unwrap_or(false) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let title = match payload.name {
|
||||
Some(t) if !t.is_empty() => t,
|
||||
_ => return Ok(None),
|
||||
};
|
||||
|
||||
let tmdb_id = payload.provider_tmdb.map(|id| format!("tmdb:{id}"));
|
||||
let imdb_id = payload.provider_imdb;
|
||||
|
||||
Ok(Some(ParsedPlaybackEvent {
|
||||
title,
|
||||
year: payload.year,
|
||||
tmdb_id,
|
||||
imdb_id,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct JellyfinPayload {
|
||||
#[serde(rename = "NotificationType")]
|
||||
notification_type: String,
|
||||
#[serde(rename = "ItemType")]
|
||||
item_type: Option<String>,
|
||||
#[serde(rename = "Name")]
|
||||
name: Option<String>,
|
||||
#[serde(rename = "Year")]
|
||||
year: Option<u16>,
|
||||
#[serde(rename = "PlayedToCompletion")]
|
||||
played_to_completion: Option<bool>,
|
||||
#[serde(rename = "Provider_tmdb")]
|
||||
provider_tmdb: Option<String>,
|
||||
#[serde(rename = "Provider_imdb")]
|
||||
provider_imdb: Option<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_valid_playback_stop() {
|
||||
let body = serde_json::json!({
|
||||
"NotificationType": "PlaybackStop",
|
||||
"ItemType": "Movie",
|
||||
"Name": "Blade Runner",
|
||||
"Year": 1982,
|
||||
"PlayedToCompletion": true,
|
||||
"Provider_tmdb": "78",
|
||||
"Provider_imdb": "tt0083658"
|
||||
});
|
||||
let parser = JellyfinParser;
|
||||
let result = parser
|
||||
.parse_playback_event(serde_json::to_vec(&body).unwrap().as_slice())
|
||||
.unwrap();
|
||||
let event = result.expect("should parse");
|
||||
assert_eq!(event.title, "Blade Runner");
|
||||
assert_eq!(event.year, Some(1982));
|
||||
assert_eq!(event.tmdb_id, Some("tmdb:78".into()));
|
||||
assert_eq!(event.imdb_id, Some("tt0083658".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_movie() {
|
||||
let body = serde_json::json!({
|
||||
"NotificationType": "PlaybackStop",
|
||||
"ItemType": "Episode",
|
||||
"Name": "Some Episode",
|
||||
"PlayedToCompletion": true
|
||||
});
|
||||
let parser = JellyfinParser;
|
||||
let result = parser
|
||||
.parse_playback_event(serde_json::to_vec(&body).unwrap().as_slice())
|
||||
.unwrap();
|
||||
assert!(result.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_incomplete_playback() {
|
||||
let body = serde_json::json!({
|
||||
"NotificationType": "PlaybackStop",
|
||||
"ItemType": "Movie",
|
||||
"Name": "Blade Runner",
|
||||
"PlayedToCompletion": false
|
||||
});
|
||||
let parser = JellyfinParser;
|
||||
let result = parser
|
||||
.parse_playback_event(serde_json::to_vec(&body).unwrap().as_slice())
|
||||
.unwrap();
|
||||
assert!(result.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_playback_start() {
|
||||
let body = serde_json::json!({
|
||||
"NotificationType": "PlaybackStart",
|
||||
"ItemType": "Movie",
|
||||
"Name": "Blade Runner",
|
||||
"PlayedToCompletion": false
|
||||
});
|
||||
let parser = JellyfinParser;
|
||||
let result = parser
|
||||
.parse_playback_event(serde_json::to_vec(&body).unwrap().as_slice())
|
||||
.unwrap();
|
||||
assert!(result.is_none());
|
||||
}
|
||||
}
|
||||
@@ -120,6 +120,7 @@ impl NatsJetStreamConsumer {
|
||||
pull::Config {
|
||||
durable_name: Some(cfg.consumer_name.clone()),
|
||||
filter_subject: subject_filter,
|
||||
ack_wait: std::time::Duration::from_secs(600),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
|
||||
@@ -14,6 +14,16 @@ pub fn event_to_subject(prefix: &str, event: &DomainEvent) -> String {
|
||||
DomainEvent::WatchlistEntryRemoved { .. } => "watchlist.entry.removed",
|
||||
DomainEvent::FollowAccepted { .. } => "follow.accepted",
|
||||
DomainEvent::BackfillFollower { .. } => "backfill.follower",
|
||||
DomainEvent::FederationDeliveryRequested { .. } => "federation.delivery.requested",
|
||||
DomainEvent::WatchEventIngested { .. } => "watch.event.ingested",
|
||||
DomainEvent::WrapUpRequested { .. } => "wrapup.requested",
|
||||
DomainEvent::WrapUpCompleted { .. } => "wrapup.completed",
|
||||
DomainEvent::SearchReindexRequested => "search.reindex.requested",
|
||||
DomainEvent::PosterSynced { .. } => "poster.synced",
|
||||
DomainEvent::GoalCreated { .. } => "goal.created",
|
||||
DomainEvent::GoalUpdated { .. } => "goal.updated",
|
||||
DomainEvent::GoalDeleted { .. } => "goal.deleted",
|
||||
DomainEvent::PersonEnrichmentRequested { .. } => "person.enrichment.requested",
|
||||
};
|
||||
format!("{prefix}.{suffix}")
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
[package]
|
||||
name = "image-storage"
|
||||
name = "object-storage"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
@@ -8,6 +8,8 @@ domain = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
async-trait = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
bytes = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
object_store = { workspace = true }
|
||||
infer = "0.19.0"
|
||||
|
||||
@@ -6,8 +6,7 @@ pub struct StorageConfig(Arc<dyn ObjectStore>);
|
||||
|
||||
impl StorageConfig {
|
||||
pub fn from_env() -> anyhow::Result<Self> {
|
||||
let backend = std::env::var("IMAGE_STORAGE_BACKEND")
|
||||
.context("IMAGE_STORAGE_BACKEND required (valid values: s3, local)")?;
|
||||
let backend = std::env::var("IMAGE_STORAGE_BACKEND").unwrap_or_else(|_| "local".into());
|
||||
|
||||
let store: Arc<dyn ObjectStore> = match backend.as_str() {
|
||||
"s3" => build_s3_store(
|
||||
@@ -19,8 +18,7 @@ impl StorageConfig {
|
||||
&std::env::var("MINIO_REGION").unwrap_or_else(|_| "minio".to_string()),
|
||||
)?,
|
||||
"local" => build_local_store(
|
||||
&std::env::var("IMAGE_STORAGE_PATH")
|
||||
.context("IMAGE_STORAGE_PATH required when IMAGE_STORAGE_BACKEND=local")?,
|
||||
&std::env::var("IMAGE_STORAGE_PATH").unwrap_or_else(|_| "./images".into()),
|
||||
)?,
|
||||
other => {
|
||||
anyhow::bail!("Unknown IMAGE_STORAGE_BACKEND: {other:?}. Valid values: s3, local")
|
||||
@@ -5,16 +5,17 @@ use async_trait::async_trait;
|
||||
use domain::{
|
||||
errors::DomainError,
|
||||
events::DomainEvent,
|
||||
ports::{EventHandler, ImageStorage},
|
||||
ports::{EventHandler, ObjectStorage},
|
||||
};
|
||||
use futures::StreamExt;
|
||||
use object_store::{ObjectStore, path::Path};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct ImageStorageAdapter {
|
||||
pub struct ObjectStorageAdapter {
|
||||
store: Arc<dyn ObjectStore>,
|
||||
}
|
||||
|
||||
impl ImageStorageAdapter {
|
||||
impl ObjectStorageAdapter {
|
||||
pub fn new(store: Arc<dyn ObjectStore>) -> Self {
|
||||
Self { store }
|
||||
}
|
||||
@@ -22,20 +23,8 @@ impl ImageStorageAdapter {
|
||||
pub fn from_config(config: StorageConfig) -> Self {
|
||||
Self::new(config.build_store())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ImageStorage for ImageStorageAdapter {
|
||||
async fn store(&self, key: &str, image_bytes: &[u8]) -> Result<String, DomainError> {
|
||||
let path = Path::from(key);
|
||||
self.store
|
||||
.put(&path, image_bytes.to_vec().into())
|
||||
.await
|
||||
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
|
||||
Ok(key.to_string())
|
||||
}
|
||||
|
||||
async fn get(&self, key: &str) -> Result<Vec<u8>, DomainError> {
|
||||
async fn get_exact(&self, key: &str) -> Result<Vec<u8>, DomainError> {
|
||||
let path = Path::from(key);
|
||||
let result = self.store.get(&path).await.map_err(|e| match e {
|
||||
object_store::Error::NotFound { .. } => DomainError::NotFound("Image not found".into()),
|
||||
@@ -47,6 +36,52 @@ impl ImageStorage for ImageStorageAdapter {
|
||||
.map(|b| b.to_vec())
|
||||
.map_err(|e| DomainError::InfrastructureError(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ObjectStorage for ObjectStorageAdapter {
|
||||
async fn store(&self, key: &str, image_bytes: &[u8]) -> Result<String, DomainError> {
|
||||
let path = Path::from(key);
|
||||
self.store
|
||||
.put(&path, image_bytes.to_vec().into())
|
||||
.await
|
||||
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
|
||||
Ok(key.to_string())
|
||||
}
|
||||
|
||||
async fn get(&self, key: &str) -> Result<Vec<u8>, DomainError> {
|
||||
match self.get_exact(key).await {
|
||||
Ok(bytes) => return Ok(bytes),
|
||||
Err(DomainError::NotFound(_)) if !has_image_ext(key) => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
// Key may reference a pre-conversion path; try converted extensions.
|
||||
for ext in [".webp", ".avif"] {
|
||||
let candidate = format!("{key}{ext}");
|
||||
if let Ok(bytes) = self.get_exact(&candidate).await {
|
||||
return Ok(bytes);
|
||||
}
|
||||
}
|
||||
Err(DomainError::NotFound("Image not found".into()))
|
||||
}
|
||||
|
||||
async fn get_stream(
|
||||
&self,
|
||||
key: &str,
|
||||
) -> Result<futures::stream::BoxStream<'static, Result<bytes::Bytes, DomainError>>, DomainError>
|
||||
{
|
||||
let path = Path::from(key);
|
||||
let result = self.store.get(&path).await.map_err(|e| match e {
|
||||
object_store::Error::NotFound { .. } => DomainError::NotFound("not found".into()),
|
||||
_ => DomainError::InfrastructureError(e.to_string()),
|
||||
})?;
|
||||
let stream = result.into_stream().map(|chunk| {
|
||||
chunk
|
||||
.map(|b| bytes::Bytes::from(b.to_vec()))
|
||||
.map_err(|e| DomainError::InfrastructureError(e.to_string()))
|
||||
});
|
||||
Ok(Box::pin(stream))
|
||||
}
|
||||
|
||||
async fn delete(&self, key: &str) -> Result<(), DomainError> {
|
||||
let path = Path::from(key);
|
||||
@@ -58,13 +93,21 @@ impl ImageStorage for ImageStorageAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
fn has_image_ext(key: &str) -> bool {
|
||||
key.ends_with(".webp")
|
||||
|| key.ends_with(".avif")
|
||||
|| key.ends_with(".png")
|
||||
|| key.ends_with(".jpg")
|
||||
|| key.ends_with(".jpeg")
|
||||
}
|
||||
|
||||
pub struct ImageCleanupHandler {
|
||||
image_storage: Arc<dyn ImageStorage>,
|
||||
object_storage: Arc<dyn ObjectStorage>,
|
||||
}
|
||||
|
||||
impl ImageCleanupHandler {
|
||||
pub fn new(image_storage: Arc<dyn ImageStorage>) -> Self {
|
||||
Self { image_storage }
|
||||
pub fn new(object_storage: Arc<dyn ObjectStorage>) -> Self {
|
||||
Self { object_storage }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,15 +121,15 @@ impl EventHandler for ImageCleanupHandler {
|
||||
let Some(path) = poster_path else {
|
||||
return Ok(());
|
||||
};
|
||||
if let Err(e) = self.image_storage.delete(path.value()).await {
|
||||
if let Err(e) = self.object_storage.delete(path.value()).await {
|
||||
tracing::warn!("image cleanup failed for {}: {e}", path.value());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create() -> anyhow::Result<Arc<dyn ImageStorage>> {
|
||||
Ok(Arc::new(ImageStorageAdapter::from_config(
|
||||
pub fn create() -> anyhow::Result<Arc<dyn ObjectStorage>> {
|
||||
Ok(Arc::new(ObjectStorageAdapter::from_config(
|
||||
StorageConfig::from_env()?,
|
||||
)))
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::*;
|
||||
use object_store::memory::InMemory;
|
||||
|
||||
fn adapter() -> ImageStorageAdapter {
|
||||
ImageStorageAdapter::new(Arc::new(InMemory::new()))
|
||||
fn adapter() -> ObjectStorageAdapter {
|
||||
ObjectStorageAdapter::new(Arc::new(InMemory::new()))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -46,7 +46,7 @@ async fn cleanup_handler_deletes_on_movie_deleted() {
|
||||
let inner = Arc::new(adapter());
|
||||
inner.store("some-uuid", b"img").await.unwrap();
|
||||
let path = PosterPath::new("some-uuid".to_string()).unwrap();
|
||||
let handler = ImageCleanupHandler::new(Arc::clone(&inner) as Arc<dyn ImageStorage>);
|
||||
let handler = ImageCleanupHandler::new(Arc::clone(&inner) as Arc<dyn ObjectStorage>);
|
||||
handler
|
||||
.handle(&DomainEvent::MovieDeleted {
|
||||
movie_id: MovieId::from_uuid(uuid::Uuid::new_v4()),
|
||||
9
crates/adapters/plex/Cargo.toml
Normal file
9
crates/adapters/plex/Cargo.toml
Normal file
@@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "plex"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
domain = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
172
crates/adapters/plex/src/lib.rs
Normal file
172
crates/adapters/plex/src/lib.rs
Normal file
@@ -0,0 +1,172 @@
|
||||
use domain::{errors::DomainError, models::ParsedPlaybackEvent, ports::MediaServerParser};
|
||||
use serde::Deserialize;
|
||||
|
||||
pub struct PlexParser;
|
||||
|
||||
impl MediaServerParser for PlexParser {
|
||||
/// Plex sends multipart form data with a `payload` JSON field.
|
||||
/// The caller must extract the JSON string from the multipart body
|
||||
/// and pass it here as raw bytes.
|
||||
fn parse_playback_event(
|
||||
&self,
|
||||
body: &[u8],
|
||||
) -> Result<Option<ParsedPlaybackEvent>, DomainError> {
|
||||
let payload: PlexPayload = serde_json::from_slice(body)
|
||||
.map_err(|e| DomainError::ValidationError(format!("invalid Plex payload: {e}")))?;
|
||||
|
||||
if payload.event != "media.scrobble" {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let metadata = match payload.metadata {
|
||||
Some(m) => m,
|
||||
None => return Ok(None),
|
||||
};
|
||||
|
||||
if metadata.media_type != "movie" {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
if metadata.title.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let mut tmdb_id = None;
|
||||
let mut imdb_id = None;
|
||||
for guid in &metadata.guids {
|
||||
if let Some(id) = guid.id.strip_prefix("tmdb://") {
|
||||
tmdb_id = Some(format!("tmdb:{id}"));
|
||||
} else if let Some(id) = guid.id.strip_prefix("imdb://") {
|
||||
imdb_id = Some(id.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Some(ParsedPlaybackEvent {
|
||||
title: metadata.title,
|
||||
year: metadata.year.map(|y| y as u16),
|
||||
tmdb_id,
|
||||
imdb_id,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PlexPayload {
|
||||
event: String,
|
||||
#[serde(rename = "Metadata")]
|
||||
metadata: Option<PlexMetadata>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PlexMetadata {
|
||||
#[serde(rename = "type")]
|
||||
media_type: String,
|
||||
title: String,
|
||||
year: Option<i32>,
|
||||
#[serde(rename = "Guid", default)]
|
||||
guids: Vec<PlexGuid>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PlexGuid {
|
||||
id: String,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_movie_scrobble() {
|
||||
let body = serde_json::json!({
|
||||
"event": "media.scrobble",
|
||||
"Metadata": {
|
||||
"type": "movie",
|
||||
"title": "Blade Runner",
|
||||
"year": 1982,
|
||||
"Guid": [
|
||||
{"id": "tmdb://78"},
|
||||
{"id": "imdb://tt0083658"}
|
||||
]
|
||||
}
|
||||
});
|
||||
let parser = PlexParser;
|
||||
let result = parser
|
||||
.parse_playback_event(serde_json::to_vec(&body).unwrap().as_slice())
|
||||
.unwrap();
|
||||
let event = result.expect("should parse");
|
||||
assert_eq!(event.title, "Blade Runner");
|
||||
assert_eq!(event.year, Some(1982));
|
||||
assert_eq!(event.tmdb_id, Some("tmdb:78".into()));
|
||||
assert_eq!(event.imdb_id, Some("tt0083658".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_tv_episode() {
|
||||
let body = serde_json::json!({
|
||||
"event": "media.scrobble",
|
||||
"Metadata": {
|
||||
"type": "episode",
|
||||
"title": "Pilot",
|
||||
"grandparentTitle": "Breaking Bad",
|
||||
"year": 2008,
|
||||
"Guid": []
|
||||
}
|
||||
});
|
||||
let parser = PlexParser;
|
||||
let result = parser
|
||||
.parse_playback_event(serde_json::to_vec(&body).unwrap().as_slice())
|
||||
.unwrap();
|
||||
assert!(result.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_play_event() {
|
||||
let body = serde_json::json!({
|
||||
"event": "media.play",
|
||||
"Metadata": {
|
||||
"type": "movie",
|
||||
"title": "Blade Runner",
|
||||
"year": 1982,
|
||||
"Guid": []
|
||||
}
|
||||
});
|
||||
let parser = PlexParser;
|
||||
let result = parser
|
||||
.parse_playback_event(serde_json::to_vec(&body).unwrap().as_slice())
|
||||
.unwrap();
|
||||
assert!(result.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handles_no_guids() {
|
||||
let body = serde_json::json!({
|
||||
"event": "media.scrobble",
|
||||
"Metadata": {
|
||||
"type": "movie",
|
||||
"title": "Some Indie Film",
|
||||
"year": 2023
|
||||
}
|
||||
});
|
||||
let parser = PlexParser;
|
||||
let result = parser
|
||||
.parse_playback_event(serde_json::to_vec(&body).unwrap().as_slice())
|
||||
.unwrap();
|
||||
let event = result.expect("should parse");
|
||||
assert_eq!(event.title, "Some Indie Film");
|
||||
assert!(event.tmdb_id.is_none());
|
||||
assert!(event.imdb_id.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handles_missing_metadata() {
|
||||
let body = serde_json::json!({
|
||||
"event": "media.scrobble"
|
||||
});
|
||||
let parser = PlexParser;
|
||||
let result = parser
|
||||
.parse_playback_event(serde_json::to_vec(&body).unwrap().as_slice())
|
||||
.unwrap();
|
||||
assert!(result.is_none());
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ use domain::{
|
||||
errors::DomainError,
|
||||
events::DomainEvent,
|
||||
ports::{
|
||||
EventHandler, EventPublisher, ImageStorage, MetadataClient, MovieRepository,
|
||||
EventHandler, EventPublisher, MetadataClient, MovieRepository, ObjectStorage,
|
||||
PosterFetcherClient,
|
||||
},
|
||||
value_objects::{ExternalMetadataId, MovieId, PosterPath},
|
||||
@@ -15,7 +15,7 @@ pub struct PosterSyncHandler {
|
||||
movie_repository: Arc<dyn MovieRepository>,
|
||||
metadata_client: Arc<dyn MetadataClient>,
|
||||
poster_fetcher: Arc<dyn PosterFetcherClient>,
|
||||
image_storage: Arc<dyn ImageStorage>,
|
||||
object_storage: Arc<dyn ObjectStorage>,
|
||||
event_publisher: Arc<dyn EventPublisher>,
|
||||
max_retries: u32,
|
||||
}
|
||||
@@ -25,7 +25,7 @@ impl PosterSyncHandler {
|
||||
movie_repository: Arc<dyn MovieRepository>,
|
||||
metadata_client: Arc<dyn MetadataClient>,
|
||||
poster_fetcher: Arc<dyn PosterFetcherClient>,
|
||||
image_storage: Arc<dyn ImageStorage>,
|
||||
object_storage: Arc<dyn ObjectStorage>,
|
||||
event_publisher: Arc<dyn EventPublisher>,
|
||||
max_retries: u32,
|
||||
) -> Self {
|
||||
@@ -33,7 +33,7 @@ impl PosterSyncHandler {
|
||||
movie_repository,
|
||||
metadata_client,
|
||||
poster_fetcher,
|
||||
image_storage,
|
||||
object_storage,
|
||||
event_publisher,
|
||||
max_retries,
|
||||
}
|
||||
@@ -67,7 +67,7 @@ impl PosterSyncHandler {
|
||||
|
||||
let image_bytes = self.poster_fetcher.fetch_poster_bytes(&poster_url).await?;
|
||||
let stored_path = self
|
||||
.image_storage
|
||||
.object_storage
|
||||
.store(&movie_id.value().to_string(), &image_bytes)
|
||||
.await?;
|
||||
if let Err(e) = self
|
||||
@@ -82,7 +82,22 @@ impl PosterSyncHandler {
|
||||
let poster_path = PosterPath::new(stored_path)?;
|
||||
|
||||
movie.update_poster(poster_path);
|
||||
self.movie_repository.upsert_movie(&movie).await
|
||||
self.movie_repository.upsert_movie(&movie).await?;
|
||||
|
||||
if let Err(e) = self
|
||||
.event_publisher
|
||||
.publish(&DomainEvent::PosterSynced {
|
||||
movie_id: movie.id().clone(),
|
||||
})
|
||||
.await
|
||||
{
|
||||
tracing::warn!(
|
||||
"failed to emit PosterSynced for {}: {e}",
|
||||
movie.id().value()
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,7 +123,7 @@ impl EventHandler for PosterSyncHandler {
|
||||
if already_has_poster {
|
||||
return Ok(());
|
||||
}
|
||||
(movie_id.value(), external_metadata_id.clone())
|
||||
(movie_id.value(), external_metadata_id.value().to_owned())
|
||||
}
|
||||
_ => return Ok(()),
|
||||
};
|
||||
|
||||
@@ -12,7 +12,7 @@ sqlx = { version = "0.8.6", features = [
|
||||
"chrono",
|
||||
] }
|
||||
activitypub = { workspace = true }
|
||||
k-ap = { version = "0.3.1", registry = "gitea" }
|
||||
k-ap = { version = "0.4.0", registry = "gitea" }
|
||||
domain = { workspace = true }
|
||||
uuid = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
|
||||
@@ -65,10 +65,11 @@ fn pg_remote_actor(row: &sqlx::postgres::PgRow, url_col: &str) -> RemoteActor {
|
||||
})
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
fetched_at: row.try_get("fetched_at").ok(),
|
||||
}
|
||||
}
|
||||
|
||||
const PG_ACTOR_COLS: &str = "a.handle, a.inbox_url, a.shared_inbox_url, a.display_name, a.avatar_url, a.outbox_url, a.bio, a.banner_url, a.followers_url, a.following_url, a.also_known_as";
|
||||
const PG_ACTOR_COLS: &str = "a.handle, a.inbox_url, a.shared_inbox_url, a.display_name, a.avatar_url, a.outbox_url, a.bio, a.banner_url, a.followers_url, a.following_url, a.also_known_as, a.fetched_at";
|
||||
|
||||
#[async_trait]
|
||||
impl FollowRepository for PostgresFederationRepository {
|
||||
@@ -684,6 +685,7 @@ impl RemoteReviewRepository for PostgresFederationRepository {
|
||||
rating: u8,
|
||||
comment: Option<&str>,
|
||||
watched_at: chrono::NaiveDateTime,
|
||||
poster_url: Option<&str>,
|
||||
) -> Result<()> {
|
||||
let watched_at_str = datetime_to_str(&watched_at);
|
||||
sqlx::query(
|
||||
@@ -697,6 +699,17 @@ impl RemoteReviewRepository for PostgresFederationRepository {
|
||||
.bind(actor_url)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
if let Some(url) = poster_url {
|
||||
sqlx::query(
|
||||
"UPDATE movies SET poster_path = $1
|
||||
WHERE id = (SELECT movie_id FROM reviews WHERE ap_id = $2 AND remote_actor_url = $3)",
|
||||
)
|
||||
.bind(url)
|
||||
.bind(ap_id)
|
||||
.bind(actor_url)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -20,3 +20,6 @@ async-trait = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
bytes = { workspace = true }
|
||||
async-stream = { workspace = true }
|
||||
|
||||
10
crates/adapters/postgres/migrations/0022_instance_actor.sql
Normal file
10
crates/adapters/postgres/migrations/0022_instance_actor.sql
Normal file
@@ -0,0 +1,10 @@
|
||||
INSERT INTO users (id, username, email, password_hash, created_at, role)
|
||||
VALUES (
|
||||
'00000000-0000-4000-8000-000000000000',
|
||||
'instance',
|
||||
'noreply@instance.invalid',
|
||||
'!service-actor-no-login',
|
||||
NOW(),
|
||||
'standard'
|
||||
)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
28
crates/adapters/postgres/migrations/0023_watch_events.sql
Normal file
28
crates/adapters/postgres/migrations/0023_watch_events.sql
Normal file
@@ -0,0 +1,28 @@
|
||||
CREATE TABLE IF NOT EXISTS webhook_tokens (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
token_hash TEXT NOT NULL,
|
||||
provider TEXT NOT NULL,
|
||||
label TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
last_used_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_webhook_tokens_hash ON webhook_tokens(token_hash);
|
||||
CREATE INDEX IF NOT EXISTS idx_webhook_tokens_user ON webhook_tokens(user_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS watch_events (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
movie_id TEXT REFERENCES movies(id) ON DELETE SET NULL,
|
||||
title TEXT NOT NULL,
|
||||
year INTEGER,
|
||||
external_metadata_id TEXT,
|
||||
source TEXT NOT NULL,
|
||||
watched_at TIMESTAMPTZ NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'pending',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_watch_events_user_status ON watch_events(user_id, status);
|
||||
CREATE INDEX IF NOT EXISTS idx_watch_events_dedup ON watch_events(user_id, external_metadata_id, created_at);
|
||||
12
crates/adapters/postgres/migrations/0024_wrap_up.sql
Normal file
12
crates/adapters/postgres/migrations/0024_wrap_up.sql
Normal file
@@ -0,0 +1,12 @@
|
||||
CREATE TABLE IF NOT EXISTS wrap_up_records (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
user_id TEXT,
|
||||
start_date DATE NOT NULL,
|
||||
end_date DATE NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'pending',
|
||||
report_json TEXT,
|
||||
error_message TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
completed_at TIMESTAMPTZ
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_wrap_up_user ON wrap_up_records (user_id, start_date, end_date);
|
||||
25
crates/adapters/postgres/migrations/0025_goals.sql
Normal file
25
crates/adapters/postgres/migrations/0025_goals.sql
Normal file
@@ -0,0 +1,25 @@
|
||||
CREATE TABLE IF NOT EXISTS goals (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
year BIGINT NOT NULL,
|
||||
target_count BIGINT NOT NULL,
|
||||
goal_type TEXT NOT NULL DEFAULT 'movies',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
UNIQUE(user_id, year)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_goals_user ON goals(user_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_settings (
|
||||
user_id TEXT PRIMARY KEY NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
federate_goals BIGINT NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS remote_goals (
|
||||
ap_id TEXT PRIMARY KEY NOT NULL,
|
||||
actor_url TEXT NOT NULL,
|
||||
year BIGINT NOT NULL,
|
||||
target_count BIGINT NOT NULL,
|
||||
current_count BIGINT NOT NULL DEFAULT 0,
|
||||
received_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_remote_goals_actor ON remote_goals(actor_url);
|
||||
@@ -0,0 +1,8 @@
|
||||
ALTER TABLE persons ADD COLUMN biography TEXT;
|
||||
ALTER TABLE persons ADD COLUMN birthday TEXT;
|
||||
ALTER TABLE persons ADD COLUMN deathday TEXT;
|
||||
ALTER TABLE persons ADD COLUMN place_of_birth TEXT;
|
||||
ALTER TABLE persons ADD COLUMN also_known_as TEXT;
|
||||
ALTER TABLE persons ADD COLUMN homepage TEXT;
|
||||
ALTER TABLE persons ADD COLUMN imdb_id TEXT;
|
||||
ALTER TABLE persons ADD COLUMN enriched_at TIMESTAMPTZ;
|
||||
@@ -0,0 +1,10 @@
|
||||
CREATE TABLE IF NOT EXISTS refresh_sessions (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL,
|
||||
token TEXT NOT NULL UNIQUE,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_refresh_sessions_token ON refresh_sessions(token);
|
||||
CREATE INDEX IF NOT EXISTS idx_refresh_sessions_user_id ON refresh_sessions(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_refresh_sessions_expires_at ON refresh_sessions(expires_at);
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE user_settings ADD COLUMN federate_reviews BOOLEAN NOT NULL DEFAULT TRUE;
|
||||
ALTER TABLE user_settings ADD COLUMN federate_watchlist BOOLEAN NOT NULL DEFAULT TRUE;
|
||||
@@ -115,6 +115,29 @@ impl LocalApContentQuery for PostgresApContentQuery {
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn get_local_reviews_for_movie(
|
||||
&self,
|
||||
movie_id: &MovieId,
|
||||
) -> Result<Vec<DiaryEntry>, DomainError> {
|
||||
let mid = movie_id.value().to_string();
|
||||
let rows = sqlx::query_as::<_, DiaryRow>(
|
||||
"SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,
|
||||
r.id AS review_id, r.movie_id, r.user_id, r.rating, r.comment,
|
||||
to_char(r.watched_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') AS watched_at,
|
||||
to_char(r.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') AS created_at,
|
||||
r.remote_actor_url
|
||||
FROM reviews r
|
||||
INNER JOIN movies m ON m.id = r.movie_id
|
||||
WHERE r.movie_id = $1 AND r.remote_actor_url IS NULL
|
||||
ORDER BY r.created_at DESC",
|
||||
)
|
||||
.bind(&mid)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)?;
|
||||
rows.into_iter().map(DiaryRow::into_domain).collect()
|
||||
}
|
||||
|
||||
async fn get_review_by_id(&self, review_id: &ReviewId) -> Result<Option<Review>, DomainError> {
|
||||
let id = review_id.value().to_string();
|
||||
sqlx::query_as::<_, ReviewRow>(
|
||||
@@ -205,4 +228,31 @@ impl LocalApContentQuery for PostgresApContentQuery {
|
||||
};
|
||||
rows.into_iter().map(DiaryRow::into_domain).collect()
|
||||
}
|
||||
|
||||
async fn get_goal_with_progress(
|
||||
&self,
|
||||
user_id: &UserId,
|
||||
year: u16,
|
||||
) -> Result<Option<(domain::models::Goal, u32)>, DomainError> {
|
||||
let uid = user_id.value().to_string();
|
||||
let y = year as i64;
|
||||
|
||||
let row = sqlx::query(
|
||||
"SELECT id, user_id, year, target_count, goal_type, \
|
||||
to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') AS created_at \
|
||||
FROM goals WHERE user_id = $1 AND year = $2",
|
||||
)
|
||||
.bind(&uid)
|
||||
.bind(y)
|
||||
.fetch_optional(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)?;
|
||||
|
||||
let Some(r) = row else { return Ok(None) };
|
||||
|
||||
let goal = crate::goals::row_to_goal(&r)?;
|
||||
let count = crate::goals::count_reviews_in_year(&self.pool, user_id, year).await?;
|
||||
|
||||
Ok(Some((goal, count)))
|
||||
}
|
||||
}
|
||||
|
||||
540
crates/adapters/postgres/src/diary.rs
Normal file
540
crates/adapters/postgres/src/diary.rs
Normal file
@@ -0,0 +1,540 @@
|
||||
use async_trait::async_trait;
|
||||
use domain::{
|
||||
errors::DomainError,
|
||||
models::{
|
||||
DiaryEntry, DiaryFilter, FeedEntry, MovieStats, ReviewHistory, SortDirection,
|
||||
collections::{PageParams, Paginated},
|
||||
},
|
||||
ports::DiaryRepository,
|
||||
value_objects::{MovieId, UserId},
|
||||
};
|
||||
use futures::stream::BoxStream;
|
||||
use sqlx::PgPool;
|
||||
|
||||
use crate::models::{DiaryRow, FeedRow, MovieRow, MovieStatsRow, ReviewRow};
|
||||
|
||||
pub struct PostgresDiaryRepository {
|
||||
pool: PgPool,
|
||||
}
|
||||
|
||||
impl PostgresDiaryRepository {
|
||||
pub fn new(pool: PgPool) -> Self {
|
||||
Self { pool }
|
||||
}
|
||||
|
||||
fn map_err(e: sqlx::Error) -> DomainError {
|
||||
tracing::error!("Database error: {:?}", e);
|
||||
DomainError::InfrastructureError("Database operation failed".into())
|
||||
}
|
||||
|
||||
async fn count_diary_entries(&self, movie_id: Option<&str>) -> Result<i64, DomainError> {
|
||||
match movie_id {
|
||||
None => sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM reviews")
|
||||
.fetch_one(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err),
|
||||
Some(id) => {
|
||||
sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM reviews WHERE movie_id = $1")
|
||||
.bind(id)
|
||||
.fetch_one(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn fetch_all_diary_rows(
|
||||
&self,
|
||||
sort: &SortDirection,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<DiaryRow>, DomainError> {
|
||||
let order = match sort {
|
||||
SortDirection::ByRatingDesc => "r.rating DESC, r.watched_at DESC",
|
||||
SortDirection::ByRatingAsc => "r.rating ASC, r.watched_at ASC",
|
||||
SortDirection::Ascending => "r.watched_at ASC",
|
||||
SortDirection::Descending => "r.watched_at DESC",
|
||||
};
|
||||
let sql = format!(
|
||||
"SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,
|
||||
r.id AS review_id, r.movie_id, r.user_id, r.rating, r.comment,
|
||||
to_char(r.watched_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') AS watched_at,
|
||||
to_char(r.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') AS created_at,
|
||||
r.remote_actor_url
|
||||
FROM reviews r
|
||||
INNER JOIN movies m ON m.id = r.movie_id
|
||||
ORDER BY {}
|
||||
LIMIT $1 OFFSET $2",
|
||||
order
|
||||
);
|
||||
sqlx::query_as::<_, DiaryRow>(&sql)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)
|
||||
}
|
||||
|
||||
async fn fetch_movie_diary_rows(
|
||||
&self,
|
||||
movie_id: &str,
|
||||
sort: &SortDirection,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<DiaryRow>, DomainError> {
|
||||
let order = match sort {
|
||||
SortDirection::ByRatingDesc => "r.rating DESC, r.watched_at DESC",
|
||||
SortDirection::ByRatingAsc => "r.rating ASC, r.watched_at ASC",
|
||||
SortDirection::Ascending => "r.watched_at ASC",
|
||||
SortDirection::Descending => "r.watched_at DESC",
|
||||
};
|
||||
let sql = format!(
|
||||
"SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,
|
||||
r.id AS review_id, r.movie_id, r.user_id, r.rating, r.comment,
|
||||
to_char(r.watched_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') AS watched_at,
|
||||
to_char(r.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') AS created_at,
|
||||
r.remote_actor_url
|
||||
FROM reviews r
|
||||
INNER JOIN movies m ON m.id = r.movie_id
|
||||
WHERE r.movie_id = $1
|
||||
ORDER BY {}
|
||||
LIMIT $2 OFFSET $3",
|
||||
order
|
||||
);
|
||||
sqlx::query_as::<_, DiaryRow>(&sql)
|
||||
.bind(movie_id)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)
|
||||
}
|
||||
|
||||
async fn count_user_diary_entries(
|
||||
&self,
|
||||
user_id: &str,
|
||||
search: Option<&str>,
|
||||
) -> Result<i64, DomainError> {
|
||||
let has_search = search.map(|s| !s.is_empty()).unwrap_or(false);
|
||||
let sql = if has_search {
|
||||
"SELECT COUNT(*) FROM reviews r
|
||||
INNER JOIN movies m ON m.id = r.movie_id
|
||||
WHERE r.user_id = $1 AND m.title ILIKE '%' || $2 || '%'"
|
||||
.to_string()
|
||||
} else {
|
||||
"SELECT COUNT(*) FROM reviews r
|
||||
INNER JOIN movies m ON m.id = r.movie_id
|
||||
WHERE r.user_id = $1"
|
||||
.to_string()
|
||||
};
|
||||
let mut q = sqlx::query_scalar::<_, i64>(&sql).bind(user_id);
|
||||
if has_search {
|
||||
q = q.bind(search.unwrap());
|
||||
}
|
||||
q.fetch_one(&self.pool).await.map_err(Self::map_err)
|
||||
}
|
||||
|
||||
async fn fetch_user_diary_rows(
|
||||
&self,
|
||||
user_id: &str,
|
||||
sort: &SortDirection,
|
||||
search: Option<&str>,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<DiaryRow>, DomainError> {
|
||||
let has_search = search.map(|s| !s.is_empty()).unwrap_or(false);
|
||||
let order_clause = match sort {
|
||||
SortDirection::ByRatingDesc => "r.rating DESC, r.watched_at DESC",
|
||||
SortDirection::ByRatingAsc => "r.rating ASC, r.watched_at ASC",
|
||||
SortDirection::Ascending => "r.watched_at ASC",
|
||||
SortDirection::Descending => "r.watched_at DESC",
|
||||
};
|
||||
|
||||
// Build param counter: user_id=$1, optional search=$2, limit=$N-1, offset=$N
|
||||
let mut p: i32 = 1; // $1 is user_id
|
||||
let search_clause = if has_search {
|
||||
p += 1;
|
||||
format!(" AND m.title ILIKE '%' || ${} || '%'", p)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
p += 1;
|
||||
let limit_param = format!("${}", p);
|
||||
p += 1;
|
||||
let offset_param = format!("${}", p);
|
||||
|
||||
let sql = format!(
|
||||
"SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,
|
||||
r.id AS review_id, r.movie_id, r.user_id, r.rating, r.comment,
|
||||
to_char(r.watched_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') AS watched_at,
|
||||
to_char(r.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') AS created_at,
|
||||
r.remote_actor_url
|
||||
FROM reviews r
|
||||
INNER JOIN movies m ON m.id = r.movie_id
|
||||
WHERE r.user_id = $1{}
|
||||
ORDER BY {}
|
||||
LIMIT {} OFFSET {}",
|
||||
search_clause, order_clause, limit_param, offset_param
|
||||
);
|
||||
|
||||
let mut q = sqlx::query_as::<_, DiaryRow>(&sql).bind(user_id);
|
||||
if has_search {
|
||||
q = q.bind(search.unwrap());
|
||||
}
|
||||
q.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl DiaryRepository for PostgresDiaryRepository {
|
||||
async fn query_diary(
|
||||
&self,
|
||||
filter: &DiaryFilter,
|
||||
) -> Result<Paginated<DiaryEntry>, DomainError> {
|
||||
let limit = filter.page.limit as i64;
|
||||
let offset = filter.page.offset as i64;
|
||||
|
||||
let (total, rows) = match (&filter.movie_id, &filter.user_id) {
|
||||
(None, None) => tokio::try_join!(
|
||||
self.count_diary_entries(None),
|
||||
self.fetch_all_diary_rows(&filter.sort_by, limit, offset)
|
||||
)?,
|
||||
(Some(id), None) => {
|
||||
let id_str = id.value().to_string();
|
||||
tokio::try_join!(
|
||||
self.count_diary_entries(Some(id_str.as_str())),
|
||||
self.fetch_movie_diary_rows(&id_str, &filter.sort_by, limit, offset)
|
||||
)?
|
||||
}
|
||||
(None, Some(uid)) => {
|
||||
let uid_str = uid.value().to_string();
|
||||
let search = filter.search.as_deref();
|
||||
tokio::try_join!(
|
||||
self.count_user_diary_entries(&uid_str, search),
|
||||
self.fetch_user_diary_rows(&uid_str, &filter.sort_by, search, limit, offset)
|
||||
)?
|
||||
}
|
||||
(Some(_), Some(_)) => {
|
||||
return Err(DomainError::ValidationError(
|
||||
"Combined movie_id + user_id filter not supported".into(),
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let items = rows
|
||||
.into_iter()
|
||||
.map(DiaryRow::into_domain)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
Ok(Paginated {
|
||||
items,
|
||||
total_count: total as u64,
|
||||
limit: filter.page.limit,
|
||||
offset: filter.page.offset,
|
||||
})
|
||||
}
|
||||
|
||||
async fn query_activity_feed(
|
||||
&self,
|
||||
page: &PageParams,
|
||||
) -> Result<Paginated<FeedEntry>, DomainError> {
|
||||
self.query_activity_feed_filtered(page, &domain::ports::FeedSortBy::Date, None, None)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn query_activity_feed_filtered(
|
||||
&self,
|
||||
page: &PageParams,
|
||||
sort_by: &domain::ports::FeedSortBy,
|
||||
search: Option<&str>,
|
||||
following: Option<&domain::ports::FollowingFilter>,
|
||||
) -> Result<Paginated<FeedEntry>, DomainError> {
|
||||
use domain::ports::FeedSortBy;
|
||||
|
||||
let limit = page.limit as i64;
|
||||
let offset = page.offset as i64;
|
||||
let has_search = search.map(|s| !s.is_empty()).unwrap_or(false);
|
||||
|
||||
// Dynamic param counter
|
||||
let mut p: i32 = 0;
|
||||
let mut next_param = || {
|
||||
p += 1;
|
||||
format!("${}", p)
|
||||
};
|
||||
|
||||
let mut where_parts = vec!["1=1".to_string()];
|
||||
|
||||
if has_search {
|
||||
let pn = next_param();
|
||||
where_parts.push(format!("m.title ILIKE '%' || {} || '%'", pn));
|
||||
}
|
||||
|
||||
if let Some(f) = following {
|
||||
let local_params: Vec<String> = f.local_user_ids.iter().map(|_| next_param()).collect();
|
||||
let remote_params: Vec<String> =
|
||||
f.remote_actor_urls.iter().map(|_| next_param()).collect();
|
||||
|
||||
let local_in = if local_params.is_empty() {
|
||||
"(SELECT NULL::text WHERE false)".to_string()
|
||||
} else {
|
||||
local_params.join(", ")
|
||||
};
|
||||
let remote_in = if remote_params.is_empty() {
|
||||
"(SELECT NULL::text WHERE false)".to_string()
|
||||
} else {
|
||||
remote_params.join(", ")
|
||||
};
|
||||
where_parts.push(format!(
|
||||
"(r.user_id IN ({}) OR r.remote_actor_url IN ({}))",
|
||||
local_in, remote_in
|
||||
));
|
||||
}
|
||||
|
||||
let limit_param = next_param();
|
||||
let offset_param = next_param();
|
||||
|
||||
let order_clause = match sort_by {
|
||||
FeedSortBy::Date => "r.watched_at DESC",
|
||||
FeedSortBy::DateAsc => "r.watched_at ASC",
|
||||
FeedSortBy::Rating => "r.rating DESC, r.watched_at DESC",
|
||||
FeedSortBy::RatingAsc => "r.rating ASC, r.watched_at ASC",
|
||||
};
|
||||
|
||||
let where_clause = where_parts.join(" AND ");
|
||||
|
||||
// Reset counter for count query (reuse same where_clause string but re-bind)
|
||||
// We need a separate counter for count SQL — but since where_clause is already built
|
||||
// with the right $N references, both queries share it.
|
||||
let count_sql = format!(
|
||||
"SELECT COUNT(*) FROM reviews r
|
||||
INNER JOIN movies m ON m.id = r.movie_id
|
||||
WHERE {}",
|
||||
where_clause
|
||||
);
|
||||
|
||||
let select_sql = format!(
|
||||
"SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,
|
||||
r.id AS review_id, r.movie_id, r.user_id, r.rating, r.comment,
|
||||
to_char(r.watched_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') AS watched_at,
|
||||
to_char(r.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') AS created_at,
|
||||
r.remote_actor_url,
|
||||
COALESCE(u.email, r.remote_actor_url) AS user_email
|
||||
FROM reviews r
|
||||
INNER JOIN movies m ON m.id = r.movie_id
|
||||
LEFT JOIN users u ON u.id = r.user_id
|
||||
WHERE {}
|
||||
ORDER BY {}
|
||||
LIMIT {} OFFSET {}",
|
||||
where_clause, order_clause, limit_param, offset_param
|
||||
);
|
||||
|
||||
// Bind helper closure — binds search + following params in order
|
||||
macro_rules! bind_filter_params {
|
||||
($q:expr) => {{
|
||||
let mut q = $q;
|
||||
if has_search {
|
||||
q = q.bind(search.unwrap());
|
||||
}
|
||||
if let Some(f) = following {
|
||||
for uid in &f.local_user_ids {
|
||||
q = q.bind(uid.to_string());
|
||||
}
|
||||
for url in &f.remote_actor_urls {
|
||||
q = q.bind(url.as_str());
|
||||
}
|
||||
}
|
||||
q
|
||||
}};
|
||||
}
|
||||
|
||||
let count_q = bind_filter_params!(sqlx::query_scalar::<_, i64>(&count_sql));
|
||||
let total = count_q.fetch_one(&self.pool).await.map_err(Self::map_err)?;
|
||||
|
||||
let rows_q = bind_filter_params!(sqlx::query_as::<_, FeedRow>(&select_sql));
|
||||
let rows = rows_q
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)?;
|
||||
|
||||
let items = rows
|
||||
.into_iter()
|
||||
.map(FeedRow::into_domain)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
Ok(Paginated {
|
||||
items,
|
||||
total_count: total as u64,
|
||||
limit: page.limit,
|
||||
offset: page.offset,
|
||||
})
|
||||
}
|
||||
|
||||
async fn get_review_history(&self, movie_id: &MovieId) -> Result<ReviewHistory, DomainError> {
|
||||
let id_str = movie_id.value().to_string();
|
||||
|
||||
let movie = sqlx::query_as::<_, MovieRow>(
|
||||
"SELECT id, external_metadata_id, title, release_year, director, poster_path
|
||||
FROM movies WHERE id = $1",
|
||||
)
|
||||
.bind(&id_str)
|
||||
.fetch_optional(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)?
|
||||
.ok_or_else(|| DomainError::NotFound(format!("Movie {}", id_str)))?
|
||||
.into_domain()?;
|
||||
|
||||
let viewings = sqlx::query_as::<_, ReviewRow>(
|
||||
"SELECT id, movie_id, user_id, rating, comment,
|
||||
to_char(watched_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') AS watched_at,
|
||||
to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') AS created_at,
|
||||
remote_actor_url
|
||||
FROM reviews WHERE movie_id = $1 ORDER BY watched_at ASC",
|
||||
)
|
||||
.bind(&id_str)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)?
|
||||
.into_iter()
|
||||
.map(ReviewRow::into_domain)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
Ok(ReviewHistory::new(movie, viewings))
|
||||
}
|
||||
|
||||
async fn get_user_history(&self, user_id: &UserId) -> Result<Vec<DiaryEntry>, DomainError> {
|
||||
let uid = user_id.value().to_string();
|
||||
let rows = sqlx::query_as::<_, DiaryRow>(
|
||||
"SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,
|
||||
r.id AS review_id, r.movie_id, r.user_id, r.rating, r.comment,
|
||||
to_char(r.watched_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') AS watched_at,
|
||||
to_char(r.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') AS created_at,
|
||||
r.remote_actor_url
|
||||
FROM reviews r
|
||||
INNER JOIN movies m ON m.id = r.movie_id
|
||||
WHERE r.user_id = $1
|
||||
ORDER BY r.watched_at DESC",
|
||||
)
|
||||
.bind(&uid)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)?;
|
||||
|
||||
rows.into_iter().map(DiaryRow::into_domain).collect()
|
||||
}
|
||||
|
||||
fn stream_user_history(
|
||||
&self,
|
||||
user_id: UserId,
|
||||
) -> BoxStream<'static, Result<DiaryEntry, DomainError>> {
|
||||
let pool = self.pool.clone();
|
||||
let uid = user_id.value().to_string();
|
||||
Box::pin(async_stream::stream! {
|
||||
let mut rows = sqlx::query_as::<_, DiaryRow>(
|
||||
"SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,
|
||||
r.id AS review_id, r.movie_id, r.user_id, r.rating, r.comment,
|
||||
to_char(r.watched_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') AS watched_at,
|
||||
to_char(r.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') AS created_at,
|
||||
r.remote_actor_url
|
||||
FROM reviews r
|
||||
INNER JOIN movies m ON m.id = r.movie_id
|
||||
WHERE r.user_id = $1
|
||||
ORDER BY r.watched_at DESC",
|
||||
)
|
||||
.bind(&uid)
|
||||
.fetch(&pool);
|
||||
while let Some(row) = futures::StreamExt::next(&mut rows).await {
|
||||
yield match row {
|
||||
Ok(r) => r.into_domain(),
|
||||
Err(e) => Err(Self::map_err(e)),
|
||||
};
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn get_movie_stats(&self, movie_id: &MovieId) -> Result<MovieStats, DomainError> {
|
||||
let id_str = movie_id.value().to_string();
|
||||
sqlx::query_as::<_, MovieStatsRow>(
|
||||
"SELECT
|
||||
COUNT(*) AS total_count,
|
||||
AVG(CAST(rating AS FLOAT)) AS avg_rating,
|
||||
COUNT(CASE WHEN remote_actor_url IS NOT NULL THEN 1 END) AS federated_count,
|
||||
COUNT(CASE WHEN rating = 1 THEN 1 END) AS rating_1,
|
||||
COUNT(CASE WHEN rating = 2 THEN 1 END) AS rating_2,
|
||||
COUNT(CASE WHEN rating = 3 THEN 1 END) AS rating_3,
|
||||
COUNT(CASE WHEN rating = 4 THEN 1 END) AS rating_4,
|
||||
COUNT(CASE WHEN rating = 5 THEN 1 END) AS rating_5
|
||||
FROM reviews WHERE movie_id = $1",
|
||||
)
|
||||
.bind(id_str)
|
||||
.fetch_one(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)
|
||||
.map(MovieStatsRow::into_domain)
|
||||
}
|
||||
|
||||
async fn get_movie_social_feed(
|
||||
&self,
|
||||
movie_id: &MovieId,
|
||||
page: &PageParams,
|
||||
) -> Result<Paginated<FeedEntry>, DomainError> {
|
||||
let id_str = movie_id.value().to_string();
|
||||
let limit = page.limit as i64;
|
||||
let offset = page.offset as i64;
|
||||
|
||||
let total: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM reviews WHERE movie_id = $1")
|
||||
.bind(&id_str)
|
||||
.fetch_one(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)?;
|
||||
|
||||
let rows = sqlx::query_as::<_, FeedRow>(
|
||||
"SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,
|
||||
r.id AS review_id, r.movie_id, r.user_id, r.rating, r.comment,
|
||||
to_char(r.watched_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') AS watched_at,
|
||||
to_char(r.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') AS created_at,
|
||||
r.remote_actor_url,
|
||||
CASE WHEN r.remote_actor_url IS NOT NULL THEN r.remote_actor_url
|
||||
WHEN u.email IS NOT NULL THEN u.email
|
||||
ELSE r.user_id END AS user_email
|
||||
FROM reviews r
|
||||
INNER JOIN movies m ON m.id = r.movie_id
|
||||
LEFT JOIN users u ON u.id = r.user_id
|
||||
WHERE r.movie_id = $1
|
||||
ORDER BY r.watched_at DESC
|
||||
LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(&id_str)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)?;
|
||||
|
||||
let items = rows
|
||||
.into_iter()
|
||||
.map(FeedRow::into_domain)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
Ok(Paginated {
|
||||
items,
|
||||
total_count: total as u64,
|
||||
limit: page.limit,
|
||||
offset: page.offset,
|
||||
})
|
||||
}
|
||||
|
||||
async fn count_local_posts(&self) -> Result<u64, DomainError> {
|
||||
let count: i64 =
|
||||
sqlx::query_scalar("SELECT COUNT(*) FROM reviews WHERE remote_actor_url IS NULL")
|
||||
.fetch_one(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)?;
|
||||
Ok(count as u64)
|
||||
}
|
||||
}
|
||||
195
crates/adapters/postgres/src/goals.rs
Normal file
195
crates/adapters/postgres/src/goals.rs
Normal file
@@ -0,0 +1,195 @@
|
||||
use async_trait::async_trait;
|
||||
use domain::{
|
||||
errors::DomainError,
|
||||
models::{Goal, GoalType},
|
||||
ports::GoalRepository,
|
||||
value_objects::{GoalId, UserId},
|
||||
};
|
||||
use sqlx::{PgPool, Row};
|
||||
|
||||
use crate::models::{datetime_to_str, parse_datetime, parse_uuid};
|
||||
|
||||
pub struct PostgresGoalRepository {
|
||||
pool: PgPool,
|
||||
}
|
||||
|
||||
impl PostgresGoalRepository {
|
||||
pub fn new(pool: PgPool) -> Self {
|
||||
Self { pool }
|
||||
}
|
||||
|
||||
fn map_err(e: sqlx::Error) -> DomainError {
|
||||
tracing::error!("Database error: {:?}", e);
|
||||
DomainError::InfrastructureError("Database operation failed".into())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl GoalRepository for PostgresGoalRepository {
|
||||
async fn save(&self, goal: &Goal) -> Result<(), DomainError> {
|
||||
let id = goal.id().value().to_string();
|
||||
let user_id = goal.user_id().value().to_string();
|
||||
let year = goal.year() as i64;
|
||||
let target = goal.target_count() as i64;
|
||||
let goal_type = goal.goal_type().as_str();
|
||||
let created_at = datetime_to_str(goal.created_at());
|
||||
|
||||
sqlx::query(
|
||||
"INSERT INTO goals (id, user_id, year, target_count, goal_type, created_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6::timestamptz)",
|
||||
)
|
||||
.bind(&id)
|
||||
.bind(&user_id)
|
||||
.bind(year)
|
||||
.bind(target)
|
||||
.bind(goal_type)
|
||||
.bind(&created_at)
|
||||
.execute(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn update(&self, goal: &Goal) -> Result<(), DomainError> {
|
||||
let id = goal.id().value().to_string();
|
||||
let target = goal.target_count() as i64;
|
||||
|
||||
let result = sqlx::query("UPDATE goals SET target_count = $1 WHERE id = $2")
|
||||
.bind(target)
|
||||
.bind(&id)
|
||||
.execute(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)?;
|
||||
|
||||
if result.rows_affected() == 0 {
|
||||
return Err(DomainError::NotFound("Goal not found".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn delete(&self, id: &GoalId, user_id: &UserId) -> Result<(), DomainError> {
|
||||
let gid = id.value().to_string();
|
||||
let uid = user_id.value().to_string();
|
||||
|
||||
let result = sqlx::query("DELETE FROM goals WHERE id = $1 AND user_id = $2")
|
||||
.bind(&gid)
|
||||
.bind(&uid)
|
||||
.execute(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)?;
|
||||
|
||||
if result.rows_affected() == 0 {
|
||||
return Err(DomainError::NotFound("Goal not found".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn find_by_user_and_year(
|
||||
&self,
|
||||
user_id: &UserId,
|
||||
year: u16,
|
||||
) -> Result<Option<Goal>, DomainError> {
|
||||
let uid = user_id.value().to_string();
|
||||
let y = year as i64;
|
||||
|
||||
let row = sqlx::query(
|
||||
"SELECT id, user_id, year, target_count, goal_type, \
|
||||
to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') AS created_at \
|
||||
FROM goals WHERE user_id = $1 AND year = $2",
|
||||
)
|
||||
.bind(&uid)
|
||||
.bind(y)
|
||||
.fetch_optional(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)?;
|
||||
|
||||
row.map(|r| row_to_goal(&r)).transpose()
|
||||
}
|
||||
|
||||
async fn list_for_user(&self, user_id: &UserId) -> Result<Vec<Goal>, DomainError> {
|
||||
let uid = user_id.value().to_string();
|
||||
|
||||
let rows = sqlx::query(
|
||||
"SELECT id, user_id, year, target_count, goal_type, \
|
||||
to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') AS created_at \
|
||||
FROM goals WHERE user_id = $1 ORDER BY year DESC",
|
||||
)
|
||||
.bind(&uid)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)?;
|
||||
|
||||
rows.iter().map(row_to_goal).collect()
|
||||
}
|
||||
|
||||
async fn count_reviews_in_year(&self, user_id: &UserId, year: u16) -> Result<u32, DomainError> {
|
||||
count_reviews_in_year(&self.pool, user_id, year).await
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn count_reviews_in_year(
|
||||
pool: &PgPool,
|
||||
user_id: &UserId,
|
||||
year: u16,
|
||||
) -> Result<u32, DomainError> {
|
||||
let uid = user_id.value().to_string();
|
||||
let start = format!("{year}-01-01 00:00:00");
|
||||
let end = format!("{}-01-01 00:00:00", year + 1);
|
||||
|
||||
let count: i64 = sqlx::query(
|
||||
"SELECT COUNT(*) FROM reviews \
|
||||
WHERE user_id = $1 \
|
||||
AND watched_at >= $2::timestamptz \
|
||||
AND watched_at < $3::timestamptz \
|
||||
AND remote_actor_url IS NULL",
|
||||
)
|
||||
.bind(&uid)
|
||||
.bind(&start)
|
||||
.bind(&end)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!("Database error: {:?}", e);
|
||||
DomainError::InfrastructureError("Database operation failed".into())
|
||||
})?
|
||||
.try_get(0)
|
||||
.unwrap_or(0);
|
||||
|
||||
Ok(count as u32)
|
||||
}
|
||||
|
||||
pub(crate) fn row_to_goal(r: &sqlx::postgres::PgRow) -> Result<Goal, DomainError> {
|
||||
let id_str: String = r
|
||||
.try_get("id")
|
||||
.map_err(|e| DomainError::InfrastructureError(format!("Failed to read goal id: {e}")))?;
|
||||
let user_id_str: String = r
|
||||
.try_get("user_id")
|
||||
.map_err(|e| DomainError::InfrastructureError(format!("Failed to read user_id: {e}")))?;
|
||||
let year: i64 = r
|
||||
.try_get("year")
|
||||
.map_err(|e| DomainError::InfrastructureError(format!("Failed to read year: {e}")))?;
|
||||
let target: i64 = r.try_get("target_count").map_err(|e| {
|
||||
DomainError::InfrastructureError(format!("Failed to read target_count: {e}"))
|
||||
})?;
|
||||
let goal_type_str: String = r
|
||||
.try_get("goal_type")
|
||||
.map_err(|e| DomainError::InfrastructureError(format!("Failed to read goal_type: {e}")))?;
|
||||
let created_at_str: String = r
|
||||
.try_get("created_at")
|
||||
.map_err(|e| DomainError::InfrastructureError(format!("Failed to read created_at: {e}")))?;
|
||||
|
||||
let id = GoalId::from_uuid(parse_uuid(&id_str)?);
|
||||
let user_id = UserId::from_uuid(parse_uuid(&user_id_str)?);
|
||||
let goal_type: GoalType = goal_type_str.parse()?;
|
||||
let created_at = parse_datetime(&created_at_str)?;
|
||||
|
||||
Ok(Goal::from_persistence(
|
||||
id,
|
||||
user_id,
|
||||
year as u16,
|
||||
target as u32,
|
||||
goal_type,
|
||||
created_at,
|
||||
))
|
||||
}
|
||||
@@ -5,6 +5,7 @@ use domain::{
|
||||
models::{
|
||||
AnnotatedRow, FieldMapping, ImportSession, ParsedFile,
|
||||
import::{DomainField, ImportRow, RowResult, Transform},
|
||||
import_session::PersistedImportSession,
|
||||
},
|
||||
ports::ImportSessionRepository,
|
||||
value_objects::{ImportSessionId, UserId},
|
||||
@@ -266,7 +267,7 @@ impl PostgresImportSessionRepository {
|
||||
Ok(js.into_iter().map(annotated_from_json).collect())
|
||||
})
|
||||
.transpose()?;
|
||||
Ok(ImportSession {
|
||||
Ok(ImportSession::from_persistence(PersistedImportSession {
|
||||
id: ImportSessionId::from_uuid(
|
||||
id.parse::<uuid::Uuid>()
|
||||
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?,
|
||||
@@ -281,7 +282,7 @@ impl PostgresImportSessionRepository {
|
||||
row_results,
|
||||
created_at,
|
||||
expires_at,
|
||||
})
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -7,7 +7,7 @@ use domain::{
|
||||
},
|
||||
value_objects::{
|
||||
Comment, Email, ExternalMetadataId, MovieId, MovieTitle, PosterPath, Rating, ReleaseYear,
|
||||
ReviewId, UserId,
|
||||
ReviewId, UserId, Username,
|
||||
},
|
||||
};
|
||||
use uuid::Uuid;
|
||||
@@ -237,6 +237,8 @@ impl MovieStatsRow {
|
||||
pub(crate) struct UserSummaryRow {
|
||||
pub id: String,
|
||||
pub email: String,
|
||||
pub username: String,
|
||||
pub display_name: Option<String>,
|
||||
pub total_movies: i64,
|
||||
pub avg_rating: Option<f64>,
|
||||
pub avatar_path: Option<String>,
|
||||
@@ -247,6 +249,8 @@ impl UserSummaryRow {
|
||||
Ok(UserSummary::new(
|
||||
UserId::from_uuid(parse_uuid(&self.id)?),
|
||||
Email::new(self.email)?,
|
||||
Username::new(self.username)?,
|
||||
self.display_name,
|
||||
self.total_movies,
|
||||
self.avg_rating,
|
||||
self.avatar_path,
|
||||
|
||||
242
crates/adapters/postgres/src/movie.rs
Normal file
242
crates/adapters/postgres/src/movie.rs
Normal file
@@ -0,0 +1,242 @@
|
||||
use async_trait::async_trait;
|
||||
use domain::{
|
||||
errors::DomainError,
|
||||
models::{
|
||||
Movie, MovieFilter, MovieSummary,
|
||||
collections::{PageParams, Paginated},
|
||||
},
|
||||
ports::MovieRepository,
|
||||
value_objects::{ExternalMetadataId, MovieId, MovieTitle, ReleaseYear},
|
||||
};
|
||||
use sqlx::PgPool;
|
||||
|
||||
use crate::models::{MovieRow, MovieSummaryRow};
|
||||
|
||||
pub struct PostgresMovieRepository {
|
||||
pool: PgPool,
|
||||
}
|
||||
|
||||
impl PostgresMovieRepository {
|
||||
pub fn new(pool: PgPool) -> Self {
|
||||
Self { pool }
|
||||
}
|
||||
|
||||
fn map_err(e: sqlx::Error) -> DomainError {
|
||||
tracing::error!("Database error: {:?}", e);
|
||||
DomainError::InfrastructureError("Database operation failed".into())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl MovieRepository for PostgresMovieRepository {
|
||||
async fn get_movie_by_external_id(
|
||||
&self,
|
||||
external_metadata_id: &ExternalMetadataId,
|
||||
) -> Result<Option<Movie>, DomainError> {
|
||||
let id = external_metadata_id.value();
|
||||
sqlx::query_as::<_, MovieRow>(
|
||||
"SELECT id, external_metadata_id, title, release_year, director, poster_path
|
||||
FROM movies WHERE external_metadata_id = $1",
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_optional(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)?
|
||||
.map(MovieRow::into_domain)
|
||||
.transpose()
|
||||
}
|
||||
|
||||
async fn get_movie_by_id(&self, movie_id: &MovieId) -> Result<Option<Movie>, DomainError> {
|
||||
let id = movie_id.value().to_string();
|
||||
sqlx::query_as::<_, MovieRow>(
|
||||
"SELECT id, external_metadata_id, title, release_year, director, poster_path
|
||||
FROM movies WHERE id = $1",
|
||||
)
|
||||
.bind(&id)
|
||||
.fetch_optional(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)?
|
||||
.map(MovieRow::into_domain)
|
||||
.transpose()
|
||||
}
|
||||
|
||||
async fn get_movies_by_title_and_year(
|
||||
&self,
|
||||
title: &MovieTitle,
|
||||
year: &ReleaseYear,
|
||||
) -> Result<Vec<Movie>, DomainError> {
|
||||
let title = title.value();
|
||||
let year = year.value() as i64;
|
||||
sqlx::query_as::<_, MovieRow>(
|
||||
"SELECT id, external_metadata_id, title, release_year, director, poster_path
|
||||
FROM movies WHERE title = $1 AND release_year = $2",
|
||||
)
|
||||
.bind(title)
|
||||
.bind(year)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)?
|
||||
.into_iter()
|
||||
.map(MovieRow::into_domain)
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn upsert_movie(&self, movie: &Movie) -> Result<(), DomainError> {
|
||||
let id = movie.id().value().to_string();
|
||||
let external_metadata_id = movie.external_metadata_id().map(|e| e.value().to_string());
|
||||
let title = movie.title().value();
|
||||
let release_year = movie.release_year().value() as i64;
|
||||
let director = movie.director();
|
||||
let poster_path = movie.poster_path().map(|p| p.value().to_string());
|
||||
|
||||
sqlx::query(
|
||||
"INSERT INTO movies (id, external_metadata_id, title, release_year, director, poster_path)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
external_metadata_id = excluded.external_metadata_id,
|
||||
title = excluded.title,
|
||||
release_year = excluded.release_year,
|
||||
director = excluded.director,
|
||||
poster_path = excluded.poster_path",
|
||||
)
|
||||
.bind(&id)
|
||||
.bind(&external_metadata_id)
|
||||
.bind(title)
|
||||
.bind(release_year)
|
||||
.bind(director)
|
||||
.bind(&poster_path)
|
||||
.execute(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn delete_movie(&self, movie_id: &MovieId) -> Result<(), DomainError> {
|
||||
let id = movie_id.value().to_string();
|
||||
sqlx::query("DELETE FROM movies WHERE id = $1")
|
||||
.bind(&id)
|
||||
.execute(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn existing_external_ids(
|
||||
&self,
|
||||
ids: &[ExternalMetadataId],
|
||||
) -> Result<std::collections::HashSet<String>, DomainError> {
|
||||
if ids.is_empty() {
|
||||
return Ok(Default::default());
|
||||
}
|
||||
let vals: Vec<String> = ids.iter().map(|id| id.value().to_string()).collect();
|
||||
let rows: Vec<(String,)> = sqlx::query_as(
|
||||
"SELECT external_metadata_id FROM movies WHERE external_metadata_id = ANY($1)",
|
||||
)
|
||||
.bind(&vals)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)?;
|
||||
Ok(rows.into_iter().map(|(id,)| id).collect())
|
||||
}
|
||||
|
||||
async fn existing_title_year_pairs(
|
||||
&self,
|
||||
pairs: &[(MovieTitle, ReleaseYear)],
|
||||
) -> Result<std::collections::HashSet<(String, u16)>, DomainError> {
|
||||
if pairs.is_empty() {
|
||||
return Ok(Default::default());
|
||||
}
|
||||
let titles: Vec<&str> = pairs.iter().map(|(t, _)| t.value()).collect();
|
||||
let years: Vec<i64> = pairs.iter().map(|(_, y)| y.value() as i64).collect();
|
||||
use sqlx::Row;
|
||||
let rows = sqlx::query(
|
||||
"SELECT DISTINCT m.title, m.release_year FROM movies m \
|
||||
INNER JOIN unnest($1::text[], $2::bigint[]) AS p(title, release_year) \
|
||||
ON m.title = p.title AND m.release_year = p.release_year",
|
||||
)
|
||||
.bind(&titles)
|
||||
.bind(&years)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let t: String = r.get("title");
|
||||
let y: i64 = r.get("release_year");
|
||||
(t, y as u16)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn list_movies(
|
||||
&self,
|
||||
page: &PageParams,
|
||||
filter: &MovieFilter,
|
||||
) -> Result<Paginated<MovieSummary>, DomainError> {
|
||||
use sqlx::Row;
|
||||
let limit = page.limit as i64;
|
||||
let offset = page.offset as i64;
|
||||
let pattern = filter
|
||||
.search
|
||||
.as_deref()
|
||||
.map(|s| format!("%{}%", s.to_lowercase()));
|
||||
let genre = filter.genre.as_deref();
|
||||
let language = filter.language.as_deref();
|
||||
|
||||
let rows: Vec<MovieSummaryRow> = sqlx::query_as(
|
||||
"SELECT \
|
||||
m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path, \
|
||||
p.overview, p.runtime_minutes, p.original_language, p.collection_name, \
|
||||
array_agg(g.name) FILTER (WHERE g.name IS NOT NULL) AS genres \
|
||||
FROM movies m \
|
||||
LEFT JOIN movie_profiles p ON p.movie_id = m.id \
|
||||
LEFT JOIN movie_genres g ON g.movie_id = m.id \
|
||||
WHERE ($1::text IS NULL OR LOWER(m.title) LIKE $1) \
|
||||
AND ($2::text IS NULL OR p.original_language = $2) \
|
||||
AND ($3::text IS NULL OR m.id IN (SELECT movie_id FROM movie_genres WHERE LOWER(name) = LOWER($3))) \
|
||||
GROUP BY m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path, \
|
||||
p.overview, p.runtime_minutes, p.original_language, p.collection_name \
|
||||
ORDER BY m.title ASC \
|
||||
LIMIT $4 OFFSET $5",
|
||||
)
|
||||
.bind(&pattern)
|
||||
.bind(language)
|
||||
.bind(genre)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)?;
|
||||
|
||||
let total: i64 = sqlx::query(
|
||||
"SELECT COUNT(DISTINCT m.id) \
|
||||
FROM movies m \
|
||||
LEFT JOIN movie_profiles p ON p.movie_id = m.id \
|
||||
WHERE ($1::text IS NULL OR LOWER(m.title) LIKE $1) \
|
||||
AND ($2::text IS NULL OR p.original_language = $2) \
|
||||
AND ($3::text IS NULL OR m.id IN (SELECT movie_id FROM movie_genres WHERE LOWER(name) = LOWER($3)))",
|
||||
)
|
||||
.bind(&pattern)
|
||||
.bind(language)
|
||||
.bind(genre)
|
||||
.fetch_one(&self.pool)
|
||||
.await
|
||||
.map_err(Self::map_err)?
|
||||
.try_get(0)
|
||||
.unwrap_or(0);
|
||||
|
||||
let items = rows
|
||||
.into_iter()
|
||||
.map(|r| r.into_domain())
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
Ok(Paginated {
|
||||
items,
|
||||
total_count: total as u64,
|
||||
limit: page.limit,
|
||||
offset: page.offset,
|
||||
})
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user