Add OBS overlays (goal, timer, counter, alerts) with ETag polling

Align timer state key with rules engine (timer_ends_at).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
shadowdaoandClaude Sonnet 5.5 committed 2026-11-15 08:45:22 -08:00
1 parent 7155396312
commit 65082fb2f5
10 files changed
+815

No files matched your search

+33
View File
@@ -0,0 +1,33 @@
:root{--sg-fg:#fff;--sg-accent:#7c5cff;--sg-accent2:#22d3ee;--sg-track:rgba(255,255,255,.18);--sg-bg:rgba(0,0,0,.45);--sg-font:system-ui,-apple-system,"Segoe UI",Roboto,Arial,sans-serif;--sg-scale:1}
*{box-sizing:border-box}
html,body{margin:0;padding:0;background:transparent!important;overflow:hidden;width:100%;height:100%}
body{font-family:var(--sg-font);color:var(--sg-fg);font-size:calc(clamp(12px,4.2vmin,64px) * var(--sg-scale));line-height:1.2}
.sg-theme-light{--sg-fg:#111;--sg-track:rgba(0,0,0,.15);--sg-bg:rgba(255,255,255,.75)}
.sg-theme-neon{--sg-accent:#ff2bd6;--sg-accent2:#00f0ff;--sg-bg:rgba(10,0,30,.55)}
.sg-theme-minimal{--sg-bg:transparent}
#sg-root{width:100%;height:100%;display:flex;align-items:center;justify-content:center;padding:2vmin;transition:opacity .4s}
body.sg-offline #sg-root{opacity:.6}
.sg-card{width:100%;max-width:100%;background:var(--sg-bg);border-radius:.6em;padding:.6em .8em;text-shadow:0 1px 3px rgba(0,0,0,.35)}
.sg-theme-light .sg-card{text-shadow:none}
.sg-theme-neon .sg-card{box-shadow:0 0 .8em var(--sg-accent2),inset 0 0 .4em var(--sg-accent)}
.sg-theme-minimal .sg-card{padding:0}
.sg-title{font-weight:700;margin-bottom:.35em;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.sg-track{position:relative;height:1.1em;background:var(--sg-track);border-radius:999px;overflow:hidden}
.sg-fill{height:100%;width:0;background:linear-gradient(90deg,var(--sg-accent),var(--sg-accent2));border-radius:999px;transition:width 1.2s cubic-bezier(.22,1,.36,1)}
.sg-pct{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;font-size:.7em;font-weight:700;text-shadow:0 1px 2px rgba(0,0,0,.5);color:#fff}
.sg-nums{display:flex;justify-content:space-between;gap:.5em;margin-top:.3em;font-size:.8em;font-variant-numeric:tabular-nums}
.sg-big{font-size:2.4em;font-weight:800;font-variant-numeric:tabular-nums;text-align:center;letter-spacing:.02em}
.sg-big.sg-expired{opacity:.6}
.sg-big.sg-paused{animation:sg-blink 1.4s steps(2,jump-none) infinite}
.sg-label{text-align:center;font-weight:600;opacity:.9}
.sg-w-timer .sg-card,.sg-w-counter .sg-card{width:auto;min-width:40%}
.sg-w-alerts #sg-root{align-items:flex-end}
.sg-alert{width:100%;text-align:center;background:var(--sg-bg);border:.1em solid var(--sg-accent);border-radius:.7em;padding:.6em .9em;animation:sg-in .6s cubic-bezier(.22,1,.36,1) both}
.sg-alert.sg-out{animation:sg-out .5s ease-in both}
.sg-alert-head{font-weight:800;font-size:1.2em}
.sg-alert-head b{color:var(--sg-accent2)}
.sg-alert-msg{margin-top:.3em;font-size:.85em;overflow-wrap:anywhere;max-height:5.2em;overflow:hidden}
@keyframes sg-in{from{opacity:0;transform:translateY(40%) scale(.9)}to{opacity:1;transform:none}}
@keyframes sg-out{to{opacity:0;transform:translateY(-30%) scale(.95)}}
@keyframes sg-blink{50%{opacity:.4}}
@media (prefers-reduced-motion:reduce){.sg-fill{transition:none}.sg-alert,.sg-alert.sg-out{animation:none}}
+163
View File
@@ -0,0 +1,163 @@
(function () {
'use strict';
var body = document.body;
var widget = body.getAttribute('data-widget');
var endpoint = body.getAttribute('data-endpoint');
var poll = Math.max(1000, parseInt(body.getAttribute('data-poll'), 10) || 2500);
var root = document.getElementById('sg-root');
var etag = null, failures = 0, since = null, skew = 0, timerState = null;
var queue = [], showing = false;
function el(tag, cls, text) {
var e = document.createElement(tag);
if (cls) e.className = cls;
if (text != null) e.textContent = text;
return e;
}
// ---- goal ----
var goal = null, shownRaised = 0, raf = 0;
function renderGoal(d) {
if (!d.active) { root.textContent = ''; goal = null; return; }
if (!goal) {
root.textContent = '';
var card = el('div', 'sg-card');
goal = { title: el('div', 'sg-title'), fill: el('div', 'sg-fill'), pct: el('div', 'sg-pct'),
raised: el('span'), target: el('span') };
var track = el('div', 'sg-track');
track.appendChild(goal.fill); track.appendChild(goal.pct);
var nums = el('div', 'sg-nums'); nums.appendChild(goal.raised); nums.appendChild(goal.target);
card.appendChild(goal.title); card.appendChild(track); card.appendChild(nums);
root.appendChild(card);
}
goal.title.textContent = d.title;
goal.target.textContent = d.target_display;
goal.fill.style.width = d.percent + '%';
goal.pct.textContent = d.percent + '%';
tweenRaised(d);
}
function tweenRaised(d) {
cancelAnimationFrame(raf);
var from = shownRaised, to = d.raised_minor, t0 = performance.now(), dur = 1200;
var sym = d.raised_display.replace(/[\d.,]+$/, '');
var dec = /\.\d+$/.test(d.raised_display) ? 2 : 0;
function fmt(minor) {
var v = dec ? minor / 100 : minor;
return sym + v.toLocaleString('en-US', { minimumFractionDigits: dec, maximumFractionDigits: dec });
}
function step(now) {
var p = Math.min(1, (now - t0) / dur), e = 1 - Math.pow(1 - p, 3);
shownRaised = Math.round(from + (to - from) * e);
goal.raised.textContent = p >= 1 ? d.raised_display : fmt(shownRaised);
if (p < 1) raf = requestAnimationFrame(step);
}
raf = requestAnimationFrame(step);
}
// ---- timer ----
var timerEls = null;
function renderTimer(d, receivedAtMs) {
timerState = d;
// skew = serverClock - clientClock, measured at receipt, so local ticking is immune to a wrong PC clock.
skew = d.server_now - receivedAtMs / 1000;
if (!timerEls) {
root.textContent = '';
var card = el('div', 'sg-card'); timerEls = { big: el('div', 'sg-big', '--:--:--') };
card.appendChild(timerEls.big); root.appendChild(card);
}
}
function pad(n) { return (n < 10 ? '0' : '') + n; }
function tickTimer() {
var d = timerState;
if (d && timerEls) {
var rem;
if (!d.active) rem = null;
else if (d.paused) rem = d.remaining_seconds;
else rem = Math.max(0, Math.ceil(d.ends_at - (Date.now() / 1000 + skew)));
if (rem === null) timerEls.big.textContent = '--:--:--';
else timerEls.big.textContent = pad(Math.floor(rem / 3600)) + ':' + pad(Math.floor(rem / 60) % 60) + ':' + pad(rem % 60);
timerEls.big.classList.toggle('sg-expired', rem === 0);
timerEls.big.classList.toggle('sg-paused', !!(d && d.paused));
}
setTimeout(tickTimer, 250);
}
// ---- counter ----
function renderCounter(d) {
root.textContent = '';
var card = el('div', 'sg-card');
card.appendChild(el('div', 'sg-big', Number(d.value).toLocaleString('en-US')));
if (d.label) card.appendChild(el('div', 'sg-label', d.label));
root.appendChild(card);
}
// ---- alerts ----
function renderAlerts(d) {
since = d.last_id;
for (var i = 0; i < d.alerts.length; i++) queue.push(d.alerts[i]);
next();
}
function next() {
if (showing || !queue.length) return;
showing = true;
var a = queue.shift();
root.textContent = '';
var card = el('div', 'sg-alert');
var head = el('div', 'sg-alert-head');
head.appendChild(el('b', null, a.name));
head.appendChild(document.createTextNode(' donated '));
head.appendChild(el('b', null, a.amount_display));
card.appendChild(head);
if (a.message) card.appendChild(el('div', 'sg-alert-msg', a.message));
root.appendChild(card);
setTimeout(function () {
card.classList.add('sg-out');
setTimeout(function () { root.textContent = ''; showing = false; next(); }, 500);
}, 6500);
}
// ---- polling ----
function url() {
var u = endpoint;
if (widget === 'alerts' && since !== null) u += (u.indexOf('?') < 0 ? '?' : '&') + 'since=' + encodeURIComponent(since);
return u;
}
function schedule() {
var delay = failures ? Math.min(15000, poll * Math.pow(2, Math.min(failures, 3))) : poll;
setTimeout(tick, delay);
}
function tick() {
var ctrl = typeof AbortController === 'function' ? new AbortController() : null;
var to = ctrl ? setTimeout(function () { ctrl.abort(); }, 8000) : 0;
var headers = { 'Accept': 'application/json' };
if (etag) headers['If-None-Match'] = etag;
fetch(url(), { headers: headers, cache: 'no-store', signal: ctrl ? ctrl.signal : undefined })
.then(function (r) {
clearTimeout(to);
if (r.status === 304) return null;
if (!r.ok) throw new Error('http ' + r.status);
var et = r.headers.get('ETag');
return r.json().then(function (j) { etag = et; return j; });
})
.then(function (d) {
failures = 0; body.classList.remove('sg-offline');
if (d) apply(d);
schedule();
})
.catch(function () {
clearTimeout(to);
failures++; if (failures >= 2) body.classList.add('sg-offline'); // keep last good state on screen
schedule();
});
}
function apply(d) {
var now = Date.now();
if (widget === 'goal') renderGoal(d);
else if (widget === 'timer') renderTimer(d, now);
else if (widget === 'counter') renderCounter(d);
else if (widget === 'alerts') renderAlerts(d);
}
if (widget === 'timer') tickTimer();
tick();
})();
+31
View File
@@ -0,0 +1,31 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Overlay;
/**
* Read-only data the overlay widgets need. Rows are raw associative arrays shaped like the
* sg_* tables; the payload builders do all privacy filtering, so implementations need not.
*/
interface OverlayDataSource {
/** The goal currently shown on stream (status active, newest first), or null. */
public function activeGoal(): ?array;
/** Sum of completed donations for the goal, in minor units (base or total per counts_fees). */
public function raisedMinor( array $goal ): int;
/** Raw sg_state value for a goal key, or null. */
public function stateValue( int $goalId, string $key ): ?string;
/** @return array{label:string,value:int} */
public function counter( int $goalId ): array;
/**
* Donations newer than $sinceId (ascending id, at most $limit rows). With null, return the single
* newest row so the caller can establish a baseline.
*
* @return array<int,array<string,mixed>>
*/
public function donations( ?int $sinceId, int $limit ): array;
}
+33
View File
@@ -0,0 +1,33 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Overlay;
/** Maps a widget name to its payload using a data source. */
final class OverlayService {
public const WIDGETS = array( 'goal', 'timer', 'counter', 'alerts' );
public function __construct( private OverlayDataSource $source ) {}
public function payload( string $widget, int $now, ?int $since = null ): ?array {
$goal = $this->source->activeGoal();
$gid = $goal ? (int) $goal['id'] : 0;
switch ( $widget ) {
case 'goal':
return Payloads::goal( $goal, $goal ? $this->source->raisedMinor( $goal ) : 0 );
case 'timer':
return Payloads::timer(
$gid ? $this->source->stateValue( $gid, 'timer_ends_at' ) : null,
$gid ? $this->source->stateValue( $gid, 'paused_remaining' ) : null,
$now
);
case 'counter':
$c = $gid ? $this->source->counter( $gid ) : array( 'label' => '', 'value' => 0 );
return Payloads::counter( $c['label'], $c['value'] );
case 'alerts':
return Payloads::alerts( $this->source->donations( $since, 20 ), $since );
}
return null;
}
}
+135
View File
@@ -0,0 +1,135 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Overlay;
use StreamGoals\Core\Money;
/**
* Pure, WordPress-free payload builders. Everything returned here is public-safe.
*/
final class Payloads {
public const ANON_NAME = 'Anonymous';
private const SYMBOLS = array( 'USD' => '$', 'EUR' => '€', 'GBP' => '£', 'JPY' => '¥', 'CAD' => 'CA$', 'AUD' => 'A$' );
public static function money( int $minor, string $currency ): string {
$m = new Money( max( 0, $minor ), strtoupper( $currency ) );
$amount = $m->toDecimalString();
[ $whole, $frac ] = array_pad( explode( '.', $amount, 2 ), 2, null );
$whole = preg_replace( '/\B(?=(\d{3})+(?!\d))/', ',', $whole );
$amount = null === $frac ? $whole : $whole . '.' . $frac;
$cur = strtoupper( $currency );
return isset( self::SYMBOLS[ $cur ] ) ? self::SYMBOLS[ $cur ] . $amount : $cur . ' ' . $amount;
}
public static function percent( int $raised, int $target ): int {
if ( $target <= 0 ) {
return 0;
}
return max( 0, min( 100, intdiv( max( 0, $raised ) * 100, $target ) ) );
}
public static function goal( ?array $goal, int $raised ): array {
if ( null === $goal ) {
return array( 'active' => false, 'title' => '', 'raised_minor' => 0, 'target_minor' => 0, 'percent' => 0,
'currency' => 'USD', 'raised_display' => '', 'target_display' => '' );
}
$cur = strtoupper( (string) ( $goal['currency'] ?? 'USD' ) );
$target = max( 0, (int) ( $goal['target_minor'] ?? 0 ) );
$raised = max( 0, $raised );
return array(
'active' => true,
'title' => (string) ( $goal['title'] ?? '' ),
'raised_minor' => $raised,
'target_minor' => $target,
'percent' => self::percent( $raised, $target ),
'currency' => $cur,
'raised_display' => self::money( $raised, $cur ),
'target_display' => self::money( $target, $cur ),
);
}
/**
* @param string|null $endsAt sg_state `timer_ends_at` (epoch seconds, or a UTC datetime string).
* @param string|null $pausedRemaining sg_state `paused_remaining` seconds; non-null means paused.
*/
public static function timer( ?string $endsAt, ?string $pausedRemaining, int $now ): array {
$ends = self::toEpoch( $endsAt );
if ( null !== $pausedRemaining && '' !== $pausedRemaining && is_numeric( $pausedRemaining ) ) {
$rem = max( 0, (int) $pausedRemaining );
return array( 'active' => true, 'paused' => true, 'ends_at' => $now + $rem, 'remaining_seconds' => $rem, 'server_now' => $now );
}
if ( null === $ends ) {
return array( 'active' => false, 'paused' => false, 'ends_at' => 0, 'remaining_seconds' => 0, 'server_now' => $now );
}
// remaining_seconds is only meaningful when paused; a running timer's value would change every second and defeat 304s.
return array( 'active' => true, 'paused' => false, 'ends_at' => $ends, 'remaining_seconds' => 0, 'server_now' => $now );
}
public static function counter( string $label, int $value ): array {
return array( 'label' => $label, 'value' => $value );
}
/**
* @param array<int,array<string,mixed>> $rows
* @param int|null $since Null means "first poll": no alerts, just a baseline last_id.
*/
public static function alerts( array $rows, ?int $since, int $limit = 10 ): array {
$safe = array();
foreach ( $rows as $r ) {
if ( 'completed' !== ( $r['status'] ?? '' ) || 'approved' !== ( $r['moderation'] ?? '' ) ) {
continue;
}
$safe[] = $r;
}
usort( $safe, static fn( $a, $b ) => (int) $a['id'] <=> (int) $b['id'] );
$lastId = $since ?? 0;
foreach ( $safe as $r ) {
$lastId = max( $lastId, (int) $r['id'] );
}
if ( null === $since ) {
return array( 'alerts' => array(), 'last_id' => $lastId );
}
$alerts = array();
foreach ( $safe as $r ) {
if ( (int) $r['id'] <= $since ) {
continue;
}
$cur = strtoupper( (string) ( $r['currency'] ?? 'USD' ) );
$anon = ! empty( $r['is_anonymous'] );
$name = trim( (string) ( $r['donor_name'] ?? '' ) );
$alerts[] = array(
'id' => (int) $r['id'],
'name' => ( $anon || '' === $name ) ? self::ANON_NAME : $name,
'amount_minor' => (int) $r['base_minor'],
'amount_display' => self::money( (int) $r['base_minor'], $cur ),
'currency' => $cur,
'message' => (string) ( $r['message'] ?? '' ),
);
}
$alerts = array_slice( $alerts, 0, max( 1, $limit ) );
if ( $alerts ) {
$lastId = max( $since, (int) end( $alerts )['id'] ); // don't skip rows beyond the limit
}
return array( 'alerts' => $alerts, 'last_id' => $lastId );
}
/** Strong ETag over the payload, ignoring the volatile server_now so unchanged data yields 304s. */
public static function etag( array $payload ): string {
unset( $payload['server_now'] );
return '"' . md5( (string) json_encode( $payload, JSON_UNESCAPED_UNICODE ) ) . '"';
}
private static function toEpoch( ?string $v ): ?int {
if ( null === $v || '' === $v ) {
return null;
}
if ( ctype_digit( $v ) ) {
return (int) $v;
}
$t = strtotime( $v . ' UTC' );
return false === $t ? null : $t;
}
}
+85
View File
@@ -0,0 +1,85 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Overlay;
use StreamGoals\Rest\OverlayController;
/** Serves the transparent OBS browser-source page at /streamgoals-overlay/{token}/{widget}/. */
final class Router {
public const RULES_VERSION = '1';
private const OPTION = 'sg_overlay_rules_version';
public static function register(): void {
add_action( 'init', array( self::class, 'add_rules' ) );
add_filter( 'query_vars', array( self::class, 'query_vars' ) );
add_action( 'template_redirect', array( self::class, 'render' ) );
}
public static function add_rules(): void {
add_rewrite_rule(
'^streamgoals-overlay/([A-Za-z0-9]{16,128})/(goal|timer|counter|alerts)/?$',
'index.php?sg_overlay_token=$matches[1]&sg_overlay_widget=$matches[2]',
'top'
);
}
public static function query_vars( array $vars ): array {
$vars[] = 'sg_overlay_token';
$vars[] = 'sg_overlay_widget';
return $vars;
}
/** True when rewrite rules must be flushed (first run or rule set changed). Call mark_flushed() after flushing. */
public static function flush_rules_needed(): bool {
return get_option( self::OPTION ) !== self::RULES_VERSION;
}
public static function mark_flushed(): void {
update_option( self::OPTION, self::RULES_VERSION, false );
}
public static function render(): void {
$token = get_query_var( 'sg_overlay_token' );
$widget = get_query_var( 'sg_overlay_widget' );
if ( '' === $token || '' === $widget ) {
return;
}
if ( ! is_string( $token ) || ! is_string( $widget ) || ! in_array( $widget, OverlayService::WIDGETS, true ) || ! OverlayController::verify_token( $token ) ) {
global $wp_query;
$wp_query->set_404();
status_header( 404 );
nocache_headers();
return;
}
// Only whitelisted, sanitized styling params ever reach the page.
$style = Style::fromQuery( is_array( $_GET ) ? wp_unslash( $_GET ) : array() ); // phpcs:ignore WordPress.Security.NonceVerification
$file = dirname( __DIR__, 2 ) . '/streamgoals-donate.php';
$asset = static fn( string $f ): string => esc_url( add_query_arg( 'v', (string) @filemtime( dirname( __DIR__, 2 ) . '/assets/overlay/' . $f ), plugins_url( 'assets/overlay/' . $f, $file ) ) );
$endpoint = rest_url( 'streamgoals/v1/overlay/' . rawurlencode( $token ) . '/' . $widget );
nocache_headers();
header( 'Content-Type: text/html; charset=utf-8' );
header( 'X-Robots-Tag: noindex, nofollow' );
header( 'Referrer-Policy: no-referrer' );
?>
<!doctype html>
<html lang="en" style="<?php echo esc_attr( Style::inline( $style['vars'] ) ); ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex,nofollow">
<title>StreamGoals overlay</title>
<link rel="stylesheet" href="<?php echo $asset( 'overlay.css' ); // phpcs:ignore WordPress.Security.EscapeOutput ?>">
</head>
<body class="sg-theme-<?php echo esc_attr( $style['theme'] ); ?> sg-w-<?php echo esc_attr( $widget ); ?>" data-widget="<?php echo esc_attr( $widget ); ?>" data-endpoint="<?php echo esc_url( $endpoint ); ?>" data-poll="2500">
<main id="sg-root" aria-live="polite"></main>
<script src="<?php echo $asset( 'overlay.js' ); // phpcs:ignore WordPress.Security.EscapeOutput ?>"></script>
</body>
</html>
<?php
exit;
}
}
+61
View File
@@ -0,0 +1,61 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Overlay;
/** Sanitizes owner-supplied URL styling params into a closed set of CSS custom properties. */
final class Style {
public const THEMES = array( 'dark', 'light', 'neon', 'minimal' );
private const FONTS = array(
'sans' => 'system-ui, -apple-system, "Segoe UI", Roboto, Arial, sans-serif',
'serif' => 'Georgia, "Times New Roman", serif',
'mono' => 'ui-monospace, "SFMono-Regular", Consolas, monospace',
'rounded' => 'ui-rounded, "Nunito", "Varela Round", system-ui, sans-serif',
'condensed' => '"Arial Narrow", "Roboto Condensed", Impact, sans-serif',
);
private const COLOR_KEYS = array( 'color' => 'fg', 'accent' => 'accent', 'accent2' => 'accent2', 'track' => 'track', 'bg' => 'bg' );
public static function color( mixed $v ): ?string {
if ( ! is_string( $v ) ) {
return null;
}
$v = ltrim( trim( $v ), '#' );
return preg_match( '/^([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/', $v ) ? '#' . strtolower( $v ) : null;
}
/** @return array{theme:string,vars:array<string,string>} */
public static function fromQuery( array $q ): array {
$theme = isset( $q['theme'] ) && is_string( $q['theme'] ) && in_array( strtolower( $q['theme'] ), self::THEMES, true )
? strtolower( $q['theme'] ) : 'dark';
$vars = array();
foreach ( self::COLOR_KEYS as $param => $var ) {
$c = self::color( $q[ $param ] ?? null );
if ( null !== $c ) {
$vars[ '--sg-' . $var ] = $c;
}
}
if ( isset( $q['font'] ) && is_string( $q['font'] ) ) {
$f = trim( $q['font'] );
if ( isset( self::FONTS[ strtolower( $f ) ] ) ) {
$vars['--sg-font'] = self::FONTS[ strtolower( $f ) ];
} elseif ( preg_match( '/^[A-Za-z0-9][A-Za-z0-9 \-]{0,39}$/', $f ) ) {
$vars['--sg-font'] = '"' . $f . '", ' . self::FONTS['sans']; // locally installed font name
}
}
if ( isset( $q['scale'] ) && is_scalar( $q['scale'] ) && is_numeric( $q['scale'] ) ) {
$vars['--sg-scale'] = (string) round( max( 0.5, min( 3.0, (float) $q['scale'] ) ), 2 );
}
return array( 'theme' => $theme, 'vars' => $vars );
}
public static function inline( array $vars ): string {
$out = '';
foreach ( $vars as $k => $v ) {
$out .= $k . ':' . $v . ';';
}
return $out;
}
}
+80
View File
@@ -0,0 +1,80 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Overlay;
/** $wpdb adapter reading sg_goals, sg_donations, sg_state, sg_rules directly. */
final class WpdbDataSource implements OverlayDataSource {
private function t( string $name ): string {
global $wpdb;
return $wpdb->prefix . 'sg_' . $name;
}
public function activeGoal(): ?array {
global $wpdb;
$row = $wpdb->get_row( "SELECT * FROM {$this->t('goals')} WHERE status = 'active' ORDER BY id DESC LIMIT 1", ARRAY_A );
return $row ?: null;
}
public function raisedMinor( array $goal ): int {
global $wpdb;
$col = ! empty( $goal['counts_fees'] ) ? 'total_minor' : 'base_minor';
$sum = $wpdb->get_var( $wpdb->prepare(
"SELECT COALESCE(SUM($col),0) FROM {$this->t('donations')} WHERE goal_id = %d AND status = 'completed'",
(int) $goal['id']
) );
return (int) $sum;
}
public function stateValue( int $goalId, string $key ): ?string {
global $wpdb;
$v = $wpdb->get_var( $wpdb->prepare( "SELECT svalue FROM {$this->t('state')} WHERE goal_id = %d AND skey = %s", $goalId, $key ) );
return null === $v ? null : (string) $v;
}
public function counter( int $goalId ): array {
global $wpdb;
$rows = $wpdb->get_results( $wpdb->prepare(
"SELECT skey, svalue FROM {$this->t('state')} WHERE goal_id = %d AND skey LIKE %s",
$goalId,
$wpdb->esc_like( 'counter' ) . '%'
), ARRAY_A );
$total = 0;
foreach ( (array) $rows as $r ) {
if ( preg_match( '/carry|remainder/i', (string) $r['skey'] ) || ! is_numeric( $r['svalue'] ) ) {
continue;
}
$total += (int) $r['svalue'];
}
$label = '';
$rules = $wpdb->get_col( $wpdb->prepare(
"SELECT config FROM {$this->t('rules')} WHERE goal_id = %d AND type = 'counter' AND enabled = 1 ORDER BY sort, id",
$goalId
) );
foreach ( (array) $rules as $cfg ) {
$d = json_decode( (string) $cfg, true );
if ( is_array( $d ) && ! empty( $d['label'] ) ) {
$label = (string) $d['label'];
break;
}
}
return array( 'label' => $label, 'value' => $total );
}
public function donations( ?int $sinceId, int $limit ): array {
global $wpdb;
$cols = 'id, base_minor, currency, donor_name, is_anonymous, message, status, moderation';
$where = "status = 'completed' AND moderation = 'approved'";
if ( null === $sinceId ) {
$rows = $wpdb->get_results( "SELECT $cols FROM {$this->t('donations')} WHERE $where ORDER BY id DESC LIMIT 1", ARRAY_A );
} else {
$rows = $wpdb->get_results( $wpdb->prepare(
"SELECT $cols FROM {$this->t('donations')} WHERE $where AND id > %d ORDER BY id ASC LIMIT %d",
$sinceId,
$limit
), ARRAY_A );
}
return (array) $rows;
}
}
+68
View File
@@ -0,0 +1,68 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Rest;
use StreamGoals\Core\Settings;
use StreamGoals\Overlay\OverlayService;
use StreamGoals\Overlay\Payloads;
use StreamGoals\Overlay\Router;
use StreamGoals\Overlay\WpdbDataSource;
/** GET streamgoals/v1/overlay/{token}/{widget} — public-safe, ETag'd JSON for OBS polling. */
final class OverlayController {
public static function register(): void {
add_action( 'rest_api_init', array( self::class, 'routes' ) );
Router::register();
}
public static function routes(): void {
register_rest_route( 'streamgoals/v1', '/overlay/(?P<token>[A-Za-z0-9]{16,128})/(?P<widget>goal|timer|counter|alerts)', array(
'methods' => 'GET',
'callback' => array( self::class, 'handle' ),
'permission_callback' => '__return_true', // capability is the unguessable token, checked in handle()
'args' => array(
'since' => array( 'type' => 'integer', 'minimum' => 0, 'sanitize_callback' => 'absint' ),
),
) );
}
/** Lazily generates the token (32 hex chars) on first use. */
public static function token(): string {
$token = (string) Settings::get( 'overlay_token', '' );
if ( strlen( $token ) < 32 ) {
$token = bin2hex( random_bytes( 16 ) );
Settings::update( array( 'overlay_token' => $token ) );
}
return $token;
}
public static function verify_token( string $given ): bool {
return hash_equals( self::token(), $given );
}
public static function handle( \WP_REST_Request $req ): \WP_REST_Response|\WP_Error {
if ( ! self::verify_token( (string) $req['token'] ) ) {
return new \WP_Error( 'sg_not_found', 'Not found.', array( 'status' => 404 ) );
}
$since = $req->has_param( 'since' ) && '' !== (string) $req->get_param( 'since' ) ? absint( $req->get_param( 'since' ) ) : null;
$payload = ( new OverlayService( new WpdbDataSource() ) )->payload( (string) $req['widget'], time(), $since );
if ( null === $payload ) {
return new \WP_Error( 'sg_not_found', 'Not found.', array( 'status' => 404 ) );
}
$etag = Payloads::etag( $payload );
$headers = array( 'ETag' => $etag, 'Cache-Control' => 'private, max-age=1, must-revalidate', 'X-Robots-Tag' => 'noindex' );
$inm = (string) $req->get_header( 'if_none_match' );
if ( '' !== $inm && in_array( $etag, array_map( 'trim', explode( ',', str_replace( 'W/', '', $inm ) ) ), true ) ) {
$res = new \WP_REST_Response( null, 304 );
} else {
$res = new \WP_REST_Response( $payload, 200 );
}
foreach ( $headers as $k => $v ) {
$res->header( $k, $v );
}
return $res;
}
}
+126
View File
@@ -0,0 +1,126 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Overlay\OverlayDataSource;
use StreamGoals\Overlay\OverlayService;
use StreamGoals\Overlay\Payloads;
use StreamGoals\Overlay\Style;
final class OverlayPayloadsTest extends TestCase {
private function don( int $id, array $o = array() ): array {
return array_merge( array( 'id' => $id, 'base_minor' => 500, 'currency' => 'USD', 'donor_name' => 'Alice Real',
'is_anonymous' => 0, 'message' => 'hi', 'status' => 'completed', 'moderation' => 'approved' ), $o );
}
public function test_percent_clamped(): void {
$this->assertSame( 100, Payloads::percent( 5000, 1000 ) );
$this->assertSame( 0, Payloads::percent( -5, 1000 ) );
$this->assertSame( 0, Payloads::percent( 100, 0 ) );
$this->assertSame( 33, Payloads::percent( 1, 3 ) );
$g = Payloads::goal( array( 'title' => 'T', 'target_minor' => 1000, 'currency' => 'USD' ), 123456 );
$this->assertSame( 100, $g['percent'] );
$this->assertSame( '$1,234.56', $g['raised_display'] );
}
public function test_money_zero_decimal_and_unknown_currency(): void {
$this->assertSame( '¥1,500', Payloads::money( 1500, 'JPY' ) );
$this->assertSame( 'CHF 10.00', Payloads::money( 1000, 'CHF' ) );
}
public function test_goal_none(): void {
$this->assertFalse( Payloads::goal( null, 0 )['active'] );
}
public function test_timer_running_and_paused(): void {
$t = Payloads::timer( '1000', null, 940 );
$this->assertSame( array( 1000, 940, 0, false ), array( $t['ends_at'], $t['server_now'], $t['remaining_seconds'], $t['paused'] ) );
$p = Payloads::timer( '1000', '300', 940 );
$this->assertTrue( $p['paused'] );
$this->assertSame( 300, $p['remaining_seconds'] );
$this->assertFalse( Payloads::timer( null, null, 940 )['active'] );
$this->assertSame( 0, Payloads::timer( '2024-01-01 00:00:00', null, 5 )['ends_at'] - 1704067200 );
}
public function test_counter(): void {
$this->assertSame( array( 'label' => 'Pies', 'value' => 3 ), Payloads::counter( 'Pies', 3 ) );
}
public function test_alerts_mask_anonymous_and_hide_unapproved(): void {
$rows = array(
$this->don( 1 ),
$this->don( 2, array( 'is_anonymous' => 1, 'donor_name' => 'Secret Sam' ) ),
$this->don( 3, array( 'moderation' => 'pending', 'donor_name' => 'Pending Pat' ) ),
$this->don( 4, array( 'moderation' => 'rejected' ) ),
$this->don( 5, array( 'status' => 'refunded' ) ),
$this->don( 6, array( 'donor_name' => ' ' ) ),
);
$out = Payloads::alerts( $rows, 0 );
$json = json_encode( $out );
$this->assertStringNotContainsString( 'Secret Sam', $json );
$this->assertStringNotContainsString( 'Pending Pat', $json );
$this->assertSame( array( 1, 2, 6 ), array_column( $out['alerts'], 'id' ) );
$this->assertSame( 'Anonymous', $out['alerts'][1]['name'] );
$this->assertSame( 'Anonymous', $out['alerts'][2]['name'] );
$this->assertSame( 'Alice Real', $out['alerts'][0]['name'] );
$this->assertSame( '$5.00', $out['alerts'][0]['amount_display'] );
$this->assertArrayNotHasKey( 'donor_name', $out['alerts'][0] );
}
public function test_alerts_since_filter_and_baseline(): void {
$rows = array( $this->don( 7 ), $this->don( 8 ), $this->don( 9, array( 'moderation' => 'pending' ) ) );
$out = Payloads::alerts( $rows, 7 );
$this->assertSame( array( 8 ), array_column( $out['alerts'], 'id' ) );
$this->assertSame( 8, $out['last_id'] );
$base = Payloads::alerts( $rows, null );
$this->assertSame( array(), $base['alerts'] );
$this->assertSame( 8, $base['last_id'] );
$this->assertSame( 20, Payloads::alerts( array(), 20 )['last_id'] );
}
public function test_alerts_limit_does_not_skip_rows(): void {
$rows = array( $this->don( 1 ), $this->don( 2 ), $this->don( 3 ) );
$out = Payloads::alerts( $rows, 0, 2 );
$this->assertSame( 2, $out['last_id'] );
}
public function test_etag_stable_ignores_server_now_and_changes_with_data(): void {
$a = Payloads::timer( '1000', null, 100 );
$b = Payloads::timer( '1000', null, 101 );
$this->assertSame( Payloads::etag( $a ), Payloads::etag( $b ) );
$this->assertNotSame( Payloads::etag( $a ), Payloads::etag( Payloads::timer( '1060', null, 101 ) ) );
$g = Payloads::goal( array( 'title' => 'T', 'target_minor' => 100, 'currency' => 'USD' ), 10 );
$this->assertSame( Payloads::etag( $g ), Payloads::etag( $g ) );
}
public function test_style_sanitizes(): void {
$s = Style::fromQuery( array( 'theme' => 'bogus', 'accent' => '#FF00AA', 'color' => 'red;}</style>', 'bg' => '11223344',
'font' => 'x;}body{', 'scale' => '99' ) );
$this->assertSame( 'dark', $s['theme'] );
$this->assertSame( array( '--sg-accent' => '#ff00aa', '--sg-bg' => '#11223344', '--sg-scale' => '3' ), $s['vars'] );
$f = Style::fromQuery( array( 'font' => 'Comic Neue', 'theme' => 'NEON' ) );
$this->assertSame( 'neon', $f['theme'] );
$this->assertStringStartsWith( '"Comic Neue", ', $f['vars']['--sg-font'] );
$this->assertArrayHasKey( '--sg-font', Style::fromQuery( array( 'font' => 'mono' ) )['vars'] );
$this->assertSame( array(), Style::fromQuery( array( 'accent' => array( 'x' ) ) )['vars'] );
}
public function test_service_routes_widgets(): void {
$src = new class implements OverlayDataSource {
public function activeGoal(): ?array { return array( 'id' => 1, 'title' => 'Goal', 'target_minor' => 1000, 'currency' => 'USD' ); }
public function raisedMinor( array $goal ): int { return 250; }
public function stateValue( int $goalId, string $key ): ?string { return 'timer_ends_at' === $key ? '2000' : null; }
public function counter( int $goalId ): array { return array( 'label' => 'Pies', 'value' => 4 ); }
public function donations( ?int $sinceId, int $limit ): array { return array( array( 'id' => 3, 'base_minor' => 100, 'currency' => 'USD', 'donor_name' => 'Z', 'is_anonymous' => 1, 'message' => '', 'status' => 'completed', 'moderation' => 'approved' ) ); }
};
$svc = new OverlayService( $src );
$this->assertSame( 25, $svc->payload( 'goal', 1500 )['percent'] );
$this->assertSame( 2000, $svc->payload( 'timer', 1500 )['ends_at'] );
$this->assertSame( 4, $svc->payload( 'counter', 1 )['value'] );
$this->assertSame( 'Anonymous', $svc->payload( 'alerts', 1, 0 )['alerts'][0]['name'] );
$this->assertNull( $svc->payload( 'nope', 1 ) );
}
}