# Notification WebSocket API

> WebSocket API documentation for the Aphrodite Notification Service using
> Socket.io.

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

---

## Table of Contents

1. [Connection](#connection)
2. [Notification Events](#notification-events)
3. [Notification Management](#notification-management)
4. [Preferences](#preferences)
5. [Subscriptions](#subscriptions)

---

## Connection

### Establishing Connection

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

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

### Connection Events

Upon successful connection, the user is automatically subscribed to their
personal notification room: `user:${userId}:notifications`

```typescript
socket.on('connect', () => {
  console.log('Connected to notifications');
});
```

---

## Notification Events

### Receive Notification

**Server Event:** `notification:received`

Real-time notification pushed to connected clients.

```typescript
socket.on('notification:received', (notification) => {
  console.log('New notification:', notification);
});
```

**Notification Payload:**

```json
{
  "id": "notif_abc123",
  "type": "new_follower",
  "title": "New Follower",
  "body": "johndoe started following you",
  "icon": "https://cdn.aphrodite.example.com/avatars/usr_johndoe.jpg",
  "data": {
    "followerId": "usr_johndoe",
    "followerUsername": "johndoe",
    "followerDisplayName": "John Doe"
  },
  "actionUrl": "/profile/johndoe",
  "priority": "normal",
  "read": false,
  "dismissed": false,
  "createdAt": "2026-01-18T12:00:00.000Z"
}
```

### Notification Types

| Type                    | Description                       | Priority |
| ----------------------- | --------------------------------- | -------- |
| `new_follower`          | Someone followed you              | normal   |
| `new_subscriber`        | Someone subscribed to you         | high     |
| `tip_received`          | Received a tip                    | high     |
| `stream_live`           | Followed creator went live        | high     |
| `stream_reminder`       | Scheduled stream starting soon    | high     |
| `stream_ended`          | Stream has ended                  | low      |
| `new_message`           | New direct message                | normal   |
| `mention`               | Mentioned in chat                 | normal   |
| `content_published`     | Creator published new content     | normal   |
| `subscription_expiring` | Subscription expiring soon        | high     |
| `subscription_renewed`  | Subscription was renewed          | normal   |
| `payment_received`      | Payment processed (creator)       | high     |
| `payout_completed`      | Payout sent (creator)             | high     |
| `goal_completed`        | Tip goal completed                | high     |
| `achievement_unlocked`  | New achievement earned            | normal   |
| `moderation_action`     | Moderation action on your account | urgent   |
| `system`                | System announcement               | varies   |

### Notification Payload by Type

#### `new_follower`

```json
{
  "type": "new_follower",
  "data": {
    "followerId": "usr_johndoe",
    "followerUsername": "johndoe",
    "followerDisplayName": "John Doe",
    "followerAvatarUrl": "..."
  }
}
```

#### `tip_received`

```json
{
  "type": "tip_received",
  "data": {
    "tipId": "tip_abc123",
    "amount": 100,
    "currency": "tokens",
    "message": "Great stream!",
    "senderId": "usr_tipper",
    "senderUsername": "generoustipper",
    "streamId": "str_xyz789",
    "isAnonymous": false
  }
}
```

#### `stream_live`

```json
{
  "type": "stream_live",
  "data": {
    "streamId": "str_xyz789",
    "creatorId": "usr_creator",
    "creatorUsername": "favoritestreamer",
    "title": "Saturday Night Stream",
    "thumbnailUrl": "...",
    "category": "Just Chatting"
  }
}
```

#### `new_message`

```json
{
  "type": "new_message",
  "data": {
    "conversationId": "conv_abc123",
    "senderId": "usr_sender",
    "senderUsername": "sender",
    "preview": "Hey! Just wanted to say..."
  }
}
```

---

## Notification Management

### Get Notifications

**Client Emit:** `notification:get`

```typescript
socket.emit(
  'notification:get',
  {
    filter: 'all', // 'all' | 'unread' | 'read'
    cursor: null,
    limit: 20,
  },
  (response) => {
    console.log('Notifications:', response.notifications);
  }
);
```

**Server Response:** `notification:list`

```typescript
socket.on('notification:list', (data) => {
  // {
  //   notifications: [...],
  //   pagination: { cursor: '...', hasMore: true },
  //   unreadCount: 5
  // }
});
```

---

### Get Unread Notifications

**Client Emit:** `notification:get-unread`

```typescript
socket.emit(
  'notification:get-unread',
  {
    limit: 10,
  },
  (response) => {
    console.log('Unread notifications:', response.notifications);
  }
);
```

**Server Response:** `notification:unread-list`

```typescript
socket.on('notification:unread-list', (data) => {
  // {
  //   notifications: [...],
  //   unreadCount: 5
  // }
});
```

---

### Get Notification Stats

**Client Emit:** `notification:get-stats`

```typescript
socket.emit('notification:get-stats', {}, (response) => {
  console.log('Stats:', response);
});
```

**Server Response:** `notification:stats`

```typescript
socket.on('notification:stats', (data) => {
  // {
  //   unreadCount: 5,
  //   byType: {
  //     new_follower: 2,
  //     tip_received: 1,
  //     stream_live: 2
  //   }
  // }
});
```

---

### Mark as Read

**Client Emit:** `notification:mark-read`

```typescript
socket.emit(
  'notification:mark-read',
  {
    notificationId: 'notif_abc123',
  },
  (response) => {
    console.log('Marked as read:', response.success);
  }
);
```

**Server Response:** `notification:marked-read`

```typescript
socket.on('notification:marked-read', (data) => {
  // {
  //   notificationId: 'notif_abc123',
  //   readAt: '2026-01-18T12:05:00.000Z',
  //   unreadCount: 4
  // }
});
```

---

### Mark All as Read

**Client Emit:** `notification:mark-all-read`

```typescript
socket.emit('notification:mark-all-read', {}, (response) => {
  console.log('All marked as read:', response.success);
});
```

**Server Response:** `notification:all-marked-read`

```typescript
socket.on('notification:all-marked-read', (data) => {
  // {
  //   count: 5,
  //   readAt: '2026-01-18T12:05:00.000Z'
  // }
});
```

---

### Dismiss Notification

**Client Emit:** `notification:dismiss`

```typescript
socket.emit(
  'notification:dismiss',
  {
    notificationId: 'notif_abc123',
  },
  (response) => {
    console.log('Dismissed:', response.success);
  }
);
```

**Server Response:** `notification:dismissed`

```typescript
socket.on('notification:dismissed', (data) => {
  // { notificationId: 'notif_abc123' }
});
```

---

### Delete Notification

**Client Emit:** `notification:delete`

```typescript
socket.emit(
  'notification:delete',
  {
    notificationId: 'notif_abc123',
  },
  (response) => {
    console.log('Deleted:', response.success);
  }
);
```

**Server Response:** `notification:deleted`

```typescript
socket.on('notification:deleted', (data) => {
  // { notificationId: 'notif_abc123' }
});
```

---

## Preferences

### Get Preferences

**Client Emit:** `notification:get-preferences`

```typescript
socket.emit('notification:get-preferences', {}, (response) => {
  console.log('Preferences:', response.preferences);
});
```

**Server Response:** `notification:preferences`

```typescript
socket.on('notification:preferences', (data) => {
  console.log('Notification preferences:', data);
});
```

**Preferences Payload:**

```json
{
  "preferences": {
    "channels": {
      "inApp": { "enabled": true },
      "push": { "enabled": true },
      "email": { "enabled": true, "frequency": "instant" }
    },
    "types": {
      "new_follower": { "inApp": true, "push": true, "email": false },
      "tip_received": { "inApp": true, "push": true, "email": true },
      "stream_live": { "inApp": true, "push": true, "email": false },
      "new_message": { "inApp": true, "push": true, "email": false },
      "subscription_expiring": { "inApp": true, "push": true, "email": true }
    },
    "quiet_hours": {
      "enabled": true,
      "start": "23:00",
      "end": "08:00",
      "timezone": "America/New_York"
    },
    "bundling": {
      "enabled": true,
      "interval": 300
    }
  }
}
```

---

### Update Preferences

**Client Emit:** `notification:update-preferences`

```typescript
socket.emit(
  'notification:update-preferences',
  {
    types: {
      new_follower: { push: false },
    },
    quiet_hours: {
      enabled: true,
      start: '22:00',
      end: '09:00',
    },
  },
  (response) => {
    console.log('Updated:', response.success);
  }
);
```

**Server Response:** `notification:preferences-updated`

```typescript
socket.on('notification:preferences-updated', (data) => {
  // { preferences: {...}, updatedAt: '...' }
});
```

---

## Subscriptions

### Subscribe to Channel

Subscribe to additional notification channels (beyond personal notifications).

**Client Emit:** `notification:subscribe`

```typescript
socket.emit(
  'notification:subscribe',
  {
    channel: 'creator:usr_xyz789', // Subscribe to creator's announcements
  },
  (response) => {
    console.log('Subscribed:', response.success);
  }
);
```

**Channel Types:**

| Channel Pattern       | Description                          |
| --------------------- | ------------------------------------ |
| `creator:{creatorId}` | Creator announcements                |
| `stream:{streamId}`   | Stream notifications (goals, events) |
| `system`              | Platform-wide announcements          |

---

### Unsubscribe from Channel

**Client Emit:** `notification:unsubscribe`

```typescript
socket.emit(
  'notification:unsubscribe',
  {
    channel: 'creator:usr_xyz789',
  },
  (response) => {
    console.log('Unsubscribed:', response.success);
  }
);
```

---

## Push Notification Registration

### Register Push Token

**Client Emit:** `notification:register-push`

```typescript
socket.emit(
  'notification:register-push',
  {
    token: '<fcm_token>',
    platform: 'web', // 'web' | 'ios' | 'android'
    deviceId: 'device_abc123',
  },
  (response) => {
    console.log('Registered:', response.success);
  }
);
```

---

### Unregister Push Token

**Client Emit:** `notification:unregister-push`

```typescript
socket.emit(
  'notification:unregister-push',
  {
    token: '<fcm_token>',
  },
  (response) => {
    console.log('Unregistered:', response.success);
  }
);
```

---

## Data Types

### Notification Object

```typescript
interface Notification {
  id: string;
  type: NotificationType;
  title: string;
  body: string;
  icon?: string;
  imageUrl?: string;
  data: Record<string, unknown>;
  actionUrl?: string;
  actions?: NotificationAction[];
  priority: 'low' | 'normal' | 'high' | 'urgent';
  read: boolean;
  readAt?: string;
  dismissed: boolean;
  dismissedAt?: string;
  expiresAt?: string;
  createdAt: string;
}
```

### Notification Action

```typescript
interface NotificationAction {
  id: string;
  label: string;
  url?: string;
  action?: string;
}
```

### Notification Preferences

```typescript
interface NotificationPreferences {
  channels: {
    inApp: { enabled: boolean };
    push: { enabled: boolean };
    email: { enabled: boolean; frequency: 'instant' | 'daily' | 'weekly' };
  };
  types: Record<
    NotificationType,
    { inApp: boolean; push: boolean; email: boolean }
  >;
  quiet_hours?: {
    enabled: boolean;
    start: string;
    end: string;
    timezone: string;
  };
  bundling?: {
    enabled: boolean;
    interval: number;
  };
}
```

---

## Document History

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