Compare commits
23 Commits
master
...
636d3d453d
| Author | SHA1 | Date | |
|---|---|---|---|
| 636d3d453d | |||
| 9172c82d54 | |||
| cd2eb48ddb | |||
| c5d9833c8b | |||
| f39c1a614d | |||
| 30c8a17168 | |||
| 6a8c8b1fb8 | |||
| 4ec0725ff8 | |||
| 31e0f2958c | |||
| 555121ea75 | |||
| 9e795eefdc | |||
| 18cf2c9f54 | |||
| b58c96b843 | |||
| 8ea24461ba | |||
| e14a9f90c8 | |||
| 28756ef4cd | |||
| 7f27ae49c3 | |||
| 59f3423c00 | |||
| c48aa33592 | |||
| 8f3aa4b891 | |||
| 32bfb00970 | |||
| 7ce2901c2a | |||
| 8bbc713093 |
@@ -1,9 +0,0 @@
|
|||||||
[registry]
|
|
||||||
default = "gitea"
|
|
||||||
|
|
||||||
[registries.gitea]
|
|
||||||
index = "sparse+https://git.gabrielkaszewski.dev/api/packages/GKaszewski/cargo/" # Sparse index
|
|
||||||
# index = "https://git.gabrielkaszewski.dev/GKaszewski/_cargo-index.git" # Git
|
|
||||||
|
|
||||||
[net]
|
|
||||||
git-fetch-with-cli = true
|
|
||||||
18
.env.example
18
.env.example
@@ -9,7 +9,7 @@ BASE_URL=http://localhost:3000
|
|||||||
|
|
||||||
# Optional
|
# Optional
|
||||||
HOST=0.0.0.0
|
HOST=0.0.0.0
|
||||||
PORT=8000
|
PORT=3000
|
||||||
|
|
||||||
# CORS — comma-separated allowed origins, or * for permissive (default: *)
|
# CORS — comma-separated allowed origins, or * for permissive (default: *)
|
||||||
CORS_ORIGINS=*
|
CORS_ORIGINS=*
|
||||||
@@ -24,21 +24,5 @@ RUST_ENV=development # set to "production" to disable AP debug mode
|
|||||||
# but events will not be delivered to the worker)
|
# but events will not be delivered to the worker)
|
||||||
# NATS_URL=nats://localhost:4222
|
# NATS_URL=nats://localhost:4222
|
||||||
|
|
||||||
# Media storage — local filesystem (default) or S3/MinIO
|
|
||||||
STORAGE_BACKEND=local
|
|
||||||
STORAGE_PATH=./media # required when STORAGE_BACKEND=local
|
|
||||||
# STORAGE_PREFIX= # optional key prefix
|
|
||||||
|
|
||||||
# S3/MinIO (set STORAGE_BACKEND=s3 to use)
|
|
||||||
# S3_ENDPOINT=http://localhost:9000
|
|
||||||
# S3_ACCESS_KEY_ID=minioadmin
|
|
||||||
# S3_SECRET_ACCESS_KEY=minioadmin
|
|
||||||
# S3_BUCKET=thoughts
|
|
||||||
# S3_REGION=us-east-1
|
|
||||||
|
|
||||||
# Upload limits (optional, defaults shown)
|
|
||||||
# UPLOAD_MAX_BYTES=5242880
|
|
||||||
# UPLOAD_ALLOWED_TYPES=image/jpeg,image/png,image/gif,image/webp,image/avif
|
|
||||||
|
|
||||||
# Logging
|
# Logging
|
||||||
RUST_LOG=info
|
RUST_LOG=info
|
||||||
|
|||||||
@@ -21,3 +21,32 @@ jobs:
|
|||||||
--exclude postgres-federation \
|
--exclude postgres-federation \
|
||||||
--exclude postgres-search
|
--exclude postgres-search
|
||||||
|
|
||||||
|
# Integration tests — require a real PostgreSQL instance.
|
||||||
|
# These test that the SQL queries in the adapter crates are correct.
|
||||||
|
integration:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:16
|
||||||
|
env:
|
||||||
|
POSTGRES_PASSWORD: postgres
|
||||||
|
POSTGRES_DB: thoughts_test
|
||||||
|
options: >-
|
||||||
|
--health-cmd pg_isready
|
||||||
|
--health-interval 10s
|
||||||
|
--health-timeout 5s
|
||||||
|
--health-retries 5
|
||||||
|
ports:
|
||||||
|
- 5432:5432
|
||||||
|
env:
|
||||||
|
DATABASE_URL: postgres://postgres:postgres@localhost:5432/thoughts_test
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
|
- uses: Swatinem/rust-cache@v2
|
||||||
|
- name: integration tests
|
||||||
|
run: |
|
||||||
|
cargo test \
|
||||||
|
-p postgres \
|
||||||
|
-p postgres-federation \
|
||||||
|
-p postgres-search
|
||||||
|
|||||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,6 +1,3 @@
|
|||||||
.env
|
.env
|
||||||
/.superpowers/
|
|
||||||
|
|
||||||
/target
|
/target
|
||||||
/docs/superpowers/
|
|
||||||
/media
|
|
||||||
|
|||||||
164
ARCHITECTURE.md
164
ARCHITECTURE.md
@@ -1,164 +0,0 @@
|
|||||||
# Architecture
|
|
||||||
|
|
||||||
Hexagonal (ports & adapters) architecture. Dependencies point inward — adapters implement domain ports, application orchestrates use cases, presentation handles HTTP.
|
|
||||||
|
|
||||||
## Crate dependency graph
|
|
||||||
|
|
||||||
```mermaid
|
|
||||||
graph TD
|
|
||||||
subgraph Entry Points
|
|
||||||
bootstrap["bootstrap<br/><small>HTTP server, DI wiring</small>"]
|
|
||||||
worker["worker<br/><small>background job consumer</small>"]
|
|
||||||
end
|
|
||||||
|
|
||||||
subgraph Interface Layer
|
|
||||||
presentation["presentation<br/><small>axum handlers, extractors, AppState</small>"]
|
|
||||||
api_types["api-types<br/><small>DTOs, OpenAPI</small>"]
|
|
||||||
end
|
|
||||||
|
|
||||||
subgraph Application Layer
|
|
||||||
application["application<br/><small>use cases, FederationEventService</small>"]
|
|
||||||
end
|
|
||||||
|
|
||||||
subgraph Domain Layer
|
|
||||||
domain["domain<br/><small>models, value objects, events, port traits</small>"]
|
|
||||||
end
|
|
||||||
|
|
||||||
subgraph Adapters
|
|
||||||
postgres["postgres<br/><small>UserRepo, ThoughtRepo, LikeRepo,<br/>BoostRepo, FollowRepo, BlockRepo,<br/>TagRepo, FeedRepo, FederationContentRepo, ...</small>"]
|
|
||||||
activitypub["activitypub<br/><small>FederationActionPort,<br/>FederationBroadcastPort,<br/>FederationSchedulerPort<br/>(wraps k-ap)</small>"]
|
|
||||||
postgres_fed["postgres-federation<br/><small>k-ap DB traits</small>"]
|
|
||||||
postgres_search["postgres-search<br/><small>SearchPort</small>"]
|
|
||||||
auth["auth<br/><small>AuthService, ApiKeyService</small>"]
|
|
||||||
nats["nats<br/><small>EventPublisher, EventConsumer</small>"]
|
|
||||||
storage["storage<br/><small>MediaStore</small>"]
|
|
||||||
event_transport["event-transport<br/><small>event delivery</small>"]
|
|
||||||
event_payload["event-payload<br/><small>event serialization</small>"]
|
|
||||||
end
|
|
||||||
|
|
||||||
bootstrap --> presentation
|
|
||||||
bootstrap --> application
|
|
||||||
bootstrap --> postgres
|
|
||||||
bootstrap --> postgres_fed
|
|
||||||
bootstrap --> postgres_search
|
|
||||||
bootstrap --> activitypub
|
|
||||||
bootstrap --> auth
|
|
||||||
bootstrap --> nats
|
|
||||||
bootstrap --> storage
|
|
||||||
bootstrap --> event_transport
|
|
||||||
bootstrap --> event_payload
|
|
||||||
|
|
||||||
worker --> application
|
|
||||||
worker --> activitypub
|
|
||||||
worker --> postgres
|
|
||||||
worker --> postgres_fed
|
|
||||||
worker --> nats
|
|
||||||
worker --> event_transport
|
|
||||||
worker --> event_payload
|
|
||||||
|
|
||||||
presentation --> application
|
|
||||||
presentation --> api_types
|
|
||||||
presentation --> domain
|
|
||||||
|
|
||||||
application --> domain
|
|
||||||
|
|
||||||
postgres --> domain
|
|
||||||
activitypub --> domain
|
|
||||||
postgres_fed -.-> domain
|
|
||||||
postgres_search --> domain
|
|
||||||
postgres_search --> postgres
|
|
||||||
auth --> domain
|
|
||||||
nats --> domain
|
|
||||||
storage --> domain
|
|
||||||
event_transport --> domain
|
|
||||||
event_payload --> domain
|
|
||||||
```
|
|
||||||
|
|
||||||
## Domain ports
|
|
||||||
|
|
||||||
```mermaid
|
|
||||||
classDiagram
|
|
||||||
class domain {
|
|
||||||
<<core>>
|
|
||||||
}
|
|
||||||
|
|
||||||
namespace Data Ports {
|
|
||||||
class UserRepository {
|
|
||||||
<<trait>>
|
|
||||||
find_by_id()
|
|
||||||
find_by_username()
|
|
||||||
save()
|
|
||||||
update_profile()
|
|
||||||
}
|
|
||||||
class ThoughtRepository {
|
|
||||||
<<trait>>
|
|
||||||
save()
|
|
||||||
find_by_id()
|
|
||||||
delete()
|
|
||||||
update_content()
|
|
||||||
}
|
|
||||||
class LikeRepository { <<trait>> }
|
|
||||||
class BoostRepository { <<trait>> }
|
|
||||||
class FollowRepository { <<trait>> }
|
|
||||||
class BlockRepository { <<trait>> }
|
|
||||||
class TagRepository { <<trait>> }
|
|
||||||
class FeedRepository { <<trait>> }
|
|
||||||
class NotificationRepository { <<trait>> }
|
|
||||||
class EngagementRepository { <<trait>> }
|
|
||||||
class SearchPort { <<trait>> }
|
|
||||||
}
|
|
||||||
|
|
||||||
namespace Federation Ports {
|
|
||||||
class FederationContentRepository {
|
|
||||||
<<trait>>
|
|
||||||
outbox_entries_for_actor()
|
|
||||||
find_remote_actor_id()
|
|
||||||
intern_remote_actor()
|
|
||||||
accept_note()
|
|
||||||
retract_note()
|
|
||||||
}
|
|
||||||
class FederationBroadcastPort {
|
|
||||||
<<trait>>
|
|
||||||
broadcast_create()
|
|
||||||
broadcast_delete()
|
|
||||||
broadcast_update()
|
|
||||||
broadcast_announce()
|
|
||||||
broadcast_like()
|
|
||||||
}
|
|
||||||
class FederationActionPort {
|
|
||||||
<<supertrait>>
|
|
||||||
}
|
|
||||||
class FederationLookupPort { <<trait>> }
|
|
||||||
class FederationFollowPort { <<trait>> }
|
|
||||||
class FederationFollowRequestPort { <<trait>> }
|
|
||||||
class FederationFetchPort { <<trait>> }
|
|
||||||
class FederationBlockPort { <<trait>> }
|
|
||||||
class FederationSchedulerPort { <<trait>> }
|
|
||||||
}
|
|
||||||
|
|
||||||
namespace Infra Ports {
|
|
||||||
class EventPublisher { <<trait>> }
|
|
||||||
class EventConsumer { <<trait>> }
|
|
||||||
class AuthService { <<trait>> }
|
|
||||||
class PasswordHasher { <<trait>> }
|
|
||||||
class MediaStore { <<trait>> }
|
|
||||||
}
|
|
||||||
|
|
||||||
FederationActionPort --|> FederationLookupPort
|
|
||||||
FederationActionPort --|> FederationFollowPort
|
|
||||||
FederationActionPort --|> FederationFollowRequestPort
|
|
||||||
FederationActionPort --|> FederationFetchPort
|
|
||||||
FederationActionPort --|> FederationBlockPort
|
|
||||||
```
|
|
||||||
|
|
||||||
## Dependency rule
|
|
||||||
|
|
||||||
```
|
|
||||||
bootstrap/worker ──► presentation ──► application ──► domain ◄── adapters
|
|
||||||
```
|
|
||||||
|
|
||||||
- **domain** — zero framework deps, pure business logic, defines all port traits
|
|
||||||
- **application** — orchestrates use cases, depends only on domain
|
|
||||||
- **presentation** — HTTP handlers (axum), depends on domain + application
|
|
||||||
- **adapters** — implement domain ports, depend inward on domain only
|
|
||||||
- **bootstrap/worker** — composition roots, wire adapters into ports
|
|
||||||
454
Cargo.lock
generated
454
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -14,7 +14,6 @@ members = [
|
|||||||
"crates/adapters/nats",
|
"crates/adapters/nats",
|
||||||
"crates/adapters/event-payload",
|
"crates/adapters/event-payload",
|
||||||
"crates/adapters/event-transport",
|
"crates/adapters/event-transport",
|
||||||
"crates/adapters/storage",
|
|
||||||
]
|
]
|
||||||
resolver = "2"
|
resolver = "2"
|
||||||
|
|
||||||
@@ -30,10 +29,9 @@ async-trait = "0.1"
|
|||||||
uuid = { version = "1.0", features = ["v4", "v5", "serde"] }
|
uuid = { version = "1.0", features = ["v4", "v5", "serde"] }
|
||||||
chrono = { version = "0.4", features = ["serde"] }
|
chrono = { version = "0.4", features = ["serde"] }
|
||||||
sqlx = { version = "0.8", features = ["runtime-tokio-rustls", "postgres", "uuid", "chrono", "macros"] }
|
sqlx = { version = "0.8", features = ["runtime-tokio-rustls", "postgres", "uuid", "chrono", "macros"] }
|
||||||
axum = { version = "0.8", features = ["macros", "multipart"] }
|
axum = { version = "0.8", features = ["macros"] }
|
||||||
tower-http = { version = "0.6", features = ["cors", "trace"] }
|
tower-http = { version = "0.6", features = ["cors", "trace"] }
|
||||||
futures = "0.3"
|
futures = "0.3"
|
||||||
bytes = "1.0"
|
|
||||||
dotenvy = "0.15"
|
dotenvy = "0.15"
|
||||||
async-nats = "0.48"
|
async-nats = "0.48"
|
||||||
async-stream = "0.3"
|
async-stream = "0.3"
|
||||||
@@ -52,4 +50,3 @@ auth = { path = "crates/adapters/auth" }
|
|||||||
nats = { path = "crates/adapters/nats" }
|
nats = { path = "crates/adapters/nats" }
|
||||||
event-payload = { path = "crates/adapters/event-payload" }
|
event-payload = { path = "crates/adapters/event-payload" }
|
||||||
event-transport = { path = "crates/adapters/event-transport" }
|
event-transport = { path = "crates/adapters/event-transport" }
|
||||||
storage = { path = "crates/adapters/storage" }
|
|
||||||
|
|||||||
@@ -4,11 +4,10 @@ FROM rust:slim-bookworm AS builder
|
|||||||
WORKDIR /build
|
WORKDIR /build
|
||||||
|
|
||||||
# Cache dependency compilation separately from source
|
# Cache dependency compilation separately from source
|
||||||
COPY .cargo/ .cargo/
|
|
||||||
COPY Cargo.toml Cargo.lock ./
|
COPY Cargo.toml Cargo.lock ./
|
||||||
COPY crates/adapters/activitypub/Cargo.toml crates/adapters/activitypub/Cargo.toml
|
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/auth/Cargo.toml crates/adapters/auth/Cargo.toml
|
||||||
COPY crates/adapters/storage/Cargo.toml crates/adapters/storage/Cargo.toml
|
|
||||||
COPY crates/adapters/event-payload/Cargo.toml crates/adapters/event-payload/Cargo.toml
|
COPY crates/adapters/event-payload/Cargo.toml crates/adapters/event-payload/Cargo.toml
|
||||||
COPY crates/adapters/event-transport/Cargo.toml crates/adapters/event-transport/Cargo.toml
|
COPY crates/adapters/event-transport/Cargo.toml crates/adapters/event-transport/Cargo.toml
|
||||||
COPY crates/adapters/nats/Cargo.toml crates/adapters/nats/Cargo.toml
|
COPY crates/adapters/nats/Cargo.toml crates/adapters/nats/Cargo.toml
|
||||||
@@ -36,7 +35,7 @@ RUN cargo fetch
|
|||||||
# Now copy real source and build
|
# Now copy real source and build
|
||||||
COPY crates ./crates
|
COPY crates ./crates
|
||||||
|
|
||||||
RUN cargo build --release -p bootstrap -p worker --features storage/s3
|
RUN cargo build --release -p bootstrap -p worker
|
||||||
|
|
||||||
# ----- runtime -----
|
# ----- runtime -----
|
||||||
FROM debian:bookworm-slim
|
FROM debian:bookworm-slim
|
||||||
@@ -52,7 +51,7 @@ WORKDIR /app
|
|||||||
COPY --from=builder /build/target/release/thoughts ./thoughts
|
COPY --from=builder /build/target/release/thoughts ./thoughts
|
||||||
COPY --from=builder /build/target/release/thoughts-worker ./thoughts-worker
|
COPY --from=builder /build/target/release/thoughts-worker ./thoughts-worker
|
||||||
|
|
||||||
EXPOSE 8000
|
EXPOSE 3000
|
||||||
|
|
||||||
ENV RUST_LOG=info
|
ENV RUST_LOG=info
|
||||||
|
|
||||||
|
|||||||
48
Makefile
48
Makefile
@@ -1,48 +0,0 @@
|
|||||||
.DEFAULT_GOAL := check
|
|
||||||
|
|
||||||
# Run the full local check suite — same order as CI would.
|
|
||||||
check: fmt-check clippy test
|
|
||||||
@echo "✅ All checks passed"
|
|
||||||
|
|
||||||
# Apply rustfmt to all files.
|
|
||||||
fmt:
|
|
||||||
cargo fmt
|
|
||||||
|
|
||||||
# Check formatting without modifying files (CI-safe).
|
|
||||||
fmt-check:
|
|
||||||
cargo fmt --check
|
|
||||||
|
|
||||||
# Run Clippy and treat warnings as errors.
|
|
||||||
clippy:
|
|
||||||
cargo clippy -- -D warnings
|
|
||||||
|
|
||||||
# Run the full test suite (requires DATABASE_URL).
|
|
||||||
test:
|
|
||||||
cargo test
|
|
||||||
|
|
||||||
# Unit tests only — no database required.
|
|
||||||
test-unit:
|
|
||||||
cargo test -p domain -p application -p api-types -p activitypub
|
|
||||||
|
|
||||||
# Integration tests only — requires DATABASE_URL.
|
|
||||||
test-integration:
|
|
||||||
cargo test -p postgres -p postgres-federation -p postgres-search -p presentation
|
|
||||||
|
|
||||||
# Apply fmt + clippy auto-fixes in one shot.
|
|
||||||
fix:
|
|
||||||
cargo fmt
|
|
||||||
cargo clippy --fix --allow-dirty --allow-staged
|
|
||||||
|
|
||||||
# Start infra (Postgres + NATS) for local development.
|
|
||||||
dev-infra:
|
|
||||||
docker compose up postgres nats -d
|
|
||||||
|
|
||||||
# Stop infra.
|
|
||||||
dev-infra-down:
|
|
||||||
docker compose down
|
|
||||||
|
|
||||||
# Full Docker stack.
|
|
||||||
up:
|
|
||||||
docker compose up --build
|
|
||||||
|
|
||||||
.PHONY: check fmt fmt-check clippy test test-unit test-integration fix dev-infra dev-infra-down up
|
|
||||||
105
README.md
105
README.md
@@ -14,14 +14,7 @@ A self-hosted microblogging server with full ActivityPub federation. Write short
|
|||||||
- JWT authentication (Bearer token) with API key support for third-party clients
|
- JWT authentication (Bearer token) with API key support for third-party clients
|
||||||
- OpenAPI documentation at `/docs` (Swagger UI) and `/scalar` (Scalar)
|
- OpenAPI documentation at `/docs` (Swagger UI) and `/scalar` (Scalar)
|
||||||
- Full-text search over thoughts and users via PostgreSQL trigram indexes
|
- Full-text search over thoughts and users via PostgreSQL trigram indexes
|
||||||
- **Profile fields** — up to 4 custom key/value fields (Website, Pronouns, etc.), federated as AP `PropertyValue` attachment
|
- Top friends — pin up to 5 users as highlighted contacts
|
||||||
- **Custom CSS** — per-user stylesheet applied to their profile page
|
|
||||||
- **Visibility levels** — public, followers-only, unlisted, and direct posts
|
|
||||||
- **Content warnings** — optional CW label and sensitive flag on posts
|
|
||||||
- **Feed controls** — sort by newest, oldest, most liked, most boosted, or most discussed; filter to originals only, replies only, local only, or hide sensitive
|
|
||||||
- **Popular tags** — trending hashtag discovery
|
|
||||||
- Top friends — pin up to 8 users as highlighted contacts
|
|
||||||
- Account migration — set `alsoKnownAs` for Fediverse actor moves
|
|
||||||
- Home feed, public feed, and per-user thought timelines
|
- Home feed, public feed, and per-user thought timelines
|
||||||
- Rate limiting and registration control
|
- Rate limiting and registration control
|
||||||
|
|
||||||
@@ -70,11 +63,10 @@ bootstrap — binary: thoughts (API server)
|
|||||||
worker — binary: thoughts-worker (event consumer — notifications, AP fan-out)
|
worker — binary: thoughts-worker (event consumer — notifications, AP fan-out)
|
||||||
adapters/
|
adapters/
|
||||||
auth — JWT issuance and validation, Argon2 password hashing
|
auth — JWT issuance and validation, Argon2 password hashing
|
||||||
storage — object storage adapter (local filesystem + S3/MinIO) implementing the MediaStore port
|
|
||||||
postgres — PostgreSQL repositories for all domain entities
|
postgres — PostgreSQL repositories for all domain entities
|
||||||
postgres-search — PostgreSQL trigram full-text search
|
postgres-search — PostgreSQL trigram full-text search
|
||||||
postgres-federation — PostgreSQL-backed federation repository
|
postgres-federation — PostgreSQL-backed federation repository
|
||||||
k-ap (external) — generic AP protocol layer (ActivityPubService, actor management, inbox/outbox routing, follower tracking, WebFinger, NodeInfo, HTTP signatures)
|
activitypub-base — core ActivityPub protocol types, ActivityPubService, federation middleware
|
||||||
activitypub — project-specific AP wiring (ThoughtsObjectHandler, inbox/outbox)
|
activitypub — project-specific AP wiring (ThoughtsObjectHandler, inbox/outbox)
|
||||||
nats — NATS transport implementing Transport + MessageSource ports
|
nats — NATS transport implementing Transport + MessageSource ports
|
||||||
event-payload — shared event serialization DTOs
|
event-payload — shared event serialization DTOs
|
||||||
@@ -83,20 +75,11 @@ adapters/
|
|||||||
|
|
||||||
The `domain` and `application` crates have zero concrete adapter dependencies. All I/O goes through `&dyn Port` traits, keeping business logic fully testable with in-memory fakes.
|
The `domain` and `application` crates have zero concrete adapter dependencies. All I/O goes through `&dyn Port` traits, keeping business logic fully testable with in-memory fakes.
|
||||||
|
|
||||||
## Media Storage
|
|
||||||
|
|
||||||
Users can upload avatar and banner images via `PUT /users/me/avatar` and `PUT /users/me/banner` (multipart/form-data). Uploaded images are served at `GET /media/*path` (public, no auth required). Set `STORAGE_BACKEND` to configure the backend.
|
|
||||||
|
|
||||||
## Prerequisites
|
## Prerequisites
|
||||||
|
|
||||||
- Rust stable (1.80+)
|
- Rust stable (1.80+)
|
||||||
- PostgreSQL 15+
|
- PostgreSQL 15+
|
||||||
- NATS with JetStream (optional — see [Without NATS](#without-nats))
|
- NATS with JetStream (optional — see [Without NATS](#without-nats))
|
||||||
- Docker & Docker Compose (for the easiest local setup)
|
|
||||||
|
|
||||||
### Private cargo registry
|
|
||||||
|
|
||||||
The `k-ap` crate (ActivityPub protocol library) is hosted on a private Gitea registry configured in `.cargo/config.toml`. To build the project you need read access to `git.gabrielkaszewski.dev`. If you're contributing and don't have access, open an issue and I'll sort it out.
|
|
||||||
|
|
||||||
## Environment Variables
|
## Environment Variables
|
||||||
|
|
||||||
@@ -115,60 +98,16 @@ Copy `.env.example` to `.env` and fill in your values.
|
|||||||
| Variable | Default | Description |
|
| Variable | Default | Description |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `HOST` | `0.0.0.0` | Interface to bind |
|
| `HOST` | `0.0.0.0` | Interface to bind |
|
||||||
| `PORT` | `8000` | Port to listen on |
|
| `PORT` | `3000` | Port to listen on |
|
||||||
| `NATS_URL` | — | NATS connection string. If unset, a no-op publisher is used and events are not delivered to the worker |
|
| `NATS_URL` | — | NATS connection string. If unset, a no-op publisher is used and events are not delivered to the worker |
|
||||||
| `CORS_ORIGINS` | `*` | Comma-separated allowed origins for CORS, e.g. `https://app.example.com` |
|
| `CORS_ORIGINS` | `*` | Comma-separated allowed origins for CORS, e.g. `https://app.example.com` |
|
||||||
| `RATE_LIMIT` | disabled | Max requests per minute per IP |
|
| `RATE_LIMIT` | disabled | Max requests per minute per IP |
|
||||||
| `ALLOW_REGISTRATION` | `true` | Set to `false` to close sign-ups |
|
| `ALLOW_REGISTRATION` | `true` | Set to `false` to close sign-ups |
|
||||||
| `RUST_ENV` | `development` | Set to `production` to disable ActivityPub debug logging |
|
| `RUST_ENV` | `development` | Set to `production` to disable ActivityPub debug logging |
|
||||||
| `RUST_LOG` | `info` | Log level filter (`error`, `warn`, `info`, `debug`, `trace`) |
|
| `RUST_LOG` | `info` | Log level filter (`error`, `warn`, `info`, `debug`, `trace`) |
|
||||||
| `STORAGE_BACKEND` | `local` | Storage backend: `local` or `s3` |
|
|
||||||
| `STORAGE_PATH` | — | Local filesystem path for media (required when `STORAGE_BACKEND=local`) |
|
|
||||||
| `STORAGE_PREFIX` | — | Optional key prefix for all stored objects |
|
|
||||||
| `S3_ENDPOINT` | — | S3/MinIO endpoint URL (required when `STORAGE_BACKEND=s3`) |
|
|
||||||
| `S3_ACCESS_KEY_ID` | — | S3 access key (required when `STORAGE_BACKEND=s3`) |
|
|
||||||
| `S3_SECRET_ACCESS_KEY` | — | S3 secret key (required when `STORAGE_BACKEND=s3`) |
|
|
||||||
| `S3_BUCKET` | — | S3 bucket name (required when `STORAGE_BACKEND=s3`) |
|
|
||||||
| `S3_REGION` | `us-east-1` | S3 region |
|
|
||||||
| `UPLOAD_MAX_BYTES` | `5242880` | Max upload size in bytes (default 5 MiB) |
|
|
||||||
| `UPLOAD_ALLOWED_TYPES` | `image/jpeg,image/png,image/gif,image/webp,image/avif` | Comma-separated allowed MIME types |
|
|
||||||
|
|
||||||
### Frontend environment
|
|
||||||
|
|
||||||
Copy `thoughts-frontend/.env.example` to `thoughts-frontend/.env.local` and adjust:
|
|
||||||
|
|
||||||
| Variable | Description |
|
|
||||||
|---|---|
|
|
||||||
| `NEXT_PUBLIC_API_URL` | API URL for client-side (browser) requests, e.g. `http://localhost:8000` |
|
|
||||||
| `NEXT_PUBLIC_SERVER_SIDE_API_URL` | API URL for SSR requests — same as above locally, or `http://api:8000` inside Docker |
|
|
||||||
| `NEXT_PUBLIC_FEDIVERSE_DOMAIN` | (Optional) Domain shown on profile fediverse handles, e.g. `yourinstance.example.com` |
|
|
||||||
|
|
||||||
## Run
|
## Run
|
||||||
|
|
||||||
### Local development (recommended)
|
|
||||||
|
|
||||||
Start only the infrastructure containers (Postgres + NATS), then run the Rust backend and Next.js frontend natively for fast iteration:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# 1. Start Postgres + NATS
|
|
||||||
make dev-infra
|
|
||||||
|
|
||||||
# 2. Copy and fill in env files
|
|
||||||
cp .env.example .env
|
|
||||||
cp thoughts-frontend/.env.example thoughts-frontend/.env.local
|
|
||||||
|
|
||||||
# 3. API server (runs migrations automatically on startup)
|
|
||||||
cargo run -p bootstrap
|
|
||||||
|
|
||||||
# 4. Event worker (separate terminal, optional)
|
|
||||||
cargo run -p worker
|
|
||||||
|
|
||||||
# 5. Frontend (separate terminal)
|
|
||||||
cd thoughts-frontend && bun install && bun dev
|
|
||||||
```
|
|
||||||
|
|
||||||
### Bare metal
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# API server (runs migrations automatically on startup)
|
# API server (runs migrations automatically on startup)
|
||||||
cargo run -p bootstrap
|
cargo run -p bootstrap
|
||||||
@@ -182,20 +121,14 @@ Both processes share the same PostgreSQL database. The worker is optional but re
|
|||||||
## Test
|
## Test
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Unit tests only — no database required
|
# Unit tests — no database required
|
||||||
make test-unit
|
cargo test -p application
|
||||||
|
|
||||||
# Integration tests — requires DATABASE_URL pointing to a running PostgreSQL
|
# Full workspace (requires DATABASE_URL pointing to a running PostgreSQL)
|
||||||
make test-integration
|
cargo test --workspace
|
||||||
|
|
||||||
# Everything (unit + integration)
|
|
||||||
make test
|
|
||||||
|
|
||||||
# Full check suite: fmt + clippy + tests
|
|
||||||
make check
|
|
||||||
```
|
```
|
||||||
|
|
||||||
`make test-unit` runs domain, application, api-types, and activitypub tests using in-memory fakes — the fastest feedback loop for business logic. `make test-integration` runs the adapter crates against a live PostgreSQL.
|
The `application` crate contains unit tests for all event services and use cases backed by in-memory fakes from `domain`'s `test-helpers` feature. These are the fastest feedback loop for business logic.
|
||||||
|
|
||||||
## API
|
## API
|
||||||
|
|
||||||
@@ -208,7 +141,18 @@ Interactive API documentation is available at runtime:
|
|||||||
|
|
||||||
## Frontend
|
## Frontend
|
||||||
|
|
||||||
The Next.js frontend lives in `thoughts-frontend/`. See [Frontend environment](#frontend-environment) for required env vars, or follow the [local development](#local-development-recommended) steps above.
|
The Next.js frontend lives in `thoughts-frontend/`. It requires two environment variables:
|
||||||
|
|
||||||
|
```env
|
||||||
|
NEXT_PUBLIC_API_URL=http://localhost:8000 # client-side requests
|
||||||
|
NEXT_PUBLIC_SERVER_SIDE_API_URL=http://localhost:8000 # SSR requests
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd thoughts-frontend
|
||||||
|
bun install
|
||||||
|
bun run dev # http://localhost:3000
|
||||||
|
```
|
||||||
|
|
||||||
## Docker
|
## Docker
|
||||||
|
|
||||||
@@ -223,9 +167,6 @@ docker run -p 8000:8000 \
|
|||||||
-e JWT_SECRET=change-me \
|
-e JWT_SECRET=change-me \
|
||||||
-e BASE_URL=https://yourdomain.example.com \
|
-e BASE_URL=https://yourdomain.example.com \
|
||||||
-e NATS_URL=nats://nats:4222 \
|
-e NATS_URL=nats://nats:4222 \
|
||||||
-e STORAGE_BACKEND=local \
|
|
||||||
-e STORAGE_PATH=/data/media \
|
|
||||||
-v media_vol:/data/media \
|
|
||||||
thoughts
|
thoughts
|
||||||
|
|
||||||
# Event worker (same image, different entrypoint)
|
# Event worker (same image, different entrypoint)
|
||||||
@@ -244,12 +185,12 @@ docker build -t thoughts-frontend \
|
|||||||
docker run -p 3000:3000 thoughts-frontend
|
docker run -p 3000:3000 thoughts-frontend
|
||||||
```
|
```
|
||||||
|
|
||||||
### Full Docker stack
|
### Local development stack
|
||||||
|
|
||||||
`compose.yml` spins up the full stack: PostgreSQL, NATS (with JetStream and monitoring on port 8222), the API server, the event worker, and the frontend.
|
`compose.yml` spins up the full stack: PostgreSQL, NATS (with JetStream and monitoring on port 8222), the API server, the event worker, and the frontend.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
make up # or: docker compose up --build
|
docker compose up
|
||||||
```
|
```
|
||||||
|
|
||||||
Services:
|
Services:
|
||||||
@@ -266,7 +207,7 @@ Services:
|
|||||||
|
|
||||||
Contributions are welcome. A few guidelines:
|
Contributions are welcome. A few guidelines:
|
||||||
|
|
||||||
- **Run tests before opening a PR.** At minimum: `make test-unit` (no database needed). For adapter changes: `make test-integration` with a live database. `make check` runs the full suite (fmt + clippy + tests).
|
- **Run tests before opening a PR.** At minimum: `cargo test -p application` (no database needed). For adapter changes: `cargo test --workspace` with a live database.
|
||||||
- **Keep the hexagonal boundary.** `domain` and `application` must not import any adapter crate. Use `&dyn Port` traits for all I/O.
|
- **Keep the hexagonal boundary.** `domain` and `application` must not import any adapter crate. Use `&dyn Port` traits for all I/O.
|
||||||
- **No ORM.** The project uses raw `sqlx`. Keep it that way.
|
- **No ORM.** The project uses raw `sqlx`. Keep it that way.
|
||||||
- **ActivityPub changes** — test against a live Mastodon instance if possible, or use the AP debug logs (`RUST_ENV=development`).
|
- **ActivityPub changes** — test against a live Mastodon instance if possible, or use the AP debug logs (`RUST_ENV=development`).
|
||||||
|
|||||||
@@ -47,18 +47,11 @@ services:
|
|||||||
labels:
|
labels:
|
||||||
- "traefik.enable=true"
|
- "traefik.enable=true"
|
||||||
- "traefik.docker.network=traefik"
|
- "traefik.docker.network=traefik"
|
||||||
# Original API subdomain — keep for backwards compat and direct API access
|
|
||||||
- "traefik.http.routers.thoughts-api.rule=Host(`api.thoughts.gabrielkaszewski.dev`)"
|
- "traefik.http.routers.thoughts-api.rule=Host(`api.thoughts.gabrielkaszewski.dev`)"
|
||||||
- "traefik.http.routers.thoughts-api.entrypoints=web,websecure"
|
- "traefik.http.routers.thoughts-api.entrypoints=web,websecure"
|
||||||
- "traefik.http.routers.thoughts-api.tls.certresolver=letsencrypt"
|
- "traefik.http.routers.thoughts-api.tls.certresolver=letsencrypt"
|
||||||
- "traefik.http.routers.thoughts-api.service=thoughts-api"
|
- "traefik.http.routers.thoughts-api.service=thoughts-api"
|
||||||
- "traefik.http.services.thoughts-api.loadbalancer.server.port=8000"
|
- "traefik.http.services.thoughts-api.loadbalancer.server.port=8000"
|
||||||
# Federation routes on the main domain — higher priority than the frontend catch-all
|
|
||||||
- "traefik.http.routers.thoughts-federation.rule=Host(`thoughts.gabrielkaszewski.dev`) && (PathPrefix(`/.well-known`) || PathPrefix(`/nodeinfo`) || Path(`/inbox`) || (Method(`POST`) && PathPrefix(`/users/`)))"
|
|
||||||
- "traefik.http.routers.thoughts-federation.entrypoints=web,websecure"
|
|
||||||
- "traefik.http.routers.thoughts-federation.tls.certresolver=letsencrypt"
|
|
||||||
- "traefik.http.routers.thoughts-federation.service=thoughts-api"
|
|
||||||
- "traefik.http.routers.thoughts-federation.priority=1000"
|
|
||||||
|
|
||||||
worker:
|
worker:
|
||||||
container_name: thoughts-worker
|
container_name: thoughts-worker
|
||||||
@@ -84,7 +77,6 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
NEXT_PUBLIC_SERVER_SIDE_API_URL: http://api:8000
|
NEXT_PUBLIC_SERVER_SIDE_API_URL: http://api:8000
|
||||||
NEXT_PUBLIC_API_URL: https://api.thoughts.gabrielkaszewski.dev
|
NEXT_PUBLIC_API_URL: https://api.thoughts.gabrielkaszewski.dev
|
||||||
NEXT_PUBLIC_FEDIVERSE_DOMAIN: thoughts.gabrielkaszewski.dev
|
|
||||||
PORT: 3000
|
PORT: 3000
|
||||||
HOSTNAME: 0.0.0.0
|
HOSTNAME: 0.0.0.0
|
||||||
depends_on:
|
depends_on:
|
||||||
|
|||||||
@@ -30,13 +30,8 @@ services:
|
|||||||
DATABASE_URL: postgres://postgres:postgres@postgres:5432/thoughts
|
DATABASE_URL: postgres://postgres:postgres@postgres:5432/thoughts
|
||||||
JWT_SECRET: change-me-in-production
|
JWT_SECRET: change-me-in-production
|
||||||
BASE_URL: http://localhost:8000
|
BASE_URL: http://localhost:8000
|
||||||
PORT: 8000
|
|
||||||
NATS_URL: nats://nats:4222
|
NATS_URL: nats://nats:4222
|
||||||
RUST_LOG: info
|
RUST_LOG: info
|
||||||
STORAGE_BACKEND: local
|
|
||||||
STORAGE_PATH: /data/media
|
|
||||||
volumes:
|
|
||||||
- media_data:/data/media
|
|
||||||
depends_on:
|
depends_on:
|
||||||
postgres:
|
postgres:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
@@ -70,4 +65,3 @@ services:
|
|||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
postgres_data:
|
postgres_data:
|
||||||
media_data:
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ version = "0.1.0"
|
|||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
k-ap = { version = "0.4.4", registry = "gitea" }
|
k-ap = { git = "https://git.gabrielkaszewski.dev/GKaszewski/k-ap.git", tag = "v0.1.2" }
|
||||||
domain = { workspace = true }
|
domain = { workspace = true }
|
||||||
url = { workspace = true }
|
url = { workspace = true }
|
||||||
serde = { workspace = true }
|
serde = { workspace = true }
|
||||||
@@ -14,6 +14,7 @@ chrono = { workspace = true }
|
|||||||
uuid = { workspace = true }
|
uuid = { workspace = true }
|
||||||
async-trait = { workspace = true }
|
async-trait = { workspace = true }
|
||||||
tracing = { workspace = true }
|
tracing = { workspace = true }
|
||||||
|
activitypub_federation = "0.7.0-beta.11"
|
||||||
reqwest = { workspace = true }
|
reqwest = { workspace = true }
|
||||||
futures = { workspace = true }
|
futures = { workspace = true }
|
||||||
tokio = { workspace = true }
|
tokio = { workspace = true }
|
||||||
|
|||||||
@@ -10,17 +10,15 @@ use url::Url;
|
|||||||
use crate::note::{ThoughtNote, ThoughtNoteInput};
|
use crate::note::{ThoughtNote, ThoughtNoteInput};
|
||||||
use crate::port::{AcceptNoteInput, ActivityPubRepository};
|
use crate::port::{AcceptNoteInput, ActivityPubRepository};
|
||||||
use crate::urls::ThoughtsUrls;
|
use crate::urls::ThoughtsUrls;
|
||||||
use domain::ports::{BoostRepository, EventPublisher, LikeRepository, TagRepository};
|
use k_ap::ApObjectHandler;
|
||||||
|
use domain::ports::{EventPublisher, TagRepository};
|
||||||
use domain::value_objects::UserId;
|
use domain::value_objects::UserId;
|
||||||
use k_ap::{ApContentReader, ApObjectHandler};
|
|
||||||
|
|
||||||
pub struct ThoughtsObjectHandler {
|
pub struct ThoughtsObjectHandler {
|
||||||
repo: Arc<dyn ActivityPubRepository>,
|
repo: Arc<dyn ActivityPubRepository>,
|
||||||
urls: ThoughtsUrls,
|
urls: ThoughtsUrls,
|
||||||
event_publisher: Option<Arc<dyn EventPublisher>>,
|
event_publisher: Option<Arc<dyn EventPublisher>>,
|
||||||
tag_repo: Arc<dyn TagRepository>,
|
tag_repo: Arc<dyn TagRepository>,
|
||||||
likes: Arc<dyn LikeRepository>,
|
|
||||||
boosts: Arc<dyn BoostRepository>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ThoughtsObjectHandler {
|
impl ThoughtsObjectHandler {
|
||||||
@@ -29,24 +27,53 @@ impl ThoughtsObjectHandler {
|
|||||||
base_url: &str,
|
base_url: &str,
|
||||||
event_publisher: Option<Arc<dyn EventPublisher>>,
|
event_publisher: Option<Arc<dyn EventPublisher>>,
|
||||||
tag_repo: Arc<dyn TagRepository>,
|
tag_repo: Arc<dyn TagRepository>,
|
||||||
likes: Arc<dyn LikeRepository>,
|
|
||||||
boosts: Arc<dyn BoostRepository>,
|
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
repo,
|
repo,
|
||||||
urls: ThoughtsUrls::new(base_url),
|
urls: ThoughtsUrls::new(base_url),
|
||||||
event_publisher,
|
event_publisher,
|
||||||
tag_repo,
|
tag_repo,
|
||||||
likes,
|
|
||||||
boosts,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── ApContentReader ───────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl ApContentReader for ThoughtsObjectHandler {
|
impl ApObjectHandler for ThoughtsObjectHandler {
|
||||||
|
async fn get_local_objects_for_user(
|
||||||
|
&self,
|
||||||
|
user_id: uuid::Uuid,
|
||||||
|
) -> Result<Vec<(Url, serde_json::Value)>> {
|
||||||
|
let uid = UserId::from_uuid(user_id);
|
||||||
|
let entries = self
|
||||||
|
.repo
|
||||||
|
.outbox_entries_for_actor(&uid)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow!("{e}"))?;
|
||||||
|
entries
|
||||||
|
.into_iter()
|
||||||
|
.map(|e| {
|
||||||
|
let note_url = self.urls.thought_url(e.thought.id.as_uuid());
|
||||||
|
let actor_url = self.urls.user_url(e.author_username.as_str());
|
||||||
|
let followers = self.urls.user_followers(e.author_username.as_str());
|
||||||
|
let in_reply_to = e
|
||||||
|
.thought
|
||||||
|
.in_reply_to_id
|
||||||
|
.map(|id| self.urls.thought_url(id.as_uuid()));
|
||||||
|
let note = ThoughtNote::new_public(ThoughtNoteInput {
|
||||||
|
id: note_url.clone(),
|
||||||
|
actor_url,
|
||||||
|
content: e.thought.content.as_str().to_owned(),
|
||||||
|
published: e.thought.created_at,
|
||||||
|
in_reply_to,
|
||||||
|
sensitive: e.thought.sensitive,
|
||||||
|
summary: e.thought.content_warning,
|
||||||
|
followers_url: followers,
|
||||||
|
});
|
||||||
|
Ok((note_url, serde_json::to_value(¬e)?))
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
async fn get_local_objects_page(
|
async fn get_local_objects_page(
|
||||||
&self,
|
&self,
|
||||||
user_id: uuid::Uuid,
|
user_id: uuid::Uuid,
|
||||||
@@ -64,8 +91,8 @@ impl ApContentReader for ThoughtsObjectHandler {
|
|||||||
.map(|e| {
|
.map(|e| {
|
||||||
let created_at = e.thought.created_at;
|
let created_at = e.thought.created_at;
|
||||||
let note_url = self.urls.thought_url(e.thought.id.as_uuid());
|
let note_url = self.urls.thought_url(e.thought.id.as_uuid());
|
||||||
let actor_url = self.urls.user_url(&user_id.to_string());
|
let actor_url = self.urls.user_url(e.author_username.as_str());
|
||||||
let followers = self.urls.user_followers(&user_id.to_string());
|
let followers = self.urls.user_followers(e.author_username.as_str());
|
||||||
let in_reply_to = e
|
let in_reply_to = e
|
||||||
.thought
|
.thought
|
||||||
.in_reply_to_id
|
.in_reply_to_id
|
||||||
@@ -85,38 +112,20 @@ impl ApContentReader for ThoughtsObjectHandler {
|
|||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn count_local_posts(&self) -> Result<u64> {
|
|
||||||
self.repo
|
|
||||||
.count_local_notes()
|
|
||||||
.await
|
|
||||||
.map_err(|e| anyhow!("{e}"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── ApObjectHandler ───────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl ApObjectHandler for ThoughtsObjectHandler {
|
|
||||||
async fn on_create(
|
async fn on_create(
|
||||||
&self,
|
&self,
|
||||||
ap_id: &Url,
|
ap_id: &Url,
|
||||||
actor_url: &Url,
|
actor_url: &Url,
|
||||||
object: serde_json::Value,
|
object: serde_json::Value,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let Some((note, note_extensions)) = ThoughtNote::try_from_ap(object) else {
|
let note: ThoughtNote = serde_json::from_value(object)?;
|
||||||
tracing::debug!(ap_id = %ap_id, "on_create: skipping non-Note object");
|
|
||||||
return Ok(());
|
|
||||||
};
|
|
||||||
let author_id = self
|
let author_id = self
|
||||||
.repo
|
.repo
|
||||||
.intern_remote_actor(actor_url.as_str())
|
.intern_remote_actor(actor_url.as_str())
|
||||||
.await
|
.await
|
||||||
.map_err(|e| anyhow!("{e}"))?;
|
.map_err(|e| anyhow!("{e}"))?;
|
||||||
let _ = self
|
|
||||||
.repo
|
|
||||||
.sync_remote_actor_to_user(actor_url.as_str())
|
|
||||||
.await;
|
|
||||||
|
|
||||||
|
// Derive visibility from AP addressing conventions.
|
||||||
let as_public = "https://www.w3.org/ns/activitystreams#Public";
|
let as_public = "https://www.w3.org/ns/activitystreams#Public";
|
||||||
let in_to = note.to.iter().any(|s| s == as_public);
|
let in_to = note.to.iter().any(|s| s == as_public);
|
||||||
let in_cc = note.cc.iter().any(|s| s == as_public);
|
let in_cc = note.cc.iter().any(|s| s == as_public);
|
||||||
@@ -144,11 +153,11 @@ impl ApObjectHandler for ThoughtsObjectHandler {
|
|||||||
content_warning: note.summary,
|
content_warning: note.summary,
|
||||||
visibility,
|
visibility,
|
||||||
in_reply_to: note.in_reply_to.as_ref().map(|u| u.as_str()),
|
in_reply_to: note.in_reply_to.as_ref().map(|u| u.as_str()),
|
||||||
note_extensions,
|
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.map_err(|e| anyhow!("{e}"))?;
|
.map_err(|e| anyhow!("{e}"))?;
|
||||||
|
|
||||||
|
// Extract and index hashtags from the AP tag array.
|
||||||
let hashtag_names: Vec<String> = note
|
let hashtag_names: Vec<String> = note
|
||||||
.tag
|
.tag
|
||||||
.iter()
|
.iter()
|
||||||
@@ -164,6 +173,7 @@ impl ApObjectHandler for ThoughtsObjectHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Fire mention notifications for local @mentions in the note's tag array.
|
||||||
let base_url = url::Url::parse(&self.urls.base_url)
|
let base_url = url::Url::parse(&self.urls.base_url)
|
||||||
.ok()
|
.ok()
|
||||||
.and_then(|u| u.host_str().map(|h| h.to_string()))
|
.and_then(|u| u.host_str().map(|h| h.to_string()))
|
||||||
@@ -204,51 +214,15 @@ impl ApObjectHandler for ThoughtsObjectHandler {
|
|||||||
async fn on_update(
|
async fn on_update(
|
||||||
&self,
|
&self,
|
||||||
ap_id: &Url,
|
ap_id: &Url,
|
||||||
actor_url: &Url,
|
_actor_url: &Url,
|
||||||
object: serde_json::Value,
|
object: serde_json::Value,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let obj_type = object.get("type").and_then(|v| v.as_str()).unwrap_or("");
|
let note: ThoughtNote = serde_json::from_value(object)?;
|
||||||
match obj_type {
|
|
||||||
"Note" | "Article" | "Page" => {
|
|
||||||
let Some((note, note_extensions)) = ThoughtNote::try_from_ap(object) else {
|
|
||||||
return Ok(());
|
|
||||||
};
|
|
||||||
self.repo
|
self.repo
|
||||||
.apply_note_update(ap_id.as_str(), ¬e.content, note_extensions)
|
.apply_note_update(ap_id.as_str(), ¬e.content)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| anyhow!("{e}"))
|
.map_err(|e| anyhow!("{e}"))
|
||||||
}
|
}
|
||||||
"Person" | "Service" | "Application" | "Group" | "Organization" => {
|
|
||||||
let display_name = object.get("name").and_then(|v| v.as_str());
|
|
||||||
let avatar_url = object
|
|
||||||
.get("icon")
|
|
||||||
.and_then(|v| v.get("url"))
|
|
||||||
.and_then(|v| v.as_str());
|
|
||||||
self.repo
|
|
||||||
.update_remote_actor_display(
|
|
||||||
&self
|
|
||||||
.repo
|
|
||||||
.find_remote_actor_id(actor_url.as_str())
|
|
||||||
.await
|
|
||||||
.map_err(|e| anyhow!("{e}"))?
|
|
||||||
.ok_or_else(|| anyhow!("unknown actor"))?,
|
|
||||||
display_name,
|
|
||||||
avatar_url,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.map_err(|e| anyhow!("{e}"))?;
|
|
||||||
let _ = self
|
|
||||||
.repo
|
|
||||||
.sync_remote_actor_to_user(actor_url.as_str())
|
|
||||||
.await;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
tracing::debug!(ap_id = %ap_id, obj_type, "on_update: skipping");
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_delete(&self, ap_id: &Url, _actor_url: &Url) -> Result<()> {
|
async fn on_delete(&self, ap_id: &Url, _actor_url: &Url) -> Result<()> {
|
||||||
self.repo
|
self.repo
|
||||||
@@ -288,24 +262,14 @@ impl ApObjectHandler for ThoughtsObjectHandler {
|
|||||||
let actor_user_id = match actor_user_id {
|
let actor_user_id = match actor_user_id {
|
||||||
Some(id) => id,
|
Some(id) => id,
|
||||||
None => {
|
None => {
|
||||||
tracing::debug!(actor = %actor_url, "on_like: remote actor not interned, skipping");
|
tracing::debug!(actor = %actor_url, "on_like: remote actor not interned, skipping notification");
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if let Some(ep) = &self.event_publisher {
|
||||||
let thought_id = domain::value_objects::ThoughtId::from_uuid(thought_uuid);
|
let thought_id = domain::value_objects::ThoughtId::from_uuid(thought_uuid);
|
||||||
let like_id = domain::value_objects::LikeId::new();
|
let like_id = domain::value_objects::LikeId::new();
|
||||||
|
|
||||||
let like = domain::models::social::Like {
|
|
||||||
id: like_id.clone(),
|
|
||||||
user_id: actor_user_id.clone(),
|
|
||||||
thought_id: thought_id.clone(),
|
|
||||||
ap_id: Some(object_url.to_string()),
|
|
||||||
created_at: Utc::now(),
|
|
||||||
};
|
|
||||||
let _ = self.likes.save(&like).await;
|
|
||||||
|
|
||||||
if let Some(ep) = &self.event_publisher {
|
|
||||||
ep.publish(&domain::events::DomainEvent::LikeAdded {
|
ep.publish(&domain::events::DomainEvent::LikeAdded {
|
||||||
like_id,
|
like_id,
|
||||||
user_id: actor_user_id,
|
user_id: actor_user_id,
|
||||||
@@ -347,13 +311,10 @@ impl ApObjectHandler for ThoughtsObjectHandler {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let thought_id = domain::value_objects::ThoughtId::from_uuid(thought_uuid);
|
|
||||||
let _ = self.likes.delete(&actor_user_id, &thought_id).await;
|
|
||||||
|
|
||||||
if let Some(ep) = &self.event_publisher {
|
if let Some(ep) = &self.event_publisher {
|
||||||
ep.publish(&domain::events::DomainEvent::LikeRemoved {
|
ep.publish(&domain::events::DomainEvent::LikeRemoved {
|
||||||
user_id: actor_user_id,
|
user_id: actor_user_id,
|
||||||
thought_id,
|
thought_id: domain::value_objects::ThoughtId::from_uuid(thought_uuid),
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.map_err(|e| anyhow!("{e}"))?;
|
.map_err(|e| anyhow!("{e}"))?;
|
||||||
@@ -425,19 +386,9 @@ impl ApObjectHandler for ThoughtsObjectHandler {
|
|||||||
None => return Ok(()),
|
None => return Ok(()),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if let Some(ep) = &self.event_publisher {
|
||||||
let thought_id = domain::value_objects::ThoughtId::from_uuid(thought_uuid);
|
let thought_id = domain::value_objects::ThoughtId::from_uuid(thought_uuid);
|
||||||
let boost_id = domain::value_objects::BoostId::new();
|
let boost_id = domain::value_objects::BoostId::new();
|
||||||
|
|
||||||
let boost = domain::models::social::Boost {
|
|
||||||
id: boost_id.clone(),
|
|
||||||
user_id: actor_user_id.clone(),
|
|
||||||
thought_id: thought_id.clone(),
|
|
||||||
ap_id: Some(object_url.to_string()),
|
|
||||||
created_at: Utc::now(),
|
|
||||||
};
|
|
||||||
let _ = self.boosts.save(&boost).await;
|
|
||||||
|
|
||||||
if let Some(ep) = &self.event_publisher {
|
|
||||||
ep.publish(&domain::events::DomainEvent::BoostAdded {
|
ep.publish(&domain::events::DomainEvent::BoostAdded {
|
||||||
boost_id,
|
boost_id,
|
||||||
user_id: actor_user_id,
|
user_id: actor_user_id,
|
||||||
@@ -450,45 +401,10 @@ impl ApObjectHandler for ThoughtsObjectHandler {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn on_announce_removed(&self, object_url: &Url, actor_url: &Url) -> Result<()> {
|
async fn count_local_posts(&self) -> Result<u64> {
|
||||||
let thought_uuid = object_url
|
self.repo
|
||||||
.path()
|
.count_local_notes()
|
||||||
.strip_prefix(THOUGHTS_PATH_PREFIX)
|
|
||||||
.and_then(|s| s.split('/').next())
|
|
||||||
.and_then(|s| uuid::Uuid::parse_str(s).ok());
|
|
||||||
|
|
||||||
let thought_uuid = match thought_uuid {
|
|
||||||
Some(u) => u,
|
|
||||||
None => return Ok(()),
|
|
||||||
};
|
|
||||||
|
|
||||||
let actor_user_id = self
|
|
||||||
.repo
|
|
||||||
.find_remote_actor_id(actor_url.as_str())
|
|
||||||
.await
|
.await
|
||||||
.map_err(|e| anyhow!("{e}"))?;
|
.map_err(|e| anyhow!("{e}"))
|
||||||
|
|
||||||
let actor_user_id = match actor_user_id {
|
|
||||||
Some(id) => id,
|
|
||||||
None => return Ok(()),
|
|
||||||
};
|
|
||||||
|
|
||||||
let thought_id = domain::value_objects::ThoughtId::from_uuid(thought_uuid);
|
|
||||||
let _ = self.boosts.delete(&actor_user_id, &thought_id).await;
|
|
||||||
|
|
||||||
if let Some(ep) = &self.event_publisher {
|
|
||||||
ep.publish(&domain::events::DomainEvent::BoostRemoved {
|
|
||||||
user_id: actor_user_id,
|
|
||||||
thought_id,
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.map_err(|e| anyhow!("{e}"))?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_announce_of_remote(&self, _object_url: &Url, _actor_url: &Url) -> Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,59 +4,8 @@ pub mod port;
|
|||||||
pub mod service;
|
pub mod service;
|
||||||
pub mod urls;
|
pub mod urls;
|
||||||
|
|
||||||
pub const INSTANCE_ACTOR_ID: uuid::Uuid =
|
|
||||||
uuid::Uuid::from_bytes([0, 0, 0, 0, 0, 0, 0x40, 0, 0x80, 0, 0, 0, 0, 0, 0, 0]);
|
|
||||||
|
|
||||||
pub use handler::ThoughtsObjectHandler;
|
pub use handler::ThoughtsObjectHandler;
|
||||||
pub use note::ThoughtNote;
|
pub use note::ThoughtNote;
|
||||||
pub use port::{
|
pub use port::{AcceptNoteInput, ActivityPubRepository, ActorApUrls, OutboundFederationPort, OutboxEntry};
|
||||||
AcceptNoteInput, ActivityPubRepository, ActorApUrls, OutboundFederationPort, OutboxEntry,
|
|
||||||
};
|
|
||||||
pub use service::ApFederationAdapter;
|
pub use service::ApFederationAdapter;
|
||||||
pub use urls::ThoughtsUrls;
|
pub use urls::ThoughtsUrls;
|
||||||
|
|
||||||
use domain::ports::RemoteActorConnectionRepository;
|
|
||||||
use k_ap::ActivityPubService;
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
pub struct ApServiceConfig {
|
|
||||||
pub base_url: String,
|
|
||||||
pub activity_repo: Arc<dyn k_ap::ActivityRepository>,
|
|
||||||
pub follow_repo: Arc<dyn k_ap::FollowRepository>,
|
|
||||||
pub actor_repo: Arc<dyn k_ap::ActorRepository>,
|
|
||||||
pub blocklist_repo: Arc<dyn k_ap::BlocklistRepository>,
|
|
||||||
pub user_repo: Arc<dyn k_ap::ApUserRepository>,
|
|
||||||
pub ap_handler: Arc<ThoughtsObjectHandler>,
|
|
||||||
pub connections_repo: Arc<dyn RemoteActorConnectionRepository>,
|
|
||||||
pub event_publisher: Option<Arc<dyn k_ap::data::EventPublisher>>,
|
|
||||||
pub allow_registration: bool,
|
|
||||||
pub debug: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn build_ap_service(
|
|
||||||
cfg: ApServiceConfig,
|
|
||||||
) -> (Arc<ActivityPubService>, Arc<ApFederationAdapter>) {
|
|
||||||
let mut builder = ActivityPubService::builder(cfg.base_url)
|
|
||||||
.activity_repo(cfg.activity_repo)
|
|
||||||
.follow_repo(cfg.follow_repo)
|
|
||||||
.actor_repo(cfg.actor_repo)
|
|
||||||
.blocklist_repo(cfg.blocklist_repo)
|
|
||||||
.user_repo(cfg.user_repo)
|
|
||||||
.content_reader(cfg.ap_handler.clone())
|
|
||||||
.object_handler(cfg.ap_handler)
|
|
||||||
.allow_registration(cfg.allow_registration)
|
|
||||||
.software_name("thoughts")
|
|
||||||
.debug(cfg.debug)
|
|
||||||
.signed_fetch_actor_id(INSTANCE_ACTOR_ID);
|
|
||||||
if let Some(publisher) = cfg.event_publisher {
|
|
||||||
builder = builder.event_publisher(publisher);
|
|
||||||
}
|
|
||||||
let raw = Arc::new(
|
|
||||||
builder
|
|
||||||
.build()
|
|
||||||
.await
|
|
||||||
.expect("Failed to build ActivityPubService"),
|
|
||||||
);
|
|
||||||
let adapter = Arc::new(ApFederationAdapter::new(raw.clone(), cfg.connections_repo));
|
|
||||||
(raw, adapter)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,40 +1,9 @@
|
|||||||
use chrono::{DateTime, Utc};
|
|
||||||
use k_ap::NoteType;
|
use k_ap::NoteType;
|
||||||
use k_ap::AS_PUBLIC;
|
use k_ap::AS_PUBLIC;
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use url::Url;
|
use url::Url;
|
||||||
|
|
||||||
const STANDARD_NOTE_FIELDS: &[&str] = &[
|
|
||||||
"type",
|
|
||||||
"id",
|
|
||||||
"attributedTo",
|
|
||||||
"content",
|
|
||||||
"published",
|
|
||||||
"to",
|
|
||||||
"cc",
|
|
||||||
"inReplyTo",
|
|
||||||
"sensitive",
|
|
||||||
"summary",
|
|
||||||
"tag",
|
|
||||||
"url",
|
|
||||||
"@context",
|
|
||||||
"mediaType",
|
|
||||||
];
|
|
||||||
|
|
||||||
pub fn extract_extensions(obj: &serde_json::Value) -> Option<serde_json::Value> {
|
|
||||||
let extensions: serde_json::Map<String, serde_json::Value> = obj
|
|
||||||
.as_object()?
|
|
||||||
.iter()
|
|
||||||
.filter(|(k, _)| !STANDARD_NOTE_FIELDS.contains(&k.as_str()))
|
|
||||||
.map(|(k, v)| (k.clone(), v.clone()))
|
|
||||||
.collect();
|
|
||||||
if extensions.is_empty() {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some(serde_json::Value::Object(extensions))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// AP Note representing a Thought.
|
/// AP Note representing a Thought.
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
@@ -73,21 +42,6 @@ pub struct ThoughtNoteInput {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ThoughtNote {
|
impl ThoughtNote {
|
||||||
/// Returns `(note, extensions)` if `value` is a Note object, `None` otherwise.
|
|
||||||
pub fn try_from_ap(mut value: serde_json::Value) -> Option<(Self, Option<serde_json::Value>)> {
|
|
||||||
let obj_type = value.get("type").and_then(|v| v.as_str());
|
|
||||||
if !matches!(obj_type, Some("Note" | "Article" | "Page")) {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
let extensions = extract_extensions(&value);
|
|
||||||
if let Some(obj) = value.as_object_mut() {
|
|
||||||
obj.insert("type".to_string(), serde_json::json!("Note"));
|
|
||||||
}
|
|
||||||
serde_json::from_value(value)
|
|
||||||
.ok()
|
|
||||||
.map(|note| (note, extensions))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn new_public(p: ThoughtNoteInput) -> Self {
|
pub fn new_public(p: ThoughtNoteInput) -> Self {
|
||||||
Self {
|
Self {
|
||||||
kind: Default::default(),
|
kind: Default::default(),
|
||||||
|
|||||||
@@ -1,55 +1,5 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extract_extensions_picks_up_non_standard_fields() {
|
|
||||||
let obj = serde_json::json!({
|
|
||||||
"type": "Note",
|
|
||||||
"id": "https://example.com/notes/1",
|
|
||||||
"content": "hello",
|
|
||||||
"published": "2025-01-01T00:00:00Z",
|
|
||||||
"movieTitle": "Dune",
|
|
||||||
"rating": 5,
|
|
||||||
"posterUrl": "https://example.com/poster.jpg"
|
|
||||||
});
|
|
||||||
let ext = extract_extensions(&obj).unwrap();
|
|
||||||
assert_eq!(ext["movieTitle"], "Dune");
|
|
||||||
assert_eq!(ext["rating"], 5);
|
|
||||||
assert_eq!(ext["posterUrl"], "https://example.com/poster.jpg");
|
|
||||||
assert!(ext.get("type").is_none());
|
|
||||||
assert!(ext.get("content").is_none());
|
|
||||||
assert!(ext.get("id").is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extract_extensions_returns_none_for_standard_only_note() {
|
|
||||||
let obj = serde_json::json!({
|
|
||||||
"type": "Note",
|
|
||||||
"content": "hello",
|
|
||||||
"published": "2025-01-01T00:00:00Z",
|
|
||||||
"to": ["https://www.w3.org/ns/activitystreams#Public"],
|
|
||||||
"tag": []
|
|
||||||
});
|
|
||||||
assert!(extract_extensions(&obj).is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extract_extensions_returns_none_for_non_object() {
|
|
||||||
let obj = serde_json::json!("not an object");
|
|
||||||
assert!(extract_extensions(&obj).is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn try_from_ap_returns_none_for_person() {
|
|
||||||
let person = serde_json::json!({ "type": "Person", "id": "https://example.com/users/1" });
|
|
||||||
assert!(ThoughtNote::try_from_ap(person).is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn try_from_ap_returns_none_for_missing_type() {
|
|
||||||
let obj = serde_json::json!({ "content": "hello" });
|
|
||||||
assert!(ThoughtNote::try_from_ap(obj).is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn note_serializes_with_public_audience() {
|
fn note_serializes_with_public_audience() {
|
||||||
let note = ThoughtNote::new_public(super::ThoughtNoteInput {
|
let note = ThoughtNote::new_public(super::ThoughtNoteInput {
|
||||||
|
|||||||
@@ -1,5 +1,168 @@
|
|||||||
pub use domain::ports::{
|
use async_trait::async_trait;
|
||||||
AcceptNoteInput, ActorFederationUrls as ActorApUrls,
|
use domain::{
|
||||||
FederationBroadcastPort as OutboundFederationPort,
|
errors::DomainError,
|
||||||
FederationContentRepository as ActivityPubRepository, OutboxEntry,
|
models::thought::Thought,
|
||||||
|
value_objects::{ThoughtId, UserId, Username},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
pub struct AcceptNoteInput<'a> {
|
||||||
|
pub ap_id: &'a str,
|
||||||
|
pub author_id: &'a UserId,
|
||||||
|
pub content: &'a str,
|
||||||
|
pub published: chrono::DateTime<chrono::Utc>,
|
||||||
|
pub sensitive: bool,
|
||||||
|
pub content_warning: Option<String>,
|
||||||
|
pub visibility: &'a str,
|
||||||
|
pub in_reply_to: Option<&'a str>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// AP-protocol endpoints for a locally-stored user (local or interned remote).
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ActorApUrls {
|
||||||
|
pub ap_id: String,
|
||||||
|
pub inbox_url: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A local thought ready for AP serialization, with the author's username
|
||||||
|
/// pre-joined so the handler can build AP URLs without a second query.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct OutboxEntry {
|
||||||
|
pub thought: Thought,
|
||||||
|
pub author_username: Username,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
pub trait ActivityPubRepository: Send + Sync {
|
||||||
|
// ── Outbox (local → remote) ──────────────────────────────────────
|
||||||
|
|
||||||
|
/// All public local thoughts for this actor. Used for outbox totals
|
||||||
|
/// and full-collection delivery.
|
||||||
|
async fn outbox_entries_for_actor(
|
||||||
|
&self,
|
||||||
|
user_id: &UserId,
|
||||||
|
) -> Result<Vec<OutboxEntry>, DomainError>;
|
||||||
|
|
||||||
|
/// Cursor page of public local thoughts, newest-first, before `before`.
|
||||||
|
/// Used for OrderedCollectionPage responses.
|
||||||
|
async fn outbox_page_for_actor(
|
||||||
|
&self,
|
||||||
|
user_id: &UserId,
|
||||||
|
before: Option<chrono::DateTime<chrono::Utc>>,
|
||||||
|
limit: usize,
|
||||||
|
) -> Result<Vec<OutboxEntry>, DomainError>;
|
||||||
|
|
||||||
|
// ── Remote actor resolution ──────────────────────────────────────
|
||||||
|
|
||||||
|
/// Find the local UserId for a remote actor by its AP URL.
|
||||||
|
async fn find_remote_actor_id(&self, actor_ap_url: &str)
|
||||||
|
-> Result<Option<UserId>, DomainError>;
|
||||||
|
|
||||||
|
/// Ensure a remote actor placeholder exists; create one if absent.
|
||||||
|
/// Idempotent — safe to call multiple times with the same URL.
|
||||||
|
async fn intern_remote_actor(&self, actor_ap_url: &str) -> Result<UserId, DomainError>;
|
||||||
|
|
||||||
|
/// Update display_name and avatar_url for an already-interned remote actor.
|
||||||
|
async fn update_remote_actor_display(
|
||||||
|
&self,
|
||||||
|
user_id: &UserId,
|
||||||
|
display_name: Option<&str>,
|
||||||
|
avatar_url: Option<&str>,
|
||||||
|
) -> Result<(), DomainError>;
|
||||||
|
|
||||||
|
// ── Inbox processing (remote → local) ───────────────────────────
|
||||||
|
|
||||||
|
/// Persist an incoming remote Note. Idempotent on ap_id.
|
||||||
|
|
||||||
|
async fn accept_note(&self, input: AcceptNoteInput<'_>) -> Result<ThoughtId, DomainError>;
|
||||||
|
|
||||||
|
/// Apply an Update to a previously accepted remote Note.
|
||||||
|
async fn apply_note_update(&self, ap_id: &str, new_content: &str) -> Result<(), DomainError>;
|
||||||
|
|
||||||
|
/// Remove a specific remote Note (Delete activity). Only touches
|
||||||
|
/// remotely-originated thoughts.
|
||||||
|
async fn retract_note(&self, ap_id: &str) -> Result<(), DomainError>;
|
||||||
|
|
||||||
|
/// Remove all Notes from a remote actor (actor-level Delete/Tombstone).
|
||||||
|
async fn retract_actor_notes(&self, actor_ap_url: &str) -> Result<(), DomainError>;
|
||||||
|
|
||||||
|
// ── Node-level stats ─────────────────────────────────────────────
|
||||||
|
|
||||||
|
/// Total locally-authored thought count for NodeInfo responses.
|
||||||
|
async fn count_local_notes(&self) -> Result<u64, DomainError>;
|
||||||
|
|
||||||
|
/// Return the ActivityPub object URL for a thought, if one is stored.
|
||||||
|
/// Returns None for local thoughts (caller constructs URL from base_url + thought_id).
|
||||||
|
async fn get_thought_ap_id(
|
||||||
|
&self,
|
||||||
|
thought_id: &ThoughtId,
|
||||||
|
) -> Result<Option<String>, DomainError>;
|
||||||
|
|
||||||
|
/// Return the AP actor URL and inbox URL for a user, if stored.
|
||||||
|
/// Returns None for users that have not been federated.
|
||||||
|
async fn get_actor_ap_urls(&self, user_id: &UserId)
|
||||||
|
-> Result<Option<ActorApUrls>, DomainError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
pub trait OutboundFederationPort: Send + Sync {
|
||||||
|
/// Fan out a new local Note to all accepted followers.
|
||||||
|
async fn broadcast_create(
|
||||||
|
&self,
|
||||||
|
author_user_id: &UserId,
|
||||||
|
thought: &Thought,
|
||||||
|
author_username: &str,
|
||||||
|
in_reply_to_url: Option<&str>,
|
||||||
|
) -> Result<(), DomainError>;
|
||||||
|
|
||||||
|
/// Fan out a Delete tombstone for a now-deleted local Note.
|
||||||
|
/// `thought_ap_id` is pre-constructed by the caller because the thought
|
||||||
|
/// has already been deleted from the DB when this fires.
|
||||||
|
async fn broadcast_delete(
|
||||||
|
&self,
|
||||||
|
author_user_id: &UserId,
|
||||||
|
thought_ap_id: &str,
|
||||||
|
) -> Result<(), DomainError>;
|
||||||
|
|
||||||
|
/// Fan out an Update(Note) for an edited local thought.
|
||||||
|
async fn broadcast_update(
|
||||||
|
&self,
|
||||||
|
author_user_id: &UserId,
|
||||||
|
thought: &Thought,
|
||||||
|
author_username: &str,
|
||||||
|
in_reply_to_url: Option<&str>,
|
||||||
|
) -> Result<(), DomainError>;
|
||||||
|
|
||||||
|
/// Fan out an Announce(object_ap_id) for a boost.
|
||||||
|
async fn broadcast_announce(
|
||||||
|
&self,
|
||||||
|
booster_user_id: &UserId,
|
||||||
|
object_ap_id: &str,
|
||||||
|
) -> Result<(), DomainError>;
|
||||||
|
|
||||||
|
/// Fan out an Undo(Announce) to followers when a boost is removed.
|
||||||
|
async fn broadcast_undo_announce(
|
||||||
|
&self,
|
||||||
|
booster_user_id: &UserId,
|
||||||
|
object_ap_id: &str,
|
||||||
|
) -> Result<(), DomainError>;
|
||||||
|
|
||||||
|
/// Send a Like activity to a remote thought author's inbox.
|
||||||
|
/// Only called when a LOCAL user likes a REMOTE thought (one with an ap_id).
|
||||||
|
async fn broadcast_like(
|
||||||
|
&self,
|
||||||
|
liker_user_id: &UserId,
|
||||||
|
object_ap_id: &str,
|
||||||
|
author_inbox_url: &str,
|
||||||
|
) -> Result<(), DomainError>;
|
||||||
|
|
||||||
|
/// Send Undo(Like) to a remote thought author's inbox.
|
||||||
|
async fn broadcast_undo_like(
|
||||||
|
&self,
|
||||||
|
liker_user_id: &UserId,
|
||||||
|
object_ap_id: &str,
|
||||||
|
author_inbox_url: &str,
|
||||||
|
) -> Result<(), DomainError>;
|
||||||
|
|
||||||
|
/// Fan out an Update(Actor) to all accepted followers after a profile change.
|
||||||
|
async fn broadcast_actor_update(&self, user_id: &UserId) -> Result<(), DomainError>;
|
||||||
|
}
|
||||||
|
|||||||
@@ -23,8 +23,7 @@ fn content_to_html(text: &str) -> String {
|
|||||||
.replace('&', "&")
|
.replace('&', "&")
|
||||||
.replace('<', "<")
|
.replace('<', "<")
|
||||||
.replace('>', ">")
|
.replace('>', ">")
|
||||||
.replace('"', """)
|
.replace('"', """);
|
||||||
.replace('\'', "'");
|
|
||||||
let paragraphs: Vec<&str> = escaped.split('\n').filter(|s| !s.is_empty()).collect();
|
let paragraphs: Vec<&str> = escaped.split('\n').filter(|s| !s.is_empty()).collect();
|
||||||
if paragraphs.is_empty() {
|
if paragraphs.is_empty() {
|
||||||
format!("<p>{}</p>", escaped)
|
format!("<p>{}</p>", escaped)
|
||||||
@@ -95,28 +94,9 @@ fn build_note_json(
|
|||||||
.collect();
|
.collect();
|
||||||
note["tag"] = serde_json::json!(ap_tags);
|
note["tag"] = serde_json::json!(ap_tags);
|
||||||
}
|
}
|
||||||
if let Some(ref mood) = thought.mood {
|
|
||||||
note["mood"] = serde_json::json!(mood);
|
|
||||||
}
|
|
||||||
if let Some(ref ext) = thought.note_extensions {
|
|
||||||
if let Some(obj) = ext.as_object() {
|
|
||||||
for (k, v) in obj {
|
|
||||||
note.as_object_mut().unwrap().entry(k).or_insert(v.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
note
|
note
|
||||||
}
|
}
|
||||||
|
|
||||||
fn thought_to_ap_visibility(v: &domain::models::thought::Visibility) -> k_ap::ApVisibility {
|
|
||||||
match v {
|
|
||||||
domain::models::thought::Visibility::Public => k_ap::ApVisibility::Public,
|
|
||||||
domain::models::thought::Visibility::Unlisted => k_ap::ApVisibility::Public,
|
|
||||||
domain::models::thought::Visibility::Followers => k_ap::ApVisibility::FollowersOnly,
|
|
||||||
domain::models::thought::Visibility::Direct => k_ap::ApVisibility::Private,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn k_ap_actor_to_domain(a: k_ap::RemoteActor) -> DomainRemoteActor {
|
fn k_ap_actor_to_domain(a: k_ap::RemoteActor) -> DomainRemoteActor {
|
||||||
DomainRemoteActor {
|
DomainRemoteActor {
|
||||||
url: a.url,
|
url: a.url,
|
||||||
@@ -124,14 +104,12 @@ fn k_ap_actor_to_domain(a: k_ap::RemoteActor) -> DomainRemoteActor {
|
|||||||
display_name: a.display_name,
|
display_name: a.display_name,
|
||||||
avatar_url: a.avatar_url,
|
avatar_url: a.avatar_url,
|
||||||
outbox_url: a.outbox_url,
|
outbox_url: a.outbox_url,
|
||||||
last_fetched_at: a.fetched_at.unwrap_or_else(chrono::Utc::now),
|
last_fetched_at: chrono::Utc::now(),
|
||||||
bio: a.bio,
|
bio: None,
|
||||||
banner_url: a.banner_url,
|
banner_url: None,
|
||||||
also_known_as: a.also_known_as,
|
also_known_as: None,
|
||||||
followers_url: a.followers_url,
|
followers_url: None,
|
||||||
following_url: a.following_url,
|
following_url: None,
|
||||||
inbox_url: Some(a.inbox_url),
|
|
||||||
shared_inbox_url: a.shared_inbox_url,
|
|
||||||
attachment: vec![],
|
attachment: vec![],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -168,14 +146,12 @@ async fn resolve_actor_profiles_from_urls(
|
|||||||
let display_name = resp["name"].as_str().map(|s| s.to_string());
|
let display_name = resp["name"].as_str().map(|s| s.to_string());
|
||||||
let avatar_url = resp["icon"]["url"].as_str().map(|s| s.to_string());
|
let avatar_url = resp["icon"]["url"].as_str().map(|s| s.to_string());
|
||||||
|
|
||||||
Some(
|
Some(domain::models::actor_connection_summary::ActorConnectionSummary {
|
||||||
domain::models::actor_connection_summary::ActorConnectionSummary {
|
|
||||||
url: ap_url,
|
url: ap_url,
|
||||||
handle,
|
handle,
|
||||||
display_name,
|
display_name,
|
||||||
avatar_url,
|
avatar_url,
|
||||||
},
|
})
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let futs: Vec<_> = urls.into_iter().map(fetch_one).collect();
|
let futs: Vec<_> = urls.into_iter().map(fetch_one).collect();
|
||||||
@@ -214,9 +190,7 @@ async fn webfinger_resolve_actor_url(handle: &str) -> anyhow::Result<String> {
|
|||||||
.and_then(|links| {
|
.and_then(|links| {
|
||||||
links.iter().find(|l| {
|
links.iter().find(|l| {
|
||||||
l["rel"].as_str() == Some("self")
|
l["rel"].as_str() == Some("self")
|
||||||
&& l["type"].as_str().is_some_and(|t| {
|
&& l["type"].as_str() == Some("application/activity+json")
|
||||||
t == "application/activity+json" || t.starts_with("application/ld+json")
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.and_then(|l| l["href"].as_str())
|
.and_then(|l| l["href"].as_str())
|
||||||
@@ -280,20 +254,9 @@ impl crate::port::OutboundFederationPort for ApFederationAdapter {
|
|||||||
let user_uuid = author_user_id.as_uuid();
|
let user_uuid = author_user_id.as_uuid();
|
||||||
let ap_id = self.actor_ap_id(user_uuid);
|
let ap_id = self.actor_ap_id(user_uuid);
|
||||||
let followers_url = self.actor_followers_url(user_uuid);
|
let followers_url = self.actor_followers_url(user_uuid);
|
||||||
let note = build_note_json(
|
let note = build_note_json(thought, &ap_id, &followers_url, self.base_url(), in_reply_to_url);
|
||||||
thought,
|
|
||||||
&ap_id,
|
|
||||||
&followers_url,
|
|
||||||
self.base_url(),
|
|
||||||
in_reply_to_url,
|
|
||||||
);
|
|
||||||
self.inner
|
self.inner
|
||||||
.broadcast_create_note(
|
.broadcast_create_note(user_uuid, note)
|
||||||
user_uuid,
|
|
||||||
note,
|
|
||||||
thought_to_ap_visibility(&thought.visibility),
|
|
||||||
vec![],
|
|
||||||
)
|
|
||||||
.await
|
.await
|
||||||
.map_err(|e| DomainError::Internal(e.to_string()))
|
.map_err(|e| DomainError::Internal(e.to_string()))
|
||||||
}
|
}
|
||||||
@@ -303,8 +266,8 @@ impl crate::port::OutboundFederationPort for ApFederationAdapter {
|
|||||||
author_user_id: &UserId,
|
author_user_id: &UserId,
|
||||||
thought_ap_id: &str,
|
thought_ap_id: &str,
|
||||||
) -> Result<(), DomainError> {
|
) -> Result<(), DomainError> {
|
||||||
let ap_id =
|
let ap_id = url::Url::parse(thought_ap_id)
|
||||||
url::Url::parse(thought_ap_id).map_err(|e| DomainError::Internal(e.to_string()))?;
|
.map_err(|e| DomainError::Internal(e.to_string()))?;
|
||||||
self.inner
|
self.inner
|
||||||
.broadcast_delete_to_followers(author_user_id.as_uuid(), ap_id)
|
.broadcast_delete_to_followers(author_user_id.as_uuid(), ap_id)
|
||||||
.await
|
.await
|
||||||
@@ -321,20 +284,9 @@ impl crate::port::OutboundFederationPort for ApFederationAdapter {
|
|||||||
let user_uuid = author_user_id.as_uuid();
|
let user_uuid = author_user_id.as_uuid();
|
||||||
let ap_id = self.actor_ap_id(user_uuid);
|
let ap_id = self.actor_ap_id(user_uuid);
|
||||||
let followers_url = self.actor_followers_url(user_uuid);
|
let followers_url = self.actor_followers_url(user_uuid);
|
||||||
let note = build_note_json(
|
let note = build_note_json(thought, &ap_id, &followers_url, self.base_url(), in_reply_to_url);
|
||||||
thought,
|
|
||||||
&ap_id,
|
|
||||||
&followers_url,
|
|
||||||
self.base_url(),
|
|
||||||
in_reply_to_url,
|
|
||||||
);
|
|
||||||
self.inner
|
self.inner
|
||||||
.broadcast_update_note(
|
.broadcast_update_note(user_uuid, note)
|
||||||
user_uuid,
|
|
||||||
note,
|
|
||||||
thought_to_ap_visibility(&thought.visibility),
|
|
||||||
vec![],
|
|
||||||
)
|
|
||||||
.await
|
.await
|
||||||
.map_err(|e| DomainError::Internal(e.to_string()))
|
.map_err(|e| DomainError::Internal(e.to_string()))
|
||||||
}
|
}
|
||||||
@@ -344,8 +296,8 @@ impl crate::port::OutboundFederationPort for ApFederationAdapter {
|
|||||||
booster_user_id: &UserId,
|
booster_user_id: &UserId,
|
||||||
object_ap_id: &str,
|
object_ap_id: &str,
|
||||||
) -> Result<(), DomainError> {
|
) -> Result<(), DomainError> {
|
||||||
let ap_id =
|
let ap_id = url::Url::parse(object_ap_id)
|
||||||
url::Url::parse(object_ap_id).map_err(|e| DomainError::Internal(e.to_string()))?;
|
.map_err(|e| DomainError::Internal(e.to_string()))?;
|
||||||
self.inner
|
self.inner
|
||||||
.broadcast_announce_to_followers(booster_user_id.as_uuid(), ap_id)
|
.broadcast_announce_to_followers(booster_user_id.as_uuid(), ap_id)
|
||||||
.await
|
.await
|
||||||
@@ -357,8 +309,8 @@ impl crate::port::OutboundFederationPort for ApFederationAdapter {
|
|||||||
booster_user_id: &UserId,
|
booster_user_id: &UserId,
|
||||||
object_ap_id: &str,
|
object_ap_id: &str,
|
||||||
) -> Result<(), DomainError> {
|
) -> Result<(), DomainError> {
|
||||||
let ap_id =
|
let ap_id = url::Url::parse(object_ap_id)
|
||||||
url::Url::parse(object_ap_id).map_err(|e| DomainError::Internal(e.to_string()))?;
|
.map_err(|e| DomainError::Internal(e.to_string()))?;
|
||||||
self.inner
|
self.inner
|
||||||
.broadcast_undo_announce_to_followers(booster_user_id.as_uuid(), ap_id)
|
.broadcast_undo_announce_to_followers(booster_user_id.as_uuid(), ap_id)
|
||||||
.await
|
.await
|
||||||
@@ -371,10 +323,10 @@ impl crate::port::OutboundFederationPort for ApFederationAdapter {
|
|||||||
object_ap_id: &str,
|
object_ap_id: &str,
|
||||||
author_inbox_url: &str,
|
author_inbox_url: &str,
|
||||||
) -> Result<(), DomainError> {
|
) -> Result<(), DomainError> {
|
||||||
let object =
|
let object = url::Url::parse(object_ap_id)
|
||||||
url::Url::parse(object_ap_id).map_err(|e| DomainError::Internal(e.to_string()))?;
|
.map_err(|e| DomainError::Internal(e.to_string()))?;
|
||||||
let inbox =
|
let inbox = url::Url::parse(author_inbox_url)
|
||||||
url::Url::parse(author_inbox_url).map_err(|e| DomainError::Internal(e.to_string()))?;
|
.map_err(|e| DomainError::Internal(e.to_string()))?;
|
||||||
self.inner
|
self.inner
|
||||||
.broadcast_like_to_inbox(liker_user_id.as_uuid(), object, inbox)
|
.broadcast_like_to_inbox(liker_user_id.as_uuid(), object, inbox)
|
||||||
.await
|
.await
|
||||||
@@ -387,10 +339,10 @@ impl crate::port::OutboundFederationPort for ApFederationAdapter {
|
|||||||
object_ap_id: &str,
|
object_ap_id: &str,
|
||||||
author_inbox_url: &str,
|
author_inbox_url: &str,
|
||||||
) -> Result<(), DomainError> {
|
) -> Result<(), DomainError> {
|
||||||
let object =
|
let object = url::Url::parse(object_ap_id)
|
||||||
url::Url::parse(object_ap_id).map_err(|e| DomainError::Internal(e.to_string()))?;
|
.map_err(|e| DomainError::Internal(e.to_string()))?;
|
||||||
let inbox =
|
let inbox = url::Url::parse(author_inbox_url)
|
||||||
url::Url::parse(author_inbox_url).map_err(|e| DomainError::Internal(e.to_string()))?;
|
.map_err(|e| DomainError::Internal(e.to_string()))?;
|
||||||
self.inner
|
self.inner
|
||||||
.broadcast_undo_like_to_inbox(liker_user_id.as_uuid(), object, inbox)
|
.broadcast_undo_like_to_inbox(liker_user_id.as_uuid(), object, inbox)
|
||||||
.await
|
.await
|
||||||
@@ -418,7 +370,7 @@ impl FederationSchedulerPort for ApFederationAdapter {
|
|||||||
let actor = actor_ap_url.to_string();
|
let actor = actor_ap_url.to_string();
|
||||||
let outbox = outbox_url.to_string();
|
let outbox = outbox_url.to_string();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
if let Err(e) = service.import_remote_outbox(&outbox, &actor).await {
|
if let Err(e) = service.backfill_outbox(&outbox, &actor).await {
|
||||||
tracing::warn!(actor = %actor, error = %e, "posts backfill failed");
|
tracing::warn!(actor = %actor, error = %e, "posts backfill failed");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -430,8 +382,11 @@ impl FederationSchedulerPort for ApFederationAdapter {
|
|||||||
actor_ap_url: &str,
|
actor_ap_url: &str,
|
||||||
collection_url: &str,
|
collection_url: &str,
|
||||||
connection_type: &str,
|
connection_type: &str,
|
||||||
_page: u32,
|
page: u32,
|
||||||
) -> Result<(), DomainError> {
|
) -> Result<(), DomainError> {
|
||||||
|
if page != 1 {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
let actor = actor_ap_url.to_string();
|
let actor = actor_ap_url.to_string();
|
||||||
let collection = collection_url.to_string();
|
let collection = collection_url.to_string();
|
||||||
let conn_type = connection_type.to_string();
|
let conn_type = connection_type.to_string();
|
||||||
@@ -480,7 +435,8 @@ impl FederationSchedulerPort for ApFederationAdapter {
|
|||||||
let empty = vec![];
|
let empty = vec![];
|
||||||
let items = val["orderedItems"].as_array().unwrap_or(&empty);
|
let items = val["orderedItems"].as_array().unwrap_or(&empty);
|
||||||
for item in items {
|
for item in items {
|
||||||
let actor_url = item.as_str().or_else(|| item["id"].as_str()).unwrap_or("");
|
let actor_url =
|
||||||
|
item.as_str().or_else(|| item["id"].as_str()).unwrap_or("");
|
||||||
if !actor_url.is_empty() {
|
if !actor_url.is_empty() {
|
||||||
all_urls.push(actor_url.to_string());
|
all_urls.push(actor_url.to_string());
|
||||||
}
|
}
|
||||||
@@ -533,35 +489,70 @@ impl FederationSchedulerPort for ApFederationAdapter {
|
|||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl FederationLookupPort for ApFederationAdapter {
|
impl FederationLookupPort for ApFederationAdapter {
|
||||||
async fn lookup_actor(&self, handle: &str) -> Result<DomainRemoteActor, DomainError> {
|
async fn lookup_actor(&self, handle: &str) -> Result<DomainRemoteActor, DomainError> {
|
||||||
let actor = self
|
let normalized = handle.trim_start_matches('@');
|
||||||
.inner
|
let at = normalized.rfind('@').ok_or_else(|| {
|
||||||
.lookup_actor_by_handle(handle)
|
DomainError::InvalidInput("handle must be user@domain".into())
|
||||||
|
})?;
|
||||||
|
let (user, domain_str) = (&normalized[..at], &normalized[at + 1..]);
|
||||||
|
|
||||||
|
let wf_url = format!(
|
||||||
|
"https://{}/.well-known/webfinger?resource=acct:{}@{}",
|
||||||
|
domain_str, user, domain_str
|
||||||
|
);
|
||||||
|
let wf: serde_json::Value = reqwest::Client::new()
|
||||||
|
.get(&wf_url)
|
||||||
|
.header("Accept", "application/jrd+json, application/json")
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| DomainError::ExternalService(e.to_string()))?
|
||||||
|
.json()
|
||||||
.await
|
.await
|
||||||
.map_err(|e| DomainError::ExternalService(e.to_string()))?;
|
.map_err(|e| DomainError::ExternalService(e.to_string()))?;
|
||||||
|
|
||||||
|
let self_href = wf["links"]
|
||||||
|
.as_array()
|
||||||
|
.and_then(|links| {
|
||||||
|
links.iter().find(|l| {
|
||||||
|
l["rel"].as_str() == Some("self")
|
||||||
|
&& l["type"].as_str() == Some("application/activity+json")
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.and_then(|l| l["href"].as_str())
|
||||||
|
.ok_or(DomainError::NotFound)?
|
||||||
|
.to_owned();
|
||||||
|
|
||||||
|
let actor_json: serde_json::Value = reqwest::Client::new()
|
||||||
|
.get(&self_href)
|
||||||
|
.header("Accept", "application/activity+json")
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| DomainError::ExternalService(e.to_string()))?
|
||||||
|
.json()
|
||||||
|
.await
|
||||||
|
.map_err(|e| DomainError::ExternalService(e.to_string()))?;
|
||||||
|
|
||||||
|
let ap_url = actor_json["id"].as_str().unwrap_or(&self_href).to_string();
|
||||||
|
let preferred_username =
|
||||||
|
actor_json["preferredUsername"].as_str().unwrap_or("").to_string();
|
||||||
|
let domain_part = url::Url::parse(&ap_url)
|
||||||
|
.ok()
|
||||||
|
.and_then(|u| u.host_str().map(|s| s.to_string()))
|
||||||
|
.unwrap_or_default();
|
||||||
|
let full_handle = format!("{}@{}", preferred_username, domain_part);
|
||||||
|
|
||||||
Ok(DomainRemoteActor {
|
Ok(DomainRemoteActor {
|
||||||
url: actor.ap_url.to_string(),
|
url: ap_url.clone(),
|
||||||
handle: actor.handle,
|
handle: full_handle,
|
||||||
display_name: actor.display_name,
|
display_name: actor_json["name"].as_str().map(|s| s.to_string()),
|
||||||
avatar_url: actor.avatar_url.as_ref().map(|u| u.to_string()),
|
avatar_url: actor_json["icon"]["url"].as_str().map(|s| s.to_string()),
|
||||||
outbox_url: actor.outbox_url.as_ref().map(|u| u.to_string()),
|
outbox_url: actor_json["outbox"].as_str().map(|s| s.to_string()),
|
||||||
last_fetched_at: chrono::Utc::now(),
|
last_fetched_at: chrono::Utc::now(),
|
||||||
bio: actor.bio,
|
bio: actor_json["summary"].as_str().map(|s| s.to_string()),
|
||||||
banner_url: actor.banner_url.as_ref().map(|u| u.to_string()),
|
banner_url: actor_json["image"]["url"].as_str().map(|s| s.to_string()),
|
||||||
also_known_as: actor
|
also_known_as: None,
|
||||||
.also_known_as
|
followers_url: actor_json["followers"].as_str().map(|s| s.to_string()),
|
||||||
.into_iter()
|
following_url: actor_json["following"].as_str().map(|s| s.to_string()),
|
||||||
.map(|u| u.to_string())
|
attachment: vec![],
|
||||||
.collect(),
|
|
||||||
followers_url: actor.followers_url.as_ref().map(|u| u.to_string()),
|
|
||||||
following_url: actor.following_url.as_ref().map(|u| u.to_string()),
|
|
||||||
inbox_url: None,
|
|
||||||
shared_inbox_url: None,
|
|
||||||
attachment: actor
|
|
||||||
.attachment
|
|
||||||
.into_iter()
|
|
||||||
.map(|f| (f.name, f.value))
|
|
||||||
.collect(),
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -617,19 +608,13 @@ impl FederationFetchPort for ApFederationAdapter {
|
|||||||
.await
|
.await
|
||||||
.map_err(|e| DomainError::ExternalService(e.to_string()))?;
|
.map_err(|e| DomainError::ExternalService(e.to_string()))?;
|
||||||
|
|
||||||
let first_url = base["first"]
|
let url = base["first"]
|
||||||
.as_str()
|
.as_str()
|
||||||
.map(|s| s.to_string())
|
.map(|s| s.to_string())
|
||||||
.unwrap_or_else(|| format!("{}?page=1", outbox_url));
|
.unwrap_or_else(|| format!("{}?page={}", outbox_url, page));
|
||||||
|
|
||||||
let mut current_url = first_url;
|
let resp: serde_json::Value = client
|
||||||
let mut hops = 0u32;
|
.get(&url)
|
||||||
let target_page = page.max(1);
|
|
||||||
let max_hops = 10u32;
|
|
||||||
|
|
||||||
let resp: serde_json::Value = loop {
|
|
||||||
let page_resp: serde_json::Value = client
|
|
||||||
.get(¤t_url)
|
|
||||||
.header("Accept", "application/activity+json, application/ld+json")
|
.header("Accept", "application/activity+json, application/ld+json")
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
@@ -638,16 +623,6 @@ impl FederationFetchPort for ApFederationAdapter {
|
|||||||
.await
|
.await
|
||||||
.map_err(|e| DomainError::ExternalService(e.to_string()))?;
|
.map_err(|e| DomainError::ExternalService(e.to_string()))?;
|
||||||
|
|
||||||
hops += 1;
|
|
||||||
if hops >= target_page || hops >= max_hops {
|
|
||||||
break page_resp;
|
|
||||||
}
|
|
||||||
match page_resp["next"].as_str() {
|
|
||||||
Some(next) => current_url = next.to_string(),
|
|
||||||
None => break page_resp,
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let empty = vec![];
|
let empty = vec![];
|
||||||
let items = resp["orderedItems"].as_array().unwrap_or(&empty);
|
let items = resp["orderedItems"].as_array().unwrap_or(&empty);
|
||||||
|
|
||||||
@@ -670,7 +645,8 @@ impl FederationFetchPort for ApFederationAdapter {
|
|||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
let published = DateTime::parse_from_rfc3339(note["published"].as_str()?)
|
let published =
|
||||||
|
DateTime::parse_from_rfc3339(note["published"].as_str()?)
|
||||||
.ok()?
|
.ok()?
|
||||||
.with_timezone(&chrono::Utc);
|
.with_timezone(&chrono::Utc);
|
||||||
|
|
||||||
@@ -789,17 +765,6 @@ impl FederationFollowPort for ApFederationAdapter {
|
|||||||
.map(|v| v.into_iter().map(k_ap_actor_to_domain).collect())
|
.map(|v| v.into_iter().map(k_ap_actor_to_domain).collect())
|
||||||
.map_err(|e| DomainError::ExternalService(e.to_string()))
|
.map_err(|e| DomainError::ExternalService(e.to_string()))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn broadcast_move(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
new_actor_url: url::Url,
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
self.inner
|
|
||||||
.broadcast_move(user_id.as_uuid(), new_actor_url)
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::Internal(e.to_string()))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── FederationFollowRequestPort ───────────────────────────────────────────────
|
// ── FederationFollowRequestPort ───────────────────────────────────────────────
|
||||||
@@ -860,57 +825,6 @@ impl FederationFollowRequestPort for ApFederationAdapter {
|
|||||||
.await
|
.await
|
||||||
.map_err(|e| DomainError::ExternalService(e.to_string()))
|
.map_err(|e| DomainError::ExternalService(e.to_string()))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn mark_follower_accepted(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
actor_url: &str,
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
self.inner
|
|
||||||
.mark_follower_accepted(user_id.as_uuid(), actor_url)
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::Internal(e.to_string()))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn mark_follower_rejected(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
actor_url: &str,
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
self.inner
|
|
||||||
.mark_follower_rejected(user_id.as_uuid(), actor_url)
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::Internal(e.to_string()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── FederationBlockPort ──────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl domain::ports::FederationBlockPort for ApFederationAdapter {
|
|
||||||
async fn block_remote(&self, local_user_id: &UserId, handle: &str) -> Result<(), DomainError> {
|
|
||||||
let actor_url = webfinger_resolve_actor_url(handle)
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::ExternalService(e.to_string()))?;
|
|
||||||
self.inner
|
|
||||||
.block_actor(local_user_id.as_uuid(), &actor_url)
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::ExternalService(e.to_string()))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn unblock_remote(
|
|
||||||
&self,
|
|
||||||
local_user_id: &UserId,
|
|
||||||
handle: &str,
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
let actor_url = webfinger_resolve_actor_url(handle)
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::ExternalService(e.to_string()))?;
|
|
||||||
self.inner
|
|
||||||
.unblock_actor(local_user_id.as_uuid(), &actor_url)
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::ExternalService(e.to_string()))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// FederationActionPort is a blanket supertrait; no explicit impl needed.
|
// FederationActionPort is a blanket supertrait; no explicit impl needed.
|
||||||
|
|||||||
@@ -11,24 +11,24 @@ impl ThoughtsUrls {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn user_url(&self, id: &str) -> Url {
|
pub fn user_url(&self, username: &str) -> Url {
|
||||||
Url::parse(&format!("{}/users/{}", self.base_url, id)).expect("valid URL")
|
Url::parse(&format!("{}/users/{}", self.base_url, username)).expect("valid URL")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn thought_url(&self, thought_id: uuid::Uuid) -> Url {
|
pub fn thought_url(&self, thought_id: uuid::Uuid) -> Url {
|
||||||
Url::parse(&format!("{}/thoughts/{}", self.base_url, thought_id)).expect("valid URL")
|
Url::parse(&format!("{}/thoughts/{}", self.base_url, thought_id)).expect("valid URL")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn user_inbox(&self, id: &str) -> Url {
|
pub fn user_inbox(&self, username: &str) -> Url {
|
||||||
Url::parse(&format!("{}/users/{}/inbox", self.base_url, id)).expect("valid URL")
|
Url::parse(&format!("{}/users/{}/inbox", self.base_url, username)).expect("valid URL")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn user_outbox(&self, id: &str) -> Url {
|
pub fn user_outbox(&self, username: &str) -> Url {
|
||||||
Url::parse(&format!("{}/users/{}/outbox", self.base_url, id)).expect("valid URL")
|
Url::parse(&format!("{}/users/{}/outbox", self.base_url, username)).expect("valid URL")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn user_followers(&self, id: &str) -> Url {
|
pub fn user_followers(&self, username: &str) -> Url {
|
||||||
Url::parse(&format!("{}/users/{}/followers", self.base_url, id)).expect("valid URL")
|
Url::parse(&format!("{}/users/{}/followers", self.base_url, username)).expect("valid URL")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -71,37 +71,11 @@ pub enum EventPayload {
|
|||||||
ProfileUpdated {
|
ProfileUpdated {
|
||||||
user_id: String,
|
user_id: String,
|
||||||
},
|
},
|
||||||
RemoteFollowAccepted {
|
|
||||||
local_user_id: String,
|
|
||||||
remote_actor_url: String,
|
|
||||||
},
|
|
||||||
RemoteFollowRejected {
|
|
||||||
local_user_id: String,
|
|
||||||
remote_actor_url: String,
|
|
||||||
},
|
|
||||||
ActorMoved {
|
|
||||||
user_id: String,
|
|
||||||
new_actor_url: String,
|
|
||||||
},
|
|
||||||
MentionReceived {
|
MentionReceived {
|
||||||
thought_id: String,
|
thought_id: String,
|
||||||
mentioned_user_id: String,
|
mentioned_user_id: String,
|
||||||
author_user_id: String,
|
author_user_id: String,
|
||||||
},
|
},
|
||||||
FederationDeliveryRequested {
|
|
||||||
inbox: String,
|
|
||||||
activity: serde_json::Value,
|
|
||||||
signing_actor_id: String,
|
|
||||||
},
|
|
||||||
FederationBackfillRequested {
|
|
||||||
owner_user_id: String,
|
|
||||||
follower_inbox_url: String,
|
|
||||||
},
|
|
||||||
FederationOutboundFollowAccepted {
|
|
||||||
local_user_id: String,
|
|
||||||
remote_actor_url: String,
|
|
||||||
outbox_url: Option<String>,
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EventPayload {
|
impl EventPayload {
|
||||||
@@ -123,13 +97,7 @@ impl EventPayload {
|
|||||||
Self::UserUnblocked { .. } => "users.unblocked",
|
Self::UserUnblocked { .. } => "users.unblocked",
|
||||||
Self::UserRegistered { .. } => "users.registered",
|
Self::UserRegistered { .. } => "users.registered",
|
||||||
Self::ProfileUpdated { .. } => "users.profile_updated",
|
Self::ProfileUpdated { .. } => "users.profile_updated",
|
||||||
Self::RemoteFollowAccepted { .. } => "federation.follow.accepted",
|
|
||||||
Self::RemoteFollowRejected { .. } => "federation.follow.rejected",
|
|
||||||
Self::ActorMoved { .. } => "federation.actor.moved",
|
|
||||||
Self::MentionReceived { .. } => "mentions.received",
|
Self::MentionReceived { .. } => "mentions.received",
|
||||||
Self::FederationDeliveryRequested { .. } => "federation.delivery.requested",
|
|
||||||
Self::FederationBackfillRequested { .. } => "federation.backfill.requested",
|
|
||||||
Self::FederationOutboundFollowAccepted { .. } => "federation.outbound_follow.accepted",
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -242,27 +210,6 @@ impl From<&DomainEvent> for EventPayload {
|
|||||||
DomainEvent::ProfileUpdated { user_id } => Self::ProfileUpdated {
|
DomainEvent::ProfileUpdated { user_id } => Self::ProfileUpdated {
|
||||||
user_id: user_id.to_string(),
|
user_id: user_id.to_string(),
|
||||||
},
|
},
|
||||||
DomainEvent::RemoteFollowAccepted {
|
|
||||||
local_user_id,
|
|
||||||
remote_actor_url,
|
|
||||||
} => Self::RemoteFollowAccepted {
|
|
||||||
local_user_id: local_user_id.to_string(),
|
|
||||||
remote_actor_url: remote_actor_url.clone(),
|
|
||||||
},
|
|
||||||
DomainEvent::RemoteFollowRejected {
|
|
||||||
local_user_id,
|
|
||||||
remote_actor_url,
|
|
||||||
} => Self::RemoteFollowRejected {
|
|
||||||
local_user_id: local_user_id.to_string(),
|
|
||||||
remote_actor_url: remote_actor_url.clone(),
|
|
||||||
},
|
|
||||||
DomainEvent::ActorMoved {
|
|
||||||
user_id,
|
|
||||||
new_actor_url,
|
|
||||||
} => Self::ActorMoved {
|
|
||||||
user_id: user_id.to_string(),
|
|
||||||
new_actor_url: new_actor_url.clone(),
|
|
||||||
},
|
|
||||||
DomainEvent::MentionReceived {
|
DomainEvent::MentionReceived {
|
||||||
thought_id,
|
thought_id,
|
||||||
mentioned_user_id,
|
mentioned_user_id,
|
||||||
@@ -393,27 +340,6 @@ impl TryFrom<EventPayload> for DomainEvent {
|
|||||||
EventPayload::ProfileUpdated { user_id } => DomainEvent::ProfileUpdated {
|
EventPayload::ProfileUpdated { user_id } => DomainEvent::ProfileUpdated {
|
||||||
user_id: UserId::from_uuid(parse_uuid(&user_id, "user_id")?),
|
user_id: UserId::from_uuid(parse_uuid(&user_id, "user_id")?),
|
||||||
},
|
},
|
||||||
EventPayload::RemoteFollowAccepted {
|
|
||||||
local_user_id,
|
|
||||||
remote_actor_url,
|
|
||||||
} => DomainEvent::RemoteFollowAccepted {
|
|
||||||
local_user_id: UserId::from_uuid(parse_uuid(&local_user_id, "local_user_id")?),
|
|
||||||
remote_actor_url,
|
|
||||||
},
|
|
||||||
EventPayload::RemoteFollowRejected {
|
|
||||||
local_user_id,
|
|
||||||
remote_actor_url,
|
|
||||||
} => DomainEvent::RemoteFollowRejected {
|
|
||||||
local_user_id: UserId::from_uuid(parse_uuid(&local_user_id, "local_user_id")?),
|
|
||||||
remote_actor_url,
|
|
||||||
},
|
|
||||||
EventPayload::ActorMoved {
|
|
||||||
user_id,
|
|
||||||
new_actor_url,
|
|
||||||
} => DomainEvent::ActorMoved {
|
|
||||||
user_id: UserId::from_uuid(parse_uuid(&user_id, "user_id")?),
|
|
||||||
new_actor_url,
|
|
||||||
},
|
|
||||||
EventPayload::MentionReceived {
|
EventPayload::MentionReceived {
|
||||||
thought_id,
|
thought_id,
|
||||||
mentioned_user_id,
|
mentioned_user_id,
|
||||||
@@ -426,13 +352,6 @@ impl TryFrom<EventPayload> for DomainEvent {
|
|||||||
)?),
|
)?),
|
||||||
author_user_id: UserId::from_uuid(parse_uuid(&author_user_id, "author_user_id")?),
|
author_user_id: UserId::from_uuid(parse_uuid(&author_user_id, "author_user_id")?),
|
||||||
},
|
},
|
||||||
EventPayload::FederationDeliveryRequested { .. }
|
|
||||||
| EventPayload::FederationBackfillRequested { .. }
|
|
||||||
| EventPayload::FederationOutboundFollowAccepted { .. } => {
|
|
||||||
return Err(DomainError::Internal(
|
|
||||||
"federation infrastructure event — not a domain event".into(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,13 +3,11 @@ use async_trait::async_trait;
|
|||||||
use domain::value_objects::{ThoughtId, UserId};
|
use domain::value_objects::{ThoughtId, UserId};
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
type CallLog = Arc<Mutex<Vec<(String, Vec<u8>)>>>;
|
|
||||||
|
|
||||||
struct SpyTransport {
|
struct SpyTransport {
|
||||||
calls: CallLog,
|
calls: Arc<Mutex<Vec<(String, Vec<u8>)>>>,
|
||||||
}
|
}
|
||||||
impl SpyTransport {
|
impl SpyTransport {
|
||||||
fn new() -> (Self, CallLog) {
|
fn new() -> (Self, Arc<Mutex<Vec<(String, Vec<u8>)>>>) {
|
||||||
let calls = Arc::new(Mutex::new(vec![]));
|
let calls = Arc::new(Mutex::new(vec![]));
|
||||||
(
|
(
|
||||||
Self {
|
Self {
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
use super::*;
|
||||||
use domain::{
|
use domain::{
|
||||||
events::DomainEvent,
|
events::DomainEvent,
|
||||||
value_objects::{LikeId, ThoughtId, UserId},
|
value_objects::{LikeId, ThoughtId, UserId},
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ version = "0.1.0"
|
|||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
k-ap = { version = "0.4.4", registry = "gitea" }
|
k-ap = { git = "https://git.gabrielkaszewski.dev/GKaszewski/k-ap.git", tag = "v0.1.2" }
|
||||||
sqlx = { workspace = true }
|
sqlx = { workspace = true }
|
||||||
uuid = { workspace = true }
|
uuid = { workspace = true }
|
||||||
chrono = { workspace = true }
|
chrono = { workspace = true }
|
||||||
@@ -12,7 +12,6 @@ tracing = { workspace = true }
|
|||||||
async-trait = { workspace = true }
|
async-trait = { workspace = true }
|
||||||
anyhow = { workspace = true }
|
anyhow = { workspace = true }
|
||||||
url = { workspace = true }
|
url = { workspace = true }
|
||||||
serde_json = { workspace = true }
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tokio = { workspace = true, features = ["full"] }
|
tokio = { workspace = true, features = ["full"] }
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
../postgres/migrations
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -10,7 +10,6 @@ sqlx = { workspace = true }
|
|||||||
uuid = { workspace = true }
|
uuid = { workspace = true }
|
||||||
chrono = { workspace = true }
|
chrono = { workspace = true }
|
||||||
async-trait = { workspace = true }
|
async-trait = { workspace = true }
|
||||||
serde_json = { workspace = true }
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tokio = { workspace = true, features = ["full"] }
|
tokio = { workspace = true, features = ["full"] }
|
||||||
|
|||||||
@@ -9,9 +9,9 @@ use domain::{
|
|||||||
user::User,
|
user::User,
|
||||||
},
|
},
|
||||||
ports::SearchPort,
|
ports::SearchPort,
|
||||||
value_objects::{Content, ThoughtId, UserId},
|
value_objects::{Content, Email, PasswordHash, ThoughtId, UserId, Username},
|
||||||
};
|
};
|
||||||
use postgres::user::USER_SELECT;
|
use postgres::user::{UserRow, USER_SELECT};
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
|
|
||||||
pub struct PgSearchRepository {
|
pub struct PgSearchRepository {
|
||||||
@@ -29,17 +29,24 @@ struct FeedRow {
|
|||||||
t_user_id: uuid::Uuid,
|
t_user_id: uuid::Uuid,
|
||||||
content: String,
|
content: String,
|
||||||
in_reply_to_id: Option<uuid::Uuid>,
|
in_reply_to_id: Option<uuid::Uuid>,
|
||||||
in_reply_to_url: Option<String>,
|
|
||||||
visibility: String,
|
visibility: String,
|
||||||
content_warning: Option<String>,
|
content_warning: Option<String>,
|
||||||
sensitive: bool,
|
sensitive: bool,
|
||||||
t_local: bool,
|
t_local: bool,
|
||||||
thought_created_at: DateTime<Utc>,
|
thought_created_at: DateTime<Utc>,
|
||||||
thought_updated_at: Option<DateTime<Utc>>,
|
updated_at: Option<DateTime<Utc>>,
|
||||||
note_extensions: Option<serde_json::Value>,
|
author_id: uuid::Uuid,
|
||||||
mood: Option<String>,
|
username: String,
|
||||||
#[sqlx(flatten)]
|
email: String,
|
||||||
author: postgres::user::UserRow,
|
password_hash: String,
|
||||||
|
display_name: Option<String>,
|
||||||
|
bio: Option<String>,
|
||||||
|
avatar_url: Option<String>,
|
||||||
|
header_url: Option<String>,
|
||||||
|
custom_css: Option<String>,
|
||||||
|
author_local: bool,
|
||||||
|
author_created_at: DateTime<Utc>,
|
||||||
|
author_updated_at: DateTime<Utc>,
|
||||||
like_count: i64,
|
like_count: i64,
|
||||||
boost_count: i64,
|
boost_count: i64,
|
||||||
reply_count: i64,
|
reply_count: i64,
|
||||||
@@ -58,13 +65,13 @@ fn feed_select(viewer: Option<uuid::Uuid>) -> String {
|
|||||||
format!(
|
format!(
|
||||||
"\n SELECT\n\
|
"\n SELECT\n\
|
||||||
t.id AS thought_id, t.user_id AS t_user_id, t.content,\n\
|
t.id AS thought_id, t.user_id AS t_user_id, t.content,\n\
|
||||||
t.in_reply_to_id, t.in_reply_to_url,\n\
|
t.in_reply_to_id,\n\
|
||||||
t.visibility, t.content_warning, t.sensitive, t.local AS t_local,\n\
|
t.visibility, t.content_warning, t.sensitive, t.local AS t_local,\n\
|
||||||
t.created_at AS thought_created_at, t.updated_at AS thought_updated_at, t.note_extensions, t.mood,\n\
|
t.created_at AS thought_created_at, t.updated_at,\n\
|
||||||
u.id, u.username, u.email, u.password_hash,\n\
|
u.id AS author_id, u.username, u.email, u.password_hash,\n\
|
||||||
u.display_name, u.bio, u.avatar_url, u.header_url, u.custom_css, u.profile_fields, u.custom_moods,\n\
|
u.display_name, u.bio, u.avatar_url, u.header_url, u.custom_css,\n\
|
||||||
u.local,\n\
|
u.local AS author_local,\n\
|
||||||
u.created_at, u.updated_at,\n\
|
u.created_at AS author_created_at, u.updated_at AS author_updated_at,\n\
|
||||||
(SELECT COUNT(*) FROM likes l WHERE l.thought_id=t.id) AS like_count,\n\
|
(SELECT COUNT(*) FROM likes l WHERE l.thought_id=t.id) AS like_count,\n\
|
||||||
(SELECT COUNT(*) FROM boosts b WHERE b.thought_id=t.id) AS boost_count,\n\
|
(SELECT COUNT(*) FROM boosts b WHERE b.thought_id=t.id) AS boost_count,\n\
|
||||||
(SELECT COUNT(*) FROM thoughts r WHERE r.in_reply_to_id=t.id) AS reply_count,\n\
|
(SELECT COUNT(*) FROM thoughts r WHERE r.in_reply_to_id=t.id) AS reply_count,\n\
|
||||||
@@ -79,17 +86,27 @@ fn row_to_entry(r: FeedRow, viewer: Option<uuid::Uuid>) -> Result<FeedEntry, Dom
|
|||||||
user_id: UserId::from_uuid(r.t_user_id),
|
user_id: UserId::from_uuid(r.t_user_id),
|
||||||
content: Content::new_remote(r.content),
|
content: Content::new_remote(r.content),
|
||||||
in_reply_to_id: r.in_reply_to_id.map(ThoughtId::from_uuid),
|
in_reply_to_id: r.in_reply_to_id.map(ThoughtId::from_uuid),
|
||||||
in_reply_to_url: r.in_reply_to_url,
|
|
||||||
visibility: Visibility::from_db_str(&r.visibility)?,
|
visibility: Visibility::from_db_str(&r.visibility)?,
|
||||||
content_warning: r.content_warning,
|
content_warning: r.content_warning,
|
||||||
sensitive: r.sensitive,
|
sensitive: r.sensitive,
|
||||||
local: r.t_local,
|
local: r.t_local,
|
||||||
created_at: r.thought_created_at,
|
created_at: r.thought_created_at,
|
||||||
updated_at: r.thought_updated_at,
|
updated_at: r.updated_at,
|
||||||
note_extensions: r.note_extensions,
|
};
|
||||||
mood: r.mood,
|
let author = User {
|
||||||
|
id: UserId::from_uuid(r.author_id),
|
||||||
|
username: Username::from_trusted(r.username),
|
||||||
|
email: Email::from_trusted(r.email),
|
||||||
|
password_hash: PasswordHash(r.password_hash),
|
||||||
|
display_name: r.display_name,
|
||||||
|
bio: r.bio,
|
||||||
|
avatar_url: r.avatar_url,
|
||||||
|
header_url: r.header_url,
|
||||||
|
custom_css: r.custom_css,
|
||||||
|
local: r.author_local,
|
||||||
|
created_at: r.author_created_at,
|
||||||
|
updated_at: r.author_updated_at,
|
||||||
};
|
};
|
||||||
let author = User::from(r.author);
|
|
||||||
Ok(FeedEntry {
|
Ok(FeedEntry {
|
||||||
thought,
|
thought,
|
||||||
author,
|
author,
|
||||||
@@ -170,7 +187,7 @@ impl SearchPort for PgSearchRepository {
|
|||||||
ORDER BY similarity(username || ' ' || COALESCE(display_name,''), $1) DESC
|
ORDER BY similarity(username || ' ' || COALESCE(display_name,''), $1) DESC
|
||||||
LIMIT $2 OFFSET $3"
|
LIMIT $2 OFFSET $3"
|
||||||
);
|
);
|
||||||
let rows = sqlx::query_as::<_, postgres::user::UserRow>(&sql)
|
let rows = sqlx::query_as::<_, UserRow>(&sql)
|
||||||
.bind(query)
|
.bind(query)
|
||||||
.bind(page.limit())
|
.bind(page.limit())
|
||||||
.bind(page.offset())
|
.bind(page.offset())
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use domain::{
|
|||||||
user::User,
|
user::User,
|
||||||
},
|
},
|
||||||
ports::{SearchPort, ThoughtRepository, UserWriter},
|
ports::{SearchPort, ThoughtRepository, UserWriter},
|
||||||
value_objects::{Content, Email, PasswordHash, ThoughtId, UserId, Username},
|
value_objects::*,
|
||||||
};
|
};
|
||||||
|
|
||||||
async fn seed_thought(pool: &sqlx::PgPool, username: &str, content: &str) -> (User, Thought) {
|
async fn seed_thought(pool: &sqlx::PgPool, username: &str, content: &str) -> (User, Thought) {
|
||||||
@@ -27,7 +27,6 @@ async fn seed_thought(pool: &sqlx::PgPool, username: &str, content: &str) -> (Us
|
|||||||
visibility: Visibility::Public,
|
visibility: Visibility::Public,
|
||||||
content_warning: None,
|
content_warning: None,
|
||||||
sensitive: false,
|
sensitive: false,
|
||||||
mood: None,
|
|
||||||
});
|
});
|
||||||
trepo.save(&t).await.unwrap();
|
trepo.save(&t).await.unwrap();
|
||||||
(u, t)
|
(u, t)
|
||||||
@@ -103,9 +102,9 @@ async fn search_thoughts_returns_empty_for_no_match(pool: sqlx::PgPool) {
|
|||||||
#[sqlx::test(migrations = "../postgres/migrations")]
|
#[sqlx::test(migrations = "../postgres/migrations")]
|
||||||
async fn search_thoughts_viewer_context(pool: sqlx::PgPool) {
|
async fn search_thoughts_viewer_context(pool: sqlx::PgPool) {
|
||||||
use domain::models::social::Like;
|
use domain::models::social::Like;
|
||||||
use domain::ports::LikeRepository;
|
use domain::ports::{LikeRepository, UserWriter};
|
||||||
use domain::value_objects::LikeId;
|
use domain::value_objects::LikeId;
|
||||||
use postgres::like::PgLikeRepository;
|
use postgres::{like::PgLikeRepository, user::PgUserRepository};
|
||||||
|
|
||||||
let (alice, thought) = seed_thought(&pool, "alice", "hello world").await;
|
let (alice, thought) = seed_thought(&pool, "alice", "hello world").await;
|
||||||
|
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
ALTER TABLE thoughts ADD COLUMN note_extensions JSONB;
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
ALTER TABLE users ADD COLUMN IF NOT EXISTS also_known_as TEXT;
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
CREATE TABLE IF NOT EXISTS federation_processed_activities (
|
|
||||||
activity_id TEXT PRIMARY KEY,
|
|
||||||
processed_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_fed_processed_activities_at
|
|
||||||
ON federation_processed_activities(processed_at);
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
ALTER TABLE remote_actors
|
|
||||||
ADD COLUMN IF NOT EXISTS bio TEXT,
|
|
||||||
ADD COLUMN IF NOT EXISTS banner_url TEXT,
|
|
||||||
ADD COLUMN IF NOT EXISTS followers_url TEXT,
|
|
||||||
ADD COLUMN IF NOT EXISTS following_url TEXT,
|
|
||||||
ADD COLUMN IF NOT EXISTS also_known_as TEXT[];
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
-- Indexes for feed engagement counts and sorting.
|
|
||||||
-- likes and boosts are joined/counted per thought on every feed query.
|
|
||||||
-- thoughts(in_reply_to_id) is scanned for reply_count.
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_likes_thought_id ON likes(thought_id);
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_boosts_thought_id ON boosts(thought_id);
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_thoughts_in_reply_to_id ON thoughts(in_reply_to_id) WHERE in_reply_to_id IS NOT NULL;
|
|
||||||
|
|
||||||
-- Viewer-context lookups: "did I like/boost this?"
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_likes_user_thought ON likes(user_id, thought_id);
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_boosts_user_thought ON boosts(user_id, thought_id);
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
ALTER TABLE users ALTER COLUMN username TYPE VARCHAR(255);
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
ALTER TABLE federation_following
|
|
||||||
ADD COLUMN IF NOT EXISTS status TEXT NOT NULL DEFAULT 'accepted';
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
ALTER TABLE remote_actors ADD COLUMN IF NOT EXISTS attachment JSONB DEFAULT '[]'::jsonb;
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
ALTER TABLE users ADD COLUMN IF NOT EXISTS profile_fields JSONB DEFAULT '[]'::jsonb;
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
ALTER TABLE thoughts ADD COLUMN IF NOT EXISTS mood VARCHAR(64);
|
|
||||||
ALTER TABLE users ADD COLUMN IF NOT EXISTS custom_moods JSONB DEFAULT '[]'::jsonb;
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
INSERT INTO users (id, username, email, password_hash, display_name, bio)
|
|
||||||
VALUES (
|
|
||||||
'00000000-0000-4000-8000-000000000000',
|
|
||||||
'instance',
|
|
||||||
'noreply@instance.invalid',
|
|
||||||
'!service-actor-no-login',
|
|
||||||
NULL,
|
|
||||||
NULL
|
|
||||||
)
|
|
||||||
ON CONFLICT (id) DO NOTHING;
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
use crate::db_error::IntoDbResult;
|
use crate::db_error::IntoDbResult;
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
|
|
||||||
const MAX_REMOTE_CONTENT_CHARS: usize = 5000;
|
const MAX_REMOTE_CONTENT_CHARS: usize = 500;
|
||||||
const THOUGHTS_PATH_PREFIX: &str = "/thoughts/";
|
const THOUGHTS_PATH_PREFIX: &str = "/thoughts/";
|
||||||
use chrono::{DateTime, Utc};
|
use chrono::{DateTime, Utc};
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
@@ -13,42 +13,6 @@ use domain::{
|
|||||||
value_objects::{Content, ThoughtId, UserId, Username},
|
value_objects::{Content, ThoughtId, UserId, Username},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(sqlx::FromRow)]
|
|
||||||
struct OutboxRow {
|
|
||||||
id: uuid::Uuid,
|
|
||||||
user_id: uuid::Uuid,
|
|
||||||
content: String,
|
|
||||||
created_at: DateTime<Utc>,
|
|
||||||
in_reply_to_id: Option<uuid::Uuid>,
|
|
||||||
content_warning: Option<String>,
|
|
||||||
sensitive: bool,
|
|
||||||
username: String,
|
|
||||||
updated_at: Option<DateTime<Utc>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl OutboxRow {
|
|
||||||
fn into_entry(self) -> OutboxEntry {
|
|
||||||
OutboxEntry {
|
|
||||||
thought: Thought {
|
|
||||||
id: ThoughtId::from_uuid(self.id),
|
|
||||||
user_id: UserId::from_uuid(self.user_id),
|
|
||||||
content: Content::new_remote(self.content),
|
|
||||||
in_reply_to_id: self.in_reply_to_id.map(ThoughtId::from_uuid),
|
|
||||||
in_reply_to_url: None,
|
|
||||||
visibility: Visibility::Public,
|
|
||||||
content_warning: self.content_warning,
|
|
||||||
sensitive: self.sensitive,
|
|
||||||
local: true,
|
|
||||||
created_at: self.created_at,
|
|
||||||
updated_at: self.updated_at,
|
|
||||||
note_extensions: None,
|
|
||||||
mood: None,
|
|
||||||
},
|
|
||||||
author_username: Username::from_trusted(self.username),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct PgActivityPubRepository {
|
pub struct PgActivityPubRepository {
|
||||||
pool: PgPool,
|
pool: PgPool,
|
||||||
}
|
}
|
||||||
@@ -65,7 +29,19 @@ impl ActivityPubRepository for PgActivityPubRepository {
|
|||||||
&self,
|
&self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
) -> Result<Vec<OutboxEntry>, DomainError> {
|
) -> Result<Vec<OutboxEntry>, DomainError> {
|
||||||
sqlx::query_as::<_, OutboxRow>(
|
#[derive(sqlx::FromRow)]
|
||||||
|
struct Row {
|
||||||
|
id: uuid::Uuid,
|
||||||
|
user_id: uuid::Uuid,
|
||||||
|
content: String,
|
||||||
|
created_at: DateTime<Utc>,
|
||||||
|
in_reply_to_id: Option<uuid::Uuid>,
|
||||||
|
content_warning: Option<String>,
|
||||||
|
sensitive: bool,
|
||||||
|
username: String,
|
||||||
|
updated_at: Option<DateTime<Utc>>,
|
||||||
|
}
|
||||||
|
sqlx::query_as::<_, Row>(
|
||||||
"SELECT t.id, t.user_id, t.content, t.created_at, t.in_reply_to_id, t.content_warning, t.sensitive, u.username, t.updated_at
|
"SELECT t.id, t.user_id, t.content, t.created_at, t.in_reply_to_id, t.content_warning, t.sensitive, u.username, t.updated_at
|
||||||
FROM thoughts t JOIN users u ON u.id=t.user_id
|
FROM thoughts t JOIN users u ON u.id=t.user_id
|
||||||
WHERE t.user_id=$1 AND t.local=true AND t.visibility='public'
|
WHERE t.user_id=$1 AND t.local=true AND t.visibility='public'
|
||||||
@@ -75,7 +51,25 @@ impl ActivityPubRepository for PgActivityPubRepository {
|
|||||||
.fetch_all(&self.pool)
|
.fetch_all(&self.pool)
|
||||||
.await
|
.await
|
||||||
.into_domain()
|
.into_domain()
|
||||||
.map(|rows| rows.into_iter().map(OutboxRow::into_entry).collect())
|
.map(|rows| {
|
||||||
|
rows.into_iter()
|
||||||
|
.map(|r| OutboxEntry {
|
||||||
|
thought: Thought {
|
||||||
|
id: ThoughtId::from_uuid(r.id),
|
||||||
|
user_id: UserId::from_uuid(r.user_id),
|
||||||
|
content: Content::new_remote(r.content),
|
||||||
|
in_reply_to_id: r.in_reply_to_id.map(ThoughtId::from_uuid),
|
||||||
|
visibility: Visibility::Public,
|
||||||
|
content_warning: r.content_warning,
|
||||||
|
sensitive: r.sensitive,
|
||||||
|
local: true,
|
||||||
|
created_at: r.created_at,
|
||||||
|
updated_at: r.updated_at,
|
||||||
|
},
|
||||||
|
author_username: Username::from_trusted(r.username),
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn outbox_page_for_actor(
|
async fn outbox_page_for_actor(
|
||||||
@@ -84,8 +78,20 @@ impl ActivityPubRepository for PgActivityPubRepository {
|
|||||||
before: Option<DateTime<Utc>>,
|
before: Option<DateTime<Utc>>,
|
||||||
limit: usize,
|
limit: usize,
|
||||||
) -> Result<Vec<OutboxEntry>, DomainError> {
|
) -> Result<Vec<OutboxEntry>, DomainError> {
|
||||||
|
#[derive(sqlx::FromRow)]
|
||||||
|
struct Row {
|
||||||
|
id: uuid::Uuid,
|
||||||
|
user_id: uuid::Uuid,
|
||||||
|
content: String,
|
||||||
|
created_at: DateTime<Utc>,
|
||||||
|
in_reply_to_id: Option<uuid::Uuid>,
|
||||||
|
content_warning: Option<String>,
|
||||||
|
sensitive: bool,
|
||||||
|
username: String,
|
||||||
|
updated_at: Option<DateTime<Utc>>,
|
||||||
|
}
|
||||||
let rows = if let Some(before) = before {
|
let rows = if let Some(before) = before {
|
||||||
sqlx::query_as::<_, OutboxRow>(
|
sqlx::query_as::<_, Row>(
|
||||||
"SELECT t.id, t.user_id, t.content, t.created_at, t.in_reply_to_id, t.content_warning, t.sensitive, u.username, t.updated_at
|
"SELECT t.id, t.user_id, t.content, t.created_at, t.in_reply_to_id, t.content_warning, t.sensitive, u.username, t.updated_at
|
||||||
FROM thoughts t JOIN users u ON u.id=t.user_id
|
FROM thoughts t JOIN users u ON u.id=t.user_id
|
||||||
WHERE t.user_id=$1 AND t.local=true AND t.visibility='public' AND t.created_at < $2
|
WHERE t.user_id=$1 AND t.local=true AND t.visibility='public' AND t.created_at < $2
|
||||||
@@ -97,7 +103,7 @@ impl ActivityPubRepository for PgActivityPubRepository {
|
|||||||
.fetch_all(&self.pool)
|
.fetch_all(&self.pool)
|
||||||
.await
|
.await
|
||||||
} else {
|
} else {
|
||||||
sqlx::query_as::<_, OutboxRow>(
|
sqlx::query_as::<_, Row>(
|
||||||
"SELECT t.id, t.user_id, t.content, t.created_at, t.in_reply_to_id, t.content_warning, t.sensitive, u.username, t.updated_at
|
"SELECT t.id, t.user_id, t.content, t.created_at, t.in_reply_to_id, t.content_warning, t.sensitive, u.username, t.updated_at
|
||||||
FROM thoughts t JOIN users u ON u.id=t.user_id
|
FROM thoughts t JOIN users u ON u.id=t.user_id
|
||||||
WHERE t.user_id=$1 AND t.local=true AND t.visibility='public'
|
WHERE t.user_id=$1 AND t.local=true AND t.visibility='public'
|
||||||
@@ -110,7 +116,24 @@ impl ActivityPubRepository for PgActivityPubRepository {
|
|||||||
}
|
}
|
||||||
.into_domain()?;
|
.into_domain()?;
|
||||||
|
|
||||||
Ok(rows.into_iter().map(OutboxRow::into_entry).collect())
|
Ok(rows
|
||||||
|
.into_iter()
|
||||||
|
.map(|r| OutboxEntry {
|
||||||
|
thought: Thought {
|
||||||
|
id: ThoughtId::from_uuid(r.id),
|
||||||
|
user_id: UserId::from_uuid(r.user_id),
|
||||||
|
content: Content::new_remote(r.content),
|
||||||
|
in_reply_to_id: r.in_reply_to_id.map(ThoughtId::from_uuid),
|
||||||
|
visibility: Visibility::Public,
|
||||||
|
content_warning: r.content_warning,
|
||||||
|
sensitive: r.sensitive,
|
||||||
|
local: true,
|
||||||
|
created_at: r.created_at,
|
||||||
|
updated_at: r.updated_at,
|
||||||
|
},
|
||||||
|
author_username: Username::from_trusted(r.username),
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn find_remote_actor_id(
|
async fn find_remote_actor_id(
|
||||||
@@ -130,28 +153,24 @@ impl ActivityPubRepository for PgActivityPubRepository {
|
|||||||
return Ok(id);
|
return Ok(id);
|
||||||
}
|
}
|
||||||
let new_id = uuid::Uuid::new_v4();
|
let new_id = uuid::Uuid::new_v4();
|
||||||
let parsed = url::Url::parse(actor_ap_url).ok();
|
// Use the last path segment as username (e.g. /users/alice → "alice").
|
||||||
let domain_str = parsed
|
// Falls back to a random short id for long segments (e.g. UUID-based actor URLs).
|
||||||
.as_ref()
|
// username column is VARCHAR(32).
|
||||||
.and_then(|u| u.host_str().map(|s| s.to_string()))
|
let last_seg = url::Url::parse(actor_ap_url)
|
||||||
.unwrap_or_default();
|
.ok()
|
||||||
let last_seg = parsed
|
|
||||||
.and_then(|u| {
|
.and_then(|u| {
|
||||||
u.path_segments()
|
u.path_segments()
|
||||||
.and_then(|mut s| s.next_back().map(|s| s.to_string()))
|
.and_then(|mut s| s.next_back().map(|s| s.to_string()))
|
||||||
})
|
})
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
let handle = if last_seg.is_empty() || domain_str.is_empty() {
|
let handle = if last_seg.is_empty() {
|
||||||
format!("r_{}", &new_id.to_string()[..13])
|
format!("remote_{}", &new_id.to_string()[..13])
|
||||||
|
} else if last_seg.len() <= 32 {
|
||||||
|
last_seg
|
||||||
} else {
|
} else {
|
||||||
let candidate = format!("{}@{}", last_seg, domain_str);
|
format!("remote_{}", &new_id.to_string()[..13])
|
||||||
if candidate.len() <= 255 {
|
|
||||||
candidate
|
|
||||||
} else {
|
|
||||||
format!("r_{}", &new_id.to_string()[..13])
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
let result = sqlx::query(
|
sqlx::query(
|
||||||
"INSERT INTO users(id,username,email,password_hash,local,ap_id,created_at,updated_at)
|
"INSERT INTO users(id,username,email,password_hash,local,ap_id,created_at,updated_at)
|
||||||
VALUES($1,$2,$3,'',false,$4,NOW(),NOW()) ON CONFLICT(ap_id) DO NOTHING",
|
VALUES($1,$2,$3,'',false,$4,NOW(),NOW()) ON CONFLICT(ap_id) DO NOTHING",
|
||||||
)
|
)
|
||||||
@@ -160,24 +179,9 @@ impl ActivityPubRepository for PgActivityPubRepository {
|
|||||||
.bind(format!("{}@remote", new_id))
|
.bind(format!("{}@remote", new_id))
|
||||||
.bind(actor_ap_url)
|
.bind(actor_ap_url)
|
||||||
.execute(&self.pool)
|
.execute(&self.pool)
|
||||||
.await;
|
|
||||||
|
|
||||||
if result.is_err() {
|
|
||||||
let fallback = format!("r_{}", &new_id.to_string()[..13]);
|
|
||||||
let new_id2 = uuid::Uuid::new_v4();
|
|
||||||
sqlx::query(
|
|
||||||
"INSERT INTO users(id,username,email,password_hash,local,ap_id,created_at,updated_at)
|
|
||||||
VALUES($1,$2,$3,'',false,$4,NOW(),NOW()) ON CONFLICT(ap_id) DO NOTHING",
|
|
||||||
)
|
|
||||||
.bind(new_id2)
|
|
||||||
.bind(&fallback)
|
|
||||||
.bind(format!("{}@remote", new_id2))
|
|
||||||
.bind(actor_ap_url)
|
|
||||||
.execute(&self.pool)
|
|
||||||
.await
|
.await
|
||||||
.into_domain()?;
|
.into_domain()?;
|
||||||
}
|
// Re-fetch to get whichever id won the race
|
||||||
|
|
||||||
self.find_remote_actor_id(actor_ap_url)
|
self.find_remote_actor_id(actor_ap_url)
|
||||||
.await?
|
.await?
|
||||||
.ok_or_else(|| {
|
.ok_or_else(|| {
|
||||||
@@ -216,36 +220,24 @@ impl ActivityPubRepository for PgActivityPubRepository {
|
|||||||
content_warning,
|
content_warning,
|
||||||
visibility,
|
visibility,
|
||||||
in_reply_to,
|
in_reply_to,
|
||||||
note_extensions,
|
|
||||||
} = input;
|
} = input;
|
||||||
let capped: String = content.chars().take(MAX_REMOTE_CONTENT_CHARS).collect();
|
let capped: String = content.chars().take(MAX_REMOTE_CONTENT_CHARS).collect();
|
||||||
let (in_reply_to_id, in_reply_to_url) = match in_reply_to {
|
let (in_reply_to_id, in_reply_to_url) = match in_reply_to {
|
||||||
Some(url) => {
|
Some(url) => {
|
||||||
// Fast path: local thought URL contains the UUID directly.
|
// If the parent is a local thought, extract its UUID for in_reply_to_id.
|
||||||
let local_uuid = url::Url::parse(url).ok().and_then(|u| {
|
let local_uuid = url::Url::parse(url).ok().and_then(|u| {
|
||||||
u.path()
|
u.path()
|
||||||
.strip_prefix(THOUGHTS_PATH_PREFIX)
|
.strip_prefix(THOUGHTS_PATH_PREFIX)
|
||||||
.and_then(|s| s.split('/').next())
|
.and_then(|s| s.split('/').next())
|
||||||
.and_then(|s| uuid::Uuid::parse_str(s).ok())
|
.and_then(|s| uuid::Uuid::parse_str(s).ok())
|
||||||
});
|
});
|
||||||
// Slow path: remote parent — look up by ap_id so remote-to-remote
|
(local_uuid, Some(url.to_string()))
|
||||||
// replies are threaded correctly in the feed.
|
|
||||||
let resolved = if local_uuid.is_some() {
|
|
||||||
local_uuid
|
|
||||||
} else {
|
|
||||||
sqlx::query_scalar::<_, uuid::Uuid>("SELECT id FROM thoughts WHERE ap_id=$1")
|
|
||||||
.bind(url)
|
|
||||||
.fetch_optional(&self.pool)
|
|
||||||
.await
|
|
||||||
.into_domain()?
|
|
||||||
};
|
|
||||||
(resolved, Some(url.to_string()))
|
|
||||||
}
|
}
|
||||||
None => (None, None),
|
None => (None, None),
|
||||||
};
|
};
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"INSERT INTO thoughts(id,user_id,content,ap_id,visibility,sensitive,local,content_warning,created_at,in_reply_to_id,in_reply_to_url,note_extensions)
|
"INSERT INTO thoughts(id,user_id,content,ap_id,visibility,sensitive,local,content_warning,created_at,in_reply_to_id,in_reply_to_url)
|
||||||
VALUES($1,$2,$3,$4,$8,$5,false,$6,$7,$9,$10,$11) ON CONFLICT(ap_id) DO NOTHING",
|
VALUES($1,$2,$3,$4,$8,$5,false,$6,$7,$9,$10) ON CONFLICT(ap_id) DO NOTHING",
|
||||||
)
|
)
|
||||||
.bind(uuid::Uuid::new_v4())
|
.bind(uuid::Uuid::new_v4())
|
||||||
.bind(author_id.as_uuid())
|
.bind(author_id.as_uuid())
|
||||||
@@ -257,7 +249,6 @@ impl ActivityPubRepository for PgActivityPubRepository {
|
|||||||
.bind(visibility)
|
.bind(visibility)
|
||||||
.bind(in_reply_to_id)
|
.bind(in_reply_to_id)
|
||||||
.bind(&in_reply_to_url)
|
.bind(&in_reply_to_url)
|
||||||
.bind(note_extensions)
|
|
||||||
.execute(&self.pool)
|
.execute(&self.pool)
|
||||||
.await
|
.await
|
||||||
.into_domain()?;
|
.into_domain()?;
|
||||||
@@ -271,19 +262,13 @@ impl ActivityPubRepository for PgActivityPubRepository {
|
|||||||
Ok(ThoughtId::from_uuid(row.0))
|
Ok(ThoughtId::from_uuid(row.0))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn apply_note_update(
|
async fn apply_note_update(&self, ap_id: &str, new_content: &str) -> Result<(), DomainError> {
|
||||||
&self,
|
|
||||||
ap_id: &str,
|
|
||||||
new_content: &str,
|
|
||||||
note_extensions: Option<serde_json::Value>,
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
let capped: String = new_content.chars().take(MAX_REMOTE_CONTENT_CHARS).collect();
|
let capped: String = new_content.chars().take(MAX_REMOTE_CONTENT_CHARS).collect();
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"UPDATE thoughts SET content=$2,note_extensions=$3,updated_at=NOW() WHERE ap_id=$1 AND local=false",
|
"UPDATE thoughts SET content=$2,updated_at=NOW() WHERE ap_id=$1 AND local=false",
|
||||||
)
|
)
|
||||||
.bind(ap_id)
|
.bind(ap_id)
|
||||||
.bind(&capped)
|
.bind(&capped)
|
||||||
.bind(¬e_extensions)
|
|
||||||
.execute(&self.pool)
|
.execute(&self.pool)
|
||||||
.await
|
.await
|
||||||
.into_domain()
|
.into_domain()
|
||||||
@@ -345,19 +330,6 @@ impl ActivityPubRepository for PgActivityPubRepository {
|
|||||||
.into_domain()
|
.into_domain()
|
||||||
.map(|opt| opt.map(|(ap_id, inbox_url)| ActorApUrls { ap_id, inbox_url }))
|
.map(|opt| opt.map(|(ap_id, inbox_url)| ActorApUrls { ap_id, inbox_url }))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn sync_remote_actor_to_user(&self, actor_ap_url: &str) -> Result<(), DomainError> {
|
|
||||||
sqlx::query(
|
|
||||||
"UPDATE users SET display_name = ra.display_name, avatar_url = ra.avatar_url, updated_at = NOW()
|
|
||||||
FROM remote_actors ra
|
|
||||||
WHERE users.ap_id = ra.url AND users.ap_id = $1 AND users.local = false",
|
|
||||||
)
|
|
||||||
.bind(actor_ap_url)
|
|
||||||
.execute(&self.pool)
|
|
||||||
.await
|
|
||||||
.into_domain()
|
|
||||||
.map(|_| ())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@@ -25,7 +25,6 @@ async fn accept_and_retract_note(pool: sqlx::PgPool) {
|
|||||||
content_warning: None,
|
content_warning: None,
|
||||||
visibility: "public",
|
visibility: "public",
|
||||||
in_reply_to: None,
|
in_reply_to: None,
|
||||||
note_extensions: None,
|
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -56,7 +55,6 @@ async fn accept_note_returns_thought_id(pool: sqlx::PgPool) {
|
|||||||
content_warning: None,
|
content_warning: None,
|
||||||
visibility: "public",
|
visibility: "public",
|
||||||
in_reply_to: None,
|
in_reply_to: None,
|
||||||
note_extensions: None,
|
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|||||||
@@ -9,27 +9,6 @@ use domain::{
|
|||||||
};
|
};
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
|
|
||||||
#[derive(sqlx::FromRow)]
|
|
||||||
struct ApiKeyRow {
|
|
||||||
id: uuid::Uuid,
|
|
||||||
user_id: uuid::Uuid,
|
|
||||||
key_hash: String,
|
|
||||||
name: String,
|
|
||||||
created_at: DateTime<Utc>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ApiKeyRow {
|
|
||||||
fn into_domain(self) -> ApiKey {
|
|
||||||
ApiKey {
|
|
||||||
id: ApiKeyId::from_uuid(self.id),
|
|
||||||
user_id: UserId::from_uuid(self.user_id),
|
|
||||||
key_hash: self.key_hash,
|
|
||||||
name: self.name,
|
|
||||||
created_at: self.created_at,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct PgApiKeyRepository {
|
pub struct PgApiKeyRepository {
|
||||||
pool: PgPool,
|
pool: PgPool,
|
||||||
}
|
}
|
||||||
@@ -57,21 +36,45 @@ impl ApiKeyRepository for PgApiKeyRepository {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn find_by_hash(&self, hash: &str) -> Result<Option<ApiKey>, DomainError> {
|
async fn find_by_hash(&self, hash: &str) -> Result<Option<ApiKey>, DomainError> {
|
||||||
sqlx::query_as::<_, ApiKeyRow>(
|
#[derive(sqlx::FromRow)]
|
||||||
|
struct Row {
|
||||||
|
id: uuid::Uuid,
|
||||||
|
user_id: uuid::Uuid,
|
||||||
|
key_hash: String,
|
||||||
|
name: String,
|
||||||
|
created_at: DateTime<Utc>,
|
||||||
|
}
|
||||||
|
sqlx::query_as::<_, Row>(
|
||||||
"SELECT id,user_id,key_hash,name,created_at FROM api_keys WHERE key_hash=$1",
|
"SELECT id,user_id,key_hash,name,created_at FROM api_keys WHERE key_hash=$1",
|
||||||
)
|
)
|
||||||
.bind(hash)
|
.bind(hash)
|
||||||
.fetch_optional(&self.pool)
|
.fetch_optional(&self.pool)
|
||||||
.await
|
.await
|
||||||
.into_domain()
|
.into_domain()
|
||||||
.map(|o| o.map(ApiKeyRow::into_domain))
|
.map(|o| {
|
||||||
|
o.map(|r| ApiKey {
|
||||||
|
id: ApiKeyId::from_uuid(r.id),
|
||||||
|
user_id: UserId::from_uuid(r.user_id),
|
||||||
|
key_hash: r.key_hash,
|
||||||
|
name: r.name,
|
||||||
|
created_at: r.created_at,
|
||||||
|
})
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn list_for_user(&self, user_id: &UserId) -> Result<Vec<ApiKey>, DomainError> {
|
async fn list_for_user(&self, user_id: &UserId) -> Result<Vec<ApiKey>, DomainError> {
|
||||||
sqlx::query_as::<_, ApiKeyRow>("SELECT id,user_id,key_hash,name,created_at FROM api_keys WHERE user_id=$1 ORDER BY created_at DESC")
|
#[derive(sqlx::FromRow)]
|
||||||
|
struct Row {
|
||||||
|
id: uuid::Uuid,
|
||||||
|
user_id: uuid::Uuid,
|
||||||
|
key_hash: String,
|
||||||
|
name: String,
|
||||||
|
created_at: DateTime<Utc>,
|
||||||
|
}
|
||||||
|
sqlx::query_as::<_, Row>("SELECT id,user_id,key_hash,name,created_at FROM api_keys WHERE user_id=$1 ORDER BY created_at DESC")
|
||||||
.bind(user_id.as_uuid()).fetch_all(&self.pool).await
|
.bind(user_id.as_uuid()).fetch_all(&self.pool).await
|
||||||
.into_domain()
|
.into_domain()
|
||||||
.map(|rows| rows.into_iter().map(ApiKeyRow::into_domain).collect())
|
.map(|rows| rows.into_iter().map(|r| ApiKey { id: ApiKeyId::from_uuid(r.id), user_id: UserId::from_uuid(r.user_id), key_hash: r.key_hash, name: r.name, created_at: r.created_at }).collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn delete(&self, id: &ApiKeyId, user_id: &UserId) -> Result<(), DomainError> {
|
async fn delete(&self, id: &ApiKeyId, user_id: &UserId) -> Result<(), DomainError> {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::test_helpers::seed_user;
|
use crate::test_helpers::seed_user;
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
|
use domain::value_objects::*;
|
||||||
|
|
||||||
#[sqlx::test(migrations = "./migrations")]
|
#[sqlx::test(migrations = "./migrations")]
|
||||||
async fn block_exists(pool: sqlx::PgPool) {
|
async fn block_exists(pool: sqlx::PgPool) {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::test_helpers::seed_user_and_thought;
|
use crate::test_helpers::seed_user_and_thought;
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
|
use domain::value_objects::*;
|
||||||
|
|
||||||
#[sqlx::test(migrations = "./migrations")]
|
#[sqlx::test(migrations = "./migrations")]
|
||||||
async fn boost_and_count(pool: sqlx::PgPool) {
|
async fn boost_and_count(pool: sqlx::PgPool) {
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
pub const STATUS_ACCEPTED: &str = "accepted";
|
|
||||||
pub const STATUS_PENDING: &str = "pending";
|
|
||||||
pub const STATUS_REJECTED: &str = "rejected";
|
|
||||||
|
|
||||||
pub const VIS_PUBLIC: &str = "public";
|
|
||||||
pub const VIS_UNLISTED: &str = "unlisted";
|
|
||||||
pub const VIS_FOLLOWERS: &str = "followers";
|
|
||||||
pub const VIS_DIRECT: &str = "direct";
|
|
||||||
@@ -9,8 +9,8 @@ use domain::{
|
|||||||
thought::{Thought, Visibility},
|
thought::{Thought, Visibility},
|
||||||
user::User,
|
user::User,
|
||||||
},
|
},
|
||||||
ports::{FeedOptions, FeedRepository, FeedRequest, FeedScope, FeedSort},
|
ports::{FeedQuery, FeedRepository, FeedScope},
|
||||||
value_objects::{Content, ThoughtId, UserId},
|
value_objects::{Content, Email, PasswordHash, ThoughtId, UserId, Username},
|
||||||
};
|
};
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
|
|
||||||
@@ -29,17 +29,24 @@ struct FeedRow {
|
|||||||
t_user_id: uuid::Uuid,
|
t_user_id: uuid::Uuid,
|
||||||
content: String,
|
content: String,
|
||||||
in_reply_to_id: Option<uuid::Uuid>,
|
in_reply_to_id: Option<uuid::Uuid>,
|
||||||
in_reply_to_url: Option<String>,
|
|
||||||
visibility: String,
|
visibility: String,
|
||||||
content_warning: Option<String>,
|
content_warning: Option<String>,
|
||||||
sensitive: bool,
|
sensitive: bool,
|
||||||
t_local: bool,
|
t_local: bool,
|
||||||
thought_created_at: DateTime<Utc>,
|
thought_created_at: DateTime<Utc>,
|
||||||
thought_updated_at: Option<DateTime<Utc>>,
|
updated_at: Option<DateTime<Utc>>,
|
||||||
note_extensions: Option<serde_json::Value>,
|
author_id: uuid::Uuid,
|
||||||
mood: Option<String>,
|
username: String,
|
||||||
#[sqlx(flatten)]
|
email: String,
|
||||||
author: crate::user::UserRow,
|
password_hash: String,
|
||||||
|
display_name: Option<String>,
|
||||||
|
bio: Option<String>,
|
||||||
|
avatar_url: Option<String>,
|
||||||
|
header_url: Option<String>,
|
||||||
|
custom_css: Option<String>,
|
||||||
|
author_local: bool,
|
||||||
|
author_created_at: DateTime<Utc>,
|
||||||
|
author_updated_at: DateTime<Utc>,
|
||||||
like_count: i64,
|
like_count: i64,
|
||||||
boost_count: i64,
|
boost_count: i64,
|
||||||
reply_count: i64,
|
reply_count: i64,
|
||||||
@@ -47,23 +54,85 @@ struct FeedRow {
|
|||||||
boosted_by_viewer: bool,
|
boosted_by_viewer: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn federation_following_clause(follower: Option<uuid::Uuid>) -> String {
|
||||||
|
match follower {
|
||||||
|
Some(fid) => format!(
|
||||||
|
" OR t.user_id IN (
|
||||||
|
SELECT u2.id FROM users u2
|
||||||
|
JOIN federation_following ff ON u2.ap_id = ff.remote_actor_url
|
||||||
|
WHERE ff.local_user_id = '{fid}'
|
||||||
|
)"
|
||||||
|
),
|
||||||
|
None => String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn feed_select(viewer: Option<uuid::Uuid>) -> String {
|
||||||
|
let viewer_checks = match viewer {
|
||||||
|
Some(uid) => format!(
|
||||||
|
"EXISTS(SELECT 1 FROM likes WHERE user_id='{uid}' AND thought_id=t.id) AS liked_by_viewer,
|
||||||
|
EXISTS(SELECT 1 FROM boosts WHERE user_id='{uid}' AND thought_id=t.id) AS boosted_by_viewer"
|
||||||
|
),
|
||||||
|
None => "false AS liked_by_viewer, false AS boosted_by_viewer".to_string(),
|
||||||
|
};
|
||||||
|
format!(
|
||||||
|
"
|
||||||
|
SELECT
|
||||||
|
t.id AS thought_id, t.user_id AS t_user_id, t.content,
|
||||||
|
t.in_reply_to_id,
|
||||||
|
t.visibility, t.content_warning, t.sensitive, t.local AS t_local,
|
||||||
|
t.created_at AS thought_created_at, t.updated_at,
|
||||||
|
u.id AS author_id,
|
||||||
|
CASE WHEN NOT u.local AND ra.handle IS NOT NULL AND ra.handle != ''
|
||||||
|
THEN '@' || ra.handle ||
|
||||||
|
CASE WHEN ra.handle NOT LIKE '%@%'
|
||||||
|
THEN '@' || SPLIT_PART(ra.url, '/', 3)
|
||||||
|
ELSE '' END
|
||||||
|
ELSE u.username END AS username,
|
||||||
|
u.email, u.password_hash,
|
||||||
|
COALESCE(ra.display_name, u.display_name) AS display_name,
|
||||||
|
u.bio,
|
||||||
|
COALESCE(ra.avatar_url, u.avatar_url) AS avatar_url,
|
||||||
|
u.header_url, u.custom_css,
|
||||||
|
u.local AS author_local,
|
||||||
|
u.created_at AS author_created_at, u.updated_at AS author_updated_at,
|
||||||
|
(SELECT COUNT(*) FROM likes l WHERE l.thought_id=t.id) AS like_count,
|
||||||
|
(SELECT COUNT(*) FROM boosts b WHERE b.thought_id=t.id) AS boost_count,
|
||||||
|
(SELECT COUNT(*) FROM thoughts r WHERE r.in_reply_to_id=t.id) AS reply_count,
|
||||||
|
{viewer_checks}
|
||||||
|
FROM thoughts t
|
||||||
|
JOIN users u ON u.id=t.user_id
|
||||||
|
LEFT JOIN remote_actors ra ON u.ap_id = ra.url"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
fn row_to_entry(r: FeedRow, viewer: Option<uuid::Uuid>) -> Result<FeedEntry, DomainError> {
|
fn row_to_entry(r: FeedRow, viewer: Option<uuid::Uuid>) -> Result<FeedEntry, DomainError> {
|
||||||
let thought = Thought {
|
let thought = Thought {
|
||||||
id: ThoughtId::from_uuid(r.thought_id),
|
id: ThoughtId::from_uuid(r.thought_id),
|
||||||
user_id: UserId::from_uuid(r.t_user_id),
|
user_id: UserId::from_uuid(r.t_user_id),
|
||||||
content: Content::new_remote(r.content),
|
content: Content::new_remote(r.content),
|
||||||
in_reply_to_id: r.in_reply_to_id.map(ThoughtId::from_uuid),
|
in_reply_to_id: r.in_reply_to_id.map(ThoughtId::from_uuid),
|
||||||
in_reply_to_url: r.in_reply_to_url,
|
|
||||||
visibility: Visibility::from_db_str(&r.visibility)?,
|
visibility: Visibility::from_db_str(&r.visibility)?,
|
||||||
content_warning: r.content_warning,
|
content_warning: r.content_warning,
|
||||||
sensitive: r.sensitive,
|
sensitive: r.sensitive,
|
||||||
local: r.t_local,
|
local: r.t_local,
|
||||||
created_at: r.thought_created_at,
|
created_at: r.thought_created_at,
|
||||||
updated_at: r.thought_updated_at,
|
updated_at: r.updated_at,
|
||||||
note_extensions: r.note_extensions,
|
};
|
||||||
mood: r.mood,
|
let author = User {
|
||||||
|
id: UserId::from_uuid(r.author_id),
|
||||||
|
username: Username::from_trusted(r.username),
|
||||||
|
email: Email::from_trusted(r.email),
|
||||||
|
password_hash: PasswordHash(r.password_hash),
|
||||||
|
display_name: r.display_name,
|
||||||
|
bio: r.bio,
|
||||||
|
avatar_url: r.avatar_url,
|
||||||
|
header_url: r.header_url,
|
||||||
|
custom_css: r.custom_css,
|
||||||
|
local: r.author_local,
|
||||||
|
created_at: r.author_created_at,
|
||||||
|
updated_at: r.author_updated_at,
|
||||||
};
|
};
|
||||||
let author = User::from(r.author);
|
|
||||||
Ok(FeedEntry {
|
Ok(FeedEntry {
|
||||||
thought,
|
thought,
|
||||||
author,
|
author,
|
||||||
@@ -79,227 +148,36 @@ fn row_to_entry(r: FeedRow, viewer: Option<uuid::Uuid>) -> Result<FeedEntry, Dom
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
struct FeedSqlBuilder<'a> {
|
|
||||||
options: &'a FeedOptions,
|
|
||||||
scope: &'a FeedScope,
|
|
||||||
viewer: Option<uuid::Uuid>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> FeedSqlBuilder<'a> {
|
|
||||||
fn new(options: &'a FeedOptions, scope: &'a FeedScope, viewer: Option<uuid::Uuid>) -> Self {
|
|
||||||
Self {
|
|
||||||
options,
|
|
||||||
scope,
|
|
||||||
viewer,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn select(&self, viewer_param: &str) -> String {
|
|
||||||
let (viewer_cols, viewer_joins) = match self.viewer {
|
|
||||||
Some(_) => (
|
|
||||||
"(lv.thought_id IS NOT NULL) AS liked_by_viewer,
|
|
||||||
(bv.thought_id IS NOT NULL) AS boosted_by_viewer".to_string(),
|
|
||||||
format!(
|
|
||||||
"LEFT JOIN (SELECT thought_id FROM likes WHERE user_id={viewer_param}) lv ON lv.thought_id = t.id
|
|
||||||
LEFT JOIN (SELECT thought_id FROM boosts WHERE user_id={viewer_param}) bv ON bv.thought_id = t.id"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
None => (
|
|
||||||
"false AS liked_by_viewer, false AS boosted_by_viewer".to_string(),
|
|
||||||
String::new(),
|
|
||||||
),
|
|
||||||
};
|
|
||||||
format!(
|
|
||||||
"
|
|
||||||
SELECT
|
|
||||||
t.id AS thought_id, t.user_id AS t_user_id, t.content,
|
|
||||||
t.in_reply_to_id, t.in_reply_to_url,
|
|
||||||
t.visibility, t.content_warning, t.sensitive, t.local AS t_local,
|
|
||||||
t.created_at AS thought_created_at, t.updated_at AS thought_updated_at,
|
|
||||||
t.note_extensions, t.mood,
|
|
||||||
u.id,
|
|
||||||
CASE WHEN NOT u.local AND ra.handle IS NOT NULL AND ra.handle != ''
|
|
||||||
THEN '@' || ra.handle ||
|
|
||||||
CASE WHEN ra.handle NOT LIKE '%@%'
|
|
||||||
THEN '@' || SPLIT_PART(ra.url, '/', 3)
|
|
||||||
ELSE '' END
|
|
||||||
ELSE u.username END AS username,
|
|
||||||
u.email, u.password_hash,
|
|
||||||
COALESCE(ra.display_name, u.display_name) AS display_name,
|
|
||||||
u.bio,
|
|
||||||
COALESCE(ra.avatar_url, u.avatar_url) AS avatar_url,
|
|
||||||
u.header_url, u.custom_css, u.profile_fields, u.custom_moods,
|
|
||||||
u.local,
|
|
||||||
u.created_at, u.updated_at,
|
|
||||||
COALESCE(l_agg.cnt, 0) AS like_count,
|
|
||||||
COALESCE(b_agg.cnt, 0) AS boost_count,
|
|
||||||
COALESCE(r_agg.cnt, 0) AS reply_count,
|
|
||||||
{viewer_cols}
|
|
||||||
FROM thoughts t
|
|
||||||
JOIN users u ON u.id=t.user_id
|
|
||||||
LEFT JOIN remote_actors ra ON u.ap_id = ra.url
|
|
||||||
LEFT JOIN (SELECT thought_id, COUNT(*) AS cnt FROM likes GROUP BY thought_id) l_agg ON l_agg.thought_id = t.id
|
|
||||||
LEFT JOIN (SELECT thought_id, COUNT(*) AS cnt FROM boosts GROUP BY thought_id) b_agg ON b_agg.thought_id = t.id
|
|
||||||
LEFT JOIN (SELECT in_reply_to_id, COUNT(*) AS cnt FROM thoughts WHERE in_reply_to_id IS NOT NULL GROUP BY in_reply_to_id) r_agg ON r_agg.in_reply_to_id = t.id
|
|
||||||
{viewer_joins}"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn fed_clause(&self, viewer_param: &str) -> String {
|
|
||||||
match self.viewer {
|
|
||||||
Some(_) => format!(
|
|
||||||
" OR t.user_id IN (
|
|
||||||
SELECT u2.id FROM users u2
|
|
||||||
JOIN federation_following ff ON u2.ap_id = ff.remote_actor_url
|
|
||||||
WHERE ff.local_user_id = {viewer_param}
|
|
||||||
)"
|
|
||||||
),
|
|
||||||
None => String::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn filter_sql(&self) -> String {
|
|
||||||
let f = &self.options.filter;
|
|
||||||
let mut s = String::new();
|
|
||||||
if f.originals_only {
|
|
||||||
s += " AND t.in_reply_to_id IS NULL";
|
|
||||||
}
|
|
||||||
if f.replies_only {
|
|
||||||
s += " AND t.in_reply_to_id IS NOT NULL";
|
|
||||||
}
|
|
||||||
if f.local_only {
|
|
||||||
s += " AND t.local = true";
|
|
||||||
}
|
|
||||||
if f.hide_sensitive {
|
|
||||||
s += " AND t.sensitive = false";
|
|
||||||
}
|
|
||||||
s
|
|
||||||
}
|
|
||||||
|
|
||||||
fn order_sql(&self) -> &'static str {
|
|
||||||
if matches!(self.scope, FeedScope::Search { .. }) {
|
|
||||||
return "ORDER BY similarity(t.content, $1) DESC";
|
|
||||||
}
|
|
||||||
match &self.options.sort {
|
|
||||||
FeedSort::Newest => "ORDER BY t.created_at DESC",
|
|
||||||
FeedSort::Oldest => "ORDER BY t.created_at ASC",
|
|
||||||
FeedSort::MostLiked => "ORDER BY like_count DESC, t.created_at DESC",
|
|
||||||
FeedSort::MostBoosted => "ORDER BY boost_count DESC, t.created_at DESC",
|
|
||||||
FeedSort::MostDiscussed => "ORDER BY reply_count DESC, t.created_at DESC",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn public(&self) -> (String, String) {
|
|
||||||
let filter = self.filter_sql();
|
|
||||||
let order = self.order_sql();
|
|
||||||
let count = format!(
|
|
||||||
"SELECT COUNT(*) FROM thoughts t WHERE t.local=true AND t.visibility='public'{}",
|
|
||||||
filter
|
|
||||||
);
|
|
||||||
let data = format!(
|
|
||||||
"{} WHERE t.local=true AND t.visibility='public'{} {} LIMIT $1 OFFSET $2",
|
|
||||||
self.select("$3"),
|
|
||||||
filter,
|
|
||||||
order
|
|
||||||
);
|
|
||||||
(count, data)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn home(&self) -> (String, String) {
|
|
||||||
let filter = self.filter_sql();
|
|
||||||
let order = self.order_sql();
|
|
||||||
let count = format!(
|
|
||||||
"SELECT COUNT(*) FROM thoughts t WHERE (t.user_id=ANY($1){}) AND t.visibility != 'direct'{}",
|
|
||||||
self.fed_clause("$2"), filter
|
|
||||||
);
|
|
||||||
let data =
|
|
||||||
format!(
|
|
||||||
"{} WHERE (t.user_id=ANY($1){}) AND t.visibility != 'direct'{} {} LIMIT $2 OFFSET $3",
|
|
||||||
self.select("$4"), self.fed_clause("$4"), filter, order
|
|
||||||
);
|
|
||||||
(count, data)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn search(&self) -> (String, String) {
|
|
||||||
let filter = self.filter_sql();
|
|
||||||
let order = self.order_sql();
|
|
||||||
let count = format!(
|
|
||||||
"SELECT COUNT(*) FROM thoughts t WHERE t.content % $1 AND t.visibility='public'{}",
|
|
||||||
filter
|
|
||||||
);
|
|
||||||
let data = format!(
|
|
||||||
"{} WHERE t.content % $1 AND t.visibility='public'{} {} LIMIT $2 OFFSET $3",
|
|
||||||
self.select("$4"),
|
|
||||||
filter,
|
|
||||||
order
|
|
||||||
);
|
|
||||||
(count, data)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn tag(&self) -> (String, String) {
|
|
||||||
let filter = self.filter_sql();
|
|
||||||
let order = self.order_sql();
|
|
||||||
let count = format!(
|
|
||||||
"SELECT COUNT(*) FROM thoughts t
|
|
||||||
JOIN thought_tags tt ON tt.thought_id = t.id
|
|
||||||
JOIN tags tg ON tg.id = tt.tag_id
|
|
||||||
WHERE tg.name = $1 AND t.visibility = 'public'{}",
|
|
||||||
filter
|
|
||||||
);
|
|
||||||
let data = format!(
|
|
||||||
"{}
|
|
||||||
JOIN thought_tags tt ON tt.thought_id = t.id
|
|
||||||
JOIN tags tg ON tg.id = tt.tag_id
|
|
||||||
WHERE tg.name = $1 AND t.visibility = 'public'{} {} LIMIT $2 OFFSET $3",
|
|
||||||
self.select("$4"),
|
|
||||||
filter,
|
|
||||||
order
|
|
||||||
);
|
|
||||||
(count, data)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn user(&self) -> (String, String) {
|
|
||||||
let filter = self.filter_sql();
|
|
||||||
let order = self.order_sql();
|
|
||||||
let count = format!(
|
|
||||||
"SELECT COUNT(*) FROM thoughts t WHERE t.user_id = $1 AND ($2::uuid = $1 OR (t.visibility != 'direct' AND (t.visibility IN ('public', 'unlisted') OR (t.visibility = 'followers' AND EXISTS(SELECT 1 FROM follows WHERE follower_id = $2 AND following_id = $1 AND state = 'accepted'))))){}",
|
|
||||||
filter
|
|
||||||
);
|
|
||||||
let data = format!(
|
|
||||||
"{} WHERE t.user_id = $1 AND ($4::uuid = $1 OR (t.visibility != 'direct' AND (t.visibility IN ('public', 'unlisted') OR (t.visibility = 'followers' AND EXISTS(SELECT 1 FROM follows WHERE follower_id = $4 AND following_id = $1 AND state = 'accepted'))))){} {} LIMIT $2 OFFSET $3",
|
|
||||||
self.select("$4"), filter, order
|
|
||||||
);
|
|
||||||
(count, data)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl FeedRepository for PgFeedRepository {
|
impl FeedRepository for PgFeedRepository {
|
||||||
async fn query(&self, req: &FeedRequest) -> Result<Paginated<FeedEntry>, DomainError> {
|
async fn query(&self, q: &FeedQuery) -> Result<Paginated<FeedEntry>, DomainError> {
|
||||||
let viewer = req.query.viewer_id.as_ref().map(|v| v.as_uuid());
|
let viewer = q.viewer_id.as_ref().map(|v| v.as_uuid());
|
||||||
let page = &req.query.page;
|
let page = &q.page;
|
||||||
let builder = FeedSqlBuilder::new(&req.options, &req.query.scope, viewer);
|
|
||||||
|
|
||||||
let viewer_uuid = viewer.unwrap_or(uuid::Uuid::nil());
|
match &q.scope {
|
||||||
|
|
||||||
match &req.query.scope {
|
|
||||||
FeedScope::Home { following_ids } => {
|
FeedScope::Home { following_ids } => {
|
||||||
let ids: Vec<uuid::Uuid> = following_ids.iter().map(|id| id.as_uuid()).collect();
|
let ids: Vec<uuid::Uuid> = following_ids.iter().map(|id| id.as_uuid()).collect();
|
||||||
let (count_sql, data_sql) = builder.home();
|
let fed_clause = federation_following_clause(viewer);
|
||||||
|
let count_sql = format!(
|
||||||
|
"SELECT COUNT(*) FROM thoughts t WHERE (t.user_id=ANY($1){}) AND t.visibility != 'direct'",
|
||||||
|
fed_clause
|
||||||
|
);
|
||||||
let total: i64 = sqlx::query_scalar(&count_sql)
|
let total: i64 = sqlx::query_scalar(&count_sql)
|
||||||
.bind(&ids)
|
.bind(&ids)
|
||||||
.bind(viewer_uuid)
|
|
||||||
.fetch_one(&self.pool)
|
.fetch_one(&self.pool)
|
||||||
.await
|
.await
|
||||||
.into_domain()?;
|
.into_domain()?;
|
||||||
let rows = sqlx::query_as::<_, FeedRow>(&data_sql)
|
|
||||||
|
let sel = feed_select(viewer);
|
||||||
|
let sql = format!("{sel} WHERE (t.user_id=ANY($1){}) AND t.visibility != 'direct' ORDER BY t.created_at DESC LIMIT $2 OFFSET $3", fed_clause);
|
||||||
|
let rows = sqlx::query_as::<_, FeedRow>(&sql)
|
||||||
.bind(&ids)
|
.bind(&ids)
|
||||||
.bind(page.limit())
|
.bind(page.limit())
|
||||||
.bind(page.offset())
|
.bind(page.offset())
|
||||||
.bind(viewer_uuid)
|
|
||||||
.fetch_all(&self.pool)
|
.fetch_all(&self.pool)
|
||||||
.await
|
.await
|
||||||
.into_domain()?;
|
.into_domain()?;
|
||||||
|
|
||||||
Ok(Paginated {
|
Ok(Paginated {
|
||||||
items: rows
|
items: rows
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@@ -312,18 +190,22 @@ impl FeedRepository for PgFeedRepository {
|
|||||||
}
|
}
|
||||||
|
|
||||||
FeedScope::Public => {
|
FeedScope::Public => {
|
||||||
let (count_sql, data_sql) = builder.public();
|
let total: i64 = sqlx::query_scalar(
|
||||||
let total: i64 = sqlx::query_scalar(&count_sql)
|
"SELECT COUNT(*) FROM thoughts t WHERE t.local=true AND t.visibility='public'",
|
||||||
|
)
|
||||||
.fetch_one(&self.pool)
|
.fetch_one(&self.pool)
|
||||||
.await
|
.await
|
||||||
.into_domain()?;
|
.into_domain()?;
|
||||||
let rows = sqlx::query_as::<_, FeedRow>(&data_sql)
|
|
||||||
|
let sel = feed_select(viewer);
|
||||||
|
let sql = format!("{sel} WHERE t.local=true AND t.visibility='public' ORDER BY t.created_at DESC LIMIT $1 OFFSET $2");
|
||||||
|
let rows = sqlx::query_as::<_, FeedRow>(&sql)
|
||||||
.bind(page.limit())
|
.bind(page.limit())
|
||||||
.bind(page.offset())
|
.bind(page.offset())
|
||||||
.bind(viewer_uuid)
|
|
||||||
.fetch_all(&self.pool)
|
.fetch_all(&self.pool)
|
||||||
.await
|
.await
|
||||||
.into_domain()?;
|
.into_domain()?;
|
||||||
|
|
||||||
Ok(Paginated {
|
Ok(Paginated {
|
||||||
items: rows
|
items: rows
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@@ -336,20 +218,24 @@ impl FeedRepository for PgFeedRepository {
|
|||||||
}
|
}
|
||||||
|
|
||||||
FeedScope::Search { query } => {
|
FeedScope::Search { query } => {
|
||||||
let (count_sql, data_sql) = builder.search();
|
let total: i64 = sqlx::query_scalar(
|
||||||
let total: i64 = sqlx::query_scalar(&count_sql)
|
"SELECT COUNT(*) FROM thoughts t WHERE t.content % $1 AND t.visibility='public'",
|
||||||
|
)
|
||||||
.bind(query)
|
.bind(query)
|
||||||
.fetch_one(&self.pool)
|
.fetch_one(&self.pool)
|
||||||
.await
|
.await
|
||||||
.into_domain()?;
|
.into_domain()?;
|
||||||
let rows = sqlx::query_as::<_, FeedRow>(&data_sql)
|
|
||||||
|
let sel = feed_select(viewer);
|
||||||
|
let sql = format!("{sel} WHERE t.content % $1 AND t.visibility='public' ORDER BY similarity(t.content, $1) DESC LIMIT $2 OFFSET $3");
|
||||||
|
let rows = sqlx::query_as::<_, FeedRow>(&sql)
|
||||||
.bind(query)
|
.bind(query)
|
||||||
.bind(page.limit())
|
.bind(page.limit())
|
||||||
.bind(page.offset())
|
.bind(page.offset())
|
||||||
.bind(viewer_uuid)
|
|
||||||
.fetch_all(&self.pool)
|
.fetch_all(&self.pool)
|
||||||
.await
|
.await
|
||||||
.into_domain()?;
|
.into_domain()?;
|
||||||
|
|
||||||
Ok(Paginated {
|
Ok(Paginated {
|
||||||
items: rows
|
items: rows
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@@ -362,20 +248,33 @@ impl FeedRepository for PgFeedRepository {
|
|||||||
}
|
}
|
||||||
|
|
||||||
FeedScope::Tag { tag_name } => {
|
FeedScope::Tag { tag_name } => {
|
||||||
let (count_sql, data_sql) = builder.tag();
|
let total: i64 = sqlx::query_scalar(
|
||||||
let total: i64 = sqlx::query_scalar(&count_sql)
|
"SELECT COUNT(*) FROM thoughts t
|
||||||
|
JOIN thought_tags tt ON tt.thought_id = t.id
|
||||||
|
JOIN tags tg ON tg.id = tt.tag_id
|
||||||
|
WHERE tg.name = $1 AND t.visibility = 'public'",
|
||||||
|
)
|
||||||
.bind(tag_name)
|
.bind(tag_name)
|
||||||
.fetch_one(&self.pool)
|
.fetch_one(&self.pool)
|
||||||
.await
|
.await
|
||||||
.into_domain()?;
|
.into_domain()?;
|
||||||
let rows = sqlx::query_as::<_, FeedRow>(&data_sql)
|
|
||||||
|
let sel = feed_select(viewer);
|
||||||
|
let sql = format!(
|
||||||
|
"{sel}
|
||||||
|
JOIN thought_tags tt ON tt.thought_id = t.id
|
||||||
|
JOIN tags tg ON tg.id = tt.tag_id
|
||||||
|
WHERE tg.name = $1 AND t.visibility = 'public'
|
||||||
|
ORDER BY t.created_at DESC LIMIT $2 OFFSET $3"
|
||||||
|
);
|
||||||
|
let rows = sqlx::query_as::<_, FeedRow>(&sql)
|
||||||
.bind(tag_name)
|
.bind(tag_name)
|
||||||
.bind(page.limit())
|
.bind(page.limit())
|
||||||
.bind(page.offset())
|
.bind(page.offset())
|
||||||
.bind(viewer_uuid)
|
|
||||||
.fetch_all(&self.pool)
|
.fetch_all(&self.pool)
|
||||||
.await
|
.await
|
||||||
.into_domain()?;
|
.into_domain()?;
|
||||||
|
|
||||||
Ok(Paginated {
|
Ok(Paginated {
|
||||||
items: rows
|
items: rows
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@@ -389,14 +288,21 @@ impl FeedRepository for PgFeedRepository {
|
|||||||
|
|
||||||
FeedScope::User { user_id } => {
|
FeedScope::User { user_id } => {
|
||||||
let uid = user_id.as_uuid();
|
let uid = user_id.as_uuid();
|
||||||
let (count_sql, data_sql) = builder.user();
|
// Use nil UUID for unauthenticated viewers — won't match owner or follower checks.
|
||||||
let total: i64 = sqlx::query_scalar(&count_sql)
|
let viewer_uuid = viewer.unwrap_or(uuid::Uuid::nil());
|
||||||
|
|
||||||
|
let total: i64 = sqlx::query_scalar(
|
||||||
|
"SELECT COUNT(*) FROM thoughts t WHERE t.user_id = $1 AND ($2::uuid = $1 OR (t.visibility != 'direct' AND (t.visibility IN ('public', 'unlisted') OR (t.visibility = 'followers' AND EXISTS(SELECT 1 FROM follows WHERE follower_id = $2 AND following_id = $1 AND state = 'accepted')))))",
|
||||||
|
)
|
||||||
.bind(uid)
|
.bind(uid)
|
||||||
.bind(viewer_uuid)
|
.bind(viewer_uuid)
|
||||||
.fetch_one(&self.pool)
|
.fetch_one(&self.pool)
|
||||||
.await
|
.await
|
||||||
.into_domain()?;
|
.into_domain()?;
|
||||||
let rows = sqlx::query_as::<_, FeedRow>(&data_sql)
|
|
||||||
|
let sel = feed_select(viewer);
|
||||||
|
let sql = format!("{sel} WHERE t.user_id = $1 AND ($4::uuid = $1 OR (t.visibility != 'direct' AND (t.visibility IN ('public', 'unlisted') OR (t.visibility = 'followers' AND EXISTS(SELECT 1 FROM follows WHERE follower_id = $4 AND following_id = $1 AND state = 'accepted'))))) ORDER BY t.created_at DESC LIMIT $2 OFFSET $3");
|
||||||
|
let rows = sqlx::query_as::<_, FeedRow>(&sql)
|
||||||
.bind(uid)
|
.bind(uid)
|
||||||
.bind(page.limit())
|
.bind(page.limit())
|
||||||
.bind(page.offset())
|
.bind(page.offset())
|
||||||
@@ -404,6 +310,7 @@ impl FeedRepository for PgFeedRepository {
|
|||||||
.fetch_all(&self.pool)
|
.fetch_all(&self.pool)
|
||||||
.await
|
.await
|
||||||
.into_domain()?;
|
.into_domain()?;
|
||||||
|
|
||||||
Ok(Paginated {
|
Ok(Paginated {
|
||||||
items: rows
|
items: rows
|
||||||
.into_iter()
|
.into_iter()
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ use domain::{
|
|||||||
thought::{NewThought, Thought, Visibility},
|
thought::{NewThought, Thought, Visibility},
|
||||||
user::User,
|
user::User,
|
||||||
},
|
},
|
||||||
ports::{FeedOptions, FeedQuery, FeedRequest, ThoughtRepository, UserWriter},
|
ports::{FeedQuery, ThoughtRepository, UserWriter},
|
||||||
value_objects::{Content, Email, PasswordHash, ThoughtId, UserId, Username},
|
value_objects::*,
|
||||||
};
|
};
|
||||||
|
|
||||||
async fn seed(pool: &sqlx::PgPool, username: &str, content: &str) -> (User, Thought) {
|
async fn seed(pool: &sqlx::PgPool, username: &str, content: &str) -> (User, Thought) {
|
||||||
@@ -28,7 +28,6 @@ async fn seed(pool: &sqlx::PgPool, username: &str, content: &str) -> (User, Thou
|
|||||||
visibility: Visibility::Public,
|
visibility: Visibility::Public,
|
||||||
content_warning: None,
|
content_warning: None,
|
||||||
sensitive: false,
|
sensitive: false,
|
||||||
mood: None,
|
|
||||||
});
|
});
|
||||||
trepo.save(&t).await.unwrap();
|
trepo.save(&t).await.unwrap();
|
||||||
(u, t)
|
(u, t)
|
||||||
@@ -39,16 +38,13 @@ async fn public_feed_returns_local_thoughts(pool: sqlx::PgPool) {
|
|||||||
let (_, _) = seed(&pool, "alice", "hello").await;
|
let (_, _) = seed(&pool, "alice", "hello").await;
|
||||||
let repo = PgFeedRepository::new(pool);
|
let repo = PgFeedRepository::new(pool);
|
||||||
let result = repo
|
let result = repo
|
||||||
.query(&FeedRequest {
|
.query(&FeedQuery::public(
|
||||||
query: FeedQuery::public(
|
|
||||||
PageParams {
|
PageParams {
|
||||||
page: 1,
|
page: 1,
|
||||||
per_page: 20,
|
per_page: 20,
|
||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
),
|
))
|
||||||
options: FeedOptions::default(),
|
|
||||||
})
|
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(result.total, 1);
|
assert_eq!(result.total, 1);
|
||||||
@@ -61,17 +57,14 @@ async fn search_returns_matching_thoughts(pool: sqlx::PgPool) {
|
|||||||
let (_, _) = seed(&pool, "bob", "goodbye world").await;
|
let (_, _) = seed(&pool, "bob", "goodbye world").await;
|
||||||
let repo = PgFeedRepository::new(pool);
|
let repo = PgFeedRepository::new(pool);
|
||||||
let result = repo
|
let result = repo
|
||||||
.query(&FeedRequest {
|
.query(&FeedQuery::search(
|
||||||
query: FeedQuery::search(
|
|
||||||
"hello world",
|
"hello world",
|
||||||
PageParams {
|
PageParams {
|
||||||
page: 1,
|
page: 1,
|
||||||
per_page: 20,
|
per_page: 20,
|
||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
),
|
))
|
||||||
options: FeedOptions::default(),
|
|
||||||
})
|
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(result.total >= 1);
|
assert!(result.total >= 1);
|
||||||
|
|||||||
@@ -120,7 +120,7 @@ impl FollowRepository for PgFollowRepository {
|
|||||||
.into_domain()?;
|
.into_domain()?;
|
||||||
|
|
||||||
let rows = sqlx::query_as::<_, crate::user::UserRow>(
|
let rows = sqlx::query_as::<_, crate::user::UserRow>(
|
||||||
"SELECT u.id,u.username,u.email,u.password_hash,u.display_name,u.bio,u.avatar_url,u.header_url,u.custom_css,u.profile_fields,u.custom_moods,u.local,u.created_at,u.updated_at
|
"SELECT u.id,u.username,u.email,u.password_hash,u.display_name,u.bio,u.avatar_url,u.header_url,u.custom_css,u.local,u.ap_id,u.inbox_url,u.created_at,u.updated_at
|
||||||
FROM users u JOIN follows f ON f.follower_id=u.id
|
FROM users u JOIN follows f ON f.follower_id=u.id
|
||||||
WHERE f.following_id=$1 AND f.state='accepted'
|
WHERE f.following_id=$1 AND f.state='accepted'
|
||||||
ORDER BY f.created_at DESC LIMIT $2 OFFSET $3"
|
ORDER BY f.created_at DESC LIMIT $2 OFFSET $3"
|
||||||
@@ -154,7 +154,7 @@ impl FollowRepository for PgFollowRepository {
|
|||||||
.into_domain()?;
|
.into_domain()?;
|
||||||
|
|
||||||
let rows = sqlx::query_as::<_, crate::user::UserRow>(
|
let rows = sqlx::query_as::<_, crate::user::UserRow>(
|
||||||
"SELECT u.id,u.username,u.email,u.password_hash,u.display_name,u.bio,u.avatar_url,u.header_url,u.custom_css,u.profile_fields,u.custom_moods,u.local,u.created_at,u.updated_at
|
"SELECT u.id,u.username,u.email,u.password_hash,u.display_name,u.bio,u.avatar_url,u.header_url,u.custom_css,u.local,u.ap_id,u.inbox_url,u.created_at,u.updated_at
|
||||||
FROM users u JOIN follows f ON f.following_id=u.id
|
FROM users u JOIN follows f ON f.following_id=u.id
|
||||||
WHERE f.follower_id=$1 AND f.state='accepted'
|
WHERE f.follower_id=$1 AND f.state='accepted'
|
||||||
ORDER BY f.created_at DESC LIMIT $2 OFFSET $3"
|
ORDER BY f.created_at DESC LIMIT $2 OFFSET $3"
|
||||||
@@ -187,59 +187,6 @@ impl FollowRepository for PgFollowRepository {
|
|||||||
.into_domain()?;
|
.into_domain()?;
|
||||||
Ok(ids.into_iter().map(UserId::from_uuid).collect())
|
Ok(ids.into_iter().map(UserId::from_uuid).collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn list_mutual(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
page: &PageParams,
|
|
||||||
) -> Result<Paginated<User>, DomainError> {
|
|
||||||
let total: i64 = sqlx::query_scalar(
|
|
||||||
"SELECT COUNT(*) FROM follows f1
|
|
||||||
WHERE f1.follower_id = $1 AND f1.state = 'accepted'
|
|
||||||
AND EXISTS (
|
|
||||||
SELECT 1 FROM follows f2
|
|
||||||
WHERE f2.follower_id = f1.following_id
|
|
||||||
AND f2.following_id = f1.follower_id
|
|
||||||
AND f2.state = 'accepted'
|
|
||||||
)",
|
|
||||||
)
|
|
||||||
.bind(user_id.as_uuid())
|
|
||||||
.fetch_one(&self.pool)
|
|
||||||
.await
|
|
||||||
.into_domain()?;
|
|
||||||
|
|
||||||
let rows = sqlx::query_as::<_, crate::user::UserRow>(
|
|
||||||
"SELECT u.id, u.username, u.email, u.password_hash, u.display_name, u.bio,
|
|
||||||
u.avatar_url, u.header_url, u.custom_css, u.profile_fields, u.custom_moods, u.local,
|
|
||||||
u.created_at, u.updated_at
|
|
||||||
FROM users u
|
|
||||||
JOIN follows f1
|
|
||||||
ON f1.follower_id = $1
|
|
||||||
AND f1.following_id = u.id
|
|
||||||
AND f1.state = 'accepted'
|
|
||||||
WHERE EXISTS (
|
|
||||||
SELECT 1 FROM follows f2
|
|
||||||
WHERE f2.follower_id = u.id
|
|
||||||
AND f2.following_id = $1
|
|
||||||
AND f2.state = 'accepted'
|
|
||||||
)
|
|
||||||
ORDER BY f1.created_at DESC
|
|
||||||
LIMIT $2 OFFSET $3",
|
|
||||||
)
|
|
||||||
.bind(user_id.as_uuid())
|
|
||||||
.bind(page.limit())
|
|
||||||
.bind(page.offset())
|
|
||||||
.fetch_all(&self.pool)
|
|
||||||
.await
|
|
||||||
.into_domain()?;
|
|
||||||
|
|
||||||
Ok(Paginated {
|
|
||||||
items: rows.into_iter().map(User::from).collect(),
|
|
||||||
total,
|
|
||||||
page: page.page,
|
|
||||||
per_page: page.per_page,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::test_helpers::seed_user;
|
use crate::test_helpers::seed_user;
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
|
use domain::value_objects::*;
|
||||||
|
|
||||||
#[sqlx::test(migrations = "./migrations")]
|
#[sqlx::test(migrations = "./migrations")]
|
||||||
async fn save_and_find_follow(pool: sqlx::PgPool) {
|
async fn save_and_find_follow(pool: sqlx::PgPool) {
|
||||||
@@ -55,86 +56,3 @@ async fn get_accepted_following_ids(pool: sqlx::PgPool) {
|
|||||||
let ids = repo.get_accepted_following_ids(&alice.id).await.unwrap();
|
let ids = repo.get_accepted_following_ids(&alice.id).await.unwrap();
|
||||||
assert_eq!(ids, vec![bob.id]);
|
assert_eq!(ids, vec![bob.id]);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[sqlx::test(migrations = "./migrations")]
|
|
||||||
async fn list_mutual_returns_only_mutual_accepted_follows(pool: sqlx::PgPool) {
|
|
||||||
let alice = seed_user(&pool, "alice", "alice@ex.com").await;
|
|
||||||
let bob = seed_user(&pool, "bob", "bob@ex.com").await;
|
|
||||||
let carol = seed_user(&pool, "carol", "carol@ex.com").await;
|
|
||||||
let repo = PgFollowRepository::new(pool);
|
|
||||||
let page = domain::models::feed::PageParams {
|
|
||||||
page: 1,
|
|
||||||
per_page: 20,
|
|
||||||
};
|
|
||||||
|
|
||||||
// alice → bob (accepted), bob → alice (accepted) = friends
|
|
||||||
repo.save(&Follow {
|
|
||||||
follower_id: alice.id.clone(),
|
|
||||||
following_id: bob.id.clone(),
|
|
||||||
state: FollowState::Accepted,
|
|
||||||
ap_id: None,
|
|
||||||
created_at: Utc::now(),
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
repo.save(&Follow {
|
|
||||||
follower_id: bob.id.clone(),
|
|
||||||
following_id: alice.id.clone(),
|
|
||||||
state: FollowState::Accepted,
|
|
||||||
ap_id: None,
|
|
||||||
created_at: Utc::now(),
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
// alice → carol (accepted), carol does NOT follow back = not a friend
|
|
||||||
repo.save(&Follow {
|
|
||||||
follower_id: alice.id.clone(),
|
|
||||||
following_id: carol.id.clone(),
|
|
||||||
state: FollowState::Accepted,
|
|
||||||
ap_id: None,
|
|
||||||
created_at: Utc::now(),
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let result = repo.list_mutual(&alice.id, &page).await.unwrap();
|
|
||||||
assert_eq!(result.total, 1);
|
|
||||||
assert_eq!(result.items.len(), 1);
|
|
||||||
assert_eq!(result.items[0].id, bob.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[sqlx::test(migrations = "./migrations")]
|
|
||||||
async fn list_mutual_excludes_pending_follows(pool: sqlx::PgPool) {
|
|
||||||
let alice = seed_user(&pool, "alice", "alice@ex.com").await;
|
|
||||||
let bob = seed_user(&pool, "bob", "bob@ex.com").await;
|
|
||||||
let repo = PgFollowRepository::new(pool);
|
|
||||||
let page = domain::models::feed::PageParams {
|
|
||||||
page: 1,
|
|
||||||
per_page: 20,
|
|
||||||
};
|
|
||||||
|
|
||||||
// alice → bob (accepted), bob → alice (PENDING) = NOT a friend
|
|
||||||
repo.save(&Follow {
|
|
||||||
follower_id: alice.id.clone(),
|
|
||||||
following_id: bob.id.clone(),
|
|
||||||
state: FollowState::Accepted,
|
|
||||||
ap_id: None,
|
|
||||||
created_at: Utc::now(),
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
repo.save(&Follow {
|
|
||||||
follower_id: bob.id.clone(),
|
|
||||||
following_id: alice.id.clone(),
|
|
||||||
state: FollowState::Pending,
|
|
||||||
ap_id: None,
|
|
||||||
created_at: Utc::now(),
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let result = repo.list_mutual(&alice.id, &page).await.unwrap();
|
|
||||||
assert_eq!(result.total, 0);
|
|
||||||
assert!(result.items.is_empty());
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
pub fn parse_name_value(v: Option<serde_json::Value>) -> Vec<(String, String)> {
|
|
||||||
v.and_then(|v| v.as_array().cloned())
|
|
||||||
.map(|arr| {
|
|
||||||
arr.into_iter()
|
|
||||||
.filter_map(|item| {
|
|
||||||
let name = item.get("name")?.as_str()?.to_string();
|
|
||||||
let value = item.get("value")?.as_str()?.to_string();
|
|
||||||
Some((name, value))
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
})
|
|
||||||
.unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn serialize_name_value(fields: &[(String, String)]) -> serde_json::Value {
|
|
||||||
fields
|
|
||||||
.iter()
|
|
||||||
.map(|(n, v)| serde_json::json!({"name": n, "value": v}))
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
@@ -2,13 +2,11 @@ pub mod activitypub;
|
|||||||
pub mod api_key;
|
pub mod api_key;
|
||||||
pub mod block;
|
pub mod block;
|
||||||
pub mod boost;
|
pub mod boost;
|
||||||
pub mod constants;
|
|
||||||
mod db_error;
|
mod db_error;
|
||||||
pub mod engagement;
|
pub mod engagement;
|
||||||
pub mod failed_event;
|
pub mod failed_event;
|
||||||
pub mod feed;
|
pub mod feed;
|
||||||
pub mod follow;
|
pub mod follow;
|
||||||
pub(crate) mod jsonb;
|
|
||||||
pub mod like;
|
pub mod like;
|
||||||
pub mod notification;
|
pub mod notification;
|
||||||
pub mod outbox;
|
pub mod outbox;
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::test_helpers::seed_user_and_thought;
|
use crate::test_helpers::seed_user_and_thought;
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
|
use domain::value_objects::*;
|
||||||
|
|
||||||
#[sqlx::test(migrations = "./migrations")]
|
#[sqlx::test(migrations = "./migrations")]
|
||||||
async fn like_and_count(pool: sqlx::PgPool) {
|
async fn like_and_count(pool: sqlx::PgPool) {
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::test_helpers;
|
use crate::test_helpers;
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
use domain::models::notification::NotificationKind;
|
use domain::{
|
||||||
|
models::{notification::NotificationKind, user::User},
|
||||||
|
value_objects::*,
|
||||||
|
};
|
||||||
|
|
||||||
#[sqlx::test(migrations = "./migrations")]
|
#[sqlx::test(migrations = "./migrations")]
|
||||||
async fn save_and_list(pool: sqlx::PgPool) {
|
async fn save_and_list(pool: sqlx::PgPool) {
|
||||||
|
|||||||
@@ -32,9 +32,6 @@ fn aggregate_id(event: &DomainEvent) -> Uuid {
|
|||||||
DomainEvent::UserUnblocked { blocker_id, .. } => blocker_id.as_uuid(),
|
DomainEvent::UserUnblocked { blocker_id, .. } => blocker_id.as_uuid(),
|
||||||
DomainEvent::UserRegistered { user_id } => user_id.as_uuid(),
|
DomainEvent::UserRegistered { user_id } => user_id.as_uuid(),
|
||||||
DomainEvent::ProfileUpdated { user_id } => user_id.as_uuid(),
|
DomainEvent::ProfileUpdated { user_id } => user_id.as_uuid(),
|
||||||
DomainEvent::RemoteFollowAccepted { local_user_id, .. } => local_user_id.as_uuid(),
|
|
||||||
DomainEvent::RemoteFollowRejected { local_user_id, .. } => local_user_id.as_uuid(),
|
|
||||||
DomainEvent::ActorMoved { user_id, .. } => user_id.as_uuid(),
|
|
||||||
DomainEvent::MentionReceived { thought_id, .. } => thought_id.as_uuid(),
|
DomainEvent::MentionReceived { thought_id, .. } => thought_id.as_uuid(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,40 +18,14 @@ impl PgRemoteActorRepository {
|
|||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl RemoteActorRepository for PgRemoteActorRepository {
|
impl RemoteActorRepository for PgRemoteActorRepository {
|
||||||
async fn upsert(&self, a: &RemoteActor) -> Result<(), DomainError> {
|
async fn upsert(&self, a: &RemoteActor) -> Result<(), DomainError> {
|
||||||
let also_known_as: Option<Vec<&str>> = if a.also_known_as.is_empty() {
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some(a.also_known_as.iter().map(|s| s.as_str()).collect())
|
|
||||||
};
|
|
||||||
let attachment_json = crate::jsonb::serialize_name_value(&a.attachment);
|
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"INSERT INTO remote_actors(url,handle,display_name,avatar_url,last_fetched_at,
|
"INSERT INTO remote_actors(url,handle,display_name,avatar_url,last_fetched_at)
|
||||||
bio,banner_url,outbox_url,followers_url,following_url,also_known_as,attachment)
|
VALUES($1,$2,$3,$4,$5)
|
||||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)
|
ON CONFLICT(url) DO UPDATE SET handle=EXCLUDED.handle,display_name=EXCLUDED.display_name,
|
||||||
ON CONFLICT(url) DO UPDATE SET
|
avatar_url=EXCLUDED.avatar_url,last_fetched_at=EXCLUDED.last_fetched_at"
|
||||||
handle=EXCLUDED.handle,display_name=EXCLUDED.display_name,
|
|
||||||
avatar_url=EXCLUDED.avatar_url,last_fetched_at=EXCLUDED.last_fetched_at,
|
|
||||||
bio=EXCLUDED.bio,banner_url=EXCLUDED.banner_url,
|
|
||||||
outbox_url=EXCLUDED.outbox_url,followers_url=EXCLUDED.followers_url,
|
|
||||||
following_url=EXCLUDED.following_url,also_known_as=EXCLUDED.also_known_as,
|
|
||||||
attachment=EXCLUDED.attachment",
|
|
||||||
)
|
)
|
||||||
.bind(&a.url)
|
.bind(&a.url).bind(&a.handle).bind(&a.display_name).bind(&a.avatar_url).bind(a.last_fetched_at)
|
||||||
.bind(&a.handle)
|
.execute(&self.pool).await.into_domain().map(|_| ())
|
||||||
.bind(&a.display_name)
|
|
||||||
.bind(&a.avatar_url)
|
|
||||||
.bind(a.last_fetched_at)
|
|
||||||
.bind(&a.bio)
|
|
||||||
.bind(&a.banner_url)
|
|
||||||
.bind(&a.outbox_url)
|
|
||||||
.bind(&a.followers_url)
|
|
||||||
.bind(&a.following_url)
|
|
||||||
.bind(also_known_as.as_deref())
|
|
||||||
.bind(&attachment_json)
|
|
||||||
.execute(&self.pool)
|
|
||||||
.await
|
|
||||||
.into_domain()
|
|
||||||
.map(|_| ())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn find_by_url(&self, url: &str) -> Result<Option<RemoteActor>, DomainError> {
|
async fn find_by_url(&self, url: &str) -> Result<Option<RemoteActor>, DomainError> {
|
||||||
@@ -62,43 +36,24 @@ impl RemoteActorRepository for PgRemoteActorRepository {
|
|||||||
display_name: Option<String>,
|
display_name: Option<String>,
|
||||||
avatar_url: Option<String>,
|
avatar_url: Option<String>,
|
||||||
last_fetched_at: DateTime<Utc>,
|
last_fetched_at: DateTime<Utc>,
|
||||||
bio: Option<String>,
|
|
||||||
banner_url: Option<String>,
|
|
||||||
outbox_url: Option<String>,
|
|
||||||
followers_url: Option<String>,
|
|
||||||
following_url: Option<String>,
|
|
||||||
also_known_as: Option<Vec<String>>,
|
|
||||||
inbox_url: Option<String>,
|
|
||||||
shared_inbox_url: Option<String>,
|
|
||||||
attachment: Option<serde_json::Value>,
|
|
||||||
}
|
}
|
||||||
sqlx::query_as::<_, Row>(
|
sqlx::query_as::<_, Row>(
|
||||||
"SELECT url,handle,display_name,avatar_url,last_fetched_at,
|
"SELECT url,handle,display_name,avatar_url,last_fetched_at FROM remote_actors WHERE url=$1"
|
||||||
bio,banner_url,outbox_url,followers_url,following_url,also_known_as,
|
).bind(url).fetch_optional(&self.pool).await
|
||||||
inbox_url,shared_inbox_url,attachment
|
|
||||||
FROM remote_actors WHERE url=$1",
|
|
||||||
)
|
|
||||||
.bind(url)
|
|
||||||
.fetch_optional(&self.pool)
|
|
||||||
.await
|
|
||||||
.into_domain()
|
.into_domain()
|
||||||
.map(|o| {
|
.map(|o| o.map(|r| RemoteActor {
|
||||||
o.map(|r| RemoteActor {
|
|
||||||
url: r.url,
|
url: r.url,
|
||||||
handle: r.handle,
|
handle: r.handle,
|
||||||
display_name: r.display_name,
|
display_name: r.display_name,
|
||||||
avatar_url: r.avatar_url,
|
avatar_url: r.avatar_url,
|
||||||
last_fetched_at: r.last_fetched_at,
|
last_fetched_at: r.last_fetched_at,
|
||||||
bio: r.bio,
|
bio: None,
|
||||||
banner_url: r.banner_url,
|
banner_url: None,
|
||||||
also_known_as: r.also_known_as.unwrap_or_default(),
|
also_known_as: None,
|
||||||
outbox_url: r.outbox_url,
|
outbox_url: None,
|
||||||
followers_url: r.followers_url,
|
followers_url: None,
|
||||||
following_url: r.following_url,
|
following_url: None,
|
||||||
inbox_url: r.inbox_url,
|
attachment: vec![],
|
||||||
shared_inbox_url: r.shared_inbox_url,
|
}))
|
||||||
attachment: crate::jsonb::parse_name_value(r.attachment),
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,12 +12,6 @@ use domain::{
|
|||||||
};
|
};
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
|
|
||||||
#[derive(sqlx::FromRow)]
|
|
||||||
struct TagRow {
|
|
||||||
id: i32,
|
|
||||||
name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct PgTagRepository {
|
pub struct PgTagRepository {
|
||||||
pool: PgPool,
|
pool: PgPool,
|
||||||
}
|
}
|
||||||
@@ -36,7 +30,12 @@ impl TagRepository for PgTagRepository {
|
|||||||
.execute(&self.pool)
|
.execute(&self.pool)
|
||||||
.await
|
.await
|
||||||
.into_domain()?;
|
.into_domain()?;
|
||||||
let row = sqlx::query_as::<_, TagRow>("SELECT id,name FROM tags WHERE name=$1")
|
#[derive(sqlx::FromRow)]
|
||||||
|
struct Row {
|
||||||
|
id: i32,
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
let row = sqlx::query_as::<_, Row>("SELECT id,name FROM tags WHERE name=$1")
|
||||||
.bind(&name)
|
.bind(&name)
|
||||||
.fetch_one(&self.pool)
|
.fetch_one(&self.pool)
|
||||||
.await
|
.await
|
||||||
@@ -73,7 +72,12 @@ impl TagRepository for PgTagRepository {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn list_for_thought(&self, thought_id: &ThoughtId) -> Result<Vec<Tag>, DomainError> {
|
async fn list_for_thought(&self, thought_id: &ThoughtId) -> Result<Vec<Tag>, DomainError> {
|
||||||
sqlx::query_as::<_, TagRow>(
|
#[derive(sqlx::FromRow)]
|
||||||
|
struct Row {
|
||||||
|
id: i32,
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
sqlx::query_as::<_, Row>(
|
||||||
"SELECT t.id,t.name FROM tags t JOIN thought_tags tt ON tt.tag_id=t.id WHERE tt.thought_id=$1"
|
"SELECT t.id,t.name FROM tags t JOIN thought_tags tt ON tt.tag_id=t.id WHERE tt.thought_id=$1"
|
||||||
).bind(thought_id.as_uuid()).fetch_all(&self.pool).await
|
).bind(thought_id.as_uuid()).fetch_all(&self.pool).await
|
||||||
.into_domain()
|
.into_domain()
|
||||||
|
|||||||
@@ -37,7 +37,6 @@ async fn attach_and_list(pool: sqlx::PgPool) {
|
|||||||
visibility: Visibility::Public,
|
visibility: Visibility::Public,
|
||||||
content_warning: None,
|
content_warning: None,
|
||||||
sensitive: false,
|
sensitive: false,
|
||||||
mood: None,
|
|
||||||
});
|
});
|
||||||
trepo.save(&t).await.unwrap();
|
trepo.save(&t).await.unwrap();
|
||||||
let repo = PgTagRepository::new(pool);
|
let repo = PgTagRepository::new(pool);
|
||||||
|
|||||||
@@ -31,7 +31,6 @@ pub async fn seed_user_and_thought(pool: &sqlx::PgPool) -> (User, Thought) {
|
|||||||
visibility: Visibility::Public,
|
visibility: Visibility::Public,
|
||||||
content_warning: None,
|
content_warning: None,
|
||||||
sensitive: false,
|
sensitive: false,
|
||||||
mood: None,
|
|
||||||
});
|
});
|
||||||
trepo.save(&t).await.unwrap();
|
trepo.save(&t).await.unwrap();
|
||||||
(user, t)
|
(user, t)
|
||||||
|
|||||||
@@ -28,15 +28,12 @@ pub(crate) struct ThoughtRow {
|
|||||||
pub user_id: uuid::Uuid,
|
pub user_id: uuid::Uuid,
|
||||||
pub content: String,
|
pub content: String,
|
||||||
pub in_reply_to_id: Option<uuid::Uuid>,
|
pub in_reply_to_id: Option<uuid::Uuid>,
|
||||||
pub in_reply_to_url: Option<String>,
|
|
||||||
pub visibility: String,
|
pub visibility: String,
|
||||||
pub content_warning: Option<String>,
|
pub content_warning: Option<String>,
|
||||||
pub sensitive: bool,
|
pub sensitive: bool,
|
||||||
pub local: bool,
|
pub local: bool,
|
||||||
pub created_at: DateTime<Utc>,
|
pub created_at: DateTime<Utc>,
|
||||||
pub updated_at: Option<DateTime<Utc>>,
|
pub updated_at: Option<DateTime<Utc>>,
|
||||||
pub note_extensions: Option<serde_json::Value>,
|
|
||||||
pub mood: Option<String>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TryFrom<ThoughtRow> for Thought {
|
impl TryFrom<ThoughtRow> for Thought {
|
||||||
@@ -47,28 +44,25 @@ impl TryFrom<ThoughtRow> for Thought {
|
|||||||
user_id: UserId::from_uuid(r.user_id),
|
user_id: UserId::from_uuid(r.user_id),
|
||||||
content: Content::new_remote(r.content),
|
content: Content::new_remote(r.content),
|
||||||
in_reply_to_id: r.in_reply_to_id.map(ThoughtId::from_uuid),
|
in_reply_to_id: r.in_reply_to_id.map(ThoughtId::from_uuid),
|
||||||
in_reply_to_url: r.in_reply_to_url,
|
|
||||||
visibility: Visibility::from_db_str(&r.visibility)?,
|
visibility: Visibility::from_db_str(&r.visibility)?,
|
||||||
content_warning: r.content_warning,
|
content_warning: r.content_warning,
|
||||||
sensitive: r.sensitive,
|
sensitive: r.sensitive,
|
||||||
local: r.local,
|
local: r.local,
|
||||||
created_at: r.created_at,
|
created_at: r.created_at,
|
||||||
updated_at: r.updated_at,
|
updated_at: r.updated_at,
|
||||||
note_extensions: r.note_extensions,
|
|
||||||
mood: r.mood,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const THOUGHT_SELECT: &str =
|
const THOUGHT_SELECT: &str =
|
||||||
"SELECT id,user_id,content,in_reply_to_id,in_reply_to_url,visibility,content_warning,sensitive,local,created_at,updated_at,note_extensions,mood FROM thoughts";
|
"SELECT id,user_id,content,in_reply_to_id,visibility,content_warning,sensitive,local,created_at,updated_at FROM thoughts";
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl ThoughtRepository for PgThoughtRepository {
|
impl ThoughtRepository for PgThoughtRepository {
|
||||||
async fn save(&self, t: &Thought) -> Result<(), DomainError> {
|
async fn save(&self, t: &Thought) -> Result<(), DomainError> {
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"INSERT INTO thoughts(id,user_id,content,in_reply_to_id,visibility,content_warning,sensitive,local,created_at,mood)
|
"INSERT INTO thoughts(id,user_id,content,in_reply_to_id,visibility,content_warning,sensitive,local,created_at)
|
||||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)
|
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)
|
||||||
ON CONFLICT(id) DO UPDATE SET content=EXCLUDED.content,updated_at=NOW()"
|
ON CONFLICT(id) DO UPDATE SET content=EXCLUDED.content,updated_at=NOW()"
|
||||||
)
|
)
|
||||||
.bind(t.id.as_uuid())
|
.bind(t.id.as_uuid())
|
||||||
@@ -80,7 +74,6 @@ impl ThoughtRepository for PgThoughtRepository {
|
|||||||
.bind(t.sensitive)
|
.bind(t.sensitive)
|
||||||
.bind(t.local)
|
.bind(t.local)
|
||||||
.bind(t.created_at)
|
.bind(t.created_at)
|
||||||
.bind(&t.mood)
|
|
||||||
.execute(&self.pool)
|
.execute(&self.pool)
|
||||||
.await
|
.await
|
||||||
.into_domain()
|
.into_domain()
|
||||||
@@ -123,12 +116,12 @@ impl ThoughtRepository for PgThoughtRepository {
|
|||||||
// Recursive CTE: fetches the root thought and all nested replies at any depth.
|
// Recursive CTE: fetches the root thought and all nested replies at any depth.
|
||||||
sqlx::query_as::<_, ThoughtRow>(
|
sqlx::query_as::<_, ThoughtRow>(
|
||||||
"WITH RECURSIVE thread AS (
|
"WITH RECURSIVE thread AS (
|
||||||
SELECT id,user_id,content,in_reply_to_id,in_reply_to_url,
|
SELECT id,user_id,content,in_reply_to_id,
|
||||||
visibility,content_warning,sensitive,local,created_at,updated_at,note_extensions,mood
|
visibility,content_warning,sensitive,local,created_at,updated_at
|
||||||
FROM thoughts WHERE id = $1
|
FROM thoughts WHERE id = $1
|
||||||
UNION ALL
|
UNION ALL
|
||||||
SELECT t.id,t.user_id,t.content,t.in_reply_to_id,t.in_reply_to_url,
|
SELECT t.id,t.user_id,t.content,t.in_reply_to_id,
|
||||||
t.visibility,t.content_warning,t.sensitive,t.local,t.created_at,t.updated_at,t.note_extensions,t.mood
|
t.visibility,t.content_warning,t.sensitive,t.local,t.created_at,t.updated_at
|
||||||
FROM thoughts t JOIN thread ON t.in_reply_to_id = thread.id
|
FROM thoughts t JOIN thread ON t.in_reply_to_id = thread.id
|
||||||
)
|
)
|
||||||
SELECT * FROM thread ORDER BY created_at ASC",
|
SELECT * FROM thread ORDER BY created_at ASC",
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::test_helpers::seed_user;
|
use crate::test_helpers::seed_user;
|
||||||
use domain::models::thought::{NewThought, Thought, Visibility};
|
use domain::{
|
||||||
|
models::thought::{NewThought, Thought, Visibility},
|
||||||
|
value_objects::*,
|
||||||
|
};
|
||||||
|
|
||||||
#[sqlx::test(migrations = "./migrations")]
|
#[sqlx::test(migrations = "./migrations")]
|
||||||
async fn save_and_find_thought(pool: sqlx::PgPool) {
|
async fn save_and_find_thought(pool: sqlx::PgPool) {
|
||||||
@@ -14,7 +17,6 @@ async fn save_and_find_thought(pool: sqlx::PgPool) {
|
|||||||
visibility: Visibility::Public,
|
visibility: Visibility::Public,
|
||||||
content_warning: None,
|
content_warning: None,
|
||||||
sensitive: false,
|
sensitive: false,
|
||||||
mood: None,
|
|
||||||
});
|
});
|
||||||
repo.save(&t).await.unwrap();
|
repo.save(&t).await.unwrap();
|
||||||
let found = repo.find_by_id(&t.id).await.unwrap().unwrap();
|
let found = repo.find_by_id(&t.id).await.unwrap().unwrap();
|
||||||
@@ -34,7 +36,6 @@ async fn delete_thought(pool: sqlx::PgPool) {
|
|||||||
visibility: Visibility::Public,
|
visibility: Visibility::Public,
|
||||||
content_warning: None,
|
content_warning: None,
|
||||||
sensitive: false,
|
sensitive: false,
|
||||||
mood: None,
|
|
||||||
});
|
});
|
||||||
repo.save(&t).await.unwrap();
|
repo.save(&t).await.unwrap();
|
||||||
repo.delete(&t.id, &user.id).await.unwrap();
|
repo.delete(&t.id, &user.id).await.unwrap();
|
||||||
@@ -54,7 +55,6 @@ async fn delete_wrong_owner_returns_not_found(pool: sqlx::PgPool) {
|
|||||||
visibility: Visibility::Public,
|
visibility: Visibility::Public,
|
||||||
content_warning: None,
|
content_warning: None,
|
||||||
sensitive: false,
|
sensitive: false,
|
||||||
mood: None,
|
|
||||||
});
|
});
|
||||||
repo.save(&t).await.unwrap();
|
repo.save(&t).await.unwrap();
|
||||||
let err = repo.delete(&t.id, &bob.id).await.unwrap_err();
|
let err = repo.delete(&t.id, &bob.id).await.unwrap_err();
|
||||||
@@ -73,7 +73,6 @@ async fn get_thread_returns_root_and_replies(pool: sqlx::PgPool) {
|
|||||||
visibility: Visibility::Public,
|
visibility: Visibility::Public,
|
||||||
content_warning: None,
|
content_warning: None,
|
||||||
sensitive: false,
|
sensitive: false,
|
||||||
mood: None,
|
|
||||||
});
|
});
|
||||||
let reply = Thought::new_local(NewThought {
|
let reply = Thought::new_local(NewThought {
|
||||||
id: ThoughtId::new(),
|
id: ThoughtId::new(),
|
||||||
@@ -83,7 +82,6 @@ async fn get_thread_returns_root_and_replies(pool: sqlx::PgPool) {
|
|||||||
visibility: Visibility::Public,
|
visibility: Visibility::Public,
|
||||||
content_warning: None,
|
content_warning: None,
|
||||||
sensitive: false,
|
sensitive: false,
|
||||||
mood: None,
|
|
||||||
});
|
});
|
||||||
repo.save(&root).await.unwrap();
|
repo.save(&root).await.unwrap();
|
||||||
repo.save(&reply).await.unwrap();
|
repo.save(&reply).await.unwrap();
|
||||||
|
|||||||
@@ -44,17 +44,27 @@ impl TopFriendRepository for PgTopFriendRepository {
|
|||||||
|
|
||||||
async fn list_for_user(&self, user_id: &UserId) -> Result<Vec<(TopFriend, User)>, DomainError> {
|
async fn list_for_user(&self, user_id: &UserId) -> Result<Vec<(TopFriend, User)>, DomainError> {
|
||||||
#[derive(sqlx::FromRow)]
|
#[derive(sqlx::FromRow)]
|
||||||
struct TopFriendRow {
|
struct Row {
|
||||||
tf_user_id: uuid::Uuid,
|
tf_user_id: uuid::Uuid,
|
||||||
friend_id: uuid::Uuid,
|
friend_id: uuid::Uuid,
|
||||||
position: i16,
|
position: i16,
|
||||||
#[sqlx(flatten)]
|
id: uuid::Uuid,
|
||||||
user: crate::user::UserRow,
|
username: String,
|
||||||
|
email: String,
|
||||||
|
password_hash: String,
|
||||||
|
display_name: Option<String>,
|
||||||
|
bio: Option<String>,
|
||||||
|
avatar_url: Option<String>,
|
||||||
|
header_url: Option<String>,
|
||||||
|
custom_css: Option<String>,
|
||||||
|
local: bool,
|
||||||
|
created_at: chrono::DateTime<chrono::Utc>,
|
||||||
|
updated_at: chrono::DateTime<chrono::Utc>,
|
||||||
}
|
}
|
||||||
let rows = sqlx::query_as::<_, TopFriendRow>(
|
let rows = sqlx::query_as::<_, Row>(
|
||||||
"SELECT tf.user_id AS tf_user_id, tf.friend_id, tf.position,
|
"SELECT tf.user_id AS tf_user_id, tf.friend_id, tf.position,
|
||||||
u.id, u.username, u.email, u.password_hash, u.display_name, u.bio,
|
u.id, u.username, u.email, u.password_hash, u.display_name, u.bio,
|
||||||
u.avatar_url, u.header_url, u.custom_css, u.profile_fields, u.custom_moods, u.local,
|
u.avatar_url, u.header_url, u.custom_css, u.local,
|
||||||
u.created_at, u.updated_at
|
u.created_at, u.updated_at
|
||||||
FROM top_friends tf JOIN users u ON u.id=tf.friend_id
|
FROM top_friends tf JOIN users u ON u.id=tf.friend_id
|
||||||
WHERE tf.user_id=$1 ORDER BY tf.position",
|
WHERE tf.user_id=$1 ORDER BY tf.position",
|
||||||
@@ -67,12 +77,27 @@ impl TopFriendRepository for PgTopFriendRepository {
|
|||||||
Ok(rows
|
Ok(rows
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|r| {
|
.map(|r| {
|
||||||
|
use domain::value_objects::{Email, PasswordHash, Username};
|
||||||
let tf = TopFriend {
|
let tf = TopFriend {
|
||||||
user_id: UserId::from_uuid(r.tf_user_id),
|
user_id: UserId::from_uuid(r.tf_user_id),
|
||||||
friend_id: UserId::from_uuid(r.friend_id),
|
friend_id: UserId::from_uuid(r.friend_id),
|
||||||
position: r.position,
|
position: r.position,
|
||||||
};
|
};
|
||||||
(tf, User::from(r.user))
|
let u = User {
|
||||||
|
id: UserId::from_uuid(r.id),
|
||||||
|
username: Username::from_trusted(r.username),
|
||||||
|
email: Email::from_trusted(r.email),
|
||||||
|
password_hash: PasswordHash(r.password_hash),
|
||||||
|
display_name: r.display_name,
|
||||||
|
bio: r.bio,
|
||||||
|
avatar_url: r.avatar_url,
|
||||||
|
header_url: r.header_url,
|
||||||
|
custom_css: r.custom_css,
|
||||||
|
local: r.local,
|
||||||
|
created_at: r.created_at,
|
||||||
|
updated_at: r.updated_at,
|
||||||
|
};
|
||||||
|
(tf, u)
|
||||||
})
|
})
|
||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,8 +31,6 @@ pub struct UserRow {
|
|||||||
pub avatar_url: Option<String>,
|
pub avatar_url: Option<String>,
|
||||||
pub header_url: Option<String>,
|
pub header_url: Option<String>,
|
||||||
pub custom_css: Option<String>,
|
pub custom_css: Option<String>,
|
||||||
pub profile_fields: Option<serde_json::Value>,
|
|
||||||
pub custom_moods: Option<serde_json::Value>,
|
|
||||||
pub local: bool,
|
pub local: bool,
|
||||||
pub created_at: DateTime<Utc>,
|
pub created_at: DateTime<Utc>,
|
||||||
pub updated_at: DateTime<Utc>,
|
pub updated_at: DateTime<Utc>,
|
||||||
@@ -50,8 +48,6 @@ impl From<UserRow> for User {
|
|||||||
avatar_url: r.avatar_url,
|
avatar_url: r.avatar_url,
|
||||||
header_url: r.header_url,
|
header_url: r.header_url,
|
||||||
custom_css: r.custom_css,
|
custom_css: r.custom_css,
|
||||||
profile_fields: crate::jsonb::parse_name_value(r.profile_fields),
|
|
||||||
custom_moods: crate::jsonb::parse_name_value(r.custom_moods),
|
|
||||||
local: r.local,
|
local: r.local,
|
||||||
created_at: r.created_at,
|
created_at: r.created_at,
|
||||||
updated_at: r.updated_at,
|
updated_at: r.updated_at,
|
||||||
@@ -61,7 +57,7 @@ impl From<UserRow> for User {
|
|||||||
|
|
||||||
pub const USER_SELECT: &str =
|
pub const USER_SELECT: &str =
|
||||||
"SELECT id,username,email,password_hash,display_name,bio,avatar_url,header_url,\
|
"SELECT id,username,email,password_hash,display_name,bio,avatar_url,header_url,\
|
||||||
custom_css,profile_fields,custom_moods,local,created_at,updated_at FROM users";
|
custom_css,local,created_at,updated_at FROM users";
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl UserReader for PgUserRepository {
|
impl UserReader for PgUserRepository {
|
||||||
@@ -226,18 +222,14 @@ impl UserReader for PgUserRepository {
|
|||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl UserWriter for PgUserRepository {
|
impl UserWriter for PgUserRepository {
|
||||||
async fn save(&self, user: &User) -> Result<(), DomainError> {
|
async fn save(&self, user: &User) -> Result<(), DomainError> {
|
||||||
let profile_fields_json = crate::jsonb::serialize_name_value(&user.profile_fields);
|
|
||||||
let custom_moods_json = crate::jsonb::serialize_name_value(&user.custom_moods);
|
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"INSERT INTO users (id,username,email,password_hash,display_name,bio,avatar_url,header_url,custom_css,profile_fields,custom_moods,local,created_at,updated_at)
|
"INSERT INTO users (id,username,email,password_hash,display_name,bio,avatar_url,header_url,custom_css,local,created_at,updated_at)
|
||||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14)
|
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)
|
||||||
ON CONFLICT(id) DO UPDATE SET
|
ON CONFLICT(id) DO UPDATE SET
|
||||||
username=EXCLUDED.username, email=EXCLUDED.email,
|
username=EXCLUDED.username, email=EXCLUDED.email,
|
||||||
password_hash=EXCLUDED.password_hash, display_name=EXCLUDED.display_name,
|
password_hash=EXCLUDED.password_hash, display_name=EXCLUDED.display_name,
|
||||||
bio=EXCLUDED.bio, avatar_url=EXCLUDED.avatar_url,
|
bio=EXCLUDED.bio, avatar_url=EXCLUDED.avatar_url,
|
||||||
header_url=EXCLUDED.header_url, custom_css=EXCLUDED.custom_css,
|
header_url=EXCLUDED.header_url, custom_css=EXCLUDED.custom_css,
|
||||||
profile_fields=EXCLUDED.profile_fields,
|
|
||||||
custom_moods=EXCLUDED.custom_moods,
|
|
||||||
local=EXCLUDED.local,
|
local=EXCLUDED.local,
|
||||||
updated_at=NOW()"
|
updated_at=NOW()"
|
||||||
)
|
)
|
||||||
@@ -250,8 +242,6 @@ impl UserWriter for PgUserRepository {
|
|||||||
.bind(&user.avatar_url)
|
.bind(&user.avatar_url)
|
||||||
.bind(&user.header_url)
|
.bind(&user.header_url)
|
||||||
.bind(&user.custom_css)
|
.bind(&user.custom_css)
|
||||||
.bind(&profile_fields_json)
|
|
||||||
.bind(&custom_moods_json)
|
|
||||||
.bind(user.local)
|
.bind(user.local)
|
||||||
.bind(user.created_at)
|
.bind(user.created_at)
|
||||||
.bind(user.updated_at)
|
.bind(user.updated_at)
|
||||||
@@ -277,25 +267,8 @@ impl UserWriter for PgUserRepository {
|
|||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
input: UpdateProfileInput,
|
input: UpdateProfileInput,
|
||||||
) -> Result<(), DomainError> {
|
) -> Result<(), DomainError> {
|
||||||
let profile_fields_json: Option<serde_json::Value> = input
|
|
||||||
.profile_fields
|
|
||||||
.as_ref()
|
|
||||||
.map(|f| crate::jsonb::serialize_name_value(f));
|
|
||||||
let custom_moods_json: Option<serde_json::Value> = input
|
|
||||||
.custom_moods
|
|
||||||
.as_ref()
|
|
||||||
.map(|f| crate::jsonb::serialize_name_value(f));
|
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"UPDATE users SET \
|
"UPDATE users SET display_name=$2,bio=$3,avatar_url=$4,header_url=$5,custom_css=$6,updated_at=NOW() WHERE id=$1"
|
||||||
display_name = COALESCE($2, display_name), \
|
|
||||||
bio = COALESCE($3, bio), \
|
|
||||||
avatar_url = COALESCE($4, avatar_url), \
|
|
||||||
header_url = COALESCE($5, header_url), \
|
|
||||||
custom_css = COALESCE($6, custom_css), \
|
|
||||||
profile_fields = COALESCE($7, profile_fields), \
|
|
||||||
custom_moods = COALESCE($8, custom_moods), \
|
|
||||||
updated_at = NOW() \
|
|
||||||
WHERE id = $1",
|
|
||||||
)
|
)
|
||||||
.bind(user_id.as_uuid())
|
.bind(user_id.as_uuid())
|
||||||
.bind(input.display_name)
|
.bind(input.display_name)
|
||||||
@@ -303,22 +276,6 @@ impl UserWriter for PgUserRepository {
|
|||||||
.bind(input.avatar_url)
|
.bind(input.avatar_url)
|
||||||
.bind(input.header_url)
|
.bind(input.header_url)
|
||||||
.bind(input.custom_css)
|
.bind(input.custom_css)
|
||||||
.bind(profile_fields_json)
|
|
||||||
.bind(custom_moods_json)
|
|
||||||
.execute(&self.pool)
|
|
||||||
.await
|
|
||||||
.into_domain()
|
|
||||||
.map(|_| ())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn set_also_known_as(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
value: Option<String>,
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
sqlx::query("UPDATE users SET also_known_as = $2, updated_at = NOW() WHERE id = $1")
|
|
||||||
.bind(user_id.as_uuid())
|
|
||||||
.bind(value)
|
|
||||||
.execute(&self.pool)
|
.execute(&self.pool)
|
||||||
.await
|
.await
|
||||||
.into_domain()
|
.into_domain()
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
use domain::models::user::{UpdateProfileInput, User};
|
use domain::{
|
||||||
|
models::user::{UpdateProfileInput, User},
|
||||||
|
value_objects::*,
|
||||||
|
};
|
||||||
|
|
||||||
#[sqlx::test(migrations = "./migrations")]
|
#[sqlx::test(migrations = "./migrations")]
|
||||||
async fn save_and_find_by_id(pool: sqlx::PgPool) {
|
async fn save_and_find_by_id(pool: sqlx::PgPool) {
|
||||||
|
|||||||
@@ -1,18 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "storage"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2021"
|
|
||||||
|
|
||||||
[features]
|
|
||||||
s3 = ["object_store/aws"]
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
domain = { workspace = true }
|
|
||||||
async-trait = { workspace = true }
|
|
||||||
bytes = { workspace = true }
|
|
||||||
futures = { workspace = true }
|
|
||||||
anyhow = { workspace = true }
|
|
||||||
object_store = { version = "0.11" }
|
|
||||||
|
|
||||||
[dev-dependencies]
|
|
||||||
tokio = { workspace = true, features = ["full"] }
|
|
||||||
@@ -1,237 +0,0 @@
|
|||||||
use async_trait::async_trait;
|
|
||||||
use domain::{
|
|
||||||
errors::DomainError,
|
|
||||||
ports::{DataStream, MediaStore},
|
|
||||||
};
|
|
||||||
use futures::stream::StreamExt;
|
|
||||||
use object_store::{path::Path, Error as OsError, ObjectStore};
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
pub struct ObjectStorageAdapter {
|
|
||||||
store: Arc<dyn ObjectStore>,
|
|
||||||
prefix: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn validate_key(key: &str) -> Result<(), DomainError> {
|
|
||||||
if key.is_empty() {
|
|
||||||
return Err(DomainError::InvalidInput(
|
|
||||||
"storage key must not be empty".into(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
if key.starts_with('/') {
|
|
||||||
return Err(DomainError::InvalidInput(format!(
|
|
||||||
"storage key must not start with '/': {key}"
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
if key.split('/').any(|seg| seg == ".." || seg == ".") {
|
|
||||||
return Err(DomainError::InvalidInput(format!(
|
|
||||||
"storage key contains invalid path segment: {key}"
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn map_os_err(e: OsError) -> DomainError {
|
|
||||||
match e {
|
|
||||||
OsError::NotFound { .. } => DomainError::NotFound,
|
|
||||||
e => DomainError::Internal(e.to_string()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ObjectStorageAdapter {
|
|
||||||
pub fn new(
|
|
||||||
store: Arc<dyn ObjectStore>,
|
|
||||||
prefix: impl Into<String>,
|
|
||||||
) -> Result<Self, DomainError> {
|
|
||||||
let prefix = prefix.into();
|
|
||||||
if !prefix.is_empty() {
|
|
||||||
validate_key(&prefix)?;
|
|
||||||
}
|
|
||||||
Ok(Self { store, prefix })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn path(&self, key: &str) -> Path {
|
|
||||||
if self.prefix.is_empty() {
|
|
||||||
Path::from(key)
|
|
||||||
} else {
|
|
||||||
Path::from(format!("{}/{key}", self.prefix))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl MediaStore for ObjectStorageAdapter {
|
|
||||||
async fn put(&self, key: &str, data: DataStream) -> Result<(), DomainError> {
|
|
||||||
validate_key(key)?;
|
|
||||||
let path = self.path(key);
|
|
||||||
let mut upload = self
|
|
||||||
.store
|
|
||||||
.put_multipart(&path)
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::Internal(e.to_string()))?;
|
|
||||||
let mut stream = data;
|
|
||||||
while let Some(result) = stream.next().await {
|
|
||||||
match result {
|
|
||||||
Ok(bytes) => {
|
|
||||||
if let Err(e) = upload.put_part(bytes.into()).await {
|
|
||||||
let _ = upload.abort().await;
|
|
||||||
return Err(DomainError::Internal(e.to_string()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
let _ = upload.abort().await;
|
|
||||||
return Err(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
upload
|
|
||||||
.complete()
|
|
||||||
.await
|
|
||||||
.map(|_| ())
|
|
||||||
.map_err(|e| DomainError::Internal(e.to_string()))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get(&self, key: &str) -> Result<DataStream, DomainError> {
|
|
||||||
validate_key(key)?;
|
|
||||||
let path = self.path(key);
|
|
||||||
let result = self.store.get(&path).await.map_err(map_os_err)?;
|
|
||||||
let s = result
|
|
||||||
.into_stream()
|
|
||||||
.map(|r| r.map_err(|e| DomainError::Internal(e.to_string())));
|
|
||||||
Ok(Box::pin(s))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn delete(&self, key: &str) -> Result<(), DomainError> {
|
|
||||||
validate_key(key)?;
|
|
||||||
let path = self.path(key);
|
|
||||||
match self.store.delete(&path).await {
|
|
||||||
Ok(()) => Ok(()),
|
|
||||||
Err(OsError::NotFound { .. }) => Ok(()),
|
|
||||||
Err(e) => Err(DomainError::Internal(e.to_string())),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use bytes::Bytes;
|
|
||||||
use futures::stream;
|
|
||||||
use object_store::memory::InMemory;
|
|
||||||
|
|
||||||
fn make_adapter() -> ObjectStorageAdapter {
|
|
||||||
ObjectStorageAdapter::new(Arc::new(InMemory::new()), "test").unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn one_shot(data: &'static [u8]) -> DataStream {
|
|
||||||
Box::pin(stream::once(async move { Ok(Bytes::from(data)) }))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn put_get_roundtrip() {
|
|
||||||
let a = make_adapter();
|
|
||||||
a.put("hello.txt", one_shot(b"world")).await.unwrap();
|
|
||||||
let mut s = a.get("hello.txt").await.unwrap();
|
|
||||||
let mut out = Vec::new();
|
|
||||||
while let Some(chunk) = s.next().await {
|
|
||||||
out.extend_from_slice(&chunk.unwrap());
|
|
||||||
}
|
|
||||||
assert_eq!(out, b"world");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn get_missing_is_not_found() {
|
|
||||||
let a = make_adapter();
|
|
||||||
assert!(matches!(
|
|
||||||
a.get("nope.txt").await,
|
|
||||||
Err(DomainError::NotFound)
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn delete_is_idempotent() {
|
|
||||||
let a = make_adapter();
|
|
||||||
a.delete("nope.txt").await.unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn delete_removes_key() {
|
|
||||||
let a = make_adapter();
|
|
||||||
a.put("file.txt", one_shot(b"data")).await.unwrap();
|
|
||||||
a.delete("file.txt").await.unwrap();
|
|
||||||
assert!(matches!(
|
|
||||||
a.get("file.txt").await,
|
|
||||||
Err(DomainError::NotFound)
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn put_overwrites_existing() {
|
|
||||||
let a = make_adapter();
|
|
||||||
a.put("file.txt", one_shot(b"v1")).await.unwrap();
|
|
||||||
a.put("file.txt", one_shot(b"v2")).await.unwrap();
|
|
||||||
let mut s = a.get("file.txt").await.unwrap();
|
|
||||||
let mut out = Vec::new();
|
|
||||||
while let Some(chunk) = s.next().await {
|
|
||||||
out.extend_from_slice(&chunk.unwrap());
|
|
||||||
}
|
|
||||||
assert_eq!(out, b"v2");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn rejects_empty_key() {
|
|
||||||
let a = make_adapter();
|
|
||||||
assert!(matches!(
|
|
||||||
a.put("", one_shot(b"x")).await,
|
|
||||||
Err(DomainError::InvalidInput(_))
|
|
||||||
));
|
|
||||||
assert!(matches!(a.get("").await, Err(DomainError::InvalidInput(_))));
|
|
||||||
assert!(matches!(
|
|
||||||
a.delete("").await,
|
|
||||||
Err(DomainError::InvalidInput(_))
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn rejects_absolute_key() {
|
|
||||||
let a = make_adapter();
|
|
||||||
assert!(matches!(
|
|
||||||
a.put("/etc/passwd", one_shot(b"x")).await,
|
|
||||||
Err(DomainError::InvalidInput(_))
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn rejects_path_traversal() {
|
|
||||||
let a = make_adapter();
|
|
||||||
assert!(matches!(
|
|
||||||
a.get("../escape").await,
|
|
||||||
Err(DomainError::InvalidInput(_))
|
|
||||||
));
|
|
||||||
assert!(matches!(
|
|
||||||
a.get("a/../../../etc").await,
|
|
||||||
Err(DomainError::InvalidInput(_))
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn new_rejects_traversal_prefix() {
|
|
||||||
assert!(matches!(
|
|
||||||
ObjectStorageAdapter::new(Arc::new(InMemory::new()), "../evil"),
|
|
||||||
Err(DomainError::InvalidInput(_))
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn new_rejects_absolute_prefix() {
|
|
||||||
assert!(matches!(
|
|
||||||
ObjectStorageAdapter::new(Arc::new(InMemory::new()), "/root"),
|
|
||||||
Err(DomainError::InvalidInput(_))
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn new_accepts_empty_prefix() {
|
|
||||||
assert!(ObjectStorageAdapter::new(Arc::new(InMemory::new()), "").is_ok());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
use anyhow::{Context, Result};
|
|
||||||
use object_store::local::LocalFileSystem;
|
|
||||||
use object_store::ObjectStore;
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct StorageConfig {
|
|
||||||
pub backend: String,
|
|
||||||
pub local_path: Option<String>,
|
|
||||||
pub s3_endpoint: Option<String>,
|
|
||||||
pub s3_access_key_id: Option<String>,
|
|
||||||
pub s3_secret_access_key: Option<String>,
|
|
||||||
pub s3_bucket: Option<String>,
|
|
||||||
pub s3_region: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn build_store(config: &StorageConfig) -> Result<Arc<dyn ObjectStore>> {
|
|
||||||
match config.backend.as_str() {
|
|
||||||
"local" => {
|
|
||||||
let path = config
|
|
||||||
.local_path
|
|
||||||
.as_deref()
|
|
||||||
.context("STORAGE_PATH must be set when STORAGE_BACKEND=local")?;
|
|
||||||
std::fs::create_dir_all(path)
|
|
||||||
.with_context(|| format!("failed to create storage dir: {path}"))?;
|
|
||||||
let store = LocalFileSystem::new_with_prefix(path)?;
|
|
||||||
Ok(Arc::new(store))
|
|
||||||
}
|
|
||||||
#[cfg(feature = "s3")]
|
|
||||||
"s3" => {
|
|
||||||
use object_store::aws::AmazonS3Builder;
|
|
||||||
let store = AmazonS3Builder::new()
|
|
||||||
.with_endpoint(
|
|
||||||
config
|
|
||||||
.s3_endpoint
|
|
||||||
.as_deref()
|
|
||||||
.context("S3_ENDPOINT must be set")?,
|
|
||||||
)
|
|
||||||
.with_access_key_id(
|
|
||||||
config
|
|
||||||
.s3_access_key_id
|
|
||||||
.as_deref()
|
|
||||||
.context("S3_ACCESS_KEY_ID must be set")?,
|
|
||||||
)
|
|
||||||
.with_secret_access_key(
|
|
||||||
config
|
|
||||||
.s3_secret_access_key
|
|
||||||
.as_deref()
|
|
||||||
.context("S3_SECRET_ACCESS_KEY must be set")?,
|
|
||||||
)
|
|
||||||
.with_bucket_name(
|
|
||||||
config
|
|
||||||
.s3_bucket
|
|
||||||
.as_deref()
|
|
||||||
.context("S3_BUCKET must be set")?,
|
|
||||||
)
|
|
||||||
.with_region(config.s3_region.as_deref().unwrap_or("us-east-1"))
|
|
||||||
.with_allow_http(true)
|
|
||||||
.build()?;
|
|
||||||
Ok(Arc::new(store))
|
|
||||||
}
|
|
||||||
other => anyhow::bail!(
|
|
||||||
"unknown STORAGE_BACKEND={other:?}; supported: local{}",
|
|
||||||
if cfg!(feature = "s3") { ", s3" } else { "" },
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
pub mod adapter;
|
|
||||||
pub mod config;
|
|
||||||
|
|
||||||
pub use adapter::ObjectStorageAdapter;
|
|
||||||
pub use config::{build_store, StorageConfig};
|
|
||||||
@@ -5,7 +5,6 @@ edition = "2021"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
serde = { workspace = true }
|
serde = { workspace = true }
|
||||||
serde_json = { workspace = true }
|
|
||||||
uuid = { workspace = true }
|
uuid = { workspace = true }
|
||||||
chrono = { workspace = true }
|
chrono = { workspace = true }
|
||||||
utoipa = { version = "5.5.0", features = ["uuid", "chrono"] }
|
utoipa = { version = "5.5.0", features = ["uuid", "chrono"] }
|
||||||
|
|||||||
@@ -31,7 +31,6 @@ pub struct CreateThoughtRequest {
|
|||||||
pub visibility: Option<String>,
|
pub visibility: Option<String>,
|
||||||
pub content_warning: Option<String>,
|
pub content_warning: Option<String>,
|
||||||
pub sensitive: Option<bool>,
|
pub sensitive: Option<bool>,
|
||||||
pub mood: Option<String>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize, utoipa::ToSchema)]
|
#[derive(Deserialize, utoipa::ToSchema)]
|
||||||
@@ -48,8 +47,6 @@ pub struct UpdateProfileRequest {
|
|||||||
pub avatar_url: Option<String>,
|
pub avatar_url: Option<String>,
|
||||||
pub header_url: Option<String>,
|
pub header_url: Option<String>,
|
||||||
pub custom_css: Option<String>,
|
pub custom_css: Option<String>,
|
||||||
pub profile_fields: Option<Vec<crate::responses::ProfileField>>,
|
|
||||||
pub custom_moods: Option<Vec<crate::responses::ProfileField>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize, utoipa::ToSchema)]
|
#[derive(Deserialize, utoipa::ToSchema)]
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use chrono::{DateTime, Utc};
|
use chrono::{DateTime, Utc};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::Serialize;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
#[derive(Serialize, utoipa::ToSchema)]
|
#[derive(Serialize, utoipa::ToSchema)]
|
||||||
@@ -19,8 +19,6 @@ pub struct UserResponse {
|
|||||||
pub avatar_url: Option<String>,
|
pub avatar_url: Option<String>,
|
||||||
pub header_url: Option<String>,
|
pub header_url: Option<String>,
|
||||||
pub custom_css: Option<String>,
|
pub custom_css: Option<String>,
|
||||||
pub profile_fields: Vec<ProfileField>,
|
|
||||||
pub custom_moods: Vec<ProfileField>,
|
|
||||||
pub local: bool,
|
pub local: bool,
|
||||||
pub is_followed_by_viewer: bool,
|
pub is_followed_by_viewer: bool,
|
||||||
#[serde(rename = "joinedAt")]
|
#[serde(rename = "joinedAt")]
|
||||||
@@ -47,10 +45,6 @@ pub struct ThoughtResponse {
|
|||||||
pub boosted_by_viewer: bool,
|
pub boosted_by_viewer: bool,
|
||||||
pub created_at: DateTime<Utc>,
|
pub created_at: DateTime<Utc>,
|
||||||
pub updated_at: Option<DateTime<Utc>>,
|
pub updated_at: Option<DateTime<Utc>>,
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub note_extensions: Option<serde_json::Value>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub mood: Option<String>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, utoipa::ToSchema)]
|
#[derive(Serialize, utoipa::ToSchema)]
|
||||||
@@ -87,13 +81,6 @@ pub struct TopFriendsResponse {
|
|||||||
pub top_friends: Vec<UserResponse>,
|
pub top_friends: Vec<UserResponse>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, utoipa::ToSchema)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
pub struct NotificationSummaryResponse {
|
|
||||||
pub total: i64,
|
|
||||||
pub unread: u64,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, utoipa::ToSchema)]
|
#[derive(Serialize, utoipa::ToSchema)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct ErrorResponse {
|
pub struct ErrorResponse {
|
||||||
@@ -105,12 +92,11 @@ pub struct ErrorResponse {
|
|||||||
pub struct CreatedApiKeyResponse {
|
pub struct CreatedApiKeyResponse {
|
||||||
pub id: Uuid,
|
pub id: Uuid,
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub created_at: DateTime<Utc>,
|
|
||||||
/// Raw API key — shown only once at creation
|
/// Raw API key — shown only once at creation
|
||||||
pub key: String,
|
pub key: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, utoipa::ToSchema)]
|
#[derive(Serialize, Clone, utoipa::ToSchema)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct ProfileField {
|
pub struct ProfileField {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
@@ -126,7 +112,7 @@ pub struct RemoteActorResponse {
|
|||||||
pub url: String,
|
pub url: String,
|
||||||
pub bio: Option<String>,
|
pub bio: Option<String>,
|
||||||
pub banner_url: Option<String>,
|
pub banner_url: Option<String>,
|
||||||
pub also_known_as: Vec<String>,
|
pub also_known_as: Option<String>,
|
||||||
pub outbox_url: Option<String>,
|
pub outbox_url: Option<String>,
|
||||||
pub followers_url: Option<String>,
|
pub followers_url: Option<String>,
|
||||||
pub following_url: Option<String>,
|
pub following_url: Option<String>,
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ edition = "2021"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
domain = { workspace = true }
|
domain = { workspace = true }
|
||||||
|
activitypub = { workspace = true }
|
||||||
async-trait = { workspace = true }
|
async-trait = { workspace = true }
|
||||||
thiserror = { workspace = true }
|
thiserror = { workspace = true }
|
||||||
uuid = { workspace = true }
|
uuid = { workspace = true }
|
||||||
@@ -14,10 +15,7 @@ hex = "0.4"
|
|||||||
tracing = { workspace = true }
|
tracing = { workspace = true }
|
||||||
url = { workspace = true }
|
url = { workspace = true }
|
||||||
tokio = { workspace = true }
|
tokio = { workspace = true }
|
||||||
bytes = { workspace = true }
|
|
||||||
futures = { workspace = true }
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tokio = { workspace = true, features = ["full"] }
|
tokio = { workspace = true, features = ["full"] }
|
||||||
domain = { workspace = true, features = ["test-helpers"] }
|
domain = { workspace = true, features = ["test-helpers"] }
|
||||||
serde_json = { workspace = true }
|
|
||||||
|
|||||||
@@ -1,22 +1,19 @@
|
|||||||
|
use activitypub::{ActivityPubRepository, OutboundFederationPort};
|
||||||
use domain::{
|
use domain::{
|
||||||
errors::DomainError,
|
errors::DomainError,
|
||||||
events::DomainEvent,
|
events::DomainEvent,
|
||||||
models::thought::Visibility,
|
models::thought::Visibility,
|
||||||
ports::{FederationBroadcastPort, FederationContentRepository, ThoughtRepository, UserReader},
|
ports::{ThoughtRepository, UserReader},
|
||||||
value_objects::ThoughtId,
|
value_objects::ThoughtId,
|
||||||
};
|
};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
fn should_broadcast(t: &domain::models::thought::Thought) -> bool {
|
|
||||||
t.local && matches!(t.visibility, Visibility::Public | Visibility::Unlisted)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct FederationEventService {
|
pub struct FederationEventService {
|
||||||
pub thoughts: Arc<dyn ThoughtRepository>,
|
pub thoughts: Arc<dyn ThoughtRepository>,
|
||||||
pub users: Arc<dyn UserReader>,
|
pub users: Arc<dyn UserReader>,
|
||||||
pub ap: Arc<dyn FederationBroadcastPort>,
|
pub ap: Arc<dyn OutboundFederationPort>,
|
||||||
pub base_url: String,
|
pub base_url: String,
|
||||||
pub ap_repo: Arc<dyn FederationContentRepository>,
|
pub ap_repo: Arc<dyn ActivityPubRepository>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FederationEventService {
|
impl FederationEventService {
|
||||||
@@ -35,11 +32,16 @@ impl FederationEventService {
|
|||||||
..
|
..
|
||||||
} => {
|
} => {
|
||||||
let thought = match self.thoughts.find_by_id(thought_id).await? {
|
let thought = match self.thoughts.find_by_id(thought_id).await? {
|
||||||
Some(t) if should_broadcast(&t) => t,
|
Some(t)
|
||||||
_ => {
|
if t.local
|
||||||
tracing::debug!(thought_id = %thought_id, "federation: skipping ThoughtCreated (remote or non-public)");
|
&& matches!(
|
||||||
return Ok(());
|
t.visibility,
|
||||||
|
Visibility::Public | Visibility::Unlisted
|
||||||
|
) =>
|
||||||
|
{
|
||||||
|
t
|
||||||
}
|
}
|
||||||
|
_ => return Ok(()),
|
||||||
};
|
};
|
||||||
let user = match self.users.find_by_id(user_id).await? {
|
let user = match self.users.find_by_id(user_id).await? {
|
||||||
Some(u) => u,
|
Some(u) => u,
|
||||||
@@ -56,7 +58,6 @@ impl FederationEventService {
|
|||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
tracing::info!(thought_id = %thought_id, user_id = %user_id, "federation: broadcasting Create(Note)");
|
|
||||||
self.ap
|
self.ap
|
||||||
.broadcast_create(
|
.broadcast_create(
|
||||||
user_id,
|
user_id,
|
||||||
@@ -71,7 +72,8 @@ impl FederationEventService {
|
|||||||
thought_id,
|
thought_id,
|
||||||
user_id,
|
user_id,
|
||||||
} => {
|
} => {
|
||||||
tracing::info!(thought_id = %thought_id, user_id = %user_id, "federation: broadcasting Delete");
|
// No DB lookup — thought is already deleted when this event fires.
|
||||||
|
// No locality guard: delete commands only reach local thoughts via the use case.
|
||||||
let ap_id = format!("{}/thoughts/{}", self.base_url, thought_id);
|
let ap_id = format!("{}/thoughts/{}", self.base_url, thought_id);
|
||||||
self.ap.broadcast_delete(user_id, &ap_id).await
|
self.ap.broadcast_delete(user_id, &ap_id).await
|
||||||
}
|
}
|
||||||
@@ -81,7 +83,15 @@ impl FederationEventService {
|
|||||||
user_id,
|
user_id,
|
||||||
} => {
|
} => {
|
||||||
let thought = match self.thoughts.find_by_id(thought_id).await? {
|
let thought = match self.thoughts.find_by_id(thought_id).await? {
|
||||||
Some(t) if should_broadcast(&t) => t,
|
Some(t)
|
||||||
|
if t.local
|
||||||
|
&& matches!(
|
||||||
|
t.visibility,
|
||||||
|
Visibility::Public | Visibility::Unlisted
|
||||||
|
) =>
|
||||||
|
{
|
||||||
|
t
|
||||||
|
}
|
||||||
_ => return Ok(()),
|
_ => return Ok(()),
|
||||||
};
|
};
|
||||||
let user = match self.users.find_by_id(user_id).await? {
|
let user = match self.users.find_by_id(user_id).await? {
|
||||||
@@ -96,7 +106,6 @@ impl FederationEventService {
|
|||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
tracing::info!(thought_id = %thought_id, user_id = %user_id, "federation: broadcasting Update(Note)");
|
|
||||||
self.ap
|
self.ap
|
||||||
.broadcast_update(
|
.broadcast_update(
|
||||||
user_id,
|
user_id,
|
||||||
@@ -112,15 +121,16 @@ impl FederationEventService {
|
|||||||
user_id,
|
user_id,
|
||||||
thought_id,
|
thought_id,
|
||||||
} => {
|
} => {
|
||||||
if !matches!(self.users.find_by_id(user_id).await?, Some(u) if u.local) {
|
// Only fan-out if the booster is a local user. Remote boosts must not be re-broadcast.
|
||||||
tracing::debug!(user_id = %user_id, "federation: skipping BoostAdded (remote user)");
|
let booster = match self.users.find_by_id(user_id).await? {
|
||||||
return Ok(());
|
Some(u) if u.local => u,
|
||||||
}
|
_ => return Ok(()),
|
||||||
|
};
|
||||||
|
let _ = booster;
|
||||||
if self.thoughts.find_by_id(thought_id).await?.is_none() {
|
if self.thoughts.find_by_id(thought_id).await?.is_none() {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
let object_ap_id = self.object_ap_id(thought_id).await?;
|
let object_ap_id = self.object_ap_id(thought_id).await?;
|
||||||
tracing::info!(thought_id = %thought_id, user_id = %user_id, "federation: broadcasting Announce");
|
|
||||||
self.ap.broadcast_announce(user_id, &object_ap_id).await
|
self.ap.broadcast_announce(user_id, &object_ap_id).await
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -132,7 +142,6 @@ impl FederationEventService {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
let object_ap_id = self.object_ap_id(thought_id).await?;
|
let object_ap_id = self.object_ap_id(thought_id).await?;
|
||||||
tracing::info!(thought_id = %thought_id, user_id = %user_id, "federation: broadcasting Undo(Announce)");
|
|
||||||
self.ap
|
self.ap
|
||||||
.broadcast_undo_announce(user_id, &object_ap_id)
|
.broadcast_undo_announce(user_id, &object_ap_id)
|
||||||
.await
|
.await
|
||||||
@@ -143,26 +152,24 @@ impl FederationEventService {
|
|||||||
user_id,
|
user_id,
|
||||||
thought_id,
|
thought_id,
|
||||||
} => {
|
} => {
|
||||||
if !matches!(self.users.find_by_id(user_id).await?, Some(u) if u.local) {
|
// Only federate: local liker + remote thought (has ap_id) + author has inbox.
|
||||||
tracing::debug!(user_id = %user_id, "federation: skipping LikeAdded (remote user)");
|
let liker = match self.users.find_by_id(user_id).await? {
|
||||||
return Ok(());
|
Some(u) if u.local => u,
|
||||||
}
|
_ => return Ok(()),
|
||||||
|
};
|
||||||
|
let _ = liker;
|
||||||
let thought = match self.thoughts.find_by_id(thought_id).await? {
|
let thought = match self.thoughts.find_by_id(thought_id).await? {
|
||||||
Some(t) => t,
|
Some(t) => t,
|
||||||
_ => return Ok(()),
|
_ => return Ok(()),
|
||||||
};
|
};
|
||||||
let thought_ap_id = match self.ap_repo.get_thought_ap_id(thought_id).await? {
|
let thought_ap_id = match self.ap_repo.get_thought_ap_id(thought_id).await? {
|
||||||
Some(id) => id,
|
Some(id) => id,
|
||||||
None => {
|
None => return Ok(()), // local thought — no federation needed
|
||||||
tracing::debug!(thought_id = %thought_id, "federation: skipping LikeAdded (local thought)");
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
let actor_urls = match self.ap_repo.get_actor_ap_urls(&thought.user_id).await? {
|
let actor_urls = match self.ap_repo.get_actor_ap_urls(&thought.user_id).await? {
|
||||||
Some(u) => u,
|
Some(u) => u,
|
||||||
None => return Ok(()),
|
None => return Ok(()),
|
||||||
};
|
};
|
||||||
tracing::info!(thought_id = %thought_id, user_id = %user_id, "federation: broadcasting Like");
|
|
||||||
self.ap
|
self.ap
|
||||||
.broadcast_like(user_id, &thought_ap_id, &actor_urls.inbox_url)
|
.broadcast_like(user_id, &thought_ap_id, &actor_urls.inbox_url)
|
||||||
.await
|
.await
|
||||||
@@ -172,9 +179,11 @@ impl FederationEventService {
|
|||||||
user_id,
|
user_id,
|
||||||
thought_id,
|
thought_id,
|
||||||
} => {
|
} => {
|
||||||
if !matches!(self.users.find_by_id(user_id).await?, Some(u) if u.local) {
|
let liker = match self.users.find_by_id(user_id).await? {
|
||||||
return Ok(());
|
Some(u) if u.local => u,
|
||||||
}
|
_ => return Ok(()),
|
||||||
|
};
|
||||||
|
let _ = liker;
|
||||||
let thought = match self.thoughts.find_by_id(thought_id).await? {
|
let thought = match self.thoughts.find_by_id(thought_id).await? {
|
||||||
Some(t) => t,
|
Some(t) => t,
|
||||||
_ => return Ok(()),
|
_ => return Ok(()),
|
||||||
@@ -187,14 +196,12 @@ impl FederationEventService {
|
|||||||
Some(u) => u,
|
Some(u) => u,
|
||||||
None => return Ok(()),
|
None => return Ok(()),
|
||||||
};
|
};
|
||||||
tracing::info!(thought_id = %thought_id, user_id = %user_id, "federation: broadcasting Undo(Like)");
|
|
||||||
self.ap
|
self.ap
|
||||||
.broadcast_undo_like(user_id, &thought_ap_id, &actor_urls.inbox_url)
|
.broadcast_undo_like(user_id, &thought_ap_id, &actor_urls.inbox_url)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
DomainEvent::ProfileUpdated { user_id } => {
|
DomainEvent::ProfileUpdated { user_id } => {
|
||||||
tracing::info!(user_id = %user_id, "federation: broadcasting actor update");
|
|
||||||
self.ap.broadcast_actor_update(user_id).await
|
self.ap.broadcast_actor_update(user_id).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::testing::TestApRepo;
|
use crate::testing::TestApRepo;
|
||||||
|
use activitypub::{ActorApUrls, OutboundFederationPort};
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use domain::ports::{ActorFederationUrls, FederationBroadcastPort};
|
|
||||||
use domain::{
|
use domain::{
|
||||||
errors::DomainError,
|
errors::DomainError,
|
||||||
events::DomainEvent,
|
events::DomainEvent,
|
||||||
@@ -27,7 +27,7 @@ struct SpyPort {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl FederationBroadcastPort for SpyPort {
|
impl OutboundFederationPort for SpyPort {
|
||||||
async fn broadcast_create(
|
async fn broadcast_create(
|
||||||
&self,
|
&self,
|
||||||
_: &UserId,
|
_: &UserId,
|
||||||
@@ -100,7 +100,6 @@ fn local_thought(author_id: UserId) -> Thought {
|
|||||||
visibility: Visibility::Public,
|
visibility: Visibility::Public,
|
||||||
content_warning: None,
|
content_warning: None,
|
||||||
sensitive: false,
|
sensitive: false,
|
||||||
mood: None,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -284,7 +283,6 @@ async fn direct_thought_created_does_not_broadcast() {
|
|||||||
visibility: Visibility::Direct,
|
visibility: Visibility::Direct,
|
||||||
content_warning: None,
|
content_warning: None,
|
||||||
sensitive: false,
|
sensitive: false,
|
||||||
mood: None,
|
|
||||||
});
|
});
|
||||||
store.users.lock().unwrap().push(alice.clone());
|
store.users.lock().unwrap().push(alice.clone());
|
||||||
store.thoughts.lock().unwrap().push(thought.clone());
|
store.thoughts.lock().unwrap().push(thought.clone());
|
||||||
@@ -314,7 +312,6 @@ async fn followers_only_thought_does_not_broadcast_publicly() {
|
|||||||
visibility: Visibility::Followers,
|
visibility: Visibility::Followers,
|
||||||
content_warning: None,
|
content_warning: None,
|
||||||
sensitive: false,
|
sensitive: false,
|
||||||
mood: None,
|
|
||||||
});
|
});
|
||||||
store.users.lock().unwrap().push(alice.clone());
|
store.users.lock().unwrap().push(alice.clone());
|
||||||
store.thoughts.lock().unwrap().push(thought.clone());
|
store.thoughts.lock().unwrap().push(thought.clone());
|
||||||
@@ -482,7 +479,7 @@ async fn like_added_local_user_remote_thought_broadcasts_like() {
|
|||||||
let ap_repo = TestApRepo::new(store.clone());
|
let ap_repo = TestApRepo::new(store.clone());
|
||||||
ap_repo.actor_ap_urls.lock().unwrap().insert(
|
ap_repo.actor_ap_urls.lock().unwrap().insert(
|
||||||
author.id.clone(),
|
author.id.clone(),
|
||||||
ActorFederationUrls {
|
ActorApUrls {
|
||||||
ap_id: "https://mastodon.social/users/author".into(),
|
ap_id: "https://mastodon.social/users/author".into(),
|
||||||
inbox_url: "https://mastodon.social/users/author/inbox".into(),
|
inbox_url: "https://mastodon.social/users/author/inbox".into(),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,56 +0,0 @@
|
|||||||
use domain::{errors::DomainError, events::DomainEvent, ports::FederationActionPort};
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
pub struct FederationManagementEventService {
|
|
||||||
pub federation: Arc<dyn FederationActionPort>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FederationManagementEventService {
|
|
||||||
pub async fn process(&self, event: &DomainEvent) -> Result<(), DomainError> {
|
|
||||||
match event {
|
|
||||||
DomainEvent::RemoteFollowAccepted {
|
|
||||||
local_user_id,
|
|
||||||
remote_actor_url,
|
|
||||||
} => {
|
|
||||||
tracing::info!(
|
|
||||||
local_user_id = %local_user_id,
|
|
||||||
actor = %remote_actor_url,
|
|
||||||
"federation-mgmt: accepting follow — sending Accept + backfill"
|
|
||||||
);
|
|
||||||
self.federation
|
|
||||||
.accept_follow_request(local_user_id, remote_actor_url)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
DomainEvent::RemoteFollowRejected {
|
|
||||||
local_user_id,
|
|
||||||
remote_actor_url,
|
|
||||||
} => {
|
|
||||||
tracing::info!(
|
|
||||||
local_user_id = %local_user_id,
|
|
||||||
actor = %remote_actor_url,
|
|
||||||
"federation-mgmt: rejecting follow — sending Reject"
|
|
||||||
);
|
|
||||||
self.federation
|
|
||||||
.reject_follow_request(local_user_id, remote_actor_url)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
DomainEvent::ActorMoved {
|
|
||||||
user_id,
|
|
||||||
new_actor_url,
|
|
||||||
} => {
|
|
||||||
tracing::info!(
|
|
||||||
user_id = %user_id,
|
|
||||||
target = %new_actor_url,
|
|
||||||
"federation-mgmt: broadcasting Move"
|
|
||||||
);
|
|
||||||
let url = url::Url::parse(new_actor_url)
|
|
||||||
.map_err(|e| DomainError::Internal(e.to_string()))?;
|
|
||||||
self.federation
|
|
||||||
.broadcast_move(user_id, url)
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::Internal(e.to_string()))
|
|
||||||
}
|
|
||||||
_ => Ok(()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,5 @@
|
|||||||
pub mod federation_event;
|
pub mod federation_event;
|
||||||
pub mod federation_management_event;
|
|
||||||
pub mod notification_event;
|
pub mod notification_event;
|
||||||
|
|
||||||
pub use federation_event::FederationEventService;
|
pub use federation_event::FederationEventService;
|
||||||
pub use federation_management_event::FederationManagementEventService;
|
|
||||||
pub use notification_event::NotificationEventService;
|
pub use notification_event::NotificationEventService;
|
||||||
|
|||||||
@@ -35,7 +35,6 @@ impl NotificationEventService {
|
|||||||
if is_self_action(&thought.user_id, user_id) {
|
if is_self_action(&thought.user_id, user_id) {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
tracing::info!(from = %user_id, to = %thought.user_id, thought_id = %thought_id, "notification: Like");
|
|
||||||
self.notifications
|
self.notifications
|
||||||
.save(&Notification {
|
.save(&Notification {
|
||||||
id: NotificationId::new(),
|
id: NotificationId::new(),
|
||||||
@@ -61,7 +60,6 @@ impl NotificationEventService {
|
|||||||
if is_self_action(&thought.user_id, user_id) {
|
if is_self_action(&thought.user_id, user_id) {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
tracing::info!(from = %user_id, to = %thought.user_id, thought_id = %thought_id, "notification: Boost");
|
|
||||||
self.notifications
|
self.notifications
|
||||||
.save(&Notification {
|
.save(&Notification {
|
||||||
id: NotificationId::new(),
|
id: NotificationId::new(),
|
||||||
@@ -79,7 +77,6 @@ impl NotificationEventService {
|
|||||||
follower_id,
|
follower_id,
|
||||||
following_id,
|
following_id,
|
||||||
} => {
|
} => {
|
||||||
tracing::info!(from = %follower_id, to = %following_id, "notification: Follow");
|
|
||||||
self.notifications
|
self.notifications
|
||||||
.save(&Notification {
|
.save(&Notification {
|
||||||
id: NotificationId::new(),
|
id: NotificationId::new(),
|
||||||
@@ -108,7 +105,6 @@ impl NotificationEventService {
|
|||||||
if is_self_action(&original.user_id, user_id) {
|
if is_self_action(&original.user_id, user_id) {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
tracing::info!(from = %user_id, to = %original.user_id, thought_id = %thought_id, "notification: Reply");
|
|
||||||
self.notifications
|
self.notifications
|
||||||
.save(&Notification {
|
.save(&Notification {
|
||||||
id: NotificationId::new(),
|
id: NotificationId::new(),
|
||||||
@@ -127,7 +123,6 @@ impl NotificationEventService {
|
|||||||
mentioned_user_id,
|
mentioned_user_id,
|
||||||
author_user_id,
|
author_user_id,
|
||||||
} => {
|
} => {
|
||||||
tracing::info!(from = %author_user_id, to = %mentioned_user_id, thought_id = %thought_id, "notification: Mention");
|
|
||||||
self.notifications
|
self.notifications
|
||||||
.save(&Notification {
|
.save(&Notification {
|
||||||
id: NotificationId::new(),
|
id: NotificationId::new(),
|
||||||
|
|||||||
@@ -32,7 +32,6 @@ async fn like_creates_notification_for_thought_author() {
|
|||||||
visibility: Visibility::Public,
|
visibility: Visibility::Public,
|
||||||
content_warning: None,
|
content_warning: None,
|
||||||
sensitive: false,
|
sensitive: false,
|
||||||
mood: None,
|
|
||||||
});
|
});
|
||||||
store.thoughts.lock().unwrap().push(thought.clone());
|
store.thoughts.lock().unwrap().push(thought.clone());
|
||||||
let svc = NotificationEventService {
|
let svc = NotificationEventService {
|
||||||
@@ -63,7 +62,6 @@ async fn self_like_creates_no_notification() {
|
|||||||
visibility: Visibility::Public,
|
visibility: Visibility::Public,
|
||||||
content_warning: None,
|
content_warning: None,
|
||||||
sensitive: false,
|
sensitive: false,
|
||||||
mood: None,
|
|
||||||
});
|
});
|
||||||
store.thoughts.lock().unwrap().push(thought.clone());
|
store.thoughts.lock().unwrap().push(thought.clone());
|
||||||
let svc = NotificationEventService {
|
let svc = NotificationEventService {
|
||||||
@@ -113,7 +111,6 @@ async fn reply_creates_notification_for_original_author() {
|
|||||||
visibility: Visibility::Public,
|
visibility: Visibility::Public,
|
||||||
content_warning: None,
|
content_warning: None,
|
||||||
sensitive: false,
|
sensitive: false,
|
||||||
mood: None,
|
|
||||||
});
|
});
|
||||||
store.thoughts.lock().unwrap().push(original.clone());
|
store.thoughts.lock().unwrap().push(original.clone());
|
||||||
let svc = NotificationEventService {
|
let svc = NotificationEventService {
|
||||||
@@ -144,7 +141,6 @@ async fn self_reply_creates_no_notification() {
|
|||||||
visibility: Visibility::Public,
|
visibility: Visibility::Public,
|
||||||
content_warning: None,
|
content_warning: None,
|
||||||
sensitive: false,
|
sensitive: false,
|
||||||
mood: None,
|
|
||||||
});
|
});
|
||||||
store.thoughts.lock().unwrap().push(original.clone());
|
store.thoughts.lock().unwrap().push(original.clone());
|
||||||
let svc = NotificationEventService {
|
let svc = NotificationEventService {
|
||||||
@@ -173,7 +169,6 @@ async fn self_boost_creates_no_notification() {
|
|||||||
visibility: Visibility::Public,
|
visibility: Visibility::Public,
|
||||||
content_warning: None,
|
content_warning: None,
|
||||||
sensitive: false,
|
sensitive: false,
|
||||||
mood: None,
|
|
||||||
});
|
});
|
||||||
store.thoughts.lock().unwrap().push(thought.clone());
|
store.thoughts.lock().unwrap().push(thought.clone());
|
||||||
let svc = NotificationEventService {
|
let svc = NotificationEventService {
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
|
/// Test helpers for application-layer tests that need activitypub traits.
|
||||||
|
use activitypub::{ActivityPubRepository, ActorApUrls, OutboxEntry};
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use domain::{
|
use domain::{
|
||||||
errors::DomainError,
|
errors::DomainError,
|
||||||
models::user::User,
|
models::user::User,
|
||||||
ports::{AcceptNoteInput, ActorFederationUrls, FederationContentRepository, OutboxEntry},
|
|
||||||
testing::TestStore,
|
testing::TestStore,
|
||||||
value_objects::{Email, ThoughtId, UserId, Username},
|
value_objects::{Email, PasswordHash, ThoughtId, UserId, Username},
|
||||||
};
|
};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
@@ -13,8 +14,8 @@ use std::sync::{Arc, Mutex};
|
|||||||
#[derive(Default, Clone)]
|
#[derive(Default, Clone)]
|
||||||
pub struct TestApRepo {
|
pub struct TestApRepo {
|
||||||
pub inner: TestStore,
|
pub inner: TestStore,
|
||||||
/// UserId → ActorFederationUrls (for get_actor_ap_urls)
|
/// UserId → ActorApUrls (for get_actor_ap_urls)
|
||||||
pub actor_ap_urls: Arc<Mutex<HashMap<UserId, ActorFederationUrls>>>,
|
pub actor_ap_urls: Arc<Mutex<HashMap<UserId, ActorApUrls>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TestApRepo {
|
impl TestApRepo {
|
||||||
@@ -27,7 +28,7 @@ impl TestApRepo {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl FederationContentRepository for TestApRepo {
|
impl ActivityPubRepository for TestApRepo {
|
||||||
async fn outbox_entries_for_actor(
|
async fn outbox_entries_for_actor(
|
||||||
&self,
|
&self,
|
||||||
_uid: &UserId,
|
_uid: &UserId,
|
||||||
@@ -62,11 +63,20 @@ impl FederationContentRepository for TestApRepo {
|
|||||||
let handle = url::Url::parse(actor_ap_url)
|
let handle = url::Url::parse(actor_ap_url)
|
||||||
.map(|u| u.path().trim_start_matches('/').replace('/', "_"))
|
.map(|u| u.path().trim_start_matches('/').replace('/', "_"))
|
||||||
.unwrap_or_else(|_| format!("remote_{}", &uid.to_string()[..8]));
|
.unwrap_or_else(|_| format!("remote_{}", &uid.to_string()[..8]));
|
||||||
let user = User::new_remote(
|
let user = User {
|
||||||
uid.clone(),
|
id: uid.clone(),
|
||||||
Username::from_trusted(handle),
|
username: Username::from_trusted(handle),
|
||||||
Email::from_trusted(format!("{}@remote", uid)),
|
email: Email::from_trusted(format!("{}@remote", uid)),
|
||||||
);
|
password_hash: PasswordHash("".into()),
|
||||||
|
display_name: None,
|
||||||
|
bio: None,
|
||||||
|
avatar_url: None,
|
||||||
|
header_url: None,
|
||||||
|
custom_css: None,
|
||||||
|
local: false,
|
||||||
|
created_at: chrono::Utc::now(),
|
||||||
|
updated_at: chrono::Utc::now(),
|
||||||
|
};
|
||||||
self.inner.users.lock().unwrap().push(user);
|
self.inner.users.lock().unwrap().push(user);
|
||||||
self.inner
|
self.inner
|
||||||
.actor_ap_ids
|
.actor_ap_ids
|
||||||
@@ -83,15 +93,13 @@ impl FederationContentRepository for TestApRepo {
|
|||||||
) -> Result<(), DomainError> {
|
) -> Result<(), DomainError> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
async fn accept_note(&self, _input: AcceptNoteInput<'_>) -> Result<ThoughtId, DomainError> {
|
async fn accept_note(
|
||||||
|
&self,
|
||||||
|
_input: activitypub::AcceptNoteInput<'_>,
|
||||||
|
) -> Result<ThoughtId, DomainError> {
|
||||||
Ok(ThoughtId::from_uuid(uuid::Uuid::new_v4()))
|
Ok(ThoughtId::from_uuid(uuid::Uuid::new_v4()))
|
||||||
}
|
}
|
||||||
async fn apply_note_update(
|
async fn apply_note_update(&self, _ap_id: &str, _new_content: &str) -> Result<(), DomainError> {
|
||||||
&self,
|
|
||||||
_ap_id: &str,
|
|
||||||
_new_content: &str,
|
|
||||||
_: Option<serde_json::Value>,
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
async fn retract_note(&self, _ap_id: &str) -> Result<(), DomainError> {
|
async fn retract_note(&self, _ap_id: &str) -> Result<(), DomainError> {
|
||||||
@@ -125,10 +133,7 @@ impl FederationContentRepository for TestApRepo {
|
|||||||
async fn get_actor_ap_urls(
|
async fn get_actor_ap_urls(
|
||||||
&self,
|
&self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
) -> Result<Option<ActorFederationUrls>, DomainError> {
|
) -> Result<Option<ActorApUrls>, DomainError> {
|
||||||
Ok(self.actor_ap_urls.lock().unwrap().get(user_id).cloned())
|
Ok(self.actor_ap_urls.lock().unwrap().get(user_id).cloned())
|
||||||
}
|
}
|
||||||
async fn sync_remote_actor_to_user(&self, _actor_ap_url: &str) -> Result<(), DomainError> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -60,13 +60,6 @@ impl UserWriter for ConflictOnSaveStore {
|
|||||||
) -> Result<(), DomainError> {
|
) -> Result<(), DomainError> {
|
||||||
self.0.update_profile(user_id, input).await
|
self.0.update_profile(user_id, input).await
|
||||||
}
|
}
|
||||||
async fn set_also_known_as(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
value: Option<String>,
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
self.0.set_also_known_as(user_id, value).await
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
@@ -112,13 +105,6 @@ impl UserWriter for EmailConflictOnSaveStore {
|
|||||||
) -> Result<(), DomainError> {
|
) -> Result<(), DomainError> {
|
||||||
self.0.update_profile(user_id, input).await
|
self.0.update_profile(user_id, input).await
|
||||||
}
|
}
|
||||||
async fn set_also_known_as(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
value: Option<String>,
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
self.0.set_also_known_as(user_id, value).await
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
struct FakeHasher;
|
struct FakeHasher;
|
||||||
|
|||||||
@@ -1,36 +1,21 @@
|
|||||||
|
use activitypub::ActivityPubRepository;
|
||||||
use domain::{
|
use domain::{
|
||||||
errors::DomainError,
|
errors::DomainError,
|
||||||
events::DomainEvent,
|
|
||||||
models::{
|
models::{
|
||||||
actor_connection_summary::ActorConnectionSummary,
|
actor_connection_summary::ActorConnectionSummary,
|
||||||
feed::{FeedEntry, PageParams, Paginated},
|
feed::{FeedEntry, PageParams, Paginated},
|
||||||
remote_actor::RemoteActor,
|
remote_actor::RemoteActor,
|
||||||
},
|
},
|
||||||
ports::{
|
ports::{
|
||||||
EventPublisher, FederationActionPort, FederationContentRepository, FederationFollowPort,
|
EventPublisher, FederationActionPort, FederationFollowPort, FederationFollowRequestPort,
|
||||||
FederationFollowRequestPort, FederationSchedulerPort, FeedOptions, FeedQuery,
|
FederationSchedulerPort, FeedQuery, FeedRepository, FollowRepository,
|
||||||
FeedRepository, FeedRequest, FollowRepository, RemoteActorConnectionRepository, UserReader,
|
RemoteActorConnectionRepository, UserReader,
|
||||||
UserWriter,
|
|
||||||
},
|
},
|
||||||
value_objects::UserId,
|
value_objects::UserId,
|
||||||
};
|
};
|
||||||
|
|
||||||
use super::social;
|
use super::social;
|
||||||
|
|
||||||
pub async fn initiate_actor_move(
|
|
||||||
events: &dyn EventPublisher,
|
|
||||||
user_id: &UserId,
|
|
||||||
new_actor_url: url::Url,
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
events
|
|
||||||
.publish(&DomainEvent::ActorMoved {
|
|
||||||
user_id: user_id.clone(),
|
|
||||||
new_actor_url: new_actor_url.to_string(),
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::Internal(e.to_string()))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn list_pending_requests(
|
pub async fn list_pending_requests(
|
||||||
federation: &dyn FederationFollowRequestPort,
|
federation: &dyn FederationFollowRequestPort,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
@@ -40,34 +25,18 @@ pub async fn list_pending_requests(
|
|||||||
|
|
||||||
pub async fn accept_follow_request(
|
pub async fn accept_follow_request(
|
||||||
federation: &dyn FederationFollowRequestPort,
|
federation: &dyn FederationFollowRequestPort,
|
||||||
events: &dyn EventPublisher,
|
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
actor_url: &str,
|
actor_url: &str,
|
||||||
) -> Result<(), DomainError> {
|
) -> Result<(), DomainError> {
|
||||||
events
|
federation.accept_follow_request(user_id, actor_url).await
|
||||||
.publish(&DomainEvent::RemoteFollowAccepted {
|
|
||||||
local_user_id: user_id.clone(),
|
|
||||||
remote_actor_url: actor_url.to_string(),
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::Internal(e.to_string()))?;
|
|
||||||
federation.mark_follower_accepted(user_id, actor_url).await
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn reject_follow_request(
|
pub async fn reject_follow_request(
|
||||||
federation: &dyn FederationFollowRequestPort,
|
federation: &dyn FederationFollowRequestPort,
|
||||||
events: &dyn EventPublisher,
|
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
actor_url: &str,
|
actor_url: &str,
|
||||||
) -> Result<(), DomainError> {
|
) -> Result<(), DomainError> {
|
||||||
events
|
federation.reject_follow_request(user_id, actor_url).await
|
||||||
.publish(&DomainEvent::RemoteFollowRejected {
|
|
||||||
local_user_id: user_id.clone(),
|
|
||||||
remote_actor_url: actor_url.to_string(),
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::Internal(e.to_string()))?;
|
|
||||||
federation.mark_follower_rejected(user_id, actor_url).await
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn list_remote_followers(
|
pub async fn list_remote_followers(
|
||||||
@@ -92,20 +61,6 @@ pub async fn list_remote_following(
|
|||||||
federation.get_remote_following(user_id).await
|
federation.get_remote_following(user_id).await
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_remote_friends(
|
|
||||||
federation: &dyn FederationActionPort,
|
|
||||||
user_id: &UserId,
|
|
||||||
) -> Result<Vec<RemoteActor>, DomainError> {
|
|
||||||
use std::collections::HashSet;
|
|
||||||
let following = federation.get_remote_following(user_id).await?;
|
|
||||||
let followers = federation.get_remote_followers(user_id).await?;
|
|
||||||
let follower_urls: HashSet<&str> = followers.iter().map(|a| a.url.as_str()).collect();
|
|
||||||
Ok(following
|
|
||||||
.into_iter()
|
|
||||||
.filter(|a| follower_urls.contains(a.url.as_str()))
|
|
||||||
.collect())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn remove_remote_following(
|
pub async fn remove_remote_following(
|
||||||
follows: &dyn FollowRepository,
|
follows: &dyn FollowRepository,
|
||||||
users: &dyn UserReader,
|
users: &dyn UserReader,
|
||||||
@@ -119,7 +74,7 @@ pub async fn remove_remote_following(
|
|||||||
|
|
||||||
pub async fn get_remote_actor_posts(
|
pub async fn get_remote_actor_posts(
|
||||||
federation: &dyn FederationActionPort,
|
federation: &dyn FederationActionPort,
|
||||||
ap_repo: &dyn FederationContentRepository,
|
ap_repo: &dyn ActivityPubRepository,
|
||||||
feed: &dyn FeedRepository,
|
feed: &dyn FeedRepository,
|
||||||
scheduler: &dyn FederationSchedulerPort,
|
scheduler: &dyn FederationSchedulerPort,
|
||||||
handle: &str,
|
handle: &str,
|
||||||
@@ -132,10 +87,11 @@ pub async fn get_remote_actor_posts(
|
|||||||
None => ap_repo.intern_remote_actor(&actor.url).await?,
|
None => ap_repo.intern_remote_actor(&actor.url).await?,
|
||||||
};
|
};
|
||||||
let result = feed
|
let result = feed
|
||||||
.query(&FeedRequest {
|
.query(&FeedQuery::user(
|
||||||
query: FeedQuery::user(author_id, page.clone(), viewer_id.cloned()),
|
author_id,
|
||||||
options: FeedOptions::default(),
|
page.clone(),
|
||||||
})
|
viewer_id.cloned(),
|
||||||
|
))
|
||||||
.await?;
|
.await?;
|
||||||
if let Some(outbox_url) = actor.outbox_url {
|
if let Some(outbox_url) = actor.outbox_url {
|
||||||
let _ = scheduler
|
let _ = scheduler
|
||||||
@@ -175,22 +131,13 @@ pub async fn get_actor_connections_page(
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
if stale {
|
if stale {
|
||||||
// Always fetch from page 1 — the full collection is fetched and chunked.
|
|
||||||
let _ = scheduler
|
let _ = scheduler
|
||||||
.schedule_connections_fetch(&actor.url, &collection_url, connection_type, 1)
|
.schedule_connections_fetch(&actor.url, &collection_url, connection_type, page)
|
||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
let has_more = items.len() >= PAGE_SIZE;
|
let has_more = items.len() >= PAGE_SIZE;
|
||||||
Ok((items, has_more))
|
Ok((items, has_more))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn set_also_known_as(
|
|
||||||
users: &dyn UserWriter,
|
|
||||||
user_id: &UserId,
|
|
||||||
value: Option<String>,
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
users.set_also_known_as(user_id, value).await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests;
|
mod tests;
|
||||||
|
|||||||
@@ -1,27 +1,6 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
use chrono::Utc;
|
|
||||||
use domain::models::remote_actor::RemoteActor;
|
|
||||||
use domain::testing::TestStore;
|
use domain::testing::TestStore;
|
||||||
|
|
||||||
fn remote_actor(url: &str, handle: &str) -> RemoteActor {
|
|
||||||
RemoteActor {
|
|
||||||
url: url.to_string(),
|
|
||||||
handle: handle.to_string(),
|
|
||||||
display_name: None,
|
|
||||||
avatar_url: None,
|
|
||||||
bio: None,
|
|
||||||
banner_url: None,
|
|
||||||
also_known_as: vec![],
|
|
||||||
outbox_url: None,
|
|
||||||
followers_url: None,
|
|
||||||
following_url: None,
|
|
||||||
inbox_url: None,
|
|
||||||
shared_inbox_url: None,
|
|
||||||
attachment: vec![],
|
|
||||||
last_fetched_at: Utc::now(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn list_pending_returns_empty_by_default() {
|
async fn list_pending_returns_empty_by_default() {
|
||||||
let store = TestStore::default();
|
let store = TestStore::default();
|
||||||
@@ -34,7 +13,7 @@ async fn list_pending_returns_empty_by_default() {
|
|||||||
async fn accept_follow_request_returns_ok() {
|
async fn accept_follow_request_returns_ok() {
|
||||||
let store = TestStore::default();
|
let store = TestStore::default();
|
||||||
let uid = UserId::new();
|
let uid = UserId::new();
|
||||||
accept_follow_request(&store, &store, &uid, "https://mastodon.social/users/alice")
|
accept_follow_request(&store, &uid, "https://mastodon.social/users/alice")
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
@@ -43,7 +22,7 @@ async fn accept_follow_request_returns_ok() {
|
|||||||
async fn reject_follow_request_returns_ok() {
|
async fn reject_follow_request_returns_ok() {
|
||||||
let store = TestStore::default();
|
let store = TestStore::default();
|
||||||
let uid = UserId::new();
|
let uid = UserId::new();
|
||||||
reject_follow_request(&store, &store, &uid, "https://mastodon.social/users/alice")
|
reject_follow_request(&store, &uid, "https://mastodon.social/users/alice")
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
@@ -72,41 +51,3 @@ async fn list_remote_following_returns_empty_by_default() {
|
|||||||
let result = list_remote_following(&store, &uid).await.unwrap();
|
let result = list_remote_following(&store, &uid).await.unwrap();
|
||||||
assert!(result.is_empty());
|
assert!(result.is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn get_remote_friends_returns_intersection() {
|
|
||||||
let store = TestStore::default();
|
|
||||||
let uid = UserId::new();
|
|
||||||
|
|
||||||
let bob = remote_actor("https://bob.example.com/users/bob", "bob@bob.example.com");
|
|
||||||
let carol = remote_actor(
|
|
||||||
"https://carol.example.com/users/carol",
|
|
||||||
"carol@carol.example.com",
|
|
||||||
);
|
|
||||||
|
|
||||||
// uid follows bob and carol
|
|
||||||
store
|
|
||||||
.remote_following
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.extend([bob.clone(), carol.clone()]);
|
|
||||||
// only bob follows back
|
|
||||||
store.remote_followers.lock().unwrap().push(bob.clone());
|
|
||||||
|
|
||||||
let friends = get_remote_friends(&store, &uid).await.unwrap();
|
|
||||||
assert_eq!(friends.len(), 1);
|
|
||||||
assert_eq!(friends[0].url, bob.url);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn get_remote_friends_empty_when_no_mutual() {
|
|
||||||
let store = TestStore::default();
|
|
||||||
let uid = UserId::new();
|
|
||||||
|
|
||||||
let bob = remote_actor("https://bob.example.com/users/bob", "bob@bob.example.com");
|
|
||||||
store.remote_following.lock().unwrap().push(bob.clone());
|
|
||||||
// bob does NOT follow back
|
|
||||||
|
|
||||||
let friends = get_remote_friends(&store, &uid).await.unwrap();
|
|
||||||
assert!(friends.is_empty());
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use domain::{
|
use domain::{
|
||||||
errors::DomainError,
|
errors::DomainError,
|
||||||
models::feed::{FeedEntry, PageParams, Paginated},
|
models::feed::{FeedEntry, PageParams, Paginated},
|
||||||
ports::{FeedOptions, FeedQuery, FeedRepository, FeedRequest, FollowRepository, TagRepository},
|
ports::{FeedQuery, FeedRepository, FollowRepository},
|
||||||
value_objects::UserId,
|
value_objects::UserId,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -10,61 +10,9 @@ pub async fn get_home_feed(
|
|||||||
follows: &dyn FollowRepository,
|
follows: &dyn FollowRepository,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
page: PageParams,
|
page: PageParams,
|
||||||
opts: FeedOptions,
|
|
||||||
) -> Result<Paginated<FeedEntry>, DomainError> {
|
) -> Result<Paginated<FeedEntry>, DomainError> {
|
||||||
let mut following_ids = follows.get_accepted_following_ids(user_id).await?;
|
let mut following_ids = follows.get_accepted_following_ids(user_id).await?;
|
||||||
following_ids.push(user_id.clone());
|
following_ids.push(user_id.clone());
|
||||||
feed.query(&FeedRequest {
|
feed.query(&FeedQuery::home(user_id.clone(), following_ids, page))
|
||||||
query: FeedQuery::home(user_id.clone(), following_ids, page),
|
|
||||||
options: opts,
|
|
||||||
})
|
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_public_feed(
|
|
||||||
feed: &dyn FeedRepository,
|
|
||||||
viewer: Option<UserId>,
|
|
||||||
page: PageParams,
|
|
||||||
opts: FeedOptions,
|
|
||||||
) -> Result<Paginated<FeedEntry>, DomainError> {
|
|
||||||
feed.query(&FeedRequest {
|
|
||||||
query: FeedQuery::public(page, viewer),
|
|
||||||
options: opts,
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn get_user_feed(
|
|
||||||
feed: &dyn FeedRepository,
|
|
||||||
user_id: UserId,
|
|
||||||
page: PageParams,
|
|
||||||
opts: FeedOptions,
|
|
||||||
viewer: Option<UserId>,
|
|
||||||
) -> Result<Paginated<FeedEntry>, DomainError> {
|
|
||||||
feed.query(&FeedRequest {
|
|
||||||
query: FeedQuery::user(user_id, page, viewer),
|
|
||||||
options: opts,
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn get_tag_feed(
|
|
||||||
feed: &dyn FeedRepository,
|
|
||||||
tag: &str,
|
|
||||||
page: PageParams,
|
|
||||||
opts: FeedOptions,
|
|
||||||
viewer: Option<UserId>,
|
|
||||||
) -> Result<Paginated<FeedEntry>, DomainError> {
|
|
||||||
feed.query(&FeedRequest {
|
|
||||||
query: FeedQuery::tag(tag, page, viewer),
|
|
||||||
options: opts,
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn get_popular_tags(
|
|
||||||
tags: &dyn TagRepository,
|
|
||||||
limit: usize,
|
|
||||||
) -> Result<Vec<(String, i64)>, DomainError> {
|
|
||||||
tags.popular_tags(limit).await
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,24 +1,13 @@
|
|||||||
const MAX_TOP_FRIENDS: usize = 8;
|
const MAX_TOP_FRIENDS: usize = 8;
|
||||||
const MAX_PROFILE_FIELDS: usize = 4;
|
|
||||||
const MAX_FIELD_NAME_LEN: usize = 64;
|
|
||||||
const MAX_FIELD_VALUE_LEN: usize = 256;
|
|
||||||
const MAX_CUSTOM_MOODS: usize = 8;
|
|
||||||
const MAX_MOOD_LABEL_LEN: usize = 32;
|
|
||||||
const MAX_MOOD_EMOJI_LEN: usize = 8;
|
|
||||||
|
|
||||||
use bytes::Bytes;
|
|
||||||
use domain::{
|
use domain::{
|
||||||
errors::DomainError,
|
errors::DomainError,
|
||||||
events::DomainEvent,
|
events::DomainEvent,
|
||||||
models::{
|
models::{
|
||||||
feed::{PageParams, Paginated, UserSummary},
|
|
||||||
top_friend::TopFriend,
|
top_friend::TopFriend,
|
||||||
user::{UpdateProfileInput, User},
|
user::{UpdateProfileInput, User},
|
||||||
},
|
},
|
||||||
ports::{
|
ports::{EventPublisher, TopFriendRepository, UserReader, UserWriter},
|
||||||
EventPublisher, FollowRepository, MediaStore, TopFriendRepository, UserReader,
|
|
||||||
UserRepository, UserWriter,
|
|
||||||
},
|
|
||||||
value_objects::{UserId, Username},
|
value_objects::{UserId, Username},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -61,34 +50,6 @@ pub async fn update_profile(
|
|||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
input: UpdateProfileInput,
|
input: UpdateProfileInput,
|
||||||
) -> Result<(), DomainError> {
|
) -> Result<(), DomainError> {
|
||||||
if let Some(ref fields) = input.profile_fields {
|
|
||||||
if fields.len() > MAX_PROFILE_FIELDS {
|
|
||||||
return Err(DomainError::InvalidInput(format!(
|
|
||||||
"profile fields: max {MAX_PROFILE_FIELDS}"
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
for (name, value) in fields {
|
|
||||||
if name.len() > MAX_FIELD_NAME_LEN || value.len() > MAX_FIELD_VALUE_LEN {
|
|
||||||
return Err(DomainError::InvalidInput(
|
|
||||||
"profile field name or value too long".into(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if let Some(ref moods) = input.custom_moods {
|
|
||||||
if moods.len() > MAX_CUSTOM_MOODS {
|
|
||||||
return Err(DomainError::InvalidInput(format!(
|
|
||||||
"custom moods: max {MAX_CUSTOM_MOODS}"
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
for (label, emoji) in moods {
|
|
||||||
if label.len() > MAX_MOOD_LABEL_LEN || emoji.len() > MAX_MOOD_EMOJI_LEN {
|
|
||||||
return Err(DomainError::InvalidInput(
|
|
||||||
"custom mood label or emoji too long".into(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
users.update_profile(user_id, input).await?;
|
users.update_profile(user_id, input).await?;
|
||||||
events
|
events
|
||||||
.publish(&DomainEvent::ProfileUpdated {
|
.publish(&DomainEvent::ProfileUpdated {
|
||||||
@@ -120,188 +81,5 @@ pub async fn set_top_friends(
|
|||||||
top_friends.set_top_friends(user_id, friends).await
|
top_friends.set_top_friends(user_id, friends).await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct UploadConfig {
|
|
||||||
pub max_bytes: usize,
|
|
||||||
pub allowed_content_types: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for UploadConfig {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
max_bytes: 5 * 1024 * 1024,
|
|
||||||
allowed_content_types: vec![
|
|
||||||
"image/jpeg".into(),
|
|
||||||
"image/png".into(),
|
|
||||||
"image/gif".into(),
|
|
||||||
"image/webp".into(),
|
|
||||||
"image/avif".into(),
|
|
||||||
],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn mime_to_ext(mime: &str) -> Result<&'static str, DomainError> {
|
|
||||||
match mime {
|
|
||||||
"image/jpeg" => Ok("jpg"),
|
|
||||||
"image/png" => Ok("png"),
|
|
||||||
"image/gif" => Ok("gif"),
|
|
||||||
"image/webp" => Ok("webp"),
|
|
||||||
"image/avif" => Ok("avif"),
|
|
||||||
_ => Err(DomainError::InvalidInput("unsupported content type".into())),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct UploadContext<'a> {
|
|
||||||
pub users: &'a dyn UserRepository,
|
|
||||||
pub media: &'a dyn MediaStore,
|
|
||||||
pub events: &'a dyn EventPublisher,
|
|
||||||
pub upload_config: &'a UploadConfig,
|
|
||||||
pub base_url: &'a str,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn store_image(
|
|
||||||
ctx: &UploadContext<'_>,
|
|
||||||
content_type: &str,
|
|
||||||
data: Bytes,
|
|
||||||
user_id: &UserId,
|
|
||||||
key_segment: &str,
|
|
||||||
old_url: Option<&str>,
|
|
||||||
) -> Result<String, DomainError> {
|
|
||||||
let cfg = ctx.upload_config;
|
|
||||||
let media = ctx.media;
|
|
||||||
let base_url = ctx.base_url;
|
|
||||||
if !cfg.allowed_content_types.iter().any(|t| t == content_type) {
|
|
||||||
return Err(DomainError::InvalidInput("unsupported content type".into()));
|
|
||||||
}
|
|
||||||
if data.len() > cfg.max_bytes {
|
|
||||||
return Err(DomainError::InvalidInput("file too large".into()));
|
|
||||||
}
|
|
||||||
let ext = mime_to_ext(content_type)?;
|
|
||||||
if let Some(old) = old_url {
|
|
||||||
let prefix = format!("{base_url}/media/");
|
|
||||||
if let Some(old_key) = old.strip_prefix(&prefix) {
|
|
||||||
media.delete(old_key).await?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let key = format!("users/{}/{key_segment}.{ext}", user_id.as_uuid());
|
|
||||||
let stream = Box::pin(futures::stream::once(async move { Ok(data) }));
|
|
||||||
media.put(&key, stream).await?;
|
|
||||||
Ok(key)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn upload_avatar(
|
|
||||||
ctx: &UploadContext<'_>,
|
|
||||||
user_id: &UserId,
|
|
||||||
content_type: &str,
|
|
||||||
data: Bytes,
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
let current = ctx
|
|
||||||
.users
|
|
||||||
.find_by_id(user_id)
|
|
||||||
.await?
|
|
||||||
.ok_or(DomainError::NotFound)?;
|
|
||||||
let key = store_image(
|
|
||||||
ctx,
|
|
||||||
content_type,
|
|
||||||
data,
|
|
||||||
user_id,
|
|
||||||
"avatar",
|
|
||||||
current.avatar_url.as_deref(),
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
ctx.users
|
|
||||||
.update_profile(
|
|
||||||
user_id,
|
|
||||||
UpdateProfileInput {
|
|
||||||
avatar_url: Some(format!("{}/media/{key}", ctx.base_url)),
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
ctx.events
|
|
||||||
.publish(&DomainEvent::ProfileUpdated {
|
|
||||||
user_id: user_id.clone(),
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn upload_banner(
|
|
||||||
ctx: &UploadContext<'_>,
|
|
||||||
user_id: &UserId,
|
|
||||||
content_type: &str,
|
|
||||||
data: Bytes,
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
let current = ctx
|
|
||||||
.users
|
|
||||||
.find_by_id(user_id)
|
|
||||||
.await?
|
|
||||||
.ok_or(DomainError::NotFound)?;
|
|
||||||
let key = store_image(
|
|
||||||
ctx,
|
|
||||||
content_type,
|
|
||||||
data,
|
|
||||||
user_id,
|
|
||||||
"banner",
|
|
||||||
current.header_url.as_deref(),
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
ctx.users
|
|
||||||
.update_profile(
|
|
||||||
user_id,
|
|
||||||
UpdateProfileInput {
|
|
||||||
header_url: Some(format!("{}/media/{key}", ctx.base_url)),
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
ctx.events
|
|
||||||
.publish(&DomainEvent::ProfileUpdated {
|
|
||||||
user_id: user_id.clone(),
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn get_user_profile(
|
|
||||||
users: &dyn UserReader,
|
|
||||||
follows: &dyn FollowRepository,
|
|
||||||
id_or_username: &str,
|
|
||||||
viewer_id: Option<&UserId>,
|
|
||||||
) -> Result<(User, bool), DomainError> {
|
|
||||||
let user = get_user_by_id_or_username(users, id_or_username).await?;
|
|
||||||
let is_followed = match viewer_id {
|
|
||||||
Some(vid) if vid != &user.id => follows.find(vid, &user.id).await?.is_some(),
|
|
||||||
_ => false,
|
|
||||||
};
|
|
||||||
Ok((user, is_followed))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn list_users(
|
|
||||||
users: &dyn UserReader,
|
|
||||||
page: PageParams,
|
|
||||||
) -> Result<Paginated<UserSummary>, DomainError> {
|
|
||||||
users.list_paginated(page).await
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn count_local_users(users: &dyn UserReader) -> Result<i64, DomainError> {
|
|
||||||
users.count().await
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn list_local_followers(
|
|
||||||
follows: &dyn FollowRepository,
|
|
||||||
user_id: &UserId,
|
|
||||||
page: PageParams,
|
|
||||||
) -> Result<Paginated<User>, DomainError> {
|
|
||||||
follows.list_followers(user_id, &page).await
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn list_local_following(
|
|
||||||
follows: &dyn FollowRepository,
|
|
||||||
user_id: &UserId,
|
|
||||||
page: PageParams,
|
|
||||||
) -> Result<Paginated<User>, DomainError> {
|
|
||||||
follows.list_following(user_id, &page).await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests;
|
mod tests;
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ use domain::{
|
|||||||
testing::TestStore,
|
testing::TestStore,
|
||||||
value_objects::{Email, PasswordHash, UserId, Username},
|
value_objects::{Email, PasswordHash, UserId, Username},
|
||||||
};
|
};
|
||||||
use std::sync::{Arc, Mutex};
|
|
||||||
|
|
||||||
fn make_user() -> User {
|
fn make_user() -> User {
|
||||||
User::new_local(
|
User::new_local(
|
||||||
@@ -65,191 +64,3 @@ async fn get_user_by_username_returns_correct_user() {
|
|||||||
let found = get_user_by_username(&store, "alice").await.unwrap();
|
let found = get_user_by_username(&store, "alice").await.unwrap();
|
||||||
assert_eq!(found.id, user.id);
|
assert_eq!(found.id, user.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── upload tests ──────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
use bytes::Bytes;
|
|
||||||
use domain::ports::{DataStream, MediaStore};
|
|
||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
#[derive(Default, Clone)]
|
|
||||||
struct MockMedia {
|
|
||||||
store: Arc<Mutex<HashMap<String, Bytes>>>,
|
|
||||||
deleted: Arc<Mutex<Vec<String>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait::async_trait]
|
|
||||||
impl MediaStore for MockMedia {
|
|
||||||
async fn put(&self, key: &str, mut data: DataStream) -> Result<(), DomainError> {
|
|
||||||
use futures::stream::StreamExt;
|
|
||||||
let mut buf = Vec::new();
|
|
||||||
while let Some(chunk) = data.next().await {
|
|
||||||
buf.extend_from_slice(&chunk?);
|
|
||||||
}
|
|
||||||
self.store
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.insert(key.to_string(), Bytes::from(buf));
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
async fn get(&self, key: &str) -> Result<DataStream, DomainError> {
|
|
||||||
let bytes = self
|
|
||||||
.store
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.get(key)
|
|
||||||
.cloned()
|
|
||||||
.ok_or(DomainError::NotFound)?;
|
|
||||||
Ok(Box::pin(futures::stream::once(async move { Ok(bytes) })))
|
|
||||||
}
|
|
||||||
async fn delete(&self, key: &str) -> Result<(), DomainError> {
|
|
||||||
self.store.lock().unwrap().remove(key);
|
|
||||||
self.deleted.lock().unwrap().push(key.to_string());
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn default_cfg() -> UploadConfig {
|
|
||||||
UploadConfig::default()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn make_ctx<'a>(
|
|
||||||
store: &'a TestStore,
|
|
||||||
media: &'a MockMedia,
|
|
||||||
cfg: &'a UploadConfig,
|
|
||||||
) -> UploadContext<'a> {
|
|
||||||
UploadContext {
|
|
||||||
users: store,
|
|
||||||
media,
|
|
||||||
events: store,
|
|
||||||
upload_config: cfg,
|
|
||||||
base_url: "http://localhost",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn upload_avatar_rejects_unsupported_mime() {
|
|
||||||
let store = TestStore::default();
|
|
||||||
let media = MockMedia::default();
|
|
||||||
let user = make_user();
|
|
||||||
store.users.lock().unwrap().push(user.clone());
|
|
||||||
let cfg = default_cfg();
|
|
||||||
let ctx = make_ctx(&store, &media, &cfg);
|
|
||||||
let err = upload_avatar(&ctx, &user.id, "text/plain", Bytes::from("hi"))
|
|
||||||
.await
|
|
||||||
.unwrap_err();
|
|
||||||
assert!(matches!(err, DomainError::InvalidInput(_)));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn upload_avatar_rejects_oversized_data() {
|
|
||||||
let store = TestStore::default();
|
|
||||||
let media = MockMedia::default();
|
|
||||||
let user = make_user();
|
|
||||||
store.users.lock().unwrap().push(user.clone());
|
|
||||||
let big = Bytes::from(vec![0u8; 6 * 1024 * 1024]);
|
|
||||||
let cfg = default_cfg();
|
|
||||||
let ctx = make_ctx(&store, &media, &cfg);
|
|
||||||
let err = upload_avatar(&ctx, &user.id, "image/jpeg", big)
|
|
||||||
.await
|
|
||||||
.unwrap_err();
|
|
||||||
assert!(matches!(err, DomainError::InvalidInput(_)));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn upload_avatar_stores_file_and_updates_url() {
|
|
||||||
let store = TestStore::default();
|
|
||||||
let media = MockMedia::default();
|
|
||||||
let user = make_user();
|
|
||||||
store.users.lock().unwrap().push(user.clone());
|
|
||||||
let cfg = default_cfg();
|
|
||||||
let ctx = make_ctx(&store, &media, &cfg);
|
|
||||||
upload_avatar(&ctx, &user.id, "image/jpeg", Bytes::from("img"))
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
let key = format!("users/{}/avatar.jpg", user.id.as_uuid());
|
|
||||||
assert!(media.store.lock().unwrap().contains_key(&key));
|
|
||||||
let saved = store
|
|
||||||
.users
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.iter()
|
|
||||||
.find(|u| u.id == user.id)
|
|
||||||
.unwrap()
|
|
||||||
.clone();
|
|
||||||
assert_eq!(
|
|
||||||
saved.avatar_url,
|
|
||||||
Some(format!("http://localhost/media/{key}"))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn upload_avatar_deletes_old_file_on_reupload() {
|
|
||||||
let store = TestStore::default();
|
|
||||||
let media = MockMedia::default();
|
|
||||||
let mut user = make_user();
|
|
||||||
let old_key = format!("users/{}/avatar.png", user.id.as_uuid());
|
|
||||||
user.avatar_url = Some(format!("http://localhost/media/{old_key}"));
|
|
||||||
store.users.lock().unwrap().push(user.clone());
|
|
||||||
media
|
|
||||||
.store
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.insert(old_key.clone(), Bytes::from("old"));
|
|
||||||
let cfg = default_cfg();
|
|
||||||
let ctx = make_ctx(&store, &media, &cfg);
|
|
||||||
upload_avatar(&ctx, &user.id, "image/jpeg", Bytes::from("new"))
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
assert!(!media.store.lock().unwrap().contains_key(&old_key));
|
|
||||||
assert!(media.deleted.lock().unwrap().contains(&old_key));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn upload_banner_stores_file_and_updates_header_url() {
|
|
||||||
let store = TestStore::default();
|
|
||||||
let media = MockMedia::default();
|
|
||||||
let user = make_user();
|
|
||||||
store.users.lock().unwrap().push(user.clone());
|
|
||||||
let cfg = default_cfg();
|
|
||||||
let ctx = make_ctx(&store, &media, &cfg);
|
|
||||||
upload_banner(&ctx, &user.id, "image/png", Bytes::from("banner"))
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
let key = format!("users/{}/banner.png", user.id.as_uuid());
|
|
||||||
assert!(media.store.lock().unwrap().contains_key(&key));
|
|
||||||
let saved = store
|
|
||||||
.users
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.iter()
|
|
||||||
.find(|u| u.id == user.id)
|
|
||||||
.unwrap()
|
|
||||||
.clone();
|
|
||||||
assert_eq!(
|
|
||||||
saved.header_url,
|
|
||||||
Some(format!("http://localhost/media/{key}"))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn upload_banner_deletes_old_file_on_reupload() {
|
|
||||||
let store = TestStore::default();
|
|
||||||
let media = MockMedia::default();
|
|
||||||
let mut user = make_user();
|
|
||||||
let old_key = format!("users/{}/banner.jpg", user.id.as_uuid());
|
|
||||||
user.header_url = Some(format!("http://localhost/media/{old_key}"));
|
|
||||||
store.users.lock().unwrap().push(user.clone());
|
|
||||||
media
|
|
||||||
.store
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.insert(old_key.clone(), Bytes::from("old"));
|
|
||||||
let cfg = default_cfg();
|
|
||||||
let ctx = make_ctx(&store, &media, &cfg);
|
|
||||||
upload_banner(&ctx, &user.id, "image/png", Bytes::from("new"))
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
assert!(!media.store.lock().unwrap().contains_key(&old_key));
|
|
||||||
assert!(media.deleted.lock().unwrap().contains(&old_key));
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -2,14 +2,10 @@ use chrono::Utc;
|
|||||||
use domain::{
|
use domain::{
|
||||||
errors::DomainError,
|
errors::DomainError,
|
||||||
events::DomainEvent,
|
events::DomainEvent,
|
||||||
models::{
|
models::social::{Block, Boost, Follow, FollowState, Like},
|
||||||
feed::{PageParams, Paginated},
|
|
||||||
social::{Block, Boost, Follow, FollowState, Like},
|
|
||||||
user::User,
|
|
||||||
},
|
|
||||||
ports::{
|
ports::{
|
||||||
BlockRepository, BoostRepository, EventPublisher, FederationBlockPort,
|
BlockRepository, BoostRepository, EventPublisher, FederationFollowPort, FollowRepository,
|
||||||
FederationFollowPort, FollowRepository, LikeRepository, UserReader,
|
LikeRepository, UserReader,
|
||||||
},
|
},
|
||||||
value_objects::{BoostId, LikeId, ThoughtId, UserId, Username},
|
value_objects::{BoostId, LikeId, ThoughtId, UserId, Username},
|
||||||
};
|
};
|
||||||
@@ -217,14 +213,10 @@ pub async fn reject_follow(
|
|||||||
pub async fn block_by_username(
|
pub async fn block_by_username(
|
||||||
blocks: &dyn BlockRepository,
|
blocks: &dyn BlockRepository,
|
||||||
users: &dyn UserReader,
|
users: &dyn UserReader,
|
||||||
federation: &dyn FederationBlockPort,
|
|
||||||
events: &dyn EventPublisher,
|
events: &dyn EventPublisher,
|
||||||
blocker_id: &UserId,
|
blocker_id: &UserId,
|
||||||
username: &str,
|
username: &str,
|
||||||
) -> Result<(), DomainError> {
|
) -> Result<(), DomainError> {
|
||||||
if username.contains('@') {
|
|
||||||
return federation.block_remote(blocker_id, username).await;
|
|
||||||
}
|
|
||||||
let uname = Username::new(username).map_err(|_| DomainError::NotFound)?;
|
let uname = Username::new(username).map_err(|_| DomainError::NotFound)?;
|
||||||
let target = users
|
let target = users
|
||||||
.find_by_username(&uname)
|
.find_by_username(&uname)
|
||||||
@@ -236,14 +228,10 @@ pub async fn block_by_username(
|
|||||||
pub async fn unblock_by_username(
|
pub async fn unblock_by_username(
|
||||||
blocks: &dyn BlockRepository,
|
blocks: &dyn BlockRepository,
|
||||||
users: &dyn UserReader,
|
users: &dyn UserReader,
|
||||||
federation: &dyn FederationBlockPort,
|
|
||||||
events: &dyn EventPublisher,
|
events: &dyn EventPublisher,
|
||||||
blocker_id: &UserId,
|
blocker_id: &UserId,
|
||||||
username: &str,
|
username: &str,
|
||||||
) -> Result<(), DomainError> {
|
) -> Result<(), DomainError> {
|
||||||
if username.contains('@') {
|
|
||||||
return federation.unblock_remote(blocker_id, username).await;
|
|
||||||
}
|
|
||||||
let uname = Username::new(username).map_err(|_| DomainError::NotFound)?;
|
let uname = Username::new(username).map_err(|_| DomainError::NotFound)?;
|
||||||
let target = users
|
let target = users
|
||||||
.find_by_username(&uname)
|
.find_by_username(&uname)
|
||||||
@@ -292,13 +280,5 @@ pub async fn unblock_user(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_local_friends(
|
|
||||||
follows: &dyn FollowRepository,
|
|
||||||
user_id: &UserId,
|
|
||||||
page: &PageParams,
|
|
||||||
) -> Result<Paginated<User>, DomainError> {
|
|
||||||
follows.list_mutual(user_id, page).await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests;
|
mod tests;
|
||||||
|
|||||||
@@ -34,7 +34,6 @@ async fn like_and_unlike() {
|
|||||||
visibility: Visibility::Public,
|
visibility: Visibility::Public,
|
||||||
content_warning: None,
|
content_warning: None,
|
||||||
sensitive: false,
|
sensitive: false,
|
||||||
mood: None,
|
|
||||||
}));
|
}));
|
||||||
like_thought(&store, &store, &alice.id, &tid).await.unwrap();
|
like_thought(&store, &store, &alice.id, &tid).await.unwrap();
|
||||||
assert_eq!(store.likes.lock().unwrap().len(), 1);
|
assert_eq!(store.likes.lock().unwrap().len(), 1);
|
||||||
@@ -205,51 +204,3 @@ async fn boost_and_unboost() {
|
|||||||
.iter()
|
.iter()
|
||||||
.any(|e| matches!(e, DomainEvent::BoostRemoved { .. })));
|
.any(|e| matches!(e, DomainEvent::BoostRemoved { .. })));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn get_local_friends_returns_mutual_follows() {
|
|
||||||
use domain::models::feed::PageParams;
|
|
||||||
let store = TestStore::default();
|
|
||||||
let alice = user("alice");
|
|
||||||
let bob = user("bob");
|
|
||||||
let carol = user("carol");
|
|
||||||
|
|
||||||
store
|
|
||||||
.users
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.extend([alice.clone(), bob.clone(), carol.clone()]);
|
|
||||||
|
|
||||||
// alice ↔ bob = friends; alice → carol but not back
|
|
||||||
store.follows.lock().unwrap().extend([
|
|
||||||
domain::models::social::Follow {
|
|
||||||
follower_id: alice.id.clone(),
|
|
||||||
following_id: bob.id.clone(),
|
|
||||||
state: domain::models::social::FollowState::Accepted,
|
|
||||||
ap_id: None,
|
|
||||||
created_at: chrono::Utc::now(),
|
|
||||||
},
|
|
||||||
domain::models::social::Follow {
|
|
||||||
follower_id: bob.id.clone(),
|
|
||||||
following_id: alice.id.clone(),
|
|
||||||
state: domain::models::social::FollowState::Accepted,
|
|
||||||
ap_id: None,
|
|
||||||
created_at: chrono::Utc::now(),
|
|
||||||
},
|
|
||||||
domain::models::social::Follow {
|
|
||||||
follower_id: alice.id.clone(),
|
|
||||||
following_id: carol.id.clone(),
|
|
||||||
state: domain::models::social::FollowState::Accepted,
|
|
||||||
ap_id: None,
|
|
||||||
created_at: chrono::Utc::now(),
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
|
|
||||||
let page = PageParams {
|
|
||||||
page: 1,
|
|
||||||
per_page: 20,
|
|
||||||
};
|
|
||||||
let result = get_local_friends(&store, &alice.id, &page).await.unwrap();
|
|
||||||
assert_eq!(result.total, 1);
|
|
||||||
assert_eq!(result.items[0].id, bob.id);
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -26,7 +26,6 @@ pub struct CreateThoughtInput {
|
|||||||
pub visibility: Option<String>,
|
pub visibility: Option<String>,
|
||||||
pub content_warning: Option<String>,
|
pub content_warning: Option<String>,
|
||||||
pub sensitive: bool,
|
pub sensitive: bool,
|
||||||
pub mood: Option<String>,
|
|
||||||
}
|
}
|
||||||
pub struct CreateThoughtOutput {
|
pub struct CreateThoughtOutput {
|
||||||
pub thought: Thought,
|
pub thought: Thought,
|
||||||
@@ -40,11 +39,6 @@ pub async fn create_thought(
|
|||||||
outbox: &dyn OutboxWriter,
|
outbox: &dyn OutboxWriter,
|
||||||
input: CreateThoughtInput,
|
input: CreateThoughtInput,
|
||||||
) -> Result<CreateThoughtOutput, DomainError> {
|
) -> Result<CreateThoughtOutput, DomainError> {
|
||||||
if let Some(ref m) = input.mood {
|
|
||||||
if m.len() > 64 {
|
|
||||||
return Err(DomainError::InvalidInput("mood: max 64 chars".into()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let content = Content::new_local(input.content)?;
|
let content = Content::new_local(input.content)?;
|
||||||
let visibility = match input.visibility.as_deref() {
|
let visibility = match input.visibility.as_deref() {
|
||||||
Some("followers") => Visibility::Followers,
|
Some("followers") => Visibility::Followers,
|
||||||
@@ -60,7 +54,6 @@ pub async fn create_thought(
|
|||||||
visibility,
|
visibility,
|
||||||
content_warning: input.content_warning,
|
content_warning: input.content_warning,
|
||||||
sensitive: input.sensitive,
|
sensitive: input.sensitive,
|
||||||
mood: input.mood,
|
|
||||||
});
|
});
|
||||||
thoughts.save(&thought).await?;
|
thoughts.save(&thought).await?;
|
||||||
|
|
||||||
|
|||||||
@@ -22,7 +22,6 @@ fn input(uid: UserId) -> CreateThoughtInput {
|
|||||||
visibility: None,
|
visibility: None,
|
||||||
content_warning: None,
|
content_warning: None,
|
||||||
sensitive: false,
|
sensitive: false,
|
||||||
mood: None,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -208,7 +207,6 @@ async fn create_reply_sets_in_reply_to_id() {
|
|||||||
visibility: None,
|
visibility: None,
|
||||||
content_warning: None,
|
content_warning: None,
|
||||||
sensitive: false,
|
sensitive: false,
|
||||||
mood: None,
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
@@ -245,7 +243,6 @@ fn make_thought(user_id: UserId) -> Thought {
|
|||||||
visibility: Visibility::Public,
|
visibility: Visibility::Public,
|
||||||
content_warning: None,
|
content_warning: None,
|
||||||
sensitive: false,
|
sensitive: false,
|
||||||
mood: None,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -298,7 +295,6 @@ async fn get_thread_views_batches_correctly() {
|
|||||||
visibility: Visibility::Public,
|
visibility: Visibility::Public,
|
||||||
content_warning: None,
|
content_warning: None,
|
||||||
sensitive: false,
|
sensitive: false,
|
||||||
mood: None,
|
|
||||||
});
|
});
|
||||||
<TestStore as ThoughtRepository>::save(&store, &reply)
|
<TestStore as ThoughtRepository>::save(&store, &reply)
|
||||||
.await
|
.await
|
||||||
|
|||||||
@@ -14,15 +14,10 @@ postgres = { workspace = true }
|
|||||||
postgres-search = { workspace = true }
|
postgres-search = { workspace = true }
|
||||||
postgres-federation = { workspace = true }
|
postgres-federation = { workspace = true }
|
||||||
activitypub = { workspace = true }
|
activitypub = { workspace = true }
|
||||||
k-ap = { version = "0.4.4", registry = "gitea" }
|
k-ap = { git = "https://git.gabrielkaszewski.dev/GKaszewski/k-ap.git", tag = "v0.1.2" }
|
||||||
serde_json = { workspace = true }
|
|
||||||
anyhow = { workspace = true }
|
|
||||||
nats = { workspace = true }
|
nats = { workspace = true }
|
||||||
event-transport = { workspace = true }
|
event-transport = { workspace = true }
|
||||||
event-payload = { workspace = true }
|
|
||||||
auth = { workspace = true }
|
auth = { workspace = true }
|
||||||
storage = { workspace = true }
|
|
||||||
application = { workspace = true }
|
|
||||||
sqlx = { workspace = true }
|
sqlx = { workspace = true }
|
||||||
async-nats = { workspace = true }
|
async-nats = { workspace = true }
|
||||||
async-trait = { workspace = true }
|
async-trait = { workspace = true }
|
||||||
|
|||||||
@@ -11,18 +11,6 @@ pub struct Config {
|
|||||||
pub host: String,
|
pub host: String,
|
||||||
pub cors_origins: String,
|
pub cors_origins: String,
|
||||||
pub rate_limit: Option<u32>,
|
pub rate_limit: Option<u32>,
|
||||||
// Storage
|
|
||||||
pub storage_backend: String,
|
|
||||||
pub storage_path: Option<String>,
|
|
||||||
pub storage_prefix: String,
|
|
||||||
pub s3_endpoint: Option<String>,
|
|
||||||
pub s3_access_key_id: Option<String>,
|
|
||||||
pub s3_secret_access_key: Option<String>,
|
|
||||||
pub s3_bucket: Option<String>,
|
|
||||||
pub s3_region: Option<String>,
|
|
||||||
// Upload limits
|
|
||||||
pub upload_max_bytes: usize,
|
|
||||||
pub upload_allowed_types: Vec<String>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Config {
|
impl Config {
|
||||||
@@ -31,12 +19,12 @@ impl Config {
|
|||||||
Self {
|
Self {
|
||||||
database_url: std::env::var("DATABASE_URL").expect("DATABASE_URL is required"),
|
database_url: std::env::var("DATABASE_URL").expect("DATABASE_URL is required"),
|
||||||
jwt_secret: std::env::var("JWT_SECRET").expect("JWT_SECRET is required"),
|
jwt_secret: std::env::var("JWT_SECRET").expect("JWT_SECRET is required"),
|
||||||
base_url: std::env::var("BASE_URL").unwrap_or_else(|_| "http://localhost:8000".into()),
|
base_url: std::env::var("BASE_URL").unwrap_or_else(|_| "http://localhost:3000".into()),
|
||||||
nats_url: std::env::var("NATS_URL").ok(),
|
nats_url: std::env::var("NATS_URL").ok(),
|
||||||
port: std::env::var("PORT")
|
port: std::env::var("PORT")
|
||||||
.ok()
|
.ok()
|
||||||
.and_then(|p| p.parse().ok())
|
.and_then(|p| p.parse().ok())
|
||||||
.unwrap_or(8000),
|
.unwrap_or(3000),
|
||||||
allow_registration: std::env::var("ALLOW_REGISTRATION")
|
allow_registration: std::env::var("ALLOW_REGISTRATION")
|
||||||
.map(|v| v == "true")
|
.map(|v| v == "true")
|
||||||
.unwrap_or(true),
|
.unwrap_or(true),
|
||||||
@@ -48,23 +36,6 @@ impl Config {
|
|||||||
rate_limit: std::env::var("RATE_LIMIT")
|
rate_limit: std::env::var("RATE_LIMIT")
|
||||||
.ok()
|
.ok()
|
||||||
.and_then(|v| v.parse().ok()),
|
.and_then(|v| v.parse().ok()),
|
||||||
storage_backend: std::env::var("STORAGE_BACKEND").unwrap_or_else(|_| "local".into()),
|
|
||||||
storage_path: std::env::var("STORAGE_PATH").ok(),
|
|
||||||
storage_prefix: std::env::var("STORAGE_PREFIX").unwrap_or_default(),
|
|
||||||
s3_endpoint: std::env::var("S3_ENDPOINT").ok(),
|
|
||||||
s3_access_key_id: std::env::var("S3_ACCESS_KEY_ID").ok(),
|
|
||||||
s3_secret_access_key: std::env::var("S3_SECRET_ACCESS_KEY").ok(),
|
|
||||||
s3_bucket: std::env::var("S3_BUCKET").ok(),
|
|
||||||
s3_region: std::env::var("S3_REGION").ok(),
|
|
||||||
upload_max_bytes: std::env::var("UPLOAD_MAX_BYTES")
|
|
||||||
.ok()
|
|
||||||
.and_then(|v| v.parse().ok())
|
|
||||||
.unwrap_or(5 * 1024 * 1024),
|
|
||||||
upload_allowed_types: std::env::var("UPLOAD_ALLOWED_TYPES")
|
|
||||||
.unwrap_or_else(|_| "image/jpeg,image/png,image/gif,image/webp,image/avif".into())
|
|
||||||
.split(',')
|
|
||||||
.map(|s| s.trim().to_string())
|
|
||||||
.collect(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,24 +5,21 @@ use async_trait::async_trait;
|
|||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use application::use_cases::profile::UploadConfig;
|
use activitypub::{ApFederationAdapter, ThoughtsObjectHandler};
|
||||||
use storage::{build_store, ObjectStorageAdapter, StorageConfig};
|
use k_ap::ActivityPubService;
|
||||||
|
|
||||||
use activitypub::{build_ap_service, ApFederationAdapter, ApServiceConfig, ThoughtsObjectHandler};
|
|
||||||
use auth::ApiKeyServiceImpl;
|
use auth::ApiKeyServiceImpl;
|
||||||
use domain::{
|
use domain::{
|
||||||
errors::DomainError,
|
errors::DomainError,
|
||||||
events::DomainEvent,
|
events::DomainEvent,
|
||||||
ports::{EventPublisher, OutboxWriter},
|
ports::{EventPublisher, OutboxWriter},
|
||||||
};
|
};
|
||||||
use event_transport::{EventPublisherAdapter, Transport};
|
use event_transport::EventPublisherAdapter;
|
||||||
use k_ap::FederationEvent;
|
|
||||||
use nats::NatsTransport;
|
use nats::NatsTransport;
|
||||||
use postgres::activitypub::PgActivityPubRepository;
|
use postgres::activitypub::PgActivityPubRepository;
|
||||||
use postgres::engagement::PgEngagementRepository;
|
use postgres::engagement::PgEngagementRepository;
|
||||||
use postgres::outbox::PgOutboxWriter;
|
use postgres::outbox::PgOutboxWriter;
|
||||||
use postgres::remote_actor_connections::PgRemoteActorConnectionRepository;
|
use postgres::remote_actor_connections::PgRemoteActorConnectionRepository;
|
||||||
use postgres_federation::{PgApUserRepository, PgFederationRepository};
|
use postgres_federation::{PostgresApUserRepository, PostgresFederationRepository};
|
||||||
use presentation::state::AppState;
|
use presentation::state::AppState;
|
||||||
|
|
||||||
use crate::config::Config;
|
use crate::config::Config;
|
||||||
@@ -42,60 +39,6 @@ impl EventPublisher for NoOpEventPublisher {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct KapPublisher(NatsTransport);
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl k_ap::data::EventPublisher for KapPublisher {
|
|
||||||
async fn publish(&self, event: FederationEvent) -> anyhow::Result<()> {
|
|
||||||
let (subject, payload) = match event {
|
|
||||||
FederationEvent::DeliveryRequested {
|
|
||||||
inbox,
|
|
||||||
activity,
|
|
||||||
signing_actor_id,
|
|
||||||
} => (
|
|
||||||
"federation.delivery.requested",
|
|
||||||
serde_json::to_vec(&event_payload::EventPayload::FederationDeliveryRequested {
|
|
||||||
inbox: inbox.to_string(),
|
|
||||||
activity,
|
|
||||||
signing_actor_id: signing_actor_id.to_string(),
|
|
||||||
})?,
|
|
||||||
),
|
|
||||||
FederationEvent::BackfillRequested {
|
|
||||||
owner_user_id,
|
|
||||||
follower_inbox_url,
|
|
||||||
} => (
|
|
||||||
"federation.backfill.requested",
|
|
||||||
serde_json::to_vec(&event_payload::EventPayload::FederationBackfillRequested {
|
|
||||||
owner_user_id: owner_user_id.to_string(),
|
|
||||||
follower_inbox_url,
|
|
||||||
})?,
|
|
||||||
),
|
|
||||||
FederationEvent::OutboundFollowAccepted {
|
|
||||||
local_user_id,
|
|
||||||
remote_actor_url,
|
|
||||||
outbox_url,
|
|
||||||
} => (
|
|
||||||
"federation.outbound_follow.accepted",
|
|
||||||
serde_json::to_vec(
|
|
||||||
&event_payload::EventPayload::FederationOutboundFollowAccepted {
|
|
||||||
local_user_id: local_user_id.to_string(),
|
|
||||||
remote_actor_url,
|
|
||||||
outbox_url,
|
|
||||||
},
|
|
||||||
)?,
|
|
||||||
),
|
|
||||||
FederationEvent::DeliveryFailed { inbox, error, .. } => {
|
|
||||||
tracing::warn!(%inbox, %error, "AP delivery failed permanently");
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
};
|
|
||||||
self.0
|
|
||||||
.publish_bytes(subject, &payload)
|
|
||||||
.await
|
|
||||||
.map_err(|e| anyhow::anyhow!(e))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn build(cfg: &Config) -> Infrastructure {
|
pub async fn build(cfg: &Config) -> Infrastructure {
|
||||||
// 1. Database connection + migrations
|
// 1. Database connection + migrations
|
||||||
let pool = PgPool::connect(&cfg.database_url)
|
let pool = PgPool::connect(&cfg.database_url)
|
||||||
@@ -108,91 +51,59 @@ pub async fn build(cfg: &Config) -> Infrastructure {
|
|||||||
tracing::info!("Database connected and migrations applied");
|
tracing::info!("Database connected and migrations applied");
|
||||||
|
|
||||||
// 2. Event publisher — real NATS or no-op fallback
|
// 2. Event publisher — real NATS or no-op fallback
|
||||||
let nats_client: Option<async_nats::Client> = match &cfg.nats_url {
|
let event_publisher: Arc<dyn EventPublisher> = match &cfg.nats_url {
|
||||||
Some(url) => match async_nats::connect(url).await {
|
Some(url) => match async_nats::connect(url).await {
|
||||||
Ok(client) => {
|
Ok(client) => {
|
||||||
tracing::info!("Connected to NATS at {url}");
|
tracing::info!("Connected to NATS at {url}");
|
||||||
if let Err(e) = nats::ensure_stream(&client).await {
|
if let Err(e) = nats::ensure_stream(&client).await {
|
||||||
tracing::warn!("JetStream stream setup failed: {e} — events may be lost");
|
tracing::warn!("JetStream stream setup failed: {e} — events may be lost");
|
||||||
}
|
}
|
||||||
Some(client)
|
Arc::new(EventPublisherAdapter::new(NatsTransport::new(client)))
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
tracing::warn!("NATS connect failed ({e}) — falling back to no-op publisher");
|
tracing::warn!("NATS connect failed ({e}) — falling back to no-op publisher");
|
||||||
None
|
Arc::new(NoOpEventPublisher)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
None => {
|
None => {
|
||||||
tracing::info!("NATS_URL not set — using no-op event publisher");
|
tracing::info!("NATS_URL not set — using no-op event publisher");
|
||||||
None
|
Arc::new(NoOpEventPublisher)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let event_publisher: Arc<dyn EventPublisher> = match &nats_client {
|
|
||||||
Some(client) => Arc::new(EventPublisherAdapter::new(NatsTransport::new(
|
|
||||||
client.clone(),
|
|
||||||
))),
|
|
||||||
None => Arc::new(NoOpEventPublisher),
|
|
||||||
};
|
|
||||||
let kap_publisher: Option<Arc<dyn k_ap::data::EventPublisher>> = nats_client
|
|
||||||
.as_ref()
|
|
||||||
.map(|c| Arc::new(KapPublisher(NatsTransport::new(c.clone()))) as _);
|
|
||||||
|
|
||||||
// 3. ActivityPub federation
|
// 3. ActivityPub federation
|
||||||
let connections_repo = Arc::new(PgRemoteActorConnectionRepository::new(pool.clone()));
|
let connections_repo =
|
||||||
let fed_repo = Arc::new(PgFederationRepository::new(pool.clone()));
|
Arc::new(PgRemoteActorConnectionRepository::new(pool.clone()));
|
||||||
let likes: Arc<dyn domain::ports::LikeRepository> =
|
let raw_ap_service = Arc::new(
|
||||||
Arc::new(postgres::like::PgLikeRepository::new(pool.clone()));
|
ActivityPubService::builder(
|
||||||
let boosts: Arc<dyn domain::ports::BoostRepository> =
|
Arc::new(PostgresFederationRepository::new(pool.clone())),
|
||||||
Arc::new(postgres::boost::PgBoostRepository::new(pool.clone()));
|
Arc::new(PostgresApUserRepository::new(
|
||||||
let ap_handler = Arc::new(ThoughtsObjectHandler::new(
|
pool.clone(),
|
||||||
|
cfg.base_url.clone(),
|
||||||
|
)),
|
||||||
|
Arc::new(ThoughtsObjectHandler::new(
|
||||||
Arc::new(PgActivityPubRepository::new(pool.clone())),
|
Arc::new(PgActivityPubRepository::new(pool.clone())),
|
||||||
&cfg.base_url,
|
&cfg.base_url,
|
||||||
Some(event_publisher.clone()),
|
Some(event_publisher.clone()),
|
||||||
Arc::new(postgres::tag::PgTagRepository::new(pool.clone())),
|
Arc::new(postgres::tag::PgTagRepository::new(pool.clone())),
|
||||||
likes.clone(),
|
)),
|
||||||
boosts.clone(),
|
cfg.base_url.clone(),
|
||||||
));
|
)
|
||||||
let (_raw, ap_service) = build_ap_service(ApServiceConfig {
|
.allow_registration(cfg.allow_registration)
|
||||||
base_url: cfg.base_url.clone(),
|
.software_name("thoughts")
|
||||||
activity_repo: fed_repo.clone(),
|
.debug(cfg.debug)
|
||||||
follow_repo: fed_repo.clone(),
|
.build()
|
||||||
actor_repo: fed_repo.clone(),
|
.await
|
||||||
blocklist_repo: fed_repo.clone(),
|
.expect("Failed to build ActivityPubService"),
|
||||||
user_repo: Arc::new(PgApUserRepository::new(pool.clone(), cfg.base_url.clone())),
|
|
||||||
ap_handler,
|
|
||||||
connections_repo,
|
|
||||||
event_publisher: kap_publisher,
|
|
||||||
allow_registration: cfg.allow_registration,
|
|
||||||
debug: cfg.debug,
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
|
|
||||||
// 4. Storage adapter
|
|
||||||
let storage_cfg = StorageConfig {
|
|
||||||
backend: cfg.storage_backend.clone(),
|
|
||||||
local_path: cfg.storage_path.clone(),
|
|
||||||
s3_endpoint: cfg.s3_endpoint.clone(),
|
|
||||||
s3_access_key_id: cfg.s3_access_key_id.clone(),
|
|
||||||
s3_secret_access_key: cfg.s3_secret_access_key.clone(),
|
|
||||||
s3_bucket: cfg.s3_bucket.clone(),
|
|
||||||
s3_region: cfg.s3_region.clone(),
|
|
||||||
};
|
|
||||||
let object_store = build_store(&storage_cfg).expect("Failed to build object store");
|
|
||||||
let media_adapter: Arc<dyn domain::ports::MediaStore> = Arc::new(
|
|
||||||
ObjectStorageAdapter::new(object_store, cfg.storage_prefix.clone())
|
|
||||||
.expect("Failed to create storage adapter"),
|
|
||||||
);
|
);
|
||||||
let upload_config = UploadConfig {
|
let ap_service = Arc::new(ApFederationAdapter::new(raw_ap_service, connections_repo));
|
||||||
max_bytes: cfg.upload_max_bytes,
|
|
||||||
allowed_content_types: cfg.upload_allowed_types.clone(),
|
|
||||||
};
|
|
||||||
|
|
||||||
// 5. Application state
|
// 4. Application state
|
||||||
let state = AppState {
|
let state = AppState {
|
||||||
users: Arc::new(postgres::user::PgUserRepository::new(pool.clone())),
|
users: Arc::new(postgres::user::PgUserRepository::new(pool.clone())),
|
||||||
thoughts: Arc::new(postgres::thought::PgThoughtRepository::new(pool.clone())),
|
thoughts: Arc::new(postgres::thought::PgThoughtRepository::new(pool.clone())),
|
||||||
likes: likes.clone(),
|
likes: Arc::new(postgres::like::PgLikeRepository::new(pool.clone())),
|
||||||
boosts: boosts.clone(),
|
boosts: Arc::new(postgres::boost::PgBoostRepository::new(pool.clone())),
|
||||||
follows: Arc::new(postgres::follow::PgFollowRepository::new(pool.clone())),
|
follows: Arc::new(postgres::follow::PgFollowRepository::new(pool.clone())),
|
||||||
blocks: Arc::new(postgres::block::PgBlockRepository::new(pool.clone())),
|
blocks: Arc::new(postgres::block::PgBlockRepository::new(pool.clone())),
|
||||||
tags: Arc::new(postgres::tag::PgTagRepository::new(pool.clone())),
|
tags: Arc::new(postgres::tag::PgTagRepository::new(pool.clone())),
|
||||||
@@ -229,9 +140,6 @@ pub async fn build(cfg: &Config) -> Infrastructure {
|
|||||||
postgres::api_key::PgApiKeyRepository::new(pool.clone()),
|
postgres::api_key::PgApiKeyRepository::new(pool.clone()),
|
||||||
))),
|
))),
|
||||||
engagement: Arc::new(PgEngagementRepository::new(pool.clone())),
|
engagement: Arc::new(PgEngagementRepository::new(pool.clone())),
|
||||||
media: media_adapter,
|
|
||||||
upload_config,
|
|
||||||
base_url: cfg.base_url.clone(),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
Infrastructure { state, ap_service }
|
Infrastructure { state, ap_service }
|
||||||
|
|||||||
@@ -35,13 +35,8 @@ async fn main() {
|
|||||||
.allow_headers(tower_http::cors::Any)
|
.allow_headers(tower_http::cors::Any)
|
||||||
};
|
};
|
||||||
|
|
||||||
let ap_router = infra
|
|
||||||
.ap_service
|
|
||||||
.router::<presentation::state::AppState>()
|
|
||||||
.layer(axum::extract::DefaultBodyLimit::max(256 * 1024));
|
|
||||||
|
|
||||||
let base = presentation::routes::router()
|
let base = presentation::routes::router()
|
||||||
.merge(ap_router)
|
.merge(infra.ap_service.router::<presentation::state::AppState>())
|
||||||
.with_state(infra.state)
|
.with_state(infra.state)
|
||||||
.layer(cors);
|
.layer(cors);
|
||||||
|
|
||||||
|
|||||||
@@ -12,10 +12,8 @@ thiserror = { workspace = true }
|
|||||||
uuid = { workspace = true }
|
uuid = { workspace = true }
|
||||||
chrono = { workspace = true }
|
chrono = { workspace = true }
|
||||||
serde = { workspace = true }
|
serde = { workspace = true }
|
||||||
serde_json = { workspace = true }
|
|
||||||
futures = { workspace = true }
|
futures = { workspace = true }
|
||||||
url = { workspace = true }
|
url = { workspace = true }
|
||||||
bytes = { workspace = true }
|
|
||||||
sha2 = { version = "0.10", optional = true }
|
sha2 = { version = "0.10", optional = true }
|
||||||
hex = { version = "0.4", optional = true }
|
hex = { version = "0.4", optional = true }
|
||||||
|
|
||||||
|
|||||||
@@ -63,18 +63,6 @@ pub enum DomainEvent {
|
|||||||
ProfileUpdated {
|
ProfileUpdated {
|
||||||
user_id: UserId,
|
user_id: UserId,
|
||||||
},
|
},
|
||||||
RemoteFollowAccepted {
|
|
||||||
local_user_id: UserId,
|
|
||||||
remote_actor_url: String,
|
|
||||||
},
|
|
||||||
RemoteFollowRejected {
|
|
||||||
local_user_id: UserId,
|
|
||||||
remote_actor_url: String,
|
|
||||||
},
|
|
||||||
ActorMoved {
|
|
||||||
user_id: UserId,
|
|
||||||
new_actor_url: String,
|
|
||||||
},
|
|
||||||
MentionReceived {
|
MentionReceived {
|
||||||
thought_id: ThoughtId,
|
thought_id: ThoughtId,
|
||||||
mentioned_user_id: UserId,
|
mentioned_user_id: UserId,
|
||||||
|
|||||||
@@ -8,12 +8,10 @@ pub struct RemoteActor {
|
|||||||
pub avatar_url: Option<String>,
|
pub avatar_url: Option<String>,
|
||||||
pub bio: Option<String>,
|
pub bio: Option<String>,
|
||||||
pub banner_url: Option<String>,
|
pub banner_url: Option<String>,
|
||||||
pub also_known_as: Vec<String>,
|
pub also_known_as: Option<String>,
|
||||||
pub outbox_url: Option<String>,
|
pub outbox_url: Option<String>,
|
||||||
pub followers_url: Option<String>,
|
pub followers_url: Option<String>,
|
||||||
pub following_url: Option<String>,
|
pub following_url: Option<String>,
|
||||||
pub inbox_url: Option<String>,
|
|
||||||
pub shared_inbox_url: Option<String>,
|
|
||||||
pub attachment: Vec<(String, String)>,
|
pub attachment: Vec<(String, String)>,
|
||||||
pub last_fetched_at: DateTime<Utc>,
|
pub last_fetched_at: DateTime<Utc>,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,15 +15,12 @@ pub struct Thought {
|
|||||||
pub user_id: UserId,
|
pub user_id: UserId,
|
||||||
pub content: Content,
|
pub content: Content,
|
||||||
pub in_reply_to_id: Option<ThoughtId>,
|
pub in_reply_to_id: Option<ThoughtId>,
|
||||||
pub in_reply_to_url: Option<String>,
|
|
||||||
pub visibility: Visibility,
|
pub visibility: Visibility,
|
||||||
pub content_warning: Option<String>,
|
pub content_warning: Option<String>,
|
||||||
pub sensitive: bool,
|
pub sensitive: bool,
|
||||||
pub local: bool,
|
pub local: bool,
|
||||||
pub created_at: DateTime<Utc>,
|
pub created_at: DateTime<Utc>,
|
||||||
pub updated_at: Option<DateTime<Utc>>,
|
pub updated_at: Option<DateTime<Utc>>,
|
||||||
pub note_extensions: Option<serde_json::Value>,
|
|
||||||
pub mood: Option<String>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Visibility {
|
impl Visibility {
|
||||||
@@ -57,7 +54,6 @@ pub struct NewThought {
|
|||||||
pub visibility: Visibility,
|
pub visibility: Visibility,
|
||||||
pub content_warning: Option<String>,
|
pub content_warning: Option<String>,
|
||||||
pub sensitive: bool,
|
pub sensitive: bool,
|
||||||
pub mood: Option<String>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Thought {
|
impl Thought {
|
||||||
@@ -67,15 +63,12 @@ impl Thought {
|
|||||||
user_id: p.user_id,
|
user_id: p.user_id,
|
||||||
content: p.content,
|
content: p.content,
|
||||||
in_reply_to_id: p.in_reply_to_id,
|
in_reply_to_id: p.in_reply_to_id,
|
||||||
in_reply_to_url: None,
|
|
||||||
visibility: p.visibility,
|
visibility: p.visibility,
|
||||||
content_warning: p.content_warning,
|
content_warning: p.content_warning,
|
||||||
sensitive: p.sensitive,
|
sensitive: p.sensitive,
|
||||||
local: true,
|
local: true,
|
||||||
created_at: Utc::now(),
|
created_at: Utc::now(),
|
||||||
updated_at: None,
|
updated_at: None,
|
||||||
note_extensions: None,
|
|
||||||
mood: p.mood,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,8 +8,6 @@ pub struct UpdateProfileInput {
|
|||||||
pub avatar_url: Option<String>,
|
pub avatar_url: Option<String>,
|
||||||
pub header_url: Option<String>,
|
pub header_url: Option<String>,
|
||||||
pub custom_css: Option<String>,
|
pub custom_css: Option<String>,
|
||||||
pub profile_fields: Option<Vec<(String, String)>>,
|
|
||||||
pub custom_moods: Option<Vec<(String, String)>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@@ -23,8 +21,6 @@ pub struct User {
|
|||||||
pub avatar_url: Option<String>,
|
pub avatar_url: Option<String>,
|
||||||
pub header_url: Option<String>,
|
pub header_url: Option<String>,
|
||||||
pub custom_css: Option<String>,
|
pub custom_css: Option<String>,
|
||||||
pub profile_fields: Vec<(String, String)>,
|
|
||||||
pub custom_moods: Vec<(String, String)>,
|
|
||||||
pub local: bool,
|
pub local: bool,
|
||||||
pub created_at: DateTime<Utc>,
|
pub created_at: DateTime<Utc>,
|
||||||
pub updated_at: DateTime<Utc>,
|
pub updated_at: DateTime<Utc>,
|
||||||
@@ -48,31 +44,9 @@ impl User {
|
|||||||
avatar_url: None,
|
avatar_url: None,
|
||||||
header_url: None,
|
header_url: None,
|
||||||
custom_css: None,
|
custom_css: None,
|
||||||
profile_fields: vec![],
|
|
||||||
custom_moods: vec![],
|
|
||||||
local: true,
|
local: true,
|
||||||
created_at: now,
|
created_at: now,
|
||||||
updated_at: now,
|
updated_at: now,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn new_remote(id: UserId, username: Username, email: Email) -> Self {
|
|
||||||
let now = Utc::now();
|
|
||||||
Self {
|
|
||||||
id,
|
|
||||||
username,
|
|
||||||
email,
|
|
||||||
password_hash: PasswordHash(String::new()),
|
|
||||||
display_name: None,
|
|
||||||
bio: None,
|
|
||||||
avatar_url: None,
|
|
||||||
header_url: None,
|
|
||||||
custom_css: None,
|
|
||||||
profile_fields: vec![],
|
|
||||||
custom_moods: vec![],
|
|
||||||
local: false,
|
|
||||||
created_at: now,
|
|
||||||
updated_at: now,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::pin::Pin;
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
errors::DomainError,
|
errors::DomainError,
|
||||||
@@ -20,17 +19,6 @@ use crate::{
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use bytes::Bytes;
|
|
||||||
|
|
||||||
pub type DataStream =
|
|
||||||
Pin<Box<dyn futures::stream::Stream<Item = Result<Bytes, DomainError>> + Send>>;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
pub trait MediaStore: Send + Sync {
|
|
||||||
async fn put(&self, key: &str, data: DataStream) -> Result<(), DomainError>;
|
|
||||||
async fn get(&self, key: &str) -> Result<DataStream, DomainError>;
|
|
||||||
async fn delete(&self, key: &str) -> Result<(), DomainError>;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct GeneratedToken {
|
pub struct GeneratedToken {
|
||||||
pub token: String,
|
pub token: String,
|
||||||
@@ -83,11 +71,6 @@ pub trait UserWriter: Send + Sync {
|
|||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
input: UpdateProfileInput,
|
input: UpdateProfileInput,
|
||||||
) -> Result<(), DomainError>;
|
) -> Result<(), DomainError>;
|
||||||
async fn set_also_known_as(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
value: Option<String>,
|
|
||||||
) -> Result<(), DomainError>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Combined supertrait — `AppState.users` stays `Arc<dyn UserRepository>`.
|
/// Combined supertrait — `AppState.users` stays `Arc<dyn UserRepository>`.
|
||||||
@@ -171,11 +154,6 @@ pub trait FollowRepository: Send + Sync {
|
|||||||
&self,
|
&self,
|
||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
) -> Result<Vec<UserId>, DomainError>;
|
) -> Result<Vec<UserId>, DomainError>;
|
||||||
async fn list_mutual(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
page: &PageParams,
|
|
||||||
) -> Result<Paginated<User>, DomainError>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
@@ -297,11 +275,6 @@ pub trait FederationFollowPort: Send + Sync {
|
|||||||
) -> Result<(), DomainError>;
|
) -> Result<(), DomainError>;
|
||||||
async fn get_remote_following(&self, user_id: &UserId)
|
async fn get_remote_following(&self, user_id: &UserId)
|
||||||
-> Result<Vec<RemoteActor>, DomainError>;
|
-> Result<Vec<RemoteActor>, DomainError>;
|
||||||
async fn broadcast_move(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
new_actor_url: url::Url,
|
|
||||||
) -> Result<(), DomainError>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
@@ -327,20 +300,6 @@ pub trait FederationFollowRequestPort: Send + Sync {
|
|||||||
user_id: &UserId,
|
user_id: &UserId,
|
||||||
actor_url: &str,
|
actor_url: &str,
|
||||||
) -> Result<(), DomainError>;
|
) -> Result<(), DomainError>;
|
||||||
|
|
||||||
/// Update follower status to Accepted in DB only — no federation activity sent.
|
|
||||||
async fn mark_follower_accepted(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
actor_url: &str,
|
|
||||||
) -> Result<(), DomainError>;
|
|
||||||
|
|
||||||
/// Remove follower from DB only — no federation activity sent.
|
|
||||||
async fn mark_follower_rejected(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
actor_url: &str,
|
|
||||||
) -> Result<(), DomainError>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
@@ -360,27 +319,15 @@ pub trait FederationFetchPort: Send + Sync {
|
|||||||
) -> Vec<crate::models::actor_connection_summary::ActorConnectionSummary>;
|
) -> Vec<crate::models::actor_connection_summary::ActorConnectionSummary>;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
pub trait FederationBlockPort: Send + Sync {
|
|
||||||
async fn block_remote(&self, local_user_id: &UserId, handle: &str) -> Result<(), DomainError>;
|
|
||||||
async fn unblock_remote(&self, local_user_id: &UserId, handle: &str)
|
|
||||||
-> Result<(), DomainError>;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait FederationActionPort:
|
pub trait FederationActionPort:
|
||||||
FederationLookupPort
|
FederationLookupPort + FederationFollowPort + FederationFollowRequestPort + FederationFetchPort
|
||||||
+ FederationFollowPort
|
|
||||||
+ FederationFollowRequestPort
|
|
||||||
+ FederationFetchPort
|
|
||||||
+ FederationBlockPort
|
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
impl<
|
impl<
|
||||||
T: FederationLookupPort
|
T: FederationLookupPort
|
||||||
+ FederationFollowPort
|
+ FederationFollowPort
|
||||||
+ FederationFollowRequestPort
|
+ FederationFollowRequestPort
|
||||||
+ FederationFetchPort
|
+ FederationFetchPort,
|
||||||
+ FederationBlockPort,
|
|
||||||
> FederationActionPort for T
|
> FederationActionPort for T
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
@@ -443,38 +390,9 @@ impl FeedQuery {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default)]
|
|
||||||
pub enum FeedSort {
|
|
||||||
#[default]
|
|
||||||
Newest,
|
|
||||||
Oldest,
|
|
||||||
MostLiked,
|
|
||||||
MostBoosted,
|
|
||||||
MostDiscussed,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default)]
|
|
||||||
pub struct FeedFilter {
|
|
||||||
pub originals_only: bool,
|
|
||||||
pub replies_only: bool,
|
|
||||||
pub local_only: bool,
|
|
||||||
pub hide_sensitive: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default)]
|
|
||||||
pub struct FeedOptions {
|
|
||||||
pub sort: FeedSort,
|
|
||||||
pub filter: FeedFilter,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct FeedRequest {
|
|
||||||
pub query: FeedQuery,
|
|
||||||
pub options: FeedOptions,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
pub trait FeedRepository: Send + Sync {
|
pub trait FeedRepository: Send + Sync {
|
||||||
async fn query(&self, req: &FeedRequest) -> Result<Paginated<FeedEntry>, DomainError>;
|
async fn query(&self, q: &FeedQuery) -> Result<Paginated<FeedEntry>, DomainError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
@@ -511,136 +429,3 @@ pub trait FederationSchedulerPort: Send + Sync {
|
|||||||
page: u32,
|
page: u32,
|
||||||
) -> Result<(), DomainError>;
|
) -> Result<(), DomainError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Federation content & broadcast ports ────────────────────────────────
|
|
||||||
|
|
||||||
pub struct AcceptNoteInput<'a> {
|
|
||||||
pub ap_id: &'a str,
|
|
||||||
pub author_id: &'a UserId,
|
|
||||||
pub content: &'a str,
|
|
||||||
pub published: chrono::DateTime<chrono::Utc>,
|
|
||||||
pub sensitive: bool,
|
|
||||||
pub content_warning: Option<String>,
|
|
||||||
pub visibility: &'a str,
|
|
||||||
pub in_reply_to: Option<&'a str>,
|
|
||||||
pub note_extensions: Option<serde_json::Value>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct ActorFederationUrls {
|
|
||||||
pub ap_id: String,
|
|
||||||
pub inbox_url: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct OutboxEntry {
|
|
||||||
pub thought: Thought,
|
|
||||||
pub author_username: Username,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
pub trait FederationContentRepository: Send + Sync {
|
|
||||||
async fn outbox_entries_for_actor(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
) -> Result<Vec<OutboxEntry>, DomainError>;
|
|
||||||
|
|
||||||
async fn outbox_page_for_actor(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
before: Option<chrono::DateTime<chrono::Utc>>,
|
|
||||||
limit: usize,
|
|
||||||
) -> Result<Vec<OutboxEntry>, DomainError>;
|
|
||||||
|
|
||||||
async fn find_remote_actor_id(&self, actor_ap_url: &str)
|
|
||||||
-> Result<Option<UserId>, DomainError>;
|
|
||||||
|
|
||||||
async fn intern_remote_actor(&self, actor_ap_url: &str) -> Result<UserId, DomainError>;
|
|
||||||
|
|
||||||
async fn update_remote_actor_display(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
display_name: Option<&str>,
|
|
||||||
avatar_url: Option<&str>,
|
|
||||||
) -> Result<(), DomainError>;
|
|
||||||
|
|
||||||
async fn accept_note(&self, input: AcceptNoteInput<'_>) -> Result<ThoughtId, DomainError>;
|
|
||||||
|
|
||||||
async fn apply_note_update(
|
|
||||||
&self,
|
|
||||||
ap_id: &str,
|
|
||||||
new_content: &str,
|
|
||||||
note_extensions: Option<serde_json::Value>,
|
|
||||||
) -> Result<(), DomainError>;
|
|
||||||
|
|
||||||
async fn retract_note(&self, ap_id: &str) -> Result<(), DomainError>;
|
|
||||||
|
|
||||||
async fn retract_actor_notes(&self, actor_ap_url: &str) -> Result<(), DomainError>;
|
|
||||||
|
|
||||||
async fn count_local_notes(&self) -> Result<u64, DomainError>;
|
|
||||||
|
|
||||||
async fn get_thought_ap_id(
|
|
||||||
&self,
|
|
||||||
thought_id: &ThoughtId,
|
|
||||||
) -> Result<Option<String>, DomainError>;
|
|
||||||
|
|
||||||
async fn get_actor_ap_urls(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
) -> Result<Option<ActorFederationUrls>, DomainError>;
|
|
||||||
|
|
||||||
async fn sync_remote_actor_to_user(&self, actor_ap_url: &str) -> Result<(), DomainError>;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
pub trait FederationBroadcastPort: Send + Sync {
|
|
||||||
async fn broadcast_create(
|
|
||||||
&self,
|
|
||||||
author_user_id: &UserId,
|
|
||||||
thought: &Thought,
|
|
||||||
author_username: &str,
|
|
||||||
in_reply_to_url: Option<&str>,
|
|
||||||
) -> Result<(), DomainError>;
|
|
||||||
|
|
||||||
async fn broadcast_delete(
|
|
||||||
&self,
|
|
||||||
author_user_id: &UserId,
|
|
||||||
thought_ap_id: &str,
|
|
||||||
) -> Result<(), DomainError>;
|
|
||||||
|
|
||||||
async fn broadcast_update(
|
|
||||||
&self,
|
|
||||||
author_user_id: &UserId,
|
|
||||||
thought: &Thought,
|
|
||||||
author_username: &str,
|
|
||||||
in_reply_to_url: Option<&str>,
|
|
||||||
) -> Result<(), DomainError>;
|
|
||||||
|
|
||||||
async fn broadcast_announce(
|
|
||||||
&self,
|
|
||||||
booster_user_id: &UserId,
|
|
||||||
object_ap_id: &str,
|
|
||||||
) -> Result<(), DomainError>;
|
|
||||||
|
|
||||||
async fn broadcast_undo_announce(
|
|
||||||
&self,
|
|
||||||
booster_user_id: &UserId,
|
|
||||||
object_ap_id: &str,
|
|
||||||
) -> Result<(), DomainError>;
|
|
||||||
|
|
||||||
async fn broadcast_like(
|
|
||||||
&self,
|
|
||||||
liker_user_id: &UserId,
|
|
||||||
object_ap_id: &str,
|
|
||||||
author_inbox_url: &str,
|
|
||||||
) -> Result<(), DomainError>;
|
|
||||||
|
|
||||||
async fn broadcast_undo_like(
|
|
||||||
&self,
|
|
||||||
liker_user_id: &UserId,
|
|
||||||
object_ap_id: &str,
|
|
||||||
author_inbox_url: &str,
|
|
||||||
) -> Result<(), DomainError>;
|
|
||||||
|
|
||||||
async fn broadcast_actor_update(&self, user_id: &UserId) -> Result<(), DomainError>;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -13,7 +13,9 @@ use crate::{
|
|||||||
user::{UpdateProfileInput, User},
|
user::{UpdateProfileInput, User},
|
||||||
},
|
},
|
||||||
ports::*,
|
ports::*,
|
||||||
value_objects::{ApiKeyId, Content, Email, NotificationId, ThoughtId, UserId, Username},
|
value_objects::{
|
||||||
|
ApiKeyId, Content, Email, NotificationId, PasswordHash, ThoughtId, UserId, Username,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
@@ -37,8 +39,6 @@ pub struct TestStore {
|
|||||||
pub actor_ap_ids: Arc<Mutex<HashMap<String, UserId>>>,
|
pub actor_ap_ids: Arc<Mutex<HashMap<String, UserId>>>,
|
||||||
/// ThoughtId → AP object URL (used by get_thought_ap_id)
|
/// ThoughtId → AP object URL (used by get_thought_ap_id)
|
||||||
pub thought_ap_ids: Arc<Mutex<HashMap<ThoughtId, String>>>,
|
pub thought_ap_ids: Arc<Mutex<HashMap<ThoughtId, String>>>,
|
||||||
pub remote_following: Arc<Mutex<Vec<RemoteActor>>>,
|
|
||||||
pub remote_followers: Arc<Mutex<Vec<RemoteActor>>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
@@ -134,30 +134,12 @@ impl UserWriter for TestStore {
|
|||||||
.iter_mut()
|
.iter_mut()
|
||||||
.find(|u| &u.id == user_id)
|
.find(|u| &u.id == user_id)
|
||||||
{
|
{
|
||||||
if let Some(v) = input.display_name {
|
u.display_name = input.display_name;
|
||||||
u.display_name = Some(v);
|
u.bio = input.bio;
|
||||||
|
u.avatar_url = input.avatar_url;
|
||||||
|
u.header_url = input.header_url;
|
||||||
|
u.custom_css = input.custom_css;
|
||||||
}
|
}
|
||||||
if let Some(v) = input.bio {
|
|
||||||
u.bio = Some(v);
|
|
||||||
}
|
|
||||||
if let Some(v) = input.avatar_url {
|
|
||||||
u.avatar_url = Some(v);
|
|
||||||
}
|
|
||||||
if let Some(v) = input.header_url {
|
|
||||||
u.header_url = Some(v);
|
|
||||||
}
|
|
||||||
if let Some(v) = input.custom_css {
|
|
||||||
u.custom_css = Some(v);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn set_also_known_as(
|
|
||||||
&self,
|
|
||||||
_user_id: &UserId,
|
|
||||||
_value: Option<String>,
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -454,46 +436,6 @@ impl FollowRepository for TestStore {
|
|||||||
.map(|f| f.following_id.clone())
|
.map(|f| f.following_id.clone())
|
||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
async fn list_mutual(
|
|
||||||
&self,
|
|
||||||
user_id: &UserId,
|
|
||||||
page: &PageParams,
|
|
||||||
) -> Result<Paginated<User>, DomainError> {
|
|
||||||
use std::collections::HashSet;
|
|
||||||
let follows = self.follows.lock().unwrap();
|
|
||||||
let following_ids: HashSet<UserId> = follows
|
|
||||||
.iter()
|
|
||||||
.filter(|f| &f.follower_id == user_id && f.state == FollowState::Accepted)
|
|
||||||
.map(|f| f.following_id.clone())
|
|
||||||
.collect();
|
|
||||||
let follower_ids: HashSet<UserId> = follows
|
|
||||||
.iter()
|
|
||||||
.filter(|f| &f.following_id == user_id && f.state == FollowState::Accepted)
|
|
||||||
.map(|f| f.follower_id.clone())
|
|
||||||
.collect();
|
|
||||||
let mutual_ids: HashSet<UserId> =
|
|
||||||
following_ids.intersection(&follower_ids).cloned().collect();
|
|
||||||
drop(follows);
|
|
||||||
let users = self.users.lock().unwrap();
|
|
||||||
let all_items: Vec<User> = users
|
|
||||||
.iter()
|
|
||||||
.filter(|u| mutual_ids.contains(&u.id))
|
|
||||||
.cloned()
|
|
||||||
.collect();
|
|
||||||
let total = all_items.len() as i64;
|
|
||||||
let offset = page.offset() as usize;
|
|
||||||
let items: Vec<User> = all_items
|
|
||||||
.into_iter()
|
|
||||||
.skip(offset)
|
|
||||||
.take(page.limit() as usize)
|
|
||||||
.collect();
|
|
||||||
Ok(Paginated {
|
|
||||||
items,
|
|
||||||
total,
|
|
||||||
page: page.page,
|
|
||||||
per_page: page.per_page,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
@@ -752,15 +694,7 @@ impl FederationFollowPort for TestStore {
|
|||||||
&self,
|
&self,
|
||||||
_user_id: &UserId,
|
_user_id: &UserId,
|
||||||
) -> Result<Vec<RemoteActor>, DomainError> {
|
) -> Result<Vec<RemoteActor>, DomainError> {
|
||||||
Ok(self.remote_following.lock().unwrap().clone())
|
Ok(vec![])
|
||||||
}
|
|
||||||
|
|
||||||
async fn broadcast_move(
|
|
||||||
&self,
|
|
||||||
_user_id: &UserId,
|
|
||||||
_new_actor_url: url::Url,
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -793,7 +727,7 @@ impl FederationFollowRequestPort for TestStore {
|
|||||||
&self,
|
&self,
|
||||||
_user_id: &UserId,
|
_user_id: &UserId,
|
||||||
) -> Result<Vec<RemoteActor>, DomainError> {
|
) -> Result<Vec<RemoteActor>, DomainError> {
|
||||||
Ok(self.remote_followers.lock().unwrap().clone())
|
Ok(vec![])
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn remove_remote_follower(
|
async fn remove_remote_follower(
|
||||||
@@ -803,22 +737,6 @@ impl FederationFollowRequestPort for TestStore {
|
|||||||
) -> Result<(), DomainError> {
|
) -> Result<(), DomainError> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn mark_follower_accepted(
|
|
||||||
&self,
|
|
||||||
_user_id: &UserId,
|
|
||||||
_actor_url: &str,
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn mark_follower_rejected(
|
|
||||||
&self,
|
|
||||||
_user_id: &UserId,
|
|
||||||
_actor_url: &str,
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
@@ -846,24 +764,6 @@ impl FederationFetchPort for TestStore {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl FederationBlockPort for TestStore {
|
|
||||||
async fn block_remote(
|
|
||||||
&self,
|
|
||||||
_local_user_id: &UserId,
|
|
||||||
_handle: &str,
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
async fn unblock_remote(
|
|
||||||
&self,
|
|
||||||
_local_user_id: &UserId,
|
|
||||||
_handle: &str,
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl RemoteActorConnectionRepository for TestStore {
|
impl RemoteActorConnectionRepository for TestStore {
|
||||||
async fn upsert_connections(
|
async fn upsert_connections(
|
||||||
@@ -900,7 +800,7 @@ impl RemoteActorConnectionRepository for TestStore {
|
|||||||
impl FeedRepository for TestStore {
|
impl FeedRepository for TestStore {
|
||||||
async fn query(
|
async fn query(
|
||||||
&self,
|
&self,
|
||||||
_req: &crate::ports::FeedRequest,
|
_q: &crate::ports::FeedQuery,
|
||||||
) -> Result<Paginated<FeedEntry>, DomainError> {
|
) -> Result<Paginated<FeedEntry>, DomainError> {
|
||||||
Ok(Paginated {
|
Ok(Paginated {
|
||||||
items: vec![],
|
items: vec![],
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user