# Aphrodite Domain - Developer Guide

Aphrodite is the Adult Entertainment Streaming Platform domain. It provides a
large-scale, real-time streaming platform with 22 backend services and 74
libraries covering media delivery, interactive device control, payment
processing, chat, VR/AR experiences, and compliance infrastructure. Services
communicate via REST, WebSocket, gRPC, and Kafka.

---

## Prerequisites

### Required Software

| Software       | Minimum Version | Purpose                                         |
| -------------- | --------------- | ----------------------------------------------- |
| Node.js        | >= 20.0.0       | Runtime for all backend services                |
| pnpm           | >= 10.0         | Package manager (monorepo workspace)            |
| Docker         | >= 24.0         | Infrastructure (PostgreSQL, Redis, Kafka, etc.) |
| Docker Compose | >= 2.20         | Multi-container orchestration                   |
| TypeScript     | ~5.6.x          | Type checking and compilation                   |
| Git            | >= 2.40         | Version control                                 |

### For Mobile Development

| Software     | Purpose                              |
| ------------ | ------------------------------------ |
| React Native | Mobile apps (viewer and broadcaster) |
| Xcode        | iOS builds                           |
| Android SDK  | Android builds                       |

---

## Project Structure

```
apps/aphrodite/
  auth/                  # Authentication service (JWT, OAuth, 2FA) - Port 3003
  streaming/             # Stream ingestion, transcoding, distribution - Port 3003/50051/1935
  chat/                  # Real-time chat (Hono + Socket.io) - Port 5000
  payment/               # Token purchases, tips, subscriptions, payouts - Port 4000
  viewer/                # Stream viewing and interactions - Port 3002
  broadcaster/           # Stream creation and management - Port 3100
  cdn/                   # CDN management, signed URLs - Port 3005
  admin/                 # Platform administration - Port 3004
  admin-bi-dashboard/    # Business intelligence dashboard - Port 3000
  analytics/             # Event ingestion and dashboards
  analytics-dashboard/   # Creator analytics dashboard
  realtime-analytics/    # Live viewer counts, trending - Port 3450
  notifications/         # Multi-channel delivery (push, email, SMS)
  devices/               # Device control, haptic patterns (WebSocket) - Port 4003
  vr/                    # VR capture, playback, spatial audio (WebSocket) - Port 3008
  mobile/                # Mobile viewer application (React Native)
  mobile-broadcaster/    # Mobile broadcasting application (React Native)
  mobile-viewer/         # Mobile viewer-focused application (React Native)

libs/aphrodite/
  core/                  # Types, validation, utilities, constants
  database/              # Prisma schema, repositories, migrations
  cache/                 # Redis-based caching layer
  storage/               # S3-compatible file/media storage
  event-publisher/       # Event publishing and subscription
  oauth-providers/       # OAuth integration (Google, Twitter, Discord)
  safety/                # Emergency controls and safety features
  sdk/                   # Unified SDK for platform integration
  payment/               # Payment processing utilities
  testing/               # Mock factories and test utilities
  streaming-core/        # Stream session management, ingest, playback
  cloud-recording/       # Cloud-based stream recording
  multi-source/          # Multi-camera/source composition
  video-effects/         # Real-time video filters and effects
  device-protocols/      # Unified device protocol layer (Lovense, Kiiroo, Handy)
  buttplug/              # Buttplug.io universal device protocol
  haptics/               # Haptic feedback engine
  bidirectional-haptics/ # Two-way haptic communication
  motion-haptics/        # Motion-based haptic patterns
  audio-haptics/         # Audio-reactive haptic responses
  wearables/             # Wearable device integration
  smart-home/            # Smart home device control
  vr-core/               # Core VR streaming (quality presets, stereo)
  vr-quest/              # Meta Quest platform integration
  vr-haptics/            # VR-specific haptic feedback
  spatial-audio/         # 3D spatial audio processing
  virtual-rooms/         # Virtual room creation and management
  ar-overlays/           # AR overlay rendering
  viewer-avatars/        # Viewer avatar representation
  avatar-motion/         # Motion capture for avatars
  avatar-renderer/       # Avatar rendering pipeline
  avatar-physics/        # Avatar physics simulation
  avatar-customization-ui/ # Avatar customization interface
  animations/            # Animation system
  animation-blending/    # Animation blend trees
  animation-triggers/    # Event-triggered animations
  chat-core/             # Core chat protocol and message handling
  chat-moderation/       # Automated chat moderation
  chat-entertainment/    # Chat games, polls, quizzes
  chat/                  # High-level chat integration layer
  viewer-interactions/   # Viewer reactions and emotes
  tip-acknowledgment/    # Tip notification and acknowledgment
  tip-effects/           # Visual effects triggered by tips
  tip-goals/             # Tip goal tracking and milestones
  vip-areas/             # VIP-only rooms and features
  payments/              # Core payment processing (CCBill, Epoch, Segpay)
  crypto-payments/       # Cryptocurrency payment (BTC, ETH)
  privacy-coins/         # Privacy-focused crypto (Monero, Zcash)
  ppv/                   # Pay-per-view access control
  revenue-sharing/       # Creator/platform revenue splits
  virtual-gifts/         # Virtual gift marketplace
  gamification/          # Achievements, leaderboards, loyalty
  nft-integration/       # NFT minting and marketplace
  remote-guest/          # Remote guest appearance management
  analytics/             # Event pipeline, aggregation, dashboards
  recommendations/       # Content recommendation engine
  ai-assistant/          # AI assistant for creators
  notification-intelligence/ # Smart notification timing
  stream-content-analysis/  # AI-based stream content moderation
  content-tagging/       # Automatic content classification
  stream-upscaling/      # AI-powered resolution upscaling
  highlight-clipping/    # Automated highlight creation
  vod-chaptering/        # VOD chapter markers and navigation
  thumbnail-generation/  # Automatic thumbnail creation
  stream-watermarking/   # Invisible forensic watermarks
  age-verification/      # Multi-provider age verification
  compliance-2257/       # 18 U.S.C. 2257 record-keeping
  gdpr-compliance/       # GDPR data export, deletion, consent
  drm/                   # Digital rights management for VOD
  e2e-encryption/        # End-to-end encrypted messaging
  recording-prevention/  # Screen recording deterrence
  content-takedown/      # DMCA takedown request handling
  eye-tracking/          # VR eye-tracking integration
  interactables/         # Interactive stream elements
```

---

## Local Development Setup

### 1. Start Infrastructure

Aphrodite requires PostgreSQL, Redis, Kafka, and optionally MongoDB and
ClickHouse for analytics.

```bash
# Start core infrastructure (PostgreSQL, Redis, MinIO)
docker compose -f docker/docker-compose.dev.yml up -d

# Start Kafka for event streaming (optional but recommended)
docker compose -f docker/docker-compose.dev.yml --profile streaming up -d
```

This starts:

- **PostgreSQL** (port 5432) -- users, payments, subscriptions, content
- **Redis** (port 6379) -- caching, sessions, pub/sub, leaderboards
- **MinIO** (ports 9000/9001) -- S3-compatible media storage
- **Kafka** (port 9092) -- event streaming and fan-out (with `streaming`
  profile)

### 2. Install Dependencies

```bash
pnpm install
```

### 3. Set Environment Variables

| Variable                    | Default                                                 | Used By                |
| --------------------------- | ------------------------------------------------------- | ---------------------- |
| `APHRODITE_DATABASE_URL`    | `postgresql://oshun:oshun_dev@localhost:5432/aphrodite` | database, all services |
| `APHRODITE_REDIS_URL`       | `redis://localhost:6379`                                | cache, sessions, chat  |
| `APHRODITE_MONGO_URL`       | `mongodb://localhost:27017/aphrodite`                   | chat, notifications    |
| `APHRODITE_KAFKA_BROKERS`   | `localhost:9092`                                        | event streaming        |
| `APHRODITE_S3_BUCKET`       | `aphrodite-media`                                       | storage                |
| `APHRODITE_CDN_URL`         | `http://localhost:9000/aphrodite-media`                 | CDN                    |
| `APHRODITE_STRIPE_KEY`      | --                                                      | payment                |
| `APHRODITE_CCBILL_ACCOUNT`  | --                                                      | payment                |
| `APHRODITE_JWT_SECRET`      | --                                                      | auth                   |
| `APHRODITE_ENCRYPTION_KEY`  | --                                                      | e2e-encryption         |
| `APHRODITE_LOVENSE_TOKEN`   | --                                                      | devices                |
| `APHRODITE_BUTTPLUG_SERVER` | `ws://localhost:12345`                                  | devices                |

### 4. Database Setup (Prisma)

The Aphrodite database schema is defined in
`libs/aphrodite/database/prisma/schema.prisma`.

```bash
cd libs/aphrodite/database

# Generate the Prisma client
npx prisma generate

# Apply schema to local database
npx prisma db push

# Or create and run migrations
npx prisma migrate dev --name initial_schema
```

---

## Running Services

### Auth Service (Port 3003)

Authentication, JWT tokens, OAuth, two-factor authentication, and age
verification.

```bash
# Development
pnpm nx dev @aphrodite/auth

# Build
pnpm nx build @aphrodite/auth
```

### Streaming Service (Port 3003 HTTP / 50051 gRPC / 1935 RTMP)

Central media infrastructure handling the full stream lifecycle: RTMP ingest,
WebRTC signaling, transcoding, HLS/DASH distribution, and recording.

```bash
# Development with hot reload
pnpm nx serve aphrodite-streaming

# Build
pnpm nx build aphrodite-streaming
```

### Chat Service (Port 5000)

Dual-protocol service combining Hono HTTP and Socket.io WebSocket for real-time
chat, DMs, and moderation.

```bash
# Development
pnpm nx dev aphrodite-chat

# Build
pnpm nx build aphrodite-chat
```

### Payment Service (Port 4000)

Handles token purchases, tips, subscriptions, PPV, payouts, and revenue sharing.
Processes webhooks from CCBill, Epoch, and Segpay.

```bash
# Development
pnpm nx dev aphrodite-payment

# Build
pnpm nx build aphrodite-payment
```

### Viewer Service (Port 3002)

Stream viewing, tipping, and viewer interactions.

```bash
# Development
pnpm nx serve aphrodite-viewer

# Build
pnpm nx build aphrodite-viewer
```

### Broadcaster Service (Port 3100)

Stream creation, management, and earnings dashboard.

```bash
# Development
pnpm nx serve aphrodite-broadcaster

# Build
pnpm nx build aphrodite-broadcaster
```

### Devices Service (Port 4003)

Device control with WebSocket for real-time haptic commands. Supports Lovense,
Kiiroo, Handy, OhMiBod, and Buttplug.io protocols.

```bash
# Development
pnpm nx dev @aphrodite/devices

# Build
pnpm nx build @aphrodite/devices
```

### VR Service (Port 3008)

VR capture, playback, spatial audio processing, and quality preset management.

```bash
# Development
pnpm nx dev @aphrodite/vr

# Build
pnpm nx build @aphrodite/vr
```

### CDN Service (Port 3005)

CDN management, signed URL generation, and cache purging.

```bash
# Development
pnpm nx dev @aphrodite/cdn

# Build
pnpm nx build @aphrodite/cdn
```

### Admin Service (Port 3004)

Platform administration and moderation.

```bash
# Development
pnpm nx dev @aphrodite/admin

# Build
pnpm nx build @aphrodite/admin
```

### Realtime Analytics (Port 3450)

Live viewer counts, trending streams, and real-time dashboards via WebSocket.

```bash
# Development
pnpm nx serve aphrodite-realtime-analytics
```

### Running Multiple Services

```bash
# Start multiple services in parallel
pnpm nx run-many -t serve --projects=aphrodite-streaming,aphrodite-chat,aphrodite-payment

# Or start all Aphrodite services
pnpm nx run-many -t dev --projects=tag:domain:aphrodite
```

---

## Building

### Build All Aphrodite Projects

```bash
pnpm nx run-many -t build --projects=tag:scope:aphrodite
```

### Build Individual Services

All backend services use tsup for bundling:

```bash
pnpm nx build aphrodite-streaming
pnpm nx build aphrodite-chat
pnpm nx build aphrodite-payment
pnpm nx build aphrodite-viewer
pnpm nx build aphrodite-broadcaster
pnpm nx build @aphrodite/auth
pnpm nx build @aphrodite/cdn
pnpm nx build @aphrodite/admin
pnpm nx build @aphrodite/devices
pnpm nx build @aphrodite/vr
```

### Build Libraries

```bash
pnpm nx build @aphrodite/database
pnpm nx build @aphrodite/core
pnpm nx build @aphrodite/streaming-core
pnpm nx build @aphrodite/payments
```

---

## Testing

### Test Runner

All Aphrodite projects use Vitest via the `@nx/vite:test` executor.

### Running Tests

```bash
# All Aphrodite projects
pnpm nx run-many -t test --projects=tag:scope:aphrodite

# Individual service
pnpm nx test aphrodite-streaming
pnpm nx test aphrodite-chat

# Individual library
pnpm nx test @aphrodite/core
pnpm nx test @aphrodite/database

# With coverage
pnpm nx test @aphrodite/core --coverage

# Watch mode
pnpm nx test @aphrodite/payments --watch
```

### Linting and Formatting

```bash
# Lint all Aphrodite projects
pnpm nx run-many -t lint --projects=tag:scope:aphrodite

# Lint individual project
pnpm nx lint @aphrodite/core

# Fix lint issues
pnpm nx lint @aphrodite/core --fix

# Format
pnpm prettier --write "libs/aphrodite/**/*.ts"
pnpm prettier --write "apps/aphrodite/**/*.ts"
```

---

## Common Development Tasks

### Adding a New Service

1. Create the directory structure:

   ```bash
   mkdir -p apps/aphrodite/my-service/src
   ```

2. Create `project.json` with build (tsup), serve (tsx watch), lint, and test
   targets. Use `tags: ["scope:aphrodite", "type:app"]`.

3. Create `package.json` with `tsup` and `tsx` as dev dependencies.

4. Implement the Hono application in `src/index.ts`:

   ```typescript
   import { Hono } from 'hono';
   import { serve } from '@hono/node-server';

   const app = new Hono();

   app.get('/health', (c) => c.json({ status: 'ok' }));

   serve({ fetch: app.fetch, port: YOUR_PORT });
   ```

### Adding a New Library

1. Create `libs/aphrodite/my-lib/` with `project.json`, `package.json`,
   `tsconfig.json`, and `src/index.ts`.

2. Use tags: `["scope:aphrodite", "layer:domain", "type:lib"]`.

3. Add path mapping to `tsconfig.base.json`:

   ```json
   "@aphrodite/my-lib": ["libs/aphrodite/my-lib/src/index.ts"]
   ```

### Working with the Prisma Schema

```bash
cd libs/aphrodite/database

# Generate client after schema changes
npx prisma generate

# Create a new migration
npx prisma migrate dev --name describe_your_change

# Apply migrations in production
npx prisma migrate deploy

# Browse database
npx prisma studio

# Reset database (destructive)
npx prisma migrate reset
```

### Working with Kafka Events

Aphrodite uses Kafka for event streaming between services:

| Topic                  | Producer(s) | Consumer(s)                   |
| ---------------------- | ----------- | ----------------------------- |
| `stream.events`        | Streaming   | Analytics, Chat, Notification |
| `chat.messages`        | Chat        | Analytics, Moderation         |
| `payment.transactions` | Payment     | Analytics, Notification       |
| `user.events`          | Auth        | Analytics, Recommendation     |
| `moderation.actions`   | Moderation  | Chat, Streaming, Notification |
| `device.commands`      | Devices     | Analytics                     |

### Working with WebSocket Services

The Chat (Socket.io), Devices (ws), VR (ws), and Realtime Analytics (ws)
services use WebSocket. Redis pub/sub is used for horizontal scaling of
Socket.io across multiple chat service instances.

---

## Debugging

### Service Not Starting

- Verify PostgreSQL is running:
  `docker compose -f docker/docker-compose.dev.yml ps`
- Check `APHRODITE_DATABASE_URL` is set correctly
- Ensure Redis is reachable at `APHRODITE_REDIS_URL`
- Verify Prisma client is generated:
  `cd libs/aphrodite/database && npx prisma generate`
- Check port conflicts: `lsof -i :3003` (auth/streaming share port 3003)

### Payment Processing Issues

- Payment services require valid API credentials for CCBill, Epoch, or Segpay
- For local development, use test/sandbox credentials from each provider
- Webhook endpoints must be accessible from payment provider servers
- Check transaction status in the `token_purchases` and `payouts` tables

### Chat Not Working

- Chat uses Socket.io on port 5000 -- verify it is not blocked
- Redis pub/sub is required for horizontal scaling of chat
- Kafka must be running for chat message event streaming
- Check moderation filters if messages are being silently dropped

### Device Connection Issues

- Devices service uses WebSocket on port 4003
- Buttplug.io server must be running at `APHRODITE_BUTTPLUG_SERVER`
- Lovense devices require the Lovense Connect app running on the device
- Check `device_controls` table for command execution status

### VR Streaming Issues

- VR service runs on port 3008 with WebSocket
- Check VR quality preset configuration -- bandwidth requirements range from 5
  Mbps (low) to 50 Mbps (ultra)
- Meta Quest integration requires the Quest SDK

### Database Issues

- Use `npx prisma studio` to browse data visually in the browser
- For migration conflicts: `npx prisma migrate reset` (destructive)
- The schema uses extensive indexing on foreign keys and status fields
- Token balances use integer arithmetic (no floating point) to prevent rounding

---

## Quick Reference

| Task                    | Command                                                                     |
| ----------------------- | --------------------------------------------------------------------------- |
| Start infrastructure    | `docker compose -f docker/docker-compose.dev.yml up -d`                     |
| Start with Kafka        | `docker compose -f docker/docker-compose.dev.yml --profile streaming up -d` |
| Install dependencies    | `pnpm install`                                                              |
| Generate Prisma client  | `cd libs/aphrodite/database && npx prisma generate`                         |
| Apply database schema   | `cd libs/aphrodite/database && npx prisma db push`                          |
| Browse database         | `cd libs/aphrodite/database && npx prisma studio`                           |
| Build all Aphrodite     | `pnpm nx run-many -t build --projects=tag:scope:aphrodite`                  |
| Test all Aphrodite      | `pnpm nx run-many -t test --projects=tag:scope:aphrodite`                   |
| Lint all Aphrodite      | `pnpm nx run-many -t lint --projects=tag:scope:aphrodite`                   |
| Start streaming service | `pnpm nx serve aphrodite-streaming`                                         |
| Start chat service      | `pnpm nx dev aphrodite-chat`                                                |
| Start payment service   | `pnpm nx dev aphrodite-payment`                                             |
| View dependency graph   | `pnpm nx graph --focus=aphrodite-streaming`                                 |
