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

+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;
}
}