# OBS donation overlay

This page receives donations through the [live stream](https://developers.donatty.com/en/realtime.md) and shows them in OBS according to the [moderation rules](https://developers.donatty.com/en/structures/donation.md#moderation-and-display). A single HTML file uses the [centrifuge-js](https://github.com/centrifugal/centrifuge-js) library; you do not need your own server. Delivery time depends on payment processing and the [source conditions](https://developers.donatty.com/en/conditions/sources.md).

## What you need

- A secret key with `donations:read`: [how to issue one](https://developers.donatty.com/en/tokens.md#issue-a-key). Issue a separate key for the overlay with this scope only.
- OBS with the Browser source.

> **Keep the file with the key on your own computer only.**
> The file holds a secret key. Before storing a secret key in a local file, read [Keep the secret key on the server](https://developers.donatty.com/en/tokens.md#keep-the-secret-key-on-the-server); if someone else has seen the key, [replace it](https://developers.donatty.com/en/tokens.md#replace-a-secret-key).

## 1. Save the code

Save the code as `overlay.html` and replace `dnt_pat_...` with your key.

The example inserts the donor's name and message with `textContent`: if they contain markup, it stays text.

```html title="overlay.html"
<!doctype html>
<meta charset="utf-8">
<title>Donations</title>
<style>
  body { margin: 0; font: 600 32px/1.3 system-ui, sans-serif; color: #fff; text-shadow: 0 2px 6px #000; }
  #alert { padding: 24px; opacity: 0; transition: opacity .4s; }
  #alert.on { opacity: 1; }
</style>
<div id="alert"><div id="who"></div><div id="text"></div></div>
<script src="https://unpkg.com/centrifuge@5.8.0/dist/centrifuge.js"
  integrity="sha384-Hc/rqOA60dxGHNnO+nCm7KQ1yc4I121B7eeuuZ9vJMHEq6vVV4onLLtrwG8L79xQ" crossorigin="anonymous"></script>
<script>
  const API = "https://api.donatty.com";
  const KEY = "dnt_pat_...";  // secret key: keep this file on your own computer only

  const SHOW = new Set(["NONE", "PASSED"]);
  const events = new Set();   // ids of events already handled: one event can arrive twice
  const shown = new Set();    // ids of donations already shown
  const waiting = new Map();  // id → donation moderation has not decided on
  const queue = [];           // donations are shown one at a time
  let last = new Date();      // time of the last event; before the first one, the launch moment
  let busy = false;

  function next() {
    const d = queue.shift();
    busy = Boolean(d);
    if (!d) return;
    // textContent: the donor's name and message stay text even if they contain markup
    document.getElementById("who").textContent = `${d.donorName} — ${d.amount.value} ${d.amount.currency}`;
    document.getElementById("text").textContent = d.message;
    const box = document.getElementById("alert");
    box.classList.add("on");
    setTimeout(() => { box.classList.remove("on"); setTimeout(next, 500); }, 6000);
  }

  function show(d) {
    shown.add(d.id);
    queue.push(d);
    if (!busy) next();
  }

  function donation(d, replay = false) {
    const status = d.moderation.status;
    if (status === "PENDING") waiting.set(d.id, d);  // shown after donation.moderated with the PASSED status
    else if (SHOW.has(status) && (replay || !shown.has(d.id))) show(d);
  }

  function handle(event) {
    if (events.has(event.id)) return;
    events.add(event.id);
    if (new Date(event.time) > last) last = new Date(event.time);
    const { type, data } = event;
    if (type === "donation.created") donation(data);
    else if (type === "donation.replayed") donation(data, true);  // you pressed «Повторить на стриме» (Repeat on stream)
    else if (type === "donation.moderated") {
      const d = waiting.get(data.id);
      waiting.delete(data.id);
      if (d && data.moderation.status === "PASSED") show(d);
    }
  }

  const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

  // The channel history did not cover the gap: read the donations with regular requests.
  async function catchUp() {
    const since = new Date(last - 60000).toISOString();
    await sleep(1000 + Math.random() * 9000);  // so that all programs do not arrive in the same second after an outage
    const items = [];
    for (let cursor = null; ;) {
      const url = `${API}/v1/donations?limit=100&since=${since}` + (cursor ? `&cursor=${encodeURIComponent(cursor)}` : "");
      const res = await fetch(url, { headers: { Authorization: `Bearer ${KEY}` } }).catch(() => null);
      if (res && (res.status === 401 || res.status === 403)) return console.error(`HTTP ${res.status}: the key does not work`);
      if (!res || !res.ok) {
        await sleep(1000 * (Number(res && res.headers.get("Retry-After")) || 5));
        continue;
      }
      const page = await res.json();
      items.push(...page.items);
      cursor = page.nextCursor;
      if (!cursor) break;
    }
    items.reverse().forEach(d => donation(d));  // oldest first
  }

  const client = new Centrifuge(API.replace("http", "ws") + "/v1/realtime/websocket", {  // https → wss
    headers: { Authorization: `Bearer ${KEY}` },  // the key goes in the first connection message, not in the address
    data: { channels: ["donations"] },            // donations only; without data all the key's channels arrive
  });
  client.on("publication", ctx => handle(ctx.data));
  client.on("subscribed", ctx => { if (ctx.wasRecovering && !ctx.recovered) catchUp(); });
  client.on("connecting", ctx => console.log(`connecting: ${ctx.code} ${ctx.reason}`));
  client.on("disconnected", ctx => console.error(`disconnected: ${ctx.code} ${ctx.reason}`));  // final refusal
  client.connect();
</script>
```

## 2. Add the page to OBS

1. Add a Browser source to your scene.
2. Tick "Local file" and choose `overlay.html`.
3. Set the size, for example 800 by 200.

## 3. Check it

Press «Тест на стриме» (Test on stream) in your dashboard: the test donation appears in OBS for 6 seconds.

## How it works

- The key is in the `headers` option: the library sends it in the first connection message, without including it in the URL. Do not enable the `sse` transport: [why](https://developers.donatty.com/en/realtime.md#libraries).
- The page asks for the donations channel only: `data: { channels: ["donations"] }`.
- The page shows `NONE` and `PASSED` donations right away. It remembers a `PENDING` donation and shows it after `donation.moderated` with the `PASSED` status. It never shows `BLOCKED` or an unknown status: that is the [Moderation and display](https://developers.donatty.com/en/structures/donation.md#moderation-and-display) rule.
- `donation.replayed` arrives when you press «Повторить на стриме» (Repeat on stream): the donation is shown once more.
- The page skips an event that arrived twice by its `id` ([repeats and order](https://developers.donatty.com/en/realtime/recovery.md#repeats-and-order)).
- After a drop the library reconnects by itself, and the server sends what was missed from the history. If the history did not cover the gap, the page waits a random time from 1 to 10 seconds and reads the donations with the [Donations](https://developers.donatty.com/en/reference/donations.md) method: the steps are in the [Stream and catch-up](https://developers.donatty.com/en/examples/stream-recovery.md) example.
- The library is loaded from unpkg.com. The `integrity` attribute keeps the browser from running the file if it was replaced.

## If a donation did not appear

Open `overlay.html` in a browser and look at the console:

- `disconnected: <code> <reason>`: the server rejected the connection permanently. For the meaning of the code and the next step, see [Stream close codes](https://developers.donatty.com/en/realtime/close-codes.md). For example, `4501 invalid_token` means the key has a typo or the code still has the `dnt_pat_...` placeholder.
- No errors, but the donation did not show up: check its moderation status against [Moderation and display](https://developers.donatty.com/en/structures/donation.md#moderation-and-display).

## Example limitations

- After a reload, the page receives new donations only. It does not keep a record of previously displayed donations.
- The page does not show a donation that was waiting for moderation at the moment of the reload.
- The key will expire. Replace it in the file in advance ([how](https://developers.donatty.com/en/tokens.md#replace-a-secret-key)) and refresh the source in OBS.
