# API Reference Documentation

Tobuzz Extractor is a production Cloudflare Workers edge API service that resolves TMDB movies and TV episodes into preflight-validated, normalized playable sources. Provider execution follows centralized priority order (VidNest → VidSrc.su → VidSrc.to) with automatic fallback, in-flight request deduplication, English-first selection, subtitle normalization, and edge resolution caching.

---

## Base URL

When deployed on Cloudflare Workers:
`https://<your-worker-subdomain>.workers.dev` (or custom domain)

For local development:
`http://localhost:3000`

---

## Authentication

No API keys or HTTP Bearer tokens are required for public resolution or health check endpoints.

---

## Public Endpoints

### 1. Health Check
`GET /api/health`

Returns service status and health information.

#### Parameters
None.

#### Example Request
```bash
curl -X GET "https://tobuzz-extractor.example.workers.dev/api/health"
```

#### Example Response (`200 OK`)
```json
{
  "ok": true,
  "service": "tobuzz-extractor"
}
```

---

### 2. Resolve Movie
`GET /api/resolve/{tmdbId}`

Resolves a movie TMDB ID into a validated, playable media source.

#### Path Parameters
| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `tmdbId` | Integer | Yes | The TMDB movie ID (e.g. `533535` for *Deadpool & Wolverine*, `315635` for *Spider-Man: Into the Spider-Verse*). |

#### Query Parameters
| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `only` / `provider` / `providers` | String | No | Restrict resolution to specific provider ID(s), e.g. `vidnest`, `vidsrcsu`, or `vidsrcto`. Multiple values can be comma-separated or passed repeatedly. |
| `exclude` | String | No | Exclude specific provider ID(s) from execution, e.g. `?exclude=vidnest`. |

#### Example Request
```bash
curl -X GET "https://tobuzz-extractor.example.workers.dev/api/resolve/533535?only=vidsrcto"
```

#### Success Response (`200 OK`)
```json
{
  "success": true,
  "source": {
    "provider": "vidsrcto",
    "type": "hls",
    "url": "/api/media-proxy?url=https%3A%2F%2Frecursive-reverie.website%2Fv%2Fhls%2Fmaster.m3u8&referer=https%3A%2F%2Fcloudorchestranova.com%2F&tokenUrl=https%3A%2F%2Frecursive-reverie.website%2Fgenerate.php&tokenReferer=https%3A%2F%2Fvidsrc.to%2F",
    "quality": "auto",
    "headers": {
      "Referer": "https://cloudorchestranova.com/"
    },
    "subtitles": []
  },
  "attempts": [
    {
      "provider": "vidnest",
      "success": false,
      "durationMs": 120,
      "error": {
        "code": "VIDNEST_RUNTIME_RESOLUTION_FAILED",
        "message": "VidNest player/API resolution did not produce validated playable media candidates across any configured servers"
      }
    },
    {
      "provider": "vidsrcsu",
      "success": false,
      "durationMs": 350,
      "error": {
        "code": "EXTRACTION_FAILED",
        "message": "Vidsrc.su did not return a validated HLS stream"
      }
    },
    {
      "provider": "vidsrcto",
      "success": true,
      "durationMs": 890,
      "sourceType": "hls"
    }
  ]
}
```

---

### 3. Resolve TV Episode
`GET /api/resolve/{tmdbId}/{season}/{episode}`

Resolves a TV episode into a validated, playable media source.

#### Path Parameters
| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `tmdbId` | Integer | Yes | The TMDB TV show ID (e.g. `1396` for *Breaking Bad*, `1399` for *Game of Thrones*). |
| `season` | Integer | Yes | Positive season number (e.g. `1`). |
| `episode` | Integer | Yes | Positive episode number (e.g. `1`). |

#### Query Parameters
Same provider filter query parameters as Movie resolution (`only`, `provider`, `providers`, `exclude`).

#### Example Request
```bash
curl -X GET "https://tobuzz-extractor.example.workers.dev/api/resolve/1396/1/1"
```

---

### 4. Media Proxy
`GET /api/media-proxy`

Proxies media manifests and segments under server egress IP, dynamically resolves ephemeral authorization tokens, rewrites playlist URIs, and enforces SSRF host security.

#### Query Parameters
| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `url` | String | Yes | Absolute target media or playlist URL to fetch. |
| `referer` | String | No | Upstream Referer header sent to the media host. |
| `tokenUrl` | String | No | Upstream token generation endpoint (e.g. `${origin}/generate.php`). |
| `tokenReferer` | String | No | Referer header required when requesting dynamic proxy tokens. |

#### Response Headers
- `Content-Type`: `application/vnd.apple.mpegurl` (for playlists) or `video/mp4` / `application/octet-stream` (for segments).
- `Access-Control-Allow-Origin`: `*` (enables cross-origin browser playback).
- `Cache-Control`: `public, max-age=86400` (for segments).

---

## Response Schema Reference

### Root Response Object

| Field | Type | Description |
| --- | --- | --- |
| `success` | Boolean | `true` if a validated playable source was resolved; `false` if resolution failed. |
| `source` | Object | Present when `success: true`. The normalized playable media object. |
| `error` | Object | Present when `success: false`. Root error information. |
| `attempts` | Array | Log of execution attempts across requested/registered providers. |

### `source` Object Fields

| Field | Type | Description |
| --- | --- | --- |
| `provider` | String | Registered ID of the provider that successfully resolved the stream (e.g. `vidnest`, `vidsrcsu`, `vidsrcto`). |
| `type` | String | Media stream type: `"hls"`, `"mp4"`, `"dash"`, or `"other"`. |
| `url` | String | Final playable URL. May be an absolute upstream URL or a relative `/api/media-proxy` URL. |
| `quality` | String | Stream quality string, typically `"auto"`. |
| `headers` | Object (Optional) | HTTP headers required during client playback (e.g. `Referer`, `User-Agent`). |
| `subtitles` | Array | List of available subtitle track objects. |
| `metadata` | Object (Optional) | Provider-specific metadata (e.g. server key, audio language, dual audio flags). |

### `subtitles` Object Fields

| Field | Type | Description |
| --- | --- | --- |
| `lang` | String | Subtitle language (e.g. `"English"`, `"Spanish"`). |
| `url` | String | Absolute URL to the WebVTT (`.vtt`) or SubRip (`.srt`) track file. |
| `format` | String | Format identifier (`"vtt"` or `"srt"`). |

### `attempts` Array Item Fields

| Field | Type | Description |
| --- | --- | --- |
| `provider` | String | Provider ID attempted. |
| `success` | Boolean | `true` if this provider succeeded; `false` otherwise. |
| `durationMs` | Number | Execution duration in milliseconds. |
| `sourceType` | String (Optional) | Resolved stream type if successful (`"hls"`, `"mp4"`, etc.). |
| `error` | Object (Optional) | Error object containing `code` and `message` if attempt failed. |

---

## HTTP Status Codes

| Status Code | Meaning | Cause |
| --- | --- | --- |
| `200 OK` | Resolution Success | Validated playable source successfully resolved and returned. |
| `400 Bad Request` | Invalid Client Parameters | Missing TMDB ID, invalid season/episode, or bad URL parameters. |
| `403 Forbidden` | Proxy Security Denial | `/api/media-proxy` request targeting an unauthorized or prohibited host. |
| `405 Method Not Allowed` | Unsupported HTTP Method | Request method was not `GET`. |
| `502 Bad Gateway` | Resolution / Upstream Failure | None of the attempted providers returned a validated playable source. |

## Media proxy browser-playability note

`/api/resolve` returns the best server-validated source. For providers that require `/api/media-proxy`, browser playability also depends on the proxy being able to serve every HLS child resource, not just the first manifest. Clients must not equate an extracted `.m3u8` or a server-side validation pass with actual browser playback.

`/api/media-proxy` is responsible for preserving required upstream context such as referer, token refresh parameters, query strings, CORS headers, and Range-related response headers while retaining SSRF/domain protections.
