# Real-Debrid Integration Patterns

## API Key
- RD API keys are passed at container/process runtime, never hardcoded in config files
- Keys contain `!` chars — use single quotes in shell: `-e 'RD_API_KEY=TPT...RQ'`

## Checking Cache Status (Critical — Endpoint Deprecated)

**DO NOT use** `/torrents/instantAvailability/{hash}` — this endpoint is **deprecated** (error code 37: `disabled_endpoint`). This is a change that happened in 2025-2026.

**WORKING APPROACH**: Add the magnet and check the status response:

```
POST /torrents/addMagnet
Body: magnet=magnet:?xt=urn:btih:HASH&dn=name&tr=udp://tracker.opentrackr.org:1337

→ Returns { id: "TORRENT_ID" }

GET /torrents/info/{TORRENT_ID}
→ Check `status` field:
   - "waiting_files_selection" = CACHED ✅
   - "downloaded" = CACHED ✅
   - "magnet_conversion" or "downloading" = UNCACHED ❌
```

After checking, delete the test torrent: `POST /torrents/delete/{TORRENT_ID}`

Performance note: For bulk checking (10+ hashes), add each magnet, poll info, delete. This is slow (~2-3s per hash due to API latency). Consider batching with concurrent promises capped at 3-5 simultaneous checks to avoid rate limiting.

## Full Playback Flow

```
1. POST /torrents/addMagnet      → { id }
2. POST /torrents/selectFiles/{id}  Body: files=all
3. Poll GET /torrents/info/{id}   until status === "downloaded"
4. Extract links[0] from info
5. POST /unrestrict/link           Body: link=URL  → { download: "DIRECT_URL" }
6. Play DIRECT_URL
```

## Browser Playback Issue

RD direct download URLs return files in their native container format (MKV, TS, etc.). Most browsers cannot play MKV natively.

**Solutions:**
1. **Server proxy with forced video/mp4 Content-Type** — serves the RD stream through a local proxy that sets `Content-Type: video/mp4` and supports Range requests. Works for H.264/H.265 content even in MKV containers (browser handles container parsing).
2. **External player (VLC/MPV)** — provide the direct download URL for the user to open in VLC.
3. **RD streaming endpoint** — use `/streaming/transcode/{torrentId}/{fileId}` (requires file ID from torrent info, not fully tested).

## Magnet Link Format

RD requires the full magnet URI format:
```
magnet:?xt=urn:btih:HASH&dn=NAME&tr=udp://tracker.opentrackr.org:1337
```

Not just `urn:btih:HASH` — RD will reject with `wrong_parameter` error code 2.

## CORS Handling

RD API does NOT send CORS headers. Browser fetch calls to RD API directly will fail. Must proxy through server:
- Server receives browser request
- Server adds `Authorization: Bearer KEY` header
- Server forwards to RD API
- Server sends response back with `Access-Control-Allow-Origin: *`

## API Key Security

Never expose RD API key to the browser. Even in a local/test setup, proxy through the server. The key gives full account access.
