# Stream WebSocket API

> WebSocket API documentation for the Aphrodite Stream Service real-time events.

**WebSocket URL:** `wss://ws.aphrodite.example.com` **Namespace:** `/stream`
**Port:** 5000 **Protocol:** Socket.io v4

---

## Table of Contents

1. [Connection](#connection)
2. [Stream Events](#stream-events)
3. [Goal Events](#goal-events)
4. [Interactive Features](#interactive-features)
5. [Device Events](#device-events)
6. [Quality Events](#quality-events)

---

## Connection

### Establishing Connection

```typescript
import { io } from 'socket.io-client';

const socket = io('wss://ws.aphrodite.example.com/stream', {
  auth: {
    token: '<access_token>',
  },
  transports: ['websocket'],
});
```

### Join Stream Room

**Client Emit:** `stream:join`

```typescript
socket.emit(
  'stream:join',
  {
    streamId: 'str_abc123',
  },
  (response) => {
    console.log('Joined stream:', response);
  }
);
```

**Response:**

```json
{
  "success": true,
  "streamId": "str_abc123",
  "stream": {
    "title": "Saturday Night Stream",
    "status": "live",
    "startedAt": "2026-01-18T20:00:00.000Z",
    "viewerCount": 1250,
    "creator": {
      "id": "usr_xyz789",
      "username": "janedoe"
    }
  },
  "goals": [...],
  "activeDevices": [...]
}
```

### Leave Stream Room

**Client Emit:** `stream:leave`

```typescript
socket.emit('stream:leave', {
  streamId: 'str_abc123',
});
```

---

## Stream Events

### Stream Started

**Server Event:** `stream:started`

```typescript
socket.on('stream:started', (data) => {
  console.log('Stream started:', data);
});
```

**Payload:**

```json
{
  "streamId": "str_abc123",
  "creator": {
    "id": "usr_xyz789",
    "username": "janedoe",
    "displayName": "Jane Doe"
  },
  "title": "Saturday Night Stream",
  "category": "Just Chatting",
  "thumbnailUrl": "...",
  "startedAt": "2026-01-18T20:00:00.000Z"
}
```

---

### Stream Ended

**Server Event:** `stream:ended`

```typescript
socket.on('stream:ended', (data) => {
  console.log('Stream ended:', data);
});
```

**Payload:**

```json
{
  "streamId": "str_abc123",
  "endedAt": "2026-01-18T23:30:00.000Z",
  "duration": 12600,
  "stats": {
    "peakViewers": 1500,
    "totalViewers": 5200,
    "chatMessages": 8500,
    "tips": 1250.0
  },
  "vodAvailable": true,
  "vodId": "vod_xyz789"
}
```

---

### Stream Updated

**Server Event:** `stream:updated`

Stream metadata changed (title, category, etc.).

```typescript
socket.on('stream:updated', (data) => {
  console.log('Stream updated:', data);
});
```

**Payload:**

```json
{
  "streamId": "str_abc123",
  "changes": {
    "title": "New Stream Title",
    "category": "Gaming"
  },
  "updatedAt": "2026-01-18T21:00:00.000Z"
}
```

---

### Viewer Count Update

**Server Event:** `stream:viewers`

```typescript
socket.on('stream:viewers', (data) => {
  // { streamId: 'str_abc123', count: 1275 }
});
```

---

### Stream Stats Update

**Server Event:** `stream:stats`

Periodic stats update (every 30 seconds).

```typescript
socket.on('stream:stats', (data) => {
  console.log('Stream stats:', data);
});
```

**Payload:**

```json
{
  "streamId": "str_abc123",
  "viewers": {
    "current": 1275,
    "peak": 1500,
    "total": 4200
  },
  "engagement": {
    "chatMessages": 5200,
    "reactions": 850,
    "tips": 85
  },
  "duration": 7200,
  "timestamp": "2026-01-18T22:00:00.000Z"
}
```

---

## Goal Events

### Goal Created

**Server Event:** `goal:created`

```typescript
socket.on('goal:created', (data) => {
  console.log('New goal:', data);
});
```

**Payload:**

```json
{
  "streamId": "str_abc123",
  "goal": {
    "id": "goal_abc123",
    "name": "New Outfit",
    "description": "Help me reach the goal for a new outfit reveal!",
    "target": 500,
    "current": 0,
    "type": "tips",
    "reward": "Outfit reveal",
    "createdAt": "2026-01-18T20:30:00.000Z",
    "expiresAt": null
  }
}
```

---

### Goal Progress

**Server Event:** `goal:progress`

```typescript
socket.on('goal:progress', (data) => {
  console.log('Goal progress:', data);
});
```

**Payload:**

```json
{
  "streamId": "str_abc123",
  "goalId": "goal_abc123",
  "current": 350,
  "target": 500,
  "percentage": 70,
  "contributor": {
    "userId": "usr_tipper",
    "username": "generoustipper",
    "amount": 50
  },
  "timestamp": "2026-01-18T21:15:00.000Z"
}
```

---

### Goal Completed

**Server Event:** `goal:completed`

```typescript
socket.on('goal:completed', (data) => {
  console.log('Goal completed!', data);
});
```

**Payload:**

```json
{
  "streamId": "str_abc123",
  "goal": {
    "id": "goal_abc123",
    "name": "New Outfit",
    "target": 500,
    "final": 525,
    "reward": "Outfit reveal"
  },
  "topContributors": [
    { "userId": "usr_top1", "username": "toptipper", "amount": 150 },
    { "userId": "usr_top2", "username": "generous", "amount": 100 }
  ],
  "completedAt": "2026-01-18T21:45:00.000Z"
}
```

---

### Goal Expired

**Server Event:** `goal:expired`

```typescript
socket.on('goal:expired', (data) => {
  // {
  //   streamId: 'str_abc123',
  //   goalId: 'goal_abc123',
  //   final: 350,
  //   target: 500,
  //   expiredAt: '2026-01-18T22:00:00.000Z'
  // }
});
```

---

## Interactive Features

### Tip Received

**Server Event:** `tip:received`

Real-time tip notification for stream overlay.

```typescript
socket.on('tip:received', (data) => {
  console.log('Tip received:', data);
});
```

**Payload:**

```json
{
  "streamId": "str_abc123",
  "tipId": "tip_xyz789",
  "sender": {
    "id": "usr_tipper",
    "username": "generoustipper",
    "displayName": "Generous Tipper",
    "avatarUrl": "...",
    "isAnonymous": false
  },
  "amount": 100,
  "currency": "tokens",
  "message": "Great stream! Love the content!",
  "timestamp": "2026-01-18T21:30:00.000Z",
  "triggeredDevice": true,
  "devicePattern": {
    "name": "High Vibration",
    "intensity": 100,
    "duration": 30
  }
}
```

---

### Raid Incoming

**Server Event:** `raid:incoming`

```typescript
socket.on('raid:incoming', (data) => {
  console.log('Raid incoming:', data);
});
```

**Payload:**

```json
{
  "streamId": "str_abc123",
  "raider": {
    "id": "usr_raider",
    "username": "raidingcreator",
    "displayName": "Raiding Creator",
    "avatarUrl": "..."
  },
  "viewerCount": 250,
  "timestamp": "2026-01-18T22:30:00.000Z"
}
```

---

### Poll Events

#### Poll Created

**Server Event:** `poll:created`

```typescript
socket.on('poll:created', (data) => {
  console.log('Poll created:', data);
});
```

**Payload:**

```json
{
  "streamId": "str_abc123",
  "poll": {
    "id": "poll_abc123",
    "question": "What game should I play next?",
    "options": [
      { "id": "opt_1", "text": "Game A", "votes": 0 },
      { "id": "opt_2", "text": "Game B", "votes": 0 },
      { "id": "opt_3", "text": "Game C", "votes": 0 }
    ],
    "duration": 120,
    "endsAt": "2026-01-18T22:02:00.000Z",
    "createdAt": "2026-01-18T22:00:00.000Z"
  }
}
```

#### Poll Vote

**Client Emit:** `poll:vote`

```typescript
socket.emit(
  'poll:vote',
  {
    pollId: 'poll_abc123',
    optionId: 'opt_1',
  },
  (response) => {
    console.log('Vote recorded:', response.success);
  }
);
```

#### Poll Updated

**Server Event:** `poll:updated`

```typescript
socket.on('poll:updated', (data) => {
  // {
  //   pollId: 'poll_abc123',
  //   options: [
  //     { id: 'opt_1', text: 'Game A', votes: 45, percentage: 45 },
  //     { id: 'opt_2', text: 'Game B', votes: 35, percentage: 35 },
  //     { id: 'opt_3', text: 'Game C', votes: 20, percentage: 20 }
  //   ],
  //   totalVotes: 100
  // }
});
```

#### Poll Ended

**Server Event:** `poll:ended`

```typescript
socket.on('poll:ended', (data) => {
  // {
  //   pollId: 'poll_abc123',
  //   winner: { id: 'opt_1', text: 'Game A', votes: 45 },
  //   totalVotes: 100,
  //   endedAt: '2026-01-18T22:02:00.000Z'
  // }
});
```

---

## Device Events

### Device Connected

**Server Event:** `device:connected`

Creator connected an interactive device.

```typescript
socket.on('device:connected', (data) => {
  console.log('Device connected:', data);
});
```

**Payload:**

```json
{
  "streamId": "str_abc123",
  "device": {
    "id": "dev_abc123",
    "type": "lovense",
    "name": "Lush 3",
    "capabilities": ["vibrate"],
    "batteryLevel": 85
  },
  "timestamp": "2026-01-18T20:00:00.000Z"
}
```

---

### Device Disconnected

**Server Event:** `device:disconnected`

```typescript
socket.on('device:disconnected', (data) => {
  // { streamId: 'str_abc123', deviceId: 'dev_abc123' }
});
```

---

### Device Activated

**Server Event:** `device:activated`

Device was activated (tip-triggered or manual).

```typescript
socket.on('device:activated', (data) => {
  console.log('Device activated:', data);
});
```

**Payload:**

```json
{
  "streamId": "str_abc123",
  "deviceId": "dev_abc123",
  "activation": {
    "type": "tip",
    "tipId": "tip_xyz789",
    "pattern": "High Vibration",
    "intensity": 100,
    "duration": 30
  },
  "triggeredBy": {
    "userId": "usr_tipper",
    "username": "generoustipper",
    "amount": 100
  },
  "timestamp": "2026-01-18T21:30:00.000Z"
}
```

---

### Device Battery Update

**Server Event:** `device:battery`

```typescript
socket.on('device:battery', (data) => {
  // { streamId: 'str_abc123', deviceId: 'dev_abc123', batteryLevel: 75 }
});
```

---

## Quality Events

### Quality Changed

**Server Event:** `quality:changed`

Stream quality changed (adaptive bitrate).

```typescript
socket.on('quality:changed', (data) => {
  console.log('Quality changed:', data);
});
```

**Payload:**

```json
{
  "streamId": "str_abc123",
  "available": ["1080p", "720p", "480p", "360p"],
  "recommended": "720p",
  "reason": "bandwidth_limited"
}
```

---

### Buffering Event

**Server Event:** `quality:buffering`

```typescript
socket.on('quality:buffering', (data) => {
  // { streamId: 'str_abc123', buffering: true }
});
```

---

### Latency Update

**Server Event:** `quality:latency`

```typescript
socket.on('quality:latency', (data) => {
  // { streamId: 'str_abc123', latency: 2.5, unit: 'seconds' }
});
```

---

## Show Type Events

### Private Show Request

**Server Event:** `show:private:request`

Creator received a private show request.

```typescript
socket.on('show:private:request', (data) => {
  console.log('Private show request:', data);
});
```

**Payload:**

```json
{
  "streamId": "str_abc123",
  "request": {
    "id": "req_abc123",
    "requester": {
      "id": "usr_requester",
      "username": "viewer1",
      "displayName": "Viewer One"
    },
    "duration": 15,
    "pricePerMinute": 50,
    "message": "Would love a private show!"
  }
}
```

---

### Private Show Started

**Server Event:** `show:private:started`

```typescript
socket.on('show:private:started', (data) => {
  // {
  //   streamId: 'str_abc123',
  //   showId: 'pshow_abc123',
  //   participant: { id: 'usr_viewer', username: 'viewer1' },
  //   duration: 15,
  //   endsAt: '2026-01-18T22:15:00.000Z'
  // }
});
```

---

### Ticket Show Announcement

**Server Event:** `show:ticket:announced`

```typescript
socket.on('show:ticket:announced', (data) => {
  console.log('Ticket show announced:', data);
});
```

**Payload:**

```json
{
  "streamId": "str_abc123",
  "show": {
    "id": "tshow_abc123",
    "title": "Exclusive Performance",
    "description": "Special ticket-only show",
    "ticketPrice": 200,
    "currency": "tokens",
    "startsAt": "2026-01-18T23:00:00.000Z",
    "maxAttendees": 50,
    "currentAttendees": 0
  }
}
```

---

## Data Types

### Stream Object

```typescript
interface Stream {
  id: string;
  title: string;
  status: 'scheduled' | 'live' | 'ended';
  creator: Creator;
  category: string;
  tags: string[];
  thumbnailUrl?: string;
  viewerCount: number;
  startedAt?: string;
  endedAt?: string;
}
```

### Goal Object

```typescript
interface Goal {
  id: string;
  name: string;
  description?: string;
  target: number;
  current: number;
  type: 'tips' | 'viewers' | 'custom';
  reward?: string;
  createdAt: string;
  expiresAt?: string;
  completedAt?: string;
}
```

### Device Object

```typescript
interface Device {
  id: string;
  type: 'lovense' | 'buttplug' | 'handy' | 'kiiroo' | 'ohmibod';
  name: string;
  capabilities: string[];
  batteryLevel?: number;
  connected: boolean;
}
```

---

## Document History

| Date       | Version | Changes                           |
| ---------- | ------- | --------------------------------- |
| 2026-01-18 | 1.0.0   | Initial Stream WebSocket API docs |
