diff --git a/assets/overlay/overlay.js b/assets/overlay/overlay.js index 2d2f1f3..87054db 100644 --- a/assets/overlay/overlay.js +++ b/assets/overlay/overlay.js @@ -5,7 +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 etag = null, failures = 0, since = null, skew = 0, timerState = null; + var etag = null, failures = 0, skew = 0, timerState = null; var queue = [], showing = false; function el(tag, cls, text) { @@ -92,9 +92,25 @@ } // ---- alerts ---- + // Why not a `since` cursor: with moderation, a held donation keeps a low id. If a newer donation is shown + // first, the cursor moves past it and the later approval would never be returned. So we poll ?recent=1 + // (newest 20 approved alerts) and dedupe by id here. First successful poll only seeds seenIds, so + // refreshing OBS never replays old alerts. Limit: a message approved after 20+ newer donations is + // no longer in the window and is not shown. + var seenIds = {}, seenOrder = [], firstAlertPoll = true, SEEN_MAX = 200; + function markSeen(id) { + seenIds[id] = true; seenOrder.push(id); + while (seenOrder.length > SEEN_MAX) delete seenIds[seenOrder.shift()]; + } function renderAlerts(d) { - since = d.last_id; - for (var i = 0; i < d.alerts.length; i++) queue.push(d.alerts[i]); + var list = (d.alerts || []).slice().sort(function (a, b) { return a.id - b.id; }); + for (var i = 0; i < list.length; i++) { + var a = list[i]; + if (seenIds[a.id]) continue; + markSeen(a.id); + if (!firstAlertPoll) queue.push(a); + } + firstAlertPoll = false; next(); } function next() { @@ -126,7 +142,7 @@ // ---- polling ---- function url() { var u = endpoint; - if (widget === 'alerts' && since !== null) u += (u.indexOf('?') < 0 ? '?' : '&') + 'since=' + encodeURIComponent(since); + if (widget === 'alerts') u += (u.indexOf('?') < 0 ? '?' : '&') + 'recent=1'; return u; } function schedule() { diff --git a/includes/Overlay/OverlayService.php b/includes/Overlay/OverlayService.php index 3b96cf3..2558c11 100644 --- a/includes/Overlay/OverlayService.php +++ b/includes/Overlay/OverlayService.php @@ -10,7 +10,7 @@ final class OverlayService { public function __construct( private OverlayDataSource $source ) {} - public function payload( string $widget, int $now, ?int $since = null ): ?array { + public function payload( string $widget, int $now, ?int $since = null, bool $recent = false ): ?array { $goal = $this->source->activeGoal(); $gid = $goal ? (int) $goal['id'] : 0; switch ( $widget ) { @@ -26,13 +26,22 @@ final class OverlayService { $c = $gid ? $this->source->counter( $gid ) : array( 'label' => '', 'value' => 0 ); return Payloads::counter( $c['label'], $c['value'] ); case 'alerts': - $rows = $this->source->donations( $since, 20 ); + if ( $recent ) { + // Newest 20 approved rows regardless of cursor. Sources that predate RecentDonationsSource + // fall back to the oldest 20 (still correct for small installs, just not "newest"). + $rows = $this->source instanceof RecentDonationsSource + ? $this->source->recentDonations( 20 ) + : $this->source->donations( 0, 20 ); + $since = null; + } else { + $rows = $this->source->donations( $since, 20 ); + } $ids = array_values( array_filter( array_map( static fn( $r ) => (int) ( $r['id'] ?? 0 ), $rows ) ) ); - $bonuses = ( null !== $since && $ids ) ? $this->source->bonusesFor( $ids ) : array(); + $bonuses = ( ( $recent || null !== $since ) && $ids ) ? $this->source->bonusesFor( $ids ) : array(); foreach ( $rows as $i => $r ) { $rows[ $i ]['bonuses'] = $bonuses[ (int) ( $r['id'] ?? 0 ) ] ?? array(); } - return Payloads::alerts( $rows, $since ); + return Payloads::alerts( $rows, $since, $recent ? 20 : 10, $recent ); } return null; } diff --git a/includes/Overlay/Payloads.php b/includes/Overlay/Payloads.php index bfe0b8d..c65b25b 100644 --- a/includes/Overlay/Payloads.php +++ b/includes/Overlay/Payloads.php @@ -74,9 +74,11 @@ final class Payloads { /** * @param array> $rows - * @param int|null $since Null means "first poll": no alerts, just a baseline last_id. + * @param int|null $since Null means "first poll": no alerts, just a baseline last_id. + * @param bool $recent Recent mode: ignore $since and return the newest $limit approved alerts (ascending id), + * so a message approved after newer donations still shows up. The client dedupes by id. */ - public static function alerts( array $rows, ?int $since, int $limit = 10 ): array { + public static function alerts( array $rows, ?int $since, int $limit = 10, bool $recent = false ): array { $safe = array(); foreach ( $rows as $r ) { if ( 'completed' !== ( $r['status'] ?? '' ) || 'approved' !== ( $r['moderation'] ?? '' ) ) { @@ -85,6 +87,11 @@ final class Payloads { $safe[] = $r; } usort( $safe, static fn( $a, $b ) => (int) $a['id'] <=> (int) $b['id'] ); + if ( $recent ) { + $safe = array_slice( $safe, -max( 1, $limit ) ); + $alerts = array_map( array( self::class, 'alert' ), $safe ); + return array( 'alerts' => $alerts, 'last_id' => $alerts ? (int) end( $alerts )['id'] : 0 ); + } $lastId = $since ?? 0; foreach ( $safe as $r ) { $lastId = max( $lastId, (int) $r['id'] ); @@ -97,18 +104,7 @@ final class Payloads { 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'] ?? '' ), - 'bonuses' => self::bonuses( $r['bonuses'] ?? array() ), - ); + $alerts[] = self::alert( $r ); } $alerts = array_slice( $alerts, 0, max( 1, $limit ) ); if ( $alerts ) { @@ -117,6 +113,22 @@ final class Payloads { return array( 'alerts' => $alerts, 'last_id' => $lastId ); } + /** @param array $r */ + private static function alert( array $r ): array { + $cur = strtoupper( (string) ( $r['currency'] ?? 'USD' ) ); + $anon = ! empty( $r['is_anonymous'] ); + $name = trim( (string) ( $r['donor_name'] ?? '' ) ); + return 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'] ?? '' ), + 'bonuses' => self::bonuses( $r['bonuses'] ?? array() ), + ); + } + /** * Display-safe bonus labels. Stored events should be [A-Za-z0-9_-] only; anything else is stripped * anyway, then humanized ("big_donation" -> "Big donation"). Empty/duplicate results are dropped. diff --git a/includes/Overlay/RecentDonationsSource.php b/includes/Overlay/RecentDonationsSource.php new file mode 100644 index 0000000..dcd1aa0 --- /dev/null +++ b/includes/Overlay/RecentDonationsSource.php @@ -0,0 +1,15 @@ +> + */ + public function recentDonations( int $limit ): array; +} diff --git a/includes/Overlay/WpdbDataSource.php b/includes/Overlay/WpdbDataSource.php index 83650f2..9b1bca2 100644 --- a/includes/Overlay/WpdbDataSource.php +++ b/includes/Overlay/WpdbDataSource.php @@ -4,7 +4,7 @@ declare( strict_types=1 ); namespace StreamGoals\Overlay; /** $wpdb adapter reading sg_goals, sg_donations, sg_state, sg_rules directly. */ -final class WpdbDataSource implements OverlayDataSource { +final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource { private function t( string $name ): string { global $wpdb; @@ -102,4 +102,14 @@ final class WpdbDataSource implements OverlayDataSource { } return (array) $rows; } + + public function recentDonations( int $limit ): array { + global $wpdb; + $rows = $wpdb->get_results( $wpdb->prepare( + "SELECT id, base_minor, currency, donor_name, is_anonymous, message, status, moderation FROM {$this->t('donations')} + WHERE status = 'completed' AND moderation = 'approved' ORDER BY id DESC LIMIT %d", + max( 1, $limit ) + ), ARRAY_A ); + return array_reverse( (array) $rows ); + } } diff --git a/includes/Rest/OverlayController.php b/includes/Rest/OverlayController.php index f675623..055a681 100644 --- a/includes/Rest/OverlayController.php +++ b/includes/Rest/OverlayController.php @@ -24,6 +24,7 @@ final class OverlayController { 'permission_callback' => '__return_true', // capability is the unguessable token, checked in handle() 'args' => array( 'since' => array( 'type' => 'integer', 'minimum' => 0, 'sanitize_callback' => 'absint' ), + 'recent' => array( 'type' => 'integer', 'minimum' => 0, 'maximum' => 1, 'sanitize_callback' => 'absint' ), ), ) ); } @@ -47,7 +48,8 @@ final class OverlayController { 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 ); + $recent = $req->has_param( 'recent' ) && 1 === absint( $req->get_param( 'recent' ) ); + $payload = ( new OverlayService( new WpdbDataSource() ) )->payload( (string) $req['widget'], time(), $since, $recent ); if ( null === $payload ) { return new \WP_Error( 'sg_not_found', 'Not found.', array( 'status' => 404 ) ); } diff --git a/tests/Unit/OverlayRecentModeTest.php b/tests/Unit/OverlayRecentModeTest.php new file mode 100644 index 0000000..d8a9a61 --- /dev/null +++ b/tests/Unit/OverlayRecentModeTest.php @@ -0,0 +1,82 @@ +> $db */ + private function svc( array &$db ): OverlayService { + return new OverlayService( new class( $db ) implements OverlayDataSource, RecentDonationsSource { + public function __construct( private array &$db ) {} + public function activeGoal(): ?array { return null; } + public function raisedMinor( array $goal ): int { return 0; } + public function stateValue( int $goalId, string $key ): ?string { return null; } + public function counter( int $goalId ): array { return array( 'label' => '', 'value' => 0 ); } + public function bonusesFor( array $ids ): array { return array_fill_keys( $ids, array( 'big_donation' ) ); } + private function ok(): array { + $r = array_filter( $this->db, static fn( $d ) => 'completed' === $d['status'] && 'approved' === $d['moderation'] ); + usort( $r, static fn( $a, $b ) => $a['id'] <=> $b['id'] ); + return $r; + } + public function donations( ?int $sinceId, int $limit ): array { + return array_slice( array_values( array_filter( $this->ok(), static fn( $d ) => $d['id'] > (int) $sinceId ) ), 0, $limit ); + } + public function recentDonations( int $limit ): array { return array_slice( $this->ok(), -$limit ); } + } ); + } + + private function row( int $id, array $o = array() ): array { + return $o + array( 'id' => $id, 'base_minor' => 500, 'currency' => 'USD', 'donor_name' => 'Al', 'is_anonymous' => 0, + 'message' => '', 'status' => 'completed', 'moderation' => 'approved' ); + } + + public function test_recent_returns_approved_ascending_masked_with_bonuses(): void { + $db = array( $this->row( 3 ), $this->row( 1, array( 'is_anonymous' => 1, 'donor_name' => 'Secret' ) ), + $this->row( 2, array( 'moderation' => 'pending' ) ), $this->row( 4, array( 'moderation' => 'rejected' ) ) ); + $out = $this->svc( $db )->payload( 'alerts', 1, null, true ); + $this->assertSame( array( 1, 3 ), array_column( $out['alerts'], 'id' ) ); + $this->assertSame( 3, $out['last_id'] ); + $this->assertSame( 'Anonymous', $out['alerts'][0]['name'] ); + $this->assertStringNotContainsString( 'Secret', json_encode( $out ) ); + $this->assertSame( array( 'Big donation' ), $out['alerts'][1]['bonuses'] ); + } + + public function test_recent_caps_at_newest_20(): void { + $db = array(); + for ( $i = 1; $i <= 25; $i++ ) { + $db[] = $this->row( $i ); + } + $out = $this->svc( $db )->payload( 'alerts', 1, null, true ); + $this->assertCount( 20, $out['alerts'] ); + $this->assertSame( 6, $out['alerts'][0]['id'] ); + $this->assertSame( 25, $out['alerts'][19]['id'] ); + $this->assertCount( 20, Payloads::alerts( $db, null, 20, true )['alerts'] ); + } + + public function test_late_approval_appears_in_recent_but_not_since(): void { + $db = array( $this->row( 1 ), $this->row( 2, array( 'moderation' => 'pending' ) ), $this->row( 3 ) ); + $svc = $this->svc( $db ); + $first = $svc->payload( 'alerts', 1, null, true ); + $this->assertSame( array( 1, 3 ), array_column( $first['alerts'], 'id' ) ); + $db[1]['moderation'] = 'approved'; + $this->assertSame( array(), $svc->payload( 'alerts', 1, $first['last_id'] )['alerts'] ); // old cursor misses it + $next = $svc->payload( 'alerts', 1, null, true ); + $this->assertSame( array( 1, 2, 3 ), array_column( $next['alerts'], 'id' ) ); + } + + public function test_recent_etag_stable_then_changes(): void { + $db = array( $this->row( 1 ), $this->row( 2, array( 'moderation' => 'pending' ) ) ); + $s = $this->svc( $db ); + $a = Payloads::etag( $s->payload( 'alerts', 1, null, true ) ); + $this->assertSame( $a, Payloads::etag( $s->payload( 'alerts', 99, null, true ) ) ); + $db[1]['moderation'] = 'approved'; + $this->assertNotSame( $a, Payloads::etag( $s->payload( 'alerts', 1, null, true ) ) ); + } +}