Overlays refresh themselves after updates; media URLs versioned; frameless (transparent) alerts
- Overlay\Build id (plugin version + admin epoch) in X-SG-Build; overlay.js reloads once on mismatch (loop-guarded); 'Refresh all overlays now' - Media URLs carry ?v=<mtime> - Alert option 'Frameless' (schema v5): no box so transparent PNG/GIF/WebP and VP9-alpha WebM show through; admin preview with checkerboard and ffmpeg help Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9249b80cb6
commit
afa768fa42
21 files changed
+287
-16
No files matched your search
@@ -79,6 +79,19 @@ server sees.
|
||||
- **Refunds and chargebacks are not tracked.** If you refund someone in PayPal, goal totals, timers and
|
||||
counters are not adjusted.
|
||||
|
||||
## Transparent alerts
|
||||
In StreamGoals > Alerts, tick **Frameless** on an alert to drop the dark box, border and glow so only your picture or
|
||||
video shows. Transparency works with PNG, GIF and WebP pictures that have an alpha channel and with WebM (VP8/VP9)
|
||||
videos made with alpha; MP4 (H.264) can never be transparent. To make a WebM with alpha:
|
||||
`ffmpeg -i input.mov -c:v libvpx-vp9 -pix_fmt yuva420p -b:v 0 -crf 30 output.webm`. The name and bonus lines still
|
||||
show under the media, outlined so they stay readable. The alert preview has a checkerboard/sample-scene backdrop.
|
||||
|
||||
## Overlays update themselves
|
||||
An open OBS Browser Source never reloads on its own. Every overlay response now carries a build id (plugin version
|
||||
plus a counter); when it differs from the one the page was loaded with, the overlay reloads itself once. Updating the
|
||||
plugin does this automatically, and StreamGoals > Overlays > "Refresh all overlays now" does it on demand. Alert media
|
||||
URLs also carry `?v=<file modified time>`, so replacing a file with the same name is picked up.
|
||||
|
||||
## Updates
|
||||
New versions appear in WordPress automatically (Dashboard > Updates and the Plugins screen), checked against
|
||||
this repository's releases. The repository is public, so no token is needed. (If you run a private fork, paste an
|
||||
|
||||
@@ -21,3 +21,13 @@
|
||||
.sga-alert-media img,.sga-alert-media video{max-height:180px}
|
||||
.sga-media .button{min-height:40px}
|
||||
}
|
||||
|
||||
/* Frameless alerts: preview backdrops and card without the box */
|
||||
.sga-bg-light{background:repeating-conic-gradient(#e8e8ee 0 25%,#fff 0 50%) 0 0/20px 20px;color:#111}
|
||||
.sga-bg-scene{background:linear-gradient(135deg,#1e6f3c 0 33%,#c2410c 33% 66%,#1d4ed8 66%)}
|
||||
.sga-alert.sga-frameless{background:none;border:0;padding:0}
|
||||
.sga-frameless .sga-alert-head{text-shadow:0 0 3px #000,0 0 6px #000,0 1px 4px #000}
|
||||
.sga-bg-light .sga-frameless .sga-alert-head{text-shadow:0 0 3px #fff,0 0 6px #fff;color:#111}
|
||||
.sga-howto{margin-top:8px}
|
||||
.sga-howto pre{overflow-x:auto;max-width:100%;padding:8px;background:#f0f0f1}
|
||||
.sga-bg-pick{margin-left:12px}
|
||||
@@ -110,7 +110,8 @@
|
||||
var vals = { name: 'Alex', amount: money( amt || 500 ), reward: reward };
|
||||
var msg = render( form.elements.message.value, vals );
|
||||
|
||||
var card = el( 'div', 'sga-alert' );
|
||||
var frameless = !! ( visUrl && form.elements.frameless && form.elements.frameless.checked );
|
||||
var card = el( 'div', 'sga-alert' + ( frameless ? ' sga-frameless' : '' ) );
|
||||
var isVideo = /^video\//.test( visMime ), video = null;
|
||||
if ( visUrl ) {
|
||||
var box = el( 'div', 'sga-alert-media' );
|
||||
@@ -145,6 +146,10 @@
|
||||
timers.push( setTimeout( end, dur ) );
|
||||
}
|
||||
}
|
||||
/* Preview backdrop: dark / light checkerboard or a busy "scene" so transparency is visible. */
|
||||
var bgSel = document.getElementById( 'sga-bg' );
|
||||
function setBg() { stage.className = 'sga-stage' + ( bgSel && bgSel.value !== 'dark' ? ' sga-bg-' + bgSel.value : '' ); }
|
||||
if ( bgSel ) { bgSel.addEventListener( 'change', setBg ); }
|
||||
playBtn.addEventListener( 'click', play );
|
||||
stage.appendChild( el( 'span', 'sga-idle', 'Press "Play preview".' ) );
|
||||
}() );
|
||||
@@ -59,3 +59,13 @@ body.sg-offline #sg-root{opacity:.6}
|
||||
@keyframes sg-tier-pop{0%{transform:scale(1)}30%{transform:scale(1.06)}100%{transform:scale(1)}}
|
||||
@keyframes sg-tier-glow{0%,100%{box-shadow:0 0 0 transparent}50%{box-shadow:0 0 1em #f59e0b,0 0 2em var(--sg-accent2)}}
|
||||
@media (prefers-reduced-motion:reduce){.sg-card.sg-tier-up{animation:none;box-shadow:0 0 .8em #f59e0b}}
|
||||
|
||||
/* Frameless alerts (transparent PNG/GIF/WebP/WebM): no box, border or glow; media fits the window; text gets an outline. */
|
||||
.sg-alert.sg-frameless{background:none;border:0;box-shadow:none;padding:0;max-height:100%;display:flex;flex-direction:column;align-items:center;justify-content:flex-end;min-height:0}
|
||||
.sg-alert.sg-frameless.sg-bonus{border:0;animation:sg-in .6s cubic-bezier(.22,1,.36,1) both}
|
||||
.sg-alert.sg-frameless.sg-bonus.sg-out,.sg-alert.sg-frameless.sg-out{animation:sg-out .5s ease-in both}
|
||||
.sg-frameless .sg-alert-media{flex:0 1 auto;min-height:0;max-width:100%;max-height:100%;margin-bottom:.2em;overflow:hidden}
|
||||
.sg-frameless .sg-alert-media img,.sg-frameless .sg-alert-media video{max-width:100%;max-height:calc(100vh - 9em);width:auto;height:auto;object-fit:contain;border-radius:0;background:transparent}
|
||||
.sg-frameless .sg-alert-head,.sg-frameless .sg-alert-msg,.sg-frameless .sg-bonus-line{text-shadow:0 0 .06em #000,0 0 .12em #000,0 0 .2em #000,0 .04em .3em #000,.04em 0 0 #000,-.04em 0 0 #000,0 .04em 0 #000,0 -.04em 0 #000}
|
||||
.sg-theme-light .sg-frameless .sg-alert-head,.sg-theme-light .sg-frameless .sg-alert-msg{text-shadow:0 0 .06em #fff,0 0 .12em #fff,0 0 .2em #fff,.04em 0 0 #fff,-.04em 0 0 #fff,0 .04em 0 #fff,0 -.04em 0 #fff}
|
||||
@media (prefers-reduced-motion:reduce){.sg-alert.sg-frameless,.sg-alert.sg-frameless.sg-out,.sg-alert.sg-frameless.sg-bonus,.sg-alert.sg-frameless.sg-bonus.sg-out{animation:none;box-shadow:none}}
|
||||
@@ -5,6 +5,7 @@
|
||||
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 build = body.getAttribute('data-build') || '';
|
||||
var etag = null, failures = 0, skew = 0, timerState = null;
|
||||
var queue = [], showing = false;
|
||||
|
||||
@@ -151,7 +152,7 @@
|
||||
if (!v && !s && !msg) return null;
|
||||
var vol = Number(m.volume); if (!isFinite(vol)) vol = 80;
|
||||
var dur = Number(m.duration_ms); if (!isFinite(dur) || dur <= 0) dur = DEFAULT_HOLD;
|
||||
return { visual: v, sound: s, volume: Math.max(0, Math.min(100, vol)) / 100, duration: Math.max(1000, Math.min(60000, dur)), message: msg };
|
||||
return { frameless: !!(v && m.frameless === true), visual: v, sound: s, volume: Math.max(0, Math.min(100, vol)) / 100, duration: Math.max(1000, Math.min(60000, dur)), message: msg };
|
||||
}
|
||||
// Loads visual + sound before the card appears (no flash of an empty frame). Anything that fails or takes
|
||||
// longer than MEDIA_TIMEOUT is dropped, so the alert falls back to text and the queue never stalls.
|
||||
@@ -212,6 +213,7 @@
|
||||
box.appendChild(vis);
|
||||
card.appendChild(box);
|
||||
card.classList.add('sg-has-media');
|
||||
if (m && m.frameless) card.classList.add('sg-frameless');
|
||||
}
|
||||
if (m && m.message) {
|
||||
head.textContent = m.message;
|
||||
@@ -364,6 +366,33 @@
|
||||
var delay = failures ? Math.min(15000, poll * Math.pow(2, Math.min(failures, 3))) : poll;
|
||||
setTimeout(tick, delay);
|
||||
}
|
||||
// Self-refresh: every overlay response carries the current build id (plugin version + admin epoch) in X-SG-Build.
|
||||
// A different value than the one this page was rendered with means the page is stale (OBS never reloads a
|
||||
// running source after an update), so reload once. Guard: at most one reload per build per 30 s, remembered in
|
||||
// sessionStorage, or in a module flag when storage is blocked. Applies to 200 and 304 responses alike.
|
||||
var RELOAD_GUARD_MS = 30000, reloadTried = {};
|
||||
// sessionStorage first; if it is blocked, window.name (which also survives a reload) carries the marker, so a
|
||||
// blocked-storage source cannot reload in a loop. The module-level reloadTried only covers one page life.
|
||||
function readGuard(key) {
|
||||
try { return JSON.parse(sessionStorage.getItem(key) || 'null'); } catch (e) { /* fall through */ }
|
||||
try { var m = /(?:^|;)sg_reload=([^;]*)/.exec(window.name || ''); return m ? JSON.parse(decodeURIComponent(m[1])) : null; } catch (e2) { return null; }
|
||||
}
|
||||
function writeGuard(key, v) {
|
||||
try { sessionStorage.setItem(key, JSON.stringify(v)); return; } catch (e) { /* fall through */ }
|
||||
try { window.name = (window.name || '').replace(/(?:^|;)sg_reload=[^;]*/, '') + ';sg_reload=' + encodeURIComponent(JSON.stringify(v)); } catch (e2) { /* module flag only */ }
|
||||
}
|
||||
function checkBuild(r) {
|
||||
var b = null;
|
||||
try { b = r.headers.get('X-SG-Build'); } catch (e) { return false; }
|
||||
if (!b || !build || b === build) return false;
|
||||
var now = Date.now(), key = 'sg_overlay_reload', last = readGuard(key);
|
||||
var seen = last && last.b === b ? Number(last.t) : 0;
|
||||
if (reloadTried[b] && reloadTried[b] > seen) seen = reloadTried[b];
|
||||
if (seen && now - seen < RELOAD_GUARD_MS && now >= seen) return false;
|
||||
reloadTried[b] = now;
|
||||
writeGuard(key, { b: b, t: now });
|
||||
try { location.reload(); return true; } catch (e3) { return false; }
|
||||
}
|
||||
function tick() {
|
||||
var ctrl = typeof AbortController === 'function' ? new AbortController() : null;
|
||||
var to = ctrl ? setTimeout(function () { ctrl.abort(); }, 8000) : 0;
|
||||
@@ -372,6 +401,7 @@
|
||||
fetch(url(), { headers: headers, cache: 'no-store', signal: ctrl ? ctrl.signal : undefined })
|
||||
.then(function (r) {
|
||||
clearTimeout(to);
|
||||
if (checkBuild(r)) return null;
|
||||
if (r.status === 304) return null;
|
||||
if (!r.ok) throw new Error('http ' + r.status);
|
||||
var et = r.headers.get('ETag');
|
||||
|
||||
@@ -40,6 +40,7 @@ final class Admin {
|
||||
'sg_test_donation' => array( OverlaysPage::class, 'handleTestDonation' ),
|
||||
'sg_delete_tests' => array( OverlaysPage::class, 'handleDeleteTests' ),
|
||||
'sg_regen_token' => array( OverlaysPage::class, 'handleRegenerate' ),
|
||||
'sg_refresh_overlays' => array( OverlaysPage::class, 'handleRefreshAll' ),
|
||||
'sg_settings_save' => array( SettingsPage::class, 'handleSave' ),
|
||||
);
|
||||
|
||||
|
||||
@@ -178,6 +178,9 @@ final class AlertsPage {
|
||||
echo '</select><p class="description">A reward alert beats an amount alert. Only rewards that are turned on can be picked.</p></td></tr>';
|
||||
self::mediaField( 'visual_id', 'Picture, GIF or video', 'visual', (int) $val( 'visual_id', 0 ), 'PNG, JPEG, GIF, WebP, MP4 or WebM. Optional. Under 25 MB works best; big videos can slow OBS down.' );
|
||||
self::mediaField( 'sound_id', 'Sound', 'sound', (int) $val( 'sound_id', 0 ), 'MP3, OGG or WAV. Optional. If you also pick a video, the video is muted and this sound plays instead.' );
|
||||
echo '<tr><th scope="row">Frameless</th><td><label><input type="checkbox" name="frameless" value="1" id="sga_frameless"' . checked( ! empty( $d['frameless'] ), true, false ) . '> Show the picture/video without the alert box (for transparent PNG, GIF, WebP or WebM files)</label>';
|
||||
echo '<p class="description">Normally the alert sits in a dark rounded box. Tick this to remove the box, border and glow so only your picture or video shows, with the see-through parts showing your stream underneath. Transparency works with <strong>PNG, GIF and WebP</strong> pictures and <strong>WebM</strong> videos made with transparency. <strong>MP4 never supports transparency</strong>, so an MP4 always shows a solid picture. The name and bonus lines still appear under the media, with an outline so they stay readable on any scene. Only applies when you picked a picture or video.</p>';
|
||||
echo '<details class="sga-howto"><summary>How do I make a transparent video?</summary><p>Export your animation with an alpha channel (a "transparent background"), then convert it to WebM with <a href="https://ffmpeg.org/" target="_blank" rel="noopener noreferrer">ffmpeg</a>:</p><pre><code>ffmpeg -i input.mov -c:v libvpx-vp9 -pix_fmt yuva420p -b:v 0 -crf 30 -an output.webm</code></pre><p>Replace <code>input.mov</code> with your file (a ProRes 4444 .mov or a PNG sequence both work). Use <code>-an</code> to drop audio (pick a separate sound above instead) or remove it to keep the clip\'s own sound. Then upload <code>output.webm</code> to your Media Library. Use the preview below to check it: the checkerboard shows through the transparent parts.</p></details></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sga_volume">Volume</label></th><td><input type="range" min="0" max="100" id="sga_volume" name="volume" value="' . (int) $val( 'volume', 80 ) . '"> <output id="sga_volume_out">' . (int) $val( 'volume', 80 ) . '</output>%</td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sga_duration">How long a picture stays</label></th><td><input type="number" min="1" max="60" step="1" id="sga_duration" name="duration" class="small-text" value="' . esc_attr( (string) (int) round( (int) $val( 'duration_ms', 6000 ) / 1000 ) ) . '"> seconds<p class="description">1 to 60. Videos play to the end instead, for at most 30 seconds.</p></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sga_message">Message</label></th><td><input type="text" maxlength="255" id="sga_message" name="message" class="large-text" value="' . esc_attr( (string) $val( 'message' ) ) . '"><p class="description">Optional. Use {name}, {amount} and {reward}, for example "{name} just sent {amount}!". Leave empty for the normal text ("Name donated $5.00").</p></td></tr>';
|
||||
@@ -186,7 +189,7 @@ final class AlertsPage {
|
||||
|
||||
echo '<div class="sg-card"><h3>Preview</h3>';
|
||||
echo '<p class="description">This is how the alert will look on stream. Press the button to play it (browsers only allow sound after you click).</p>';
|
||||
echo '<p><button type="button" class="button" id="sga-play">Play preview</button></p>';
|
||||
echo '<p><button type="button" class="button" id="sga-play">Play preview</button> <label class="sga-bg-pick">Preview background <select id="sga-bg"><option value="dark">Dark checkerboard</option><option value="light">Light checkerboard</option><option value="scene">Sample scene</option></select></label></p>';
|
||||
echo '<div id="sga-stage" class="sga-stage" aria-live="polite"></div>';
|
||||
echo '<script type="application/json" id="sga-data">' . wp_json_encode( $data, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) . '</script></div>';
|
||||
echo '<p><button class="button button-primary">' . ( $d ? 'Save alert' : 'Add alert' ) . '</button> <a class="button" href="' . esc_url( self::url() ) . '">Cancel</a></p></form>';
|
||||
|
||||
@@ -4,6 +4,7 @@ declare( strict_types=1 );
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Core\Settings;
|
||||
use StreamGoals\Overlay\Build;
|
||||
use StreamGoals\Overlay\Style;
|
||||
use StreamGoals\Rest\OverlayController;
|
||||
|
||||
@@ -73,6 +74,11 @@ final class OverlaysPage {
|
||||
self::urlList( true );
|
||||
echo '</div>';
|
||||
|
||||
echo '<div class="sg-card"><h2>Refresh overlays</h2>';
|
||||
Admin::form( 'sg_refresh_overlays', array(), 'sg-inline' );
|
||||
echo '<button type="submit" class="button">Refresh all overlays now</button></form>';
|
||||
echo '<p class="description">Reloads every open OBS source. Done automatically after a plugin update.</p></div>';
|
||||
|
||||
echo '<div class="sg-card"><h2>Send a test donation</h2>';
|
||||
echo '<p>Shows a fake donation on the <strong>Donation alerts</strong> overlay so you can check your OBS setup. Open the alerts preview above (or have OBS running) first, then press the button; the alert appears within a few seconds.</p>';
|
||||
echo '<p class="description"><strong>How tests are kept out of your numbers:</strong> test donations are not attached to any goal, so they never count towards raised totals, timers or counters. They are excluded from the CSV export, and marked <em>TEST</em> in the Donations list. Test donations are kept in the database until you delete them below.</p>';
|
||||
@@ -105,6 +111,12 @@ final class OverlaysPage {
|
||||
Admin::redirect( Admin::url( 'streamgoals-overlays' ), 'success', $n . ' test donation(s) deleted.' );
|
||||
}
|
||||
|
||||
public static function handleRefreshAll(): void {
|
||||
Admin::guard( 'sg_refresh_overlays' );
|
||||
Build::bump();
|
||||
Admin::redirect( Admin::url( 'streamgoals-overlays' ), 'success', 'All open overlays will reload within a few seconds.' );
|
||||
}
|
||||
|
||||
public static function handleRegenerate(): void {
|
||||
Admin::guard( 'sg_regen_token' );
|
||||
Settings::update( array( 'overlay_token' => bin2hex( random_bytes( 16 ) ) ) );
|
||||
|
||||
@@ -13,8 +13,8 @@ final class AlertMedia {
|
||||
* @param array<string,mixed> $row Donation row (goal_id, base_minor).
|
||||
* @param array<int,array<string,mixed>> $defs Raw alert definitions.
|
||||
* @param array<int,array{action_id:int,amount_minor:int,title:string}> $triggered Rewards this donation triggered.
|
||||
* @param callable(int):?array{url:string,mime:string} $attachment
|
||||
* @return array{visual:?array{type:string,url:string},sound:?array{url:string},volume:int,duration_ms:int,message:?string}|null
|
||||
* @param callable(int):?array{url:string,mime:string,v?:int,modified?:string} $attachment
|
||||
* @return array{visual:?array{type:string,url:string},sound:?array{url:string},volume:int,duration_ms:int,message:?string,frameless:bool}|null
|
||||
*/
|
||||
public static function build( array $row, string $name, string $amountDisplay, array $defs, array $triggered, callable $attachment ): ?array {
|
||||
if ( ! $defs ) {
|
||||
@@ -36,13 +36,15 @@ final class AlertMedia {
|
||||
|
||||
/** @return array<string,mixed>|null */
|
||||
public static function fromDef( array $def, string $name, string $amountDisplay, array $triggered, callable $attachment ): ?array {
|
||||
$visual = null;
|
||||
$visual = null;
|
||||
$frameless = false;
|
||||
$vid = (int) ( $def['visual_id'] ?? 0 );
|
||||
if ( $vid > 0 ) {
|
||||
$a = self::lookup( $attachment, $vid );
|
||||
$type = $a ? Media::visualType( $a['mime'] ) : null;
|
||||
if ( $a && $type ) {
|
||||
$visual = array( 'type' => $type, 'url' => $a['url'] );
|
||||
$frameless = ! empty( $def['frameless'] );
|
||||
}
|
||||
}
|
||||
$sound = null;
|
||||
@@ -81,6 +83,7 @@ final class AlertMedia {
|
||||
'volume' => Media::clampVolume( $def['volume'] ?? 80 ),
|
||||
'duration_ms' => $duration,
|
||||
'message' => '' === $msg ? null : $msg,
|
||||
'frameless' => $frameless,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -95,6 +98,11 @@ final class AlertMedia {
|
||||
return null;
|
||||
}
|
||||
$url = Media::safeUrl( $a['url'] ?? null );
|
||||
return null === $url ? null : array( 'url' => $url, 'mime' => (string) $a['mime'] );
|
||||
if ( null === $url ) {
|
||||
return null;
|
||||
}
|
||||
// Cache-bust suffix from server-side data only (file mtime / post_modified_gmt supplied by the lookup).
|
||||
$versioned = Media::safeUrl( Media::withVersion( $url, (int) ( $a['v'] ?? 0 ), isset( $a['modified'] ) && is_string( $a['modified'] ) ? $a['modified'] : null ) );
|
||||
return array( 'url' => $versioned ?? $url, 'mime' => (string) $a['mime'] );
|
||||
}
|
||||
}
|
||||
@@ -99,6 +99,7 @@ final class DefInput {
|
||||
if ( null === $sort ) {
|
||||
return $fail( 'The sort order must be a whole number from 0 to 99999.' );
|
||||
}
|
||||
$frameless = self::checkbox( $post['frameless'] ?? null ) ? 1 : 0;
|
||||
return array(
|
||||
'data' => array(
|
||||
'goal_id' => $goal,
|
||||
@@ -113,12 +114,18 @@ final class DefInput {
|
||||
'duration_ms' => $dur,
|
||||
'message' => $message,
|
||||
'sort' => $sort,
|
||||
'frameless' => $frameless,
|
||||
),
|
||||
'error' => null,
|
||||
'warnings' => $warnings,
|
||||
);
|
||||
}
|
||||
|
||||
/** HTML checkbox: present with a truthy value = on; absent or anything odd = off. */
|
||||
public static function checkbox( mixed $v ): bool {
|
||||
return is_scalar( $v ) && in_array( strtolower( trim( (string) $v ) ), array( '1', 'on', 'true', 'yes' ), true );
|
||||
}
|
||||
|
||||
/** @param string[] $warnings */
|
||||
private static function sizeWarning( array $a, string $what, bool $video, array &$warnings ): void {
|
||||
if ( (int) ( $a['size'] ?? 0 ) > Media::WARN_BYTES ) {
|
||||
|
||||
@@ -31,6 +31,7 @@ final class DefRepository {
|
||||
'volume' => (int) ( $r['volume'] ?? 80 ),
|
||||
'duration_ms' => (int) ( $r['duration_ms'] ?? 6000 ),
|
||||
'message' => (string) ( $r['message'] ?? '' ),
|
||||
'frameless' => (int) ( $r['frameless'] ?? 0 ) ? 1 : 0,
|
||||
'enabled' => (int) ( $r['enabled'] ?? 0 ),
|
||||
'sort' => (int) ( $r['sort'] ?? 0 ),
|
||||
'created_at' => (string) ( $r['created_at'] ?? '' ),
|
||||
@@ -57,13 +58,13 @@ final class DefRepository {
|
||||
|
||||
private const COLS = array(
|
||||
'goal_id' => '%d', 'trigger_type' => '%s', 'min_minor' => '%d', 'action_id' => '%d', 'title' => '%s', 'visual_id' => '%d',
|
||||
'visual_type' => '%s', 'sound_id' => '%d', 'volume' => '%d', 'duration_ms' => '%d', 'message' => '%s', 'sort' => '%d',
|
||||
'visual_type' => '%s', 'sound_id' => '%d', 'volume' => '%d', 'duration_ms' => '%d', 'message' => '%s', 'sort' => '%d', 'frameless' => '%d',
|
||||
);
|
||||
|
||||
public function create( array $d ): int {
|
||||
$row = array();
|
||||
foreach ( self::COLS as $k => $f ) {
|
||||
$row[ $k ] = $d[ $k ];
|
||||
$row[ $k ] = $d[ $k ] ?? ( '%d' === $f ? 0 : '' );
|
||||
}
|
||||
$row['enabled'] = 1;
|
||||
$row['created_at'] = gmdate( 'Y-m-d H:i:s' );
|
||||
@@ -74,7 +75,7 @@ final class DefRepository {
|
||||
public function update( int $id, array $d ): void {
|
||||
$row = array();
|
||||
foreach ( self::COLS as $k => $f ) {
|
||||
$row[ $k ] = $d[ $k ];
|
||||
$row[ $k ] = $d[ $k ] ?? ( '%d' === $f ? 0 : '' );
|
||||
}
|
||||
$this->db->update( $this->t(), $row, array( 'id' => $id ), array_values( self::COLS ), array( '%d' ) );
|
||||
}
|
||||
|
||||
@@ -66,6 +66,24 @@ final class Media {
|
||||
return is_numeric( $v ) ? max( 0, min( 100, (int) $v ) ) : $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends ?v=<timestamp> so a replaced file with the same name is fetched again. The timestamp comes from the
|
||||
* server (file mtime, else the attachment's post_modified_gmt), never from input. Unknown time = URL unchanged.
|
||||
*/
|
||||
public static function withVersion( string $url, int $fileMtime, ?string $postModifiedGmt = null ): string {
|
||||
$v = $fileMtime;
|
||||
if ( $v <= 0 && null !== $postModifiedGmt && preg_match( '/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $postModifiedGmt ) ) {
|
||||
$t = strtotime( $postModifiedGmt . ' UTC' );
|
||||
$v = false === $t ? 0 : $t;
|
||||
}
|
||||
if ( $v <= 0 || str_contains( $url, '#' ) ) {
|
||||
return $url;
|
||||
}
|
||||
$base = preg_replace( '/([?&])v=[^&]*(&|$)/', '$1', $url ) ?? $url;
|
||||
$base = rtrim( $base, '?&' );
|
||||
return $base . ( str_contains( $base, '?' ) ? '&' : '?' ) . 'v=' . $v;
|
||||
}
|
||||
|
||||
/** Only plain http(s) URLs are ever handed to the overlay. */
|
||||
public static function safeUrl( mixed $url ): ?string {
|
||||
if ( ! is_string( $url ) || '' === $url || strlen( $url ) > 2000 || preg_match( '/[\x00-\x20\x7F"\'<>\\\\]/', $url ) ) {
|
||||
|
||||
@@ -8,7 +8,7 @@ namespace StreamGoals\Core;
|
||||
*/
|
||||
final class Installer {
|
||||
|
||||
public const DB_VERSION = '4';
|
||||
public const DB_VERSION = '5';
|
||||
|
||||
public static function activate(): void {
|
||||
self::install_schema();
|
||||
@@ -138,6 +138,7 @@ final class Installer {
|
||||
message VARCHAR(255) NOT NULL DEFAULT '',
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 1,
|
||||
sort INT NOT NULL DEFAULT 0,
|
||||
frameless TINYINT(1) NOT NULL DEFAULT 0,
|
||||
created_at DATETIME NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
KEY goal_enabled (goal_id,enabled)
|
||||
|
||||
@@ -20,7 +20,7 @@ interface AlertMediaSource {
|
||||
/**
|
||||
* Server-side attachment lookup (the only place media URLs come from). Null when it is gone.
|
||||
*
|
||||
* @return array{url:string,mime:string}|null
|
||||
* @return array{url:string,mime:string,v?:int,modified?:string}|null (v = file mtime, modified = post_modified_gmt; used only for the ?v= cache-bust suffix)
|
||||
*/
|
||||
public function attachment( int $id ): ?array;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Overlay;
|
||||
|
||||
/**
|
||||
* Overlay build id: plugin version + a manual "epoch". The overlay page embeds it, every overlay REST response
|
||||
* repeats it in a header, and a page that sees a different value reloads itself (OBS never does that on its own).
|
||||
*/
|
||||
final class Build {
|
||||
|
||||
public const HEADER = 'X-SG-Build';
|
||||
public const OPTION = 'sg_overlay_epoch';
|
||||
|
||||
/** Pure: the build id string for a version and epoch. Only [A-Za-z0-9._-] survive, so it is header- and attribute-safe. */
|
||||
public static function id( string $version, mixed $epoch ): string {
|
||||
$v = preg_replace( '/[^A-Za-z0-9._-]/', '', $version ) ?? '';
|
||||
return ( '' === $v ? '0' : $v ) . '-' . self::epochInt( $epoch );
|
||||
}
|
||||
|
||||
/** Pure: stored option value (anything) to a non-negative integer. */
|
||||
public static function epochInt( mixed $raw ): int {
|
||||
return ( is_int( $raw ) || ( is_string( $raw ) && ctype_digit( $raw ) && strlen( $raw ) < 15 ) ) ? max( 0, (int) $raw ) : 0;
|
||||
}
|
||||
|
||||
/** Pure: the epoch after a bump. Strictly increasing, never lower than the clock so a deleted option cannot repeat an old value. */
|
||||
public static function nextEpoch( mixed $current, int $now ): int {
|
||||
return max( self::epochInt( $current ) + 1, $now );
|
||||
}
|
||||
|
||||
/** Pure: response headers carrying the build id (merged into the existing ones; ETag semantics untouched). */
|
||||
public static function headers( string $build ): array {
|
||||
return array( self::HEADER => $build );
|
||||
}
|
||||
|
||||
public static function current(): string {
|
||||
return self::id( defined( 'STREAMGOALS_VERSION' ) ? (string) STREAMGOALS_VERSION : '', get_option( self::OPTION, 0 ) );
|
||||
}
|
||||
|
||||
/** Reloads every open overlay at its next poll. */
|
||||
public static function bump(): void {
|
||||
update_option( self::OPTION, self::nextEpoch( get_option( self::OPTION, 0 ), time() ), false );
|
||||
}
|
||||
}
|
||||
@@ -74,7 +74,7 @@ final class Router {
|
||||
<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">
|
||||
<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" data-build="<?php echo esc_attr( Build::current() ); ?>">
|
||||
<main id="sg-root" aria-live="polite"></main>
|
||||
<script src="<?php echo $asset( 'overlay.js' ); // phpcs:ignore WordPress.Security.EscapeOutput ?>"></script>
|
||||
</body>
|
||||
|
||||
@@ -6,7 +6,7 @@ namespace StreamGoals\Overlay;
|
||||
/** $wpdb adapter reading sg_goals, sg_donations, sg_state, sg_rules directly. */
|
||||
final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource, ActionsSource, AlertMediaSource, TiersSource {
|
||||
|
||||
/** @var array<int,?array{url:string,mime:string}> */
|
||||
/** @var array<int,?array{url:string,mime:string,v:int,modified:string}> */
|
||||
private array $attachments = array();
|
||||
|
||||
private function t( string $name ): string {
|
||||
@@ -160,7 +160,9 @@ final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource,
|
||||
$mime = (string) get_post_mime_type( $id );
|
||||
$url = wp_get_attachment_url( $id );
|
||||
if ( \StreamGoals\Alerts\Media::isAllowed( $mime ) && is_string( $url ) && '' !== $url ) {
|
||||
$out = array( 'url' => $url, 'mime' => $mime );
|
||||
$path = get_attached_file( $id );
|
||||
$mtime = ( is_string( $path ) && is_file( $path ) ) ? (int) @filemtime( $path ) : 0;
|
||||
$out = array( 'url' => $url, 'mime' => $mime, 'v' => $mtime, 'modified' => (string) get_post_field( 'post_modified_gmt', $id ) );
|
||||
}
|
||||
}
|
||||
return $this->attachments[ $id ] = $out;
|
||||
|
||||
@@ -4,6 +4,7 @@ declare( strict_types=1 );
|
||||
namespace StreamGoals\Rest;
|
||||
|
||||
use StreamGoals\Core\Settings;
|
||||
use StreamGoals\Overlay\Build;
|
||||
use StreamGoals\Overlay\OverlayService;
|
||||
use StreamGoals\Overlay\Payloads;
|
||||
use StreamGoals\Overlay\Router;
|
||||
@@ -56,7 +57,7 @@ final class OverlayController {
|
||||
}
|
||||
|
||||
$etag = Payloads::etag( $payload, $service->etagSalt( (string) $req['widget'] ) );
|
||||
$headers = array( 'ETag' => $etag, 'Cache-Control' => 'private, max-age=1, must-revalidate', 'X-Robots-Tag' => 'noindex' );
|
||||
$headers = array( 'ETag' => $etag, 'Cache-Control' => 'private, max-age=1, must-revalidate', 'X-Robots-Tag' => 'noindex' ) + Build::headers( Build::current() );
|
||||
$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 );
|
||||
|
||||
@@ -103,4 +103,14 @@ final class AlertDefInputTest extends TestCase {
|
||||
$this->assertStringNotContainsString( '<', $this->run_( $this->post( array( 'title' => '<script>x</script>Hi', 'message' => '<b>hi</b>' ) ) )['data']['title'] );
|
||||
$this->assertStringNotContainsString( '<', $this->run_( $this->post( array( 'message' => '<b>hi</b>{name}' ) ) )['data']['message'] );
|
||||
}
|
||||
|
||||
public function test_frameless_checkbox_parsing_defaults_off(): void {
|
||||
$this->assertSame( 0, $this->run_( $this->post() )['data']['frameless'] );
|
||||
foreach ( array( '1', 'on', 1, true, 'true' ) as $on ) {
|
||||
$this->assertSame( 1, $this->run_( $this->post( array( 'frameless' => $on ) ) )['data']['frameless'], 'on: ' . var_export( $on, true ) );
|
||||
}
|
||||
foreach ( array( '0', '', 'off', array( '1' ), 'banana' ) as $off ) {
|
||||
$this->assertSame( 0, $this->run_( $this->post( array( 'frameless' => $off ) ) )['data']['frameless'], 'off: ' . var_export( $off, true ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,7 @@ final class OverlayAlertMediaTest extends TestCase {
|
||||
'volume' => 60,
|
||||
'duration_ms' => 7000,
|
||||
'message' => 'Al gave $25.00',
|
||||
'frameless' => false,
|
||||
), $m );
|
||||
}
|
||||
|
||||
@@ -169,4 +170,22 @@ final class OverlayAlertMediaTest extends TestCase {
|
||||
Payloads::alerts( array( $this->row( 1, array( 'is_anonymous' => 1 ) ), $this->row( 2, array( 'moderation' => 'rejected' ) ) ), null, 10, true, $cb );
|
||||
$this->assertSame( array( array( 1, 'Anonymous', '$25.00' ) ), $seen );
|
||||
}
|
||||
|
||||
public function test_frameless_passes_through_only_with_a_visual(): void {
|
||||
$this->assertTrue( $this->build( $this->def( 1, array( 'frameless' => 1 ) ) )['frameless'] );
|
||||
$this->assertFalse( $this->build( $this->def( 1, array( 'frameless' => 0 ) ) )['frameless'] );
|
||||
$this->assertFalse( $this->build( $this->def( 1, array( 'frameless' => 1, 'visual_id' => 0, 'message' => 'hi' ) ) )['frameless'], 'no visual, nothing to unframe' );
|
||||
$this->assertFalse( $this->build( $this->def( 1, array( 'frameless' => 1, 'visual_id' => 13 ) ) )['frameless'], 'rejected media never unframes' );
|
||||
}
|
||||
|
||||
public function test_media_url_gets_version_suffix_from_server_data_only(): void {
|
||||
$files = array( 10 => array( 'url' => 'https://cdn.test/a.png', 'mime' => 'image/png', 'v' => 1700000000 ), 11 => array( 'url' => 'https://cdn.test/a.png?x=1', 'mime' => 'image/png', 'modified' => '2024-01-02 03:04:05' ) );
|
||||
$get = static fn( int $id ): ?array => $files[ $id ] ?? null;
|
||||
$m = AlertMedia::fromDef( $this->def( 1, array( 'sound_id' => 0 ) ), 'Al', '$1', array(), $get );
|
||||
$this->assertSame( 'https://cdn.test/a.png?v=1700000000', $m['visual']['url'] );
|
||||
$m = AlertMedia::fromDef( $this->def( 1, array( 'visual_id' => 11, 'sound_id' => 0 ) ), 'Al', '$1', array(), $get );
|
||||
$this->assertSame( 'https://cdn.test/a.png?x=1&v=' . strtotime( '2024-01-02 03:04:05 UTC' ), $m['visual']['url'] );
|
||||
$row = $this->row( 1, array( 'media' => array( 'visual' => array( 'type' => 'image', 'url' => 'https://evil.test/z.png' ) ) ) );
|
||||
$this->assertNotSame( 'https://evil.test/z.png', $this->build( $this->def( 1 ), $row )['visual']['url'] );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Alerts\Media;
|
||||
use StreamGoals\Overlay\Build;
|
||||
|
||||
final class OverlayBuildTest extends TestCase {
|
||||
|
||||
public function test_build_id_combines_version_and_epoch_and_is_safe(): void {
|
||||
$this->assertSame( '0.1.0-0', Build::id( '0.1.0', false ) );
|
||||
$this->assertSame( '0.1.0-7', Build::id( '0.1.0', '7' ) );
|
||||
$this->assertSame( '1.2x-0', Build::id( '1.2"<x>', 'abc' ), 'junk characters are stripped, junk epoch is 0' );
|
||||
$this->assertSame( '0-0', Build::id( '', null ) );
|
||||
$this->assertNotSame( Build::id( '0.1.0', 1 ), Build::id( '0.1.1', 1 ) );
|
||||
$this->assertNotSame( Build::id( '0.1.0', 1 ), Build::id( '0.1.0', 2 ) );
|
||||
}
|
||||
|
||||
public function test_headers_carry_only_the_build_and_never_touch_the_etag(): void {
|
||||
$this->assertSame( array( 'X-SG-Build' => '0.1.0-3' ), Build::headers( '0.1.0-3' ) );
|
||||
$src = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Rest/OverlayController.php' );
|
||||
$this->assertStringContainsString( 'Build::headers( Build::current() )', $src );
|
||||
$this->assertStringContainsString( 'Payloads::etag( $payload, $service->etagSalt(', $src, 'ETag is still computed from the payload only' );
|
||||
}
|
||||
|
||||
public function test_epoch_bump_rules(): void {
|
||||
$this->assertSame( 1000, Build::nextEpoch( 0, 1000 ) );
|
||||
$this->assertSame( 1000, Build::nextEpoch( false, 1000 ) );
|
||||
$this->assertSame( 1000, Build::nextEpoch( '999', 1000 ) );
|
||||
$this->assertSame( 2001, Build::nextEpoch( 2000, 1000 ), 'strictly increasing even if the clock went back' );
|
||||
$this->assertSame( 1000, Build::nextEpoch( '-5', 1000 ) );
|
||||
$this->assertSame( 1000, Build::nextEpoch( array( 9 ), 1000 ) );
|
||||
$this->assertSame( 0, Build::epochInt( 1.5 ) );
|
||||
$this->assertSame( 0, Build::epochInt( '99999999999999999999' ) );
|
||||
}
|
||||
|
||||
public function test_refresh_handler_is_guarded_registered_and_option_is_not_autoloaded(): void {
|
||||
$root = dirname( __DIR__, 2 ) . '/includes/';
|
||||
$page = (string) file_get_contents( $root . 'Admin/OverlaysPage.php' );
|
||||
$start = strpos( $page, 'function handleRefreshAll' );
|
||||
$this->assertNotFalse( $start );
|
||||
$this->assertStringContainsString( "Admin::guard( 'sg_refresh_overlays' )", substr( $page, $start, 200 ) );
|
||||
$this->assertStringContainsString( "'sg_refresh_overlays' => array( OverlaysPage::class, 'handleRefreshAll' )", (string) file_get_contents( $root . 'Admin/Admin.php' ) );
|
||||
$this->assertStringContainsString( 'Reloads every open OBS source. Done automatically after a plugin update.', $page );
|
||||
$this->assertStringContainsString( ', false );', substr( (string) file_get_contents( $root . 'Overlay/Build.php' ), (int) strpos( (string) file_get_contents( $root . 'Overlay/Build.php' ), 'update_option' ) ) );
|
||||
$this->assertStringContainsString( 'data-build=', (string) file_get_contents( $root . 'Overlay/Router.php' ) );
|
||||
}
|
||||
|
||||
public function test_media_version_suffix_builder(): void {
|
||||
$this->assertSame( 'https://x.test/a.png?v=123', Media::withVersion( 'https://x.test/a.png', 123 ) );
|
||||
$this->assertSame( 'https://x.test/a.png?q=1&v=123', Media::withVersion( 'https://x.test/a.png?q=1', 123 ) );
|
||||
$this->assertSame( 'https://x.test/a.png?v=123', Media::withVersion( 'https://x.test/a.png?v=5', 123 ), 'replaces an old v' );
|
||||
$this->assertSame( 'https://x.test/a.png?q=1&v=123', Media::withVersion( 'https://x.test/a.png?v=5&q=1', 123 ) );
|
||||
$this->assertSame( 'https://x.test/a.png?v=' . strtotime( '2024-05-06 07:08:09 UTC' ), Media::withVersion( 'https://x.test/a.png', 0, '2024-05-06 07:08:09' ), 'falls back to post_modified_gmt' );
|
||||
$this->assertSame( 'https://x.test/a.png?v=50', Media::withVersion( 'https://x.test/a.png', 50, '2024-05-06 07:08:09' ), 'file mtime wins' );
|
||||
$this->assertSame( 'https://x.test/a.png', Media::withVersion( 'https://x.test/a.png', 0, '0000-00-00 00:00:00x' ) );
|
||||
$this->assertSame( 'https://x.test/a.png', Media::withVersion( 'https://x.test/a.png', 0 ) );
|
||||
$this->assertSame( 'https://x.test/a.png#f', Media::withVersion( 'https://x.test/a.png#f', 9 ) );
|
||||
$this->assertNotNull( Media::safeUrl( Media::withVersion( 'https://x.test/a.png', 123 ) ) );
|
||||
}
|
||||
|
||||
public function test_installer_has_frameless_column_and_version_five(): void {
|
||||
$src = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Core/Installer.php' );
|
||||
$this->assertSame( 1, preg_match( "/DB_VERSION = '(\\d+)'/", $src, $m ) );
|
||||
$this->assertGreaterThanOrEqual( 5, (int) $m[1] );
|
||||
$this->assertMatchesRegularExpression( '/CREATE TABLE \{\$p\}alert_defs \([^;]*frameless TINYINT\(1\) NOT NULL DEFAULT 0,/s', $src );
|
||||
}
|
||||
|
||||
public function test_overlay_js_checks_build_on_every_response_including_304(): void {
|
||||
$js = (string) file_get_contents( dirname( __DIR__, 2 ) . '/assets/overlay/overlay.js' );
|
||||
$this->assertLessThan( strpos( $js, 'r.status === 304' ), strpos( $js, 'checkBuild(r)' ), 'build is compared before the 304 shortcut' );
|
||||
$this->assertStringContainsString( 'X-SG-Build', $js );
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user