Compare commits
84 Commits
c4d6b68ef9
...
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 |
32
Cargo.lock
generated
32
Cargo.lock
generated
@@ -314,6 +314,7 @@ name = "application"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"async-trait",
|
"async-trait",
|
||||||
|
"bytes",
|
||||||
"chrono",
|
"chrono",
|
||||||
"domain",
|
"domain",
|
||||||
"futures",
|
"futures",
|
||||||
@@ -567,6 +568,28 @@ dependencies = [
|
|||||||
"windows-sys 0.61.2",
|
"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]]
|
[[package]]
|
||||||
name = "async-task"
|
name = "async-task"
|
||||||
version = "4.7.1"
|
version = "4.7.1"
|
||||||
@@ -1822,9 +1845,12 @@ dependencies = [
|
|||||||
name = "export"
|
name = "export"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"async-stream",
|
||||||
"async-trait",
|
"async-trait",
|
||||||
|
"bytes",
|
||||||
"chrono",
|
"chrono",
|
||||||
"domain",
|
"domain",
|
||||||
|
"futures",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"tokio",
|
"tokio",
|
||||||
"uuid",
|
"uuid",
|
||||||
@@ -3848,9 +3874,12 @@ name = "postgres"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
|
"async-stream",
|
||||||
"async-trait",
|
"async-trait",
|
||||||
|
"bytes",
|
||||||
"chrono",
|
"chrono",
|
||||||
"domain",
|
"domain",
|
||||||
|
"futures",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"sqlx",
|
"sqlx",
|
||||||
@@ -5124,9 +5153,12 @@ name = "sqlite"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
|
"async-stream",
|
||||||
"async-trait",
|
"async-trait",
|
||||||
|
"bytes",
|
||||||
"chrono",
|
"chrono",
|
||||||
"domain",
|
"domain",
|
||||||
|
"futures",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"sqlx",
|
"sqlx",
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ resolver = "2"
|
|||||||
tokio = { version = "1.0", features = ["macros", "net", "rt", "rt-multi-thread", "sync", "time"] }
|
tokio = { version = "1.0", features = ["macros", "net", "rt", "rt-multi-thread", "sync", "time"] }
|
||||||
bytes = "1"
|
bytes = "1"
|
||||||
futures = "0.3"
|
futures = "0.3"
|
||||||
|
async-stream = "0.3"
|
||||||
dotenvy = "0.15"
|
dotenvy = "0.15"
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
@@ -52,7 +53,6 @@ sqlx = { version = "0.8.6", features = [
|
|||||||
"runtime-tokio-rustls",
|
"runtime-tokio-rustls",
|
||||||
"sqlite",
|
"sqlite",
|
||||||
"uuid",
|
"uuid",
|
||||||
"macros",
|
|
||||||
] }
|
] }
|
||||||
rand = "0.9"
|
rand = "0.9"
|
||||||
reqwest = { version = "0.13", features = ["json", "query"] }
|
reqwest = { version = "0.13", features = ["json", "query"] }
|
||||||
@@ -91,3 +91,10 @@ plex = { path = "crates/adapters/plex" }
|
|||||||
image-converter = { path = "crates/adapters/image-converter" }
|
image-converter = { path = "crates/adapters/image-converter" }
|
||||||
sqlite-search = { path = "crates/adapters/sqlite-search" }
|
sqlite-search = { path = "crates/adapters/sqlite-search" }
|
||||||
postgres-search = { path = "crates/adapters/postgres-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
|
||||||
|
|||||||
11
Makefile
11
Makefile
@@ -1,9 +1,18 @@
|
|||||||
.DEFAULT_GOAL := check
|
.DEFAULT_GOAL := check
|
||||||
|
|
||||||
# Run the full local check suite — same order as CI would.
|
# 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"
|
@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.
|
# Apply rustfmt to all files.
|
||||||
fmt:
|
fmt:
|
||||||
cargo fmt
|
cargo fmt
|
||||||
|
|||||||
137
README.md
137
README.md
@@ -1,6 +1,49 @@
|
|||||||
# Movies Diary
|
# 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
|
## Features
|
||||||
|
|
||||||
@@ -28,6 +71,18 @@ A self-hosted, server-side rendered movie logging system with a full REST API. B
|
|||||||
- Single-page app at `/app/` — React + TanStack Router + shadcn/ui, built with Vite, served from the backend with client-side routing fallback
|
- 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
|
- Terminal UI client (`crates/tui`, deprecated) for logging reviews, bulk CSV import, and diary browsing
|
||||||
|
|
||||||
|
## Screenshots
|
||||||
|
|
||||||
|
> SPA at `/app/` — React + TanStack Router + shadcn/ui
|
||||||
|
|
||||||
|
| Feed | Movie | Person |
|
||||||
|
|------|-------|--------|
|
||||||
|
|  |  |  |
|
||||||
|
|
||||||
|
| Profile | Wrap-Up | Wrap-Up card |
|
||||||
|
|---------|---------|--------------|
|
||||||
|
|  |  |  |
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
Hexagonal (Ports & Adapters) with Domain-Driven Design:
|
Hexagonal (Ports & Adapters) with Domain-Driven Design:
|
||||||
@@ -75,59 +130,35 @@ spa/ — React SPA (TanStack Router + shadcn/ui + Vite); served a
|
|||||||
- Poster storage: local filesystem (zero deps) or an S3-compatible object store (e.g. MinIO)
|
- Poster storage: local filesystem (zero deps) or an S3-compatible object store (e.g. MinIO)
|
||||||
- An [OMDb API key](https://www.omdbapi.com/apikey.aspx)
|
- An [OMDb API key](https://www.omdbapi.com/apikey.aspx)
|
||||||
|
|
||||||
## 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
|
| Variable | Default | Required | Description |
|
||||||
# Database
|
|---|---|---|---|
|
||||||
DATABASE_URL=sqlite://movies.db
|
| `DATABASE_URL` | `sqlite://movies.db` | Yes | SQLite or PostgreSQL connection string |
|
||||||
|
| `JWT_SECRET` | — | Yes | Secret for JWT signing — use a long random string |
|
||||||
# Authentication
|
| `OMDB_API_KEY` | — | Yes | [OMDb](https://www.omdbapi.com/apikey.aspx) key for movie metadata |
|
||||||
JWT_SECRET=change-me
|
| `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) |
|
||||||
# OMDb metadata
|
| `IMAGE_STORAGE_BACKEND` | `local` | No | `local` or `s3` |
|
||||||
OMDB_API_KEY=your-key
|
| `IMAGE_STORAGE_PATH` | `./images` | No | Path for local image storage |
|
||||||
|
| `MINIO_ENDPOINT` | — | S3 only | S3-compatible endpoint (e.g. `http://localhost:9000`) |
|
||||||
# TMDb metadata + enrichment (optional — enables full cast/crew/genre data)
|
| `MINIO_BUCKET` | — | S3 only | Bucket name |
|
||||||
# TMDB_API_KEY=your-key
|
| `MINIO_REGION` | — | S3 only | Region (e.g. `minio`) |
|
||||||
|
| `MINIO_ACCESS_KEY_ID` | — | S3 only | Access key ID |
|
||||||
# Public base URL (used for ActivityPub actor URLs and canonical links)
|
| `MINIO_SECRET_ACCESS_KEY` | — | S3 only | Secret access key |
|
||||||
BASE_URL=https://yourdomain.example.com
|
| `IMAGE_CONVERSION_ENABLED` | `false` | No | Convert stored images to AVIF or WebP |
|
||||||
|
| `IMAGE_CONVERSION_FORMAT` | `avif` | No | `avif` or `webp` |
|
||||||
# Image storage — pick one backend:
|
| `HOST` | `0.0.0.0` | No | Bind address |
|
||||||
|
| `PORT` | `3000` | No | HTTP port |
|
||||||
# Option A: local filesystem (zero deps)
|
| `RATE_LIMIT` | `60` | No | Requests per minute per IP |
|
||||||
IMAGE_STORAGE_BACKEND=local
|
| `ALLOW_REGISTRATION` | `true` | No | Set `false` to disable new sign-ups |
|
||||||
IMAGE_STORAGE_PATH=./images
|
| `SECURE_COOKIES` | `true` | No | Must be `true` when serving over HTTPS |
|
||||||
|
| `RUST_LOG` | — | No | Log verbosity (e.g. `presentation=info,worker=info`) |
|
||||||
# Option B: S3-compatible (MinIO, AWS S3, etc.)
|
| `CORS_ORIGINS` | `*` | No | Comma-separated allowed origins for SPA dev |
|
||||||
# IMAGE_STORAGE_BACKEND=s3
|
| `EVENT_BUS_BACKEND` | `db` | No | `db` (default) or `nats` |
|
||||||
# MINIO_ENDPOINT=http://localhost:9000
|
| `NATS_URL` | — | NATS only | NATS connection URL (e.g. `nats://localhost:4222`) |
|
||||||
# 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
|
|
||||||
|
|
||||||
# CORS — comma-separated origins for SPA dev (omit or "*" for any)
|
|
||||||
# CORS_ORIGINS=http://localhost:5173
|
|
||||||
|
|
||||||
# Event bus — "db" (default, uses same database) or "nats"
|
|
||||||
EVENT_BUS_BACKEND=db
|
|
||||||
# NATS_URL=nats://localhost:4222 # required when EVENT_BUS_BACKEND=nats
|
|
||||||
```
|
|
||||||
|
|
||||||
The `worker` binary must run alongside `presentation` to process events:
|
The `worker` binary must run alongside `presentation` to process events:
|
||||||
|
|
||||||
@@ -153,6 +184,8 @@ Interactive API documentation is available at runtime:
|
|||||||
- **Swagger UI** — `http://localhost:3000/docs`
|
- **Swagger UI** — `http://localhost:3000/docs`
|
||||||
- **Scalar** — `http://localhost:3000/scalar`
|
- **Scalar** — `http://localhost:3000/scalar`
|
||||||
|
|
||||||
|
An [Insomnia](https://insomnia.rest/) collection covering all endpoints is included at [`movies-diary.insomnia.json`](movies-diary.insomnia.json). Import it via **File → Import**, set `base_url` and `token` in the environment, and you're ready to go.
|
||||||
|
|
||||||
## SPA
|
## SPA
|
||||||
|
|
||||||
The single-page app lives in `spa/` and is served at `/app/` by the backend. For local development:
|
The single-page app lives in `spa/` and is served at `/app/` by the backend. For local development:
|
||||||
|
|||||||
@@ -59,8 +59,12 @@ graph TB
|
|||||||
P_SEARCH["SearchPort<br/>SearchCommand<br/>PersonQuery<br/>PersonCommand"]
|
P_SEARCH["SearchPort<br/>SearchCommand<br/>PersonQuery<br/>PersonCommand"]
|
||||||
P_FEDERATION["SocialQueryPort<br/>LocalApContentQuery<br/>RemoteWatchlistRepository<br/>RemoteGoalRepository"]
|
P_FEDERATION["SocialQueryPort<br/>LocalApContentQuery<br/>RemoteWatchlistRepository<br/>RemoteGoalRepository"]
|
||||||
end
|
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>"]
|
EVENTS["DomainEvent enum<br/><i>ReviewLogged, MovieDiscovered,<br/>GoalCreated, GoalUpdated,<br/>SearchReindexRequested, ...</i>"]
|
||||||
VO["Value Objects<br/><i>MovieId, UserId, Rating,<br/>Email, Username, ...</i>"]
|
VO["Value Objects<br/><i>MovieId, UserId, Rating,<br/>Email, Username, Password, ...</i>"]
|
||||||
end
|
end
|
||||||
|
|
||||||
subgraph ApiTypes["api-types (0 domain deps)"]
|
subgraph ApiTypes["api-types (0 domain deps)"]
|
||||||
@@ -114,6 +118,7 @@ graph TB
|
|||||||
WORKER -->|"uses"| Application
|
WORKER -->|"uses"| Application
|
||||||
|
|
||||||
Application -->|"depends on"| Domain
|
Application -->|"depends on"| Domain
|
||||||
|
UC_WRAPUP -->|"delegates to"| DS_WRAPUP
|
||||||
|
|
||||||
Adapters -.->|"implements"| Ports
|
Adapters -.->|"implements"| Ports
|
||||||
|
|
||||||
@@ -128,6 +133,7 @@ graph TB
|
|||||||
classDef api fill:#2a2a4a,stroke:#e94560,color:#fff
|
classDef api fill:#2a2a4a,stroke:#e94560,color:#fff
|
||||||
|
|
||||||
class Domain domain
|
class Domain domain
|
||||||
|
class DomainServices domain
|
||||||
class Application app
|
class Application app
|
||||||
class Adapters adapter
|
class Adapters adapter
|
||||||
class Binaries binary
|
class Binaries binary
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use domain::ports::EventHandler;
|
|||||||
use domain::{
|
use domain::{
|
||||||
errors::DomainError,
|
errors::DomainError,
|
||||||
events::DomainEvent,
|
events::DomainEvent,
|
||||||
ports::LocalApContentQuery,
|
ports::{LocalApContentQuery, UserFederationSettingsQuery},
|
||||||
value_objects::{MovieId, ReviewId, UserId},
|
value_objects::{MovieId, ReviewId, UserId},
|
||||||
};
|
};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
@@ -17,6 +17,7 @@ use crate::urls::{actor_url, goal_url, review_url};
|
|||||||
pub struct ActivityPubEventHandler {
|
pub struct ActivityPubEventHandler {
|
||||||
ap_service: Arc<ActivityPubService>,
|
ap_service: Arc<ActivityPubService>,
|
||||||
content_query: Arc<dyn LocalApContentQuery>,
|
content_query: Arc<dyn LocalApContentQuery>,
|
||||||
|
federation_settings: Arc<dyn UserFederationSettingsQuery>,
|
||||||
base_url: String,
|
base_url: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -24,11 +25,13 @@ impl ActivityPubEventHandler {
|
|||||||
pub fn new(
|
pub fn new(
|
||||||
ap_service: Arc<ActivityPubService>,
|
ap_service: Arc<ActivityPubService>,
|
||||||
content_query: Arc<dyn LocalApContentQuery>,
|
content_query: Arc<dyn LocalApContentQuery>,
|
||||||
|
federation_settings: Arc<dyn UserFederationSettingsQuery>,
|
||||||
base_url: String,
|
base_url: String,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
ap_service,
|
ap_service,
|
||||||
content_query,
|
content_query,
|
||||||
|
federation_settings,
|
||||||
base_url,
|
base_url,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -131,6 +134,19 @@ impl EventHandler for ActivityPubEventHandler {
|
|||||||
|
|
||||||
impl ActivityPubEventHandler {
|
impl ActivityPubEventHandler {
|
||||||
async fn on_review_logged(&self, user_id: &UserId, review_id: &ReviewId) -> anyhow::Result<()> {
|
async fn on_review_logged(&self, user_id: &UserId, review_id: &ReviewId) -> anyhow::Result<()> {
|
||||||
|
let flags = self
|
||||||
|
.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? {
|
let review = match self.content_query.get_review_by_id(review_id).await? {
|
||||||
Some(r) => r,
|
Some(r) => r,
|
||||||
None => return Ok(()),
|
None => return Ok(()),
|
||||||
@@ -184,6 +200,19 @@ impl ActivityPubEventHandler {
|
|||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
review_id: &ReviewId,
|
review_id: &ReviewId,
|
||||||
) -> anyhow::Result<()> {
|
) -> 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? {
|
let review = match self.content_query.get_review_by_id(review_id).await? {
|
||||||
Some(r) => r,
|
Some(r) => r,
|
||||||
None => return Ok(()),
|
None => return Ok(()),
|
||||||
@@ -250,6 +279,19 @@ impl ActivityPubEventHandler {
|
|||||||
external_metadata_id: &Option<String>,
|
external_metadata_id: &Option<String>,
|
||||||
added_at: &chrono::NaiveDateTime,
|
added_at: &chrono::NaiveDateTime,
|
||||||
) -> anyhow::Result<()> {
|
) -> 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;
|
use crate::urls::watchlist_entry_url;
|
||||||
let ap_id = watchlist_entry_url(&self.base_url, user_id.value(), movie_id.value());
|
let ap_id = watchlist_entry_url(&self.base_url, user_id.value(), movie_id.value());
|
||||||
let actor = actor_url(&self.base_url, user_id.value());
|
let actor = actor_url(&self.base_url, user_id.value());
|
||||||
@@ -316,6 +358,20 @@ impl ActivityPubEventHandler {
|
|||||||
for entry in entries {
|
for entry in entries {
|
||||||
let review = entry.review();
|
let review = entry.review();
|
||||||
let user_id = review.user_id();
|
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 ap_id = review_url(&self.base_url, review.id());
|
||||||
let actor = actor_url(&self.base_url, user_id.value());
|
let actor = actor_url(&self.base_url, user_id.value());
|
||||||
|
|
||||||
@@ -343,12 +399,16 @@ impl ActivityPubEventHandler {
|
|||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
year: u16,
|
year: u16,
|
||||||
) -> anyhow::Result<()> {
|
) -> anyhow::Result<()> {
|
||||||
if !self
|
let flags = self
|
||||||
.content_query
|
.federation_settings
|
||||||
.get_user_federate_goals(user_id)
|
.get_federation_flags(user_id)
|
||||||
.await
|
.await
|
||||||
.unwrap_or(false)
|
.unwrap_or(domain::ports::FederationFlags {
|
||||||
{
|
goals: true,
|
||||||
|
reviews: true,
|
||||||
|
watchlist: true,
|
||||||
|
});
|
||||||
|
if !flags.goals {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
let Some((goal, current)) = self
|
let Some((goal, current)) = self
|
||||||
@@ -384,12 +444,16 @@ impl ActivityPubEventHandler {
|
|||||||
target_count: u32,
|
target_count: u32,
|
||||||
is_create: bool,
|
is_create: bool,
|
||||||
) -> anyhow::Result<()> {
|
) -> anyhow::Result<()> {
|
||||||
if !self
|
let flags = self
|
||||||
.content_query
|
.federation_settings
|
||||||
.get_user_federate_goals(user_id)
|
.get_federation_flags(user_id)
|
||||||
.await
|
.await
|
||||||
.unwrap_or(false)
|
.unwrap_or(domain::ports::FederationFlags {
|
||||||
{
|
goals: true,
|
||||||
|
reviews: true,
|
||||||
|
watchlist: true,
|
||||||
|
});
|
||||||
|
if !flags.goals {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
let current = self
|
let current = self
|
||||||
@@ -418,12 +482,16 @@ impl ActivityPubEventHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn on_goal_deleted(&self, user_id: &UserId, year: u16) -> anyhow::Result<()> {
|
async fn on_goal_deleted(&self, user_id: &UserId, year: u16) -> anyhow::Result<()> {
|
||||||
if !self
|
let flags = self
|
||||||
.content_query
|
.federation_settings
|
||||||
.get_user_federate_goals(user_id)
|
.get_federation_flags(user_id)
|
||||||
.await
|
.await
|
||||||
.unwrap_or(false)
|
.unwrap_or(domain::ports::FederationFlags {
|
||||||
{
|
goals: true,
|
||||||
|
reviews: true,
|
||||||
|
watchlist: true,
|
||||||
|
});
|
||||||
|
if !flags.goals {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
let ap_id = goal_url(&self.base_url, user_id.value(), year);
|
let ap_id = goal_url(&self.base_url, user_id.value(), year);
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ pub struct ActivityPubDeps {
|
|||||||
pub remote_goal_repo: std::sync::Arc<dyn domain::ports::RemoteGoalRepository>,
|
pub remote_goal_repo: std::sync::Arc<dyn domain::ports::RemoteGoalRepository>,
|
||||||
pub local_ap_content: std::sync::Arc<dyn domain::ports::LocalApContentQuery>,
|
pub local_ap_content: std::sync::Arc<dyn domain::ports::LocalApContentQuery>,
|
||||||
pub user_repo: std::sync::Arc<dyn domain::ports::UserRepository>,
|
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 base_url: String,
|
||||||
pub allow_registration: bool,
|
pub allow_registration: bool,
|
||||||
pub event_publisher: std::sync::Arc<dyn domain::ports::EventPublisher>,
|
pub event_publisher: std::sync::Arc<dyn domain::ports::EventPublisher>,
|
||||||
@@ -68,6 +69,7 @@ pub async fn wire(deps: ActivityPubDeps) -> anyhow::Result<ActivityPubWire> {
|
|||||||
remote_goal_repo,
|
remote_goal_repo,
|
||||||
local_ap_content,
|
local_ap_content,
|
||||||
user_repo,
|
user_repo,
|
||||||
|
federation_settings,
|
||||||
base_url,
|
base_url,
|
||||||
allow_registration,
|
allow_registration,
|
||||||
event_publisher,
|
event_publisher,
|
||||||
@@ -129,6 +131,7 @@ pub async fn wire(deps: ActivityPubDeps) -> anyhow::Result<ActivityPubWire> {
|
|||||||
let event_handler = std::sync::Arc::new(ActivityPubEventHandler::new(
|
let event_handler = std::sync::Arc::new(ActivityPubEventHandler::new(
|
||||||
std::sync::Arc::clone(&concrete),
|
std::sync::Arc::clone(&concrete),
|
||||||
local_ap_content,
|
local_ap_content,
|
||||||
|
federation_settings,
|
||||||
base_url,
|
base_url,
|
||||||
)) as std::sync::Arc<dyn domain::ports::EventHandler>;
|
)) as std::sync::Arc<dyn domain::ports::EventHandler>;
|
||||||
|
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ impl AuthConfig {
|
|||||||
let ttl_seconds = std::env::var("JWT_TTL_SECONDS")
|
let ttl_seconds = std::env::var("JWT_TTL_SECONDS")
|
||||||
.ok()
|
.ok()
|
||||||
.and_then(|v| v.parse().ok())
|
.and_then(|v| v.parse().ok())
|
||||||
.unwrap_or(86400u64);
|
.unwrap_or(900u64);
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
secret,
|
secret,
|
||||||
ttl_seconds,
|
ttl_seconds,
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ use chrono::NaiveDateTime;
|
|||||||
use domain::{
|
use domain::{
|
||||||
errors::DomainError,
|
errors::DomainError,
|
||||||
events::DomainEvent,
|
events::DomainEvent,
|
||||||
|
models::{ExternalPersonId, PersonId},
|
||||||
value_objects::{
|
value_objects::{
|
||||||
ExternalMetadataId, GoalId, MovieId, PosterPath, Rating, ReviewId, UserId, WrapUpId,
|
ExternalMetadataId, GoalId, MovieId, PosterPath, Rating, ReviewId, UserId, WrapUpId,
|
||||||
},
|
},
|
||||||
@@ -109,6 +110,10 @@ pub enum EventPayload {
|
|||||||
user_id: String,
|
user_id: String,
|
||||||
year: u16,
|
year: u16,
|
||||||
},
|
},
|
||||||
|
PersonEnrichmentRequested {
|
||||||
|
person_id: String,
|
||||||
|
external_person_id: String,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EventPayload {
|
impl EventPayload {
|
||||||
@@ -135,6 +140,7 @@ impl EventPayload {
|
|||||||
EventPayload::GoalCreated { .. } => "GoalCreated",
|
EventPayload::GoalCreated { .. } => "GoalCreated",
|
||||||
EventPayload::GoalUpdated { .. } => "GoalUpdated",
|
EventPayload::GoalUpdated { .. } => "GoalUpdated",
|
||||||
EventPayload::GoalDeleted { .. } => "GoalDeleted",
|
EventPayload::GoalDeleted { .. } => "GoalDeleted",
|
||||||
|
EventPayload::PersonEnrichmentRequested { .. } => "PersonEnrichmentRequested",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -204,7 +210,7 @@ impl From<&DomainEvent> for EventPayload {
|
|||||||
external_metadata_id,
|
external_metadata_id,
|
||||||
} => EventPayload::MovieEnrichmentRequested {
|
} => EventPayload::MovieEnrichmentRequested {
|
||||||
movie_id: movie_id.value().to_string(),
|
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::ImageStored { key } => EventPayload::ImageStored { key: key.clone() },
|
||||||
DomainEvent::WatchlistEntryAdded {
|
DomainEvent::WatchlistEntryAdded {
|
||||||
@@ -311,6 +317,13 @@ impl From<&DomainEvent> for EventPayload {
|
|||||||
user_id: user_id.value().to_string(),
|
user_id: user_id.value().to_string(),
|
||||||
year: *year,
|
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(),
|
||||||
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -378,7 +391,8 @@ impl TryFrom<EventPayload> for DomainEvent {
|
|||||||
external_metadata_id,
|
external_metadata_id,
|
||||||
} => Ok(DomainEvent::MovieEnrichmentRequested {
|
} => Ok(DomainEvent::MovieEnrichmentRequested {
|
||||||
movie_id: MovieId::from_uuid(parse_uuid(&movie_id, "movie_id")?),
|
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::ImageStored { key } => Ok(DomainEvent::ImageStored { key }),
|
||||||
EventPayload::WatchlistEntryAdded {
|
EventPayload::WatchlistEntryAdded {
|
||||||
@@ -496,6 +510,13 @@ impl TryFrom<EventPayload> for DomainEvent {
|
|||||||
user_id: UserId::from_uuid(parse_uuid(&user_id, "user_id")?),
|
user_id: UserId::from_uuid(parse_uuid(&user_id, "user_id")?),
|
||||||
year,
|
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 }
|
async-trait = { workspace = true }
|
||||||
serde_json = { workspace = true }
|
serde_json = { workspace = true }
|
||||||
chrono = { workspace = true }
|
chrono = { workspace = true }
|
||||||
|
futures = { workspace = true }
|
||||||
|
bytes = { workspace = true }
|
||||||
|
async-stream = { workspace = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
uuid = { workspace = true }
|
uuid = { workspace = true }
|
||||||
|
|||||||
@@ -1,51 +1,89 @@
|
|||||||
use async_trait::async_trait;
|
use bytes::Bytes;
|
||||||
use domain::{
|
use domain::{
|
||||||
errors::DomainError,
|
errors::DomainError,
|
||||||
models::{DiaryEntry, ExportFormat},
|
models::{DiaryEntry, ExportFormat},
|
||||||
ports::DiaryExporter,
|
ports::DiaryExporter,
|
||||||
};
|
};
|
||||||
|
use futures::stream::BoxStream;
|
||||||
|
|
||||||
pub struct ExportAdapter;
|
pub struct ExportAdapter;
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl DiaryExporter for ExportAdapter {
|
impl DiaryExporter for ExportAdapter {
|
||||||
async fn serialize_entries(
|
fn stream_entries(
|
||||||
&self,
|
&self,
|
||||||
entries: &[DiaryEntry],
|
stream: BoxStream<'static, Result<DiaryEntry, DomainError>>,
|
||||||
format: ExportFormat,
|
format: ExportFormat,
|
||||||
) -> Result<Vec<u8>, DomainError> {
|
) -> BoxStream<'static, Result<Bytes, DomainError>> {
|
||||||
match format {
|
match format {
|
||||||
ExportFormat::Csv => serialize_csv(entries),
|
ExportFormat::Csv => stream_csv(stream),
|
||||||
ExportFormat::Json => serialize_json(entries),
|
ExportFormat::Json => stream_json(stream),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn serialize_csv(entries: &[DiaryEntry]) -> Result<Vec<u8>, DomainError> {
|
fn stream_csv(
|
||||||
let mut out =
|
entries: BoxStream<'static, Result<DiaryEntry, DomainError>>,
|
||||||
String::from("title,year,director,rating,comment,watched_at,external_metadata_id\n");
|
) -> BoxStream<'static, Result<Bytes, DomainError>> {
|
||||||
for e in entries {
|
use futures::StreamExt;
|
||||||
let title = csv_escape(e.movie().title().value());
|
let header = futures::stream::once(async {
|
||||||
let year = e.movie().release_year().value();
|
Ok(Bytes::from_static(
|
||||||
let director = e.movie().director().map(csv_escape).unwrap_or_default();
|
b"title,year,director,rating,comment,watched_at,external_metadata_id\n",
|
||||||
let rating = e.review().rating().value();
|
))
|
||||||
let comment = e
|
});
|
||||||
.review()
|
let rows = entries.map(|r| r.map(|e| Bytes::from(csv_row(&e))));
|
||||||
.comment()
|
Box::pin(header.chain(rows))
|
||||||
.map(|c| csv_escape(c.value()))
|
}
|
||||||
.unwrap_or_default();
|
|
||||||
let watched_at = e.review().watched_at().format("%Y-%m-%d");
|
fn stream_json(
|
||||||
let ext_id = e
|
stream: BoxStream<'static, Result<DiaryEntry, DomainError>>,
|
||||||
.movie()
|
) -> BoxStream<'static, Result<Bytes, DomainError>> {
|
||||||
.external_metadata_id()
|
Box::pin(async_stream::stream! {
|
||||||
.map(|id| id.value().to_string())
|
futures::pin_mut!(stream);
|
||||||
.unwrap_or_default();
|
let mut is_first = true;
|
||||||
out.push_str(&format!(
|
while let Some(r) = futures::StreamExt::next(&mut stream).await {
|
||||||
"{},{},{},{},{},{},{}\n",
|
match r {
|
||||||
title, year, director, rating, comment, watched_at, ext_id
|
Err(e) => { yield Err(e); return; }
|
||||||
));
|
Ok(entry) => {
|
||||||
}
|
let json = serde_json::to_string(&entry_to_json(&entry))
|
||||||
Ok(out.into_bytes())
|
.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 {
|
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> {
|
fn entry_to_json(e: &DiaryEntry) -> serde_json::Value {
|
||||||
let arr: Vec<serde_json::Value> = entries
|
serde_json::json!({
|
||||||
.iter()
|
"title": e.movie().title().value(),
|
||||||
.map(|e| {
|
"year": e.movie().release_year().value(),
|
||||||
serde_json::json!({
|
"director": e.movie().director(),
|
||||||
"title": e.movie().title().value(),
|
"rating": e.review().rating().value(),
|
||||||
"year": e.movie().release_year().value(),
|
"comment": e.review().comment().map(|c| c.value().to_string()),
|
||||||
"director": e.movie().director(),
|
"watched_at": e.review().watched_at().format("%Y-%m-%d").to_string(),
|
||||||
"rating": e.review().rating().value(),
|
"external_metadata_id": e.movie().external_metadata_id().map(|id| id.value().to_string()),
|
||||||
"comment": e.review().comment().map(|c| c.value()),
|
})
|
||||||
"watched_at": e.review().watched_at().format("%Y-%m-%d").to_string(),
|
|
||||||
"external_metadata_id": e.movie().external_metadata_id().map(|id| id.value()),
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
serde_json::to_vec_pretty(&arr).map_err(|e| DomainError::InfrastructureError(e.to_string()))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@@ -5,6 +5,27 @@ use domain::{
|
|||||||
value_objects::{ExternalMetadataId, MovieTitle, Rating, ReleaseYear},
|
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(
|
fn make_entry(
|
||||||
title: &str,
|
title: &str,
|
||||||
year: u16,
|
year: u16,
|
||||||
@@ -55,10 +76,8 @@ async fn csv_has_header_and_one_row() {
|
|||||||
5,
|
5,
|
||||||
Some("great"),
|
Some("great"),
|
||||||
);
|
);
|
||||||
let bytes = adapter
|
let bytes =
|
||||||
.serialize_entries(&[entry], ExportFormat::Csv)
|
collect_stream(adapter.stream_entries(entry_stream(vec![entry]), ExportFormat::Csv)).await;
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
let text = String::from_utf8(bytes).unwrap();
|
let text = String::from_utf8(bytes).unwrap();
|
||||||
assert!(
|
assert!(
|
||||||
text.starts_with("title,year,director,rating,comment,watched_at,external_metadata_id\n")
|
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() {
|
async fn csv_escapes_commas_in_title() {
|
||||||
let adapter = ExportAdapter;
|
let adapter = ExportAdapter;
|
||||||
let entry = make_entry("Tár, A Film", 2022, None, 4, None);
|
let entry = make_entry("Tár, A Film", 2022, None, 4, None);
|
||||||
let bytes = adapter
|
let bytes =
|
||||||
.serialize_entries(&[entry], ExportFormat::Csv)
|
collect_stream(adapter.stream_entries(entry_stream(vec![entry]), ExportFormat::Csv)).await;
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
let text = String::from_utf8(bytes).unwrap();
|
let text = String::from_utf8(bytes).unwrap();
|
||||||
assert!(text.contains("\"Tár, A Film\""));
|
assert!(text.contains("\"Tár, A Film\""));
|
||||||
}
|
}
|
||||||
@@ -87,10 +104,8 @@ async fn csv_escapes_commas_in_title() {
|
|||||||
async fn json_is_valid_array() {
|
async fn json_is_valid_array() {
|
||||||
let adapter = ExportAdapter;
|
let adapter = ExportAdapter;
|
||||||
let entry = make_entry("Dune", 2021, Some("Denis Villeneuve"), 5, None);
|
let entry = make_entry("Dune", 2021, Some("Denis Villeneuve"), 5, None);
|
||||||
let bytes = adapter
|
let bytes =
|
||||||
.serialize_entries(&[entry], ExportFormat::Json)
|
collect_stream(adapter.stream_entries(entry_stream(vec![entry]), ExportFormat::Json)).await;
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
let arr: Vec<serde_json::Value> = serde_json::from_slice(&bytes).unwrap();
|
let arr: Vec<serde_json::Value> = serde_json::from_slice(&bytes).unwrap();
|
||||||
assert_eq!(arr.len(), 1);
|
assert_eq!(arr.len(), 1);
|
||||||
assert_eq!(arr[0]["title"], "Dune");
|
assert_eq!(arr[0]["title"], "Dune");
|
||||||
@@ -104,27 +119,23 @@ async fn json_is_valid_array() {
|
|||||||
async fn external_metadata_id_included_when_present() {
|
async fn external_metadata_id_included_when_present() {
|
||||||
let adapter = ExportAdapter;
|
let adapter = ExportAdapter;
|
||||||
let entry = make_entry_full("Alien", 1979, None, 5, None, Some("tt0078748"));
|
let entry = make_entry_full("Alien", 1979, None, 5, None, Some("tt0078748"));
|
||||||
let bytes = adapter
|
let bytes =
|
||||||
.serialize_entries(&[entry], ExportFormat::Json)
|
collect_stream(adapter.stream_entries(entry_stream(vec![entry]), ExportFormat::Json)).await;
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
let arr: Vec<serde_json::Value> = serde_json::from_slice(&bytes).unwrap();
|
let arr: Vec<serde_json::Value> = serde_json::from_slice(&bytes).unwrap();
|
||||||
assert_eq!(arr[0]["external_metadata_id"], "tt0078748");
|
assert_eq!(arr[0]["external_metadata_id"], "tt0078748");
|
||||||
|
|
||||||
let bytes = adapter
|
let bytes = collect_stream(adapter.stream_entries(
|
||||||
.serialize_entries(
|
entry_stream(vec![make_entry_full(
|
||||||
&[make_entry_full(
|
"Alien",
|
||||||
"Alien",
|
1979,
|
||||||
1979,
|
None,
|
||||||
None,
|
5,
|
||||||
5,
|
None,
|
||||||
None,
|
Some("tt0078748"),
|
||||||
Some("tt0078748"),
|
)]),
|
||||||
)],
|
ExportFormat::Csv,
|
||||||
ExportFormat::Csv,
|
))
|
||||||
)
|
.await;
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
let text = String::from_utf8(bytes).unwrap();
|
let text = String::from_utf8(bytes).unwrap();
|
||||||
assert!(text.contains("tt0078748"));
|
assert!(text.contains("tt0078748"));
|
||||||
}
|
}
|
||||||
@@ -132,13 +143,20 @@ async fn external_metadata_id_included_when_present() {
|
|||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn empty_entries_returns_csv_header_only() {
|
async fn empty_entries_returns_csv_header_only() {
|
||||||
let adapter = ExportAdapter;
|
let adapter = ExportAdapter;
|
||||||
let bytes = adapter
|
let bytes =
|
||||||
.serialize_entries(&[], ExportFormat::Csv)
|
collect_stream(adapter.stream_entries(entry_stream(vec![]), ExportFormat::Csv)).await;
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
let text = String::from_utf8(bytes).unwrap();
|
let text = String::from_utf8(bytes).unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
text,
|
text,
|
||||||
"title,year,director,rating,comment,watched_at,external_metadata_id\n"
|
"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());
|
||||||
|
}
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ pub fn event_to_subject(prefix: &str, event: &DomainEvent) -> String {
|
|||||||
DomainEvent::GoalCreated { .. } => "goal.created",
|
DomainEvent::GoalCreated { .. } => "goal.created",
|
||||||
DomainEvent::GoalUpdated { .. } => "goal.updated",
|
DomainEvent::GoalUpdated { .. } => "goal.updated",
|
||||||
DomainEvent::GoalDeleted { .. } => "goal.deleted",
|
DomainEvent::GoalDeleted { .. } => "goal.deleted",
|
||||||
|
DomainEvent::PersonEnrichmentRequested { .. } => "person.enrichment.requested",
|
||||||
};
|
};
|
||||||
format!("{prefix}.{suffix}")
|
format!("{prefix}.{suffix}")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -123,7 +123,7 @@ impl EventHandler for PosterSyncHandler {
|
|||||||
if already_has_poster {
|
if already_has_poster {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
(movie_id.value(), external_metadata_id.clone())
|
(movie_id.value(), external_metadata_id.value().to_owned())
|
||||||
}
|
}
|
||||||
_ => return Ok(()),
|
_ => return Ok(()),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -20,3 +20,6 @@ async-trait = { workspace = true }
|
|||||||
tokio = { workspace = true }
|
tokio = { workspace = true }
|
||||||
serde = { workspace = true, features = ["derive"] }
|
serde = { workspace = true, features = ["derive"] }
|
||||||
serde_json = { workspace = true }
|
serde_json = { workspace = true }
|
||||||
|
futures = { workspace = true }
|
||||||
|
bytes = { workspace = true }
|
||||||
|
async-stream = { workspace = true }
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -229,23 +229,6 @@ impl LocalApContentQuery for PostgresApContentQuery {
|
|||||||
rows.into_iter().map(DiaryRow::into_domain).collect()
|
rows.into_iter().map(DiaryRow::into_domain).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_user_federate_goals(&self, user_id: &UserId) -> Result<bool, DomainError> {
|
|
||||||
let uid = user_id.value().to_string();
|
|
||||||
let row = sqlx::query("SELECT federate_goals FROM user_settings WHERE user_id = $1")
|
|
||||||
.bind(&uid)
|
|
||||||
.fetch_optional(&self.pool)
|
|
||||||
.await
|
|
||||||
.map_err(Self::map_err)?;
|
|
||||||
|
|
||||||
match row {
|
|
||||||
Some(r) => {
|
|
||||||
let val: i64 = r.try_get("federate_goals").unwrap_or(0);
|
|
||||||
Ok(val != 0)
|
|
||||||
}
|
|
||||||
None => Ok(false),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get_goal_with_progress(
|
async fn get_goal_with_progress(
|
||||||
&self,
|
&self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
|
|||||||
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ use domain::{
|
|||||||
models::{
|
models::{
|
||||||
AnnotatedRow, FieldMapping, ImportSession, ParsedFile,
|
AnnotatedRow, FieldMapping, ImportSession, ParsedFile,
|
||||||
import::{DomainField, ImportRow, RowResult, Transform},
|
import::{DomainField, ImportRow, RowResult, Transform},
|
||||||
|
import_session::PersistedImportSession,
|
||||||
},
|
},
|
||||||
ports::ImportSessionRepository,
|
ports::ImportSessionRepository,
|
||||||
value_objects::{ImportSessionId, UserId},
|
value_objects::{ImportSessionId, UserId},
|
||||||
@@ -266,7 +267,7 @@ impl PostgresImportSessionRepository {
|
|||||||
Ok(js.into_iter().map(annotated_from_json).collect())
|
Ok(js.into_iter().map(annotated_from_json).collect())
|
||||||
})
|
})
|
||||||
.transpose()?;
|
.transpose()?;
|
||||||
Ok(ImportSession {
|
Ok(ImportSession::from_persistence(PersistedImportSession {
|
||||||
id: ImportSessionId::from_uuid(
|
id: ImportSessionId::from_uuid(
|
||||||
id.parse::<uuid::Uuid>()
|
id.parse::<uuid::Uuid>()
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?,
|
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?,
|
||||||
@@ -281,7 +282,7 @@ impl PostgresImportSessionRepository {
|
|||||||
row_results,
|
row_results,
|
||||||
created_at,
|
created_at,
|
||||||
expires_at,
|
expires_at,
|
||||||
})
|
}))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
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,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use domain::{
|
use domain::{
|
||||||
errors::DomainError,
|
errors::DomainError,
|
||||||
models::{CastCredit, CrewCredit, ExternalPersonId, Person, PersonCredits, PersonId},
|
models::{
|
||||||
|
CastCredit, CrewCredit, ExternalPersonId, Person, PersonCredits, PersonEnrichmentData,
|
||||||
|
PersonId,
|
||||||
|
},
|
||||||
ports::{PersonCommand, PersonQuery},
|
ports::{PersonCommand, PersonQuery},
|
||||||
value_objects::MovieId,
|
value_objects::MovieId,
|
||||||
};
|
};
|
||||||
@@ -111,71 +114,61 @@ impl PersonCommand for PostgresPersonAdapter {
|
|||||||
}
|
}
|
||||||
Ok((count, has_more))
|
Ok((count, has_more))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn update_enrichment(
|
||||||
|
&self,
|
||||||
|
id: &PersonId,
|
||||||
|
data: &PersonEnrichmentData,
|
||||||
|
) -> Result<(), DomainError> {
|
||||||
|
let also_known_as_json =
|
||||||
|
serde_json::to_string(&data.also_known_as).unwrap_or_else(|_| "[]".into());
|
||||||
|
let now = chrono::Utc::now();
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE persons SET biography = $1, birthday = $2, deathday = $3, place_of_birth = $4, also_known_as = $5, homepage = $6, imdb_id = $7, enriched_at = $8 WHERE id = $9",
|
||||||
|
)
|
||||||
|
.bind(&data.biography)
|
||||||
|
.bind(data.birthday.map(|d| d.to_string()))
|
||||||
|
.bind(data.deathday.map(|d| d.to_string()))
|
||||||
|
.bind(&data.place_of_birth)
|
||||||
|
.bind(&also_known_as_json)
|
||||||
|
.bind(&data.homepage)
|
||||||
|
.bind(&data.imdb_id)
|
||||||
|
.bind(now)
|
||||||
|
.bind(id.value().to_string())
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(map_err)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl PersonQuery for PostgresPersonAdapter {
|
impl PersonQuery for PostgresPersonAdapter {
|
||||||
async fn get_by_id(&self, id: &PersonId) -> Result<Option<Person>, DomainError> {
|
async fn get_by_id(&self, id: &PersonId) -> Result<Option<Person>, DomainError> {
|
||||||
#[derive(sqlx::FromRow)]
|
let row = sqlx::query_as::<_, PersonRow>(
|
||||||
struct Row {
|
"SELECT id, external_id, name, known_for_department, profile_path, biography, birthday, deathday, place_of_birth, also_known_as, homepage, imdb_id, enriched_at FROM persons WHERE id = $1",
|
||||||
id: String,
|
|
||||||
external_id: String,
|
|
||||||
name: String,
|
|
||||||
known_for_department: Option<String>,
|
|
||||||
profile_path: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
let row = sqlx::query_as::<_, Row>(
|
|
||||||
"SELECT id, external_id, name, known_for_department, profile_path FROM persons WHERE id = $1",
|
|
||||||
)
|
)
|
||||||
.bind(id.value().to_string())
|
.bind(id.value().to_string())
|
||||||
.fetch_optional(&self.pool)
|
.fetch_optional(&self.pool)
|
||||||
.await
|
.await
|
||||||
.map_err(map_err)?;
|
.map_err(map_err)?;
|
||||||
|
|
||||||
Ok(row.map(|r| {
|
Ok(row.map(PersonRow::into_person))
|
||||||
let ext = ExternalPersonId::new(r.external_id);
|
|
||||||
Person::new(
|
|
||||||
PersonId::from_uuid(uuid::Uuid::parse_str(&r.id).unwrap_or_default()),
|
|
||||||
ext,
|
|
||||||
r.name,
|
|
||||||
r.known_for_department,
|
|
||||||
r.profile_path,
|
|
||||||
)
|
|
||||||
}))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_by_external_id(
|
async fn get_by_external_id(
|
||||||
&self,
|
&self,
|
||||||
id: &ExternalPersonId,
|
id: &ExternalPersonId,
|
||||||
) -> Result<Option<Person>, DomainError> {
|
) -> Result<Option<Person>, DomainError> {
|
||||||
#[derive(sqlx::FromRow)]
|
let row = sqlx::query_as::<_, PersonRow>(
|
||||||
struct Row {
|
"SELECT id, external_id, name, known_for_department, profile_path, biography, birthday, deathday, place_of_birth, also_known_as, homepage, imdb_id, enriched_at FROM persons WHERE external_id = $1",
|
||||||
id: String,
|
|
||||||
external_id: String,
|
|
||||||
name: String,
|
|
||||||
known_for_department: Option<String>,
|
|
||||||
profile_path: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
let row = sqlx::query_as::<_, Row>(
|
|
||||||
"SELECT id, external_id, name, known_for_department, profile_path FROM persons WHERE external_id = $1",
|
|
||||||
)
|
)
|
||||||
.bind(id.value())
|
.bind(id.value())
|
||||||
.fetch_optional(&self.pool)
|
.fetch_optional(&self.pool)
|
||||||
.await
|
.await
|
||||||
.map_err(map_err)?;
|
.map_err(map_err)?;
|
||||||
|
|
||||||
Ok(row.map(|r| {
|
Ok(row.map(PersonRow::into_person))
|
||||||
let ext = ExternalPersonId::new(r.external_id);
|
|
||||||
Person::new(
|
|
||||||
PersonId::from_uuid(uuid::Uuid::parse_str(&r.id).unwrap_or_default()),
|
|
||||||
ext,
|
|
||||||
r.name,
|
|
||||||
r.known_for_department,
|
|
||||||
r.profile_path,
|
|
||||||
)
|
|
||||||
}))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_credits(&self, id: &PersonId) -> Result<PersonCredits, DomainError> {
|
async fn get_credits(&self, id: &PersonId) -> Result<PersonCredits, DomainError> {
|
||||||
@@ -261,17 +254,8 @@ impl PersonQuery for PostgresPersonAdapter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn list_page(&self, limit: u32, offset: u32) -> Result<Vec<Person>, DomainError> {
|
async fn list_page(&self, limit: u32, offset: u32) -> Result<Vec<Person>, DomainError> {
|
||||||
#[derive(sqlx::FromRow)]
|
let rows = sqlx::query_as::<_, PersonRow>(
|
||||||
struct Row {
|
"SELECT id, external_id, name, known_for_department, profile_path, biography, birthday, deathday, place_of_birth, also_known_as, homepage, imdb_id, enriched_at FROM persons ORDER BY id LIMIT $1 OFFSET $2",
|
||||||
id: String,
|
|
||||||
external_id: String,
|
|
||||||
name: String,
|
|
||||||
known_for_department: Option<String>,
|
|
||||||
profile_path: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
let rows = sqlx::query_as::<_, Row>(
|
|
||||||
"SELECT id, external_id, name, known_for_department, profile_path FROM persons ORDER BY id LIMIT $1 OFFSET $2",
|
|
||||||
)
|
)
|
||||||
.bind(limit as i64)
|
.bind(limit as i64)
|
||||||
.bind(offset as i64)
|
.bind(offset as i64)
|
||||||
@@ -279,19 +263,7 @@ impl PersonQuery for PostgresPersonAdapter {
|
|||||||
.await
|
.await
|
||||||
.map_err(map_err)?;
|
.map_err(map_err)?;
|
||||||
|
|
||||||
Ok(rows
|
Ok(rows.into_iter().map(PersonRow::into_person).collect())
|
||||||
.into_iter()
|
|
||||||
.map(|r| {
|
|
||||||
let ext = ExternalPersonId::new(r.external_id);
|
|
||||||
Person::new(
|
|
||||||
PersonId::from_uuid(uuid::Uuid::parse_str(&r.id).unwrap_or_default()),
|
|
||||||
ext,
|
|
||||||
r.name,
|
|
||||||
r.known_for_department,
|
|
||||||
r.profile_path,
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.collect())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn list_orphaned_persons(&self) -> Result<Vec<PersonId>, DomainError> {
|
async fn list_orphaned_persons(&self) -> Result<Vec<PersonId>, DomainError> {
|
||||||
@@ -315,3 +287,57 @@ impl PersonQuery for PostgresPersonAdapter {
|
|||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Row types ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
#[derive(sqlx::FromRow)]
|
||||||
|
struct PersonRow {
|
||||||
|
id: String,
|
||||||
|
external_id: String,
|
||||||
|
name: String,
|
||||||
|
known_for_department: Option<String>,
|
||||||
|
profile_path: Option<String>,
|
||||||
|
biography: Option<String>,
|
||||||
|
birthday: Option<String>,
|
||||||
|
deathday: Option<String>,
|
||||||
|
place_of_birth: Option<String>,
|
||||||
|
also_known_as: Option<String>,
|
||||||
|
homepage: Option<String>,
|
||||||
|
imdb_id: Option<String>,
|
||||||
|
enriched_at: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PersonRow {
|
||||||
|
fn into_person(self) -> Person {
|
||||||
|
let ext = ExternalPersonId::new(self.external_id);
|
||||||
|
let also_known_as = self
|
||||||
|
.also_known_as
|
||||||
|
.and_then(|s| serde_json::from_str::<Vec<String>>(&s).ok())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let birthday = self
|
||||||
|
.birthday
|
||||||
|
.and_then(|s| chrono::NaiveDate::parse_from_str(&s, "%Y-%m-%d").ok());
|
||||||
|
let deathday = self
|
||||||
|
.deathday
|
||||||
|
.and_then(|s| chrono::NaiveDate::parse_from_str(&s, "%Y-%m-%d").ok());
|
||||||
|
let enriched_at = self
|
||||||
|
.enriched_at
|
||||||
|
.and_then(|s| chrono::DateTime::parse_from_rfc3339(&s).ok())
|
||||||
|
.map(|d| d.with_timezone(&chrono::Utc));
|
||||||
|
Person::new(
|
||||||
|
PersonId::from_uuid(uuid::Uuid::parse_str(&self.id).unwrap_or_default()),
|
||||||
|
ext,
|
||||||
|
self.name,
|
||||||
|
self.known_for_department,
|
||||||
|
self.profile_path,
|
||||||
|
self.biography,
|
||||||
|
birthday,
|
||||||
|
deathday,
|
||||||
|
self.place_of_birth,
|
||||||
|
also_known_as,
|
||||||
|
self.homepage,
|
||||||
|
self.imdb_id,
|
||||||
|
enriched_at,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
112
crates/adapters/postgres/src/refresh_sessions.rs
Normal file
112
crates/adapters/postgres/src/refresh_sessions.rs
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
use async_trait::async_trait;
|
||||||
|
use chrono::DateTime;
|
||||||
|
use domain::{
|
||||||
|
errors::DomainError, models::RefreshSession, ports::RefreshSessionRepository,
|
||||||
|
value_objects::UserId,
|
||||||
|
};
|
||||||
|
use sqlx::PgPool;
|
||||||
|
|
||||||
|
pub struct PostgresRefreshSessionAdapter {
|
||||||
|
pool: PgPool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PostgresRefreshSessionAdapter {
|
||||||
|
pub fn new(pool: PgPool) -> Self {
|
||||||
|
Self { pool }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn map_err(e: sqlx::Error) -> DomainError {
|
||||||
|
DomainError::InfrastructureError(e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl RefreshSessionRepository for PostgresRefreshSessionAdapter {
|
||||||
|
async fn create(&self, session: &RefreshSession) -> Result<(), DomainError> {
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO refresh_sessions (id, user_id, token, expires_at, created_at)
|
||||||
|
VALUES ($1, $2, $3, $4, $5)",
|
||||||
|
)
|
||||||
|
.bind(session.id.to_string())
|
||||||
|
.bind(session.user_id.value().to_string())
|
||||||
|
.bind(&session.token)
|
||||||
|
.bind(session.expires_at)
|
||||||
|
.bind(session.created_at)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(map_err)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_by_token(&self, token: &str) -> Result<Option<RefreshSession>, DomainError> {
|
||||||
|
let row = sqlx::query_as::<_, RefreshSessionRow>(
|
||||||
|
"SELECT id, user_id, token,
|
||||||
|
to_char(expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"') AS expires_at,
|
||||||
|
to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS\"Z\"') AS created_at
|
||||||
|
FROM refresh_sessions WHERE token = $1",
|
||||||
|
)
|
||||||
|
.bind(token)
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(map_err)?;
|
||||||
|
|
||||||
|
row.map(RefreshSessionRow::into_domain).transpose()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn revoke(&self, token: &str) -> Result<(), DomainError> {
|
||||||
|
sqlx::query("DELETE FROM refresh_sessions WHERE token = $1")
|
||||||
|
.bind(token)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(map_err)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn revoke_all_for_user(&self, user_id: &UserId) -> Result<(), DomainError> {
|
||||||
|
sqlx::query("DELETE FROM refresh_sessions WHERE user_id = $1")
|
||||||
|
.bind(user_id.value().to_string())
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(map_err)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn delete_expired(&self) -> Result<u64, DomainError> {
|
||||||
|
let result = sqlx::query("DELETE FROM refresh_sessions WHERE expires_at < NOW()")
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(map_err)?;
|
||||||
|
Ok(result.rows_affected())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(sqlx::FromRow)]
|
||||||
|
struct RefreshSessionRow {
|
||||||
|
id: String,
|
||||||
|
user_id: String,
|
||||||
|
token: String,
|
||||||
|
expires_at: String,
|
||||||
|
created_at: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RefreshSessionRow {
|
||||||
|
fn into_domain(self) -> Result<RefreshSession, DomainError> {
|
||||||
|
let id = uuid::Uuid::parse_str(&self.id)
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(format!("invalid uuid: {e}")))?;
|
||||||
|
let user_id = uuid::Uuid::parse_str(&self.user_id)
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(format!("invalid user_id: {e}")))?;
|
||||||
|
let expires_at = DateTime::parse_from_rfc3339(&self.expires_at)
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(format!("invalid expires_at: {e}")))?
|
||||||
|
.with_timezone(&chrono::Utc);
|
||||||
|
let created_at = DateTime::parse_from_rfc3339(&self.created_at)
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(format!("invalid created_at: {e}")))?
|
||||||
|
.with_timezone(&chrono::Utc);
|
||||||
|
Ok(RefreshSession {
|
||||||
|
id,
|
||||||
|
user_id: UserId::from_uuid(user_id),
|
||||||
|
token: self.token,
|
||||||
|
expires_at,
|
||||||
|
created_at,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
112
crates/adapters/postgres/src/review.rs
Normal file
112
crates/adapters/postgres/src/review.rs
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
use async_trait::async_trait;
|
||||||
|
use domain::{
|
||||||
|
errors::DomainError,
|
||||||
|
events::DomainEvent,
|
||||||
|
models::{Review, ReviewSource},
|
||||||
|
ports::ReviewRepository,
|
||||||
|
value_objects::{ReviewId, UserId},
|
||||||
|
};
|
||||||
|
use sqlx::PgPool;
|
||||||
|
|
||||||
|
use crate::models::{ReviewRow, datetime_to_str};
|
||||||
|
|
||||||
|
pub struct PostgresReviewRepository {
|
||||||
|
pool: PgPool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PostgresReviewRepository {
|
||||||
|
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 ReviewRepository for PostgresReviewRepository {
|
||||||
|
async fn save_review(&self, review: &Review) -> Result<DomainEvent, DomainError> {
|
||||||
|
let id = review.id().value().to_string();
|
||||||
|
let movie_id = review.movie_id().value().to_string();
|
||||||
|
let user_id = review.user_id().value().to_string();
|
||||||
|
let rating = review.rating().value() as i64;
|
||||||
|
let comment = review.comment().map(|c| c.value().to_string());
|
||||||
|
let watched_at = datetime_to_str(review.watched_at());
|
||||||
|
let created_at = datetime_to_str(review.created_at());
|
||||||
|
let remote_actor_url = match review.source() {
|
||||||
|
ReviewSource::Local => None,
|
||||||
|
ReviewSource::Remote { actor_url } => Some(actor_url.clone()),
|
||||||
|
};
|
||||||
|
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO reviews (id, movie_id, user_id, rating, comment, watched_at, created_at, remote_actor_url)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6::timestamptz, $7::timestamptz, $8)",
|
||||||
|
)
|
||||||
|
.bind(&id)
|
||||||
|
.bind(&movie_id)
|
||||||
|
.bind(&user_id)
|
||||||
|
.bind(rating)
|
||||||
|
.bind(&comment)
|
||||||
|
.bind(&watched_at)
|
||||||
|
.bind(&created_at)
|
||||||
|
.bind(&remote_actor_url)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(Self::map_err)?;
|
||||||
|
|
||||||
|
Ok(DomainEvent::ReviewLogged {
|
||||||
|
review_id: review.id().clone(),
|
||||||
|
movie_id: review.movie_id().clone(),
|
||||||
|
user_id: review.user_id().clone(),
|
||||||
|
rating: review.rating().clone(),
|
||||||
|
watched_at: *review.watched_at(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
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>(
|
||||||
|
"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 id = $1",
|
||||||
|
)
|
||||||
|
.bind(&id)
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(Self::map_err)?
|
||||||
|
.map(ReviewRow::into_domain)
|
||||||
|
.transpose()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn delete_review(&self, review_id: &ReviewId) -> Result<(), DomainError> {
|
||||||
|
let id = review_id.value().to_string();
|
||||||
|
sqlx::query("DELETE FROM reviews WHERE id = $1")
|
||||||
|
.bind(&id)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(Self::map_err)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_all_reviews_for_user(&self, user_id: &UserId) -> Result<Vec<Review>, DomainError> {
|
||||||
|
let uid = user_id.value().to_string();
|
||||||
|
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 user_id = $1 ORDER BY watched_at DESC",
|
||||||
|
)
|
||||||
|
.bind(&uid)
|
||||||
|
.fetch_all(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(Self::map_err)?
|
||||||
|
.into_iter()
|
||||||
|
.map(ReviewRow::into_domain)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
153
crates/adapters/postgres/src/stats.rs
Normal file
153
crates/adapters/postgres/src/stats.rs
Normal file
@@ -0,0 +1,153 @@
|
|||||||
|
use async_trait::async_trait;
|
||||||
|
use domain::{
|
||||||
|
errors::DomainError,
|
||||||
|
models::{DirectorStat, MonthlyRating, UserStats, UserTrends},
|
||||||
|
ports::StatsRepository,
|
||||||
|
value_objects::UserId,
|
||||||
|
};
|
||||||
|
use sqlx::PgPool;
|
||||||
|
|
||||||
|
use crate::format_year_month;
|
||||||
|
use crate::models::{DirectorCountRow, MonthlyRatingRow, UserTotalsRow};
|
||||||
|
|
||||||
|
pub struct PostgresStatsRepository {
|
||||||
|
pool: PgPool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PostgresStatsRepository {
|
||||||
|
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 fetch_user_totals(&self, user_id: &str) -> Result<UserTotalsRow, DomainError> {
|
||||||
|
sqlx::query_as::<_, UserTotalsRow>(
|
||||||
|
r#"SELECT COUNT(DISTINCT movie_id) AS total,
|
||||||
|
AVG(rating::float) AS avg_rating
|
||||||
|
FROM reviews WHERE user_id = $1"#,
|
||||||
|
)
|
||||||
|
.bind(user_id)
|
||||||
|
.fetch_one(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(Self::map_err)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch_user_favorite_director(
|
||||||
|
&self,
|
||||||
|
user_id: &str,
|
||||||
|
) -> Result<Option<String>, DomainError> {
|
||||||
|
sqlx::query_scalar::<_, String>(
|
||||||
|
"SELECT m.director
|
||||||
|
FROM reviews r
|
||||||
|
INNER JOIN movies m ON m.id = r.movie_id
|
||||||
|
WHERE r.user_id = $1 AND m.director IS NOT NULL
|
||||||
|
GROUP BY m.director
|
||||||
|
ORDER BY COUNT(*) DESC
|
||||||
|
LIMIT 1",
|
||||||
|
)
|
||||||
|
.bind(user_id)
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(Self::map_err)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch_user_most_active_month(
|
||||||
|
&self,
|
||||||
|
user_id: &str,
|
||||||
|
) -> Result<Option<String>, DomainError> {
|
||||||
|
sqlx::query_scalar::<_, String>(
|
||||||
|
"SELECT to_char(watched_at AT TIME ZONE 'UTC', 'YYYY-MM') AS month
|
||||||
|
FROM reviews
|
||||||
|
WHERE user_id = $1
|
||||||
|
GROUP BY to_char(watched_at AT TIME ZONE 'UTC', 'YYYY-MM')
|
||||||
|
ORDER BY COUNT(*) DESC
|
||||||
|
LIMIT 1",
|
||||||
|
)
|
||||||
|
.bind(user_id)
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(Self::map_err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl StatsRepository for PostgresStatsRepository {
|
||||||
|
async fn get_user_stats(&self, user_id: &UserId) -> Result<UserStats, DomainError> {
|
||||||
|
let uid = user_id.value().to_string();
|
||||||
|
|
||||||
|
let (totals, fav_director, most_active) = tokio::try_join!(
|
||||||
|
self.fetch_user_totals(&uid),
|
||||||
|
self.fetch_user_favorite_director(&uid),
|
||||||
|
self.fetch_user_most_active_month(&uid)
|
||||||
|
)?;
|
||||||
|
|
||||||
|
let most_active_month = most_active.map(|ym| format_year_month(&ym));
|
||||||
|
|
||||||
|
Ok(UserStats {
|
||||||
|
total_movies: totals.total,
|
||||||
|
avg_rating: totals.avg_rating,
|
||||||
|
favorite_director: fav_director,
|
||||||
|
most_active_month,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_user_trends(&self, user_id: &UserId) -> Result<UserTrends, DomainError> {
|
||||||
|
let uid = user_id.value().to_string();
|
||||||
|
|
||||||
|
let (rating_rows, director_rows) = tokio::try_join!(
|
||||||
|
sqlx::query_as::<_, MonthlyRatingRow>(
|
||||||
|
"SELECT to_char(watched_at AT TIME ZONE 'UTC', 'YYYY-MM') AS month,
|
||||||
|
AVG(rating::float) AS avg_rating,
|
||||||
|
COUNT(*) AS count
|
||||||
|
FROM reviews
|
||||||
|
WHERE user_id = $1 AND watched_at >= NOW() - INTERVAL '12 months'
|
||||||
|
GROUP BY to_char(watched_at AT TIME ZONE 'UTC', 'YYYY-MM')
|
||||||
|
ORDER BY to_char(watched_at AT TIME ZONE 'UTC', 'YYYY-MM') ASC"
|
||||||
|
)
|
||||||
|
.bind(&uid)
|
||||||
|
.fetch_all(&self.pool),
|
||||||
|
sqlx::query_as::<_, DirectorCountRow>(
|
||||||
|
"SELECT m.director AS director, COUNT(*) AS count
|
||||||
|
FROM reviews r
|
||||||
|
INNER JOIN movies m ON m.id = r.movie_id
|
||||||
|
WHERE r.user_id = $1 AND m.director IS NOT NULL
|
||||||
|
GROUP BY m.director
|
||||||
|
ORDER BY COUNT(*) DESC
|
||||||
|
LIMIT 5"
|
||||||
|
)
|
||||||
|
.bind(&uid)
|
||||||
|
.fetch_all(&self.pool)
|
||||||
|
)
|
||||||
|
.map_err(Self::map_err)?;
|
||||||
|
|
||||||
|
let max_director_count = director_rows.iter().map(|d| d.count).max().unwrap_or(1);
|
||||||
|
|
||||||
|
let monthly_ratings = rating_rows
|
||||||
|
.into_iter()
|
||||||
|
.map(|r| MonthlyRating {
|
||||||
|
month_label: format_year_month(&r.month),
|
||||||
|
year_month: r.month,
|
||||||
|
avg_rating: r.avg_rating,
|
||||||
|
count: r.count,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let top_directors = director_rows
|
||||||
|
.into_iter()
|
||||||
|
.map(|d| DirectorStat {
|
||||||
|
director: d.director,
|
||||||
|
count: d.count,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
Ok(UserTrends {
|
||||||
|
monthly_ratings,
|
||||||
|
top_directors,
|
||||||
|
max_director_count,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use domain::{
|
use domain::{
|
||||||
errors::DomainError, models::UserSettings, ports::UserSettingsRepository, value_objects::UserId,
|
errors::DomainError,
|
||||||
|
models::UserSettings,
|
||||||
|
ports::{FederationFlags, UserFederationSettingsQuery, UserSettingsRepository},
|
||||||
|
value_objects::UserId,
|
||||||
};
|
};
|
||||||
use sqlx::{PgPool, Row};
|
use sqlx::{PgPool, Row};
|
||||||
|
|
||||||
@@ -23,20 +26,25 @@ impl PostgresUserSettingsRepository {
|
|||||||
impl UserSettingsRepository for PostgresUserSettingsRepository {
|
impl UserSettingsRepository for PostgresUserSettingsRepository {
|
||||||
async fn get(&self, user_id: &UserId) -> Result<UserSettings, DomainError> {
|
async fn get(&self, user_id: &UserId) -> Result<UserSettings, DomainError> {
|
||||||
let uid = user_id.value().to_string();
|
let uid = user_id.value().to_string();
|
||||||
|
let row = sqlx::query(
|
||||||
let row =
|
"SELECT federate_goals, federate_reviews, federate_watchlist \
|
||||||
sqlx::query("SELECT user_id, federate_goals FROM user_settings WHERE user_id = $1")
|
FROM user_settings WHERE user_id = $1",
|
||||||
.bind(&uid)
|
)
|
||||||
.fetch_optional(&self.pool)
|
.bind(&uid)
|
||||||
.await
|
.fetch_optional(&self.pool)
|
||||||
.map_err(Self::map_err)?;
|
.await
|
||||||
|
.map_err(Self::map_err)?;
|
||||||
|
|
||||||
match row {
|
match row {
|
||||||
Some(r) => {
|
Some(r) => {
|
||||||
let federate: i64 = r.try_get("federate_goals").unwrap_or(0);
|
let goals: bool = r.try_get("federate_goals").unwrap_or(true);
|
||||||
|
let reviews: bool = r.try_get("federate_reviews").unwrap_or(true);
|
||||||
|
let watchlist: bool = r.try_get("federate_watchlist").unwrap_or(true);
|
||||||
Ok(UserSettings::from_persistence(
|
Ok(UserSettings::from_persistence(
|
||||||
user_id.clone(),
|
user_id.clone(),
|
||||||
federate != 0,
|
goals,
|
||||||
|
reviews,
|
||||||
|
watchlist,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
None => Ok(UserSettings::new(user_id.clone())),
|
None => Ok(UserSettings::new(user_id.clone())),
|
||||||
@@ -45,18 +53,52 @@ impl UserSettingsRepository for PostgresUserSettingsRepository {
|
|||||||
|
|
||||||
async fn save(&self, settings: &UserSettings) -> Result<(), DomainError> {
|
async fn save(&self, settings: &UserSettings) -> Result<(), DomainError> {
|
||||||
let uid = settings.user_id().value().to_string();
|
let uid = settings.user_id().value().to_string();
|
||||||
let federate = if settings.federate_goals() { 1i64 } else { 0 };
|
|
||||||
|
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"INSERT INTO user_settings (user_id, federate_goals) VALUES ($1, $2) \
|
"INSERT INTO user_settings (user_id, federate_goals, federate_reviews, federate_watchlist) \
|
||||||
ON CONFLICT (user_id) DO UPDATE SET federate_goals = $2",
|
VALUES ($1, $2, $3, $4) \
|
||||||
|
ON CONFLICT (user_id) DO UPDATE \
|
||||||
|
SET federate_goals = $2, federate_reviews = $3, federate_watchlist = $4",
|
||||||
)
|
)
|
||||||
.bind(&uid)
|
.bind(&uid)
|
||||||
.bind(federate)
|
.bind(settings.federate_goals())
|
||||||
|
.bind(settings.federate_reviews())
|
||||||
|
.bind(settings.federate_watchlist())
|
||||||
.execute(&self.pool)
|
.execute(&self.pool)
|
||||||
.await
|
.await
|
||||||
.map_err(Self::map_err)?;
|
.map_err(Self::map_err)?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl UserFederationSettingsQuery for PostgresUserSettingsRepository {
|
||||||
|
async fn get_federation_flags(&self, user_id: &UserId) -> Result<FederationFlags, DomainError> {
|
||||||
|
let uid = user_id.value().to_string();
|
||||||
|
let row = sqlx::query(
|
||||||
|
"SELECT federate_goals, federate_reviews, federate_watchlist \
|
||||||
|
FROM user_settings WHERE user_id = $1",
|
||||||
|
)
|
||||||
|
.bind(&uid)
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(Self::map_err)?;
|
||||||
|
|
||||||
|
match row {
|
||||||
|
Some(r) => {
|
||||||
|
let goals: bool = r.try_get("federate_goals").unwrap_or(true);
|
||||||
|
let reviews: bool = r.try_get("federate_reviews").unwrap_or(true);
|
||||||
|
let watchlist: bool = r.try_get("federate_watchlist").unwrap_or(true);
|
||||||
|
Ok(FederationFlags {
|
||||||
|
goals,
|
||||||
|
reviews,
|
||||||
|
watchlist,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
None => Ok(FederationFlags {
|
||||||
|
goals: true,
|
||||||
|
reviews: true,
|
||||||
|
watchlist: true,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -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,38 +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 FROM users u\n LEFT JOIN reviews r ON r.user_id = u.id AND r.remote_actor_url IS NULL\n GROUP BY u.id, u.email\n ORDER BY u.email ASC",
|
|
||||||
"describe": {
|
|
||||||
"columns": [
|
|
||||||
{
|
|
||||||
"name": "id!: String",
|
|
||||||
"ordinal": 0,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "email!: String",
|
|
||||||
"ordinal": 1,
|
|
||||||
"type_info": "Text"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "total_movies!: i64",
|
|
||||||
"ordinal": 2,
|
|
||||||
"type_info": "Integer"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "avg_rating",
|
|
||||||
"ordinal": 3,
|
|
||||||
"type_info": "Float"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"parameters": {
|
|
||||||
"Right": 0
|
|
||||||
},
|
|
||||||
"nullable": [
|
|
||||||
true,
|
|
||||||
false,
|
|
||||||
false,
|
|
||||||
true
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"hash": "2c7353f34c4748d4d4be6abbf343fa7ea30eeb985c4bfd12b0fc3997d1ba03bb"
|
|
||||||
}
|
|
||||||
@@ -1,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,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"
|
|
||||||
}
|
|
||||||
@@ -20,3 +20,6 @@ chrono = { workspace = true }
|
|||||||
tracing = { workspace = true }
|
tracing = { workspace = true }
|
||||||
async-trait = { workspace = true }
|
async-trait = { workspace = true }
|
||||||
tokio = { workspace = true }
|
tokio = { workspace = true }
|
||||||
|
futures = { workspace = true }
|
||||||
|
bytes = { workspace = true }
|
||||||
|
async-stream = { workspace = true }
|
||||||
|
|||||||
@@ -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 TEXT;
|
||||||
10
crates/adapters/sqlite/migrations/0027_refresh_sessions.sql
Normal file
10
crates/adapters/sqlite/migrations/0027_refresh_sessions.sql
Normal file
@@ -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 TEXT NOT NULL,
|
||||||
|
created_at TEXT 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;
|
||||||
@@ -5,7 +5,7 @@ use domain::{
|
|||||||
ports::LocalApContentQuery,
|
ports::LocalApContentQuery,
|
||||||
value_objects::{MovieId, ReviewId, UserId},
|
value_objects::{MovieId, ReviewId, UserId},
|
||||||
};
|
};
|
||||||
use sqlx::{Row, SqlitePool};
|
use sqlx::SqlitePool;
|
||||||
|
|
||||||
use crate::models::{DiaryRow, MovieRow, ReviewRow, WatchlistRow};
|
use crate::models::{DiaryRow, MovieRow, ReviewRow, WatchlistRow};
|
||||||
|
|
||||||
@@ -169,23 +169,6 @@ impl LocalApContentQuery for SqliteApContentQuery {
|
|||||||
rows.into_iter().map(DiaryRow::into_domain).collect()
|
rows.into_iter().map(DiaryRow::into_domain).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_user_federate_goals(&self, user_id: &UserId) -> Result<bool, DomainError> {
|
|
||||||
let uid = user_id.value().to_string();
|
|
||||||
let row = sqlx::query("SELECT federate_goals FROM user_settings WHERE user_id = ?")
|
|
||||||
.bind(&uid)
|
|
||||||
.fetch_optional(&self.pool)
|
|
||||||
.await
|
|
||||||
.map_err(Self::map_err)?;
|
|
||||||
|
|
||||||
match row {
|
|
||||||
Some(r) => {
|
|
||||||
let val: i64 = r.try_get("federate_goals").unwrap_or(0);
|
|
||||||
Ok(val != 0)
|
|
||||||
}
|
|
||||||
None => Ok(false),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get_goal_with_progress(
|
async fn get_goal_with_progress(
|
||||||
&self,
|
&self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
|
|||||||
502
crates/adapters/sqlite/src/diary.rs
Normal file
502
crates/adapters/sqlite/src/diary.rs
Normal file
@@ -0,0 +1,502 @@
|
|||||||
|
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::SqlitePool;
|
||||||
|
|
||||||
|
use crate::models::{DiaryRow, FeedRow, MovieRow, MovieStatsRow, ReviewRow};
|
||||||
|
|
||||||
|
pub struct SqliteDiaryRepository {
|
||||||
|
pool: SqlitePool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SqliteDiaryRepository {
|
||||||
|
pub fn new(pool: SqlitePool) -> 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 = ?")
|
||||||
|
.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_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",
|
||||||
|
};
|
||||||
|
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, r.watched_at, r.created_at, r.remote_actor_url
|
||||||
|
FROM reviews r
|
||||||
|
INNER JOIN movies m ON m.id = r.movie_id
|
||||||
|
ORDER BY {}
|
||||||
|
LIMIT ? OFFSET ?",
|
||||||
|
order_clause
|
||||||
|
);
|
||||||
|
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_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",
|
||||||
|
};
|
||||||
|
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, r.watched_at, r.created_at, r.remote_actor_url
|
||||||
|
FROM reviews r
|
||||||
|
INNER JOIN movies m ON m.id = r.movie_id
|
||||||
|
WHERE r.movie_id = ?
|
||||||
|
ORDER BY {}
|
||||||
|
LIMIT ? OFFSET ?",
|
||||||
|
order_clause
|
||||||
|
);
|
||||||
|
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 = ? AND m.title LIKE '%' || ? || '%'"
|
||||||
|
.to_string()
|
||||||
|
} else {
|
||||||
|
"SELECT COUNT(*) FROM reviews r
|
||||||
|
INNER JOIN movies m ON m.id = r.movie_id
|
||||||
|
WHERE r.user_id = ?"
|
||||||
|
.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 search_clause = if has_search {
|
||||||
|
" AND m.title LIKE '%' || ? || '%'"
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
};
|
||||||
|
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",
|
||||||
|
};
|
||||||
|
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, r.watched_at, r.created_at, r.remote_actor_url
|
||||||
|
FROM reviews r
|
||||||
|
INNER JOIN movies m ON m.id = r.movie_id
|
||||||
|
WHERE r.user_id = ?{}
|
||||||
|
ORDER BY {}
|
||||||
|
LIMIT ? OFFSET ?",
|
||||||
|
search_clause, order_clause
|
||||||
|
);
|
||||||
|
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 SqliteDiaryRepository {
|
||||||
|
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);
|
||||||
|
|
||||||
|
let mut where_parts = vec!["1=1".to_string()];
|
||||||
|
|
||||||
|
if has_search {
|
||||||
|
where_parts.push("m.title LIKE '%' || ? || '%'".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(f) = following {
|
||||||
|
let local_in = if f.local_user_ids.is_empty() {
|
||||||
|
"SELECT NULL WHERE 0".to_string()
|
||||||
|
} else {
|
||||||
|
f.local_user_ids
|
||||||
|
.iter()
|
||||||
|
.map(|_| "?")
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(",")
|
||||||
|
};
|
||||||
|
let remote_in = if f.remote_actor_urls.is_empty() {
|
||||||
|
"SELECT NULL WHERE 0".to_string()
|
||||||
|
} else {
|
||||||
|
f.remote_actor_urls
|
||||||
|
.iter()
|
||||||
|
.map(|_| "?")
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(",")
|
||||||
|
};
|
||||||
|
where_parts.push(format!(
|
||||||
|
"(r.user_id IN ({}) OR r.remote_actor_url IN ({}))",
|
||||||
|
local_in, remote_in
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let order_clause = match sort_by {
|
||||||
|
FeedSortBy::Date => "r.watched_at DESC",
|
||||||
|
FeedSortBy::DateAsc => "r.watched_at ASC",
|
||||||
|
FeedSortBy::Rating => "r.rating DESC, r.watched_at DESC",
|
||||||
|
FeedSortBy::RatingAsc => "r.rating ASC, r.watched_at ASC",
|
||||||
|
};
|
||||||
|
|
||||||
|
let where_clause = where_parts.join(" AND ");
|
||||||
|
|
||||||
|
let count_sql = format!(
|
||||||
|
"SELECT COUNT(*) FROM reviews r
|
||||||
|
INNER JOIN movies m ON m.id = r.movie_id
|
||||||
|
WHERE {}",
|
||||||
|
where_clause
|
||||||
|
);
|
||||||
|
|
||||||
|
let select_sql = format!(
|
||||||
|
"SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,
|
||||||
|
r.id AS review_id, r.movie_id, r.user_id, r.rating, r.comment,
|
||||||
|
r.watched_at, r.created_at, r.remote_actor_url,
|
||||||
|
COALESCE(u.email, r.remote_actor_url) AS user_email
|
||||||
|
FROM reviews r
|
||||||
|
INNER JOIN movies m ON m.id = r.movie_id
|
||||||
|
LEFT JOIN users u ON u.id = r.user_id
|
||||||
|
WHERE {}
|
||||||
|
ORDER BY {}
|
||||||
|
LIMIT ? OFFSET ?",
|
||||||
|
where_clause, order_clause
|
||||||
|
);
|
||||||
|
|
||||||
|
macro_rules! bind_filter_params {
|
||||||
|
($q:expr) => {{
|
||||||
|
let mut q = $q;
|
||||||
|
if has_search {
|
||||||
|
q = q.bind(search.unwrap());
|
||||||
|
}
|
||||||
|
if let Some(f) = following {
|
||||||
|
for uid in &f.local_user_ids {
|
||||||
|
q = q.bind(uid.to_string());
|
||||||
|
}
|
||||||
|
for url in &f.remote_actor_urls {
|
||||||
|
q = q.bind(url.as_str());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
q
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
let count_q = bind_filter_params!(sqlx::query_scalar::<_, i64>(&count_sql));
|
||||||
|
let total = count_q.fetch_one(&self.pool).await.map_err(Self::map_err)?;
|
||||||
|
|
||||||
|
let rows_q = bind_filter_params!(sqlx::query_as::<_, FeedRow>(&select_sql));
|
||||||
|
let rows = rows_q
|
||||||
|
.bind(limit)
|
||||||
|
.bind(offset)
|
||||||
|
.fetch_all(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(Self::map_err)?;
|
||||||
|
|
||||||
|
let items = rows
|
||||||
|
.into_iter()
|
||||||
|
.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 = ?",
|
||||||
|
)
|
||||||
|
.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, watched_at, created_at, remote_actor_url
|
||||||
|
FROM reviews WHERE movie_id = ? 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, r.watched_at, r.created_at, r.remote_actor_url
|
||||||
|
FROM reviews r
|
||||||
|
INNER JOIN movies m ON m.id = r.movie_id
|
||||||
|
WHERE r.user_id = ?
|
||||||
|
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, r.watched_at, r.created_at, r.remote_actor_url
|
||||||
|
FROM reviews r
|
||||||
|
INNER JOIN movies m ON m.id = r.movie_id
|
||||||
|
WHERE r.user_id = ?
|
||||||
|
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 REAL)) 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 = ?",
|
||||||
|
)
|
||||||
|
.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::<_, i64>("SELECT COUNT(*) FROM reviews WHERE movie_id = ?")
|
||||||
|
.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,
|
||||||
|
r.watched_at, r.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 = ?
|
||||||
|
ORDER BY r.watched_at DESC
|
||||||
|
LIMIT ? OFFSET ?",
|
||||||
|
)
|
||||||
|
.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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "tests/diary.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -5,6 +5,7 @@ use domain::{
|
|||||||
models::{
|
models::{
|
||||||
AnnotatedRow, FieldMapping, ImportSession, ParsedFile,
|
AnnotatedRow, FieldMapping, ImportSession, ParsedFile,
|
||||||
import::{DomainField, ImportRow, RowResult, Transform},
|
import::{DomainField, ImportRow, RowResult, Transform},
|
||||||
|
import_session::PersistedImportSession,
|
||||||
},
|
},
|
||||||
ports::ImportSessionRepository,
|
ports::ImportSessionRepository,
|
||||||
value_objects::{ImportSessionId, UserId},
|
value_objects::{ImportSessionId, UserId},
|
||||||
@@ -275,7 +276,7 @@ impl SqliteImportSessionRepository {
|
|||||||
})
|
})
|
||||||
.transpose()?;
|
.transpose()?;
|
||||||
|
|
||||||
Ok(ImportSession {
|
Ok(ImportSession::from_persistence(PersistedImportSession {
|
||||||
id: ImportSessionId::from_uuid(
|
id: ImportSessionId::from_uuid(
|
||||||
id.parse::<uuid::Uuid>()
|
id.parse::<uuid::Uuid>()
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?,
|
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?,
|
||||||
@@ -290,7 +291,7 @@ impl SqliteImportSessionRepository {
|
|||||||
row_results,
|
row_results,
|
||||||
created_at: Self::parse_dt(created_at)?,
|
created_at: Self::parse_dt(created_at)?,
|
||||||
expires_at: Self::parse_dt(expires_at)?,
|
expires_at: Self::parse_dt(expires_at)?,
|
||||||
})
|
}))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
251
crates/adapters/sqlite/src/movie.rs
Normal file
251
crates/adapters/sqlite/src/movie.rs
Normal file
@@ -0,0 +1,251 @@
|
|||||||
|
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::SqlitePool;
|
||||||
|
|
||||||
|
use crate::models::{MovieRow, MovieSummaryRow};
|
||||||
|
|
||||||
|
pub struct SqliteMovieRepository {
|
||||||
|
pool: SqlitePool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SqliteMovieRepository {
|
||||||
|
pub fn new(pool: SqlitePool) -> 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 SqliteMovieRepository {
|
||||||
|
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 = ?",
|
||||||
|
)
|
||||||
|
.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 = ?",
|
||||||
|
)
|
||||||
|
.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 t = title.value();
|
||||||
|
let y = year.value() as i64;
|
||||||
|
sqlx::query_as::<_, MovieRow>(
|
||||||
|
"SELECT id, external_metadata_id, title, release_year, director, poster_path
|
||||||
|
FROM movies WHERE title = ? AND release_year = ?",
|
||||||
|
)
|
||||||
|
.bind(t)
|
||||||
|
.bind(y)
|
||||||
|
.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 (?, ?, ?, ?, ?, ?)
|
||||||
|
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 = ?")
|
||||||
|
.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 placeholders: Vec<&str> = ids.iter().map(|_| "?").collect();
|
||||||
|
let sql = format!(
|
||||||
|
"SELECT external_metadata_id FROM movies WHERE external_metadata_id IN ({})",
|
||||||
|
placeholders.join(",")
|
||||||
|
);
|
||||||
|
let mut q = sqlx::query_scalar::<_, String>(&sql);
|
||||||
|
for id in ids {
|
||||||
|
q = q.bind(id.value().to_string());
|
||||||
|
}
|
||||||
|
let rows = q.fetch_all(&self.pool).await.map_err(Self::map_err)?;
|
||||||
|
Ok(rows.into_iter().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 conditions: Vec<String> = pairs
|
||||||
|
.iter()
|
||||||
|
.map(|_| "(title = ? AND release_year = ?)".to_string())
|
||||||
|
.collect();
|
||||||
|
let sql = format!(
|
||||||
|
"SELECT DISTINCT title, release_year FROM movies WHERE {}",
|
||||||
|
conditions.join(" OR ")
|
||||||
|
);
|
||||||
|
use sqlx::Row;
|
||||||
|
let mut q = sqlx::query(&sql);
|
||||||
|
for (t, y) in pairs {
|
||||||
|
q = q.bind(t.value().to_string()).bind(y.value() as i64);
|
||||||
|
}
|
||||||
|
let rows = q.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, \
|
||||||
|
GROUP_CONCAT(g.name) 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 (? IS NULL OR LOWER(m.title) LIKE ?) \
|
||||||
|
AND (? IS NULL OR p.original_language = ?) \
|
||||||
|
AND (? IS NULL OR m.id IN (SELECT movie_id FROM movie_genres WHERE LOWER(name) = LOWER(?))) \
|
||||||
|
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 ? OFFSET ?",
|
||||||
|
)
|
||||||
|
.bind(&pattern)
|
||||||
|
.bind(&pattern)
|
||||||
|
.bind(language)
|
||||||
|
.bind(language)
|
||||||
|
.bind(genre)
|
||||||
|
.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 (? IS NULL OR LOWER(m.title) LIKE ?) \
|
||||||
|
AND (? IS NULL OR p.original_language = ?) \
|
||||||
|
AND (? IS NULL OR m.id IN (SELECT movie_id FROM movie_genres WHERE LOWER(name) = LOWER(?)))",
|
||||||
|
)
|
||||||
|
.bind(&pattern)
|
||||||
|
.bind(&pattern)
|
||||||
|
.bind(language)
|
||||||
|
.bind(language)
|
||||||
|
.bind(genre)
|
||||||
|
.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,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use domain::{
|
use domain::{
|
||||||
errors::DomainError,
|
errors::DomainError,
|
||||||
models::{CastCredit, CrewCredit, ExternalPersonId, Person, PersonCredits, PersonId},
|
models::{
|
||||||
|
CastCredit, CrewCredit, ExternalPersonId, Person, PersonCredits, PersonEnrichmentData,
|
||||||
|
PersonId,
|
||||||
|
},
|
||||||
ports::{PersonCommand, PersonQuery},
|
ports::{PersonCommand, PersonQuery},
|
||||||
value_objects::MovieId,
|
value_objects::MovieId,
|
||||||
};
|
};
|
||||||
@@ -111,13 +114,39 @@ impl PersonCommand for SqlitePersonAdapter {
|
|||||||
}
|
}
|
||||||
Ok((count, has_more))
|
Ok((count, has_more))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn update_enrichment(
|
||||||
|
&self,
|
||||||
|
id: &PersonId,
|
||||||
|
data: &PersonEnrichmentData,
|
||||||
|
) -> Result<(), DomainError> {
|
||||||
|
let also_known_as_json =
|
||||||
|
serde_json::to_string(&data.also_known_as).unwrap_or_else(|_| "[]".into());
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE persons SET biography = ?, birthday = ?, deathday = ?, place_of_birth = ?, also_known_as = ?, homepage = ?, imdb_id = ?, enriched_at = ? WHERE id = ?",
|
||||||
|
)
|
||||||
|
.bind(&data.biography)
|
||||||
|
.bind(data.birthday.map(|d| d.to_string()))
|
||||||
|
.bind(data.deathday.map(|d| d.to_string()))
|
||||||
|
.bind(&data.place_of_birth)
|
||||||
|
.bind(&also_known_as_json)
|
||||||
|
.bind(&data.homepage)
|
||||||
|
.bind(&data.imdb_id)
|
||||||
|
.bind(&now)
|
||||||
|
.bind(id.value().to_string())
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(map_err)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl PersonQuery for SqlitePersonAdapter {
|
impl PersonQuery for SqlitePersonAdapter {
|
||||||
async fn get_by_id(&self, id: &PersonId) -> Result<Option<Person>, DomainError> {
|
async fn get_by_id(&self, id: &PersonId) -> Result<Option<Person>, DomainError> {
|
||||||
let row = sqlx::query_as::<_, PersonRow>(
|
let row = sqlx::query_as::<_, PersonRow>(
|
||||||
"SELECT id, external_id, name, known_for_department, profile_path FROM persons WHERE id = ?",
|
"SELECT id, external_id, name, known_for_department, profile_path, biography, birthday, deathday, place_of_birth, also_known_as, homepage, imdb_id, enriched_at FROM persons WHERE id = ?",
|
||||||
)
|
)
|
||||||
.bind(id.value().to_string())
|
.bind(id.value().to_string())
|
||||||
.fetch_optional(&self.pool)
|
.fetch_optional(&self.pool)
|
||||||
@@ -132,7 +161,7 @@ impl PersonQuery for SqlitePersonAdapter {
|
|||||||
id: &ExternalPersonId,
|
id: &ExternalPersonId,
|
||||||
) -> Result<Option<Person>, DomainError> {
|
) -> Result<Option<Person>, DomainError> {
|
||||||
let row = sqlx::query_as::<_, PersonRow>(
|
let row = sqlx::query_as::<_, PersonRow>(
|
||||||
"SELECT id, external_id, name, known_for_department, profile_path FROM persons WHERE external_id = ?",
|
"SELECT id, external_id, name, known_for_department, profile_path, biography, birthday, deathday, place_of_birth, also_known_as, homepage, imdb_id, enriched_at FROM persons WHERE external_id = ?",
|
||||||
)
|
)
|
||||||
.bind(id.value())
|
.bind(id.value())
|
||||||
.fetch_optional(&self.pool)
|
.fetch_optional(&self.pool)
|
||||||
@@ -212,7 +241,7 @@ impl PersonQuery for SqlitePersonAdapter {
|
|||||||
|
|
||||||
async fn list_page(&self, limit: u32, offset: u32) -> Result<Vec<Person>, DomainError> {
|
async fn list_page(&self, limit: u32, offset: u32) -> Result<Vec<Person>, DomainError> {
|
||||||
let rows = sqlx::query_as::<_, PersonRow>(
|
let rows = sqlx::query_as::<_, PersonRow>(
|
||||||
"SELECT id, external_id, name, known_for_department, profile_path FROM persons ORDER BY id LIMIT ? OFFSET ?",
|
"SELECT id, external_id, name, known_for_department, profile_path, biography, birthday, deathday, place_of_birth, also_known_as, homepage, imdb_id, enriched_at FROM persons ORDER BY id LIMIT ? OFFSET ?",
|
||||||
)
|
)
|
||||||
.bind(limit)
|
.bind(limit)
|
||||||
.bind(offset)
|
.bind(offset)
|
||||||
@@ -254,17 +283,47 @@ struct PersonRow {
|
|||||||
name: String,
|
name: String,
|
||||||
known_for_department: Option<String>,
|
known_for_department: Option<String>,
|
||||||
profile_path: Option<String>,
|
profile_path: Option<String>,
|
||||||
|
biography: Option<String>,
|
||||||
|
birthday: Option<String>,
|
||||||
|
deathday: Option<String>,
|
||||||
|
place_of_birth: Option<String>,
|
||||||
|
also_known_as: Option<String>,
|
||||||
|
homepage: Option<String>,
|
||||||
|
imdb_id: Option<String>,
|
||||||
|
enriched_at: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PersonRow {
|
impl PersonRow {
|
||||||
fn into_person(self) -> Person {
|
fn into_person(self) -> Person {
|
||||||
let ext = ExternalPersonId::new(self.external_id);
|
let ext = ExternalPersonId::new(self.external_id);
|
||||||
|
let also_known_as = self
|
||||||
|
.also_known_as
|
||||||
|
.and_then(|s| serde_json::from_str::<Vec<String>>(&s).ok())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let birthday = self
|
||||||
|
.birthday
|
||||||
|
.and_then(|s| chrono::NaiveDate::parse_from_str(&s, "%Y-%m-%d").ok());
|
||||||
|
let deathday = self
|
||||||
|
.deathday
|
||||||
|
.and_then(|s| chrono::NaiveDate::parse_from_str(&s, "%Y-%m-%d").ok());
|
||||||
|
let enriched_at = self
|
||||||
|
.enriched_at
|
||||||
|
.and_then(|s| chrono::DateTime::parse_from_rfc3339(&s).ok())
|
||||||
|
.map(|d| d.with_timezone(&chrono::Utc));
|
||||||
Person::new(
|
Person::new(
|
||||||
PersonId::from_uuid(uuid::Uuid::parse_str(&self.id).unwrap_or_default()),
|
PersonId::from_uuid(uuid::Uuid::parse_str(&self.id).unwrap_or_default()),
|
||||||
ext,
|
ext,
|
||||||
self.name,
|
self.name,
|
||||||
self.known_for_department,
|
self.known_for_department,
|
||||||
self.profile_path,
|
self.profile_path,
|
||||||
|
self.biography,
|
||||||
|
birthday,
|
||||||
|
deathday,
|
||||||
|
self.place_of_birth,
|
||||||
|
also_known_as,
|
||||||
|
self.homepage,
|
||||||
|
self.imdb_id,
|
||||||
|
enriched_at,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
111
crates/adapters/sqlite/src/refresh_sessions.rs
Normal file
111
crates/adapters/sqlite/src/refresh_sessions.rs
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
use async_trait::async_trait;
|
||||||
|
use chrono::DateTime;
|
||||||
|
use domain::{
|
||||||
|
errors::DomainError, models::RefreshSession, ports::RefreshSessionRepository,
|
||||||
|
value_objects::UserId,
|
||||||
|
};
|
||||||
|
use sqlx::SqlitePool;
|
||||||
|
|
||||||
|
pub struct SqliteRefreshSessionAdapter {
|
||||||
|
pool: SqlitePool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SqliteRefreshSessionAdapter {
|
||||||
|
pub fn new(pool: SqlitePool) -> Self {
|
||||||
|
Self { pool }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn map_err(e: sqlx::Error) -> DomainError {
|
||||||
|
DomainError::InfrastructureError(e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl RefreshSessionRepository for SqliteRefreshSessionAdapter {
|
||||||
|
async fn create(&self, session: &RefreshSession) -> Result<(), DomainError> {
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO refresh_sessions (id, user_id, token, expires_at, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?)",
|
||||||
|
)
|
||||||
|
.bind(session.id.to_string())
|
||||||
|
.bind(session.user_id.value().to_string())
|
||||||
|
.bind(&session.token)
|
||||||
|
.bind(session.expires_at.to_rfc3339())
|
||||||
|
.bind(session.created_at.to_rfc3339())
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(map_err)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_by_token(&self, token: &str) -> Result<Option<RefreshSession>, DomainError> {
|
||||||
|
let row = sqlx::query_as::<_, RefreshSessionRow>(
|
||||||
|
"SELECT id, user_id, token, expires_at, created_at FROM refresh_sessions WHERE token = ?",
|
||||||
|
)
|
||||||
|
.bind(token)
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(map_err)?;
|
||||||
|
|
||||||
|
row.map(RefreshSessionRow::into_domain).transpose()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn revoke(&self, token: &str) -> Result<(), DomainError> {
|
||||||
|
sqlx::query("DELETE FROM refresh_sessions WHERE token = ?")
|
||||||
|
.bind(token)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(map_err)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn revoke_all_for_user(&self, user_id: &UserId) -> Result<(), DomainError> {
|
||||||
|
sqlx::query("DELETE FROM refresh_sessions WHERE user_id = ?")
|
||||||
|
.bind(user_id.value().to_string())
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(map_err)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn delete_expired(&self) -> Result<u64, DomainError> {
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
let result = sqlx::query("DELETE FROM refresh_sessions WHERE expires_at < ?")
|
||||||
|
.bind(&now)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(map_err)?;
|
||||||
|
Ok(result.rows_affected())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(sqlx::FromRow)]
|
||||||
|
struct RefreshSessionRow {
|
||||||
|
id: String,
|
||||||
|
user_id: String,
|
||||||
|
token: String,
|
||||||
|
expires_at: String,
|
||||||
|
created_at: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RefreshSessionRow {
|
||||||
|
fn into_domain(self) -> Result<RefreshSession, DomainError> {
|
||||||
|
let id = uuid::Uuid::parse_str(&self.id)
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(format!("invalid uuid: {e}")))?;
|
||||||
|
let user_id = uuid::Uuid::parse_str(&self.user_id)
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(format!("invalid user_id: {e}")))?;
|
||||||
|
let expires_at = DateTime::parse_from_rfc3339(&self.expires_at)
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(format!("invalid expires_at: {e}")))?
|
||||||
|
.with_timezone(&chrono::Utc);
|
||||||
|
let created_at = DateTime::parse_from_rfc3339(&self.created_at)
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(format!("invalid created_at: {e}")))?
|
||||||
|
.with_timezone(&chrono::Utc);
|
||||||
|
Ok(RefreshSession {
|
||||||
|
id,
|
||||||
|
user_id: UserId::from_uuid(user_id),
|
||||||
|
token: self.token,
|
||||||
|
expires_at,
|
||||||
|
created_at,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
106
crates/adapters/sqlite/src/review.rs
Normal file
106
crates/adapters/sqlite/src/review.rs
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
use async_trait::async_trait;
|
||||||
|
use domain::{
|
||||||
|
errors::DomainError,
|
||||||
|
events::DomainEvent,
|
||||||
|
models::{Review, ReviewSource},
|
||||||
|
ports::ReviewRepository,
|
||||||
|
value_objects::{ReviewId, UserId},
|
||||||
|
};
|
||||||
|
use sqlx::SqlitePool;
|
||||||
|
|
||||||
|
use crate::models::{ReviewRow, datetime_to_str};
|
||||||
|
|
||||||
|
pub struct SqliteReviewRepository {
|
||||||
|
pool: SqlitePool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SqliteReviewRepository {
|
||||||
|
pub fn new(pool: SqlitePool) -> Self {
|
||||||
|
Self { pool }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn map_err(e: sqlx::Error) -> DomainError {
|
||||||
|
tracing::error!("Database error: {:?}", e);
|
||||||
|
DomainError::InfrastructureError("Database operation failed".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl ReviewRepository for SqliteReviewRepository {
|
||||||
|
async fn save_review(&self, review: &Review) -> Result<DomainEvent, DomainError> {
|
||||||
|
let id = review.id().value().to_string();
|
||||||
|
let movie_id = review.movie_id().value().to_string();
|
||||||
|
let user_id = review.user_id().value().to_string();
|
||||||
|
let rating = review.rating().value() as i64;
|
||||||
|
let comment = review.comment().map(|c| c.value().to_string());
|
||||||
|
let watched_at = datetime_to_str(review.watched_at());
|
||||||
|
let created_at = datetime_to_str(review.created_at());
|
||||||
|
let remote_actor_url = match review.source() {
|
||||||
|
ReviewSource::Local => None,
|
||||||
|
ReviewSource::Remote { actor_url } => Some(actor_url.clone()),
|
||||||
|
};
|
||||||
|
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO reviews (id, movie_id, user_id, rating, comment, watched_at, created_at, remote_actor_url)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||||
|
)
|
||||||
|
.bind(&id)
|
||||||
|
.bind(&movie_id)
|
||||||
|
.bind(&user_id)
|
||||||
|
.bind(rating)
|
||||||
|
.bind(&comment)
|
||||||
|
.bind(&watched_at)
|
||||||
|
.bind(&created_at)
|
||||||
|
.bind(&remote_actor_url)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(Self::map_err)?;
|
||||||
|
|
||||||
|
Ok(DomainEvent::ReviewLogged {
|
||||||
|
review_id: review.id().clone(),
|
||||||
|
movie_id: review.movie_id().clone(),
|
||||||
|
user_id: review.user_id().clone(),
|
||||||
|
rating: review.rating().clone(),
|
||||||
|
watched_at: *review.watched_at(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
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>(
|
||||||
|
"SELECT id, movie_id, user_id, rating, comment, watched_at, created_at, remote_actor_url
|
||||||
|
FROM reviews WHERE id = ?",
|
||||||
|
)
|
||||||
|
.bind(&id)
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(Self::map_err)?
|
||||||
|
.map(ReviewRow::into_domain)
|
||||||
|
.transpose()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn delete_review(&self, review_id: &ReviewId) -> Result<(), DomainError> {
|
||||||
|
let id = review_id.value().to_string();
|
||||||
|
sqlx::query("DELETE FROM reviews WHERE id = ?")
|
||||||
|
.bind(&id)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(Self::map_err)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_all_reviews_for_user(&self, user_id: &UserId) -> Result<Vec<Review>, DomainError> {
|
||||||
|
let uid = user_id.value().to_string();
|
||||||
|
sqlx::query_as::<_, ReviewRow>(
|
||||||
|
"SELECT id, movie_id, user_id, rating, comment, watched_at, created_at, remote_actor_url
|
||||||
|
FROM reviews WHERE user_id = ? ORDER BY watched_at DESC",
|
||||||
|
)
|
||||||
|
.bind(&uid)
|
||||||
|
.fetch_all(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(Self::map_err)?
|
||||||
|
.into_iter()
|
||||||
|
.map(ReviewRow::into_domain)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
155
crates/adapters/sqlite/src/stats.rs
Normal file
155
crates/adapters/sqlite/src/stats.rs
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
use async_trait::async_trait;
|
||||||
|
use domain::{
|
||||||
|
errors::DomainError,
|
||||||
|
models::{DirectorStat, MonthlyRating, UserStats, UserTrends},
|
||||||
|
ports::StatsRepository,
|
||||||
|
value_objects::UserId,
|
||||||
|
};
|
||||||
|
use sqlx::SqlitePool;
|
||||||
|
|
||||||
|
use crate::models::{DirectorCountRow, MonthlyRatingRow, UserTotalsRow};
|
||||||
|
|
||||||
|
pub struct SqliteStatsRepository {
|
||||||
|
pool: SqlitePool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SqliteStatsRepository {
|
||||||
|
pub fn new(pool: SqlitePool) -> Self {
|
||||||
|
Self { pool }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn map_err(e: sqlx::Error) -> DomainError {
|
||||||
|
tracing::error!("Database error: {:?}", e);
|
||||||
|
DomainError::InfrastructureError("Database operation failed".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch_user_totals(&self, user_id: &str) -> Result<UserTotalsRow, DomainError> {
|
||||||
|
sqlx::query_as::<_, UserTotalsRow>(
|
||||||
|
"SELECT COUNT(DISTINCT movie_id) AS total,
|
||||||
|
AVG(CAST(rating AS REAL)) AS avg_rating
|
||||||
|
FROM reviews WHERE user_id = ?",
|
||||||
|
)
|
||||||
|
.bind(user_id)
|
||||||
|
.fetch_one(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(Self::map_err)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch_user_favorite_director(
|
||||||
|
&self,
|
||||||
|
user_id: &str,
|
||||||
|
) -> Result<Option<String>, DomainError> {
|
||||||
|
let row: Option<String> = sqlx::query_scalar(
|
||||||
|
"SELECT m.director
|
||||||
|
FROM reviews r
|
||||||
|
INNER JOIN movies m ON m.id = r.movie_id
|
||||||
|
WHERE r.user_id = ? AND m.director IS NOT NULL
|
||||||
|
GROUP BY m.director
|
||||||
|
ORDER BY COUNT(*) DESC
|
||||||
|
LIMIT 1",
|
||||||
|
)
|
||||||
|
.bind(user_id)
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(Self::map_err)?;
|
||||||
|
Ok(row)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch_user_most_active_month(
|
||||||
|
&self,
|
||||||
|
user_id: &str,
|
||||||
|
) -> Result<Option<String>, DomainError> {
|
||||||
|
let row: Option<String> = sqlx::query_scalar(
|
||||||
|
"SELECT strftime('%Y-%m', watched_at)
|
||||||
|
FROM reviews
|
||||||
|
WHERE user_id = ?
|
||||||
|
GROUP BY strftime('%Y-%m', watched_at)
|
||||||
|
ORDER BY COUNT(*) DESC
|
||||||
|
LIMIT 1",
|
||||||
|
)
|
||||||
|
.bind(user_id)
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(Self::map_err)?;
|
||||||
|
Ok(row)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl StatsRepository for SqliteStatsRepository {
|
||||||
|
async fn get_user_stats(&self, user_id: &UserId) -> Result<UserStats, DomainError> {
|
||||||
|
let uid = user_id.value().to_string();
|
||||||
|
|
||||||
|
let (totals, fav_director, most_active) = tokio::try_join!(
|
||||||
|
self.fetch_user_totals(&uid),
|
||||||
|
self.fetch_user_favorite_director(&uid),
|
||||||
|
self.fetch_user_most_active_month(&uid)
|
||||||
|
)?;
|
||||||
|
|
||||||
|
let most_active_month = most_active.map(|ym| crate::format_year_month(&ym));
|
||||||
|
|
||||||
|
Ok(UserStats {
|
||||||
|
total_movies: totals.total,
|
||||||
|
avg_rating: totals.avg_rating,
|
||||||
|
favorite_director: fav_director,
|
||||||
|
most_active_month,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_user_trends(&self, user_id: &UserId) -> Result<UserTrends, DomainError> {
|
||||||
|
let uid = user_id.value().to_string();
|
||||||
|
|
||||||
|
let (rating_rows, director_rows) = tokio::try_join!(
|
||||||
|
sqlx::query_as::<_, MonthlyRatingRow>(
|
||||||
|
"SELECT strftime('%Y-%m', watched_at) AS month,
|
||||||
|
AVG(CAST(rating AS REAL)) AS avg_rating,
|
||||||
|
COUNT(*) AS count
|
||||||
|
FROM reviews
|
||||||
|
WHERE user_id = ? AND watched_at >= datetime('now', '-12 months')
|
||||||
|
GROUP BY month
|
||||||
|
ORDER BY month ASC",
|
||||||
|
)
|
||||||
|
.bind(&uid)
|
||||||
|
.fetch_all(&self.pool),
|
||||||
|
sqlx::query_as::<_, DirectorCountRow>(
|
||||||
|
"SELECT m.director,
|
||||||
|
COUNT(*) AS count
|
||||||
|
FROM reviews r
|
||||||
|
INNER JOIN movies m ON m.id = r.movie_id
|
||||||
|
WHERE r.user_id = ? AND m.director IS NOT NULL
|
||||||
|
GROUP BY m.director
|
||||||
|
ORDER BY COUNT(*) DESC
|
||||||
|
LIMIT 5",
|
||||||
|
)
|
||||||
|
.bind(&uid)
|
||||||
|
.fetch_all(&self.pool)
|
||||||
|
)
|
||||||
|
.map_err(Self::map_err)?;
|
||||||
|
|
||||||
|
let max_director_count = director_rows.iter().map(|d| d.count).max().unwrap_or(1);
|
||||||
|
|
||||||
|
let monthly_ratings = rating_rows
|
||||||
|
.into_iter()
|
||||||
|
.map(|r| MonthlyRating {
|
||||||
|
month_label: crate::format_year_month(&r.month),
|
||||||
|
year_month: r.month,
|
||||||
|
avg_rating: r.avg_rating,
|
||||||
|
count: r.count,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let top_directors = director_rows
|
||||||
|
.into_iter()
|
||||||
|
.map(|d| DirectorStat {
|
||||||
|
director: d.director,
|
||||||
|
count: d.count,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
Ok(UserTrends {
|
||||||
|
monthly_ratings,
|
||||||
|
top_directors,
|
||||||
|
max_director_count,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
213
crates/adapters/sqlite/src/tests/diary.rs
Normal file
213
crates/adapters/sqlite/src/tests/diary.rs
Normal file
@@ -0,0 +1,213 @@
|
|||||||
|
use super::*;
|
||||||
|
use domain::{
|
||||||
|
models::collections::PageParams,
|
||||||
|
ports::{DiaryRepository, FeedSortBy, FollowingFilter},
|
||||||
|
};
|
||||||
|
use sqlx::SqlitePool;
|
||||||
|
|
||||||
|
async fn setup(pool: &SqlitePool) {
|
||||||
|
sqlx::migrate!("./migrations").run(pool).await.unwrap();
|
||||||
|
|
||||||
|
// carol is a remote actor; we still need a non-null user_id for the schema,
|
||||||
|
// so we create a local "ghost" user and link the remote review via remote_actor_url.
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO users (id, email, username, password_hash, created_at) VALUES
|
||||||
|
('11111111-1111-1111-1111-111111111111', 'alice@example.com', 'alice', 'hash', '2024-01-01 00:00:00'),
|
||||||
|
('22222222-2222-2222-2222-222222222222', 'bob@example.com', 'bob', 'hash', '2024-01-01 00:00:00'),
|
||||||
|
('33333333-3333-3333-3333-333333333333', 'carol@remote.social', 'carol', 'hash', '2024-01-01 00:00:00')",
|
||||||
|
)
|
||||||
|
.execute(pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO movies (id, title, release_year) VALUES
|
||||||
|
('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Inception', 2010),
|
||||||
|
('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'Interstellar', 2014),
|
||||||
|
('cccccccc-cccc-cccc-cccc-cccccccccccc', 'Dune', 2021)",
|
||||||
|
)
|
||||||
|
.execute(pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// carol's review: local user_id=33333333, remote_actor_url set → remote review
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO reviews (id, movie_id, user_id, rating, watched_at, created_at, remote_actor_url) VALUES
|
||||||
|
('a1a1a1a1-a1a1-a1a1-a1a1-a1a1a1a1a1a1', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '11111111-1111-1111-1111-111111111111', 5, '2024-01-01 00:00:00', '2024-01-01 00:00:00', NULL),
|
||||||
|
('b2b2b2b2-b2b2-b2b2-b2b2-b2b2b2b2b2b2', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', '22222222-2222-2222-2222-222222222222', 3, '2024-01-02 00:00:00', '2024-01-02 00:00:00', NULL),
|
||||||
|
('c3c3c3c3-c3c3-c3c3-c3c3-c3c3c3c3c3c3', 'cccccccc-cccc-cccc-cccc-cccccccccccc', '33333333-3333-3333-3333-333333333333', 4, '2024-01-03 00:00:00', '2024-01-03 00:00:00', 'https://remote.social/users/carol')",
|
||||||
|
)
|
||||||
|
.execute(pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_sort_by_rating_descending() {
|
||||||
|
let pool = SqlitePool::connect(":memory:").await.unwrap();
|
||||||
|
setup(&pool).await;
|
||||||
|
let repo = SqliteDiaryRepository::new(pool);
|
||||||
|
|
||||||
|
let page = PageParams::new(Some(10), Some(0)).unwrap();
|
||||||
|
let result = repo
|
||||||
|
.query_activity_feed_filtered(&page, &FeedSortBy::Rating, None, None)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let ratings: Vec<u8> = result
|
||||||
|
.items
|
||||||
|
.iter()
|
||||||
|
.map(|e| e.review().rating().value())
|
||||||
|
.collect();
|
||||||
|
assert_eq!(ratings, vec![5, 4, 3]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_search_by_title() {
|
||||||
|
let pool = SqlitePool::connect(":memory:").await.unwrap();
|
||||||
|
setup(&pool).await;
|
||||||
|
let repo = SqliteDiaryRepository::new(pool);
|
||||||
|
|
||||||
|
let page = PageParams::new(Some(10), Some(0)).unwrap();
|
||||||
|
let result = repo
|
||||||
|
.query_activity_feed_filtered(&page, &FeedSortBy::Date, Some("Dune"), None)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(result.items.len(), 1);
|
||||||
|
assert_eq!(result.items[0].movie().title().value(), "Dune");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_following_filter() {
|
||||||
|
let pool = SqlitePool::connect(":memory:").await.unwrap();
|
||||||
|
setup(&pool).await;
|
||||||
|
let repo = SqliteDiaryRepository::new(pool);
|
||||||
|
|
||||||
|
let filter = FollowingFilter {
|
||||||
|
local_user_ids: vec![
|
||||||
|
uuid::Uuid::parse_str("11111111-1111-1111-1111-111111111111").unwrap(),
|
||||||
|
],
|
||||||
|
remote_actor_urls: vec!["https://remote.social/users/carol".to_string()],
|
||||||
|
};
|
||||||
|
let page = PageParams::new(Some(10), Some(0)).unwrap();
|
||||||
|
let result = repo
|
||||||
|
.query_activity_feed_filtered(&page, &FeedSortBy::Date, None, Some(&filter))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(result.items.len(), 2); // alice + carol, NOT bob
|
||||||
|
let titles: Vec<String> = result
|
||||||
|
.items
|
||||||
|
.iter()
|
||||||
|
.map(|e| e.movie().title().value().to_string())
|
||||||
|
.collect();
|
||||||
|
assert!(titles.contains(&"Inception".to_string()));
|
||||||
|
assert!(titles.contains(&"Dune".to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_get_movie_stats_local() {
|
||||||
|
let pool = SqlitePool::connect(":memory:").await.unwrap();
|
||||||
|
setup(&pool).await;
|
||||||
|
let repo = SqliteDiaryRepository::new(pool);
|
||||||
|
|
||||||
|
// Inception: 1 local review, rating=5, no federated
|
||||||
|
let movie_id = domain::value_objects::MovieId::from_uuid(
|
||||||
|
uuid::Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap(),
|
||||||
|
);
|
||||||
|
let stats = repo.get_movie_stats(&movie_id).await.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(stats.total_count, 1);
|
||||||
|
assert_eq!(stats.federated_count, 0);
|
||||||
|
assert!((stats.avg_rating.unwrap() - 5.0).abs() < 0.001);
|
||||||
|
assert_eq!(stats.rating_histogram[4], 1); // 5★ bucket
|
||||||
|
assert_eq!(stats.rating_histogram[0], 0); // 1★ bucket
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_get_movie_social_feed_returns_reviews_for_movie() {
|
||||||
|
let pool = SqlitePool::connect(":memory:").await.unwrap();
|
||||||
|
setup(&pool).await;
|
||||||
|
let repo = SqliteDiaryRepository::new(pool);
|
||||||
|
|
||||||
|
let movie_id = domain::value_objects::MovieId::from_uuid(
|
||||||
|
uuid::Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap(),
|
||||||
|
);
|
||||||
|
let page = PageParams::new(Some(10), Some(0)).unwrap();
|
||||||
|
let result = repo.get_movie_social_feed(&movie_id, &page).await.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(result.total_count, 1);
|
||||||
|
assert_eq!(result.items.len(), 1);
|
||||||
|
assert_eq!(result.items[0].movie().title().value(), "Inception");
|
||||||
|
assert_eq!(result.items[0].review().rating().value(), 5);
|
||||||
|
assert_eq!(result.items[0].user_display_name(), "alice");
|
||||||
|
assert!(!result.items[0].review().is_remote());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_get_movie_social_feed_federated_review() {
|
||||||
|
let pool = SqlitePool::connect(":memory:").await.unwrap();
|
||||||
|
setup(&pool).await;
|
||||||
|
let repo = SqliteDiaryRepository::new(pool);
|
||||||
|
|
||||||
|
let movie_id = domain::value_objects::MovieId::from_uuid(
|
||||||
|
uuid::Uuid::parse_str("cccccccc-cccc-cccc-cccc-cccccccccccc").unwrap(),
|
||||||
|
);
|
||||||
|
let page = PageParams::new(Some(10), Some(0)).unwrap();
|
||||||
|
let result = repo.get_movie_social_feed(&movie_id, &page).await.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(result.total_count, 1);
|
||||||
|
assert_eq!(result.items.len(), 1);
|
||||||
|
assert!(result.items[0].review().is_remote());
|
||||||
|
assert_eq!(
|
||||||
|
result.items[0].user_email(),
|
||||||
|
"https://remote.social/users/carol"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_get_movie_social_feed_pagination() {
|
||||||
|
let pool = SqlitePool::connect(":memory:").await.unwrap();
|
||||||
|
setup(&pool).await;
|
||||||
|
let repo = SqliteDiaryRepository::new(pool);
|
||||||
|
|
||||||
|
let movie_id = domain::value_objects::MovieId::from_uuid(
|
||||||
|
uuid::Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap(),
|
||||||
|
);
|
||||||
|
// offset beyond results: total_count still correct, items empty
|
||||||
|
let page = PageParams::new(Some(10), Some(5)).unwrap();
|
||||||
|
let result = repo.get_movie_social_feed(&movie_id, &page).await.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(result.total_count, 1);
|
||||||
|
assert_eq!(result.items.len(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn test_get_movie_stats_federated() {
|
||||||
|
let pool = SqlitePool::connect(":memory:").await.unwrap();
|
||||||
|
setup(&pool).await;
|
||||||
|
let repo = SqliteDiaryRepository::new(pool);
|
||||||
|
|
||||||
|
// Dune: 1 federated review, rating=4
|
||||||
|
let movie_id = domain::value_objects::MovieId::from_uuid(
|
||||||
|
uuid::Uuid::parse_str("cccccccc-cccc-cccc-cccc-cccccccccccc").unwrap(),
|
||||||
|
);
|
||||||
|
let stats = repo.get_movie_stats(&movie_id).await.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(stats.total_count, 1);
|
||||||
|
assert_eq!(stats.federated_count, 1);
|
||||||
|
assert_eq!(stats.rating_histogram[3], 1); // 4★ bucket
|
||||||
|
assert_eq!(stats.rating_histogram[4], 0); // 5★ bucket
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn count_local_posts_excludes_remote_reviews() {
|
||||||
|
let pool = SqlitePool::connect(":memory:").await.unwrap();
|
||||||
|
setup(&pool).await;
|
||||||
|
let repo = SqliteDiaryRepository::new(pool);
|
||||||
|
|
||||||
|
// setup() seeds 3 reviews: 2 local (alice, bob) + 1 remote (carol)
|
||||||
|
let count = repo.count_local_posts().await.unwrap();
|
||||||
|
assert_eq!(count, 2);
|
||||||
|
}
|
||||||
@@ -11,7 +11,10 @@ async fn pool_with_schema() -> SqlitePool {
|
|||||||
"CREATE TABLE persons (
|
"CREATE TABLE persons (
|
||||||
id TEXT PRIMARY KEY, external_id TEXT NOT NULL UNIQUE,
|
id TEXT PRIMARY KEY, external_id TEXT NOT NULL UNIQUE,
|
||||||
tmdb_person_id INTEGER UNIQUE, name TEXT NOT NULL,
|
tmdb_person_id INTEGER UNIQUE, name TEXT NOT NULL,
|
||||||
known_for_department TEXT, profile_path TEXT
|
known_for_department TEXT, profile_path TEXT,
|
||||||
|
biography TEXT, birthday TEXT, deathday TEXT,
|
||||||
|
place_of_birth TEXT, also_known_as TEXT,
|
||||||
|
homepage TEXT, imdb_id TEXT, enriched_at TEXT
|
||||||
)",
|
)",
|
||||||
)
|
)
|
||||||
.execute(&pool)
|
.execute(&pool)
|
||||||
@@ -46,7 +49,7 @@ async fn pool_with_schema() -> SqlitePool {
|
|||||||
|
|
||||||
fn make_person(tmdb_id: i64, name: &str, dept: Option<&str>) -> Person {
|
fn make_person(tmdb_id: i64, name: &str, dept: Option<&str>) -> Person {
|
||||||
let ext = ExternalPersonId::new(format!("tmdb:{tmdb_id}"));
|
let ext = ExternalPersonId::new(format!("tmdb:{tmdb_id}"));
|
||||||
Person::new(
|
Person::basic(
|
||||||
PersonId::from_external(&ext),
|
PersonId::from_external(&ext),
|
||||||
ext,
|
ext,
|
||||||
name.to_string(),
|
name.to_string(),
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use domain::{
|
use domain::{
|
||||||
errors::DomainError, models::UserSettings, ports::UserSettingsRepository, value_objects::UserId,
|
errors::DomainError,
|
||||||
|
models::UserSettings,
|
||||||
|
ports::{FederationFlags, UserFederationSettingsQuery, UserSettingsRepository},
|
||||||
|
value_objects::UserId,
|
||||||
};
|
};
|
||||||
use sqlx::{Row, SqlitePool};
|
use sqlx::{Row, SqlitePool};
|
||||||
|
|
||||||
@@ -23,20 +26,25 @@ impl SqliteUserSettingsRepository {
|
|||||||
impl UserSettingsRepository for SqliteUserSettingsRepository {
|
impl UserSettingsRepository for SqliteUserSettingsRepository {
|
||||||
async fn get(&self, user_id: &UserId) -> Result<UserSettings, DomainError> {
|
async fn get(&self, user_id: &UserId) -> Result<UserSettings, DomainError> {
|
||||||
let uid = user_id.value().to_string();
|
let uid = user_id.value().to_string();
|
||||||
|
let row = sqlx::query(
|
||||||
let row =
|
"SELECT federate_goals, federate_reviews, federate_watchlist \
|
||||||
sqlx::query("SELECT user_id, federate_goals FROM user_settings WHERE user_id = ?")
|
FROM user_settings WHERE user_id = ?",
|
||||||
.bind(&uid)
|
)
|
||||||
.fetch_optional(&self.pool)
|
.bind(&uid)
|
||||||
.await
|
.fetch_optional(&self.pool)
|
||||||
.map_err(Self::map_err)?;
|
.await
|
||||||
|
.map_err(Self::map_err)?;
|
||||||
|
|
||||||
match row {
|
match row {
|
||||||
Some(r) => {
|
Some(r) => {
|
||||||
let federate: i64 = r.try_get("federate_goals").unwrap_or(0);
|
let goals: i64 = r.try_get("federate_goals").unwrap_or(1);
|
||||||
|
let reviews: i64 = r.try_get("federate_reviews").unwrap_or(1);
|
||||||
|
let watchlist: i64 = r.try_get("federate_watchlist").unwrap_or(1);
|
||||||
Ok(UserSettings::from_persistence(
|
Ok(UserSettings::from_persistence(
|
||||||
user_id.clone(),
|
user_id.clone(),
|
||||||
federate != 0,
|
goals != 0,
|
||||||
|
reviews != 0,
|
||||||
|
watchlist != 0,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
None => Ok(UserSettings::new(user_id.clone())),
|
None => Ok(UserSettings::new(user_id.clone())),
|
||||||
@@ -45,15 +53,55 @@ impl UserSettingsRepository for SqliteUserSettingsRepository {
|
|||||||
|
|
||||||
async fn save(&self, settings: &UserSettings) -> Result<(), DomainError> {
|
async fn save(&self, settings: &UserSettings) -> Result<(), DomainError> {
|
||||||
let uid = settings.user_id().value().to_string();
|
let uid = settings.user_id().value().to_string();
|
||||||
let federate = if settings.federate_goals() { 1i64 } else { 0 };
|
sqlx::query(
|
||||||
|
"INSERT OR REPLACE INTO user_settings \
|
||||||
sqlx::query("INSERT OR REPLACE INTO user_settings (user_id, federate_goals) VALUES (?, ?)")
|
(user_id, federate_goals, federate_reviews, federate_watchlist) \
|
||||||
.bind(&uid)
|
VALUES (?, ?, ?, ?)",
|
||||||
.bind(federate)
|
)
|
||||||
.execute(&self.pool)
|
.bind(&uid)
|
||||||
.await
|
.bind(if settings.federate_goals() { 1i64 } else { 0 })
|
||||||
.map_err(Self::map_err)?;
|
.bind(if settings.federate_reviews() { 1i64 } else { 0 })
|
||||||
|
.bind(if settings.federate_watchlist() {
|
||||||
|
1i64
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
})
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(Self::map_err)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl UserFederationSettingsQuery for SqliteUserSettingsRepository {
|
||||||
|
async fn get_federation_flags(&self, user_id: &UserId) -> Result<FederationFlags, DomainError> {
|
||||||
|
let uid = user_id.value().to_string();
|
||||||
|
let row = sqlx::query(
|
||||||
|
"SELECT federate_goals, federate_reviews, federate_watchlist \
|
||||||
|
FROM user_settings WHERE user_id = ?",
|
||||||
|
)
|
||||||
|
.bind(&uid)
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await
|
||||||
|
.map_err(Self::map_err)?;
|
||||||
|
|
||||||
|
match row {
|
||||||
|
Some(r) => {
|
||||||
|
let goals: i64 = r.try_get("federate_goals").unwrap_or(1);
|
||||||
|
let reviews: i64 = r.try_get("federate_reviews").unwrap_or(1);
|
||||||
|
let watchlist: i64 = r.try_get("federate_watchlist").unwrap_or(1);
|
||||||
|
Ok(FederationFlags {
|
||||||
|
goals: goals != 0,
|
||||||
|
reviews: reviews != 0,
|
||||||
|
watchlist: watchlist != 0,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
None => Ok(FederationFlags {
|
||||||
|
goals: true,
|
||||||
|
reviews: true,
|
||||||
|
watchlist: true,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
247
crates/adapters/tmdb-enrichment/src/client.rs
Normal file
247
crates/adapters/tmdb-enrichment/src/client.rs
Normal file
@@ -0,0 +1,247 @@
|
|||||||
|
use async_trait::async_trait;
|
||||||
|
use chrono::Utc;
|
||||||
|
use domain::{
|
||||||
|
errors::DomainError,
|
||||||
|
models::{CastMember, CrewMember, Genre, Keyword, MovieProfile, PersonEnrichmentData},
|
||||||
|
ports::{MovieEnrichmentClient, PersonEnrichmentClient},
|
||||||
|
value_objects::MovieId,
|
||||||
|
};
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
pub struct TmdbEnrichmentClient {
|
||||||
|
api_key: String,
|
||||||
|
http: reqwest::Client,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TmdbEnrichmentClient {
|
||||||
|
pub fn from_env() -> Result<Self, DomainError> {
|
||||||
|
let api_key = std::env::var("TMDB_API_KEY")
|
||||||
|
.map_err(|_| DomainError::InfrastructureError("TMDB_API_KEY is not set".into()))?;
|
||||||
|
Ok(Self {
|
||||||
|
api_key,
|
||||||
|
http: reqwest::Client::new(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn base(&self, path: &str) -> String {
|
||||||
|
format!("https://api.themoviedb.org/3{}", path)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn get<T: for<'de> Deserialize<'de>>(
|
||||||
|
&self,
|
||||||
|
url: &str,
|
||||||
|
extra: &[(&str, &str)],
|
||||||
|
) -> Result<T, DomainError> {
|
||||||
|
let mut req = self
|
||||||
|
.http
|
||||||
|
.get(url)
|
||||||
|
.query(&[("api_key", self.api_key.as_str())]);
|
||||||
|
for (k, v) in extra {
|
||||||
|
req = req.query(&[(k, v)]);
|
||||||
|
}
|
||||||
|
req.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?
|
||||||
|
.error_for_status()
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?
|
||||||
|
.json::<T>()
|
||||||
|
.await
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(e.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn resolve_tmdb_id(&self, external_id: &str) -> Result<u64, DomainError> {
|
||||||
|
if let Some(numeric) = external_id.strip_prefix("tmdb:") {
|
||||||
|
return numeric.parse::<u64>().map_err(|_| {
|
||||||
|
DomainError::InfrastructureError(format!("Invalid tmdb id: {numeric}"))
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct FindResult {
|
||||||
|
id: u64,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct FindResponse {
|
||||||
|
movie_results: Vec<FindResult>,
|
||||||
|
}
|
||||||
|
|
||||||
|
let url = self.base(&format!("/find/{}", external_id));
|
||||||
|
let resp: FindResponse = self.get(&url, &[("external_source", "imdb_id")]).await?;
|
||||||
|
resp.movie_results
|
||||||
|
.into_iter()
|
||||||
|
.next()
|
||||||
|
.map(|r| r.id)
|
||||||
|
.ok_or_else(|| DomainError::NotFound(format!("TMDb: no movie for {external_id}")))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl MovieEnrichmentClient for TmdbEnrichmentClient {
|
||||||
|
async fn fetch_profile(
|
||||||
|
&self,
|
||||||
|
movie_id: MovieId,
|
||||||
|
external_metadata_id: &str,
|
||||||
|
) -> Result<MovieProfile, DomainError> {
|
||||||
|
let tmdb_id = self.resolve_tmdb_id(external_metadata_id).await?;
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct GenreDto {
|
||||||
|
id: u32,
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct CollectionDto {
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct CastDto {
|
||||||
|
id: u64,
|
||||||
|
name: String,
|
||||||
|
character: String,
|
||||||
|
order: u32,
|
||||||
|
profile_path: Option<String>,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct CrewDto {
|
||||||
|
id: u64,
|
||||||
|
name: String,
|
||||||
|
job: String,
|
||||||
|
department: String,
|
||||||
|
profile_path: Option<String>,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct Credits {
|
||||||
|
cast: Vec<CastDto>,
|
||||||
|
crew: Vec<CrewDto>,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct KeywordDto {
|
||||||
|
id: u32,
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct Keywords {
|
||||||
|
keywords: Vec<KeywordDto>,
|
||||||
|
}
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct Details {
|
||||||
|
imdb_id: Option<String>,
|
||||||
|
overview: Option<String>,
|
||||||
|
tagline: Option<String>,
|
||||||
|
runtime: Option<u32>,
|
||||||
|
budget: Option<i64>,
|
||||||
|
revenue: Option<i64>,
|
||||||
|
vote_average: Option<f64>,
|
||||||
|
vote_count: Option<u32>,
|
||||||
|
original_language: Option<String>,
|
||||||
|
genres: Vec<GenreDto>,
|
||||||
|
belongs_to_collection: Option<CollectionDto>,
|
||||||
|
credits: Credits,
|
||||||
|
keywords: Keywords,
|
||||||
|
}
|
||||||
|
|
||||||
|
let url = self.base(&format!("/movie/{}", tmdb_id));
|
||||||
|
let d: Details = self
|
||||||
|
.get(&url, &[("append_to_response", "credits,keywords")])
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(MovieProfile {
|
||||||
|
movie_id,
|
||||||
|
tmdb_id,
|
||||||
|
imdb_id: d.imdb_id.filter(|s| !s.is_empty()),
|
||||||
|
overview: d.overview.filter(|s| !s.is_empty()),
|
||||||
|
tagline: d.tagline.filter(|s| !s.is_empty()),
|
||||||
|
runtime_minutes: d.runtime,
|
||||||
|
budget_usd: d.budget.filter(|&v| v > 0),
|
||||||
|
revenue_usd: d.revenue.filter(|&v| v > 0),
|
||||||
|
vote_average: d.vote_average,
|
||||||
|
vote_count: d.vote_count,
|
||||||
|
original_language: d.original_language,
|
||||||
|
collection_name: d.belongs_to_collection.map(|c| c.name),
|
||||||
|
genres: d
|
||||||
|
.genres
|
||||||
|
.into_iter()
|
||||||
|
.map(|g| Genre {
|
||||||
|
tmdb_id: g.id,
|
||||||
|
name: g.name,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
keywords: d
|
||||||
|
.keywords
|
||||||
|
.keywords
|
||||||
|
.into_iter()
|
||||||
|
.map(|k| Keyword {
|
||||||
|
tmdb_id: k.id,
|
||||||
|
name: k.name,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
cast: d
|
||||||
|
.credits
|
||||||
|
.cast
|
||||||
|
.into_iter()
|
||||||
|
.map(|c| CastMember {
|
||||||
|
tmdb_person_id: c.id,
|
||||||
|
name: c.name,
|
||||||
|
character: c.character,
|
||||||
|
billing_order: c.order,
|
||||||
|
profile_path: c.profile_path,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
crew: d
|
||||||
|
.credits
|
||||||
|
.crew
|
||||||
|
.into_iter()
|
||||||
|
.map(|c| CrewMember {
|
||||||
|
tmdb_person_id: c.id,
|
||||||
|
name: c.name,
|
||||||
|
job: c.job,
|
||||||
|
department: c.department,
|
||||||
|
profile_path: c.profile_path,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
enriched_at: Utc::now(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl PersonEnrichmentClient for TmdbEnrichmentClient {
|
||||||
|
async fn fetch_details(&self, external_id: &str) -> Result<PersonEnrichmentData, DomainError> {
|
||||||
|
let tmdb_id = external_id
|
||||||
|
.strip_prefix("tmdb:")
|
||||||
|
.and_then(|s| s.parse::<u64>().ok())
|
||||||
|
.ok_or_else(|| {
|
||||||
|
DomainError::InfrastructureError(format!(
|
||||||
|
"Cannot parse person external_id: {external_id}"
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct PersonDetails {
|
||||||
|
biography: Option<String>,
|
||||||
|
birthday: Option<String>,
|
||||||
|
deathday: Option<String>,
|
||||||
|
place_of_birth: Option<String>,
|
||||||
|
also_known_as: Option<Vec<String>>,
|
||||||
|
homepage: Option<String>,
|
||||||
|
imdb_id: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
let url = self.base(&format!("/person/{tmdb_id}"));
|
||||||
|
let d: PersonDetails = self.get(&url, &[]).await?;
|
||||||
|
|
||||||
|
Ok(PersonEnrichmentData {
|
||||||
|
biography: d.biography.filter(|s| !s.is_empty()),
|
||||||
|
birthday: d
|
||||||
|
.birthday
|
||||||
|
.and_then(|s| chrono::NaiveDate::parse_from_str(&s, "%Y-%m-%d").ok()),
|
||||||
|
deathday: d
|
||||||
|
.deathday
|
||||||
|
.and_then(|s| chrono::NaiveDate::parse_from_str(&s, "%Y-%m-%d").ok()),
|
||||||
|
place_of_birth: d.place_of_birth.filter(|s| !s.is_empty()),
|
||||||
|
also_known_as: d.also_known_as.unwrap_or_default(),
|
||||||
|
homepage: d.homepage.filter(|s| !s.is_empty()),
|
||||||
|
imdb_id: d.imdb_id.filter(|s| !s.is_empty()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,312 +1,7 @@
|
|||||||
use std::sync::Arc;
|
mod client;
|
||||||
|
mod movie_handler;
|
||||||
|
mod person_handler;
|
||||||
|
|
||||||
use application::movies::{commands::EnrichMovieCommand, enrich_movie, request_enrichment};
|
pub use client::TmdbEnrichmentClient;
|
||||||
use async_trait::async_trait;
|
pub use movie_handler::MovieEnrichmentHandler;
|
||||||
use chrono::Utc;
|
pub use person_handler::PersonEnrichmentHandler;
|
||||||
use domain::{
|
|
||||||
errors::DomainError,
|
|
||||||
events::DomainEvent,
|
|
||||||
models::{CastMember, CrewMember, Genre, Keyword, MovieProfile},
|
|
||||||
ports::{
|
|
||||||
EventHandler, MovieEnrichmentClient, MovieProfileRepository, MovieRepository,
|
|
||||||
ObjectStorage, PersonCommand, SearchCommand,
|
|
||||||
},
|
|
||||||
value_objects::MovieId,
|
|
||||||
};
|
|
||||||
use serde::Deserialize;
|
|
||||||
|
|
||||||
// ── TMDb enrichment client ───────────────────────────────────────────────────
|
|
||||||
|
|
||||||
pub struct TmdbEnrichmentClient {
|
|
||||||
api_key: String,
|
|
||||||
http: reqwest::Client,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TmdbEnrichmentClient {
|
|
||||||
pub fn from_env() -> Result<Self, DomainError> {
|
|
||||||
let api_key = std::env::var("TMDB_API_KEY")
|
|
||||||
.map_err(|_| DomainError::InfrastructureError("TMDB_API_KEY is not set".into()))?;
|
|
||||||
Ok(Self {
|
|
||||||
api_key,
|
|
||||||
http: reqwest::Client::new(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn base(&self, path: &str) -> String {
|
|
||||||
format!("https://api.themoviedb.org/3{}", path)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get<T: for<'de> Deserialize<'de>>(
|
|
||||||
&self,
|
|
||||||
url: &str,
|
|
||||||
extra: &[(&str, &str)],
|
|
||||||
) -> Result<T, DomainError> {
|
|
||||||
let mut req = self
|
|
||||||
.http
|
|
||||||
.get(url)
|
|
||||||
.query(&[("api_key", self.api_key.as_str())]);
|
|
||||||
for (k, v) in extra {
|
|
||||||
req = req.query(&[(k, v)]);
|
|
||||||
}
|
|
||||||
req.send()
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?
|
|
||||||
.error_for_status()
|
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?
|
|
||||||
.json::<T>()
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::InfrastructureError(e.to_string()))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn resolve_tmdb_id(&self, external_id: &str) -> Result<u64, DomainError> {
|
|
||||||
if let Some(numeric) = external_id.strip_prefix("tmdb:") {
|
|
||||||
return numeric.parse::<u64>().map_err(|_| {
|
|
||||||
DomainError::InfrastructureError(format!("Invalid tmdb id: {numeric}"))
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Assume IMDb ID (tt…) — use /find
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct FindResult {
|
|
||||||
id: u64,
|
|
||||||
}
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct FindResponse {
|
|
||||||
movie_results: Vec<FindResult>,
|
|
||||||
}
|
|
||||||
|
|
||||||
let url = self.base(&format!("/find/{}", external_id));
|
|
||||||
let resp: FindResponse = self.get(&url, &[("external_source", "imdb_id")]).await?;
|
|
||||||
resp.movie_results
|
|
||||||
.into_iter()
|
|
||||||
.next()
|
|
||||||
.map(|r| r.id)
|
|
||||||
.ok_or_else(|| DomainError::NotFound(format!("TMDb: no movie for {external_id}")))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl MovieEnrichmentClient for TmdbEnrichmentClient {
|
|
||||||
async fn fetch_profile(
|
|
||||||
&self,
|
|
||||||
movie_id: MovieId,
|
|
||||||
external_metadata_id: &str,
|
|
||||||
) -> Result<MovieProfile, DomainError> {
|
|
||||||
let tmdb_id = self.resolve_tmdb_id(external_metadata_id).await?;
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct GenreDto {
|
|
||||||
id: u32,
|
|
||||||
name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct CollectionDto {
|
|
||||||
name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct CastDto {
|
|
||||||
id: u64,
|
|
||||||
name: String,
|
|
||||||
character: String,
|
|
||||||
order: u32,
|
|
||||||
profile_path: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct CrewDto {
|
|
||||||
id: u64,
|
|
||||||
name: String,
|
|
||||||
job: String,
|
|
||||||
department: String,
|
|
||||||
profile_path: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct Credits {
|
|
||||||
cast: Vec<CastDto>,
|
|
||||||
crew: Vec<CrewDto>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct KeywordDto {
|
|
||||||
id: u32,
|
|
||||||
name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct Keywords {
|
|
||||||
keywords: Vec<KeywordDto>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct Details {
|
|
||||||
imdb_id: Option<String>,
|
|
||||||
overview: Option<String>,
|
|
||||||
tagline: Option<String>,
|
|
||||||
runtime: Option<u32>,
|
|
||||||
budget: Option<i64>,
|
|
||||||
revenue: Option<i64>,
|
|
||||||
vote_average: Option<f64>,
|
|
||||||
vote_count: Option<u32>,
|
|
||||||
original_language: Option<String>,
|
|
||||||
genres: Vec<GenreDto>,
|
|
||||||
belongs_to_collection: Option<CollectionDto>,
|
|
||||||
credits: Credits,
|
|
||||||
keywords: Keywords,
|
|
||||||
}
|
|
||||||
|
|
||||||
let url = self.base(&format!("/movie/{}", tmdb_id));
|
|
||||||
let d: Details = self
|
|
||||||
.get(&url, &[("append_to_response", "credits,keywords")])
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(MovieProfile {
|
|
||||||
movie_id,
|
|
||||||
tmdb_id,
|
|
||||||
imdb_id: d.imdb_id.filter(|s| !s.is_empty()),
|
|
||||||
overview: d.overview.filter(|s| !s.is_empty()),
|
|
||||||
tagline: d.tagline.filter(|s| !s.is_empty()),
|
|
||||||
runtime_minutes: d.runtime,
|
|
||||||
budget_usd: d.budget.filter(|&v| v > 0),
|
|
||||||
revenue_usd: d.revenue.filter(|&v| v > 0),
|
|
||||||
vote_average: d.vote_average,
|
|
||||||
vote_count: d.vote_count,
|
|
||||||
original_language: d.original_language,
|
|
||||||
collection_name: d.belongs_to_collection.map(|c| c.name),
|
|
||||||
genres: d
|
|
||||||
.genres
|
|
||||||
.into_iter()
|
|
||||||
.map(|g| Genre {
|
|
||||||
tmdb_id: g.id,
|
|
||||||
name: g.name,
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
keywords: d
|
|
||||||
.keywords
|
|
||||||
.keywords
|
|
||||||
.into_iter()
|
|
||||||
.map(|k| Keyword {
|
|
||||||
tmdb_id: k.id,
|
|
||||||
name: k.name,
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
cast: d
|
|
||||||
.credits
|
|
||||||
.cast
|
|
||||||
.into_iter()
|
|
||||||
.map(|c| CastMember {
|
|
||||||
tmdb_person_id: c.id,
|
|
||||||
name: c.name,
|
|
||||||
character: c.character,
|
|
||||||
billing_order: c.order,
|
|
||||||
profile_path: c.profile_path,
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
crew: d
|
|
||||||
.credits
|
|
||||||
.crew
|
|
||||||
.into_iter()
|
|
||||||
.map(|c| CrewMember {
|
|
||||||
tmdb_person_id: c.id,
|
|
||||||
name: c.name,
|
|
||||||
job: c.job,
|
|
||||||
department: c.department,
|
|
||||||
profile_path: c.profile_path,
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
enriched_at: Utc::now(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Enrichment event handler ─────────────────────────────────────────────────
|
|
||||||
|
|
||||||
pub struct EnrichmentHandler {
|
|
||||||
pub enrichment_client: Arc<dyn MovieEnrichmentClient>,
|
|
||||||
pub movie_repository: Arc<dyn MovieRepository>,
|
|
||||||
pub profile_repo: Arc<dyn MovieProfileRepository>,
|
|
||||||
pub person_command: Arc<dyn PersonCommand>,
|
|
||||||
pub search_command: Arc<dyn SearchCommand>,
|
|
||||||
pub object_storage: Arc<dyn ObjectStorage>,
|
|
||||||
http: reqwest::Client,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EnrichmentHandler {
|
|
||||||
pub fn new(
|
|
||||||
enrichment_client: Arc<dyn MovieEnrichmentClient>,
|
|
||||||
movie_repository: Arc<dyn MovieRepository>,
|
|
||||||
profile_repo: Arc<dyn MovieProfileRepository>,
|
|
||||||
person_command: Arc<dyn PersonCommand>,
|
|
||||||
search_command: Arc<dyn SearchCommand>,
|
|
||||||
object_storage: Arc<dyn ObjectStorage>,
|
|
||||||
) -> Self {
|
|
||||||
Self {
|
|
||||||
enrichment_client,
|
|
||||||
movie_repository,
|
|
||||||
profile_repo,
|
|
||||||
person_command,
|
|
||||||
search_command,
|
|
||||||
object_storage,
|
|
||||||
http: reqwest::Client::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn download_cast_photos(&self, profile: &MovieProfile) {
|
|
||||||
for member in profile.cast.iter().take(5) {
|
|
||||||
let Some(ref path) = member.profile_path else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let key = format!("cast{path}");
|
|
||||||
if self.object_storage.get(&key).await.is_ok() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let url = format!("https://image.tmdb.org/t/p/w185{path}");
|
|
||||||
match self.http.get(&url).send().await {
|
|
||||||
Ok(resp) if resp.status().is_success() => {
|
|
||||||
if let Ok(bytes) = resp.bytes().await
|
|
||||||
&& let Err(e) = self.object_storage.store(&key, &bytes).await
|
|
||||||
{
|
|
||||||
tracing::debug!("cast photo store failed for {path}: {e}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => tracing::debug!("cast photo download failed for {path}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl EventHandler for EnrichmentHandler {
|
|
||||||
async fn handle(&self, event: &DomainEvent) -> Result<(), DomainError> {
|
|
||||||
let (movie_id, external_metadata_id) = match event {
|
|
||||||
DomainEvent::MovieEnrichmentRequested {
|
|
||||||
movie_id,
|
|
||||||
external_metadata_id,
|
|
||||||
} => (movie_id.clone(), external_metadata_id.clone()),
|
|
||||||
_ => return Ok(()),
|
|
||||||
};
|
|
||||||
|
|
||||||
let Some(profile) = request_enrichment::fetch_if_stale(
|
|
||||||
self.enrichment_client.as_ref(),
|
|
||||||
&self.profile_repo,
|
|
||||||
movie_id.clone(),
|
|
||||||
&external_metadata_id,
|
|
||||||
)
|
|
||||||
.await?
|
|
||||||
else {
|
|
||||||
return Ok(());
|
|
||||||
};
|
|
||||||
|
|
||||||
self.download_cast_photos(&profile).await;
|
|
||||||
enrich_movie::execute(
|
|
||||||
&self.movie_repository,
|
|
||||||
&self.profile_repo,
|
|
||||||
&self.person_command,
|
|
||||||
&self.search_command,
|
|
||||||
EnrichMovieCommand { movie_id, profile },
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
102
crates/adapters/tmdb-enrichment/src/movie_handler.rs
Normal file
102
crates/adapters/tmdb-enrichment/src/movie_handler.rs
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use application::movies::{
|
||||||
|
commands::EnrichMovieCommand, deps::EnrichMovieDeps, enrich_movie, request_enrichment,
|
||||||
|
};
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use domain::{
|
||||||
|
errors::DomainError,
|
||||||
|
events::DomainEvent,
|
||||||
|
models::MovieProfile,
|
||||||
|
ports::{
|
||||||
|
EventHandler, MovieEnrichmentClient, MovieProfileRepository, MovieRepository,
|
||||||
|
ObjectStorage, PersonCommand, SearchCommand,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub struct MovieEnrichmentHandler {
|
||||||
|
enrichment_client: Arc<dyn MovieEnrichmentClient>,
|
||||||
|
movie_repository: Arc<dyn MovieRepository>,
|
||||||
|
profile_repo: Arc<dyn MovieProfileRepository>,
|
||||||
|
person_command: Arc<dyn PersonCommand>,
|
||||||
|
search_command: Arc<dyn SearchCommand>,
|
||||||
|
object_storage: Arc<dyn ObjectStorage>,
|
||||||
|
http: reqwest::Client,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MovieEnrichmentHandler {
|
||||||
|
pub fn new(
|
||||||
|
enrichment_client: Arc<dyn MovieEnrichmentClient>,
|
||||||
|
movie_repository: Arc<dyn MovieRepository>,
|
||||||
|
profile_repo: Arc<dyn MovieProfileRepository>,
|
||||||
|
person_command: Arc<dyn PersonCommand>,
|
||||||
|
search_command: Arc<dyn SearchCommand>,
|
||||||
|
object_storage: Arc<dyn ObjectStorage>,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
enrichment_client,
|
||||||
|
movie_repository,
|
||||||
|
profile_repo,
|
||||||
|
person_command,
|
||||||
|
search_command,
|
||||||
|
object_storage,
|
||||||
|
http: reqwest::Client::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn download_cast_photos(&self, profile: &MovieProfile) {
|
||||||
|
for member in profile.cast.iter().take(5) {
|
||||||
|
let Some(ref path) = member.profile_path else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let key = format!("cast{path}");
|
||||||
|
if self.object_storage.get(&key).await.is_ok() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let url = format!("https://image.tmdb.org/t/p/w185{path}");
|
||||||
|
match self.http.get(&url).send().await {
|
||||||
|
Ok(resp) if resp.status().is_success() => {
|
||||||
|
if let Ok(bytes) = resp.bytes().await
|
||||||
|
&& let Err(e) = self.object_storage.store(&key, &bytes).await
|
||||||
|
{
|
||||||
|
tracing::debug!("cast photo store failed for {path}: {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => tracing::debug!("cast photo download failed for {path}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl EventHandler for MovieEnrichmentHandler {
|
||||||
|
async fn handle(&self, event: &DomainEvent) -> Result<(), DomainError> {
|
||||||
|
let (movie_id, external_metadata_id) = match event {
|
||||||
|
DomainEvent::MovieEnrichmentRequested {
|
||||||
|
movie_id,
|
||||||
|
external_metadata_id,
|
||||||
|
} => (movie_id.clone(), external_metadata_id.clone()),
|
||||||
|
_ => return Ok(()),
|
||||||
|
};
|
||||||
|
|
||||||
|
let Some(profile) = request_enrichment::fetch_if_stale(
|
||||||
|
self.enrichment_client.as_ref(),
|
||||||
|
&self.profile_repo,
|
||||||
|
movie_id.clone(),
|
||||||
|
external_metadata_id.value(),
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
|
||||||
|
self.download_cast_photos(&profile).await;
|
||||||
|
let enrich_deps = EnrichMovieDeps {
|
||||||
|
movie: self.movie_repository.clone(),
|
||||||
|
movie_profile: self.profile_repo.clone(),
|
||||||
|
person_command: self.person_command.clone(),
|
||||||
|
search_command: self.search_command.clone(),
|
||||||
|
};
|
||||||
|
enrich_movie::execute(&enrich_deps, EnrichMovieCommand { movie_id, profile }).await
|
||||||
|
}
|
||||||
|
}
|
||||||
46
crates/adapters/tmdb-enrichment/src/person_handler.rs
Normal file
46
crates/adapters/tmdb-enrichment/src/person_handler.rs
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use domain::{
|
||||||
|
errors::DomainError,
|
||||||
|
events::DomainEvent,
|
||||||
|
ports::{EventHandler, PersonCommand, PersonEnrichmentClient, PersonQuery},
|
||||||
|
};
|
||||||
|
|
||||||
|
use application::person::deps::EnrichPersonDeps;
|
||||||
|
|
||||||
|
pub struct PersonEnrichmentHandler {
|
||||||
|
deps: EnrichPersonDeps,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PersonEnrichmentHandler {
|
||||||
|
pub fn new(
|
||||||
|
person_query: Arc<dyn PersonQuery>,
|
||||||
|
person_enrichment: Option<Arc<dyn PersonEnrichmentClient>>,
|
||||||
|
person_command: Arc<dyn PersonCommand>,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
deps: EnrichPersonDeps {
|
||||||
|
person_query,
|
||||||
|
person_enrichment,
|
||||||
|
person_command,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl EventHandler for PersonEnrichmentHandler {
|
||||||
|
async fn handle(&self, event: &DomainEvent) -> Result<(), DomainError> {
|
||||||
|
let (person_id, external_person_id) = match event {
|
||||||
|
DomainEvent::PersonEnrichmentRequested {
|
||||||
|
person_id,
|
||||||
|
external_person_id,
|
||||||
|
} => (person_id.clone(), external_person_id.clone()),
|
||||||
|
_ => return Ok(()),
|
||||||
|
};
|
||||||
|
|
||||||
|
application::person::enrich::execute(&self.deps, person_id, external_person_id.value())
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@ pub struct LoginRequest {
|
|||||||
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
|
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
|
||||||
pub struct LoginResponse {
|
pub struct LoginResponse {
|
||||||
pub token: String,
|
pub token: String,
|
||||||
|
pub refresh_token: String,
|
||||||
pub user_id: Uuid,
|
pub user_id: Uuid,
|
||||||
pub email: String,
|
pub email: String,
|
||||||
pub expires_at: String,
|
pub expires_at: String,
|
||||||
@@ -22,3 +23,20 @@ pub struct RegisterRequest {
|
|||||||
pub username: String,
|
pub username: String,
|
||||||
pub password: String,
|
pub password: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
|
||||||
|
pub struct RefreshRequest {
|
||||||
|
pub refresh_token: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
|
||||||
|
pub struct RefreshResponse {
|
||||||
|
pub token: String,
|
||||||
|
pub refresh_token: String,
|
||||||
|
pub expires_at: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
|
||||||
|
pub struct LogoutRequest {
|
||||||
|
pub refresh_token: String,
|
||||||
|
}
|
||||||
|
|||||||
@@ -29,9 +29,13 @@ pub struct UpdateGoalRequest {
|
|||||||
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
|
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
|
||||||
pub struct UserSettingsDto {
|
pub struct UserSettingsDto {
|
||||||
pub federate_goals: bool,
|
pub federate_goals: bool,
|
||||||
|
pub federate_reviews: bool,
|
||||||
|
pub federate_watchlist: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, utoipa::ToSchema)]
|
#[derive(Debug, Clone, Deserialize, utoipa::ToSchema)]
|
||||||
pub struct UpdateUserSettingsRequest {
|
pub struct UpdateUserSettingsRequest {
|
||||||
pub federate_goals: bool,
|
pub federate_goals: bool,
|
||||||
|
pub federate_reviews: bool,
|
||||||
|
pub federate_watchlist: bool,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -70,6 +70,21 @@ pub struct PersonDto {
|
|||||||
pub name: String,
|
pub name: String,
|
||||||
pub known_for_department: Option<String>,
|
pub known_for_department: Option<String>,
|
||||||
pub profile_path: Option<String>,
|
pub profile_path: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub biography: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub birthday: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub deathday: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub place_of_birth: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub also_known_as: Vec<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub homepage: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub imdb_url: Option<String>,
|
||||||
|
pub enriched: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize, ToSchema)]
|
#[derive(Debug, Serialize, ToSchema)]
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ pub struct UserProfileQueryParams {
|
|||||||
pub view: Option<String>,
|
pub view: Option<String>,
|
||||||
pub limit: Option<u32>,
|
pub limit: Option<u32>,
|
||||||
pub offset: Option<u32>,
|
pub offset: Option<u32>,
|
||||||
|
pub search: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
|
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ sha2 = { workspace = true }
|
|||||||
rand = { workspace = true }
|
rand = { workspace = true }
|
||||||
hex = { workspace = true }
|
hex = { workspace = true }
|
||||||
serde_json = { workspace = true }
|
serde_json = { workspace = true }
|
||||||
|
bytes = { workspace = true }
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
xlsx = []
|
xlsx = []
|
||||||
|
|||||||
33
crates/application/src/auth/deps.rs
Normal file
33
crates/application/src/auth/deps.rs
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use domain::ports::{AuthService, PasswordHasher, RefreshSessionRepository, UserRepository};
|
||||||
|
|
||||||
|
use crate::config::AppConfig;
|
||||||
|
|
||||||
|
pub struct LoginDeps {
|
||||||
|
pub user: Arc<dyn UserRepository>,
|
||||||
|
pub password_hasher: Arc<dyn PasswordHasher>,
|
||||||
|
pub auth: Arc<dyn AuthService>,
|
||||||
|
pub refresh_session: Arc<dyn RefreshSessionRepository>,
|
||||||
|
pub config: AppConfig,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct RegisterDeps {
|
||||||
|
pub user: Arc<dyn UserRepository>,
|
||||||
|
pub password_hasher: Arc<dyn PasswordHasher>,
|
||||||
|
pub config: AppConfig,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct RefreshDeps {
|
||||||
|
pub refresh_session: Arc<dyn RefreshSessionRepository>,
|
||||||
|
pub auth: Arc<dyn AuthService>,
|
||||||
|
pub config: AppConfig,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct RegisterAndLoginDeps {
|
||||||
|
pub user: Arc<dyn UserRepository>,
|
||||||
|
pub password_hasher: Arc<dyn PasswordHasher>,
|
||||||
|
pub auth: Arc<dyn AuthService>,
|
||||||
|
pub refresh_session: Arc<dyn RefreshSessionRepository>,
|
||||||
|
pub config: AppConfig,
|
||||||
|
}
|
||||||
@@ -1,29 +1,28 @@
|
|||||||
use chrono::{DateTime, Utc};
|
use chrono::{DateTime, Duration, Utc};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use domain::{errors::DomainError, value_objects::Email};
|
use domain::{errors::DomainError, models::RefreshSession, value_objects::Email};
|
||||||
|
|
||||||
use crate::{auth::queries::LoginQuery, context::AppContext};
|
use crate::auth::{deps::LoginDeps, queries::LoginQuery};
|
||||||
|
|
||||||
pub struct LoginResult {
|
pub struct LoginResult {
|
||||||
pub token: String,
|
pub token: String,
|
||||||
|
pub refresh_token: String,
|
||||||
pub user_id: Uuid,
|
pub user_id: Uuid,
|
||||||
pub email: String,
|
pub email: String,
|
||||||
pub expires_at: DateTime<Utc>,
|
pub expires_at: DateTime<Utc>,
|
||||||
pub role: String,
|
pub role: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn execute(ctx: &AppContext, query: LoginQuery) -> Result<LoginResult, DomainError> {
|
pub async fn execute(deps: &LoginDeps, query: LoginQuery) -> Result<LoginResult, DomainError> {
|
||||||
let email = Email::new(query.email)?;
|
let email = Email::new(query.email)?;
|
||||||
let user = ctx
|
let user = deps
|
||||||
.repos
|
|
||||||
.user
|
.user
|
||||||
.find_by_email(&email)
|
.find_by_email(&email)
|
||||||
.await?
|
.await?
|
||||||
.ok_or_else(|| DomainError::Unauthorized("Invalid credentials".into()))?;
|
.ok_or_else(|| DomainError::Unauthorized("Invalid credentials".into()))?;
|
||||||
|
|
||||||
let valid = ctx
|
let valid = deps
|
||||||
.services
|
|
||||||
.password_hasher
|
.password_hasher
|
||||||
.verify(&query.password, user.password_hash())
|
.verify(&query.password, user.password_hash())
|
||||||
.await?;
|
.await?;
|
||||||
@@ -31,10 +30,22 @@ pub async fn execute(ctx: &AppContext, query: LoginQuery) -> Result<LoginResult,
|
|||||||
return Err(DomainError::Unauthorized("Invalid credentials".into()));
|
return Err(DomainError::Unauthorized("Invalid credentials".into()));
|
||||||
}
|
}
|
||||||
|
|
||||||
let generated = ctx.services.auth.generate_token(user.id()).await?;
|
let generated = deps.auth.generate_token(user.id()).await?;
|
||||||
|
|
||||||
|
let refresh_token = Uuid::new_v4().to_string();
|
||||||
|
let refresh_expires = Utc::now() + Duration::seconds(deps.config.refresh_ttl_seconds as i64);
|
||||||
|
let session = RefreshSession {
|
||||||
|
id: Uuid::new_v4(),
|
||||||
|
user_id: user.id().clone(),
|
||||||
|
token: refresh_token.clone(),
|
||||||
|
expires_at: refresh_expires,
|
||||||
|
created_at: Utc::now(),
|
||||||
|
};
|
||||||
|
deps.refresh_session.create(&session).await?;
|
||||||
|
|
||||||
Ok(LoginResult {
|
Ok(LoginResult {
|
||||||
token: generated.token,
|
token: generated.token,
|
||||||
|
refresh_token,
|
||||||
user_id: user.id().value(),
|
user_id: user.id().value(),
|
||||||
email: user.email().value().to_string(),
|
email: user.email().value().to_string(),
|
||||||
expires_at: generated.expires_at,
|
expires_at: generated.expires_at,
|
||||||
|
|||||||
14
crates/application/src/auth/logout.rs
Normal file
14
crates/application/src/auth/logout.rs
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use domain::{errors::DomainError, ports::RefreshSessionRepository};
|
||||||
|
|
||||||
|
pub async fn execute(
|
||||||
|
refresh_session: Arc<dyn RefreshSessionRepository>,
|
||||||
|
refresh_token: &str,
|
||||||
|
) -> Result<(), DomainError> {
|
||||||
|
refresh_session.revoke(refresh_token).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "tests/logout.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
pub mod commands;
|
pub mod commands;
|
||||||
|
pub mod deps;
|
||||||
pub mod login;
|
pub mod login;
|
||||||
|
pub mod logout;
|
||||||
pub mod queries;
|
pub mod queries;
|
||||||
|
pub mod refresh;
|
||||||
pub mod register;
|
pub mod register;
|
||||||
pub mod register_and_login;
|
pub mod register_and_login;
|
||||||
|
|||||||
56
crates/application/src/auth/refresh.rs
Normal file
56
crates/application/src/auth/refresh.rs
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
use chrono::{Duration, Utc};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use domain::{errors::DomainError, models::RefreshSession};
|
||||||
|
|
||||||
|
use crate::auth::deps::RefreshDeps;
|
||||||
|
|
||||||
|
pub struct RefreshResult {
|
||||||
|
pub token: String,
|
||||||
|
pub refresh_token: String,
|
||||||
|
pub expires_at: chrono::DateTime<Utc>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn execute(
|
||||||
|
deps: &RefreshDeps,
|
||||||
|
old_refresh_token: &str,
|
||||||
|
) -> Result<RefreshResult, DomainError> {
|
||||||
|
let session = deps
|
||||||
|
.refresh_session
|
||||||
|
.get_by_token(old_refresh_token)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| DomainError::Unauthorized("Invalid refresh token".into()))?;
|
||||||
|
|
||||||
|
if session.expires_at < Utc::now() {
|
||||||
|
deps.refresh_session.revoke(old_refresh_token).await?;
|
||||||
|
return Err(DomainError::Unauthorized("Refresh token expired".into()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Revoke old token (rotation)
|
||||||
|
deps.refresh_session.revoke(old_refresh_token).await?;
|
||||||
|
|
||||||
|
// Generate new access token
|
||||||
|
let generated = deps.auth.generate_token(&session.user_id).await?;
|
||||||
|
|
||||||
|
// Create new refresh session
|
||||||
|
let new_refresh_token = Uuid::new_v4().to_string();
|
||||||
|
let refresh_expires = Utc::now() + Duration::seconds(deps.config.refresh_ttl_seconds as i64);
|
||||||
|
let new_session = RefreshSession {
|
||||||
|
id: Uuid::new_v4(),
|
||||||
|
user_id: session.user_id,
|
||||||
|
token: new_refresh_token.clone(),
|
||||||
|
expires_at: refresh_expires,
|
||||||
|
created_at: Utc::now(),
|
||||||
|
};
|
||||||
|
deps.refresh_session.create(&new_session).await?;
|
||||||
|
|
||||||
|
Ok(RefreshResult {
|
||||||
|
token: generated.token,
|
||||||
|
refresh_token: new_refresh_token,
|
||||||
|
expires_at: generated.expires_at,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "tests/refresh.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -4,10 +4,10 @@ use domain::{
|
|||||||
value_objects::{Email, Password, Username},
|
value_objects::{Email, Password, Username},
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::{auth::commands::RegisterCommand, context::AppContext};
|
use crate::auth::{commands::RegisterCommand, deps::RegisterDeps};
|
||||||
|
|
||||||
pub async fn execute(ctx: &AppContext, cmd: RegisterCommand) -> Result<(), DomainError> {
|
pub async fn execute(deps: &RegisterDeps, cmd: RegisterCommand) -> Result<(), DomainError> {
|
||||||
if !ctx.config.allow_registration {
|
if !deps.config.allow_registration {
|
||||||
return Err(DomainError::Unauthorized("Registration is disabled".into()));
|
return Err(DomainError::Unauthorized("Registration is disabled".into()));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -15,21 +15,20 @@ pub async fn execute(ctx: &AppContext, cmd: RegisterCommand) -> Result<(), Domai
|
|||||||
let email = Email::new(cmd.email)?;
|
let email = Email::new(cmd.email)?;
|
||||||
let username = Username::new(cmd.username)?;
|
let username = Username::new(cmd.username)?;
|
||||||
|
|
||||||
if ctx.repos.user.find_by_email(&email).await?.is_some() {
|
if deps.user.find_by_email(&email).await?.is_some() {
|
||||||
return Err(DomainError::ValidationError(
|
return Err(DomainError::ValidationError(
|
||||||
"Email already registered".into(),
|
"Email already registered".into(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
if ctx.repos.user.find_by_username(&username).await?.is_some() {
|
if deps.user.find_by_username(&username).await?.is_some() {
|
||||||
return Err(DomainError::ValidationError(
|
return Err(DomainError::ValidationError(
|
||||||
"Username already taken".into(),
|
"Username already taken".into(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let hash = ctx.services.password_hasher.hash(password.value()).await?;
|
let hash = deps.password_hasher.hash(password.value()).await?;
|
||||||
ctx.repos
|
deps.user
|
||||||
.user
|
|
||||||
.save(&User::new(email, username, hash, cmd.role))
|
.save(&User::new(email, username, hash, cmd.role))
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,18 +1,25 @@
|
|||||||
use domain::errors::DomainError;
|
use domain::errors::DomainError;
|
||||||
|
|
||||||
use crate::{
|
use crate::auth::{
|
||||||
auth::commands::RegisterAndLoginCommand,
|
commands::{RegisterAndLoginCommand, RegisterCommand},
|
||||||
auth::{login, register},
|
deps::{LoginDeps, RegisterAndLoginDeps, RegisterDeps},
|
||||||
context::AppContext,
|
login::{self, LoginResult},
|
||||||
|
queries::LoginQuery,
|
||||||
|
register,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub async fn execute(
|
pub async fn execute(
|
||||||
ctx: &AppContext,
|
deps: &RegisterAndLoginDeps,
|
||||||
cmd: RegisterAndLoginCommand,
|
cmd: RegisterAndLoginCommand,
|
||||||
) -> Result<login::LoginResult, DomainError> {
|
) -> Result<LoginResult, DomainError> {
|
||||||
|
let reg_deps = RegisterDeps {
|
||||||
|
user: deps.user.clone(),
|
||||||
|
password_hasher: deps.password_hasher.clone(),
|
||||||
|
config: deps.config.clone(),
|
||||||
|
};
|
||||||
register::execute(
|
register::execute(
|
||||||
ctx,
|
®_deps,
|
||||||
crate::auth::commands::RegisterCommand {
|
RegisterCommand {
|
||||||
email: cmd.email.clone(),
|
email: cmd.email.clone(),
|
||||||
username: cmd.username,
|
username: cmd.username,
|
||||||
password: cmd.password.clone(),
|
password: cmd.password.clone(),
|
||||||
@@ -21,9 +28,16 @@ pub async fn execute(
|
|||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
|
let log_deps = LoginDeps {
|
||||||
|
user: deps.user.clone(),
|
||||||
|
password_hasher: deps.password_hasher.clone(),
|
||||||
|
auth: deps.auth.clone(),
|
||||||
|
refresh_session: deps.refresh_session.clone(),
|
||||||
|
config: deps.config.clone(),
|
||||||
|
};
|
||||||
login::execute(
|
login::execute(
|
||||||
ctx,
|
&log_deps,
|
||||||
crate::auth::queries::LoginQuery {
|
LoginQuery {
|
||||||
email: cmd.email,
|
email: cmd.email,
|
||||||
password: cmd.password,
|
password: cmd.password,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -4,15 +4,24 @@ use domain::models::UserRole;
|
|||||||
use domain::testing::InMemoryUserRepository;
|
use domain::testing::InMemoryUserRepository;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
auth::commands::RegisterCommand,
|
auth::{
|
||||||
auth::queries::LoginQuery,
|
commands::RegisterCommand,
|
||||||
auth::{login, register},
|
deps::{LoginDeps, RegisterDeps},
|
||||||
|
login,
|
||||||
|
queries::LoginQuery,
|
||||||
|
register,
|
||||||
|
},
|
||||||
test_helpers::TestContextBuilder,
|
test_helpers::TestContextBuilder,
|
||||||
};
|
};
|
||||||
|
|
||||||
async fn setup_user(ctx: &crate::context::AppContext, email: &str, password: &str) {
|
async fn setup_user(b: &TestContextBuilder, email: &str, password: &str) {
|
||||||
|
let deps = RegisterDeps {
|
||||||
|
user: b.user_repo.clone(),
|
||||||
|
password_hasher: b.password_hasher.clone(),
|
||||||
|
config: b.config.clone(),
|
||||||
|
};
|
||||||
register::execute(
|
register::execute(
|
||||||
ctx,
|
&deps,
|
||||||
RegisterCommand {
|
RegisterCommand {
|
||||||
email: email.to_string(),
|
email: email.to_string(),
|
||||||
username: "testuser".to_string(),
|
username: "testuser".to_string(),
|
||||||
@@ -27,14 +36,18 @@ async fn setup_user(ctx: &crate::context::AppContext, email: &str, password: &st
|
|||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn test_login_valid_credentials_returns_token() {
|
async fn test_login_valid_credentials_returns_token() {
|
||||||
let users = InMemoryUserRepository::new();
|
let users = InMemoryUserRepository::new();
|
||||||
let ctx = TestContextBuilder::new()
|
let b = TestContextBuilder::new().with_users(Arc::clone(&users) as _);
|
||||||
.with_users(Arc::clone(&users) as _)
|
setup_user(&b, "carol@example.com", "secret123").await;
|
||||||
.build();
|
|
||||||
|
|
||||||
setup_user(&ctx, "carol@example.com", "secret123").await;
|
|
||||||
|
|
||||||
|
let deps = LoginDeps {
|
||||||
|
user: b.user_repo.clone(),
|
||||||
|
password_hasher: b.password_hasher.clone(),
|
||||||
|
auth: b.auth_service.clone(),
|
||||||
|
refresh_session: b.refresh_session_repo.clone(),
|
||||||
|
config: b.config.clone(),
|
||||||
|
};
|
||||||
let result = login::execute(
|
let result = login::execute(
|
||||||
&ctx,
|
&deps,
|
||||||
LoginQuery {
|
LoginQuery {
|
||||||
email: "carol@example.com".into(),
|
email: "carol@example.com".into(),
|
||||||
password: "secret123".into(),
|
password: "secret123".into(),
|
||||||
@@ -44,20 +57,25 @@ async fn test_login_valid_credentials_returns_token() {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
assert!(!result.token.is_empty());
|
assert!(!result.token.is_empty());
|
||||||
|
assert!(!result.refresh_token.is_empty());
|
||||||
assert_eq!(result.email, "carol@example.com");
|
assert_eq!(result.email, "carol@example.com");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn test_login_wrong_password_fails() {
|
async fn test_login_wrong_password_fails() {
|
||||||
let users = InMemoryUserRepository::new();
|
let users = InMemoryUserRepository::new();
|
||||||
let ctx = TestContextBuilder::new()
|
let b = TestContextBuilder::new().with_users(Arc::clone(&users) as _);
|
||||||
.with_users(Arc::clone(&users) as _)
|
setup_user(&b, "dave@example.com", "correct_password").await;
|
||||||
.build();
|
|
||||||
|
|
||||||
setup_user(&ctx, "dave@example.com", "correct_password").await;
|
|
||||||
|
|
||||||
|
let deps = LoginDeps {
|
||||||
|
user: b.user_repo.clone(),
|
||||||
|
password_hasher: b.password_hasher.clone(),
|
||||||
|
auth: b.auth_service.clone(),
|
||||||
|
refresh_session: b.refresh_session_repo.clone(),
|
||||||
|
config: b.config.clone(),
|
||||||
|
};
|
||||||
let result = login::execute(
|
let result = login::execute(
|
||||||
&ctx,
|
&deps,
|
||||||
LoginQuery {
|
LoginQuery {
|
||||||
email: "dave@example.com".into(),
|
email: "dave@example.com".into(),
|
||||||
password: "wrong_password".into(),
|
password: "wrong_password".into(),
|
||||||
@@ -70,10 +88,16 @@ async fn test_login_wrong_password_fails() {
|
|||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn test_login_unknown_email_fails() {
|
async fn test_login_unknown_email_fails() {
|
||||||
let ctx = TestContextBuilder::new().build();
|
let b = TestContextBuilder::new();
|
||||||
|
let deps = LoginDeps {
|
||||||
|
user: b.user_repo.clone(),
|
||||||
|
password_hasher: b.password_hasher.clone(),
|
||||||
|
auth: b.auth_service.clone(),
|
||||||
|
refresh_session: b.refresh_session_repo.clone(),
|
||||||
|
config: b.config.clone(),
|
||||||
|
};
|
||||||
let result = login::execute(
|
let result = login::execute(
|
||||||
&ctx,
|
&deps,
|
||||||
LoginQuery {
|
LoginQuery {
|
||||||
email: "nobody@example.com".into(),
|
email: "nobody@example.com".into(),
|
||||||
password: "anything".into(),
|
password: "anything".into(),
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user