# Top Gift — this source tree The editor and browser source now use the same DOM/video renderer. Existing `top-gifter.html?o=...` links and the account-scoped storage key remain valid. The default source is **Top gifter**, using the owner's currently saved TikTok username from Account settings. Publish / save starts live preview automatically. OBS checks automatically, too. The current top gifter stays visible and updates in place; offline or failed responses clear the card. No gift relay is required for this ranking source. Top gift remains an optional webhook source. The browser checks every 15 seconds. Server lookup caching is 20 seconds while live and 90 seconds offline; detection is polling, not an instant event stream. TikTok may deny/omit rankings even when live detection succeeds. The UI reports that state; it cannot guarantee access from a username alone. An existing server-side TikTok session, if configured, is reused. No real stream was used in the local tests. Use **Where do I add this link?** beside Publish / save for OBS and LIVE Studio browser-source instructions. The **Set TikTok username** button opens the existing Account settings dialog. Changes there are read without republishing. ## Deployment Upload `index.html`, `top-gifter.html`, `assets/topgift.css`, `assets/topgift.js`, `assets/topgift-editor.js`, `assets/topgift-demo.webm`, `assets/topgift-coin.svg`, `api/topgifter.php`, `api/_topgift.php`, `api/topgift-events.php`, `api/gift-asset.php`, and this guide together. Keep the existing `_lib.php`, gift icons, account data and access rules. No Node service or build step is required on the VPS. Use the PHP version already required by `_lib.php` (PHP 8+; validated here with PHP 8.2). The old `top-gifter-paint.js` is no longer loaded, but is retained on disk for rollback. The old ranking API remains compatible for other consumers. Its TikTok-cookie feature is no longer used by the new widget. ## Gift and effects inspector Search the existing gift catalog by name or ID and select a gift to preview it. Replay selected gift plays an installed original animation when available; otherwise it shows the gift icon with the chosen overlay effects and labels the missing video. Selection changes only the preview, never the live ranking. The inspector includes gradient colors, built-in fonts, text/image glow, position, rotation, Float/Pulse/Spin motion, speed, undo/redo, reset style, and JSON style import/export. Styles are saved per account in the browser; Publish / save sends them to OBS. Reset style leaves the published link intact. Editing effects pauses live polling in the editor; choose Live preview to resume. Plan limits match the corresponding main editor features: Free has two gradient colors and one motion; Pro has five colors, image glow and one motion; Legend has 32 colors, image glow and stacked motion. Text glow and the built-in fonts are available on every plan. Server-side checks also enforce these limits. The main editor's multi-card profiles, text layers and custom font uploads are not duplicated in this single-gift inspector. ## Connect the relay 1. Sign in, open OverlayX → Top Gift, and publish. 2. Copy the OBS URL. Use 1024×768 initially; transparent is the default. 3. For the optional Top gift source, open Advanced · gift relay, get the webhook key and configure your server-side gift relay to POST JSON to the displayed webhook URL with header `X-Topgift-Key: `. Do not put the key in OBS or public JavaScript. 4. Send this shape, using real values from each gift event: ```json { "msgId": "unique-event-message-id", "giftId": "5655", "giftName": "Rose", "diamondCount": 1, "repeatCount": 3, "giftType": 1, "groupId": "unique-streak-id", "repeatEnd": true, "user": {"uniqueId": "sender", "nickname": "Sender"} } ``` For streaks, `repeatCount` is the cumulative quantity and `groupId` must remain stable through the final update. A new streak needs a new group ID. Without `groupId`, a non-streak event is treated as a distinct batch; `msgId` deduplicates delivery retries. Never invent new message IDs on HTTP retries. The final streak notification contributes only a positive count delta, so it is not double-counted. The receiver accepts nested modern `giftDetails` and `user` fields as well as the flat legacy user fields. Normalize your connector's payload to this contract. The existing Stack webhook is for game actions, not gift accounting; it is not reused. A dependency-free TikFinity adapter is included at `scripts/topgift-relay.mjs`. Run it on the same computer as TikFinity Desktop using Node.js 22+ (the VPS still uses PHP): ```powershell $env:TOPGIFT_WEBHOOK_URL = 'https://kapfortyjordy.com/api/topgift-events.php?id=YOUR_PUBLISHED_ID' $env:TOPGIFT_WEBHOOK_KEY = 'YOUR_PRIVATE_WEBHOOK_KEY' node scripts/topgift-relay.mjs ``` It connects to TikFinity's documented `ws://127.0.0.1:21213/` event API, normalizes gifts and retries webhook deliveries using the same message ID. `TIKFINITY_WS_URL` overrides the local endpoint. It keeps at most 256 queued events; overflow is explicitly logged. Stop it with Ctrl+C. No relay has been connected to a real stream as part of these local tests. Each gift event also carries an `animationUrl` harvested from the raw producer packet when TikFinity exposes a TikTok CDN video URL. The receiver remembers it per gift ID, and the next overlay poll downloads the file once into `data/gift-animations/` (TikTok CDN hosts only, 25 MiB ceiling, container magic verified, one download per poll). After that first delivery the animation is a server asset and plays through `api/gift-asset.php` on every future gift of that kind. Until then the overlay falls back to the live CDN URL, then to the spark burst. A local batch installer is also available: `python scripts/fetch-gift-animations.py --room-id ` (the unsigned global gift catalog no longer answers without a room ID; the script also accepts `--catalog ` and `--id --url `). Protocol references: [TikFinity Event API](https://tikfinity.zerody.one/tiktok/dapi) and [TikTok-Live-Connector gift events](https://github.com/zerodytrash/TikTok-Live-Connector#gift). Ranking aggregates **sender + gift ID** within the configured rolling window. Ties use the most recently accepted gift update. Expired contributions disappear on the next poll, including during silence. There is deliberately no lifetime fallback: that would reintroduce expired gifts. Reconnect fetches a complete snapshot, so OBS does not need a delivery queue. Counts update in place for the same leader. A changed leader cancels prior playback and timers. ## Real animation files The gift animations TikFinity, BetterTok and the TikTok LIVE web player itself play are the video files behind TikTok's **signed** room gift-list endpoint (`webcast.tiktok.com/webcast/gift/list/`, field `animation`/`giftpublicinfo` per gift, served from the `webcast.tiktokcdn.com` CDN). That endpoint refuses unsigned calls — the tools that use it run a paid signer (Euler Stream Business) or harvest the URLs from a real browser session on a live page. There is no free public mirror of the files; marketplace bundles are resold CDN rips. Three ways to get the files into `data/gift-animations/`: 1. **Automatic (relay learning).** Each relay-forwarded gift event carries an `animationUrl` harvested from the raw producer packet. The receiver remembers it per gift ID and the next overlay poll downloads the file once (TikTok CDN hosts only, 25 MiB ceiling, container magic verified, one download per poll). The first Rose on stream teaches the site the Rose animation; every later Rose plays it. 2. **Browser scrape (the BetterTok method).** While any streamer on the roster — or any live room — is live, run: `node scripts/scrape-gift-animations.cjs …` It opens the live page in headless Chrome, lets the page sign its own `gift/list/` request, harvests every gift's CDN animation URL from the traffic, downloads them all into `data/gift-animations/`, and writes `catalog.json`. One live session collects the whole gift catalog. 3. **Manual.** `python scripts/fetch-gift-animations.py --id --url ` for a single file, or `--catalog ` for a local export. Once a file exists as `data/gift-animations/.webm` (preferred, alpha) or `.mp4`, `api/gift-asset.php` streams it with range support; until then the overlay hotlinks the learned CDN URL directly, and without any URL the spark burst plays. The animation **loops** while the card is on screen and the card cuts out after the hold window. Files are limited to 25 MiB. Confirm the codec in your actual OBS version. Icons continue to use `assets/gifts/.webp`; an unknown icon shows a star. No real TikTok video assets were included with the request. Gift metadata is not a guarantee of a playable, transparent video. Proprietary effect bundles must be converted through an appropriate asset workflow first; renaming to `.webm` does not convert them. The receiver deliberately ignores arbitrary asset URLs, so incoming events cannot turn the server into an unrestricted download proxy. The 2-second `topgift-demo.webm` is a **synthetic playback test**, not a TikTok gift animation. `?mock=1` runs without live APIs or external services, using local static assets. It demonstrates a leader, a lower-gift no-op, an interrupt, a missing animation and a count update. `?bg=black` sets a black canvas; `?bg=transparent` keeps OBS transparency. `?debug=1` shows connection status. ## Local checks ```text node scripts/serve-topgift-preview.cjs node scripts/test-profile-recovery.cjs php scripts/test-topgift.php ``` Open `http://127.0.0.1:4177/top-gifter.html?mock=1`. The static preview server is loopback-only and never serves account data or executes PHP. It tests rendering, not authenticated publishing. Real ingestion and OBS verification require PHP and the deployed relay. ## Adapted implementation brief Use the existing PHP identity/access checks and publish IDs. Replace only the Top Gifter editor/controller and OBS renderer; preserve the main card editor and its recovery fixes. Use a centered purple glow, TOP GIFT label, 186 px gift stage, white sender name, purple coin value and cumulative quantity badge. Scale the whole composition proportionally. Default to 42% of viewport height so the stage is readable; the editor can reduce it to the original brief's 26%. Own one video and a cancellable state timer per view. Use a sequential, abortable poll loop with retry backoff instead of inventing a `/ws` service. Store ranking server-side so reload/reconnect preserves state. Keep reduced-motion rendering fade-only. Use uploaded, known-ID assets instead of assuming that TikTok exposes every animation as VP9/WebM. Do not fabricate asset URLs or diamond prices. The supplied attachments contained text only; `image.png` was mentioned in the text but was not an attached file. Visual styling follows the written reference description and has not been verified pixel-for-pixel against that missing image.