Alert media: images/GIFs/videos/sounds tied to donation amount or reward; release tag collision fix
- Alerts\Resolver/Media/Template/AlertMedia/DefInput/DefRepository; Alerts admin screen with Media Library picker and live preview - Overlay: media resolved server-side from attachment IDs (MIME whitelist), playback with timeouts and autoplay-failure fallbacks - Workflow: pick the next free minute if the version tag already exists (two pushes in one minute failed 'Create release') Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1201db175b
commit
2c16a9ebbb
22 files changed
+1591
-22
No files matched your search
@@ -28,6 +28,9 @@ final class Admin {
|
||||
'sg_action_save' => array( ActionsPage::class, 'handleSave' ),
|
||||
'sg_action_toggle' => array( ActionsPage::class, 'handleToggle' ),
|
||||
'sg_action_delete' => array( ActionsPage::class, 'handleDelete' ),
|
||||
'sg_alert_save' => array( AlertsPage::class, 'handleSave' ),
|
||||
'sg_alert_toggle' => array( AlertsPage::class, 'handleToggle' ),
|
||||
'sg_alert_delete' => array( AlertsPage::class, 'handleDelete' ),
|
||||
'sg_event_done' => array( ActionsPage::class, 'handleDone' ),
|
||||
'sg_event_done_all' => array( ActionsPage::class, 'handleDoneAll' ),
|
||||
'sg_export_csv' => array( DonationsPage::class, 'handleExport' ),
|
||||
@@ -65,6 +68,7 @@ final class Admin {
|
||||
$queued = ActionsPage::queuedCount();
|
||||
$qbadge = $queued > 0 ? ' <span class="awaiting-mod">' . (int) $queued . '</span>' : '';
|
||||
add_submenu_page( self::HOME, 'Rewards', 'Rewards' . $qbadge, self::CAP, ActionsPage::PAGE, array( ActionsPage::class, 'render' ) );
|
||||
add_submenu_page( self::HOME, 'Alerts', 'Alerts', self::CAP, AlertsPage::PAGE, array( AlertsPage::class, 'render' ) );
|
||||
add_submenu_page( self::HOME, 'Overlays', 'Overlays', self::CAP, 'streamgoals-overlays', array( OverlaysPage::class, 'render' ) );
|
||||
add_submenu_page( self::HOME, 'Settings', 'Settings', self::CAP, 'streamgoals-settings', array( SettingsPage::class, 'render' ) );
|
||||
}
|
||||
@@ -101,6 +105,11 @@ final class Admin {
|
||||
if ( ActionsPage::PAGE === $page ) {
|
||||
wp_enqueue_script( 'streamgoals-actions', STREAMGOALS_URL . 'assets/admin/actions.js', array( 'streamgoals-admin' ), STREAMGOALS_VERSION, true );
|
||||
}
|
||||
if ( AlertsPage::PAGE === $page ) {
|
||||
wp_enqueue_media();
|
||||
wp_enqueue_style( 'streamgoals-alerts', STREAMGOALS_URL . 'assets/admin/alerts.css', array( 'streamgoals-admin' ), STREAMGOALS_VERSION );
|
||||
wp_enqueue_script( 'streamgoals-alerts', STREAMGOALS_URL . 'assets/admin/alerts.js', array( 'streamgoals-admin', 'jquery' ), STREAMGOALS_VERSION, true );
|
||||
}
|
||||
if ( 'streamgoals-overlays' === $page ) {
|
||||
wp_enqueue_script( 'streamgoals-overlays', STREAMGOALS_URL . 'assets/admin/overlays.js', array( 'streamgoals-admin' ), STREAMGOALS_VERSION, true );
|
||||
}
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Actions\ActionRepository;
|
||||
use StreamGoals\Alerts\DefInput;
|
||||
use StreamGoals\Alerts\DefRepository;
|
||||
use StreamGoals\Alerts\Media;
|
||||
use StreamGoals\Core\Money;
|
||||
use StreamGoals\Core\Settings;
|
||||
|
||||
/** "Alerts": pictures, GIFs, videos and sounds that play on the alerts overlay for certain donations or rewards. */
|
||||
final class AlertsPage {
|
||||
|
||||
public const PAGE = 'streamgoals-alerts';
|
||||
|
||||
private static function repo(): DefRepository {
|
||||
return new DefRepository();
|
||||
}
|
||||
|
||||
private static function minMinor(): int {
|
||||
return Settings::effectiveMin( (int) Settings::get( 'min_donation_minor', 0 ) );
|
||||
}
|
||||
|
||||
private static function url( array $args = array() ): string {
|
||||
return Admin::url( self::PAGE, $args );
|
||||
}
|
||||
|
||||
/** @return array<int,string> goal id => title */
|
||||
private static function goalTitles(): array {
|
||||
$out = array();
|
||||
foreach ( Store::goals()->all() as $g ) {
|
||||
$out[ (int) $g['id'] ] = (string) $g['title'];
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** Attachment lookup for validation: mime + size, null when missing. */
|
||||
public static function attachmentInfo( int $id ): ?array {
|
||||
if ( $id <= 0 || 'attachment' !== get_post_type( $id ) ) {
|
||||
return null;
|
||||
}
|
||||
$path = get_attached_file( $id );
|
||||
return array(
|
||||
'mime' => (string) get_post_mime_type( $id ),
|
||||
'size' => ( is_string( $path ) && is_file( $path ) ) ? (int) filesize( $path ) : 0,
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- render */
|
||||
|
||||
public static function render(): void {
|
||||
Admin::open( 'Alerts' );
|
||||
$edit = Admin::get_int( 'edit' );
|
||||
if ( 'new' === Admin::get_str( 'view' ) || $edit ) {
|
||||
self::renderForm( $edit );
|
||||
} else {
|
||||
self::renderHelp();
|
||||
self::renderList();
|
||||
}
|
||||
Admin::close();
|
||||
}
|
||||
|
||||
private static function renderHelp(): void {
|
||||
echo '<div class="sg-card"><h2>Make your alerts come alive</h2>';
|
||||
echo '<p>An alert is the pop-up on your stream when someone donates. Here you can give it a picture, a GIF or a video, and a sound. Pick the donation size (or a reward) that should trigger it.</p>';
|
||||
echo '<ul class="sga-help">';
|
||||
echo '<li><strong>By amount:</strong> "Any donation of at least $X". If several match, the one with the highest $X wins.</li>';
|
||||
echo '<li><strong>By reward:</strong> plays when a donor triggers one of your rewards. A reward alert beats an amount alert.</li>';
|
||||
echo '<li>Nothing set up? Alerts look and work exactly as before.</li>';
|
||||
echo '<li><strong>In OBS media plays automatically. In a normal browser tab you must click the page once before sound is allowed.</strong></li>';
|
||||
echo '<li>Pictures and GIFs stay for the time you choose. Videos play to the end, for at most 30 seconds.</li>';
|
||||
echo '<li>Keep files small (under 25 MB). Big videos make OBS slow to load and can make your stream stutter.</li>';
|
||||
echo '</ul></div>';
|
||||
}
|
||||
|
||||
private static function renderList(): void {
|
||||
$cur = Admin::currency();
|
||||
$defs = self::repo()->all();
|
||||
$goals = self::goalTitles();
|
||||
$rewards = array();
|
||||
foreach ( ( new ActionRepository() )->all() as $a ) {
|
||||
$rewards[ $a['id'] ] = $a['title'];
|
||||
}
|
||||
echo '<div class="sg-card"><h2>Your alerts</h2>';
|
||||
echo '<p><a class="button button-primary" href="' . esc_url( self::url( array( 'view' => 'new' ) ) ) . '">Add an alert</a></p>';
|
||||
if ( ! $defs ) {
|
||||
echo '<p>No custom alerts yet.</p></div>';
|
||||
return;
|
||||
}
|
||||
echo '<table class="widefat striped sg-table"><thead><tr><th>Name</th><th>Plays when</th><th>Applies to</th><th>Media</th><th>Order</th><th>Actions</th></tr></thead><tbody>';
|
||||
foreach ( $defs as $d ) {
|
||||
$id = (int) $d['id'];
|
||||
$when = 'reward' === $d['trigger_type']
|
||||
? 'Reward: ' . ( $rewards[ $d['action_id'] ] ?? 'a reward that was deleted' )
|
||||
: 'Donation of at least ' . Format::money( (int) $d['min_minor'], $cur );
|
||||
$media = array();
|
||||
if ( $d['visual_id'] ) {
|
||||
$media[] = 'video' === $d['visual_type'] ? 'Video' : 'Picture/GIF';
|
||||
}
|
||||
if ( $d['sound_id'] ) {
|
||||
$media[] = 'Sound';
|
||||
}
|
||||
echo '<tr' . ( $d['enabled'] ? '' : ' class="sg-off"' ) . '><td><strong>' . esc_html( $d['title'] ) . '</strong></td>';
|
||||
echo '<td>' . esc_html( $when ) . '</td>';
|
||||
echo '<td>' . esc_html( 0 === $d['goal_id'] ? 'All goals' : ( $goals[ $d['goal_id'] ] ?? 'Goal #' . $d['goal_id'] ) ) . '</td>';
|
||||
echo '<td>' . esc_html( $media ? implode( ', ', $media ) : 'Text only' ) . '</td>';
|
||||
echo '<td>' . (int) $d['sort'] . '</td><td class="sg-actions">';
|
||||
echo '<a class="button" href="' . esc_url( self::url( array( 'edit' => $id ) ) ) . '">Edit</a> ';
|
||||
Admin::form( 'sg_alert_toggle', array( 'alert_id' => $id, 'enabled' => $d['enabled'] ? 0 : 1 ), 'sg-inline' );
|
||||
echo '<button class="button">' . ( $d['enabled'] ? 'Turn off' : 'Turn on' ) . '</button></form> ';
|
||||
Admin::form( 'sg_alert_delete', array( 'alert_id' => $id ), 'sg-inline sg-confirm' );
|
||||
echo '<button class="button button-link-delete" data-confirm="Delete this alert? Your media files stay in the Media Library.">Delete</button></form>';
|
||||
echo '</td></tr>';
|
||||
}
|
||||
echo '</tbody></table></div>';
|
||||
}
|
||||
|
||||
private static function mediaField( string $name, string $label, string $kind, int $id, string $help ): void {
|
||||
$url = '';
|
||||
$mime = '';
|
||||
if ( $id > 0 && null !== self::attachmentInfo( $id ) ) {
|
||||
$url = (string) wp_get_attachment_url( $id );
|
||||
$mime = (string) get_post_mime_type( $id );
|
||||
}
|
||||
echo '<tr><th scope="row">' . esc_html( $label ) . '</th><td>';
|
||||
echo '<div class="sga-media" data-kind="' . esc_attr( $kind ) . '">';
|
||||
echo '<input type="hidden" name="' . esc_attr( $name ) . '" value="' . ( $id > 0 ? (int) $id : 0 ) . '" data-url="' . esc_attr( $url ) . '" data-mime="' . esc_attr( $mime ) . '">';
|
||||
echo '<span class="sga-media-name">' . esc_html( '' !== $url ? wp_basename( $url ) : 'Nothing chosen' ) . '</span> ';
|
||||
echo '<button type="button" class="button sga-pick">Choose from Media Library</button> ';
|
||||
echo '<button type="button" class="button sga-clear">Remove</button>';
|
||||
echo '<p class="description sga-media-warn" role="status"></p>';
|
||||
echo '</div><p class="description">' . esc_html( $help ) . '</p></td></tr>';
|
||||
}
|
||||
|
||||
private static function renderForm( int $id ): void {
|
||||
$d = $id ? self::repo()->find( $id ) : null;
|
||||
if ( $id && ! $d ) {
|
||||
echo '<p>That alert no longer exists. <a href="' . esc_url( self::url() ) . '">Back to alerts</a></p>';
|
||||
return;
|
||||
}
|
||||
$cur = Admin::currency();
|
||||
$goals = self::goalTitles();
|
||||
$val = static fn( string $k, $default = '' ) => $d[ $k ] ?? $default;
|
||||
$trigger = (string) $val( 'trigger_type', 'amount' );
|
||||
$rewards = array();
|
||||
foreach ( ( new ActionRepository() )->all() as $a ) {
|
||||
if ( $a['enabled'] || (int) $a['id'] === (int) $val( 'action_id', 0 ) ) {
|
||||
$rewards[] = array( 'id' => $a['id'], 'title' => $a['title'], 'enabled' => (bool) $a['enabled'] );
|
||||
}
|
||||
}
|
||||
$data = array(
|
||||
'currency' => $cur,
|
||||
'exp' => Money::exponent( $cur ),
|
||||
'rewards' => $rewards,
|
||||
'videoCap' => Media::VIDEO_CAP_MS,
|
||||
'warnBytes' => Media::WARN_BYTES,
|
||||
'allowed' => Media::MIMES,
|
||||
);
|
||||
|
||||
echo '<h2>' . ( $d ? 'Edit alert' : 'Add an alert' ) . '</h2>';
|
||||
Admin::form( 'sg_alert_save', array( 'alert_id' => $id ), 'sga-form' );
|
||||
echo '<table class="form-table" role="presentation">';
|
||||
echo '<tr><th scope="row"><label for="sga_title">Name</label></th><td><input type="text" required maxlength="120" id="sga_title" name="title" class="regular-text" value="' . esc_attr( (string) $val( 'title' ) ) . '"><p class="description">Only you see this, for example "Big donation fireworks".</p></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sga_goal">Applies to</label></th><td><select id="sga_goal" name="goal_id"><option value="0"' . selected( (int) $val( 'goal_id', 0 ), 0, false ) . '>All goals</option>';
|
||||
foreach ( $goals as $gid => $title ) {
|
||||
echo '<option value="' . (int) $gid . '"' . selected( (int) $val( 'goal_id', 0 ), $gid, false ) . '>' . esc_html( $title ) . '</option>';
|
||||
}
|
||||
echo '</select></td></tr>';
|
||||
echo '<tr><th scope="row">Plays when</th><td>';
|
||||
echo '<label><input type="radio" name="trigger_type" value="amount"' . checked( $trigger, 'amount', false ) . '> Any donation of at least <input type="text" inputmode="decimal" name="amount" class="small-text" value="' . esc_attr( $d && 'amount' === $trigger ? Format::decimal( (int) $d['min_minor'], $cur ) : '' ) . '"> ' . esc_html( $cur ) . '</label>';
|
||||
echo '<p class="description">At least ' . esc_html( Format::money( self::minMinor(), $cur ) ) . ' (your minimum donation). If several amount alerts match, the one with the highest amount wins.</p>';
|
||||
echo '<label><input type="radio" name="trigger_type" value="reward"' . checked( $trigger, 'reward', false ) . '> When a reward is triggered:</label> <select name="action_id"><option value="0">Choose a reward</option>';
|
||||
foreach ( $rewards as $r ) {
|
||||
echo '<option value="' . (int) $r['id'] . '"' . selected( (int) $val( 'action_id', 0 ), (int) $r['id'], false ) . '>' . esc_html( $r['title'] . ( $r['enabled'] ? '' : ' (turned off)' ) ) . '</option>';
|
||||
}
|
||||
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"><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>';
|
||||
echo '<tr><th scope="row"><label for="sga_sort">Order</label></th><td><input type="number" min="0" max="99999" id="sga_sort" name="sort" class="small-text" value="' . ( $d ? (int) $d['sort'] : '' ) . '"><p class="description">Lower numbers win when two alerts are otherwise equal. Leave empty to put it last.</p></td></tr>';
|
||||
echo '</table>';
|
||||
|
||||
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 '<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>';
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- handlers */
|
||||
|
||||
public static function handleSave(): void {
|
||||
Admin::guard( 'sg_alert_save' );
|
||||
$post = Admin::post_raw();
|
||||
$id = isset( $post['alert_id'] ) ? absint( $post['alert_id'] ) : 0;
|
||||
$back = self::url( $id ? array( 'edit' => $id ) : array( 'view' => 'new' ) );
|
||||
$repo = self::repo();
|
||||
if ( $id && ! $repo->find( $id ) ) {
|
||||
Admin::redirect( self::url(), 'error', 'That alert no longer exists.' );
|
||||
}
|
||||
$enabled = array();
|
||||
foreach ( ( new ActionRepository() )->all() as $a ) {
|
||||
if ( $a['enabled'] ) {
|
||||
$enabled[] = (int) $a['id'];
|
||||
}
|
||||
}
|
||||
$res = DefInput::validate( $post, self::minMinor(), Admin::currency(), array_keys( self::goalTitles() ), $enabled, array( self::class, 'attachmentInfo' ), $repo->nextSort() );
|
||||
if ( null === $res['data'] ) {
|
||||
Admin::redirect( $back, 'error', (string) $res['error'] );
|
||||
}
|
||||
if ( $id ) {
|
||||
$repo->update( $id, $res['data'] );
|
||||
} else {
|
||||
$repo->create( $res['data'] );
|
||||
}
|
||||
$msg = 'Alert saved.' . ( $res['warnings'] ? ' Heads up: ' . implode( ' ', $res['warnings'] ) : '' );
|
||||
Admin::redirect( self::url(), $res['warnings'] ? 'warning' : 'success', $msg );
|
||||
}
|
||||
|
||||
public static function handleToggle(): void {
|
||||
Admin::guard( 'sg_alert_toggle' );
|
||||
$post = Admin::post_raw();
|
||||
self::repo()->setEnabled( isset( $post['alert_id'] ) ? absint( $post['alert_id'] ) : 0, ! empty( $post['enabled'] ) );
|
||||
Admin::redirect( self::url(), 'success', 'Alert updated.' );
|
||||
}
|
||||
|
||||
public static function handleDelete(): void {
|
||||
Admin::guard( 'sg_alert_delete' );
|
||||
$post = Admin::post_raw();
|
||||
self::repo()->delete( isset( $post['alert_id'] ) ? absint( $post['alert_id'] ) : 0 );
|
||||
Admin::redirect( self::url(), 'success', 'Alert deleted.' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Alerts;
|
||||
|
||||
/**
|
||||
* Builds the public `media` block for one alert. URLs only ever come from the $attachment callback
|
||||
* (WordPress attachment lookup); the DB row contributes ids, never URLs.
|
||||
*/
|
||||
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
|
||||
*/
|
||||
public static function build( array $row, string $name, string $amountDisplay, array $defs, array $triggered, callable $attachment ): ?array {
|
||||
if ( ! $defs ) {
|
||||
return null;
|
||||
}
|
||||
$ids = array();
|
||||
$amounts = array();
|
||||
foreach ( $triggered as $t ) {
|
||||
$aid = (int) ( $t['action_id'] ?? 0 );
|
||||
$ids[] = $aid;
|
||||
$amounts[ $aid ] = (int) ( $t['amount_minor'] ?? 0 );
|
||||
}
|
||||
$def = Resolver::pick( (int) ( $row['goal_id'] ?? 0 ), (int) ( $row['base_minor'] ?? 0 ), $ids, $defs, $amounts );
|
||||
if ( null === $def ) {
|
||||
return null;
|
||||
}
|
||||
return self::fromDef( $def, $name, $amountDisplay, $triggered, $attachment );
|
||||
}
|
||||
|
||||
/** @return array<string,mixed>|null */
|
||||
public static function fromDef( array $def, string $name, string $amountDisplay, array $triggered, callable $attachment ): ?array {
|
||||
$visual = null;
|
||||
$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'] );
|
||||
}
|
||||
}
|
||||
$sound = null;
|
||||
$sid = (int) ( $def['sound_id'] ?? 0 );
|
||||
if ( $sid > 0 ) {
|
||||
$a = self::lookup( $attachment, $sid );
|
||||
if ( $a && Media::isSound( $a['mime'] ) ) {
|
||||
$sound = array( 'url' => $a['url'] );
|
||||
}
|
||||
}
|
||||
$reward = '';
|
||||
$best = -1;
|
||||
foreach ( $triggered as $t ) {
|
||||
$amt = (int) ( $t['amount_minor'] ?? 0 );
|
||||
if ( 'reward' === ( $def['trigger_type'] ?? '' ) ) {
|
||||
if ( (int) ( $t['action_id'] ?? 0 ) === (int) $def['action_id'] ) {
|
||||
$reward = (string) ( $t['title'] ?? '' );
|
||||
break;
|
||||
}
|
||||
} elseif ( $amt > $best ) {
|
||||
$best = $amt;
|
||||
$reward = (string) ( $t['title'] ?? '' );
|
||||
}
|
||||
}
|
||||
$msg = Template::render( (string) ( $def['message'] ?? '' ), $name, $amountDisplay, $reward );
|
||||
if ( null === $visual && null === $sound && '' === $msg ) {
|
||||
return null; // nothing usable left: behave exactly as a plain alert
|
||||
}
|
||||
$duration = Media::clampDurationMs( $def['duration_ms'] ?? Media::DEFAULT_MS );
|
||||
if ( $visual && 'video' === $visual['type'] ) {
|
||||
$duration = Media::VIDEO_CAP_MS;
|
||||
}
|
||||
return array(
|
||||
'visual' => $visual,
|
||||
'sound' => $sound,
|
||||
'volume' => Media::clampVolume( $def['volume'] ?? 80 ),
|
||||
'duration_ms' => $duration,
|
||||
'message' => '' === $msg ? null : $msg,
|
||||
);
|
||||
}
|
||||
|
||||
/** @return array{url:string,mime:string}|null */
|
||||
private static function lookup( callable $attachment, int $id ): ?array {
|
||||
try {
|
||||
$a = $attachment( $id );
|
||||
} catch ( \Throwable ) {
|
||||
return null;
|
||||
}
|
||||
if ( ! is_array( $a ) || ! Media::isAllowed( $a['mime'] ?? null ) ) {
|
||||
return null;
|
||||
}
|
||||
$url = Media::safeUrl( $a['url'] ?? null );
|
||||
return null === $url ? null : array( 'url' => $url, 'mime' => (string) $a['mime'] );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Alerts;
|
||||
|
||||
use StreamGoals\Admin\Input;
|
||||
|
||||
/** Pure validation/sanitizing for the alert definition form. */
|
||||
final class DefInput {
|
||||
|
||||
/**
|
||||
* @param int[] $validGoalIds Existing goal ids (0 = all goals always allowed).
|
||||
* @param int[] $enabledActionIds Enabled rewards that may be chosen as a trigger.
|
||||
* @param callable(int):?array{mime:string,size?:int} $attachment Lookup of an attachment by id (null = missing).
|
||||
* @return array{data:?array,error:?string,warnings:string[]}
|
||||
*/
|
||||
public static function validate( array $post, int $minMinor, string $currency, array $validGoalIds, array $enabledActionIds, callable $attachment, int $defaultSort = 0 ): array {
|
||||
$fail = static fn( string $m ): array => array( 'data' => null, 'error' => $m, 'warnings' => array() );
|
||||
|
||||
$title = Input::text( $post['title'] ?? '', 200 );
|
||||
if ( '' === $title ) {
|
||||
return $fail( 'Please give this alert a name, for example "Big donation fireworks".' );
|
||||
}
|
||||
if ( mb_strlen( $title ) > 120 ) {
|
||||
return $fail( 'The name can be at most 120 characters.' );
|
||||
}
|
||||
$goal = Input::int( $post['goal_id'] ?? '0', 0, PHP_INT_MAX >> 1 );
|
||||
if ( null === $goal || ( 0 !== $goal && ! in_array( $goal, array_map( 'intval', $validGoalIds ), true ) ) ) {
|
||||
return $fail( 'Please choose all goals or one of your goals.' );
|
||||
}
|
||||
$trigger = is_scalar( $post['trigger_type'] ?? null ) ? (string) $post['trigger_type'] : '';
|
||||
$min = 0;
|
||||
$action = 0;
|
||||
if ( 'amount' === $trigger ) {
|
||||
$min = Input::amountToMinor( $post['amount'] ?? '', $currency );
|
||||
if ( null === $min || $min <= 0 ) {
|
||||
return $fail( 'Please enter the smallest donation that should trigger this alert, for example 10.00.' );
|
||||
}
|
||||
if ( $min < $minMinor ) {
|
||||
return $fail( 'The amount must be at least the minimum donation (' . \StreamGoals\Admin\Format::money( $minMinor, $currency ) . ').' );
|
||||
}
|
||||
} elseif ( 'reward' === $trigger ) {
|
||||
$action = Input::int( $post['action_id'] ?? '', 1, PHP_INT_MAX >> 1 );
|
||||
if ( null === $action || ! in_array( $action, array_map( 'intval', $enabledActionIds ), true ) ) {
|
||||
return $fail( 'Please choose one of your turned-on rewards.' );
|
||||
}
|
||||
} else {
|
||||
return $fail( 'Please choose when this alert plays.' );
|
||||
}
|
||||
|
||||
$warnings = array();
|
||||
$visualId = 0;
|
||||
$visual = '';
|
||||
$sound = 0;
|
||||
$vRaw = Input::int( $post['visual_id'] ?? '0', 0, PHP_INT_MAX >> 1 );
|
||||
$sRaw = Input::int( $post['sound_id'] ?? '0', 0, PHP_INT_MAX >> 1 );
|
||||
if ( null === $vRaw || null === $sRaw ) {
|
||||
return $fail( 'The chosen media file is not valid. Please pick it again.' );
|
||||
}
|
||||
if ( $vRaw > 0 ) {
|
||||
$a = $attachment( $vRaw );
|
||||
if ( ! is_array( $a ) ) {
|
||||
return $fail( 'The picture or video you chose no longer exists in your Media Library. Please pick it again.' );
|
||||
}
|
||||
$type = Media::visualType( $a['mime'] ?? null );
|
||||
if ( null === $type ) {
|
||||
return $fail( 'The picture or video must be PNG, JPEG, GIF, WebP, MP4 or WebM. Other file types are not allowed.' );
|
||||
}
|
||||
$visualId = $vRaw;
|
||||
$visual = $type;
|
||||
self::sizeWarning( $a, 'picture or video', 'video' === $type, $warnings );
|
||||
}
|
||||
if ( $sRaw > 0 ) {
|
||||
$a = $attachment( $sRaw );
|
||||
if ( ! is_array( $a ) ) {
|
||||
return $fail( 'The sound you chose no longer exists in your Media Library. Please pick it again.' );
|
||||
}
|
||||
if ( ! Media::isSound( $a['mime'] ?? null ) ) {
|
||||
return $fail( 'The sound must be an MP3, OGG or WAV file.' );
|
||||
}
|
||||
$sound = $sRaw;
|
||||
self::sizeWarning( $a, 'sound', false, $warnings );
|
||||
}
|
||||
|
||||
$vol = Input::int( $post['volume'] ?? '80', 0, 100 );
|
||||
if ( null === $vol ) {
|
||||
return $fail( 'Volume must be a whole number from 0 to 100.' );
|
||||
}
|
||||
$dur = Media::secondsToMs( $post['duration'] ?? '6' );
|
||||
if ( null === $dur || (int) round( (float) $post['duration'] * 1000 ) !== $dur ) {
|
||||
return $fail( 'How long the picture stays must be between 1 and 60 seconds.' );
|
||||
}
|
||||
$message = Input::text( $post['message'] ?? '', 400 );
|
||||
if ( mb_strlen( $message ) > 255 ) {
|
||||
return $fail( 'The message can be at most 255 characters.' );
|
||||
}
|
||||
$sortRaw = $post['sort'] ?? '';
|
||||
$sort = ( is_scalar( $sortRaw ) && '' === trim( (string) $sortRaw ) ) ? $defaultSort : Input::int( $sortRaw, 0, 99999 );
|
||||
if ( null === $sort ) {
|
||||
return $fail( 'The sort order must be a whole number from 0 to 99999.' );
|
||||
}
|
||||
return array(
|
||||
'data' => array(
|
||||
'goal_id' => $goal,
|
||||
'trigger_type' => $trigger,
|
||||
'min_minor' => $min,
|
||||
'action_id' => $action,
|
||||
'title' => $title,
|
||||
'visual_id' => $visualId,
|
||||
'visual_type' => $visual,
|
||||
'sound_id' => $sound,
|
||||
'volume' => $vol,
|
||||
'duration_ms' => $dur,
|
||||
'message' => $message,
|
||||
'sort' => $sort,
|
||||
),
|
||||
'error' => null,
|
||||
'warnings' => $warnings,
|
||||
);
|
||||
}
|
||||
|
||||
/** @param string[] $warnings */
|
||||
private static function sizeWarning( array $a, string $what, bool $video, array &$warnings ): void {
|
||||
if ( (int) ( $a['size'] ?? 0 ) > Media::WARN_BYTES ) {
|
||||
$warnings[] = 'The ' . $what . ' is over 25 MB.' . ( $video ? ' Big videos can make OBS stutter or load slowly; a short, compressed clip works much better.' : ' Large files take longer to load, so the alert may start late.' );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Alerts;
|
||||
|
||||
/** $wpdb access to sg_alert_defs. */
|
||||
final class DefRepository {
|
||||
|
||||
private object $db;
|
||||
|
||||
public function __construct( ?object $db = null ) {
|
||||
$this->db = $db ?? $GLOBALS['wpdb'];
|
||||
}
|
||||
|
||||
private function t(): string {
|
||||
return $this->db->prefix . 'sg_alert_defs';
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private static function cast( array $r ): array {
|
||||
return array(
|
||||
'id' => (int) ( $r['id'] ?? 0 ),
|
||||
'goal_id' => (int) ( $r['goal_id'] ?? 0 ),
|
||||
'trigger_type' => 'reward' === ( $r['trigger_type'] ?? '' ) ? 'reward' : 'amount',
|
||||
'min_minor' => (int) ( $r['min_minor'] ?? 0 ),
|
||||
'action_id' => (int) ( $r['action_id'] ?? 0 ),
|
||||
'title' => (string) ( $r['title'] ?? '' ),
|
||||
'visual_id' => (int) ( $r['visual_id'] ?? 0 ),
|
||||
'visual_type' => (string) ( $r['visual_type'] ?? '' ),
|
||||
'sound_id' => (int) ( $r['sound_id'] ?? 0 ),
|
||||
'volume' => (int) ( $r['volume'] ?? 80 ),
|
||||
'duration_ms' => (int) ( $r['duration_ms'] ?? 6000 ),
|
||||
'message' => (string) ( $r['message'] ?? '' ),
|
||||
'enabled' => (int) ( $r['enabled'] ?? 0 ),
|
||||
'sort' => (int) ( $r['sort'] ?? 0 ),
|
||||
'created_at' => (string) ( $r['created_at'] ?? '' ),
|
||||
);
|
||||
}
|
||||
|
||||
public function all(): array {
|
||||
return array_map( array( self::class, 'cast' ), (array) $this->db->get_results( 'SELECT * FROM ' . $this->t() . ' ORDER BY sort ASC, id ASC', ARRAY_A ) );
|
||||
}
|
||||
|
||||
/** All enabled definitions (one query); the Resolver filters by goal. */
|
||||
public function enabled(): array {
|
||||
return array_map( array( self::class, 'cast' ), (array) $this->db->get_results( 'SELECT * FROM ' . $this->t() . ' WHERE enabled = 1 ORDER BY sort ASC, id ASC', ARRAY_A ) );
|
||||
}
|
||||
|
||||
public function find( int $id ): ?array {
|
||||
$row = $this->db->get_row( $this->db->prepare( 'SELECT * FROM ' . $this->t() . ' WHERE id = %d', $id ), ARRAY_A );
|
||||
return $row ? self::cast( $row ) : null;
|
||||
}
|
||||
|
||||
public function nextSort(): int {
|
||||
return (int) $this->db->get_var( 'SELECT COALESCE(MAX(sort),0)+10 FROM ' . $this->t() );
|
||||
}
|
||||
|
||||
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',
|
||||
);
|
||||
|
||||
public function create( array $d ): int {
|
||||
$row = array();
|
||||
foreach ( self::COLS as $k => $f ) {
|
||||
$row[ $k ] = $d[ $k ];
|
||||
}
|
||||
$row['enabled'] = 1;
|
||||
$row['created_at'] = gmdate( 'Y-m-d H:i:s' );
|
||||
$ok = $this->db->insert( $this->t(), $row, array_merge( array_values( self::COLS ), array( '%d', '%s' ) ) );
|
||||
return $ok ? (int) $this->db->insert_id : 0;
|
||||
}
|
||||
|
||||
public function update( int $id, array $d ): void {
|
||||
$row = array();
|
||||
foreach ( self::COLS as $k => $f ) {
|
||||
$row[ $k ] = $d[ $k ];
|
||||
}
|
||||
$this->db->update( $this->t(), $row, array( 'id' => $id ), array_values( self::COLS ), array( '%d' ) );
|
||||
}
|
||||
|
||||
public function setEnabled( int $id, bool $on ): void {
|
||||
$this->db->update( $this->t(), array( 'enabled' => $on ? 1 : 0 ), array( 'id' => $id ), array( '%d' ), array( '%d' ) );
|
||||
}
|
||||
|
||||
public function delete( int $id ): void {
|
||||
$this->db->delete( $this->t(), array( 'id' => $id ), array( '%d' ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Alerts;
|
||||
|
||||
/** Pure helpers: MIME whitelist, type classification and duration clamping for alert media. */
|
||||
final class Media {
|
||||
|
||||
/** Exact MIME => kind. Everything else (svg, html, ...) is rejected. */
|
||||
public const MIMES = array(
|
||||
'image/png' => 'image',
|
||||
'image/jpeg' => 'image',
|
||||
'image/gif' => 'image',
|
||||
'image/webp' => 'image',
|
||||
'video/mp4' => 'video',
|
||||
'video/webm' => 'video',
|
||||
'audio/mpeg' => 'audio',
|
||||
'audio/ogg' => 'audio',
|
||||
'audio/wav' => 'audio',
|
||||
);
|
||||
|
||||
public const WARN_BYTES = 26214400; // 25 MB
|
||||
public const MIN_DURATION_MS = 1000;
|
||||
public const MAX_DURATION_MS = 60000;
|
||||
public const DEFAULT_MS = 6000;
|
||||
public const VIDEO_CAP_MS = 30000;
|
||||
|
||||
/** 'image' | 'video' | 'audio' for an allowed MIME, else null. Strict: no parameters, no case games. */
|
||||
public static function kind( mixed $mime ): ?string {
|
||||
if ( ! is_string( $mime ) ) {
|
||||
return null;
|
||||
}
|
||||
return self::MIMES[ strtolower( $mime ) ] ?? null;
|
||||
}
|
||||
|
||||
public static function isAllowed( mixed $mime ): bool {
|
||||
return null !== self::kind( $mime );
|
||||
}
|
||||
|
||||
/** 'image' | 'video' for a visual attachment MIME, else null (audio is not a visual). */
|
||||
public static function visualType( mixed $mime ): ?string {
|
||||
$k = self::kind( $mime );
|
||||
return 'image' === $k || 'video' === $k ? $k : null;
|
||||
}
|
||||
|
||||
public static function isSound( mixed $mime ): bool {
|
||||
return 'audio' === self::kind( $mime );
|
||||
}
|
||||
|
||||
public static function clampDurationMs( mixed $ms, int $default = self::DEFAULT_MS ): int {
|
||||
if ( ! is_numeric( $ms ) ) {
|
||||
return $default;
|
||||
}
|
||||
return max( self::MIN_DURATION_MS, min( self::MAX_DURATION_MS, (int) $ms ) );
|
||||
}
|
||||
|
||||
/** Whole seconds (1-60) to clamped milliseconds; null when the input is not a number. */
|
||||
public static function secondsToMs( mixed $s ): ?int {
|
||||
if ( ! is_scalar( $s ) || ! preg_match( '/^\s*\d{1,4}(\.\d+)?\s*$/', (string) $s ) ) {
|
||||
return null;
|
||||
}
|
||||
return self::clampDurationMs( (int) round( (float) $s * 1000 ) );
|
||||
}
|
||||
|
||||
public static function clampVolume( mixed $v, int $default = 80 ): int {
|
||||
return is_numeric( $v ) ? max( 0, min( 100, (int) $v ) ) : $default;
|
||||
}
|
||||
|
||||
/** 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 ) ) {
|
||||
return null;
|
||||
}
|
||||
return preg_match( '#^https?://[^/]#i', $url ) ? $url : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Alerts;
|
||||
|
||||
/** Picks the single alert definition that applies to one donation. Pure. */
|
||||
final class Resolver {
|
||||
|
||||
/**
|
||||
* @param int[] $triggeredActionIds Rewards triggered by this donation.
|
||||
* @param array<int,array<string,mixed>> $defs Raw sg_alert_defs rows (any state; filtered here).
|
||||
* @param array<int,int> $actionAmounts action id => reward amount (minor); ties fall back to sort, id.
|
||||
* @return array<string,mixed>|null the winning row (with ints normalised) or null
|
||||
*/
|
||||
public static function pick( int $goalId, int $baseMinor, array $triggeredActionIds, array $defs, array $actionAmounts = array() ): ?array {
|
||||
$triggered = array_flip( array_map( 'intval', $triggeredActionIds ) );
|
||||
$reward = array();
|
||||
$amount = array();
|
||||
foreach ( $defs as $d ) {
|
||||
if ( ! is_array( $d ) || empty( $d['enabled'] ) ) {
|
||||
continue;
|
||||
}
|
||||
$dg = (int) ( $d['goal_id'] ?? 0 );
|
||||
if ( 0 !== $dg && $dg !== $goalId ) {
|
||||
continue;
|
||||
}
|
||||
$d['id'] = (int) ( $d['id'] ?? 0 );
|
||||
$d['sort'] = (int) ( $d['sort'] ?? 0 );
|
||||
$d['min_minor'] = (int) ( $d['min_minor'] ?? 0 );
|
||||
$d['action_id'] = (int) ( $d['action_id'] ?? 0 );
|
||||
$d['goal_id'] = $dg;
|
||||
if ( 'reward' === ( $d['trigger_type'] ?? '' ) ) {
|
||||
if ( $d['action_id'] > 0 && isset( $triggered[ $d['action_id'] ] ) ) {
|
||||
$reward[] = $d;
|
||||
}
|
||||
} elseif ( 'amount' === ( $d['trigger_type'] ?? '' ) && $baseMinor >= $d['min_minor'] ) {
|
||||
$amount[] = $d;
|
||||
}
|
||||
}
|
||||
if ( $reward ) {
|
||||
usort( $reward, static function ( array $a, array $b ) use ( $actionAmounts ): int {
|
||||
return ( (int) ( $actionAmounts[ $b['action_id'] ] ?? 0 ) <=> (int) ( $actionAmounts[ $a['action_id'] ] ?? 0 ) )
|
||||
?: ( $a['sort'] <=> $b['sort'] )
|
||||
?: ( $a['id'] <=> $b['id'] );
|
||||
} );
|
||||
return $reward[0];
|
||||
}
|
||||
if ( $amount ) {
|
||||
usort( $amount, static fn( array $a, array $b ): int => ( $b['min_minor'] <=> $a['min_minor'] ) ?: ( $a['sort'] <=> $b['sort'] ) ?: ( $a['id'] <=> $b['id'] ) );
|
||||
return $amount[0];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Alerts;
|
||||
|
||||
/** Renders the custom alert message. Output is plain text: no tags, no control characters, length-capped. */
|
||||
final class Template {
|
||||
|
||||
public const MAX = 200;
|
||||
|
||||
public static function clean( string $s ): string {
|
||||
$s = strip_tags( $s );
|
||||
$s = (string) preg_replace( '/[\x00-\x1F\x7F\x{200B}-\x{200F}\x{202A}-\x{202E}\x{2066}-\x{2069}\x{FEFF}]+/u', ' ', $s );
|
||||
$s = str_replace( array( '<', '>' ), '', $s );
|
||||
return trim( (string) preg_replace( '/\s+/u', ' ', $s ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Tokens: {name} {amount} {reward} (case-insensitive). Unknown tokens are dropped. Substituted values are never
|
||||
* re-scanned for tokens. Empty template (or empty result) returns '' meaning "use the default text".
|
||||
*/
|
||||
public static function render( string $template, string $name, string $amount, string $reward, int $max = self::MAX ): string {
|
||||
$tpl = self::clean( $template );
|
||||
if ( '' === $tpl ) {
|
||||
return '';
|
||||
}
|
||||
$name = self::clean( $name );
|
||||
$vals = array(
|
||||
'name' => '' === $name ? 'Anonymous' : mb_substr( $name, 0, 60 ),
|
||||
'amount' => mb_substr( self::clean( $amount ), 0, 30 ),
|
||||
'reward' => mb_substr( self::clean( $reward ), 0, 80 ),
|
||||
);
|
||||
$out = (string) preg_replace_callback(
|
||||
'/\{([A-Za-z_]{1,20})\}/',
|
||||
static fn( array $m ): string => $vals[ strtolower( $m[1] ) ] ?? '',
|
||||
$tpl
|
||||
);
|
||||
$out = trim( (string) preg_replace( '/\s+/u', ' ', $out ) );
|
||||
return mb_substr( $out, 0, max( 1, $max ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Overlay;
|
||||
|
||||
/** Optional capability: configurable alert media (definitions, triggered rewards, attachment lookup). */
|
||||
interface AlertMediaSource {
|
||||
|
||||
/** Enabled alert definitions, raw rows. Called at most once per request. */
|
||||
public function alertDefs(): array;
|
||||
|
||||
/**
|
||||
* Rewards triggered per donation, one lookup for the whole page.
|
||||
*
|
||||
* @param int[] $donationIds
|
||||
* @return array<int,array<int,array{action_id:int,amount_minor:int,title:string}>> donation id => rewards
|
||||
*/
|
||||
public function triggeredActionsFor( array $donationIds ): array;
|
||||
|
||||
/**
|
||||
* Server-side attachment lookup (the only place media URLs come from). Null when it is gone.
|
||||
*
|
||||
* @return array{url:string,mime:string}|null
|
||||
*/
|
||||
public function attachment( int $id ): ?array;
|
||||
}
|
||||
@@ -8,8 +8,24 @@ final class OverlayService {
|
||||
|
||||
public const WIDGETS = array( 'goal', 'timer', 'counter', 'alerts', 'actions' );
|
||||
|
||||
/** @var array<int,array<string,mixed>>|null */
|
||||
private ?array $defs = null;
|
||||
|
||||
public function __construct( private OverlayDataSource $source ) {}
|
||||
|
||||
/** Enabled alert definitions, loaded at most once per service instance (= per request). */
|
||||
private function defs(): array {
|
||||
if ( null === $this->defs ) {
|
||||
$this->defs = $this->source instanceof AlertMediaSource ? array_values( $this->source->alertDefs() ) : array();
|
||||
}
|
||||
return $this->defs;
|
||||
}
|
||||
|
||||
/** Extra ETag input so editing media definitions invalidates cached alert payloads even when no alert is pending. */
|
||||
public function etagSalt( string $widget ): string {
|
||||
return 'alerts' === $widget && $this->defs() ? md5( (string) json_encode( $this->defs() ) ) : '';
|
||||
}
|
||||
|
||||
public function payload( string $widget, int $now, ?int $since = null, bool $recent = false ): ?array {
|
||||
$goal = $this->source->activeGoal();
|
||||
$gid = $goal ? (int) $goal['id'] : 0;
|
||||
@@ -43,7 +59,16 @@ final class OverlayService {
|
||||
$rows[ $i ]['bonuses'] = $bonuses[ (int) ( $r['id'] ?? 0 ) ] ?? array();
|
||||
$rows[ $i ]['actions'] = $actions[ (int) ( $r['id'] ?? 0 ) ] ?? array();
|
||||
}
|
||||
return Payloads::alerts( $rows, $since, $recent ? 20 : 10, $recent );
|
||||
$mediaFor = null;
|
||||
$defs = ( $recent || null !== $since ) ? $this->defs() : array();
|
||||
if ( $defs && $ids && $this->source instanceof AlertMediaSource ) {
|
||||
$src = $this->source;
|
||||
$triggered = $src->triggeredActionsFor( $ids );
|
||||
$mediaFor = static fn( array $r, string $name, string $amount ): ?array => \StreamGoals\Alerts\AlertMedia::build(
|
||||
$r, $name, $amount, $defs, $triggered[ (int) ( $r['id'] ?? 0 ) ] ?? array(), static fn( int $id ): ?array => $src->attachment( $id )
|
||||
);
|
||||
}
|
||||
return Payloads::alerts( $rows, $since, $recent ? 20 : 10, $recent, $mediaFor );
|
||||
case 'actions':
|
||||
$rows = ( $gid && $this->source instanceof ActionsSource ) ? $this->source->menuActions( $gid ) : array();
|
||||
return Payloads::actionsMenu( $goal, $rows );
|
||||
|
||||
@@ -78,7 +78,7 @@ final class Payloads {
|
||||
* @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, bool $recent = false ): array {
|
||||
public static function alerts( array $rows, ?int $since, int $limit = 10, bool $recent = false, ?callable $mediaFor = null ): array {
|
||||
$safe = array();
|
||||
foreach ( $rows as $r ) {
|
||||
if ( 'completed' !== ( $r['status'] ?? '' ) || 'approved' !== ( $r['moderation'] ?? '' ) ) {
|
||||
@@ -89,7 +89,7 @@ final class Payloads {
|
||||
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 );
|
||||
$alerts = array_map( static fn( array $r ): array => self::alert( $r, $mediaFor ), $safe );
|
||||
return array( 'alerts' => $alerts, 'last_id' => $alerts ? (int) end( $alerts )['id'] : 0 );
|
||||
}
|
||||
$lastId = $since ?? 0;
|
||||
@@ -104,7 +104,7 @@ final class Payloads {
|
||||
if ( (int) $r['id'] <= $since ) {
|
||||
continue;
|
||||
}
|
||||
$alerts[] = self::alert( $r );
|
||||
$alerts[] = self::alert( $r, $mediaFor );
|
||||
}
|
||||
$alerts = array_slice( $alerts, 0, max( 1, $limit ) );
|
||||
if ( $alerts ) {
|
||||
@@ -113,20 +113,26 @@ final class Payloads {
|
||||
return array( 'alerts' => $alerts, 'last_id' => $lastId );
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $r */
|
||||
private static function alert( array $r ): array {
|
||||
/**
|
||||
* @param array<string,mixed> $r
|
||||
* @param (callable(array,string,string):?array)|null $mediaFor Builds the `media` block from (row, public name, amount display).
|
||||
*/
|
||||
private static function alert( array $r, ?callable $mediaFor = null ): array {
|
||||
$cur = strtoupper( (string) ( $r['currency'] ?? 'USD' ) );
|
||||
$anon = ! empty( $r['is_anonymous'] );
|
||||
$name = trim( (string) ( $r['donor_name'] ?? '' ) );
|
||||
$pub = ( $anon || '' === $name ) ? self::ANON_NAME : $name;
|
||||
$disp = self::money( (int) $r['base_minor'], $cur );
|
||||
return array(
|
||||
'id' => (int) $r['id'],
|
||||
'name' => ( $anon || '' === $name ) ? self::ANON_NAME : $name,
|
||||
'name' => $pub,
|
||||
'amount_minor' => (int) $r['base_minor'],
|
||||
'amount_display' => self::money( (int) $r['base_minor'], $cur ),
|
||||
'amount_display' => $disp,
|
||||
'currency' => $cur,
|
||||
'message' => (string) ( $r['message'] ?? '' ),
|
||||
'bonuses' => self::bonuses( $r['bonuses'] ?? array() ),
|
||||
'actions' => self::actionEvents( $r['actions'] ?? array() ),
|
||||
'media' => $mediaFor ? $mediaFor( $r, $pub, $disp ) : null,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -223,10 +229,10 @@ final class Payloads {
|
||||
return array( 'active' => (bool) $list, 'currency' => $cur, 'actions' => $list );
|
||||
}
|
||||
|
||||
/** Strong ETag over the payload, ignoring the volatile server_now so unchanged data yields 304s. */
|
||||
public static function etag( array $payload ): string {
|
||||
/** Strong ETag over the payload (plus an optional salt, e.g. a hash of media definitions), ignoring the volatile server_now so unchanged data yields 304s. */
|
||||
public static function etag( array $payload, string $salt = '' ): string {
|
||||
unset( $payload['server_now'] );
|
||||
return '"' . md5( (string) json_encode( $payload, JSON_UNESCAPED_UNICODE ) ) . '"';
|
||||
return '"' . md5( $salt . (string) json_encode( $payload, JSON_UNESCAPED_UNICODE ) ) . '"';
|
||||
}
|
||||
|
||||
private static function toEpoch( ?string $v ): ?int {
|
||||
|
||||
@@ -4,7 +4,10 @@ declare( strict_types=1 );
|
||||
namespace StreamGoals\Overlay;
|
||||
|
||||
/** $wpdb adapter reading sg_goals, sg_donations, sg_state, sg_rules directly. */
|
||||
final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource, ActionsSource {
|
||||
final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource, ActionsSource, AlertMediaSource {
|
||||
|
||||
/** @var array<int,?array{url:string,mime:string}> */
|
||||
private array $attachments = array();
|
||||
|
||||
private function t( string $name ): string {
|
||||
global $wpdb;
|
||||
@@ -117,9 +120,47 @@ final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource,
|
||||
return $out;
|
||||
}
|
||||
|
||||
public function alertDefs(): array {
|
||||
return ( new \StreamGoals\Alerts\DefRepository( $GLOBALS['wpdb'] ) )->enabled();
|
||||
}
|
||||
|
||||
public function triggeredActionsFor( array $donationIds ): array {
|
||||
global $wpdb;
|
||||
$ids = array_values( array_unique( array_filter( array_map( 'intval', $donationIds ), static fn( $i ) => $i > 0 ) ) );
|
||||
if ( ! $ids ) {
|
||||
return array();
|
||||
}
|
||||
$in = implode( ',', array_fill( 0, count( $ids ), '%d' ) );
|
||||
$rows = $wpdb->get_results( $wpdb->prepare(
|
||||
"SELECT e.donation_id, e.action_id, e.title, COALESCE(a.amount_minor,0) AS amount_minor FROM {$this->t('action_events')} e
|
||||
LEFT JOIN {$this->t('actions')} a ON a.id = e.action_id WHERE e.donation_id IN ($in) ORDER BY e.id ASC",
|
||||
$ids
|
||||
), ARRAY_A );
|
||||
$out = array();
|
||||
foreach ( (array) $rows as $row ) {
|
||||
$out[ (int) $row['donation_id'] ][] = array( 'action_id' => (int) $row['action_id'], 'amount_minor' => (int) $row['amount_minor'], 'title' => (string) $row['title'] );
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
public function attachment( int $id ): ?array {
|
||||
if ( array_key_exists( $id, $this->attachments ) ) {
|
||||
return $this->attachments[ $id ];
|
||||
}
|
||||
$out = null;
|
||||
if ( $id > 0 && 'attachment' === get_post_type( $id ) ) {
|
||||
$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 );
|
||||
}
|
||||
}
|
||||
return $this->attachments[ $id ] = $out;
|
||||
}
|
||||
|
||||
public function donations( ?int $sinceId, int $limit ): array {
|
||||
global $wpdb;
|
||||
$cols = 'id, base_minor, currency, donor_name, is_anonymous, message, status, moderation';
|
||||
$cols = 'id, goal_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 );
|
||||
@@ -136,7 +177,7 @@ final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource,
|
||||
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')}
|
||||
"SELECT id, goal_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 );
|
||||
|
||||
@@ -49,12 +49,13 @@ final class OverlayController {
|
||||
}
|
||||
$since = $req->has_param( 'since' ) && '' !== (string) $req->get_param( 'since' ) ? absint( $req->get_param( 'since' ) ) : null;
|
||||
$recent = $req->has_param( 'recent' ) && 1 === absint( $req->get_param( 'recent' ) );
|
||||
$payload = ( new OverlayService( new WpdbDataSource() ) )->payload( (string) $req['widget'], time(), $since, $recent );
|
||||
$service = new OverlayService( new WpdbDataSource() );
|
||||
$payload = $service->payload( (string) $req['widget'], time(), $since, $recent );
|
||||
if ( null === $payload ) {
|
||||
return new \WP_Error( 'sg_not_found', 'Not found.', array( 'status' => 404 ) );
|
||||
}
|
||||
|
||||
$etag = Payloads::etag( $payload );
|
||||
$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' );
|
||||
$inm = (string) $req->get_header( 'if_none_match' );
|
||||
if ( '' !== $inm && in_array( $etag, array_map( 'trim', explode( ',', str_replace( 'W/', '', $inm ) ) ), true ) ) {
|
||||
|
||||
Reference in new issue
Block a user