Compare commits
120 Commits
master
...
87cb36f9fe
| Author | SHA1 | Date | |
|---|---|---|---|
| 87cb36f9fe | |||
| bacf7b7252 | |||
| c4b6d52196 | |||
| ffb323dbbf | |||
| 0a18992a73 | |||
| b0ce316c30 | |||
| 0d3c2c937d | |||
| 86909ecede | |||
| 482575aed0 | |||
| 377ee1d176 | |||
| 9cda5b4681 | |||
| 74fb893751 | |||
| 32b114cecd | |||
| bd571b3b51 | |||
| f226071cbd | |||
| aaa9cb0a1e | |||
| 31dba4ca95 | |||
| 1b3f906312 | |||
| 465d233ae9 | |||
| 1f03889b30 | |||
| 4159e60148 | |||
| d66a89059d | |||
| b3c243257d | |||
| e1f2442e77 | |||
| 7a66661932 | |||
| b30a6a102b | |||
| 38a3aa6bbf | |||
| 3135a15cb3 | |||
| d083f8ae3d | |||
| 874c406d4a | |||
| 78e1f4ef72 | |||
| cf74b06b4a | |||
| 317898d51b | |||
| 790bb6fbb5 | |||
| 658df38788 | |||
| cff0f854fa | |||
| 66ade70273 | |||
| cbd2ac5b3e | |||
| 0433cd4d9b | |||
| b5a8ea2395 | |||
| 49b79799c1 | |||
| f4aba551a2 | |||
| 91df35dbd3 | |||
| 623f90e43f | |||
| e28f628c80 | |||
| 60c25d4c24 | |||
| 22aafe99be | |||
| 0ff22cca5f | |||
| ccc39e27e4 | |||
| 76319756f4 | |||
| 7703227970 | |||
| b9933bb48d | |||
| 0c48708ce6 | |||
| a2a889bced | |||
| a4846f3bea | |||
| 27be840faa | |||
| 965fc0eda8 | |||
| d700b85337 | |||
| ffbab75910 | |||
| dda7c40f7f | |||
| 1b827b1bdd | |||
| 1ee6873a60 | |||
| 7352b533ff | |||
| 85e254fee2 | |||
| fa8221322d | |||
| 38da37de55 | |||
| f3dedbad8a | |||
| d468ce131f | |||
| d034af9e9c | |||
| 59d308f41b | |||
| bbb2ee00d6 | |||
| 5dd9aac68d | |||
| 6dcc4c8317 | |||
| e31d99a240 | |||
| 41fec1efa5 | |||
| 160c08d1c4 | |||
| 7aa6d7bf4d | |||
| 144f2f8e0c | |||
| cff64f7a6b | |||
| 5baff54cb9 | |||
| f94d2db8b1 | |||
| 48875a6e86 | |||
| 9387ae705b | |||
| 9871e21bc0 | |||
| fa8efbaa23 | |||
| d769a5b55c | |||
| 8e1fb1a974 | |||
| 6145b873f5 | |||
| cc668ae44d | |||
| e5097c22dd | |||
| 450468ef3d | |||
| 6e7c6467a7 | |||
| 7f815f8207 | |||
| 5df89200d4 | |||
| eb273dc277 | |||
| 5689db0ad7 | |||
| 5c70b8b8be | |||
| 4c547df04e | |||
| 602df8df22 | |||
| 5b69a3a7c0 | |||
| a38f78d261 | |||
| 17f90726e8 | |||
| 563f33212e | |||
| 8e5ac9f433 | |||
| f790fa2a0f | |||
| edcf3c1170 | |||
| 1985d2c57f | |||
| f0b3d8ad90 | |||
| da72ab1446 | |||
| 93c65cd155 | |||
| ba42d3d445 | |||
| 819332522a | |||
| 79a06e6844 | |||
| 97a496553a | |||
| 5a58625265 | |||
| 6d9ac07dfc | |||
| b6a7cf9417 | |||
| c4b39c9410 | |||
| f60cc368b6 | |||
| 65bab7fd44 |
2
.cargo/config.toml
Normal file
2
.cargo/config.toml
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
[env]
|
||||||
|
SQLX_OFFLINE = "true"
|
||||||
10
.dockerignore
Normal file
10
.dockerignore
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
target/
|
||||||
|
.git/
|
||||||
|
.env
|
||||||
|
*.db
|
||||||
|
*.db-shm
|
||||||
|
*.db-wal
|
||||||
|
.cargo/
|
||||||
|
.sqlx/
|
||||||
|
docs/
|
||||||
|
dev.db
|
||||||
34
.env.example
34
.env.example
@@ -0,0 +1,34 @@
|
|||||||
|
# Database
|
||||||
|
DATABASE_URL=sqlite://movies.db
|
||||||
|
|
||||||
|
# Authentication
|
||||||
|
JWT_SECRET=change-me
|
||||||
|
JWT_TTL_SECONDS=86400
|
||||||
|
|
||||||
|
# OMDb metadata
|
||||||
|
OMDB_API_KEY=your-key
|
||||||
|
|
||||||
|
# Poster storage — Option A (local) is active. To use S3, comment it out and uncomment Option B:
|
||||||
|
|
||||||
|
# Option A: local filesystem (zero external dependencies)
|
||||||
|
POSTER_STORAGE_BACKEND=local
|
||||||
|
POSTER_STORAGE_PATH=./posters
|
||||||
|
|
||||||
|
# Option B: S3-compatible (MinIO, AWS S3, etc.)
|
||||||
|
# POSTER_STORAGE_BACKEND=s3
|
||||||
|
# MINIO_ENDPOINT=http://localhost:9000
|
||||||
|
# MINIO_BUCKET=posters
|
||||||
|
# MINIO_REGION=minio
|
||||||
|
# MINIO_ACCESS_KEY_ID=minioadmin
|
||||||
|
# MINIO_SECRET_ACCESS_KEY=minioadmin
|
||||||
|
|
||||||
|
# Optional
|
||||||
|
HOST=0.0.0.0
|
||||||
|
PORT=3000
|
||||||
|
BASE_URL=http://localhost:3000
|
||||||
|
SECURE_COOKIES=false
|
||||||
|
ALLOW_REGISTRATION=false
|
||||||
|
RATE_LIMIT=20
|
||||||
|
POSTER_FETCH_TIMEOUT_SECONDS=30
|
||||||
|
EVENT_CHANNEL_BUFFER=128
|
||||||
|
RUST_LOG=presentation=debug,tower_http=debug
|
||||||
|
|||||||
8
.gitignore
vendored
8
.gitignore
vendored
@@ -6,3 +6,11 @@
|
|||||||
|
|
||||||
.env
|
.env
|
||||||
.env.prod
|
.env.prod
|
||||||
|
|
||||||
|
*.db
|
||||||
|
*db-shm
|
||||||
|
*db-wal
|
||||||
|
|
||||||
|
.worktrees/
|
||||||
|
.superpowers/
|
||||||
|
docs/
|
||||||
|
|||||||
98
.sqlx/query-05d958c1fa38095ae2b5b81ede48fc85702d8c39c6301839de7b4d27f4a4d41b.json
generated
Normal file
98
.sqlx/query-05d958c1fa38095ae2b5b81ede48fc85702d8c39c6301839de7b4d27f4a4d41b.json
generated
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,\n r.id AS review_id, r.movie_id, r.user_id, r.rating, r.comment, r.watched_at, r.created_at, r.remote_actor_url\n FROM reviews r\n INNER JOIN movies m ON m.id = r.movie_id\n WHERE r.movie_id = ?\n ORDER BY r.watched_at DESC\n LIMIT ? OFFSET ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "external_metadata_id",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "title",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "release_year",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "director",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "poster_path",
|
||||||
|
"ordinal": 5,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "review_id",
|
||||||
|
"ordinal": 6,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "movie_id",
|
||||||
|
"ordinal": 7,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "user_id",
|
||||||
|
"ordinal": 8,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "rating",
|
||||||
|
"ordinal": 9,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "comment",
|
||||||
|
"ordinal": 10,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "watched_at",
|
||||||
|
"ordinal": 11,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_at",
|
||||||
|
"ordinal": 12,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "remote_actor_url",
|
||||||
|
"ordinal": 13,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 3
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "05d958c1fa38095ae2b5b81ede48fc85702d8c39c6301839de7b4d27f4a4d41b"
|
||||||
|
}
|
||||||
20
.sqlx/query-0963b9661182e139cd760bbabb0d6ea3a301a2a3adbdfdda4a88f333a1144c77.json
generated
Normal file
20
.sqlx/query-0963b9661182e139cd760bbabb0d6ea3a301a2a3adbdfdda4a88f333a1144c77.json
generated
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT COUNT(*) FROM reviews",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "COUNT(*)",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Integer"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 0
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "0963b9661182e139cd760bbabb0d6ea3a301a2a3adbdfdda4a88f333a1144c77"
|
||||||
|
}
|
||||||
20
.sqlx/query-0cd1a7b7255a0ee753deffab7cbb48027d22900a570b98a636c780cb3e2efd23.json
generated
Normal file
20
.sqlx/query-0cd1a7b7255a0ee753deffab7cbb48027d22900a570b98a636c780cb3e2efd23.json
generated
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT COUNT(*) FROM reviews WHERE user_id = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "COUNT(*)",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Integer"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "0cd1a7b7255a0ee753deffab7cbb48027d22900a570b98a636c780cb3e2efd23"
|
||||||
|
}
|
||||||
38
.sqlx/query-0e36417429360e7e332f60768c2283a78b18c57cb72978921ccc0df963a756ba.json
generated
Normal file
38
.sqlx/query-0e36417429360e7e332f60768c2283a78b18c57cb72978921ccc0df963a756ba.json
generated
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT id, email, username, password_hash FROM users WHERE username = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "email",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "username",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "password_hash",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "0e36417429360e7e332f60768c2283a78b18c57cb72978921ccc0df963a756ba"
|
||||||
|
}
|
||||||
98
.sqlx/query-106b5b65162314c47217c26b7e89194094e10122ea596e8d9323968e600635a9.json
generated
Normal file
98
.sqlx/query-106b5b65162314c47217c26b7e89194094e10122ea596e8d9323968e600635a9.json
generated
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,\n r.id AS review_id, r.movie_id, r.user_id, r.rating, r.comment, r.watched_at, r.created_at, r.remote_actor_url\n FROM reviews r\n INNER JOIN movies m ON m.id = r.movie_id\n WHERE r.user_id = ?\n ORDER BY r.watched_at DESC",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "external_metadata_id",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "title",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "release_year",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "director",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "poster_path",
|
||||||
|
"ordinal": 5,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "review_id",
|
||||||
|
"ordinal": 6,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "movie_id",
|
||||||
|
"ordinal": 7,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "user_id",
|
||||||
|
"ordinal": 8,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "rating",
|
||||||
|
"ordinal": 9,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "comment",
|
||||||
|
"ordinal": 10,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "watched_at",
|
||||||
|
"ordinal": 11,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_at",
|
||||||
|
"ordinal": 12,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "remote_actor_url",
|
||||||
|
"ordinal": 13,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "106b5b65162314c47217c26b7e89194094e10122ea596e8d9323968e600635a9"
|
||||||
|
}
|
||||||
12
.sqlx/query-21751a2efb5fc58f5c1057f332f537419b7067ff665a03e248e6ea0fe7b6919b.json
generated
Normal file
12
.sqlx/query-21751a2efb5fc58f5c1057f332f537419b7067ff665a03e248e6ea0fe7b6919b.json
generated
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "INSERT INTO users (id, email, username, password_hash, created_at) VALUES (?, ?, ?, ?, ?)",
|
||||||
|
"describe": {
|
||||||
|
"columns": [],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 5
|
||||||
|
},
|
||||||
|
"nullable": []
|
||||||
|
},
|
||||||
|
"hash": "21751a2efb5fc58f5c1057f332f537419b7067ff665a03e248e6ea0fe7b6919b"
|
||||||
|
}
|
||||||
98
.sqlx/query-25fd01355c929a83daf2c802b8ae3adaa4ce73fc037e2bf2a87d60187aeb7361.json
generated
Normal file
98
.sqlx/query-25fd01355c929a83daf2c802b8ae3adaa4ce73fc037e2bf2a87d60187aeb7361.json
generated
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,\n r.id AS review_id, r.movie_id, r.user_id, r.rating, r.comment, r.watched_at, r.created_at, r.remote_actor_url\n FROM reviews r\n INNER JOIN movies m ON m.id = r.movie_id\n ORDER BY r.watched_at ASC\n LIMIT ? OFFSET ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "external_metadata_id",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "title",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "release_year",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "director",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "poster_path",
|
||||||
|
"ordinal": 5,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "review_id",
|
||||||
|
"ordinal": 6,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "movie_id",
|
||||||
|
"ordinal": 7,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "user_id",
|
||||||
|
"ordinal": 8,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "rating",
|
||||||
|
"ordinal": 9,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "comment",
|
||||||
|
"ordinal": 10,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "watched_at",
|
||||||
|
"ordinal": 11,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_at",
|
||||||
|
"ordinal": 12,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "remote_actor_url",
|
||||||
|
"ordinal": 13,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 2
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "25fd01355c929a83daf2c802b8ae3adaa4ce73fc037e2bf2a87d60187aeb7361"
|
||||||
|
}
|
||||||
38
.sqlx/query-2c7353f34c4748d4d4be6abbf343fa7ea30eeb985c4bfd12b0fc3997d1ba03bb.json
generated
Normal file
38
.sqlx/query-2c7353f34c4748d4d4be6abbf343fa7ea30eeb985c4bfd12b0fc3997d1ba03bb.json
generated
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT u.id AS \"id!: String\",\n u.email AS \"email!: String\",\n COUNT(DISTINCT r.movie_id) AS \"total_movies!: i64\",\n AVG(CAST(r.rating AS REAL)) AS avg_rating\n FROM users u\n LEFT JOIN reviews r ON r.user_id = u.id AND r.remote_actor_url IS NULL\n GROUP BY u.id, u.email\n ORDER BY u.email ASC",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id!: String",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "email!: String",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "total_movies!: i64",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "avg_rating",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Float"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 0
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "2c7353f34c4748d4d4be6abbf343fa7ea30eeb985c4bfd12b0fc3997d1ba03bb"
|
||||||
|
}
|
||||||
50
.sqlx/query-3047579c6ed13ce87aad9b9ce6300c02f0df3516979518976e13f9d9abc6a403.json
generated
Normal file
50
.sqlx/query-3047579c6ed13ce87aad9b9ce6300c02f0df3516979518976e13f9d9abc6a403.json
generated
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT id, external_metadata_id, title, release_year, director, poster_path\n FROM movies WHERE title = ? AND release_year = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "external_metadata_id",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "title",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "release_year",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "director",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "poster_path",
|
||||||
|
"ordinal": 5,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 2
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "3047579c6ed13ce87aad9b9ce6300c02f0df3516979518976e13f9d9abc6a403"
|
||||||
|
}
|
||||||
50
.sqlx/query-33d0dae7d16b0635c1c7eb5afd10824bb55af7cc7a854f590d326622863759d1.json
generated
Normal file
50
.sqlx/query-33d0dae7d16b0635c1c7eb5afd10824bb55af7cc7a854f590d326622863759d1.json
generated
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT id, external_metadata_id, title, release_year, director, poster_path\n FROM movies WHERE id = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "external_metadata_id",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "title",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "release_year",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "director",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "poster_path",
|
||||||
|
"ordinal": 5,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "33d0dae7d16b0635c1c7eb5afd10824bb55af7cc7a854f590d326622863759d1"
|
||||||
|
}
|
||||||
98
.sqlx/query-4ad3b7d450e46e8d4982a0517c7345b386fc7dc6cf3e72c924e2f5da49dfb469.json
generated
Normal file
98
.sqlx/query-4ad3b7d450e46e8d4982a0517c7345b386fc7dc6cf3e72c924e2f5da49dfb469.json
generated
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,\n r.id AS review_id, r.movie_id, r.user_id, r.rating, r.comment, r.watched_at, r.created_at, r.remote_actor_url\n FROM reviews r\n INNER JOIN movies m ON m.id = r.movie_id\n WHERE r.user_id = ?\n ORDER BY r.rating DESC, 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": "4ad3b7d450e46e8d4982a0517c7345b386fc7dc6cf3e72c924e2f5da49dfb469"
|
||||||
|
}
|
||||||
20
.sqlx/query-4b3074b532342c6356ee0e8e4d8c4a830f016234bb690e1f6240f02824d6d84f.json
generated
Normal file
20
.sqlx/query-4b3074b532342c6356ee0e8e4d8c4a830f016234bb690e1f6240f02824d6d84f.json
generated
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT COUNT(*) FROM reviews WHERE movie_id = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "COUNT(*)",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Integer"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "4b3074b532342c6356ee0e8e4d8c4a830f016234bb690e1f6240f02824d6d84f"
|
||||||
|
}
|
||||||
98
.sqlx/query-4c235060b78cc5c73e0400b39472467a36d3920ff4c020f5461b2cdb04361888.json
generated
Normal file
98
.sqlx/query-4c235060b78cc5c73e0400b39472467a36d3920ff4c020f5461b2cdb04361888.json
generated
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,\n r.id AS review_id, r.movie_id, r.user_id, r.rating, r.comment, r.watched_at, r.created_at, r.remote_actor_url\n FROM reviews r\n INNER JOIN movies m ON m.id = r.movie_id\n WHERE r.user_id = ?\n ORDER BY r.watched_at DESC\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": "4c235060b78cc5c73e0400b39472467a36d3920ff4c020f5461b2cdb04361888"
|
||||||
|
}
|
||||||
20
.sqlx/query-4d85f0ff9732576bba77dc84d3885a0002c2b600c34ba4d99f1e1c5e99f35e75.json
generated
Normal file
20
.sqlx/query-4d85f0ff9732576bba77dc84d3885a0002c2b600c34ba4d99f1e1c5e99f35e75.json
generated
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT strftime('%Y-%m', watched_at) AS month\n FROM reviews\n WHERE user_id = ?\n GROUP BY month\n ORDER BY COUNT(*) DESC\n LIMIT 1",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "month",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "4d85f0ff9732576bba77dc84d3885a0002c2b600c34ba4d99f1e1c5e99f35e75"
|
||||||
|
}
|
||||||
38
.sqlx/query-4eeae6aa887319cab4a9fd673c3a75dec1e6681739d722481233a3d9e7a01955.json
generated
Normal file
38
.sqlx/query-4eeae6aa887319cab4a9fd673c3a75dec1e6681739d722481233a3d9e7a01955.json
generated
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT id, email, username, password_hash 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"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "4eeae6aa887319cab4a9fd673c3a75dec1e6681739d722481233a3d9e7a01955"
|
||||||
|
}
|
||||||
104
.sqlx/query-70843058606802f0958d216a47473f78b29854518c48c2da3cc11a94d6d37bb1.json
generated
Normal file
104
.sqlx/query-70843058606802f0958d216a47473f78b29854518c48c2da3cc11a94d6d37bb1.json
generated
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
{
|
||||||
|
"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 COALESCE(u.email, r.remote_actor_url) AS \"user_email!: String\"\n FROM reviews r\n INNER JOIN movies m ON m.id = r.movie_id\n LEFT JOIN users u ON u.id = r.user_id\n ORDER BY r.watched_at DESC\n LIMIT ? OFFSET ?",
|
||||||
|
"describe": {
|
||||||
|
"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"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "user_email!: String",
|
||||||
|
"ordinal": 14,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 2
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "70843058606802f0958d216a47473f78b29854518c48c2da3cc11a94d6d37bb1"
|
||||||
|
}
|
||||||
50
.sqlx/query-7bc4aebcb94547976d3d7e063e4e908fc22b977b3cbf063ee93ffe4648c42011.json
generated
Normal file
50
.sqlx/query-7bc4aebcb94547976d3d7e063e4e908fc22b977b3cbf063ee93ffe4648c42011.json
generated
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT id, external_metadata_id, title, release_year, director, poster_path\n FROM movies WHERE external_metadata_id = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "external_metadata_id",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "title",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "release_year",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "director",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "poster_path",
|
||||||
|
"ordinal": 5,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "7bc4aebcb94547976d3d7e063e4e908fc22b977b3cbf063ee93ffe4648c42011"
|
||||||
|
}
|
||||||
12
.sqlx/query-7d7e23355ee0e442f2aa27e898dcfa40bdc4b09391afe04325f076157d9d84aa.json
generated
Normal file
12
.sqlx/query-7d7e23355ee0e442f2aa27e898dcfa40bdc4b09391afe04325f076157d9d84aa.json
generated
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "INSERT INTO movies (id, external_metadata_id, title, release_year, director, poster_path)\n VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n external_metadata_id = excluded.external_metadata_id,\n title = excluded.title,\n release_year = excluded.release_year,\n director = excluded.director,\n poster_path = excluded.poster_path",
|
||||||
|
"describe": {
|
||||||
|
"columns": [],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 6
|
||||||
|
},
|
||||||
|
"nullable": []
|
||||||
|
},
|
||||||
|
"hash": "7d7e23355ee0e442f2aa27e898dcfa40bdc4b09391afe04325f076157d9d84aa"
|
||||||
|
}
|
||||||
62
.sqlx/query-7ff439f22f880f999a72aad1359eb8fec11fe868b940faee5a351795caaa2357.json
generated
Normal file
62
.sqlx/query-7ff439f22f880f999a72aad1359eb8fec11fe868b940faee5a351795caaa2357.json
generated
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT id, movie_id, user_id, rating, comment, watched_at, created_at, remote_actor_url\n FROM reviews WHERE movie_id = ? ORDER BY watched_at ASC",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "movie_id",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "user_id",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "rating",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "comment",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "watched_at",
|
||||||
|
"ordinal": 5,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_at",
|
||||||
|
"ordinal": 6,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "remote_actor_url",
|
||||||
|
"ordinal": 7,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "7ff439f22f880f999a72aad1359eb8fec11fe868b940faee5a351795caaa2357"
|
||||||
|
}
|
||||||
98
.sqlx/query-8a70f21c39d203867c06dc0bf74a54745b3331b84ce9a2178f7812f1ed7262cc.json
generated
Normal file
98
.sqlx/query-8a70f21c39d203867c06dc0bf74a54745b3331b84ce9a2178f7812f1ed7262cc.json
generated
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,\n r.id AS review_id, r.movie_id, r.user_id, r.rating, r.comment, r.watched_at, r.created_at, r.remote_actor_url\n FROM reviews r\n INNER JOIN movies m ON m.id = r.movie_id\n WHERE r.movie_id = ?\n ORDER BY r.watched_at ASC\n LIMIT ? OFFSET ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "external_metadata_id",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "title",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "release_year",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "director",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "poster_path",
|
||||||
|
"ordinal": 5,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "review_id",
|
||||||
|
"ordinal": 6,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "movie_id",
|
||||||
|
"ordinal": 7,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "user_id",
|
||||||
|
"ordinal": 8,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "rating",
|
||||||
|
"ordinal": 9,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "comment",
|
||||||
|
"ordinal": 10,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "watched_at",
|
||||||
|
"ordinal": 11,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_at",
|
||||||
|
"ordinal": 12,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "remote_actor_url",
|
||||||
|
"ordinal": 13,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 3
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "8a70f21c39d203867c06dc0bf74a54745b3331b84ce9a2178f7812f1ed7262cc"
|
||||||
|
}
|
||||||
26
.sqlx/query-a01336632a54099e31686a9cbe6fc53fef1299fc7c7b52be44f99c2302490a22.json
generated
Normal file
26
.sqlx/query-a01336632a54099e31686a9cbe6fc53fef1299fc7c7b52be44f99c2302490a22.json
generated
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT COUNT(DISTINCT movie_id) AS \"total!: i64\",\n AVG(CAST(rating AS REAL)) AS avg_rating\n FROM reviews WHERE user_id = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "total!: i64",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "avg_rating",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Float"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "a01336632a54099e31686a9cbe6fc53fef1299fc7c7b52be44f99c2302490a22"
|
||||||
|
}
|
||||||
98
.sqlx/query-a7c424c26663e4e51b1c563fa977f28e1d55234a242a7ddba50db13cf73b488d.json
generated
Normal file
98
.sqlx/query-a7c424c26663e4e51b1c563fa977f28e1d55234a242a7ddba50db13cf73b488d.json
generated
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT m.id, m.external_metadata_id, m.title, m.release_year, m.director, m.poster_path,\n r.id AS review_id, r.movie_id, r.user_id, r.rating, r.comment, r.watched_at, r.created_at, r.remote_actor_url\n FROM reviews r\n INNER JOIN movies m ON m.id = r.movie_id\n ORDER BY r.watched_at DESC\n LIMIT ? OFFSET ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "external_metadata_id",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "title",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "release_year",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "director",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "poster_path",
|
||||||
|
"ordinal": 5,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "review_id",
|
||||||
|
"ordinal": 6,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "movie_id",
|
||||||
|
"ordinal": 7,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "user_id",
|
||||||
|
"ordinal": 8,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "rating",
|
||||||
|
"ordinal": 9,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "comment",
|
||||||
|
"ordinal": 10,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "watched_at",
|
||||||
|
"ordinal": 11,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_at",
|
||||||
|
"ordinal": 12,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "remote_actor_url",
|
||||||
|
"ordinal": 13,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 2
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "a7c424c26663e4e51b1c563fa977f28e1d55234a242a7ddba50db13cf73b488d"
|
||||||
|
}
|
||||||
26
.sqlx/query-aca9e7aaa32c23b4de3f5048d60340e978d31a36be9121da3c59378f2fc1ed8e.json
generated
Normal file
26
.sqlx/query-aca9e7aaa32c23b4de3f5048d60340e978d31a36be9121da3c59378f2fc1ed8e.json
generated
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT m.director AS \"director!\",\n COUNT(*) AS \"count!: i64\"\n FROM reviews r\n INNER JOIN movies m ON m.id = r.movie_id\n WHERE r.user_id = ? AND m.director IS NOT NULL\n GROUP BY m.director\n ORDER BY COUNT(*) DESC\n LIMIT 5",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "director!",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "count!: i64",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Integer"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
true,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "aca9e7aaa32c23b4de3f5048d60340e978d31a36be9121da3c59378f2fc1ed8e"
|
||||||
|
}
|
||||||
62
.sqlx/query-ae983138ad90fda3794b784fbf62c31fddcf182850782e9bfbc4ff3ee8b7d4bb.json
generated
Normal file
62
.sqlx/query-ae983138ad90fda3794b784fbf62c31fddcf182850782e9bfbc4ff3ee8b7d4bb.json
generated
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT id, movie_id, user_id, rating, comment, watched_at, created_at, remote_actor_url\n FROM reviews WHERE id = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "movie_id",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "user_id",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "rating",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "comment",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "watched_at",
|
||||||
|
"ordinal": 5,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "created_at",
|
||||||
|
"ordinal": 6,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "remote_actor_url",
|
||||||
|
"ordinal": 7,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "ae983138ad90fda3794b784fbf62c31fddcf182850782e9bfbc4ff3ee8b7d4bb"
|
||||||
|
}
|
||||||
12
.sqlx/query-cca022ac6275f2b1aaf63a14420897074c8ff4cdd1d3e9a13ef4b9dd5346d12a.json
generated
Normal file
12
.sqlx/query-cca022ac6275f2b1aaf63a14420897074c8ff4cdd1d3e9a13ef4b9dd5346d12a.json
generated
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "INSERT INTO reviews (id, movie_id, user_id, rating, comment, watched_at, created_at, remote_actor_url)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||||
|
"describe": {
|
||||||
|
"columns": [],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 8
|
||||||
|
},
|
||||||
|
"nullable": []
|
||||||
|
},
|
||||||
|
"hash": "cca022ac6275f2b1aaf63a14420897074c8ff4cdd1d3e9a13ef4b9dd5346d12a"
|
||||||
|
}
|
||||||
20
.sqlx/query-d5d2a81306488a8cee5654cea7e14d76d76ecc7d2190ffb73d12bec2874111d2.json
generated
Normal file
20
.sqlx/query-d5d2a81306488a8cee5654cea7e14d76d76ecc7d2190ffb73d12bec2874111d2.json
generated
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT m.director\n FROM reviews r\n INNER JOIN movies m ON m.id = r.movie_id\n WHERE r.user_id = ? AND m.director IS NOT NULL\n GROUP BY m.director\n ORDER BY COUNT(*) DESC\n LIMIT 1",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "director",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "d5d2a81306488a8cee5654cea7e14d76d76ecc7d2190ffb73d12bec2874111d2"
|
||||||
|
}
|
||||||
12
.sqlx/query-e431381ad41c1c2f7b9c89509d5e3f4c19cb52dcfff66772145cd80c53c16883.json
generated
Normal file
12
.sqlx/query-e431381ad41c1c2f7b9c89509d5e3f4c19cb52dcfff66772145cd80c53c16883.json
generated
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "DELETE FROM movies WHERE id = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": []
|
||||||
|
},
|
||||||
|
"hash": "e431381ad41c1c2f7b9c89509d5e3f4c19cb52dcfff66772145cd80c53c16883"
|
||||||
|
}
|
||||||
38
.sqlx/query-e51c6da943bd326a09632aa0cfd30c4f15ca554e229778b6cfa04889b7231b36.json
generated
Normal file
38
.sqlx/query-e51c6da943bd326a09632aa0cfd30c4f15ca554e229778b6cfa04889b7231b36.json
generated
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT id, email, username, password_hash 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"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "e51c6da943bd326a09632aa0cfd30c4f15ca554e229778b6cfa04889b7231b36"
|
||||||
|
}
|
||||||
12
.sqlx/query-f84e5483ca4210aec67b38cc1a9de4a42c12891025236abc48ea4f175292a6cc.json
generated
Normal file
12
.sqlx/query-f84e5483ca4210aec67b38cc1a9de4a42c12891025236abc48ea4f175292a6cc.json
generated
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "DELETE FROM reviews WHERE id = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": []
|
||||||
|
},
|
||||||
|
"hash": "f84e5483ca4210aec67b38cc1a9de4a42c12891025236abc48ea4f175292a6cc"
|
||||||
|
}
|
||||||
32
.sqlx/query-fdd5b522f26b5e0ce62f76c774fbb606fd9ee9884f4457831f693a0df3609317.json
generated
Normal file
32
.sqlx/query-fdd5b522f26b5e0ce62f76c774fbb606fd9ee9884f4457831f693a0df3609317.json
generated
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT strftime('%Y-%m', watched_at) AS \"month!\",\n AVG(CAST(rating AS REAL)) AS \"avg_rating!: f64\",\n COUNT(*) AS \"count!: i64\"\n FROM reviews\n WHERE user_id = ? AND watched_at >= datetime('now', '-12 months')\n GROUP BY \"month!\"\n ORDER BY \"month!\" ASC",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "month!",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "avg_rating!: f64",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Float"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "count!: i64",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Integer"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "fdd5b522f26b5e0ce62f76c774fbb606fd9ee9884f4457831f693a0df3609317"
|
||||||
|
}
|
||||||
3690
Cargo.lock
generated
3690
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
26
Cargo.toml
26
Cargo.toml
@@ -1,18 +1,25 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
members = [
|
members = [
|
||||||
"crates/adapters/auth",
|
"crates/adapters/auth",
|
||||||
|
"crates/adapters/event-publisher",
|
||||||
"crates/adapters/metadata",
|
"crates/adapters/metadata",
|
||||||
|
"crates/adapters/poster-fetcher",
|
||||||
|
"crates/adapters/poster-storage",
|
||||||
"crates/adapters/rss",
|
"crates/adapters/rss",
|
||||||
"crates/adapters/sqlite",
|
"crates/adapters/sqlite",
|
||||||
|
"crates/adapters/template-askama",
|
||||||
|
"crates/adapters/activitypub",
|
||||||
|
"crates/adapters/activitypub-base",
|
||||||
"crates/application",
|
"crates/application",
|
||||||
"crates/common",
|
|
||||||
"crates/domain",
|
"crates/domain",
|
||||||
"crates/presentation",
|
"crates/presentation",
|
||||||
|
"crates/tui",
|
||||||
]
|
]
|
||||||
resolver = "2"
|
resolver = "2"
|
||||||
|
|
||||||
[workspace.dependencies]
|
[workspace.dependencies]
|
||||||
tokio = { version = "1.0", features = ["full"] }
|
tokio = { version = "1.0", features = ["full"] }
|
||||||
|
dotenvy = "0.15"
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
anyhow = "1.0"
|
anyhow = "1.0"
|
||||||
@@ -20,14 +27,27 @@ thiserror = "2.0"
|
|||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
|
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
|
||||||
async-trait = "0.1"
|
async-trait = "0.1"
|
||||||
uuid = { version = "1.23.0", features = ["v4", "serde"] }
|
uuid = { version = "1.23.0", features = ["v4", "v5", "serde"] }
|
||||||
chrono = { version = "0.4", features = ["serde"] }
|
chrono = { version = "0.4", features = ["serde"] }
|
||||||
|
sqlx = { version = "0.8.6", features = [
|
||||||
|
"runtime-tokio-rustls",
|
||||||
|
"sqlite",
|
||||||
|
"uuid",
|
||||||
|
"macros",
|
||||||
|
] }
|
||||||
|
reqwest = { version = "0.13", features = ["json", "query"] }
|
||||||
|
object_store = { version = "0.11", features = ["aws"] }
|
||||||
|
|
||||||
domain = { path = "crates/domain" }
|
domain = { path = "crates/domain" }
|
||||||
common = { path = "crates/common" }
|
|
||||||
application = { path = "crates/application" }
|
application = { path = "crates/application" }
|
||||||
presentation = { path = "crates/presentation" }
|
presentation = { path = "crates/presentation" }
|
||||||
auth = { path = "crates/adapters/auth" }
|
auth = { path = "crates/adapters/auth" }
|
||||||
metadata = { path = "crates/adapters/metadata" }
|
metadata = { path = "crates/adapters/metadata" }
|
||||||
|
poster-fetcher = { path = "crates/adapters/poster-fetcher" }
|
||||||
|
poster-storage = { path = "crates/adapters/poster-storage" }
|
||||||
|
event-publisher = { path = "crates/adapters/event-publisher" }
|
||||||
rss = { path = "crates/adapters/rss" }
|
rss = { path = "crates/adapters/rss" }
|
||||||
sqlite = { path = "crates/adapters/sqlite" }
|
sqlite = { path = "crates/adapters/sqlite" }
|
||||||
|
template-askama = { path = "crates/adapters/template-askama" }
|
||||||
|
activitypub = { path = "crates/adapters/activitypub" }
|
||||||
|
activitypub-base = { path = "crates/adapters/activitypub-base" }
|
||||||
|
|||||||
68
Dockerfile
Normal file
68
Dockerfile
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
# ----- build -----
|
||||||
|
FROM rust:slim-bookworm AS builder
|
||||||
|
|
||||||
|
RUN apt-get update && apt-get install -y --no-install-recommends sqlite3 && rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
WORKDIR /build
|
||||||
|
|
||||||
|
# Cache dependency compilation separately from source
|
||||||
|
COPY Cargo.toml Cargo.lock ./
|
||||||
|
COPY crates/adapters/activitypub/Cargo.toml crates/adapters/activitypub/Cargo.toml
|
||||||
|
COPY crates/adapters/activitypub-base/Cargo.toml crates/adapters/activitypub-base/Cargo.toml
|
||||||
|
COPY crates/adapters/auth/Cargo.toml crates/adapters/auth/Cargo.toml
|
||||||
|
COPY crates/adapters/event-publisher/Cargo.toml crates/adapters/event-publisher/Cargo.toml
|
||||||
|
COPY crates/adapters/metadata/Cargo.toml crates/adapters/metadata/Cargo.toml
|
||||||
|
COPY crates/adapters/poster-fetcher/Cargo.toml crates/adapters/poster-fetcher/Cargo.toml
|
||||||
|
COPY crates/adapters/poster-storage/Cargo.toml crates/adapters/poster-storage/Cargo.toml
|
||||||
|
COPY crates/adapters/rss/Cargo.toml crates/adapters/rss/Cargo.toml
|
||||||
|
COPY crates/adapters/sqlite/Cargo.toml crates/adapters/sqlite/Cargo.toml
|
||||||
|
COPY crates/adapters/template-askama/Cargo.toml crates/adapters/template-askama/Cargo.toml
|
||||||
|
COPY crates/application/Cargo.toml crates/application/Cargo.toml
|
||||||
|
COPY crates/domain/Cargo.toml crates/domain/Cargo.toml
|
||||||
|
COPY crates/presentation/Cargo.toml crates/presentation/Cargo.toml
|
||||||
|
COPY crates/tui/Cargo.toml crates/tui/Cargo.toml
|
||||||
|
|
||||||
|
# Stub every crate so cargo can resolve and fetch deps
|
||||||
|
RUN find crates -name "Cargo.toml" | sed 's|/Cargo.toml||' | \
|
||||||
|
xargs -I{} sh -c 'mkdir -p {}/src && echo "fn main(){}" > {}/src/main.rs && echo "" > {}/src/lib.rs'
|
||||||
|
|
||||||
|
RUN cargo fetch
|
||||||
|
|
||||||
|
# Now copy real sources (invalidates cache only on source changes)
|
||||||
|
COPY crates ./crates
|
||||||
|
|
||||||
|
# sqlx macros verify queries at compile time; create a real DB from migrations
|
||||||
|
RUN sqlite3 /build/dev.db \
|
||||||
|
< crates/adapters/sqlite/migrations/0001_initial.sql && \
|
||||||
|
sqlite3 /build/dev.db \
|
||||||
|
< crates/adapters/sqlite/migrations/0002_users.sql && \
|
||||||
|
sqlite3 /build/dev.db \
|
||||||
|
< crates/adapters/sqlite/migrations/0003_activitypub.sql && \
|
||||||
|
sqlite3 /build/dev.db \
|
||||||
|
< crates/adapters/sqlite/migrations/0004_username.sql && \
|
||||||
|
sqlite3 /build/dev.db \
|
||||||
|
< crates/adapters/sqlite/migrations/0005_activitypub_v2.sql && \
|
||||||
|
sqlite3 /build/dev.db \
|
||||||
|
< crates/adapters/sqlite/migrations/0006_follower_activity_id.sql
|
||||||
|
|
||||||
|
ENV DATABASE_URL=sqlite:///build/dev.db
|
||||||
|
|
||||||
|
RUN cargo build --release -p presentation
|
||||||
|
|
||||||
|
# ----- runtime -----
|
||||||
|
FROM debian:bookworm-slim
|
||||||
|
|
||||||
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
|
ca-certificates \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY --from=builder /build/target/release/presentation ./presentation
|
||||||
|
COPY static ./static
|
||||||
|
|
||||||
|
EXPOSE 3000
|
||||||
|
|
||||||
|
ENV RUST_LOG=presentation=info,tower_http=info
|
||||||
|
|
||||||
|
CMD ["./presentation"]
|
||||||
21
LICENSE
Normal file
21
LICENSE
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 Gabriel Kaszewski
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
87
README.md
Normal file
87
README.md
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
# Movies Diary
|
||||||
|
|
||||||
|
A self-hosted, server-side rendered movie logging system. Built in Rust — no JavaScript, no SPA, just HTML forms and an RSS feed. Designed to run as a lightweight widget embedded on a personal site.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- Log movies with a TMDB/OMDb ID and a 0–5 rating
|
||||||
|
- Immutable append-only viewing ledger (tracks re-watches)
|
||||||
|
- Background poster fetching and storage (local filesystem or S3-compatible)
|
||||||
|
- RSS/Atom feed for public subscription
|
||||||
|
- JWT authentication via cookie (HTML) or Bearer token (REST API)
|
||||||
|
- Zero JavaScript
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
Hexagonal (Ports & Adapters) with Domain-Driven Design:
|
||||||
|
|
||||||
|
```
|
||||||
|
domain — pure types and trait definitions, no external deps
|
||||||
|
application — use cases / business logic orchestration
|
||||||
|
presentation — Axum HTTP router, wires all adapters together
|
||||||
|
adapters/
|
||||||
|
auth — JWT issuance and validation (Argon2 passwords)
|
||||||
|
sqlite — SQLite repository via sqlx
|
||||||
|
metadata — OMDb HTTP client
|
||||||
|
poster-fetcher — downloads poster images
|
||||||
|
poster-storage — uploads posters to local filesystem or S3-compatible storage
|
||||||
|
template-askama — Askama HTML rendering
|
||||||
|
rss — RSS/Atom feed generation
|
||||||
|
event-publisher — async event channel for background poster sync
|
||||||
|
```
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
- Rust (stable, 2024 edition)
|
||||||
|
- SQLite
|
||||||
|
- Poster storage: local filesystem (zero deps) or an S3-compatible object store (e.g. MinIO)
|
||||||
|
- An [OMDb API key](https://www.omdbapi.com/apikey.aspx)
|
||||||
|
|
||||||
|
## Environment Variables
|
||||||
|
|
||||||
|
A `.env.example` file is provided at the repo root — copy it to `.env` and fill in your values. Key variables:
|
||||||
|
|
||||||
|
```env
|
||||||
|
# Database
|
||||||
|
DATABASE_URL=sqlite://movies.db
|
||||||
|
|
||||||
|
# Authentication
|
||||||
|
JWT_SECRET=change-me
|
||||||
|
|
||||||
|
# OMDb metadata
|
||||||
|
OMDB_API_KEY=your-key
|
||||||
|
|
||||||
|
# Poster storage — pick one backend:
|
||||||
|
|
||||||
|
# Option A: local filesystem (zero deps)
|
||||||
|
POSTER_STORAGE_BACKEND=local
|
||||||
|
POSTER_STORAGE_PATH=./posters
|
||||||
|
|
||||||
|
# Option B: S3-compatible (MinIO, AWS S3, etc.)
|
||||||
|
# POSTER_STORAGE_BACKEND=s3
|
||||||
|
# MINIO_ENDPOINT=http://localhost:9000
|
||||||
|
# MINIO_BUCKET=posters
|
||||||
|
# MINIO_REGION=minio
|
||||||
|
# MINIO_ACCESS_KEY_ID=minioadmin
|
||||||
|
# MINIO_SECRET_ACCESS_KEY=minioadmin
|
||||||
|
```
|
||||||
|
|
||||||
|
See `.env.example` for optional variables (rate limiting, logging, host/port, etc.).
|
||||||
|
|
||||||
|
## Run
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cargo run -p presentation
|
||||||
|
```
|
||||||
|
|
||||||
|
Server listens on `0.0.0.0:3000`.
|
||||||
|
|
||||||
|
## Test
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cargo test
|
||||||
|
```
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT License. See [LICENSE](LICENSE).
|
||||||
21
crates/adapters/activitypub-base/Cargo.toml
Normal file
21
crates/adapters/activitypub-base/Cargo.toml
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
[package]
|
||||||
|
name = "activitypub-base"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
tokio = { workspace = true }
|
||||||
|
serde = { workspace = true }
|
||||||
|
serde_json = { workspace = true }
|
||||||
|
reqwest = { workspace = true }
|
||||||
|
uuid = { workspace = true }
|
||||||
|
chrono = { workspace = true }
|
||||||
|
thiserror = { workspace = true }
|
||||||
|
anyhow = { workspace = true }
|
||||||
|
tracing = { workspace = true }
|
||||||
|
async-trait = { workspace = true }
|
||||||
|
|
||||||
|
activitypub_federation = "0.7.0-beta.11"
|
||||||
|
url = { version = "2", features = ["serde"] }
|
||||||
|
enum_delegate = "0.2"
|
||||||
|
axum = "0.8"
|
||||||
341
crates/adapters/activitypub-base/src/activities.rs
Normal file
341
crates/adapters/activitypub-base/src/activities.rs
Normal file
@@ -0,0 +1,341 @@
|
|||||||
|
use activitypub_federation::{
|
||||||
|
config::Data,
|
||||||
|
fetch::object_id::ObjectId,
|
||||||
|
kinds::activity::{AcceptType, CreateType, DeleteType, FollowType, RejectType, UndoType, UpdateType},
|
||||||
|
traits::Activity,
|
||||||
|
};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
use crate::actors::DbActor;
|
||||||
|
use crate::data::FederationData;
|
||||||
|
use crate::error::Error;
|
||||||
|
use crate::repository::{FollowerStatus, FollowingStatus};
|
||||||
|
|
||||||
|
// --- Follow ---
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct FollowActivity {
|
||||||
|
pub(crate) id: Url,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub(crate) kind: FollowType,
|
||||||
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
|
pub(crate) object: ObjectId<DbActor>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Activity for FollowActivity {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actor(&self) -> &Url {
|
||||||
|
self.actor.inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(&self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
let target_url = self.object.inner();
|
||||||
|
let target_domain = match (target_url.host_str(), target_url.port()) {
|
||||||
|
(Some(host), Some(port)) => format!("{}:{}", host, port),
|
||||||
|
(Some(host), None) => host.to_string(),
|
||||||
|
_ => return Err(Error::bad_request(anyhow::anyhow!("invalid follow target URL"))),
|
||||||
|
};
|
||||||
|
if target_domain != data.domain {
|
||||||
|
return Err(Error::bad_request(anyhow::anyhow!("follow target is not a local actor")));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
let _follower = self.actor.dereference(data).await?;
|
||||||
|
let local_actor = self.object.dereference(data).await?;
|
||||||
|
|
||||||
|
data.federation_repo
|
||||||
|
.add_follower(
|
||||||
|
local_actor.user_id,
|
||||||
|
self.actor.inner().as_str(),
|
||||||
|
FollowerStatus::Pending,
|
||||||
|
self.id.as_str(),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
follower = %self.actor.inner(),
|
||||||
|
local_user = %local_actor.user_id,
|
||||||
|
"follow request pending approval"
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Accept ---
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct AcceptActivity {
|
||||||
|
pub(crate) id: Url,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub(crate) kind: AcceptType,
|
||||||
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
|
pub(crate) object: FollowActivity,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Activity for AcceptActivity {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actor(&self) -> &Url {
|
||||||
|
self.actor.inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
let local_user_id = crate::urls::extract_user_id_from_url(self.object.actor.inner())
|
||||||
|
.ok_or_else(|| Error::bad_request(anyhow::anyhow!("invalid actor URL in Follow")))?;
|
||||||
|
data.federation_repo
|
||||||
|
.update_following_status(local_user_id, self.actor.inner().as_str(), FollowingStatus::Accepted)
|
||||||
|
.await?;
|
||||||
|
tracing::info!(remote_actor = %self.actor.inner(), "follow accepted by remote");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Reject ---
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct RejectActivity {
|
||||||
|
pub(crate) id: Url,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub(crate) kind: RejectType,
|
||||||
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
|
pub(crate) object: FollowActivity,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Activity for RejectActivity {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actor(&self) -> &Url {
|
||||||
|
self.actor.inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
if let Some(user_id) = crate::urls::extract_user_id_from_url(self.object.actor.inner()) {
|
||||||
|
data.federation_repo
|
||||||
|
.remove_following(user_id, self.actor.inner().as_str())
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
tracing::info!(actor = %self.actor.inner(), "follow rejected");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Undo ---
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct UndoActivity {
|
||||||
|
pub(crate) id: Url,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub(crate) kind: UndoType,
|
||||||
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
|
pub(crate) object: FollowActivity,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Activity for UndoActivity {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actor(&self) -> &Url {
|
||||||
|
self.actor.inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
if let Some(user_id) = crate::urls::extract_user_id_from_url(self.object.object.inner()) {
|
||||||
|
data.federation_repo
|
||||||
|
.remove_follower(user_id, self.actor.inner().as_str())
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
data.object_handler
|
||||||
|
.on_actor_removed(self.actor.inner())
|
||||||
|
.await
|
||||||
|
.map_err(|e| Error::from(anyhow::anyhow!(e)))?;
|
||||||
|
tracing::info!(actor = %self.actor.inner(), "unfollowed");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Create ---
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct CreateActivity {
|
||||||
|
pub(crate) id: Url,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub(crate) kind: CreateType,
|
||||||
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
|
pub(crate) object: serde_json::Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Activity for CreateActivity {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actor(&self) -> &Url {
|
||||||
|
self.actor.inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
let ap_id = self.id.clone();
|
||||||
|
let actor_url = self.actor.inner().clone();
|
||||||
|
data.object_handler
|
||||||
|
.on_create(&ap_id, &actor_url, self.object)
|
||||||
|
.await
|
||||||
|
.map_err(|e| Error::from(anyhow::anyhow!(e)))?;
|
||||||
|
tracing::info!(actor = %actor_url, "received create activity");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Delete ---
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct DeleteActivity {
|
||||||
|
pub(crate) id: Url,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub(crate) kind: DeleteType,
|
||||||
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
|
pub(crate) object: Url,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Activity for DeleteActivity {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actor(&self) -> &Url {
|
||||||
|
self.actor.inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
let actor_url = self.actor.inner().clone();
|
||||||
|
data.object_handler
|
||||||
|
.on_delete(&self.object, &actor_url)
|
||||||
|
.await
|
||||||
|
.map_err(|e| Error::from(anyhow::anyhow!(e)))?;
|
||||||
|
tracing::info!(object = %self.object, "received delete activity");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Update ---
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct UpdateActivity {
|
||||||
|
pub(crate) id: Url,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub(crate) kind: UpdateType,
|
||||||
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
|
pub(crate) object: serde_json::Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Activity for UpdateActivity {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actor(&self) -> &Url {
|
||||||
|
self.actor.inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
let ap_id = self.id.clone();
|
||||||
|
let actor_url = self.actor.inner().clone();
|
||||||
|
data.object_handler
|
||||||
|
.on_update(&ap_id, &actor_url, self.object)
|
||||||
|
.await
|
||||||
|
.map_err(|e| Error::from(anyhow::anyhow!(e)))?;
|
||||||
|
tracing::info!(actor = %actor_url, "received update activity");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Inbox dispatch enum ---
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(tag = "type")]
|
||||||
|
#[enum_delegate::implement(Activity)]
|
||||||
|
pub enum InboxActivities {
|
||||||
|
#[serde(rename = "Follow")]
|
||||||
|
Follow(FollowActivity),
|
||||||
|
#[serde(rename = "Accept")]
|
||||||
|
Accept(AcceptActivity),
|
||||||
|
#[serde(rename = "Reject")]
|
||||||
|
Reject(RejectActivity),
|
||||||
|
#[serde(rename = "Undo")]
|
||||||
|
Undo(UndoActivity),
|
||||||
|
#[serde(rename = "Create")]
|
||||||
|
Create(CreateActivity),
|
||||||
|
#[serde(rename = "Delete")]
|
||||||
|
Delete(DeleteActivity),
|
||||||
|
#[serde(rename = "Update")]
|
||||||
|
Update(UpdateActivity),
|
||||||
|
}
|
||||||
21
crates/adapters/activitypub-base/src/actor_handler.rs
Normal file
21
crates/adapters/activitypub-base/src/actor_handler.rs
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
use activitypub_federation::{
|
||||||
|
axum::json::FederationJson, config::Data, protocol::context::WithContext, traits::Object,
|
||||||
|
};
|
||||||
|
use axum::extract::Path;
|
||||||
|
|
||||||
|
use crate::actors::{get_local_actor, Person};
|
||||||
|
use crate::data::FederationData;
|
||||||
|
use crate::error::Error;
|
||||||
|
|
||||||
|
pub async fn actor_handler(
|
||||||
|
Path(user_id_str): Path<String>,
|
||||||
|
data: Data<FederationData>,
|
||||||
|
) -> Result<FederationJson<WithContext<Person>>, Error> {
|
||||||
|
let uuid = uuid::Uuid::parse_str(&user_id_str)
|
||||||
|
.map_err(|_| Error::bad_request(anyhow::anyhow!("invalid user id")))?;
|
||||||
|
|
||||||
|
let db_actor = get_local_actor(uuid, &data).await?;
|
||||||
|
let person = db_actor.into_json(&data).await?;
|
||||||
|
|
||||||
|
Ok(FederationJson(WithContext::new_default(person)))
|
||||||
|
}
|
||||||
230
crates/adapters/activitypub-base/src/actors.rs
Normal file
230
crates/adapters/activitypub-base/src/actors.rs
Normal file
@@ -0,0 +1,230 @@
|
|||||||
|
use activitypub_federation::{
|
||||||
|
config::Data,
|
||||||
|
fetch::object_id::ObjectId,
|
||||||
|
http_signatures::generate_actor_keypair,
|
||||||
|
kinds::actor::PersonType,
|
||||||
|
protocol::{public_key::PublicKey, verification::verify_domains_match},
|
||||||
|
traits::{Actor, Object},
|
||||||
|
};
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
use crate::data::FederationData;
|
||||||
|
use crate::error::Error;
|
||||||
|
use crate::repository::RemoteActor;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct DbActor {
|
||||||
|
pub user_id: uuid::Uuid,
|
||||||
|
pub username: String,
|
||||||
|
pub public_key_pem: String,
|
||||||
|
pub private_key_pem: Option<String>,
|
||||||
|
pub inbox_url: Url,
|
||||||
|
pub outbox_url: Url,
|
||||||
|
pub followers_url: Url,
|
||||||
|
pub following_url: Url,
|
||||||
|
pub ap_id: Url,
|
||||||
|
pub last_refreshed_at: DateTime<Utc>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct Person {
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
kind: PersonType,
|
||||||
|
id: ObjectId<DbActor>,
|
||||||
|
preferred_username: String,
|
||||||
|
inbox: Url,
|
||||||
|
outbox: Url,
|
||||||
|
followers: Url,
|
||||||
|
following: Url,
|
||||||
|
public_key: PublicKey,
|
||||||
|
name: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_local_actor(
|
||||||
|
user_id: uuid::Uuid,
|
||||||
|
data: &Data<FederationData>,
|
||||||
|
) -> Result<DbActor, Error> {
|
||||||
|
let user = data
|
||||||
|
.user_repo
|
||||||
|
.find_by_id(user_id)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)?
|
||||||
|
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found: {}", user_id)))?;
|
||||||
|
|
||||||
|
let (public_key, private_key) = match data
|
||||||
|
.federation_repo
|
||||||
|
.get_local_actor_keypair(user_id)
|
||||||
|
.await?
|
||||||
|
{
|
||||||
|
Some(kp) => kp,
|
||||||
|
None => {
|
||||||
|
let kp = generate_actor_keypair()?;
|
||||||
|
data.federation_repo
|
||||||
|
.save_local_actor_keypair(
|
||||||
|
user_id,
|
||||||
|
kp.public_key.clone(),
|
||||||
|
kp.private_key.clone(),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
(kp.public_key, kp.private_key)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let ap_id = crate::urls::actor_url(&data.base_url, user_id);
|
||||||
|
let inbox_url = Url::parse(&format!("{}/inbox", &ap_id)).expect("valid inbox url");
|
||||||
|
let outbox_url = Url::parse(&format!("{}/outbox", &ap_id)).expect("valid outbox url");
|
||||||
|
let followers_url = Url::parse(&format!("{}/followers", &ap_id)).expect("valid followers url");
|
||||||
|
let following_url = Url::parse(&format!("{}/following", &ap_id)).expect("valid following url");
|
||||||
|
|
||||||
|
Ok(DbActor {
|
||||||
|
user_id,
|
||||||
|
username: user.username,
|
||||||
|
public_key_pem: public_key,
|
||||||
|
private_key_pem: Some(private_key),
|
||||||
|
inbox_url,
|
||||||
|
outbox_url,
|
||||||
|
followers_url,
|
||||||
|
following_url,
|
||||||
|
ap_id,
|
||||||
|
last_refreshed_at: Utc::now(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Object for DbActor {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Kind = Person;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.ap_id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn last_refreshed_at(&self) -> Option<DateTime<Utc>> {
|
||||||
|
Some(self.last_refreshed_at)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn read_from_id(
|
||||||
|
object_id: Url,
|
||||||
|
data: &Data<Self::DataType>,
|
||||||
|
) -> Result<Option<Self>, Self::Error> {
|
||||||
|
let user_id = match crate::urls::extract_user_id_from_url(&object_id) {
|
||||||
|
Some(id) => id,
|
||||||
|
None => return Ok(None),
|
||||||
|
};
|
||||||
|
let user = match data.user_repo.find_by_id(user_id).await {
|
||||||
|
Ok(Some(u)) => u,
|
||||||
|
_ => return Ok(None),
|
||||||
|
};
|
||||||
|
|
||||||
|
let keypair = data
|
||||||
|
.federation_repo
|
||||||
|
.get_local_actor_keypair(user_id)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let (public_key, private_key) = match keypair {
|
||||||
|
Some(kp) => (kp.0, Some(kp.1)),
|
||||||
|
None => return Ok(None),
|
||||||
|
};
|
||||||
|
|
||||||
|
let ap_id = crate::urls::actor_url(&data.base_url, user_id);
|
||||||
|
let inbox_url = Url::parse(&format!("{}/inbox", &ap_id)).expect("valid url");
|
||||||
|
let outbox_url = Url::parse(&format!("{}/outbox", &ap_id)).expect("valid url");
|
||||||
|
let followers_url = Url::parse(&format!("{}/followers", &ap_id)).expect("valid url");
|
||||||
|
let following_url = Url::parse(&format!("{}/following", &ap_id)).expect("valid url");
|
||||||
|
|
||||||
|
Ok(Some(DbActor {
|
||||||
|
user_id,
|
||||||
|
username: user.username,
|
||||||
|
public_key_pem: public_key,
|
||||||
|
private_key_pem: private_key,
|
||||||
|
inbox_url,
|
||||||
|
outbox_url,
|
||||||
|
followers_url,
|
||||||
|
following_url,
|
||||||
|
ap_id,
|
||||||
|
last_refreshed_at: Utc::now(),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn into_json(self, _data: &Data<Self::DataType>) -> Result<Self::Kind, Self::Error> {
|
||||||
|
let public_key = PublicKey {
|
||||||
|
id: format!("{}#main-key", &self.ap_id),
|
||||||
|
owner: self.ap_id.clone(),
|
||||||
|
public_key_pem: self.public_key_pem.clone(),
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(Person {
|
||||||
|
kind: Default::default(),
|
||||||
|
id: self.ap_id.clone().into(),
|
||||||
|
preferred_username: self.username.clone(),
|
||||||
|
inbox: self.inbox_url.clone(),
|
||||||
|
outbox: self.outbox_url.clone(),
|
||||||
|
followers: self.followers_url.clone(),
|
||||||
|
following: self.following_url.clone(),
|
||||||
|
public_key,
|
||||||
|
name: Some(self.username.clone()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(
|
||||||
|
json: &Self::Kind,
|
||||||
|
expected_domain: &Url,
|
||||||
|
_data: &Data<Self::DataType>,
|
||||||
|
) -> Result<(), Self::Error> {
|
||||||
|
verify_domains_match(json.id.inner(), expected_domain)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn from_json(
|
||||||
|
json: Self::Kind,
|
||||||
|
data: &Data<Self::DataType>,
|
||||||
|
) -> Result<Self, Self::Error> {
|
||||||
|
let actor = RemoteActor {
|
||||||
|
url: json.id.inner().to_string(),
|
||||||
|
handle: json.preferred_username.clone(),
|
||||||
|
inbox_url: json.inbox.to_string(),
|
||||||
|
shared_inbox_url: None,
|
||||||
|
display_name: json.name.clone(),
|
||||||
|
};
|
||||||
|
data.federation_repo.upsert_remote_actor(actor).await?;
|
||||||
|
|
||||||
|
let url_str = json.id.inner().to_string();
|
||||||
|
let user_id = uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_URL, url_str.as_bytes());
|
||||||
|
let ap_id = json.id.inner().clone();
|
||||||
|
let inbox_url = json.inbox.clone();
|
||||||
|
let outbox_url = json.outbox.clone();
|
||||||
|
let followers_url = json.followers.clone();
|
||||||
|
let following_url = json.following.clone();
|
||||||
|
|
||||||
|
Ok(DbActor {
|
||||||
|
user_id,
|
||||||
|
username: json.preferred_username.clone(),
|
||||||
|
public_key_pem: json.public_key.public_key_pem,
|
||||||
|
private_key_pem: None,
|
||||||
|
inbox_url,
|
||||||
|
outbox_url,
|
||||||
|
followers_url,
|
||||||
|
following_url,
|
||||||
|
ap_id,
|
||||||
|
last_refreshed_at: Utc::now(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Actor for DbActor {
|
||||||
|
fn public_key_pem(&self) -> &str {
|
||||||
|
&self.public_key_pem
|
||||||
|
}
|
||||||
|
|
||||||
|
fn private_key_pem(&self) -> Option<String> {
|
||||||
|
self.private_key_pem.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn inbox(&self) -> Url {
|
||||||
|
self.inbox_url.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
34
crates/adapters/activitypub-base/src/content.rs
Normal file
34
crates/adapters/activitypub-base/src/content.rs
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
use async_trait::async_trait;
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
pub trait ApObjectHandler: Send + Sync {
|
||||||
|
/// Returns (ap_id, serialized object) for all local content owned by this user.
|
||||||
|
/// Used by outbox (count) and backfill (delivery). Must only return locally-authored content.
|
||||||
|
async fn get_local_objects_for_user(
|
||||||
|
&self,
|
||||||
|
user_id: uuid::Uuid,
|
||||||
|
) -> anyhow::Result<Vec<(Url, serde_json::Value)>>;
|
||||||
|
|
||||||
|
/// Incoming Create activity — persist remote content.
|
||||||
|
async fn on_create(
|
||||||
|
&self,
|
||||||
|
ap_id: &Url,
|
||||||
|
actor_url: &Url,
|
||||||
|
object: serde_json::Value,
|
||||||
|
) -> anyhow::Result<()>;
|
||||||
|
|
||||||
|
/// Incoming Update activity — update existing remote content.
|
||||||
|
async fn on_update(
|
||||||
|
&self,
|
||||||
|
ap_id: &Url,
|
||||||
|
actor_url: &Url,
|
||||||
|
object: serde_json::Value,
|
||||||
|
) -> anyhow::Result<()>;
|
||||||
|
|
||||||
|
/// Incoming Delete activity — remove specific remote content.
|
||||||
|
async fn on_delete(&self, ap_id: &Url, actor_url: &Url) -> anyhow::Result<()>;
|
||||||
|
|
||||||
|
/// Actor unfollowed/was removed — clean up all their remote content.
|
||||||
|
async fn on_actor_removed(&self, actor_url: &Url) -> anyhow::Result<()>;
|
||||||
|
}
|
||||||
38
crates/adapters/activitypub-base/src/data.rs
Normal file
38
crates/adapters/activitypub-base/src/data.rs
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use crate::content::ApObjectHandler;
|
||||||
|
use crate::repository::FederationRepository;
|
||||||
|
use crate::user::ApUserRepository;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct FederationData {
|
||||||
|
pub(crate) federation_repo: Arc<dyn FederationRepository>,
|
||||||
|
pub(crate) user_repo: Arc<dyn ApUserRepository>,
|
||||||
|
pub(crate) object_handler: Arc<dyn ApObjectHandler>,
|
||||||
|
pub(crate) base_url: String,
|
||||||
|
pub(crate) domain: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FederationData {
|
||||||
|
pub fn new(
|
||||||
|
federation_repo: Arc<dyn FederationRepository>,
|
||||||
|
user_repo: Arc<dyn ApUserRepository>,
|
||||||
|
object_handler: Arc<dyn ApObjectHandler>,
|
||||||
|
base_url: String,
|
||||||
|
) -> Self {
|
||||||
|
let domain = base_url
|
||||||
|
.trim_start_matches("https://")
|
||||||
|
.trim_start_matches("http://")
|
||||||
|
.split('/')
|
||||||
|
.next()
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_string();
|
||||||
|
Self {
|
||||||
|
federation_repo,
|
||||||
|
user_repo,
|
||||||
|
object_handler,
|
||||||
|
base_url,
|
||||||
|
domain,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
48
crates/adapters/activitypub-base/src/error.rs
Normal file
48
crates/adapters/activitypub-base/src/error.rs
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
use std::fmt::{Display, Formatter};
|
||||||
|
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Error(pub(crate) anyhow::Error, pub(crate) StatusCode);
|
||||||
|
|
||||||
|
impl Error {
|
||||||
|
pub fn not_found(e: impl Into<anyhow::Error>) -> Self {
|
||||||
|
Self(e.into(), StatusCode::NOT_FOUND)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn bad_request(e: impl Into<anyhow::Error>) -> Self {
|
||||||
|
Self(e.into(), StatusCode::BAD_REQUEST)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for Error {
|
||||||
|
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||||
|
std::fmt::Display::fmt(&self.0, f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> From<T> for Error
|
||||||
|
where
|
||||||
|
T: Into<anyhow::Error>,
|
||||||
|
{
|
||||||
|
fn from(t: T) -> Self {
|
||||||
|
Error(t.into(), StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl axum::response::IntoResponse for Error {
|
||||||
|
fn into_response(self) -> axum::response::Response {
|
||||||
|
let status = self.1;
|
||||||
|
if status.is_server_error() {
|
||||||
|
tracing::error!(error = %self.0, status = status.as_u16(), "federation error");
|
||||||
|
} else {
|
||||||
|
tracing::debug!(error = %self.0, status = status.as_u16(), "federation response");
|
||||||
|
}
|
||||||
|
let body = if status.is_server_error() {
|
||||||
|
"internal server error".to_string()
|
||||||
|
} else {
|
||||||
|
self.0.to_string()
|
||||||
|
};
|
||||||
|
(status, body).into_response()
|
||||||
|
}
|
||||||
|
}
|
||||||
50
crates/adapters/activitypub-base/src/federation.rs
Normal file
50
crates/adapters/activitypub-base/src/federation.rs
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
use activitypub_federation::config::{Data, FederationConfig, FederationMiddleware, UrlVerifier};
|
||||||
|
use activitypub_federation::error::Error as FedError;
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
use crate::data::FederationData;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct PermissiveVerifier;
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl UrlVerifier for PermissiveVerifier {
|
||||||
|
async fn verify(&self, _url: &Url) -> Result<(), FedError> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct ApFederationConfig(pub FederationConfig<FederationData>);
|
||||||
|
|
||||||
|
impl ApFederationConfig {
|
||||||
|
pub async fn new(data: FederationData, debug: bool) -> anyhow::Result<Self> {
|
||||||
|
let config = if debug {
|
||||||
|
FederationConfig::builder()
|
||||||
|
.domain(&data.domain)
|
||||||
|
.app_data(data)
|
||||||
|
.debug(true)
|
||||||
|
.http_signature_compat(true)
|
||||||
|
.url_verifier(Box::new(PermissiveVerifier))
|
||||||
|
.build()
|
||||||
|
.await?
|
||||||
|
} else {
|
||||||
|
FederationConfig::builder()
|
||||||
|
.domain(&data.domain)
|
||||||
|
.app_data(data)
|
||||||
|
.debug(false)
|
||||||
|
.http_signature_compat(true)
|
||||||
|
.build()
|
||||||
|
.await?
|
||||||
|
};
|
||||||
|
Ok(Self(config))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_request_data(&self) -> Data<FederationData> {
|
||||||
|
self.0.to_request_data()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn middleware(&self) -> FederationMiddleware<FederationData> {
|
||||||
|
FederationMiddleware::new(self.0.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
71
crates/adapters/activitypub-base/src/followers_handler.rs
Normal file
71
crates/adapters/activitypub-base/src/followers_handler.rs
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
use activitypub_federation::{axum::json::FederationJson, config::Data};
|
||||||
|
use axum::extract::Path;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
use crate::data::FederationData;
|
||||||
|
use crate::error::Error;
|
||||||
|
use crate::repository::FollowerStatus;
|
||||||
|
|
||||||
|
fn ordered_collection(id: String, total: usize, items: Vec<String>) -> serde_json::Value {
|
||||||
|
json!({
|
||||||
|
"@context": "https://www.w3.org/ns/activitystreams",
|
||||||
|
"type": "OrderedCollection",
|
||||||
|
"id": id,
|
||||||
|
"totalItems": total,
|
||||||
|
"orderedItems": items,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn followers_handler(
|
||||||
|
Path(user_id_str): Path<String>,
|
||||||
|
data: Data<FederationData>,
|
||||||
|
) -> Result<FederationJson<serde_json::Value>, Error> {
|
||||||
|
let user_id = uuid::Uuid::parse_str(&user_id_str)
|
||||||
|
.map_err(|_| Error::bad_request(anyhow::anyhow!("invalid user id")))?;
|
||||||
|
|
||||||
|
data.user_repo
|
||||||
|
.find_by_id(user_id)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)?
|
||||||
|
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found")))?;
|
||||||
|
|
||||||
|
let followers = data
|
||||||
|
.federation_repo
|
||||||
|
.get_followers(user_id)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)?;
|
||||||
|
|
||||||
|
let items: Vec<String> = followers
|
||||||
|
.into_iter()
|
||||||
|
.filter(|f| f.status == FollowerStatus::Accepted)
|
||||||
|
.map(|f| f.actor.url)
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let id = format!("{}/users/{}/followers", data.base_url, user_id_str);
|
||||||
|
Ok(FederationJson(ordered_collection(id, items.len(), items)))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn following_handler(
|
||||||
|
Path(user_id_str): Path<String>,
|
||||||
|
data: Data<FederationData>,
|
||||||
|
) -> Result<FederationJson<serde_json::Value>, Error> {
|
||||||
|
let user_id = uuid::Uuid::parse_str(&user_id_str)
|
||||||
|
.map_err(|_| Error::bad_request(anyhow::anyhow!("invalid user id")))?;
|
||||||
|
|
||||||
|
data.user_repo
|
||||||
|
.find_by_id(user_id)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)?
|
||||||
|
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found")))?;
|
||||||
|
|
||||||
|
let following = data
|
||||||
|
.federation_repo
|
||||||
|
.get_following(user_id)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)?;
|
||||||
|
|
||||||
|
let items: Vec<String> = following.into_iter().map(|a| a.url).collect();
|
||||||
|
|
||||||
|
let id = format!("{}/users/{}/following", data.base_url, user_id_str);
|
||||||
|
Ok(FederationJson(ordered_collection(id, items.len(), items)))
|
||||||
|
}
|
||||||
20
crates/adapters/activitypub-base/src/inbox.rs
Normal file
20
crates/adapters/activitypub-base/src/inbox.rs
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
use activitypub_federation::{
|
||||||
|
axum::inbox::{receive_activity, ActivityData},
|
||||||
|
config::Data,
|
||||||
|
protocol::context::WithContext,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::activities::InboxActivities;
|
||||||
|
use crate::actors::DbActor;
|
||||||
|
use crate::data::FederationData;
|
||||||
|
use crate::error::Error;
|
||||||
|
|
||||||
|
pub async fn inbox_handler(
|
||||||
|
data: Data<FederationData>,
|
||||||
|
activity_data: ActivityData,
|
||||||
|
) -> Result<(), Error> {
|
||||||
|
receive_activity::<WithContext<InboxActivities>, DbActor, FederationData>(
|
||||||
|
activity_data, &data,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
23
crates/adapters/activitypub-base/src/lib.rs
Normal file
23
crates/adapters/activitypub-base/src/lib.rs
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
pub mod activities;
|
||||||
|
pub mod actor_handler;
|
||||||
|
pub mod actors;
|
||||||
|
pub mod content;
|
||||||
|
pub mod data;
|
||||||
|
pub mod error;
|
||||||
|
pub mod federation;
|
||||||
|
pub mod followers_handler;
|
||||||
|
pub mod inbox;
|
||||||
|
pub mod outbox;
|
||||||
|
pub mod repository;
|
||||||
|
pub mod service;
|
||||||
|
pub mod user;
|
||||||
|
pub mod webfinger;
|
||||||
|
pub(crate) mod urls;
|
||||||
|
|
||||||
|
pub use content::ApObjectHandler;
|
||||||
|
pub use data::FederationData;
|
||||||
|
pub use error::Error;
|
||||||
|
pub use federation::ApFederationConfig;
|
||||||
|
pub use repository::{FederationRepository, Follower, FollowerStatus, FollowingStatus, RemoteActor};
|
||||||
|
pub use service::ActivityPubService;
|
||||||
|
pub use user::{ApUser, ApUserRepository};
|
||||||
48
crates/adapters/activitypub-base/src/outbox.rs
Normal file
48
crates/adapters/activitypub-base/src/outbox.rs
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
use activitypub_federation::{axum::json::FederationJson, config::Data};
|
||||||
|
use axum::extract::Path;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::data::FederationData;
|
||||||
|
use crate::error::Error;
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct OrderedCollection {
|
||||||
|
#[serde(rename = "@context")]
|
||||||
|
context: String,
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
kind: String,
|
||||||
|
id: String,
|
||||||
|
total_items: u64,
|
||||||
|
ordered_items: Vec<serde_json::Value>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn outbox_handler(
|
||||||
|
Path(user_id_str): Path<String>,
|
||||||
|
data: Data<FederationData>,
|
||||||
|
) -> Result<FederationJson<OrderedCollection>, Error> {
|
||||||
|
let uuid = uuid::Uuid::parse_str(&user_id_str)
|
||||||
|
.map_err(|_| Error::bad_request(anyhow::anyhow!("invalid user id")))?;
|
||||||
|
|
||||||
|
data.user_repo
|
||||||
|
.find_by_id(uuid)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)?
|
||||||
|
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found")))?;
|
||||||
|
|
||||||
|
let objects = data
|
||||||
|
.object_handler
|
||||||
|
.get_local_objects_for_user(uuid)
|
||||||
|
.await
|
||||||
|
.map_err(|e| Error::from(anyhow::anyhow!(e)))?;
|
||||||
|
|
||||||
|
let outbox_url = format!("{}/users/{}/outbox", data.base_url, user_id_str);
|
||||||
|
|
||||||
|
Ok(FederationJson(OrderedCollection {
|
||||||
|
context: "https://www.w3.org/ns/activitystreams".to_string(),
|
||||||
|
kind: "OrderedCollection".to_string(),
|
||||||
|
id: outbox_url,
|
||||||
|
total_items: objects.len() as u64,
|
||||||
|
ordered_items: vec![],
|
||||||
|
}))
|
||||||
|
}
|
||||||
50
crates/adapters/activitypub-base/src/repository.rs
Normal file
50
crates/adapters/activitypub-base/src/repository.rs
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
use anyhow::Result;
|
||||||
|
use async_trait::async_trait;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum FollowerStatus {
|
||||||
|
Pending,
|
||||||
|
Accepted,
|
||||||
|
Rejected,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum FollowingStatus {
|
||||||
|
Pending,
|
||||||
|
Accepted,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct RemoteActor {
|
||||||
|
pub url: String,
|
||||||
|
pub handle: String,
|
||||||
|
pub inbox_url: String,
|
||||||
|
pub shared_inbox_url: Option<String>,
|
||||||
|
pub display_name: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Follower {
|
||||||
|
pub actor: RemoteActor,
|
||||||
|
pub status: FollowerStatus,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
pub trait FederationRepository: Send + Sync {
|
||||||
|
async fn add_follower(&self, local_user_id: uuid::Uuid, remote_actor_url: &str, status: FollowerStatus, follow_activity_id: &str) -> Result<()>;
|
||||||
|
async fn get_follower_follow_activity_id(&self, local_user_id: uuid::Uuid, remote_actor_url: &str) -> Result<Option<String>>;
|
||||||
|
async fn remove_follower(&self, local_user_id: uuid::Uuid, remote_actor_url: &str) -> Result<()>;
|
||||||
|
async fn get_followers(&self, local_user_id: uuid::Uuid) -> Result<Vec<Follower>>;
|
||||||
|
async fn update_follower_status(&self, local_user_id: uuid::Uuid, remote_actor_url: &str, status: FollowerStatus) -> Result<()>;
|
||||||
|
async fn add_following(&self, local_user_id: uuid::Uuid, actor: RemoteActor, follow_activity_id: &str) -> Result<()>;
|
||||||
|
async fn get_follow_activity_id(&self, local_user_id: uuid::Uuid, remote_actor_url: &str) -> Result<Option<String>>;
|
||||||
|
async fn remove_following(&self, local_user_id: uuid::Uuid, actor_url: &str) -> Result<()>;
|
||||||
|
async fn get_following(&self, local_user_id: uuid::Uuid) -> Result<Vec<RemoteActor>>;
|
||||||
|
async fn count_following(&self, local_user_id: uuid::Uuid) -> Result<usize>;
|
||||||
|
async fn upsert_remote_actor(&self, actor: RemoteActor) -> Result<()>;
|
||||||
|
async fn get_remote_actor(&self, actor_url: &str) -> Result<Option<RemoteActor>>;
|
||||||
|
async fn get_local_actor_keypair(&self, user_id: uuid::Uuid) -> Result<Option<(String, String)>>;
|
||||||
|
async fn save_local_actor_keypair(&self, user_id: uuid::Uuid, public_key: String, private_key: String) -> Result<()>;
|
||||||
|
async fn get_pending_followers(&self, local_user_id: uuid::Uuid) -> Result<Vec<RemoteActor>>;
|
||||||
|
async fn update_following_status(&self, local_user_id: uuid::Uuid, remote_actor_url: &str, status: FollowingStatus) -> Result<()>;
|
||||||
|
}
|
||||||
470
crates/adapters/activitypub-base/src/service.rs
Normal file
470
crates/adapters/activitypub-base/src/service.rs
Normal file
@@ -0,0 +1,470 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use activitypub_federation::{
|
||||||
|
activity_sending::SendActivityTask,
|
||||||
|
fetch::{object_id::ObjectId, webfinger::webfinger_resolve_actor},
|
||||||
|
protocol::context::WithContext,
|
||||||
|
traits::Actor,
|
||||||
|
};
|
||||||
|
use axum::{routing::get, routing::post, Router};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
activities::{AcceptActivity, CreateActivity, FollowActivity, RejectActivity, UndoActivity},
|
||||||
|
actor_handler::actor_handler,
|
||||||
|
actors::{get_local_actor, DbActor},
|
||||||
|
content::ApObjectHandler,
|
||||||
|
data::FederationData,
|
||||||
|
federation::ApFederationConfig,
|
||||||
|
followers_handler::{followers_handler, following_handler},
|
||||||
|
inbox::inbox_handler,
|
||||||
|
outbox::outbox_handler,
|
||||||
|
repository::{FederationRepository, FollowerStatus, RemoteActor},
|
||||||
|
user::ApUserRepository,
|
||||||
|
urls::activity_url,
|
||||||
|
webfinger::webfinger_handler,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub(crate) async fn send_with_retry(
|
||||||
|
sends: Vec<SendActivityTask>,
|
||||||
|
data: &activitypub_federation::config::Data<FederationData>,
|
||||||
|
) -> Vec<anyhow::Error> {
|
||||||
|
let mut failures = vec![];
|
||||||
|
for send in sends {
|
||||||
|
let mut delay = std::time::Duration::from_secs(1);
|
||||||
|
for attempt in 1..=3u32 {
|
||||||
|
match send.clone().sign_and_send(data).await {
|
||||||
|
Ok(()) => break,
|
||||||
|
Err(e) if attempt < 3 => {
|
||||||
|
tracing::warn!(attempt, error = %e, "delivery failed, retrying");
|
||||||
|
tokio::time::sleep(delay).await;
|
||||||
|
delay *= 2;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!(attempt, error = %e, "delivery failed permanently");
|
||||||
|
failures.push(anyhow::anyhow!(e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
failures
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ActivityPubService {
|
||||||
|
federation_config: ApFederationConfig,
|
||||||
|
base_url: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActivityPubService {
|
||||||
|
pub async fn new(
|
||||||
|
repo: Arc<dyn FederationRepository>,
|
||||||
|
user_repo: Arc<dyn ApUserRepository>,
|
||||||
|
object_handler: Arc<dyn ApObjectHandler>,
|
||||||
|
base_url: String,
|
||||||
|
debug: bool,
|
||||||
|
) -> anyhow::Result<Self> {
|
||||||
|
let data = FederationData::new(repo, user_repo, object_handler, base_url.clone());
|
||||||
|
let federation_config = ApFederationConfig::new(data, debug).await?;
|
||||||
|
Ok(Self { federation_config, base_url })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn federation_config(&self) -> &ApFederationConfig {
|
||||||
|
&self.federation_config
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn request_data(&self) -> activitypub_federation::config::Data<FederationData> {
|
||||||
|
self.federation_config.to_request_data()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn actor_json(&self, user_id_str: &str) -> anyhow::Result<String> {
|
||||||
|
use activitypub_federation::traits::Object;
|
||||||
|
let uuid = uuid::Uuid::parse_str(user_id_str)?;
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
let actor = get_local_actor(uuid, &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
let person = actor.into_json(&data).await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
Ok(serde_json::to_string(&WithContext::new_default(person))?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn router(&self) -> Router {
|
||||||
|
Router::new()
|
||||||
|
.route("/.well-known/webfinger", get(webfinger_handler))
|
||||||
|
.route("/users/{user_id}", get(actor_handler))
|
||||||
|
.route("/users/{user_id}/inbox", post(inbox_handler))
|
||||||
|
.route("/users/{user_id}/outbox", get(outbox_handler))
|
||||||
|
.route("/users/{user_id}/followers", get(followers_handler))
|
||||||
|
.route("/users/{user_id}/following", get(following_handler))
|
||||||
|
.layer(self.federation_config.middleware())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn follow(&self, local_user_id: uuid::Uuid, handle: &str) -> anyhow::Result<()> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
|
||||||
|
let remote_actor: DbActor = webfinger_resolve_actor(handle, &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
|
let local_actor = get_local_actor(local_user_id, &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
|
let follow_id = activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
let follow_id_str = follow_id.to_string();
|
||||||
|
let follow = FollowActivity {
|
||||||
|
id: follow_id,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
object: ObjectId::from(remote_actor.ap_id.clone()),
|
||||||
|
};
|
||||||
|
let follow_with_ctx = WithContext::new_default(follow);
|
||||||
|
|
||||||
|
let sends = SendActivityTask::prepare(
|
||||||
|
&follow_with_ctx,
|
||||||
|
&local_actor,
|
||||||
|
vec![remote_actor.inbox()],
|
||||||
|
&data,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let failures = send_with_retry(sends, &data).await;
|
||||||
|
if !failures.is_empty() {
|
||||||
|
tracing::warn!(count = failures.len(), "some activity deliveries failed permanently");
|
||||||
|
}
|
||||||
|
|
||||||
|
let remote = RemoteActor {
|
||||||
|
url: remote_actor.ap_id.to_string(),
|
||||||
|
handle: remote_actor.username.clone(),
|
||||||
|
inbox_url: remote_actor.inbox_url.to_string(),
|
||||||
|
shared_inbox_url: None,
|
||||||
|
display_name: Some(remote_actor.username.clone()),
|
||||||
|
};
|
||||||
|
data.federation_repo
|
||||||
|
.add_following(local_user_id, remote, &follow_id_str)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn unfollow(&self, local_user_id: uuid::Uuid, actor_url_str: &str) -> anyhow::Result<()> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
|
||||||
|
let remote = data
|
||||||
|
.federation_repo
|
||||||
|
.get_remote_actor(actor_url_str)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("remote actor not found: {}", actor_url_str))?;
|
||||||
|
|
||||||
|
let local_actor = get_local_actor(local_user_id, &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
|
let remote_ap_id = Url::parse(actor_url_str)?;
|
||||||
|
let inbox = Url::parse(&remote.inbox_url)?;
|
||||||
|
|
||||||
|
let follow_activity_id_str = data
|
||||||
|
.federation_repo
|
||||||
|
.get_follow_activity_id(local_user_id, actor_url_str)
|
||||||
|
.await?;
|
||||||
|
let follow_id = match follow_activity_id_str {
|
||||||
|
Some(id) => Url::parse(&id)?,
|
||||||
|
None => activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?,
|
||||||
|
};
|
||||||
|
let follow = FollowActivity {
|
||||||
|
id: follow_id,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
object: ObjectId::from(remote_ap_id),
|
||||||
|
};
|
||||||
|
|
||||||
|
let undo_id = activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
let undo = UndoActivity {
|
||||||
|
id: undo_id,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
object: follow,
|
||||||
|
};
|
||||||
|
|
||||||
|
let sends = SendActivityTask::prepare(
|
||||||
|
&WithContext::new_default(undo),
|
||||||
|
&local_actor,
|
||||||
|
vec![inbox],
|
||||||
|
&data,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let failures = send_with_retry(sends, &data).await;
|
||||||
|
if !failures.is_empty() {
|
||||||
|
tracing::warn!(count = failures.len(), "some activity deliveries failed permanently");
|
||||||
|
}
|
||||||
|
|
||||||
|
data.federation_repo
|
||||||
|
.remove_following(local_user_id, actor_url_str)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
data.object_handler
|
||||||
|
.on_actor_removed(&Url::parse(actor_url_str)?)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn accept_follower(
|
||||||
|
&self,
|
||||||
|
local_user_id: uuid::Uuid,
|
||||||
|
remote_actor_url: &str,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
let local_actor = get_local_actor(local_user_id, &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
|
let remote_actor = data
|
||||||
|
.federation_repo
|
||||||
|
.get_remote_actor(remote_actor_url)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("remote actor not found"))?;
|
||||||
|
|
||||||
|
let follow_id_str = data
|
||||||
|
.federation_repo
|
||||||
|
.get_follower_follow_activity_id(local_user_id, remote_actor_url)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("follow activity id not found for {}", remote_actor_url))?;
|
||||||
|
let follow_id = Url::parse(&follow_id_str)?;
|
||||||
|
let follow = FollowActivity {
|
||||||
|
id: follow_id,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(Url::parse(remote_actor_url)?),
|
||||||
|
object: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
};
|
||||||
|
let accept = AcceptActivity {
|
||||||
|
id: activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
object: follow,
|
||||||
|
};
|
||||||
|
|
||||||
|
data.federation_repo
|
||||||
|
.update_follower_status(local_user_id, remote_actor_url, FollowerStatus::Accepted)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let inbox = Url::parse(&remote_actor.inbox_url)?;
|
||||||
|
let sends = SendActivityTask::prepare(
|
||||||
|
&WithContext::new_default(accept),
|
||||||
|
&local_actor,
|
||||||
|
vec![inbox.clone()],
|
||||||
|
&data,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let failures = send_with_retry(sends, &data).await;
|
||||||
|
if !failures.is_empty() {
|
||||||
|
tracing::warn!("failed to deliver Accept activity, but follower is marked accepted locally");
|
||||||
|
}
|
||||||
|
|
||||||
|
self.spawn_backfill(local_user_id, remote_actor.inbox_url.clone());
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn reject_follower(
|
||||||
|
&self,
|
||||||
|
local_user_id: uuid::Uuid,
|
||||||
|
remote_actor_url: &str,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
let local_actor = get_local_actor(local_user_id, &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
|
let remote_actor = data
|
||||||
|
.federation_repo
|
||||||
|
.get_remote_actor(remote_actor_url)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("remote actor not found"))?;
|
||||||
|
|
||||||
|
let follow_id = activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
let follow = FollowActivity {
|
||||||
|
id: follow_id,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(Url::parse(remote_actor_url)?),
|
||||||
|
object: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
};
|
||||||
|
let reject = RejectActivity {
|
||||||
|
id: activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
object: follow,
|
||||||
|
};
|
||||||
|
|
||||||
|
let inbox = Url::parse(&remote_actor.inbox_url)?;
|
||||||
|
let sends = SendActivityTask::prepare(
|
||||||
|
&WithContext::new_default(reject),
|
||||||
|
&local_actor,
|
||||||
|
vec![inbox],
|
||||||
|
&data,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let failures = send_with_retry(sends, &data).await;
|
||||||
|
if !failures.is_empty() {
|
||||||
|
tracing::warn!(count = failures.len(), "some activity deliveries failed permanently");
|
||||||
|
}
|
||||||
|
|
||||||
|
data.federation_repo
|
||||||
|
.remove_follower(local_user_id, remote_actor_url)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_pending_followers(&self, local_user_id: uuid::Uuid) -> anyhow::Result<Vec<RemoteActor>> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
data.federation_repo.get_pending_followers(local_user_id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_accepted_followers(&self, local_user_id: uuid::Uuid) -> anyhow::Result<Vec<RemoteActor>> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
let followers = data.federation_repo.get_followers(local_user_id).await?;
|
||||||
|
Ok(followers
|
||||||
|
.into_iter()
|
||||||
|
.filter(|f| f.status == FollowerStatus::Accepted)
|
||||||
|
.map(|f| f.actor)
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn count_accepted_followers(&self, local_user_id: uuid::Uuid) -> anyhow::Result<usize> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
let followers = data.federation_repo.get_followers(local_user_id).await?;
|
||||||
|
Ok(followers.into_iter().filter(|f| f.status == FollowerStatus::Accepted).count())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_following(&self, local_user_id: uuid::Uuid) -> anyhow::Result<Vec<RemoteActor>> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
data.federation_repo.get_following(local_user_id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn count_following(&self, local_user_id: uuid::Uuid) -> anyhow::Result<usize> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
data.federation_repo.count_following(local_user_id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn remove_follower(&self, local_user_id: uuid::Uuid, actor_url: &str) -> anyhow::Result<()> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
data.federation_repo.remove_follower(local_user_id, actor_url).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Broadcast a single object to all accepted followers as a Create activity.
|
||||||
|
/// Called by project-specific event handlers when new content is created.
|
||||||
|
pub async fn broadcast_to_followers(
|
||||||
|
&self,
|
||||||
|
local_user_id: uuid::Uuid,
|
||||||
|
ap_id: Url,
|
||||||
|
object: serde_json::Value,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
let local_actor = get_local_actor(local_user_id, &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
|
let followers = data.federation_repo.get_followers(local_user_id).await?;
|
||||||
|
let accepted: Vec<_> = followers
|
||||||
|
.into_iter()
|
||||||
|
.filter(|f| f.status == FollowerStatus::Accepted)
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
if accepted.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let create = CreateActivity {
|
||||||
|
id: ap_id.clone(),
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
object,
|
||||||
|
};
|
||||||
|
let create_with_ctx = WithContext::new_default(create);
|
||||||
|
|
||||||
|
let inboxes: Vec<Url> = accepted
|
||||||
|
.iter()
|
||||||
|
.filter_map(|f| Url::parse(&f.actor.inbox_url).ok())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let sends = SendActivityTask::prepare(&create_with_ctx, &local_actor, inboxes, &data).await?;
|
||||||
|
let failures = send_with_retry(sends, &data).await;
|
||||||
|
if !failures.is_empty() {
|
||||||
|
tracing::warn!(count = failures.len(), "some activity deliveries failed permanently");
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spawn_backfill(&self, owner_user_id: uuid::Uuid, follower_inbox_url: String) {
|
||||||
|
let config = self.federation_config.clone();
|
||||||
|
let base_url = self.base_url.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
if let Err(e) = ActivityPubService::run_backfill(config, base_url, owner_user_id, follower_inbox_url).await {
|
||||||
|
tracing::warn!(error = %e, "backfill: task failed");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run_backfill(
|
||||||
|
config: ApFederationConfig,
|
||||||
|
base_url: String,
|
||||||
|
owner_user_id: uuid::Uuid,
|
||||||
|
follower_inbox_url: String,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
const BATCH_SIZE: usize = 20;
|
||||||
|
|
||||||
|
let data = config.to_request_data();
|
||||||
|
let local_actor = get_local_actor(owner_user_id, &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
let inbox = Url::parse(&follower_inbox_url)?;
|
||||||
|
|
||||||
|
let mut objects = data.object_handler.get_local_objects_for_user(owner_user_id).await?;
|
||||||
|
objects.reverse(); // oldest first → chronological feed
|
||||||
|
|
||||||
|
let total = objects.len();
|
||||||
|
let mut success_count = 0usize;
|
||||||
|
let mut failure_count = 0usize;
|
||||||
|
|
||||||
|
for chunk in objects.chunks(BATCH_SIZE) {
|
||||||
|
for (ap_id, object_json) in chunk {
|
||||||
|
// Use a stable Create activity ID derived from the object's ap_id
|
||||||
|
let create_id = Url::parse(&format!("{}/activities/create/{}", base_url,
|
||||||
|
uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_URL, ap_id.as_str().as_bytes())
|
||||||
|
))?;
|
||||||
|
|
||||||
|
let create = CreateActivity {
|
||||||
|
id: create_id,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
object: object_json.clone(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let sends = SendActivityTask::prepare(
|
||||||
|
&WithContext::new_default(create),
|
||||||
|
&local_actor,
|
||||||
|
vec![inbox.clone()],
|
||||||
|
&data,
|
||||||
|
).await?;
|
||||||
|
let failures = send_with_retry(sends, &data).await;
|
||||||
|
if failures.is_empty() {
|
||||||
|
success_count += 1;
|
||||||
|
} else {
|
||||||
|
failure_count += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
user_id = %owner_user_id,
|
||||||
|
follower = %follower_inbox_url,
|
||||||
|
sent = success_count,
|
||||||
|
failed = failure_count,
|
||||||
|
total = total,
|
||||||
|
"backfill complete"
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
20
crates/adapters/activitypub-base/src/urls.rs
Normal file
20
crates/adapters/activitypub-base/src/urls.rs
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
use url::Url;
|
||||||
|
|
||||||
|
use crate::error::Error;
|
||||||
|
|
||||||
|
pub fn extract_user_id_from_url(url: &Url) -> Option<uuid::Uuid> {
|
||||||
|
let path = url.path();
|
||||||
|
path.strip_prefix("/users/")
|
||||||
|
.and_then(|s| s.split('/').next())
|
||||||
|
.and_then(|s| uuid::Uuid::parse_str(s).ok())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn activity_url(base_url: &str) -> Result<Url, Error> {
|
||||||
|
Url::parse(&format!("{}/activities/{}", base_url, uuid::Uuid::new_v4()))
|
||||||
|
.map_err(|e| Error::bad_request(anyhow::anyhow!(e)))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn actor_url(base_url: &str, user_id: uuid::Uuid) -> Url {
|
||||||
|
Url::parse(&format!("{}/users/{}", base_url, user_id))
|
||||||
|
.expect("base_url is always a valid URL prefix")
|
||||||
|
}
|
||||||
13
crates/adapters/activitypub-base/src/user.rs
Normal file
13
crates/adapters/activitypub-base/src/user.rs
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
use async_trait::async_trait;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ApUser {
|
||||||
|
pub id: uuid::Uuid,
|
||||||
|
pub username: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
pub trait ApUserRepository: Send + Sync {
|
||||||
|
async fn find_by_id(&self, id: uuid::Uuid) -> anyhow::Result<Option<ApUser>>;
|
||||||
|
async fn find_by_username(&self, username: &str) -> anyhow::Result<Option<ApUser>>;
|
||||||
|
}
|
||||||
42
crates/adapters/activitypub-base/src/webfinger.rs
Normal file
42
crates/adapters/activitypub-base/src/webfinger.rs
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
use activitypub_federation::{
|
||||||
|
config::Data,
|
||||||
|
fetch::webfinger::{build_webfinger_response, extract_webfinger_name, Webfinger},
|
||||||
|
};
|
||||||
|
use axum::{
|
||||||
|
extract::Query,
|
||||||
|
http::header,
|
||||||
|
response::{IntoResponse, Response},
|
||||||
|
};
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use crate::data::FederationData;
|
||||||
|
use crate::error::Error;
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct WebfingerQuery {
|
||||||
|
resource: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn webfinger_handler(
|
||||||
|
Query(query): Query<WebfingerQuery>,
|
||||||
|
data: Data<FederationData>,
|
||||||
|
) -> Result<Response, Error> {
|
||||||
|
let name = extract_webfinger_name(&query.resource, &data)?;
|
||||||
|
|
||||||
|
let user = data
|
||||||
|
.user_repo
|
||||||
|
.find_by_username(name)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)?
|
||||||
|
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found")))?;
|
||||||
|
|
||||||
|
let ap_id = crate::urls::actor_url(&data.base_url, user.id);
|
||||||
|
|
||||||
|
let wf: Webfinger = build_webfinger_response(query.resource, ap_id);
|
||||||
|
let body = serde_json::to_string(&wf)
|
||||||
|
.map_err(|e| Error::from(anyhow::anyhow!(e)))?;
|
||||||
|
Ok((
|
||||||
|
[(header::CONTENT_TYPE, "application/jrd+json")],
|
||||||
|
body,
|
||||||
|
).into_response())
|
||||||
|
}
|
||||||
20
crates/adapters/activitypub/Cargo.toml
Normal file
20
crates/adapters/activitypub/Cargo.toml
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
[package]
|
||||||
|
name = "activitypub"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
activitypub-base = { workspace = true }
|
||||||
|
domain = { workspace = true }
|
||||||
|
tokio = { workspace = true }
|
||||||
|
serde = { workspace = true }
|
||||||
|
serde_json = { workspace = true }
|
||||||
|
uuid = { workspace = true }
|
||||||
|
chrono = { workspace = true }
|
||||||
|
anyhow = { workspace = true }
|
||||||
|
tracing = { workspace = true }
|
||||||
|
async-trait = { workspace = true }
|
||||||
|
event-publisher = { workspace = true }
|
||||||
|
|
||||||
|
activitypub_federation = "0.7.0-beta.11"
|
||||||
|
url = { version = "2", features = ["serde"] }
|
||||||
361
crates/adapters/activitypub/src/activities.rs
Normal file
361
crates/adapters/activitypub/src/activities.rs
Normal file
@@ -0,0 +1,361 @@
|
|||||||
|
use activitypub_federation::{
|
||||||
|
config::Data,
|
||||||
|
fetch::object_id::ObjectId,
|
||||||
|
kinds::activity::{AcceptType, CreateType, DeleteType, FollowType, RejectType, UndoType, UpdateType},
|
||||||
|
traits::{Activity, Object},
|
||||||
|
};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
use crate::actors::DbActor;
|
||||||
|
use crate::data::FederationData;
|
||||||
|
use crate::error::Error;
|
||||||
|
use crate::objects::{DbReview, ReviewObject};
|
||||||
|
use crate::repository::{FollowerStatus, FollowingStatus};
|
||||||
|
|
||||||
|
// --- Follow ---
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct FollowActivity {
|
||||||
|
pub(crate) id: Url,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub(crate) kind: FollowType,
|
||||||
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
|
pub(crate) object: ObjectId<DbActor>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Activity for FollowActivity {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actor(&self) -> &Url {
|
||||||
|
self.actor.inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(&self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
let target_url = self.object.inner();
|
||||||
|
// Url::domain() strips the port, so build host:port explicitly
|
||||||
|
let target_domain = match (target_url.host_str(), target_url.port()) {
|
||||||
|
(Some(host), Some(port)) => format!("{}:{}", host, port),
|
||||||
|
(Some(host), None) => host.to_string(),
|
||||||
|
_ => return Err(Error::bad_request(anyhow::anyhow!("invalid follow target URL"))),
|
||||||
|
};
|
||||||
|
if target_domain != data.domain {
|
||||||
|
return Err(Error::bad_request(anyhow::anyhow!("follow target is not a local actor")));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
let _follower = self.actor.dereference(data).await?;
|
||||||
|
let local_actor = self.object.dereference(data).await?;
|
||||||
|
|
||||||
|
data.federation_repo
|
||||||
|
.add_follower(
|
||||||
|
local_actor.user_id.clone(),
|
||||||
|
self.actor.inner().as_str(),
|
||||||
|
FollowerStatus::Pending,
|
||||||
|
self.id.as_str(),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
follower = %self.actor.inner(),
|
||||||
|
local_user = %local_actor.user_id.value(),
|
||||||
|
"follow request pending approval"
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Accept ---
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct AcceptActivity {
|
||||||
|
pub(crate) id: Url,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub(crate) kind: AcceptType,
|
||||||
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
|
pub(crate) object: FollowActivity,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Activity for AcceptActivity {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actor(&self) -> &Url {
|
||||||
|
self.actor.inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
let local_user_id = crate::urls::extract_user_id_from_url(self.object.actor.inner())
|
||||||
|
.ok_or_else(|| Error::bad_request(anyhow::anyhow!("invalid actor URL in Follow")))?;
|
||||||
|
let remote_actor_url = self.actor.inner().as_str();
|
||||||
|
data.federation_repo
|
||||||
|
.update_following_status(local_user_id, remote_actor_url, FollowingStatus::Accepted)
|
||||||
|
.await?;
|
||||||
|
tracing::info!(
|
||||||
|
remote_actor = %self.actor.inner(),
|
||||||
|
"follow accepted by remote"
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Reject ---
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct RejectActivity {
|
||||||
|
pub(crate) id: Url,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub(crate) kind: RejectType,
|
||||||
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
|
pub(crate) object: FollowActivity,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Activity for RejectActivity {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actor(&self) -> &Url {
|
||||||
|
self.actor.inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
// The actor rejected our follow. Extract the local user from the original Follow's actor.
|
||||||
|
let local_user_url = self.object.actor.inner();
|
||||||
|
if let Some(user_id) = crate::urls::extract_user_id_from_url(local_user_url) {
|
||||||
|
data.federation_repo
|
||||||
|
.remove_following(user_id, self.actor.inner().as_str())
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
tracing::info!(actor = %self.actor.inner(), "follow rejected");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Undo ---
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct UndoActivity {
|
||||||
|
pub(crate) id: Url,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub(crate) kind: UndoType,
|
||||||
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
|
pub(crate) object: FollowActivity,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Activity for UndoActivity {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actor(&self) -> &Url {
|
||||||
|
self.actor.inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
// Remote actor is unfollowing a local user
|
||||||
|
let local_user_url = self.object.object.inner();
|
||||||
|
if let Some(user_id) = crate::urls::extract_user_id_from_url(local_user_url) {
|
||||||
|
data.federation_repo
|
||||||
|
.remove_follower(user_id, self.actor.inner().as_str())
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
tracing::info!(actor = %self.actor.inner(), "unfollowed");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Create ---
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct CreateActivity {
|
||||||
|
pub(crate) id: Url,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub(crate) kind: CreateType,
|
||||||
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
|
pub(crate) object: ReviewObject,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Activity for CreateActivity {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actor(&self) -> &Url {
|
||||||
|
self.actor.inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
if self.object.attributed_to.inner() != self.actor.inner() {
|
||||||
|
return Err(Error::bad_request(anyhow::anyhow!(
|
||||||
|
"activity actor does not match object attributed_to"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
DbReview::from_json(self.object, data).await?;
|
||||||
|
tracing::info!(actor = %self.actor.inner(), "received review");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Delete ---
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct DeleteActivity {
|
||||||
|
pub(crate) id: Url,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub(crate) kind: DeleteType,
|
||||||
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
|
pub(crate) object: Url,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Activity for DeleteActivity {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actor(&self) -> &Url {
|
||||||
|
self.actor.inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
data.federation_repo
|
||||||
|
.delete_remote_review_by_ap_id(
|
||||||
|
self.object.as_str(),
|
||||||
|
self.actor.inner().as_str(),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
tracing::info!(object = %self.object, "remote review deleted");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Update ---
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct UpdateActivity {
|
||||||
|
pub(crate) id: Url,
|
||||||
|
#[serde(rename = "type", default)]
|
||||||
|
pub(crate) kind: UpdateType,
|
||||||
|
pub(crate) actor: ObjectId<DbActor>,
|
||||||
|
pub(crate) object: serde_json::Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Activity for UpdateActivity {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actor(&self) -> &Url {
|
||||||
|
self.actor.inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||||
|
let object: ReviewObject = match serde_json::from_value(self.object) {
|
||||||
|
Ok(o) => o,
|
||||||
|
Err(_) => {
|
||||||
|
tracing::debug!(actor = %self.actor.inner(), "ignoring non-review Update activity");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if object.attributed_to.inner() != self.actor.inner() {
|
||||||
|
return Err(Error::bad_request(anyhow::anyhow!(
|
||||||
|
"update actor does not match object attributed_to"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
let ap_id = object.id.inner().as_str();
|
||||||
|
let rating = object.rating.min(5);
|
||||||
|
let comment = object.comment.as_deref();
|
||||||
|
let watched_at = object.watched_at.naive_utc();
|
||||||
|
data.federation_repo
|
||||||
|
.update_remote_review(ap_id, self.actor.inner().as_str(), rating, comment, watched_at)
|
||||||
|
.await?;
|
||||||
|
tracing::info!(actor = %self.actor.inner(), ap_id = %ap_id, "remote review updated");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Inbox dispatch enum ---
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
#[serde(tag = "type")]
|
||||||
|
#[enum_delegate::implement(Activity)]
|
||||||
|
pub enum InboxActivities {
|
||||||
|
#[serde(rename = "Follow")]
|
||||||
|
Follow(FollowActivity),
|
||||||
|
#[serde(rename = "Accept")]
|
||||||
|
Accept(AcceptActivity),
|
||||||
|
#[serde(rename = "Reject")]
|
||||||
|
Reject(RejectActivity),
|
||||||
|
#[serde(rename = "Undo")]
|
||||||
|
Undo(UndoActivity),
|
||||||
|
#[serde(rename = "Create")]
|
||||||
|
Create(CreateActivity),
|
||||||
|
#[serde(rename = "Delete")]
|
||||||
|
Delete(DeleteActivity),
|
||||||
|
#[serde(rename = "Update")]
|
||||||
|
Update(UpdateActivity),
|
||||||
|
}
|
||||||
24
crates/adapters/activitypub/src/actor_handler.rs
Normal file
24
crates/adapters/activitypub/src/actor_handler.rs
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
use activitypub_federation::{
|
||||||
|
axum::json::FederationJson, config::Data, protocol::context::WithContext, traits::Object,
|
||||||
|
};
|
||||||
|
use axum::extract::Path;
|
||||||
|
|
||||||
|
use domain::value_objects::UserId;
|
||||||
|
|
||||||
|
use crate::actors::{get_local_actor, Person};
|
||||||
|
use crate::data::FederationData;
|
||||||
|
use crate::error::Error;
|
||||||
|
|
||||||
|
pub async fn actor_handler(
|
||||||
|
Path(user_id_str): Path<String>,
|
||||||
|
data: Data<FederationData>,
|
||||||
|
) -> Result<FederationJson<WithContext<Person>>, Error> {
|
||||||
|
let uuid = uuid::Uuid::parse_str(&user_id_str)
|
||||||
|
.map_err(|_| Error::bad_request(anyhow::anyhow!("invalid user id")))?;
|
||||||
|
let user_id = UserId::from_uuid(uuid);
|
||||||
|
|
||||||
|
let db_actor = get_local_actor(user_id, &data).await?;
|
||||||
|
let person = db_actor.into_json(&data).await?;
|
||||||
|
|
||||||
|
Ok(FederationJson(WithContext::new_default(person)))
|
||||||
|
}
|
||||||
235
crates/adapters/activitypub/src/actors.rs
Normal file
235
crates/adapters/activitypub/src/actors.rs
Normal file
@@ -0,0 +1,235 @@
|
|||||||
|
use activitypub_federation::{
|
||||||
|
config::Data,
|
||||||
|
fetch::object_id::ObjectId,
|
||||||
|
http_signatures::generate_actor_keypair,
|
||||||
|
kinds::actor::PersonType,
|
||||||
|
protocol::{public_key::PublicKey, verification::verify_domains_match},
|
||||||
|
traits::{Actor, Object},
|
||||||
|
};
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
use domain::value_objects::UserId;
|
||||||
|
|
||||||
|
use crate::data::FederationData;
|
||||||
|
use crate::error::Error;
|
||||||
|
use crate::repository::RemoteActor;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct DbActor {
|
||||||
|
pub user_id: UserId,
|
||||||
|
pub username: String,
|
||||||
|
pub public_key_pem: String,
|
||||||
|
pub private_key_pem: Option<String>,
|
||||||
|
pub inbox_url: Url,
|
||||||
|
pub outbox_url: Url,
|
||||||
|
pub followers_url: Url,
|
||||||
|
pub following_url: Url,
|
||||||
|
pub ap_id: Url,
|
||||||
|
pub last_refreshed_at: DateTime<Utc>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct Person {
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
kind: PersonType,
|
||||||
|
id: ObjectId<DbActor>,
|
||||||
|
preferred_username: String,
|
||||||
|
inbox: Url,
|
||||||
|
outbox: Url,
|
||||||
|
followers: Url,
|
||||||
|
following: Url,
|
||||||
|
public_key: PublicKey,
|
||||||
|
name: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_local_actor(
|
||||||
|
user_id: UserId,
|
||||||
|
data: &Data<FederationData>,
|
||||||
|
) -> Result<DbActor, Error> {
|
||||||
|
let user = data
|
||||||
|
.user_repo
|
||||||
|
.find_by_id(&user_id)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)?
|
||||||
|
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found: {}", user_id.value())))?;
|
||||||
|
|
||||||
|
let (public_key, private_key) = match data
|
||||||
|
.federation_repo
|
||||||
|
.get_local_actor_keypair(user_id.clone())
|
||||||
|
.await?
|
||||||
|
{
|
||||||
|
Some(kp) => kp,
|
||||||
|
None => {
|
||||||
|
let kp = generate_actor_keypair()?;
|
||||||
|
data.federation_repo
|
||||||
|
.save_local_actor_keypair(
|
||||||
|
user_id.clone(),
|
||||||
|
kp.public_key.clone(),
|
||||||
|
kp.private_key.clone(),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
(kp.public_key, kp.private_key)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let ap_id = crate::urls::actor_url(&data.base_url, user.id());
|
||||||
|
let inbox_url = Url::parse(&format!("{}/inbox", &ap_id)).expect("valid inbox url");
|
||||||
|
let outbox_url = Url::parse(&format!("{}/outbox", &ap_id)).expect("valid outbox url");
|
||||||
|
let followers_url = Url::parse(&format!("{}/followers", &ap_id)).expect("valid followers url");
|
||||||
|
let following_url = Url::parse(&format!("{}/following", &ap_id)).expect("valid following url");
|
||||||
|
|
||||||
|
Ok(DbActor {
|
||||||
|
user_id: user.id().clone(),
|
||||||
|
username: user.username().value().to_string(),
|
||||||
|
public_key_pem: public_key,
|
||||||
|
private_key_pem: Some(private_key),
|
||||||
|
inbox_url,
|
||||||
|
outbox_url,
|
||||||
|
followers_url,
|
||||||
|
following_url,
|
||||||
|
ap_id,
|
||||||
|
last_refreshed_at: Utc::now(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl Object for DbActor {
|
||||||
|
type DataType = FederationData;
|
||||||
|
type Kind = Person;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn id(&self) -> &Url {
|
||||||
|
&self.ap_id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn last_refreshed_at(&self) -> Option<DateTime<Utc>> {
|
||||||
|
Some(self.last_refreshed_at)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn read_from_id(
|
||||||
|
object_id: Url,
|
||||||
|
data: &Data<Self::DataType>,
|
||||||
|
) -> Result<Option<Self>, Self::Error> {
|
||||||
|
// Extract user_id from URL path: /users/{uuid}
|
||||||
|
let user_id = match crate::urls::extract_user_id_from_url(&object_id) {
|
||||||
|
Some(id) => id,
|
||||||
|
None => return Ok(None),
|
||||||
|
};
|
||||||
|
let user = match data.user_repo.find_by_id(&user_id).await {
|
||||||
|
Ok(Some(u)) => u,
|
||||||
|
_ => return Ok(None),
|
||||||
|
};
|
||||||
|
|
||||||
|
let keypair = data
|
||||||
|
.federation_repo
|
||||||
|
.get_local_actor_keypair(user_id.clone())
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let (public_key, private_key) = match keypair {
|
||||||
|
Some(kp) => (kp.0, Some(kp.1)),
|
||||||
|
None => return Ok(None),
|
||||||
|
};
|
||||||
|
|
||||||
|
let ap_id = crate::urls::actor_url(&data.base_url, user.id());
|
||||||
|
let inbox_url = Url::parse(&format!("{}/inbox", &ap_id)).expect("valid url");
|
||||||
|
let outbox_url = Url::parse(&format!("{}/outbox", &ap_id)).expect("valid url");
|
||||||
|
let followers_url = Url::parse(&format!("{}/followers", &ap_id)).expect("valid url");
|
||||||
|
let following_url = Url::parse(&format!("{}/following", &ap_id)).expect("valid url");
|
||||||
|
|
||||||
|
Ok(Some(DbActor {
|
||||||
|
user_id: user.id().clone(),
|
||||||
|
username: user.username().value().to_string(),
|
||||||
|
public_key_pem: public_key,
|
||||||
|
private_key_pem: private_key,
|
||||||
|
inbox_url,
|
||||||
|
outbox_url,
|
||||||
|
followers_url,
|
||||||
|
following_url,
|
||||||
|
ap_id,
|
||||||
|
last_refreshed_at: Utc::now(),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn into_json(self, _data: &Data<Self::DataType>) -> Result<Self::Kind, Self::Error> {
|
||||||
|
let public_key = PublicKey {
|
||||||
|
id: format!("{}#main-key", &self.ap_id),
|
||||||
|
owner: self.ap_id.clone(),
|
||||||
|
public_key_pem: self.public_key_pem.clone(),
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(Person {
|
||||||
|
kind: Default::default(),
|
||||||
|
id: self.ap_id.clone().into(),
|
||||||
|
preferred_username: self.username.clone(),
|
||||||
|
inbox: self.inbox_url.clone(),
|
||||||
|
outbox: self.outbox_url.clone(),
|
||||||
|
followers: self.followers_url.clone(),
|
||||||
|
following: self.following_url.clone(),
|
||||||
|
public_key,
|
||||||
|
name: Some(self.username.clone()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(
|
||||||
|
json: &Self::Kind,
|
||||||
|
expected_domain: &Url,
|
||||||
|
_data: &Data<Self::DataType>,
|
||||||
|
) -> Result<(), Self::Error> {
|
||||||
|
verify_domains_match(json.id.inner(), expected_domain)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn from_json(
|
||||||
|
json: Self::Kind,
|
||||||
|
data: &Data<Self::DataType>,
|
||||||
|
) -> Result<Self, Self::Error> {
|
||||||
|
let actor = RemoteActor {
|
||||||
|
url: json.id.inner().to_string(),
|
||||||
|
handle: json.preferred_username.clone(),
|
||||||
|
inbox_url: json.inbox.to_string(),
|
||||||
|
shared_inbox_url: None,
|
||||||
|
display_name: json.name.clone(),
|
||||||
|
};
|
||||||
|
data.federation_repo.upsert_remote_actor(actor).await?;
|
||||||
|
|
||||||
|
// Deterministic UUID from actor URL so the same remote actor always maps to the same UserId
|
||||||
|
let url_str = json.id.inner().to_string();
|
||||||
|
let stable_id = uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_URL, url_str.as_bytes());
|
||||||
|
let user_id = UserId::from_uuid(stable_id);
|
||||||
|
let ap_id = json.id.inner().clone();
|
||||||
|
let inbox_url = json.inbox.clone();
|
||||||
|
let outbox_url = json.outbox.clone();
|
||||||
|
let followers_url = json.followers.clone();
|
||||||
|
let following_url = json.following.clone();
|
||||||
|
|
||||||
|
Ok(DbActor {
|
||||||
|
user_id,
|
||||||
|
username: json.preferred_username.clone(),
|
||||||
|
public_key_pem: json.public_key.public_key_pem,
|
||||||
|
private_key_pem: None,
|
||||||
|
inbox_url,
|
||||||
|
outbox_url,
|
||||||
|
followers_url,
|
||||||
|
following_url,
|
||||||
|
ap_id,
|
||||||
|
last_refreshed_at: Utc::now(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Actor for DbActor {
|
||||||
|
fn public_key_pem(&self) -> &str {
|
||||||
|
&self.public_key_pem
|
||||||
|
}
|
||||||
|
|
||||||
|
fn private_key_pem(&self) -> Option<String> {
|
||||||
|
self.private_key_pem.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn inbox(&self) -> Url {
|
||||||
|
self.inbox_url.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
38
crates/adapters/activitypub/src/data.rs
Normal file
38
crates/adapters/activitypub/src/data.rs
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use domain::ports::{MovieRepository, UserRepository};
|
||||||
|
|
||||||
|
use crate::repository::FederationRepository;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct FederationData {
|
||||||
|
pub(crate) federation_repo: Arc<dyn FederationRepository>,
|
||||||
|
pub(crate) user_repo: Arc<dyn UserRepository>,
|
||||||
|
pub(crate) movie_repo: Arc<dyn MovieRepository>,
|
||||||
|
pub(crate) base_url: String,
|
||||||
|
pub(crate) domain: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FederationData {
|
||||||
|
pub fn new(
|
||||||
|
federation_repo: Arc<dyn FederationRepository>,
|
||||||
|
user_repo: Arc<dyn UserRepository>,
|
||||||
|
movie_repo: Arc<dyn MovieRepository>,
|
||||||
|
base_url: String,
|
||||||
|
) -> Self {
|
||||||
|
let domain = base_url
|
||||||
|
.trim_start_matches("https://")
|
||||||
|
.trim_start_matches("http://")
|
||||||
|
.split('/')
|
||||||
|
.next()
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_string();
|
||||||
|
Self {
|
||||||
|
federation_repo,
|
||||||
|
user_repo,
|
||||||
|
movie_repo,
|
||||||
|
base_url,
|
||||||
|
domain,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
49
crates/adapters/activitypub/src/error.rs
Normal file
49
crates/adapters/activitypub/src/error.rs
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
use std::fmt::{Display, Formatter};
|
||||||
|
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Error(pub(crate) anyhow::Error, pub(crate) StatusCode);
|
||||||
|
|
||||||
|
impl Error {
|
||||||
|
pub fn not_found(e: impl Into<anyhow::Error>) -> Self {
|
||||||
|
Self(e.into(), StatusCode::NOT_FOUND)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn bad_request(e: impl Into<anyhow::Error>) -> Self {
|
||||||
|
Self(e.into(), StatusCode::BAD_REQUEST)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for Error {
|
||||||
|
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||||
|
std::fmt::Display::fmt(&self.0, f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> From<T> for Error
|
||||||
|
where
|
||||||
|
T: Into<anyhow::Error>,
|
||||||
|
{
|
||||||
|
fn from(t: T) -> Self {
|
||||||
|
Error(t.into(), StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl axum::response::IntoResponse for Error {
|
||||||
|
fn into_response(self) -> axum::response::Response {
|
||||||
|
let status = self.1;
|
||||||
|
if status.is_server_error() {
|
||||||
|
tracing::error!(error = %self.0, status = status.as_u16(), "federation error");
|
||||||
|
} else {
|
||||||
|
tracing::debug!(error = %self.0, status = status.as_u16(), "federation response");
|
||||||
|
}
|
||||||
|
let body = if status.is_server_error() {
|
||||||
|
"internal server error".to_string()
|
||||||
|
} else {
|
||||||
|
self.0.to_string()
|
||||||
|
};
|
||||||
|
(status, body).into_response()
|
||||||
|
}
|
||||||
|
}
|
||||||
77
crates/adapters/activitypub/src/event_handler.rs
Normal file
77
crates/adapters/activitypub/src/event_handler.rs
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
use async_trait::async_trait;
|
||||||
|
use domain::{
|
||||||
|
errors::DomainError,
|
||||||
|
events::DomainEvent,
|
||||||
|
ports::MovieRepository,
|
||||||
|
value_objects::{ReviewId, UserId},
|
||||||
|
};
|
||||||
|
use event_publisher::EventHandler;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use activitypub_base::ActivityPubService;
|
||||||
|
|
||||||
|
use crate::objects::review_to_ap_object;
|
||||||
|
use crate::urls::{actor_url, review_url};
|
||||||
|
|
||||||
|
pub struct ActivityPubEventHandler {
|
||||||
|
ap_service: Arc<ActivityPubService>,
|
||||||
|
movie_repo: Arc<dyn MovieRepository>,
|
||||||
|
base_url: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActivityPubEventHandler {
|
||||||
|
pub fn new(
|
||||||
|
ap_service: Arc<ActivityPubService>,
|
||||||
|
movie_repo: Arc<dyn MovieRepository>,
|
||||||
|
base_url: String,
|
||||||
|
) -> Self {
|
||||||
|
Self { ap_service, movie_repo, base_url }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl EventHandler for ActivityPubEventHandler {
|
||||||
|
async fn handle(&self, event: &DomainEvent) -> Result<(), DomainError> {
|
||||||
|
match event {
|
||||||
|
DomainEvent::ReviewLogged { review_id, user_id, .. } => self
|
||||||
|
.on_review_logged(user_id, review_id)
|
||||||
|
.await
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(e.to_string())),
|
||||||
|
_ => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActivityPubEventHandler {
|
||||||
|
async fn on_review_logged(
|
||||||
|
&self,
|
||||||
|
user_id: &UserId,
|
||||||
|
review_id: &ReviewId,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let review = match self.movie_repo.get_review_by_id(review_id).await? {
|
||||||
|
Some(r) => r,
|
||||||
|
None => return Ok(()),
|
||||||
|
};
|
||||||
|
|
||||||
|
let ap_id = review_url(&self.base_url, review_id);
|
||||||
|
let actor = actor_url(&self.base_url, user_id.value());
|
||||||
|
|
||||||
|
let movie = self.movie_repo.get_movie_by_id(review.movie_id()).await.ok().flatten();
|
||||||
|
let movie_title = movie.as_ref()
|
||||||
|
.map(|m| m.title().value().to_string())
|
||||||
|
.unwrap_or_else(|| "Unknown".to_string());
|
||||||
|
let release_year = movie.as_ref().map(|m| m.release_year().value()).unwrap_or(0);
|
||||||
|
let poster_url = movie.as_ref()
|
||||||
|
.and_then(|m| m.poster_path())
|
||||||
|
.map(|p| format!("{}/posters/{}", self.base_url, p.value()));
|
||||||
|
|
||||||
|
let obj = review_to_ap_object(&review, ap_id.clone(), actor, movie_title, release_year, poster_url);
|
||||||
|
let json = serde_json::to_value(obj)?;
|
||||||
|
|
||||||
|
self.ap_service
|
||||||
|
.broadcast_to_followers(user_id.value(), ap_id, json)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
52
crates/adapters/activitypub/src/federation.rs
Normal file
52
crates/adapters/activitypub/src/federation.rs
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
use activitypub_federation::config::{Data, FederationConfig, FederationMiddleware, UrlVerifier};
|
||||||
|
use activitypub_federation::error::Error as FedError;
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
use crate::data::FederationData;
|
||||||
|
|
||||||
|
// In debug mode, allow all URLs (including http://localhost:3000 where the
|
||||||
|
// port colon would otherwise fail the default domain character check).
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct PermissiveVerifier;
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl UrlVerifier for PermissiveVerifier {
|
||||||
|
async fn verify(&self, _url: &Url) -> Result<(), FedError> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct ApFederationConfig(pub FederationConfig<FederationData>);
|
||||||
|
|
||||||
|
impl ApFederationConfig {
|
||||||
|
pub async fn new(data: FederationData, debug: bool) -> anyhow::Result<Self> {
|
||||||
|
let config = if debug {
|
||||||
|
FederationConfig::builder()
|
||||||
|
.domain(&data.domain)
|
||||||
|
.app_data(data)
|
||||||
|
.debug(true)
|
||||||
|
.http_signature_compat(true)
|
||||||
|
.url_verifier(Box::new(PermissiveVerifier))
|
||||||
|
.build()
|
||||||
|
.await?
|
||||||
|
} else {
|
||||||
|
FederationConfig::builder()
|
||||||
|
.domain(&data.domain)
|
||||||
|
.app_data(data)
|
||||||
|
.debug(false)
|
||||||
|
.http_signature_compat(true)
|
||||||
|
.build()
|
||||||
|
.await?
|
||||||
|
};
|
||||||
|
Ok(Self(config))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_request_data(&self) -> Data<FederationData> {
|
||||||
|
self.0.to_request_data()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn middleware(&self) -> FederationMiddleware<FederationData> {
|
||||||
|
FederationMiddleware::new(self.0.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
80
crates/adapters/activitypub/src/followers_handler.rs
Normal file
80
crates/adapters/activitypub/src/followers_handler.rs
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
use activitypub_federation::{axum::json::FederationJson, config::Data};
|
||||||
|
use axum::extract::Path;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
use domain::value_objects::UserId;
|
||||||
|
|
||||||
|
use crate::data::FederationData;
|
||||||
|
use crate::error::Error;
|
||||||
|
use crate::repository::FollowerStatus;
|
||||||
|
|
||||||
|
fn ordered_collection(id: String, total: usize, items: Vec<String>) -> serde_json::Value {
|
||||||
|
json!({
|
||||||
|
"@context": "https://www.w3.org/ns/activitystreams",
|
||||||
|
"type": "OrderedCollection",
|
||||||
|
"id": id,
|
||||||
|
"totalItems": total,
|
||||||
|
"orderedItems": items,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn followers_handler(
|
||||||
|
Path(user_id_str): Path<String>,
|
||||||
|
data: Data<FederationData>,
|
||||||
|
) -> Result<FederationJson<serde_json::Value>, Error> {
|
||||||
|
let user_id = UserId::from_uuid(
|
||||||
|
uuid::Uuid::parse_str(&user_id_str)
|
||||||
|
.map_err(|_| Error::bad_request(anyhow::anyhow!("invalid user id")))?,
|
||||||
|
);
|
||||||
|
|
||||||
|
data.user_repo
|
||||||
|
.find_by_id(&user_id)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)?
|
||||||
|
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found")))?;
|
||||||
|
|
||||||
|
let followers = data
|
||||||
|
.federation_repo
|
||||||
|
.get_followers(user_id)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)?;
|
||||||
|
|
||||||
|
let items: Vec<String> = followers
|
||||||
|
.into_iter()
|
||||||
|
.filter(|f| f.status == FollowerStatus::Accepted)
|
||||||
|
.map(|f| f.actor.url)
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let id = format!("{}/users/{}/followers", data.base_url, user_id_str);
|
||||||
|
Ok(FederationJson(ordered_collection(id, items.len(), items)))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn following_handler(
|
||||||
|
Path(user_id_str): Path<String>,
|
||||||
|
data: Data<FederationData>,
|
||||||
|
) -> Result<FederationJson<serde_json::Value>, Error> {
|
||||||
|
let user_id = UserId::from_uuid(
|
||||||
|
uuid::Uuid::parse_str(&user_id_str)
|
||||||
|
.map_err(|_| Error::bad_request(anyhow::anyhow!("invalid user id")))?,
|
||||||
|
);
|
||||||
|
|
||||||
|
data.user_repo
|
||||||
|
.find_by_id(&user_id)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)?
|
||||||
|
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found")))?;
|
||||||
|
|
||||||
|
let following = data
|
||||||
|
.federation_repo
|
||||||
|
.get_following(user_id)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)?;
|
||||||
|
|
||||||
|
let items: Vec<String> = following
|
||||||
|
.into_iter()
|
||||||
|
.map(|a| a.url)
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let id = format!("{}/users/{}/following", data.base_url, user_id_str);
|
||||||
|
Ok(FederationJson(ordered_collection(id, items.len(), items)))
|
||||||
|
}
|
||||||
20
crates/adapters/activitypub/src/inbox.rs
Normal file
20
crates/adapters/activitypub/src/inbox.rs
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
use activitypub_federation::{
|
||||||
|
axum::inbox::{receive_activity, ActivityData},
|
||||||
|
config::Data,
|
||||||
|
protocol::context::WithContext,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::activities::InboxActivities;
|
||||||
|
use crate::actors::DbActor;
|
||||||
|
use crate::data::FederationData;
|
||||||
|
use crate::error::Error;
|
||||||
|
|
||||||
|
pub async fn inbox_handler(
|
||||||
|
data: Data<FederationData>,
|
||||||
|
activity_data: ActivityData,
|
||||||
|
) -> Result<(), Error> {
|
||||||
|
receive_activity::<WithContext<InboxActivities>, DbActor, FederationData>(
|
||||||
|
activity_data, &data,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
17
crates/adapters/activitypub/src/lib.rs
Normal file
17
crates/adapters/activitypub/src/lib.rs
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
pub mod event_handler;
|
||||||
|
pub mod objects;
|
||||||
|
pub mod remote_review_repository;
|
||||||
|
pub mod review_handler;
|
||||||
|
pub mod user_adapter;
|
||||||
|
pub(crate) mod urls;
|
||||||
|
|
||||||
|
// Re-export the generic base types that callers need
|
||||||
|
pub use activitypub_base::{
|
||||||
|
ActivityPubService, ApFederationConfig, ApObjectHandler, ApUser, ApUserRepository,
|
||||||
|
FederationData, FederationRepository, Follower, FollowerStatus, FollowingStatus, RemoteActor,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub use event_handler::ActivityPubEventHandler;
|
||||||
|
pub use remote_review_repository::RemoteReviewRepository;
|
||||||
|
pub use review_handler::ReviewObjectHandler;
|
||||||
|
pub use user_adapter::DomainUserRepoAdapter;
|
||||||
59
crates/adapters/activitypub/src/objects.rs
Normal file
59
crates/adapters/activitypub/src/objects.rs
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
use activitypub_federation::kinds::object::NoteType;
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
use domain::models::Review;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct ReviewObject {
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
pub(crate) kind: NoteType,
|
||||||
|
pub(crate) id: Url,
|
||||||
|
pub(crate) attributed_to: Url,
|
||||||
|
pub(crate) content: String,
|
||||||
|
pub(crate) published: DateTime<Utc>,
|
||||||
|
pub(crate) movie_title: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub(crate) release_year: u16,
|
||||||
|
#[serde(default)]
|
||||||
|
pub(crate) poster_url: Option<String>,
|
||||||
|
pub(crate) rating: u8,
|
||||||
|
pub(crate) comment: Option<String>,
|
||||||
|
pub(crate) watched_at: DateTime<Utc>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Serialize a local Review into a ReviewObject for AP delivery.
|
||||||
|
/// Takes movie metadata explicitly since the handler fetches it separately.
|
||||||
|
pub fn review_to_ap_object(
|
||||||
|
review: &Review,
|
||||||
|
ap_id: Url,
|
||||||
|
actor_url: Url,
|
||||||
|
movie_title: String,
|
||||||
|
release_year: u16,
|
||||||
|
poster_url: Option<String>,
|
||||||
|
) -> ReviewObject {
|
||||||
|
let stars: String = "\u{2B50}".repeat(review.rating().value() as usize);
|
||||||
|
let comment_text = review.comment().map(|c| c.value().to_string());
|
||||||
|
let year_str = if release_year > 0 { format!(" ({})", release_year) } else { String::new() };
|
||||||
|
let watched_str = format!("Watched: {}", review.watched_at().format("%b %-d, %Y"));
|
||||||
|
let content = match &comment_text {
|
||||||
|
Some(c) => format!("{} {}{}\n{}\n{}", stars, movie_title, year_str, c, watched_str),
|
||||||
|
None => format!("{} {}{}\n{}", stars, movie_title, year_str, watched_str),
|
||||||
|
};
|
||||||
|
|
||||||
|
ReviewObject {
|
||||||
|
kind: NoteType::default(),
|
||||||
|
id: ap_id,
|
||||||
|
attributed_to: actor_url,
|
||||||
|
content,
|
||||||
|
published: DateTime::from_naive_utc_and_offset(*review.created_at(), Utc),
|
||||||
|
movie_title,
|
||||||
|
release_year,
|
||||||
|
poster_url,
|
||||||
|
rating: review.rating().value(),
|
||||||
|
comment: comment_text,
|
||||||
|
watched_at: DateTime::from_naive_utc_and_offset(*review.watched_at(), Utc),
|
||||||
|
}
|
||||||
|
}
|
||||||
56
crates/adapters/activitypub/src/outbox.rs
Normal file
56
crates/adapters/activitypub/src/outbox.rs
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
use activitypub_federation::{axum::json::FederationJson, config::Data};
|
||||||
|
use axum::extract::Path;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use domain::{models::ReviewSource, value_objects::UserId};
|
||||||
|
|
||||||
|
use crate::data::FederationData;
|
||||||
|
use crate::error::Error;
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct OrderedCollection {
|
||||||
|
#[serde(rename = "@context")]
|
||||||
|
context: String,
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
kind: String,
|
||||||
|
id: String,
|
||||||
|
total_items: u64,
|
||||||
|
ordered_items: Vec<serde_json::Value>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn outbox_handler(
|
||||||
|
Path(user_id_str): Path<String>,
|
||||||
|
data: Data<FederationData>,
|
||||||
|
) -> Result<FederationJson<OrderedCollection>, Error> {
|
||||||
|
let uuid = uuid::Uuid::parse_str(&user_id_str)
|
||||||
|
.map_err(|_| Error::bad_request(anyhow::anyhow!("invalid user id")))?;
|
||||||
|
let user_id = UserId::from_uuid(uuid);
|
||||||
|
|
||||||
|
data.user_repo
|
||||||
|
.find_by_id(&user_id)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)?
|
||||||
|
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found")))?;
|
||||||
|
|
||||||
|
let history = data
|
||||||
|
.movie_repo
|
||||||
|
.get_user_history(&user_id)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)?;
|
||||||
|
|
||||||
|
let local_count = history
|
||||||
|
.iter()
|
||||||
|
.filter(|e| matches!(e.review().source(), ReviewSource::Local))
|
||||||
|
.count();
|
||||||
|
|
||||||
|
let outbox_url = format!("{}/users/{}/outbox", data.base_url, user_id_str);
|
||||||
|
|
||||||
|
Ok(FederationJson(OrderedCollection {
|
||||||
|
context: "https://www.w3.org/ns/activitystreams".to_string(),
|
||||||
|
kind: "OrderedCollection".to_string(),
|
||||||
|
id: outbox_url,
|
||||||
|
total_items: local_count as u64,
|
||||||
|
ordered_items: vec![],
|
||||||
|
}))
|
||||||
|
}
|
||||||
29
crates/adapters/activitypub/src/remote_review_repository.rs
Normal file
29
crates/adapters/activitypub/src/remote_review_repository.rs
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
use anyhow::Result;
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use chrono::NaiveDateTime;
|
||||||
|
use domain::models::Review;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
pub trait RemoteReviewRepository: Send + Sync {
|
||||||
|
async fn save_remote_review(
|
||||||
|
&self,
|
||||||
|
review: &Review,
|
||||||
|
ap_id: &str,
|
||||||
|
movie_title: &str,
|
||||||
|
release_year: u16,
|
||||||
|
poster_url: Option<&str>,
|
||||||
|
) -> Result<()>;
|
||||||
|
|
||||||
|
async fn delete_remote_review(&self, ap_id: &str, actor_url: &str) -> Result<()>;
|
||||||
|
|
||||||
|
async fn update_remote_review(
|
||||||
|
&self,
|
||||||
|
ap_id: &str,
|
||||||
|
actor_url: &str,
|
||||||
|
rating: u8,
|
||||||
|
comment: Option<&str>,
|
||||||
|
watched_at: NaiveDateTime,
|
||||||
|
) -> Result<()>;
|
||||||
|
|
||||||
|
async fn delete_by_actor(&self, actor_url: &str) -> Result<()>;
|
||||||
|
}
|
||||||
76
crates/adapters/activitypub/src/repository.rs
Normal file
76
crates/adapters/activitypub/src/repository.rs
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
use anyhow::Result;
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use chrono::NaiveDateTime;
|
||||||
|
use domain::models::Review;
|
||||||
|
use domain::value_objects::UserId;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum FollowerStatus {
|
||||||
|
Pending,
|
||||||
|
Accepted,
|
||||||
|
Rejected,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum FollowingStatus {
|
||||||
|
Pending,
|
||||||
|
Accepted,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct RemoteActor {
|
||||||
|
pub url: String,
|
||||||
|
pub handle: String,
|
||||||
|
pub inbox_url: String,
|
||||||
|
pub shared_inbox_url: Option<String>,
|
||||||
|
pub display_name: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Follower {
|
||||||
|
pub actor: RemoteActor,
|
||||||
|
pub status: FollowerStatus,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
pub trait FederationRepository: Send + Sync {
|
||||||
|
async fn add_follower(&self, local_user_id: UserId, remote_actor_url: &str, status: FollowerStatus, follow_activity_id: &str) -> Result<()>;
|
||||||
|
async fn get_follower_follow_activity_id(&self, local_user_id: UserId, remote_actor_url: &str) -> Result<Option<String>>;
|
||||||
|
async fn remove_follower(&self, local_user_id: UserId, remote_actor_url: &str) -> Result<()>;
|
||||||
|
async fn get_followers(&self, local_user_id: UserId) -> Result<Vec<Follower>>;
|
||||||
|
async fn update_follower_status(&self, local_user_id: UserId, remote_actor_url: &str, status: FollowerStatus) -> Result<()>;
|
||||||
|
async fn add_following(&self, local_user_id: UserId, actor: RemoteActor, follow_activity_id: &str) -> Result<()>;
|
||||||
|
async fn get_follow_activity_id(&self, local_user_id: UserId, remote_actor_url: &str) -> Result<Option<String>>;
|
||||||
|
async fn remove_following(&self, local_user_id: UserId, actor_url: &str) -> Result<()>;
|
||||||
|
async fn get_following(&self, local_user_id: UserId) -> Result<Vec<RemoteActor>>;
|
||||||
|
async fn count_following(&self, local_user_id: UserId) -> Result<usize>;
|
||||||
|
async fn upsert_remote_actor(&self, actor: RemoteActor) -> Result<()>;
|
||||||
|
async fn get_remote_actor(&self, actor_url: &str) -> Result<Option<RemoteActor>>;
|
||||||
|
async fn save_remote_review(
|
||||||
|
&self,
|
||||||
|
review: &Review,
|
||||||
|
ap_id: &str,
|
||||||
|
movie_title: &str,
|
||||||
|
release_year: u16,
|
||||||
|
poster_url: Option<&str>,
|
||||||
|
) -> Result<()>;
|
||||||
|
async fn delete_remote_review_by_ap_id(&self, ap_id: &str, actor_url: &str) -> Result<()>;
|
||||||
|
async fn update_remote_review(
|
||||||
|
&self,
|
||||||
|
ap_id: &str,
|
||||||
|
actor_url: &str,
|
||||||
|
rating: u8,
|
||||||
|
comment: Option<&str>,
|
||||||
|
watched_at: NaiveDateTime,
|
||||||
|
) -> Result<()>;
|
||||||
|
async fn get_local_actor_keypair(&self, user_id: UserId) -> Result<Option<(String, String)>>;
|
||||||
|
async fn save_local_actor_keypair(&self, user_id: UserId, public_key: String, private_key: String) -> Result<()>;
|
||||||
|
async fn delete_remote_reviews_by_actor(&self, actor_url: &str) -> Result<()>;
|
||||||
|
async fn get_pending_followers(&self, local_user_id: UserId) -> Result<Vec<RemoteActor>>;
|
||||||
|
async fn update_following_status(
|
||||||
|
&self,
|
||||||
|
local_user_id: UserId,
|
||||||
|
remote_actor_url: &str,
|
||||||
|
status: FollowingStatus,
|
||||||
|
) -> Result<()>;
|
||||||
|
}
|
||||||
138
crates/adapters/activitypub/src/review_handler.rs
Normal file
138
crates/adapters/activitypub/src/review_handler.rs
Normal file
@@ -0,0 +1,138 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use activitypub_base::ApObjectHandler;
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use domain::{
|
||||||
|
models::{Review, ReviewSource},
|
||||||
|
ports::MovieRepository,
|
||||||
|
value_objects::{Comment, MovieId, Rating, ReviewId, UserId},
|
||||||
|
};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
use crate::objects::{review_to_ap_object, ReviewObject};
|
||||||
|
use crate::remote_review_repository::RemoteReviewRepository;
|
||||||
|
use crate::urls::{actor_url, review_url};
|
||||||
|
|
||||||
|
pub struct ReviewObjectHandler {
|
||||||
|
pub movie_repo: Arc<dyn MovieRepository>,
|
||||||
|
pub review_store: Arc<dyn RemoteReviewRepository>,
|
||||||
|
pub base_url: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl ApObjectHandler for ReviewObjectHandler {
|
||||||
|
async fn get_local_objects_for_user(
|
||||||
|
&self,
|
||||||
|
user_id: uuid::Uuid,
|
||||||
|
) -> anyhow::Result<Vec<(Url, serde_json::Value)>> {
|
||||||
|
let domain_user_id = UserId::from_uuid(user_id);
|
||||||
|
let history = self.movie_repo.get_user_history(&domain_user_id).await?;
|
||||||
|
|
||||||
|
let mut results = Vec::new();
|
||||||
|
for entry in history {
|
||||||
|
let review = entry.review();
|
||||||
|
if !matches!(review.source(), ReviewSource::Local) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let ap_id = review_url(&self.base_url, review.id());
|
||||||
|
let actor_url = actor_url(&self.base_url, user_id);
|
||||||
|
|
||||||
|
let movie = self.movie_repo.get_movie_by_id(review.movie_id()).await.ok().flatten();
|
||||||
|
let movie_title = movie.as_ref()
|
||||||
|
.map(|m| m.title().value().to_string())
|
||||||
|
.unwrap_or_else(|| "Unknown".to_string());
|
||||||
|
let release_year = movie.as_ref()
|
||||||
|
.map(|m| m.release_year().value())
|
||||||
|
.unwrap_or(0);
|
||||||
|
let poster_url = movie.as_ref()
|
||||||
|
.and_then(|m| m.poster_path())
|
||||||
|
.map(|p| format!("{}/posters/{}", self.base_url, p.value()));
|
||||||
|
|
||||||
|
let obj = review_to_ap_object(review, ap_id.clone(), actor_url, movie_title, release_year, poster_url);
|
||||||
|
let json = serde_json::to_value(obj)?;
|
||||||
|
results.push((ap_id, json));
|
||||||
|
}
|
||||||
|
Ok(results)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn on_create(
|
||||||
|
&self,
|
||||||
|
_ap_id: &Url,
|
||||||
|
_actor_url: &Url,
|
||||||
|
object: serde_json::Value,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let obj: ReviewObject = match serde_json::from_value(object) {
|
||||||
|
Ok(o) => o,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::debug!("ignoring unrecognized Create object: {}", e);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let actor_url_str = obj.attributed_to.to_string();
|
||||||
|
let review_id = ReviewId::generate();
|
||||||
|
let movie_id = MovieId::from_uuid(uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_URL, obj.movie_title.as_bytes()));
|
||||||
|
let user_id = UserId::from_uuid(uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_URL, actor_url_str.as_bytes()));
|
||||||
|
let rating = Rating::new(obj.rating.min(5))?;
|
||||||
|
let comment = obj.comment.map(Comment::new).transpose()?;
|
||||||
|
|
||||||
|
let review = Review::from_persistence(
|
||||||
|
review_id,
|
||||||
|
movie_id,
|
||||||
|
user_id,
|
||||||
|
rating,
|
||||||
|
comment,
|
||||||
|
obj.watched_at.naive_utc(),
|
||||||
|
obj.published.naive_utc(),
|
||||||
|
ReviewSource::Remote { actor_url: actor_url_str },
|
||||||
|
);
|
||||||
|
|
||||||
|
self.review_store
|
||||||
|
.save_remote_review(&review, obj.id.as_str(), &obj.movie_title, obj.release_year, obj.poster_url.as_deref())
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn on_update(
|
||||||
|
&self,
|
||||||
|
ap_id: &Url,
|
||||||
|
actor_url: &Url,
|
||||||
|
object: serde_json::Value,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let obj: ReviewObject = match serde_json::from_value(object) {
|
||||||
|
Ok(o) => o,
|
||||||
|
Err(_) => {
|
||||||
|
tracing::debug!(actor = %actor_url, "ignoring non-review Update activity");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if obj.attributed_to != *actor_url {
|
||||||
|
anyhow::bail!("update actor does not match object attributed_to");
|
||||||
|
}
|
||||||
|
|
||||||
|
self.review_store
|
||||||
|
.update_remote_review(
|
||||||
|
ap_id.as_str(),
|
||||||
|
actor_url.as_str(),
|
||||||
|
obj.rating.min(5),
|
||||||
|
obj.comment.as_deref(),
|
||||||
|
obj.watched_at.naive_utc(),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn on_delete(&self, ap_id: &Url, actor_url: &Url) -> anyhow::Result<()> {
|
||||||
|
self.review_store
|
||||||
|
.delete_remote_review(ap_id.as_str(), actor_url.as_str())
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn on_actor_removed(&self, actor_url: &Url) -> anyhow::Result<()> {
|
||||||
|
self.review_store.delete_by_actor(actor_url.as_str()).await
|
||||||
|
}
|
||||||
|
}
|
||||||
485
crates/adapters/activitypub/src/service.rs
Normal file
485
crates/adapters/activitypub/src/service.rs
Normal file
@@ -0,0 +1,485 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use activitypub_federation::{
|
||||||
|
activity_sending::SendActivityTask,
|
||||||
|
config::Data,
|
||||||
|
fetch::{object_id::ObjectId, webfinger::webfinger_resolve_actor},
|
||||||
|
protocol::context::WithContext,
|
||||||
|
traits::Actor,
|
||||||
|
};
|
||||||
|
use axum::{routing::get, routing::post, Router};
|
||||||
|
use domain::{ports::UserRepository, value_objects::UserId};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
activities::{AcceptActivity, CreateActivity, FollowActivity, RejectActivity, UndoActivity},
|
||||||
|
actor_handler::actor_handler,
|
||||||
|
actors::{get_local_actor, DbActor},
|
||||||
|
data::FederationData,
|
||||||
|
event_handler::ActivityPubEventHandler,
|
||||||
|
federation::ApFederationConfig,
|
||||||
|
followers_handler::{followers_handler, following_handler},
|
||||||
|
inbox::inbox_handler,
|
||||||
|
outbox::outbox_handler,
|
||||||
|
repository::{FederationRepository, FollowerStatus, RemoteActor},
|
||||||
|
webfinger::webfinger_handler,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub(crate) async fn send_with_retry(
|
||||||
|
sends: Vec<SendActivityTask>,
|
||||||
|
data: &Data<FederationData>,
|
||||||
|
) -> Vec<anyhow::Error> {
|
||||||
|
let mut failures = vec![];
|
||||||
|
for send in sends {
|
||||||
|
let mut delay = std::time::Duration::from_secs(1);
|
||||||
|
for attempt in 1..=3u32 {
|
||||||
|
match send.clone().sign_and_send(data).await {
|
||||||
|
Ok(()) => {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Err(e) if attempt < 3 => {
|
||||||
|
tracing::warn!(attempt, error = %e, "delivery failed, retrying");
|
||||||
|
tokio::time::sleep(delay).await;
|
||||||
|
delay *= 2;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!(attempt, error = %e, "delivery failed permanently");
|
||||||
|
failures.push(anyhow::anyhow!(e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
failures
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ActivityPubService {
|
||||||
|
federation_config: ApFederationConfig,
|
||||||
|
base_url: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActivityPubService {
|
||||||
|
pub async fn new(
|
||||||
|
repo: Arc<dyn FederationRepository>,
|
||||||
|
user_repo: Arc<dyn UserRepository>,
|
||||||
|
movie_repo: Arc<dyn domain::ports::MovieRepository>,
|
||||||
|
base_url: String,
|
||||||
|
debug: bool,
|
||||||
|
) -> anyhow::Result<Self> {
|
||||||
|
let data = FederationData::new(repo, user_repo, movie_repo, base_url.clone());
|
||||||
|
let federation_config = ApFederationConfig::new(data, debug).await?;
|
||||||
|
Ok(Self {
|
||||||
|
federation_config,
|
||||||
|
base_url,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn federation_config(&self) -> &ApFederationConfig {
|
||||||
|
&self.federation_config
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn request_data(&self) -> Data<FederationData> {
|
||||||
|
self.federation_config.to_request_data()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Returns the AP actor document JSON for a local user.
|
||||||
|
// Used for content negotiation in the HTML profile handler.
|
||||||
|
pub async fn actor_json(&self, user_id_str: &str) -> anyhow::Result<String> {
|
||||||
|
use activitypub_federation::traits::Object;
|
||||||
|
use crate::actors::get_local_actor;
|
||||||
|
let uuid = uuid::Uuid::parse_str(user_id_str)?;
|
||||||
|
let user_id = UserId::from_uuid(uuid);
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
let actor = get_local_actor(user_id, &data).await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
let person = actor.into_json(&data).await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
let with_context = WithContext::new_default(person);
|
||||||
|
Ok(serde_json::to_string(&with_context)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn router(&self) -> Router {
|
||||||
|
Router::new()
|
||||||
|
.route("/.well-known/webfinger", get(webfinger_handler))
|
||||||
|
.route("/users/{user_id}", get(actor_handler))
|
||||||
|
.route("/users/{user_id}/inbox", post(inbox_handler))
|
||||||
|
.route("/users/{user_id}/outbox", get(outbox_handler))
|
||||||
|
.route("/users/{user_id}/followers", get(followers_handler))
|
||||||
|
.route("/users/{user_id}/following", get(following_handler))
|
||||||
|
.layer(self.federation_config.middleware())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn event_handler(&self) -> ActivityPubEventHandler {
|
||||||
|
ActivityPubEventHandler::new(self.federation_config.clone(), self.base_url.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn follow(&self, local_user_id: UserId, handle: &str) -> anyhow::Result<()> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
|
||||||
|
let remote_actor: DbActor = webfinger_resolve_actor(handle, &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
|
let local_actor = get_local_actor(local_user_id.clone(), &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
|
let follow_id = crate::urls::activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
let follow_id_str = follow_id.to_string();
|
||||||
|
let follow = FollowActivity {
|
||||||
|
id: follow_id,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
object: ObjectId::from(remote_actor.ap_id.clone()),
|
||||||
|
};
|
||||||
|
let follow_with_ctx = WithContext::new_default(follow);
|
||||||
|
|
||||||
|
let sends = SendActivityTask::prepare(
|
||||||
|
&follow_with_ctx,
|
||||||
|
&local_actor,
|
||||||
|
vec![remote_actor.inbox()],
|
||||||
|
&data,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let failures = send_with_retry(sends, &data).await;
|
||||||
|
if !failures.is_empty() {
|
||||||
|
tracing::warn!(count = failures.len(), "some activity deliveries failed permanently");
|
||||||
|
}
|
||||||
|
|
||||||
|
let remote = RemoteActor {
|
||||||
|
url: remote_actor.ap_id.to_string(),
|
||||||
|
handle: remote_actor.username.clone(),
|
||||||
|
inbox_url: remote_actor.inbox_url.to_string(),
|
||||||
|
shared_inbox_url: None,
|
||||||
|
display_name: Some(remote_actor.username.clone()),
|
||||||
|
};
|
||||||
|
data.federation_repo
|
||||||
|
.add_following(local_user_id, remote, &follow_id_str)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn unfollow(&self, local_user_id: UserId, actor_url_str: &str) -> anyhow::Result<()> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
|
||||||
|
let remote = data
|
||||||
|
.federation_repo
|
||||||
|
.get_remote_actor(actor_url_str)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("remote actor not found: {}", actor_url_str))?;
|
||||||
|
|
||||||
|
let local_actor = get_local_actor(local_user_id.clone(), &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
|
let remote_ap_id = Url::parse(actor_url_str)?;
|
||||||
|
let inbox = Url::parse(&remote.inbox_url)?;
|
||||||
|
|
||||||
|
let follow_activity_id_str = data
|
||||||
|
.federation_repo
|
||||||
|
.get_follow_activity_id(local_user_id.clone(), actor_url_str)
|
||||||
|
.await?;
|
||||||
|
let follow_id = match follow_activity_id_str {
|
||||||
|
Some(id) => Url::parse(&id)?,
|
||||||
|
None => crate::urls::activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?,
|
||||||
|
};
|
||||||
|
let follow = FollowActivity {
|
||||||
|
id: follow_id,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
object: ObjectId::from(remote_ap_id),
|
||||||
|
};
|
||||||
|
|
||||||
|
let undo_id = crate::urls::activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
let undo = UndoActivity {
|
||||||
|
id: undo_id,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
object: follow,
|
||||||
|
};
|
||||||
|
let undo_with_ctx = WithContext::new_default(undo);
|
||||||
|
|
||||||
|
let sends =
|
||||||
|
SendActivityTask::prepare(&undo_with_ctx, &local_actor, vec![inbox], &data).await?;
|
||||||
|
let failures = send_with_retry(sends, &data).await;
|
||||||
|
if !failures.is_empty() {
|
||||||
|
tracing::warn!(count = failures.len(), "some activity deliveries failed permanently");
|
||||||
|
}
|
||||||
|
|
||||||
|
data.federation_repo
|
||||||
|
.remove_following(local_user_id, actor_url_str)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
data.federation_repo
|
||||||
|
.delete_remote_reviews_by_actor(actor_url_str)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_following(&self, local_user_id: UserId) -> anyhow::Result<Vec<RemoteActor>> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
data.federation_repo.get_following(local_user_id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn count_following(&self, local_user_id: UserId) -> anyhow::Result<usize> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
data.federation_repo.count_following(local_user_id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn accept_follower(
|
||||||
|
&self,
|
||||||
|
local_user_id: UserId,
|
||||||
|
remote_actor_url: &str,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
let local_actor = get_local_actor(local_user_id.clone(), &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
|
let remote_actor = data
|
||||||
|
.federation_repo
|
||||||
|
.get_remote_actor(remote_actor_url)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("remote actor not found"))?;
|
||||||
|
|
||||||
|
let follow_id_str = data
|
||||||
|
.federation_repo
|
||||||
|
.get_follower_follow_activity_id(local_user_id.clone(), remote_actor_url)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("follow activity id not found for {}", remote_actor_url))?;
|
||||||
|
let follow_id = Url::parse(&follow_id_str)?;
|
||||||
|
let follow = FollowActivity {
|
||||||
|
id: follow_id,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(Url::parse(remote_actor_url)?),
|
||||||
|
object: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
};
|
||||||
|
let accept = AcceptActivity {
|
||||||
|
id: crate::urls::activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
object: follow,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Update status first so local state is correct even if delivery fails
|
||||||
|
data.federation_repo
|
||||||
|
.update_follower_status(local_user_id.clone(), remote_actor_url, FollowerStatus::Accepted)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let inbox = Url::parse(&remote_actor.inbox_url)?;
|
||||||
|
let sends = SendActivityTask::prepare(
|
||||||
|
&WithContext::new_default(accept),
|
||||||
|
&local_actor,
|
||||||
|
vec![inbox.clone()],
|
||||||
|
&data,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let failures = send_with_retry(sends, &data).await;
|
||||||
|
if !failures.is_empty() {
|
||||||
|
tracing::warn!("failed to deliver Accept activity, but follower is marked accepted locally");
|
||||||
|
}
|
||||||
|
|
||||||
|
self.spawn_backfill(local_user_id, remote_actor.inbox_url.clone());
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn reject_follower(
|
||||||
|
&self,
|
||||||
|
local_user_id: UserId,
|
||||||
|
remote_actor_url: &str,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
let local_actor = get_local_actor(local_user_id.clone(), &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
|
let remote_actor = data
|
||||||
|
.federation_repo
|
||||||
|
.get_remote_actor(remote_actor_url)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("remote actor not found"))?;
|
||||||
|
|
||||||
|
let follow_id = crate::urls::activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
let follow = FollowActivity {
|
||||||
|
id: follow_id,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(Url::parse(remote_actor_url)?),
|
||||||
|
object: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
};
|
||||||
|
let reject = RejectActivity {
|
||||||
|
id: crate::urls::activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
object: follow,
|
||||||
|
};
|
||||||
|
|
||||||
|
let inbox = Url::parse(&remote_actor.inbox_url)?;
|
||||||
|
let sends = SendActivityTask::prepare(
|
||||||
|
&WithContext::new_default(reject),
|
||||||
|
&local_actor,
|
||||||
|
vec![inbox],
|
||||||
|
&data,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let failures = send_with_retry(sends, &data).await;
|
||||||
|
if !failures.is_empty() {
|
||||||
|
tracing::warn!(count = failures.len(), "some activity deliveries failed permanently");
|
||||||
|
}
|
||||||
|
|
||||||
|
data.federation_repo
|
||||||
|
.remove_follower(local_user_id, remote_actor_url)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_pending_followers(
|
||||||
|
&self,
|
||||||
|
local_user_id: UserId,
|
||||||
|
) -> anyhow::Result<Vec<RemoteActor>> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
data.federation_repo
|
||||||
|
.get_pending_followers(local_user_id)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_accepted_followers(
|
||||||
|
&self,
|
||||||
|
local_user_id: UserId,
|
||||||
|
) -> anyhow::Result<Vec<RemoteActor>> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
let followers = data.federation_repo.get_followers(local_user_id).await?;
|
||||||
|
Ok(followers
|
||||||
|
.into_iter()
|
||||||
|
.filter(|f| f.status == FollowerStatus::Accepted)
|
||||||
|
.map(|f| f.actor)
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn count_accepted_followers(&self, local_user_id: UserId) -> anyhow::Result<usize> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
let followers = data.federation_repo.get_followers(local_user_id).await?;
|
||||||
|
Ok(followers
|
||||||
|
.into_iter()
|
||||||
|
.filter(|f| f.status == FollowerStatus::Accepted)
|
||||||
|
.count())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn remove_follower(
|
||||||
|
&self,
|
||||||
|
local_user_id: UserId,
|
||||||
|
actor_url: &str,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let data = self.federation_config.to_request_data();
|
||||||
|
data.federation_repo.remove_follower(local_user_id, actor_url).await
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spawn_backfill(&self, owner_user_id: UserId, follower_inbox_url: String) {
|
||||||
|
let config = self.federation_config.clone();
|
||||||
|
let base_url = self.base_url.clone();
|
||||||
|
|
||||||
|
tokio::spawn(async move {
|
||||||
|
if let Err(e) = ActivityPubService::run_backfill(
|
||||||
|
config, base_url, owner_user_id, follower_inbox_url,
|
||||||
|
).await {
|
||||||
|
tracing::warn!(error = %e, "backfill: task failed");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run_backfill(
|
||||||
|
config: ApFederationConfig,
|
||||||
|
base_url: String,
|
||||||
|
owner_user_id: UserId,
|
||||||
|
follower_inbox_url: String,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
const BATCH_SIZE: usize = 20;
|
||||||
|
|
||||||
|
let data = config.to_request_data();
|
||||||
|
let local_actor = get_local_actor(owner_user_id.clone(), &data)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
let inbox = Url::parse(&follower_inbox_url)?;
|
||||||
|
|
||||||
|
let history = data.movie_repo.get_user_history(&owner_user_id).await?;
|
||||||
|
let mut local_reviews: Vec<_> = history
|
||||||
|
.into_iter()
|
||||||
|
.filter(|e| matches!(e.review().source(), domain::models::ReviewSource::Local))
|
||||||
|
.collect();
|
||||||
|
local_reviews.reverse(); // oldest first so Mastodon feed is chronological
|
||||||
|
|
||||||
|
let total = local_reviews.len();
|
||||||
|
|
||||||
|
let mut success_count = 0usize;
|
||||||
|
let mut failure_count = 0usize;
|
||||||
|
|
||||||
|
for chunk in local_reviews.chunks(BATCH_SIZE) {
|
||||||
|
for entry in chunk {
|
||||||
|
match ActivityPubService::deliver_review_to_inbox(
|
||||||
|
entry.review().clone(),
|
||||||
|
&local_actor,
|
||||||
|
inbox.clone(),
|
||||||
|
&data,
|
||||||
|
&base_url,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(_) => success_count += 1,
|
||||||
|
Err(_) => failure_count += 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
user_id = %owner_user_id.value(),
|
||||||
|
follower = %follower_inbox_url,
|
||||||
|
sent = success_count,
|
||||||
|
failed = failure_count,
|
||||||
|
total = total,
|
||||||
|
"backfill complete"
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn deliver_review_to_inbox(
|
||||||
|
review: domain::models::Review,
|
||||||
|
local_actor: &DbActor,
|
||||||
|
inbox: Url,
|
||||||
|
data: &Data<FederationData>,
|
||||||
|
base_url: &str,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
use activitypub_federation::traits::Object;
|
||||||
|
use crate::objects::DbReview;
|
||||||
|
|
||||||
|
let review_id = review.id().clone();
|
||||||
|
let ap_id = crate::urls::review_url(base_url, &review_id);
|
||||||
|
let db_review = DbReview { review, ap_id };
|
||||||
|
let object = db_review.into_json(data).await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
|
||||||
|
let activity_id = crate::urls::create_activity_url(base_url, &review_id)
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
let create = CreateActivity {
|
||||||
|
id: activity_id,
|
||||||
|
kind: Default::default(),
|
||||||
|
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||||
|
object,
|
||||||
|
};
|
||||||
|
|
||||||
|
let sends = SendActivityTask::prepare(
|
||||||
|
&WithContext::new_default(create),
|
||||||
|
local_actor,
|
||||||
|
vec![inbox],
|
||||||
|
data,
|
||||||
|
).await?;
|
||||||
|
let failures = send_with_retry(sends, data).await;
|
||||||
|
if let Some(e) = failures.into_iter().next() {
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
14
crates/adapters/activitypub/src/urls.rs
Normal file
14
crates/adapters/activitypub/src/urls.rs
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
use url::Url;
|
||||||
|
use domain::value_objects::ReviewId;
|
||||||
|
|
||||||
|
/// Builds the canonical actor URL: `{base_url}/users/{user_id}`
|
||||||
|
pub fn actor_url(base_url: &str, user_id: uuid::Uuid) -> Url {
|
||||||
|
Url::parse(&format!("{}/users/{}", base_url, user_id))
|
||||||
|
.expect("base_url is always a valid URL prefix")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds the canonical review URL: `{base_url}/reviews/{review_id}`
|
||||||
|
pub fn review_url(base_url: &str, review_id: &ReviewId) -> Url {
|
||||||
|
Url::parse(&format!("{}/reviews/{}", base_url, review_id.value()))
|
||||||
|
.expect("base_url is always a valid URL prefix")
|
||||||
|
}
|
||||||
28
crates/adapters/activitypub/src/user_adapter.rs
Normal file
28
crates/adapters/activitypub/src/user_adapter.rs
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use activitypub_base::{ApUser, ApUserRepository};
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use domain::{ports::UserRepository, value_objects::UserId};
|
||||||
|
|
||||||
|
pub struct DomainUserRepoAdapter(pub Arc<dyn UserRepository>);
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl ApUserRepository for DomainUserRepoAdapter {
|
||||||
|
async fn find_by_id(&self, id: uuid::Uuid) -> anyhow::Result<Option<ApUser>> {
|
||||||
|
let user_id = UserId::from_uuid(id);
|
||||||
|
Ok(self.0.find_by_id(&user_id).await?.map(|u| ApUser {
|
||||||
|
id: u.id().value(),
|
||||||
|
username: u.username().value().to_string(),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn find_by_username(&self, username: &str) -> anyhow::Result<Option<ApUser>> {
|
||||||
|
use domain::value_objects::Username;
|
||||||
|
let uname = Username::new(username.to_string())
|
||||||
|
.map_err(|e| anyhow::anyhow!(e.to_string()))?;
|
||||||
|
Ok(self.0.find_by_username(&uname).await?.map(|u| ApUser {
|
||||||
|
id: u.id().value(),
|
||||||
|
username: u.username().value().to_string(),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
46
crates/adapters/activitypub/src/webfinger.rs
Normal file
46
crates/adapters/activitypub/src/webfinger.rs
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
use activitypub_federation::{
|
||||||
|
config::Data,
|
||||||
|
fetch::webfinger::{build_webfinger_response, extract_webfinger_name, Webfinger},
|
||||||
|
};
|
||||||
|
use axum::{
|
||||||
|
extract::Query,
|
||||||
|
http::header,
|
||||||
|
response::{IntoResponse, Response},
|
||||||
|
};
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use domain::value_objects::Username;
|
||||||
|
|
||||||
|
use crate::data::FederationData;
|
||||||
|
use crate::error::Error;
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct WebfingerQuery {
|
||||||
|
resource: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn webfinger_handler(
|
||||||
|
Query(query): Query<WebfingerQuery>,
|
||||||
|
data: Data<FederationData>,
|
||||||
|
) -> Result<Response, Error> {
|
||||||
|
let name = extract_webfinger_name(&query.resource, &data)?;
|
||||||
|
|
||||||
|
let username = Username::new(name.to_string())
|
||||||
|
.map_err(|e| Error::bad_request(anyhow::anyhow!(e.to_string())))?;
|
||||||
|
let user = data
|
||||||
|
.user_repo
|
||||||
|
.find_by_username(&username)
|
||||||
|
.await
|
||||||
|
.map_err(Error::from)?
|
||||||
|
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found")))?;
|
||||||
|
|
||||||
|
let ap_id = crate::urls::actor_url(&data.base_url, user.id());
|
||||||
|
|
||||||
|
let wf: Webfinger = build_webfinger_response(query.resource, ap_id);
|
||||||
|
let body = serde_json::to_string(&wf)
|
||||||
|
.map_err(|e| Error::from(anyhow::anyhow!(e)))?;
|
||||||
|
Ok((
|
||||||
|
[(header::CONTENT_TYPE, "application/jrd+json")],
|
||||||
|
body,
|
||||||
|
).into_response())
|
||||||
|
}
|
||||||
@@ -4,3 +4,12 @@ version = "0.1.0"
|
|||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
async-trait = { workspace = true }
|
||||||
|
domain = { workspace = true }
|
||||||
|
anyhow = { workspace = true }
|
||||||
|
chrono = { workspace = true }
|
||||||
|
uuid = { workspace = true }
|
||||||
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
|
jsonwebtoken = "9"
|
||||||
|
argon2 = { version = "0.5", features = ["std"] }
|
||||||
|
rand_core = { version = "0.6", features = ["getrandom"] }
|
||||||
|
|||||||
@@ -1,14 +1,104 @@
|
|||||||
pub fn add(left: u64, right: u64) -> u64 {
|
use async_trait::async_trait;
|
||||||
left + right
|
use argon2::{
|
||||||
|
Argon2,
|
||||||
|
password_hash::{PasswordHasher as _, PasswordVerifier, SaltString},
|
||||||
|
};
|
||||||
|
use chrono::{Duration, Utc};
|
||||||
|
use jsonwebtoken::{DecodingKey, EncodingKey, Header, Validation, decode, encode};
|
||||||
|
use rand_core::OsRng;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use domain::{
|
||||||
|
errors::DomainError,
|
||||||
|
ports::{AuthService, GeneratedToken, PasswordHasher},
|
||||||
|
value_objects::{PasswordHash, UserId},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub struct AuthConfig {
|
||||||
|
secret: String,
|
||||||
|
ttl_seconds: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
impl AuthConfig {
|
||||||
mod tests {
|
pub fn from_env() -> anyhow::Result<Self> {
|
||||||
use super::*;
|
let secret = std::env::var("JWT_SECRET")
|
||||||
|
.map_err(|_| anyhow::anyhow!("JWT_SECRET env var is required"))?;
|
||||||
|
if secret.is_empty() {
|
||||||
|
anyhow::bail!("JWT_SECRET must not be empty");
|
||||||
|
}
|
||||||
|
let ttl_seconds = std::env::var("JWT_TTL_SECONDS")
|
||||||
|
.ok()
|
||||||
|
.and_then(|v| v.parse().ok())
|
||||||
|
.unwrap_or(86400u64);
|
||||||
|
Ok(Self { secret, ttl_seconds })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[derive(Serialize, Deserialize)]
|
||||||
fn it_works() {
|
struct Claims {
|
||||||
let result = add(2, 2);
|
sub: String,
|
||||||
assert_eq!(result, 4);
|
exp: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct JwtAuthService {
|
||||||
|
config: AuthConfig,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl JwtAuthService {
|
||||||
|
pub fn new(config: AuthConfig) -> Self {
|
||||||
|
Self { config }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl AuthService for JwtAuthService {
|
||||||
|
async fn generate_token(&self, user_id: &UserId) -> Result<GeneratedToken, DomainError> {
|
||||||
|
let expires_at = Utc::now() + Duration::seconds(self.config.ttl_seconds as i64);
|
||||||
|
let claims = Claims {
|
||||||
|
sub: user_id.value().to_string(),
|
||||||
|
exp: expires_at.timestamp() as u64,
|
||||||
|
};
|
||||||
|
let token = encode(
|
||||||
|
&Header::default(),
|
||||||
|
&claims,
|
||||||
|
&EncodingKey::from_secret(self.config.secret.as_bytes()),
|
||||||
|
)
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
|
||||||
|
Ok(GeneratedToken { token, expires_at })
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn validate_token(&self, token: &str) -> Result<UserId, DomainError> {
|
||||||
|
let data = decode::<Claims>(
|
||||||
|
token,
|
||||||
|
&DecodingKey::from_secret(self.config.secret.as_bytes()),
|
||||||
|
&Validation::default(),
|
||||||
|
)
|
||||||
|
.map_err(|_| DomainError::Unauthorized("Invalid or expired token".into()))?;
|
||||||
|
let uuid = Uuid::parse_str(&data.claims.sub)
|
||||||
|
.map_err(|_| DomainError::Unauthorized("Invalid token subject".into()))?;
|
||||||
|
Ok(UserId::from_uuid(uuid))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Argon2PasswordHasher;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl PasswordHasher for Argon2PasswordHasher {
|
||||||
|
async fn hash(&self, plain_password: &str) -> Result<PasswordHash, DomainError> {
|
||||||
|
let salt = SaltString::generate(&mut OsRng);
|
||||||
|
let hash = Argon2::default()
|
||||||
|
.hash_password(plain_password.as_bytes(), &salt)
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?
|
||||||
|
.to_string();
|
||||||
|
PasswordHash::new(hash).map_err(|e| DomainError::InfrastructureError(e.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify(&self, plain_password: &str, hash: &PasswordHash) -> Result<bool, DomainError> {
|
||||||
|
let parsed = argon2::password_hash::PasswordHash::new(hash.value())
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
|
||||||
|
Ok(Argon2::default()
|
||||||
|
.verify_password(plain_password.as_bytes(), &parsed)
|
||||||
|
.is_ok())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
10
crates/adapters/event-publisher/Cargo.toml
Normal file
10
crates/adapters/event-publisher/Cargo.toml
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
[package]
|
||||||
|
name = "event-publisher"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
domain = { workspace = true }
|
||||||
|
async-trait = { workspace = true }
|
||||||
|
tokio = { workspace = true }
|
||||||
|
tracing = { workspace = true }
|
||||||
226
crates/adapters/event-publisher/src/lib.rs
Normal file
226
crates/adapters/event-publisher/src/lib.rs
Normal file
@@ -0,0 +1,226 @@
|
|||||||
|
use async_trait::async_trait;
|
||||||
|
use domain::{errors::DomainError, events::DomainEvent, ports::EventPublisher};
|
||||||
|
use tokio::sync::mpsc;
|
||||||
|
|
||||||
|
pub struct EventPublisherConfig {
|
||||||
|
pub channel_buffer: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventPublisherConfig {
|
||||||
|
pub fn from_env() -> Self {
|
||||||
|
let channel_buffer = std::env::var("EVENT_CHANNEL_BUFFER")
|
||||||
|
.ok()
|
||||||
|
.and_then(|v| v.parse().ok())
|
||||||
|
.unwrap_or(128);
|
||||||
|
Self { channel_buffer }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
pub trait EventHandler: Send + Sync {
|
||||||
|
async fn handle(&self, event: &DomainEvent) -> Result<(), DomainError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ChannelEventPublisher {
|
||||||
|
sender: mpsc::Sender<DomainEvent>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl EventPublisher for ChannelEventPublisher {
|
||||||
|
async fn publish(&self, event: &DomainEvent) -> Result<(), DomainError> {
|
||||||
|
self.sender
|
||||||
|
.send(event.clone())
|
||||||
|
.await
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(e.to_string()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct EventWorker {
|
||||||
|
receiver: mpsc::Receiver<DomainEvent>,
|
||||||
|
handlers: Vec<Box<dyn EventHandler>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventWorker {
|
||||||
|
pub async fn run(mut self) {
|
||||||
|
while let Some(event) = self.receiver.recv().await {
|
||||||
|
match &event {
|
||||||
|
DomainEvent::ReviewLogged {
|
||||||
|
review_id,
|
||||||
|
movie_id,
|
||||||
|
user_id,
|
||||||
|
rating,
|
||||||
|
watched_at,
|
||||||
|
} => {
|
||||||
|
tracing::info!(
|
||||||
|
review_id = %review_id.value(),
|
||||||
|
movie_id = %movie_id.value(),
|
||||||
|
user_id = %user_id.value(),
|
||||||
|
rating = rating.value(),
|
||||||
|
watched_at = %watched_at,
|
||||||
|
"event: review_logged"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
DomainEvent::ReviewUpdated {
|
||||||
|
review_id,
|
||||||
|
movie_id,
|
||||||
|
user_id,
|
||||||
|
rating,
|
||||||
|
watched_at,
|
||||||
|
} => {
|
||||||
|
tracing::info!(
|
||||||
|
review_id = %review_id.value(),
|
||||||
|
movie_id = %movie_id.value(),
|
||||||
|
user_id = %user_id.value(),
|
||||||
|
rating = rating.value(),
|
||||||
|
watched_at = %watched_at,
|
||||||
|
"event: review_updated"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
DomainEvent::MovieDiscovered {
|
||||||
|
movie_id,
|
||||||
|
external_metadata_id,
|
||||||
|
} => {
|
||||||
|
tracing::info!(
|
||||||
|
movie_id = %movie_id.value(),
|
||||||
|
external_id = external_metadata_id.value(),
|
||||||
|
"event: movie_discovered"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for handler in &self.handlers {
|
||||||
|
if let Err(e) = handler.handle(&event).await {
|
||||||
|
tracing::error!("event handler error: {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tracing::info!("event worker shut down");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct NoopEventPublisher;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl EventPublisher for NoopEventPublisher {
|
||||||
|
async fn publish(&self, _event: &DomainEvent) -> Result<(), DomainError> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create_event_channel(
|
||||||
|
config: EventPublisherConfig,
|
||||||
|
handlers: Vec<Box<dyn EventHandler>>,
|
||||||
|
) -> (ChannelEventPublisher, EventWorker) {
|
||||||
|
let (tx, rx) = mpsc::channel(config.channel_buffer);
|
||||||
|
(
|
||||||
|
ChannelEventPublisher { sender: tx },
|
||||||
|
EventWorker {
|
||||||
|
receiver: rx,
|
||||||
|
handlers,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use domain::{
|
||||||
|
errors::DomainError,
|
||||||
|
events::DomainEvent,
|
||||||
|
value_objects::{ExternalMetadataId, MovieId},
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RecordingHandler {
|
||||||
|
calls: Arc<Mutex<Vec<String>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl EventHandler for RecordingHandler {
|
||||||
|
async fn handle(&self, event: &DomainEvent) -> Result<(), DomainError> {
|
||||||
|
let label = match event {
|
||||||
|
DomainEvent::ReviewLogged { .. } => "review_logged",
|
||||||
|
DomainEvent::ReviewUpdated { .. } => "review_updated",
|
||||||
|
DomainEvent::MovieDiscovered { .. } => "movie_discovered",
|
||||||
|
};
|
||||||
|
self.calls.lock().unwrap().push(label.to_string());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn single_handler_receives_event() {
|
||||||
|
let calls = Arc::new(Mutex::new(vec![]));
|
||||||
|
let handler = RecordingHandler { calls: Arc::clone(&calls) };
|
||||||
|
let config = EventPublisherConfig { channel_buffer: 8 };
|
||||||
|
let (publisher, worker) = create_event_channel(config, vec![Box::new(handler)]);
|
||||||
|
|
||||||
|
let handle = tokio::spawn(worker.run());
|
||||||
|
|
||||||
|
let event = DomainEvent::MovieDiscovered {
|
||||||
|
movie_id: MovieId::generate(),
|
||||||
|
external_metadata_id: ExternalMetadataId::new("tt1234567".into()).unwrap(),
|
||||||
|
};
|
||||||
|
publisher.publish(&event).await.unwrap();
|
||||||
|
drop(publisher);
|
||||||
|
handle.await.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(*calls.lock().unwrap(), vec!["movie_discovered"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn multiple_handlers_all_receive_event() {
|
||||||
|
let calls1 = Arc::new(Mutex::new(vec![]));
|
||||||
|
let calls2 = Arc::new(Mutex::new(vec![]));
|
||||||
|
let handler1 = RecordingHandler { calls: Arc::clone(&calls1) };
|
||||||
|
let handler2 = RecordingHandler { calls: Arc::clone(&calls2) };
|
||||||
|
let config = EventPublisherConfig { channel_buffer: 8 };
|
||||||
|
let (publisher, worker) = create_event_channel(
|
||||||
|
config,
|
||||||
|
vec![Box::new(handler1), Box::new(handler2)],
|
||||||
|
);
|
||||||
|
|
||||||
|
let handle = tokio::spawn(worker.run());
|
||||||
|
|
||||||
|
let event = DomainEvent::MovieDiscovered {
|
||||||
|
movie_id: MovieId::generate(),
|
||||||
|
external_metadata_id: ExternalMetadataId::new("tt9999999".into()).unwrap(),
|
||||||
|
};
|
||||||
|
publisher.publish(&event).await.unwrap();
|
||||||
|
drop(publisher);
|
||||||
|
handle.await.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(calls1.lock().unwrap().len(), 1);
|
||||||
|
assert_eq!(calls2.lock().unwrap().len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn handler_error_does_not_stop_worker() {
|
||||||
|
struct FailingHandler;
|
||||||
|
#[async_trait]
|
||||||
|
impl EventHandler for FailingHandler {
|
||||||
|
async fn handle(&self, _: &DomainEvent) -> Result<(), DomainError> {
|
||||||
|
Err(DomainError::InfrastructureError("boom".into()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let calls = Arc::new(Mutex::new(vec![]));
|
||||||
|
let good = RecordingHandler { calls: Arc::clone(&calls) };
|
||||||
|
let config = EventPublisherConfig { channel_buffer: 8 };
|
||||||
|
let (publisher, worker) = create_event_channel(
|
||||||
|
config,
|
||||||
|
vec![Box::new(FailingHandler), Box::new(good)],
|
||||||
|
);
|
||||||
|
|
||||||
|
let handle = tokio::spawn(worker.run());
|
||||||
|
|
||||||
|
let event = DomainEvent::MovieDiscovered {
|
||||||
|
movie_id: MovieId::generate(),
|
||||||
|
external_metadata_id: ExternalMetadataId::new("tt0000001".into()).unwrap(),
|
||||||
|
};
|
||||||
|
publisher.publish(&event).await.unwrap();
|
||||||
|
drop(publisher);
|
||||||
|
handle.await.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(calls.lock().unwrap().len(), 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,3 +4,7 @@ version = "0.1.0"
|
|||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
async-trait = { workspace = true }
|
||||||
|
reqwest = { workspace = true }
|
||||||
|
serde = { workspace = true }
|
||||||
|
domain = { workspace = true }
|
||||||
|
|||||||
@@ -1,14 +1,54 @@
|
|||||||
pub fn add(left: u64, right: u64) -> u64 {
|
use async_trait::async_trait;
|
||||||
left + right
|
use domain::{
|
||||||
|
errors::DomainError,
|
||||||
|
models::Movie,
|
||||||
|
ports::{MetadataClient, MetadataSearchCriteria},
|
||||||
|
value_objects::{ExternalMetadataId, MovieTitle, PosterUrl, ReleaseYear},
|
||||||
|
};
|
||||||
|
|
||||||
|
mod omdb;
|
||||||
|
|
||||||
|
pub(crate) struct ProviderMovie {
|
||||||
|
pub imdb_id: ExternalMetadataId,
|
||||||
|
pub title: MovieTitle,
|
||||||
|
pub release_year: ReleaseYear,
|
||||||
|
pub director: Option<String>,
|
||||||
|
pub poster_url: Option<PosterUrl>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[async_trait]
|
||||||
mod tests {
|
pub(crate) trait MetadataProvider: Send + Sync {
|
||||||
use super::*;
|
async fn fetch(&self, criteria: &MetadataSearchCriteria) -> Result<ProviderMovie, DomainError>;
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
pub struct MetadataClientImpl {
|
||||||
fn it_works() {
|
provider: Box<dyn MetadataProvider>,
|
||||||
let result = add(2, 2);
|
}
|
||||||
assert_eq!(result, 4);
|
|
||||||
|
impl MetadataClientImpl {
|
||||||
|
pub fn new_omdb(api_key: String) -> Self {
|
||||||
|
Self {
|
||||||
|
provider: Box::new(omdb::OmdbProvider::new(api_key)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl MetadataClient for MetadataClientImpl {
|
||||||
|
async fn fetch_movie_metadata(
|
||||||
|
&self,
|
||||||
|
criteria: &MetadataSearchCriteria,
|
||||||
|
) -> Result<Movie, DomainError> {
|
||||||
|
let pm = self.provider.fetch(criteria).await?;
|
||||||
|
Ok(Movie::new(Some(pm.imdb_id), pm.title, pm.release_year, pm.director, None))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_poster_url(
|
||||||
|
&self,
|
||||||
|
external_metadata_id: &ExternalMetadataId,
|
||||||
|
) -> Result<Option<PosterUrl>, DomainError> {
|
||||||
|
let criteria = MetadataSearchCriteria::ImdbId(external_metadata_id.clone());
|
||||||
|
let pm = self.provider.fetch(&criteria).await?;
|
||||||
|
Ok(pm.poster_url)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
119
crates/adapters/metadata/src/omdb.rs
Normal file
119
crates/adapters/metadata/src/omdb.rs
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
use async_trait::async_trait;
|
||||||
|
use domain::{
|
||||||
|
errors::DomainError,
|
||||||
|
ports::MetadataSearchCriteria,
|
||||||
|
value_objects::{ExternalMetadataId, MovieTitle, PosterUrl, ReleaseYear},
|
||||||
|
};
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use crate::{MetadataProvider, ProviderMovie};
|
||||||
|
|
||||||
|
pub(crate) struct OmdbProvider {
|
||||||
|
client: reqwest::Client,
|
||||||
|
api_key: String,
|
||||||
|
base_url: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OmdbProvider {
|
||||||
|
pub(crate) fn new(api_key: String) -> Self {
|
||||||
|
Self {
|
||||||
|
client: reqwest::Client::new(),
|
||||||
|
api_key,
|
||||||
|
base_url: "http://www.omdbapi.com/".to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct OmdbResponse {
|
||||||
|
#[serde(rename = "Title")]
|
||||||
|
title: String,
|
||||||
|
#[serde(rename = "Year")]
|
||||||
|
year: String,
|
||||||
|
#[serde(rename = "Director")]
|
||||||
|
director: String,
|
||||||
|
#[serde(rename = "Poster")]
|
||||||
|
poster: String,
|
||||||
|
#[serde(rename = "imdbID")]
|
||||||
|
imdb_id: String,
|
||||||
|
#[serde(rename = "Response")]
|
||||||
|
response: String,
|
||||||
|
#[serde(rename = "Error")]
|
||||||
|
error: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl MetadataProvider for OmdbProvider {
|
||||||
|
async fn fetch(&self, criteria: &MetadataSearchCriteria) -> Result<ProviderMovie, DomainError> {
|
||||||
|
let mut url = reqwest::Url::parse(&self.base_url)
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
|
||||||
|
|
||||||
|
{
|
||||||
|
let mut params = url.query_pairs_mut();
|
||||||
|
params.append_pair("apikey", &self.api_key);
|
||||||
|
match criteria {
|
||||||
|
MetadataSearchCriteria::ImdbId(id) => {
|
||||||
|
params.append_pair("i", id.value());
|
||||||
|
}
|
||||||
|
MetadataSearchCriteria::Title { title, year } => {
|
||||||
|
params.append_pair("t", title.value());
|
||||||
|
if let Some(y) = year {
|
||||||
|
params.append_pair("y", &y.value().to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let http_resp = self
|
||||||
|
.client
|
||||||
|
.get(url)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e: reqwest::Error| DomainError::InfrastructureError(e.to_string()))?
|
||||||
|
.error_for_status()
|
||||||
|
.map_err(|e: reqwest::Error| DomainError::InfrastructureError(e.to_string()))?;
|
||||||
|
|
||||||
|
let resp: OmdbResponse = http_resp
|
||||||
|
.json()
|
||||||
|
.await
|
||||||
|
.map_err(|e: reqwest::Error| DomainError::InfrastructureError(e.to_string()))?;
|
||||||
|
|
||||||
|
if resp.response != "True" {
|
||||||
|
let msg = resp.error.unwrap_or_default();
|
||||||
|
return if msg.to_lowercase().contains("not found") {
|
||||||
|
Err(DomainError::NotFound(msg))
|
||||||
|
} else {
|
||||||
|
Err(DomainError::InfrastructureError(msg))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let year: u16 = resp
|
||||||
|
.year
|
||||||
|
.chars()
|
||||||
|
.take(4)
|
||||||
|
.collect::<String>()
|
||||||
|
.parse()
|
||||||
|
.map_err(|_| {
|
||||||
|
DomainError::InfrastructureError(format!("Unparseable year: {}", resp.year))
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let imdb_id = ExternalMetadataId::new(resp.imdb_id)
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
|
||||||
|
let title = MovieTitle::new(resp.title)
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
|
||||||
|
let release_year = ReleaseYear::new(year)
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
|
||||||
|
|
||||||
|
let director = match resp.director.as_str() {
|
||||||
|
"N/A" | "" => None,
|
||||||
|
d => Some(d.to_string()),
|
||||||
|
};
|
||||||
|
|
||||||
|
let poster_url = match resp.poster.as_str() {
|
||||||
|
"N/A" | "" => None,
|
||||||
|
url => PosterUrl::new(url.to_string()).ok(),
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(ProviderMovie { imdb_id, title, release_year, director, poster_url })
|
||||||
|
}
|
||||||
|
}
|
||||||
10
crates/adapters/poster-fetcher/Cargo.toml
Normal file
10
crates/adapters/poster-fetcher/Cargo.toml
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
[package]
|
||||||
|
name = "poster-fetcher"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
domain = { workspace = true }
|
||||||
|
async-trait = { workspace = true }
|
||||||
|
reqwest = { workspace = true }
|
||||||
|
anyhow = { workspace = true }
|
||||||
13
crates/adapters/poster-fetcher/src/config.rs
Normal file
13
crates/adapters/poster-fetcher/src/config.rs
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
pub struct PosterFetcherConfig {
|
||||||
|
pub timeout_seconds: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PosterFetcherConfig {
|
||||||
|
pub fn from_env() -> Self {
|
||||||
|
let timeout_seconds = std::env::var("POSTER_FETCH_TIMEOUT_SECONDS")
|
||||||
|
.ok()
|
||||||
|
.and_then(|v| v.parse().ok())
|
||||||
|
.unwrap_or(30);
|
||||||
|
Self { timeout_seconds }
|
||||||
|
}
|
||||||
|
}
|
||||||
38
crates/adapters/poster-fetcher/src/lib.rs
Normal file
38
crates/adapters/poster-fetcher/src/lib.rs
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
mod config;
|
||||||
|
pub use config::PosterFetcherConfig;
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use domain::{errors::DomainError, ports::PosterFetcherClient, value_objects::PosterUrl};
|
||||||
|
|
||||||
|
pub struct ReqwestPosterFetcher {
|
||||||
|
client: reqwest::Client,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ReqwestPosterFetcher {
|
||||||
|
pub fn new(config: PosterFetcherConfig) -> anyhow::Result<Self> {
|
||||||
|
let client = reqwest::Client::builder()
|
||||||
|
.timeout(Duration::from_secs(config.timeout_seconds))
|
||||||
|
.build()?;
|
||||||
|
Ok(Self { client })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl PosterFetcherClient for ReqwestPosterFetcher {
|
||||||
|
async fn fetch_poster_bytes(&self, poster_url: &PosterUrl) -> Result<Vec<u8>, DomainError> {
|
||||||
|
let bytes = self
|
||||||
|
.client
|
||||||
|
.get(poster_url.value())
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?
|
||||||
|
.error_for_status()
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?
|
||||||
|
.bytes()
|
||||||
|
.await
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
|
||||||
|
Ok(bytes.to_vec())
|
||||||
|
}
|
||||||
|
}
|
||||||
16
crates/adapters/poster-storage/Cargo.toml
Normal file
16
crates/adapters/poster-storage/Cargo.toml
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
[package]
|
||||||
|
name = "poster-storage"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
domain = { workspace = true }
|
||||||
|
anyhow = { workspace = true }
|
||||||
|
async-trait = { workspace = true }
|
||||||
|
tracing = { workspace = true }
|
||||||
|
object_store = { workspace = true }
|
||||||
|
infer = "0.19.0"
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tokio = { workspace = true }
|
||||||
|
uuid = { workspace = true }
|
||||||
86
crates/adapters/poster-storage/src/config.rs
Normal file
86
crates/adapters/poster-storage/src/config.rs
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
use anyhow::Context;
|
||||||
|
use object_store::{ObjectStore, aws::AmazonS3Builder, local::LocalFileSystem};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
pub struct StorageConfig(Arc<dyn ObjectStore>);
|
||||||
|
|
||||||
|
impl StorageConfig {
|
||||||
|
pub fn from_env() -> anyhow::Result<Self> {
|
||||||
|
let backend = std::env::var("POSTER_STORAGE_BACKEND")
|
||||||
|
.context("POSTER_STORAGE_BACKEND required (valid values: s3, local)")?;
|
||||||
|
|
||||||
|
let store: Arc<dyn ObjectStore> = match backend.as_str() {
|
||||||
|
"s3" => build_s3_store(
|
||||||
|
&std::env::var("MINIO_ENDPOINT").context("MINIO_ENDPOINT required")?,
|
||||||
|
&std::env::var("MINIO_ACCESS_KEY_ID").context("MINIO_ACCESS_KEY_ID required")?,
|
||||||
|
&std::env::var("MINIO_SECRET_ACCESS_KEY")
|
||||||
|
.context("MINIO_SECRET_ACCESS_KEY required")?,
|
||||||
|
&std::env::var("MINIO_BUCKET").context("MINIO_BUCKET required")?,
|
||||||
|
&std::env::var("MINIO_REGION").unwrap_or_else(|_| "minio".to_string()),
|
||||||
|
)?,
|
||||||
|
"local" => build_local_store(
|
||||||
|
&std::env::var("POSTER_STORAGE_PATH")
|
||||||
|
.context("POSTER_STORAGE_PATH required when POSTER_STORAGE_BACKEND=local")?,
|
||||||
|
)?,
|
||||||
|
other => anyhow::bail!(
|
||||||
|
"Unknown POSTER_STORAGE_BACKEND: {other:?}. Valid values: s3, local"
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(Self(store))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn build_store(self) -> Arc<dyn ObjectStore> {
|
||||||
|
self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build_s3_store(
|
||||||
|
endpoint: &str,
|
||||||
|
access_key_id: &str,
|
||||||
|
secret_access_key: &str,
|
||||||
|
bucket: &str,
|
||||||
|
region: &str,
|
||||||
|
) -> anyhow::Result<Arc<dyn ObjectStore>> {
|
||||||
|
let store = AmazonS3Builder::new()
|
||||||
|
.with_endpoint(endpoint)
|
||||||
|
.with_access_key_id(access_key_id)
|
||||||
|
.with_secret_access_key(secret_access_key)
|
||||||
|
.with_bucket_name(bucket)
|
||||||
|
.with_region(region)
|
||||||
|
.with_allow_http(true)
|
||||||
|
.build()
|
||||||
|
.context("Failed to build S3/Minio store")?;
|
||||||
|
Ok(Arc::new(store))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build_local_store(path: &str) -> anyhow::Result<Arc<dyn ObjectStore>> {
|
||||||
|
std::fs::create_dir_all(path)
|
||||||
|
.context("Failed to create poster storage directory")?;
|
||||||
|
let store = LocalFileSystem::new_with_prefix(path)
|
||||||
|
.context("Failed to initialise local file system store")?;
|
||||||
|
Ok(Arc::new(store))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn local_store_creates_dir_and_succeeds() {
|
||||||
|
let dir = std::env::temp_dir()
|
||||||
|
.join(format!("poster_test_{}", uuid::Uuid::new_v4()));
|
||||||
|
let result = build_local_store(dir.to_str().unwrap());
|
||||||
|
assert!(result.is_ok(), "expected Ok, got: {:?}", result.err());
|
||||||
|
assert!(dir.exists(), "directory should have been created");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn local_store_succeeds_if_dir_already_exists() {
|
||||||
|
let dir = std::env::temp_dir()
|
||||||
|
.join(format!("poster_test_{}", uuid::Uuid::new_v4()));
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
let result = build_local_store(dir.to_str().unwrap());
|
||||||
|
assert!(result.is_ok());
|
||||||
|
}
|
||||||
|
}
|
||||||
95
crates/adapters/poster-storage/src/lib.rs
Normal file
95
crates/adapters/poster-storage/src/lib.rs
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
mod config;
|
||||||
|
pub use config::StorageConfig;
|
||||||
|
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use domain::{
|
||||||
|
errors::DomainError,
|
||||||
|
ports::PosterStorage,
|
||||||
|
value_objects::{MovieId, PosterPath},
|
||||||
|
};
|
||||||
|
use object_store::{Attribute, Attributes, PutOptions, path::Path, ObjectStore};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
fn detect_mime(bytes: &[u8]) -> &'static str {
|
||||||
|
infer::get(bytes)
|
||||||
|
.map(|t| t.mime_type())
|
||||||
|
.unwrap_or("application/octet-stream")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct PosterStorageAdapter {
|
||||||
|
store: Arc<dyn ObjectStore>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PosterStorageAdapter {
|
||||||
|
pub fn new(store: Arc<dyn ObjectStore>) -> Self {
|
||||||
|
Self { store }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn from_config(config: StorageConfig) -> Self {
|
||||||
|
Self::new(config.build_store())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl PosterStorage for PosterStorageAdapter {
|
||||||
|
async fn store_poster(
|
||||||
|
&self,
|
||||||
|
movie_id: &MovieId,
|
||||||
|
image_bytes: &[u8],
|
||||||
|
) -> Result<PosterPath, DomainError> {
|
||||||
|
let path = Path::from(movie_id.value().to_string());
|
||||||
|
let mime = detect_mime(image_bytes);
|
||||||
|
let mut attributes = Attributes::new();
|
||||||
|
attributes.insert(Attribute::ContentType, mime.into());
|
||||||
|
let opts = PutOptions { attributes, ..Default::default() };
|
||||||
|
self.store
|
||||||
|
.put_opts(&path, image_bytes.to_vec().into(), opts)
|
||||||
|
.await
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(e.to_string()))?;
|
||||||
|
PosterPath::new(path.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_poster(&self, poster_path: &PosterPath) -> Result<Vec<u8>, DomainError> {
|
||||||
|
let path = Path::from(poster_path.value().to_string());
|
||||||
|
let result = self.store.get(&path).await.map_err(|e| match e {
|
||||||
|
object_store::Error::NotFound { .. } => DomainError::NotFound("Poster not found".into()),
|
||||||
|
_ => DomainError::InfrastructureError(e.to_string()),
|
||||||
|
})?;
|
||||||
|
result
|
||||||
|
.bytes()
|
||||||
|
.await
|
||||||
|
.map(|b| b.to_vec())
|
||||||
|
.map_err(|e| DomainError::InfrastructureError(e.to_string()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use object_store::memory::InMemory;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
fn adapter() -> PosterStorageAdapter {
|
||||||
|
PosterStorageAdapter::new(Arc::new(InMemory::new()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn store_and_retrieve_round_trip() {
|
||||||
|
let adapter = adapter();
|
||||||
|
let movie_id = MovieId::from_uuid(Uuid::new_v4());
|
||||||
|
let bytes = b"fake-image-bytes";
|
||||||
|
|
||||||
|
let path = adapter.store_poster(&movie_id, bytes).await.unwrap();
|
||||||
|
let retrieved = adapter.get_poster(&path).await.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(retrieved, bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn get_missing_returns_not_found() {
|
||||||
|
let adapter = adapter();
|
||||||
|
let path = PosterPath::new("nonexistent".into()).unwrap();
|
||||||
|
let result = adapter.get_poster(&path).await;
|
||||||
|
assert!(matches!(result, Err(DomainError::NotFound(_))));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,3 +4,7 @@ version = "0.1.0"
|
|||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
rss-feed = { package = "rss", version = "2" }
|
||||||
|
chrono = { workspace = true }
|
||||||
|
domain = { workspace = true }
|
||||||
|
application = { workspace = true }
|
||||||
|
|||||||
@@ -1,5 +1,59 @@
|
|||||||
pub fn add(left: u64, right: u64) -> u64 {
|
use application::ports::RssFeedRenderer;
|
||||||
left + right
|
use domain::models::DiaryEntry;
|
||||||
|
use rss_feed::{ChannelBuilder, GuidBuilder, ItemBuilder};
|
||||||
|
|
||||||
|
pub struct RssAdapter {
|
||||||
|
feed_link: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RssAdapter {
|
||||||
|
pub fn new(feed_link: String) -> Self {
|
||||||
|
Self { feed_link }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RssFeedRenderer for RssAdapter {
|
||||||
|
fn render_feed(&self, entries: &[DiaryEntry], title: &str) -> Result<String, String> {
|
||||||
|
let items = entries
|
||||||
|
.iter()
|
||||||
|
.map(|e| {
|
||||||
|
let item_title = format!(
|
||||||
|
"{} ({})",
|
||||||
|
e.movie().title().value(),
|
||||||
|
e.movie().release_year().value()
|
||||||
|
);
|
||||||
|
let description = match e.review().comment() {
|
||||||
|
Some(c) => format!("{}/5 — {}", e.review().rating().value(), c.value()),
|
||||||
|
None => format!("{}/5", e.review().rating().value()),
|
||||||
|
};
|
||||||
|
let pub_date = e
|
||||||
|
.review()
|
||||||
|
.watched_at()
|
||||||
|
.and_utc()
|
||||||
|
.format("%a, %d %b %Y %H:%M:%S +0000")
|
||||||
|
.to_string();
|
||||||
|
let guid = GuidBuilder::default()
|
||||||
|
.value(e.review().id().value().to_string())
|
||||||
|
.permalink(false)
|
||||||
|
.build();
|
||||||
|
ItemBuilder::default()
|
||||||
|
.title(Some(item_title))
|
||||||
|
.description(Some(description))
|
||||||
|
.pub_date(Some(pub_date))
|
||||||
|
.guid(Some(guid))
|
||||||
|
.build()
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
let channel = ChannelBuilder::default()
|
||||||
|
.title(title.to_string())
|
||||||
|
.link(self.feed_link.clone())
|
||||||
|
.description(title.to_string())
|
||||||
|
.items(items)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
Ok(channel.to_string())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -7,8 +61,16 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn it_works() {
|
fn render_feed_uses_provided_title() {
|
||||||
let result = add(2, 2);
|
let adapter = RssAdapter::new("http://example.com".into());
|
||||||
assert_eq!(result, 4);
|
let xml = adapter.render_feed(&[], "Custom Title").unwrap();
|
||||||
|
assert!(xml.contains("<title>Custom Title</title>"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn render_feed_empty_entries_produces_valid_xml() {
|
||||||
|
let adapter = RssAdapter::new("http://example.com".into());
|
||||||
|
let xml = adapter.render_feed(&[], "My Feed").unwrap();
|
||||||
|
assert!(xml.starts_with("<?xml") || xml.starts_with("<rss"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
{
|
||||||
|
"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\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"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 3
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "01a08873b7fa815ad98a56a0902b60414cfcdc2c7a8570351320c4bc425347c6"
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
{
|
||||||
|
"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\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"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 2
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "026e2afeb573707cb360fcdab8f6137aabfaf603b5ed57b98ac2888b4a0389ff"
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT COUNT(*) FROM reviews",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "COUNT(*)",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Integer"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 0
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "0963b9661182e139cd760bbabb0d6ea3a301a2a3adbdfdda4a88f333a1144c77"
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT id, email, password_hash FROM users WHERE email = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "email",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "password_hash",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "167481bb1692cc81531d9a5cd85425e43d09a6df97c335ac347f7cfd61acd171"
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "INSERT OR IGNORE INTO users (id, email, password_hash, created_at) VALUES (?, ?, ?, ?)",
|
||||||
|
"describe": {
|
||||||
|
"columns": [],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 4
|
||||||
|
},
|
||||||
|
"nullable": []
|
||||||
|
},
|
||||||
|
"hash": "18de90feb13b9f467f06d0ce25332d9ea7eabc99d9f1a44694e5d10762606f82"
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT id, email, password_hash FROM users WHERE id = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "email",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "password_hash",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "1bc5a51762717e45292626052f0a65ac0b8a001798a2476ea86143c5565df399"
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT id, external_metadata_id, title, release_year, director, poster_path\n FROM movies WHERE title = ? AND release_year = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "external_metadata_id",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "title",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "release_year",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "director",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "poster_path",
|
||||||
|
"ordinal": 5,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 2
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "3047579c6ed13ce87aad9b9ce6300c02f0df3516979518976e13f9d9abc6a403"
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
{
|
||||||
|
"db_name": "SQLite",
|
||||||
|
"query": "SELECT id, external_metadata_id, title, release_year, director, poster_path\n FROM movies WHERE id = ?",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"name": "id",
|
||||||
|
"ordinal": 0,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "external_metadata_id",
|
||||||
|
"ordinal": 1,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "title",
|
||||||
|
"ordinal": 2,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "release_year",
|
||||||
|
"ordinal": 3,
|
||||||
|
"type_info": "Integer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "director",
|
||||||
|
"ordinal": 4,
|
||||||
|
"type_info": "Text"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "poster_path",
|
||||||
|
"ordinal": 5,
|
||||||
|
"type_info": "Text"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 1
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "33d0dae7d16b0635c1c7eb5afd10824bb55af7cc7a854f590d326622863759d1"
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
{
|
||||||
|
"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\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"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Right": 3
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "47f7cf95ce3450635b643ab710cadba96f40319140834d510bc5207b2552e055"
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user