Files
wp-donations/includes/Admin/AlertsPage.php
T
shadowdaoandClaude Sonnet 5.5 2c16a9ebbb
Test and Release / test (push) Successful in 1m20s
Test and Release / release (push) Successful in 4s
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>
2026-11-15 13:01:31 -08:00

239 lines
13 KiB
PHP

<?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.' );
}
}