diff --git a/README.md b/README.md index cc71f60..0c52c86 100644 --- a/README.md +++ b/README.md @@ -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=`, 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 diff --git a/assets/admin/alerts.css b/assets/admin/alerts.css index 0aeb87a..4c75060 100644 --- a/assets/admin/alerts.css +++ b/assets/admin/alerts.css @@ -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} diff --git a/assets/admin/alerts.js b/assets/admin/alerts.js index 9497a97..8396ee0 100644 --- a/assets/admin/alerts.js +++ b/assets/admin/alerts.js @@ -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".' ) ); }() ); diff --git a/assets/overlay/overlay.css b/assets/overlay/overlay.css index f923600..3737517 100644 --- a/assets/overlay/overlay.css +++ b/assets/overlay/overlay.css @@ -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}} diff --git a/assets/overlay/overlay.js b/assets/overlay/overlay.js index 8cf822c..ddd8622 100644 --- a/assets/overlay/overlay.js +++ b/assets/overlay/overlay.js @@ -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'); diff --git a/includes/Admin/Admin.php b/includes/Admin/Admin.php index ac9513e..d1d84c3 100644 --- a/includes/Admin/Admin.php +++ b/includes/Admin/Admin.php @@ -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' ), ); diff --git a/includes/Admin/AlertsPage.php b/includes/Admin/AlertsPage.php index e425f5c..319951d 100644 --- a/includes/Admin/AlertsPage.php +++ b/includes/Admin/AlertsPage.php @@ -178,6 +178,9 @@ final class AlertsPage { echo '

A reward alert beats an amount alert. Only rewards that are turned on can be picked.

'; 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 'Frameless'; + echo '

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 PNG, GIF and WebP pictures and WebM videos made with transparency. MP4 never supports transparency, 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.

'; + echo '
How do I make a transparent video?

Export your animation with an alpha channel (a "transparent background"), then convert it to WebM with ffmpeg:

ffmpeg -i input.mov -c:v libvpx-vp9 -pix_fmt yuva420p -b:v 0 -crf 30 -an output.webm

Replace input.mov with your file (a ProRes 4444 .mov or a PNG sequence both work). Use -an to drop audio (pick a separate sound above instead) or remove it to keep the clip\'s own sound. Then upload output.webm to your Media Library. Use the preview below to check it: the checkerboard shows through the transparent parts.

'; echo ' ' . (int) $val( 'volume', 80 ) . '%'; echo ' seconds

1 to 60. Videos play to the end instead, for at most 30 seconds.

'; echo '

Optional. Use {name}, {amount} and {reward}, for example "{name} just sent {amount}!". Leave empty for the normal text ("Name donated $5.00").

'; @@ -186,7 +189,7 @@ final class AlertsPage { echo '

Preview

'; echo '

This is how the alert will look on stream. Press the button to play it (browsers only allow sound after you click).

'; - echo '

'; + echo '

'; echo '
'; echo '
'; echo '

Cancel

'; diff --git a/includes/Admin/OverlaysPage.php b/includes/Admin/OverlaysPage.php index aa3d54f..3b6a0f4 100644 --- a/includes/Admin/OverlaysPage.php +++ b/includes/Admin/OverlaysPage.php @@ -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 ''; + echo '

Refresh overlays

'; + Admin::form( 'sg_refresh_overlays', array(), 'sg-inline' ); + echo ''; + echo '

Reloads every open OBS source. Done automatically after a plugin update.

'; + echo '

Send a test donation

'; echo '

Shows a fake donation on the Donation alerts 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.

'; echo '

How tests are kept out of your numbers: 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 TEST in the Donations list. Test donations are kept in the database until you delete them below.

'; @@ -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 ) ) ) ); diff --git a/includes/Alerts/AlertMedia.php b/includes/Alerts/AlertMedia.php index b7d74f5..8f78991 100644 --- a/includes/Alerts/AlertMedia.php +++ b/includes/Alerts/AlertMedia.php @@ -13,8 +13,8 @@ final class AlertMedia { * @param array $row Donation row (goal_id, base_minor). * @param array> $defs Raw alert definitions. * @param array $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|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'] ); } } diff --git a/includes/Alerts/DefInput.php b/includes/Alerts/DefInput.php index 0a815c8..fd3022d 100644 --- a/includes/Alerts/DefInput.php +++ b/includes/Alerts/DefInput.php @@ -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 ) { diff --git a/includes/Alerts/DefRepository.php b/includes/Alerts/DefRepository.php index 0e06192..a8a526c 100644 --- a/includes/Alerts/DefRepository.php +++ b/includes/Alerts/DefRepository.php @@ -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' ) ); } diff --git a/includes/Alerts/Media.php b/includes/Alerts/Media.php index db67b94..f62864c 100644 --- a/includes/Alerts/Media.php +++ b/includes/Alerts/Media.php @@ -66,6 +66,24 @@ final class Media { return is_numeric( $v ) ? max( 0, min( 100, (int) $v ) ) : $default; } + /** + * Appends ?v= 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 ) ) { diff --git a/includes/Core/Installer.php b/includes/Core/Installer.php index 741ec3e..b950c47 100644 --- a/includes/Core/Installer.php +++ b/includes/Core/Installer.php @@ -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) diff --git a/includes/Overlay/AlertMediaSource.php b/includes/Overlay/AlertMediaSource.php index cf11746..2c7e268 100644 --- a/includes/Overlay/AlertMediaSource.php +++ b/includes/Overlay/AlertMediaSource.php @@ -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; } diff --git a/includes/Overlay/Build.php b/includes/Overlay/Build.php new file mode 100644 index 0000000..85f0128 --- /dev/null +++ b/includes/Overlay/Build.php @@ -0,0 +1,44 @@ + $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 ); + } +} diff --git a/includes/Overlay/Router.php b/includes/Overlay/Router.php index 8a7d7e2..fa9d777 100644 --- a/includes/Overlay/Router.php +++ b/includes/Overlay/Router.php @@ -74,7 +74,7 @@ final class Router { StreamGoals overlay - +
diff --git a/includes/Overlay/WpdbDataSource.php b/includes/Overlay/WpdbDataSource.php index 35802c1..c96a008 100644 --- a/includes/Overlay/WpdbDataSource.php +++ b/includes/Overlay/WpdbDataSource.php @@ -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 */ + /** @var array */ 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; diff --git a/includes/Rest/OverlayController.php b/includes/Rest/OverlayController.php index 99e9ba9..e5115cd 100644 --- a/includes/Rest/OverlayController.php +++ b/includes/Rest/OverlayController.php @@ -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 ); diff --git a/tests/Unit/AlertDefInputTest.php b/tests/Unit/AlertDefInputTest.php index f00e872..a200eae 100644 --- a/tests/Unit/AlertDefInputTest.php +++ b/tests/Unit/AlertDefInputTest.php @@ -103,4 +103,14 @@ final class AlertDefInputTest extends TestCase { $this->assertStringNotContainsString( '<', $this->run_( $this->post( array( 'title' => 'Hi', 'message' => 'hi' ) ) )['data']['title'] ); $this->assertStringNotContainsString( '<', $this->run_( $this->post( array( 'message' => 'hi{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 ) ); + } + } } diff --git a/tests/Unit/OverlayAlertMediaTest.php b/tests/Unit/OverlayAlertMediaTest.php index 6b10a28..ffe48d4 100644 --- a/tests/Unit/OverlayAlertMediaTest.php +++ b/tests/Unit/OverlayAlertMediaTest.php @@ -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'] ); + } } diff --git a/tests/Unit/OverlayBuildTest.php b/tests/Unit/OverlayBuildTest.php new file mode 100644 index 0000000..56fc1df --- /dev/null +++ b/tests/Unit/OverlayBuildTest.php @@ -0,0 +1,76 @@ +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"', '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 ); + } +}