| 1 |
<?php |
| 2 |
/** |
| 3 |
* OpenStation — Games Heartbeat sync (PHP). |
| 4 |
* |
| 5 |
* Piggybacks on the WordPress Heartbeat tick — the same channel |
| 6 |
* presence and folder sharing use — to deliver challenge activity |
| 7 |
* to connected users live: a new pending challenge for the |
| 8 |
* recipient, a completed run for the challenger. |
| 9 |
* |
| 10 |
* Wire format. Client sends: |
| 11 |
* |
| 12 |
* { |
| 13 |
* openstation_games_subscribe: { |
| 14 |
* challengesVersion: lastSeenUpdatedAtMs |
| 15 |
* } |
| 16 |
* } |
| 17 |
* |
| 18 |
* Server responds: |
| 19 |
* |
| 20 |
* openstation_games: { |
| 21 |
* challenges: [ <ChallengeShape> ], // rows involving me, |
| 22 |
* // updated_at_ms > version |
| 23 |
* serverTimeMs: int, |
| 24 |
* truncated: bool |
| 25 |
* } |
| 26 |
* |
| 27 |
* Version-gated: a quiet tick carries no rows. Truncation kicks in |
| 28 |
* past `openstation_games_heartbeat_max_rows` (default 50) — the |
| 29 |
* client falls back to `GET /games/challenges` for a full resync. |
| 30 |
* |
| 31 |
* @package OpenStation |
| 32 |
*/ |
| 33 |
|
| 34 |
defined( 'ABSPATH' ) || exit; |
| 35 |
|
| 36 |
/** |
| 37 |
* @param array $response Pre-filtered response. |
| 38 |
* @param array $data Client-sent payload. |
| 39 |
* @return array |
| 40 |
*/ |
| 41 |
function openstation_games_heartbeat_received( $response, $data ) { |
| 42 |
if ( ! is_array( $response ) ) { |
| 43 |
$response = array(); |
| 44 |
} |
| 45 |
if ( empty( $data['openstation_games_subscribe'] ) || ! is_array( $data['openstation_games_subscribe'] ) ) { |
| 46 |
return $response; |
| 47 |
} |
| 48 |
if ( ! function_exists( 'openstation_is_enabled' ) || ! openstation_is_enabled() ) { |
| 49 |
return $response; |
| 50 |
} |
| 51 |
|
| 52 |
$user_id = (int) get_current_user_id(); |
| 53 |
if ( $user_id <= 0 ) { |
| 54 |
return $response; |
| 55 |
} |
| 56 |
|
| 57 |
$sub = $data['openstation_games_subscribe']; |
| 58 |
$version = isset( $sub['challengesVersion'] ) ? (int) $sub['challengesVersion'] : 0; |
| 59 |
|
| 60 |
/** |
| 61 |
* Filter the per-tick challenge row cap. Past the cap the |
| 62 |
* payload is flagged `truncated` and the client resyncs over |
| 63 |
* REST. |
| 64 |
* |
| 65 |
* @param int $cap Default 50. |
| 66 |
*/ |
| 67 |
$cap = max( 1, (int) apply_filters( 'openstation_games_heartbeat_max_rows', 50 ) ); |
| 68 |
|
| 69 |
$rows = openstation_games_get_challenges_for_user( $user_id, $version, $cap + 1 ); |
| 70 |
$truncated = count( $rows ) > $cap; |
| 71 |
if ( $truncated ) { |
| 72 |
$rows = array_slice( $rows, 0, $cap ); |
| 73 |
} |
| 74 |
|
| 75 |
$response['openstation_games'] = array( |
| 76 |
'challenges' => array_map( 'openstation_games_shape_challenge', $rows ), |
| 77 |
'serverTimeMs' => openstation_games_now_ms(), |
| 78 |
'truncated' => $truncated, |
| 79 |
); |
| 80 |
return $response; |
| 81 |
} |
| 82 |
add_filter( 'heartbeat_received', 'openstation_games_heartbeat_received', 5, 2 ); |
| 83 |
|