# Analytics Service API

> REST API documentation for the Aphrodite Analytics Service.

**Base URL:** `https://api.aphrodite.example.com/api/v1/analytics` **Port:**
7000 **Authentication:** JWT Bearer Token

---

## Table of Contents

1. [Event Ingestion](#event-ingestion)
2. [Creator Dashboard](#creator-dashboard)
3. [Viewer Analytics](#viewer-analytics)
4. [Stream Analytics](#stream-analytics)
5. [Earnings Analytics](#earnings-analytics)

---

## Event Ingestion

### Track Event

Track analytics events from client applications.

```http
POST /ingestion/events
Authorization: Bearer <access_token>
Content-Type: application/json

{
  "events": [
    {
      "type": "page_view",
      "timestamp": "2026-01-18T12:00:00.000Z",
      "properties": {
        "page": "/creator/janedoe",
        "referrer": "https://google.com"
      },
      "context": {
        "sessionId": "sess_abc123",
        "userAgent": "Mozilla/5.0...",
        "ip": "masked"
      }
    },
    {
      "type": "stream_view",
      "timestamp": "2026-01-18T12:01:00.000Z",
      "properties": {
        "streamId": "str_xyz789",
        "creatorId": "usr_xyz789",
        "quality": "1080p",
        "viewDuration": 300
      }
    }
  ]
}
```

**Response (202 Accepted):**

```json
{
  "success": true,
  "data": {
    "accepted": 2,
    "rejected": 0,
    "batchId": "batch_abc123"
  }
}
```

**Event Types:**

| Event Type         | Description                  | Required Properties        |
| ------------------ | ---------------------------- | -------------------------- |
| `page_view`        | Page/screen view             | `page`                     |
| `stream_view`      | Watching a stream            | `streamId`, `creatorId`    |
| `stream_join`      | Joined a stream              | `streamId`                 |
| `stream_leave`     | Left a stream                | `streamId`, `viewDuration` |
| `tip_sent`         | Sent a tip                   | `amount`, `recipientId`    |
| `content_view`     | Viewed content               | `contentId`, `contentType` |
| `content_purchase` | Purchased content            | `contentId`, `price`       |
| `follow`           | Followed a creator           | `creatorId`                |
| `subscribe`        | Subscribed to creator        | `creatorId`, `tierId`      |
| `chat_message`     | Sent chat message            | `roomId`                   |
| `device_connect`   | Connected interactive device | `deviceType`               |

---

### Track Stream Event

Specialized endpoint for stream-related events.

```http
POST /ingestion/stream
Authorization: Bearer <access_token>
Content-Type: application/json

{
  "streamId": "str_xyz789",
  "eventType": "quality_change",
  "timestamp": "2026-01-18T12:00:00.000Z",
  "data": {
    "previousQuality": "720p",
    "newQuality": "1080p",
    "bufferTime": 2.5
  }
}
```

**Response (202 Accepted):**

```json
{
  "success": true,
  "data": {
    "eventId": "evt_abc123"
  }
}
```

---

## Creator Dashboard

### Get Dashboard Overview

```http
GET /creator-dashboard/overview?period=30d
Authorization: Bearer <access_token>
```

**Query Parameters:**

| Parameter | Type   | Description                       |
| --------- | ------ | --------------------------------- |
| `period`  | string | `24h`, `7d`, `30d`, `90d`, `365d` |

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "period": {
      "start": "2025-12-19T00:00:00.000Z",
      "end": "2026-01-18T23:59:59.000Z"
    },
    "summary": {
      "totalViewers": 45230,
      "uniqueViewers": 12450,
      "totalWatchTime": 892450,
      "avgWatchTime": 1185,
      "peakConcurrentViewers": 1250,
      "totalEarnings": 4520.5,
      "newFollowers": 890,
      "newSubscribers": 45
    },
    "comparison": {
      "totalViewers": { "value": 45230, "change": 12.5, "trend": "up" },
      "totalEarnings": { "value": 4520.5, "change": -3.2, "trend": "down" },
      "newFollowers": { "value": 890, "change": 25.0, "trend": "up" }
    },
    "topContent": [
      {
        "id": "cnt_abc123",
        "title": "Latest Stream",
        "type": "stream",
        "views": 5200,
        "earnings": 450.0
      }
    ]
  }
}
```

---

### Get Viewer Analytics

```http
GET /creator-dashboard/viewers?period=30d&groupBy=day
Authorization: Bearer <access_token>
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "period": {
      "start": "2025-12-19T00:00:00.000Z",
      "end": "2026-01-18T23:59:59.000Z"
    },
    "totals": {
      "totalViewers": 45230,
      "uniqueViewers": 12450,
      "returningViewers": 8500,
      "newViewers": 3950,
      "avgSessionDuration": 1185
    },
    "timeSeries": [
      {
        "date": "2026-01-18",
        "totalViewers": 1520,
        "uniqueViewers": 890,
        "avgSessionDuration": 1250
      }
    ],
    "demographics": {
      "countries": [
        { "country": "US", "viewers": 5200, "percentage": 41.7 },
        { "country": "UK", "viewers": 1850, "percentage": 14.9 },
        { "country": "CA", "viewers": 1200, "percentage": 9.6 }
      ],
      "devices": [
        { "device": "desktop", "viewers": 7500, "percentage": 60.2 },
        { "device": "mobile", "viewers": 4200, "percentage": 33.7 },
        { "device": "tablet", "viewers": 750, "percentage": 6.1 }
      ]
    },
    "peakHours": [
      { "hour": 20, "avgViewers": 850, "dayOfWeek": "friday" },
      { "hour": 21, "avgViewers": 920, "dayOfWeek": "saturday" }
    ]
  }
}
```

---

### Get Earnings Analytics

```http
GET /creator-dashboard/earnings?period=30d&groupBy=day
Authorization: Bearer <access_token>
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "period": {
      "start": "2025-12-19T00:00:00.000Z",
      "end": "2026-01-18T23:59:59.000Z"
    },
    "totals": {
      "gross": 5650.0,
      "platformFee": 1130.0,
      "net": 4520.0,
      "currency": "USD"
    },
    "breakdown": {
      "tips": { "amount": 2850.0, "percentage": 50.4, "count": 1250 },
      "subscriptions": { "amount": 1500.0, "percentage": 26.5, "count": 75 },
      "contentSales": { "amount": 950.0, "percentage": 16.8, "count": 38 },
      "ticketShows": { "amount": 350.0, "percentage": 6.3, "count": 2 }
    },
    "timeSeries": [
      {
        "date": "2026-01-18",
        "gross": 185.5,
        "net": 148.4,
        "tips": 95.0,
        "subscriptions": 50.0,
        "contentSales": 40.5
      }
    ],
    "topTippers": [
      {
        "user": { "id": "usr_top1", "username": "generousfan" },
        "totalAmount": 500.0,
        "tipCount": 25
      }
    ]
  }
}
```

---

### Get Tip Analytics

```http
GET /creator-dashboard/tips?period=30d
Authorization: Bearer <access_token>
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "period": {
      "start": "2025-12-19T00:00:00.000Z",
      "end": "2026-01-18T23:59:59.000Z"
    },
    "totals": {
      "totalAmount": 2850.0,
      "tipCount": 1250,
      "avgTipAmount": 2.28,
      "medianTipAmount": 1.0,
      "uniqueTippers": 450
    },
    "distribution": [
      { "range": "1-10", "count": 850, "total": 425.0 },
      { "range": "11-50", "count": 280, "total": 700.0 },
      { "range": "51-100", "count": 85, "total": 637.5 },
      { "range": "100+", "count": 35, "total": 1087.5 }
    ],
    "bySource": {
      "stream": { "amount": 2200.0, "count": 980 },
      "tipMenu": { "amount": 450.0, "count": 180 },
      "goals": { "amount": 200.0, "count": 90 }
    },
    "peakTipHours": [{ "hour": 21, "avgTips": 45.0, "dayOfWeek": "saturday" }]
  }
}
```

---

### Get Content Performance

```http
GET /creator-dashboard/content?period=30d&type=all&sort=views
Authorization: Bearer <access_token>
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "period": {
      "start": "2025-12-19T00:00:00.000Z",
      "end": "2026-01-18T23:59:59.000Z"
    },
    "summary": {
      "totalContent": 45,
      "totalViews": 125000,
      "totalPurchases": 380,
      "totalRevenue": 950.0
    },
    "content": [
      {
        "id": "cnt_abc123",
        "title": "Exclusive Photo Set",
        "type": "photoset",
        "visibility": "paid",
        "price": 50,
        "stats": {
          "views": 5200,
          "purchases": 42,
          "revenue": 210.0,
          "likes": 156,
          "conversionRate": 0.81
        },
        "publishedAt": "2026-01-15T12:00:00.000Z"
      }
    ],
    "pagination": {
      "cursor": "next_cursor",
      "hasMore": true,
      "total": 45
    }
  }
}
```

---

### Get Stream Performance

```http
GET /creator-dashboard/streams?period=30d
Authorization: Bearer <access_token>
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "period": {
      "start": "2025-12-19T00:00:00.000Z",
      "end": "2026-01-18T23:59:59.000Z"
    },
    "summary": {
      "totalStreams": 12,
      "totalStreamTime": 48,
      "avgStreamDuration": 240,
      "totalViewers": 15000,
      "avgConcurrentViewers": 312,
      "peakConcurrentViewers": 1250,
      "totalEarnings": 3200.0
    },
    "streams": [
      {
        "id": "str_xyz789",
        "title": "Saturday Night Stream",
        "startedAt": "2026-01-18T20:00:00.000Z",
        "endedAt": "2026-01-18T23:30:00.000Z",
        "duration": 210,
        "stats": {
          "peakViewers": 1250,
          "avgViewers": 850,
          "totalViewers": 3500,
          "chatMessages": 4200,
          "tips": 450.0,
          "newFollowers": 45,
          "newSubscribers": 8
        }
      }
    ],
    "bestPerformingDay": "saturday",
    "bestPerformingHour": 21
  }
}
```

---

### Get Retention Metrics

```http
GET /creator-dashboard/retention?period=30d
Authorization: Bearer <access_token>
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "period": {
      "start": "2025-12-19T00:00:00.000Z",
      "end": "2026-01-18T23:59:59.000Z"
    },
    "followerRetention": {
      "day1": 85.5,
      "day7": 65.2,
      "day30": 45.8
    },
    "subscriberRetention": {
      "month1": 92.5,
      "month3": 78.0,
      "month6": 62.5,
      "churnRate": 7.5
    },
    "viewerRetention": {
      "returning": 68.2,
      "avgVisitsPerUser": 3.5,
      "avgSessionsPerWeek": 2.1
    },
    "cohortAnalysis": [
      {
        "cohort": "2025-12",
        "size": 250,
        "retention": [100, 72, 58, 45]
      },
      {
        "cohort": "2026-01",
        "size": 320,
        "retention": [100, 78, 62]
      }
    ]
  }
}
```

---

## Viewer Analytics

### Get Watch History

```http
GET /viewer/history?cursor=<cursor>&limit=20
Authorization: Bearer <access_token>
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": [
    {
      "contentId": "str_xyz789",
      "contentType": "stream",
      "title": "Saturday Night Stream",
      "creator": {
        "id": "usr_xyz789",
        "username": "janedoe"
      },
      "watchedAt": "2026-01-18T20:00:00.000Z",
      "duration": 3600,
      "progress": 0.85
    }
  ],
  "pagination": {
    "cursor": "next_cursor",
    "hasMore": true
  }
}
```

---

### Get Viewing Stats

```http
GET /viewer/stats?period=30d
Authorization: Bearer <access_token>
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "period": {
      "start": "2025-12-19T00:00:00.000Z",
      "end": "2026-01-18T23:59:59.000Z"
    },
    "totalWatchTime": 12500,
    "streamsWatched": 45,
    "vodWatched": 12,
    "favoriteCreators": [
      {
        "creator": { "id": "usr_xyz789", "username": "janedoe" },
        "watchTime": 5000,
        "streamCount": 20
      }
    ],
    "peakWatchingHours": [{ "hour": 21, "avgWatchTime": 90 }]
  }
}
```

---

## Stream Analytics

### Get Live Stream Analytics (Real-time)

```http
GET /streams/:streamId/analytics/live
Authorization: Bearer <access_token>
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "streamId": "str_xyz789",
    "status": "live",
    "startedAt": "2026-01-18T20:00:00.000Z",
    "duration": 7200,
    "realtime": {
      "currentViewers": 1150,
      "peakViewers": 1250,
      "chatMessagesPerMinute": 45,
      "tipsInLast5Minutes": 125.0,
      "newFollowersInLast5Minutes": 12
    },
    "totals": {
      "totalViewers": 3500,
      "chatMessages": 4200,
      "tips": 850.0,
      "newFollowers": 65,
      "newSubscribers": 12
    },
    "quality": {
      "avgBitrate": 5500,
      "bufferingRate": 0.02,
      "avgLatency": 2.5
    },
    "viewerDistribution": {
      "quality": {
        "1080p": 45,
        "720p": 35,
        "480p": 15,
        "360p": 5
      }
    }
  }
}
```

---

### Get Stream Summary (Post-stream)

```http
GET /streams/:streamId/analytics/summary
Authorization: Bearer <access_token>
```

**Response (200 OK):**

```json
{
  "success": true,
  "data": {
    "streamId": "str_xyz789",
    "title": "Saturday Night Stream",
    "startedAt": "2026-01-18T20:00:00.000Z",
    "endedAt": "2026-01-18T23:30:00.000Z",
    "duration": 12600,
    "viewerMetrics": {
      "totalViewers": 3500,
      "uniqueViewers": 2800,
      "peakConcurrentViewers": 1250,
      "avgConcurrentViewers": 850,
      "avgWatchTime": 2520
    },
    "engagementMetrics": {
      "chatMessages": 4200,
      "chatParticipants": 450,
      "reactions": 1250
    },
    "revenueMetrics": {
      "totalTips": 850.0,
      "tipCount": 125,
      "avgTipAmount": 6.8,
      "topTipper": { "username": "generousfan", "amount": 100.0 },
      "goalsCompleted": 2
    },
    "growthMetrics": {
      "newFollowers": 65,
      "newSubscribers": 12,
      "subscriptionRevenue": 120.0
    },
    "technicalMetrics": {
      "avgBitrate": 5500,
      "avgLatency": 2.5,
      "bufferingEvents": 45,
      "qualityChanges": 120
    },
    "timeline": [
      { "timestamp": 0, "viewers": 50, "tips": 0 },
      { "timestamp": 600, "viewers": 450, "tips": 25.0 },
      { "timestamp": 1200, "viewers": 850, "tips": 75.0 }
    ]
  }
}
```

---

## Data Types

### Analytics Event

```typescript
interface AnalyticsEvent {
  type: string;
  timestamp: string;
  properties: Record<string, unknown>;
  context?: {
    sessionId?: string;
    userAgent?: string;
    referrer?: string;
  };
}
```

### Time Series Data Point

```typescript
interface TimeSeriesPoint {
  date: string;
  value: number;
  breakdown?: Record<string, number>;
}
```

---

## Document History

| Date       | Version | Changes                            |
| ---------- | ------- | ---------------------------------- |
| 2026-01-18 | 1.0.0   | Initial Analytics Service API docs |
