forked from Talishar/Talishar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetUpdateSSE.php
More file actions
237 lines (205 loc) · 7.61 KB
/
GetUpdateSSE.php
File metadata and controls
237 lines (205 loc) · 7.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
<?php
/**
* GetUpdateSSE.php
*
* Server-Sent Events endpoint that pushes full game state updates directly to clients.
* This eliminates the extra HTTP round-trip that was previously needed to GetNextTurn.php.
*/
ignore_user_abort(false);
include 'Libraries/HTTPLibraries.php';
include "HostFiles/Redirector.php";
include_once "Libraries/SHMOPLibraries.php";
include "Libraries/CacheLibraries.php";
include "WriteLog.php";
include_once "./Assets/patreon-php-master/src/PatreonDictionary.php";
include_once "./Assets/MetafyDictionary.php";
include_once "./AccountFiles/AccountSessionAPI.php";
include_once "includes/dbh.inc.php";
include_once "includes/MetafyHelper.php";
include_once 'GameLogic.php';
include_once "GameTerms.php";
include_once "Libraries/UILibraries.php";
include_once "Libraries/StatFunctions.php";
include_once "Libraries/PlayerSettings.php";
include_once "BuildGameState.php";
include_once "BuildPlayerInputPopup.php";
// Close any buffers that php.ini may have opened (e.g. output_buffering=On).
// Then immediately open our own buffer so every ob_flush() call below is safe.
while (ob_get_level() > 0) {
ob_end_clean();
}
ob_start();
SetHeaders();
$response = new stdClass();
$gameName = $_GET["gameName"];
if (!IsGameNameValid($gameName)) {
echo ("data: " . json_encode(["error" => "Invalid gamename"]) . "\n\n");
ob_flush();
flush();
exit;
}
$playerID = TryGet("playerID", 3);
if (!is_numeric($playerID)) {
echo ("data: " . json_encode(["error" => "Invalid playerID"]) . "\n\n");
ob_flush();
flush();
exit;
}
$authKey = TryGet("authKey", "");
if (($playerID == 1 || $playerID == 2) && $authKey == "") {
if (isset($_COOKIE["lastAuthKey"])) $authKey = $_COOKIE["lastAuthKey"];
}
// Capture session data before setting SSE headers
// This is critical - we must capture and close session BEFORE the long-running SSE loop
$sessionData = [];
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
$sessionData['userLoggedIn'] = IsUserLoggedIn();
$sessionData['userName'] = LoggedInUserName() ?: (TryGet('userName', '') ?: null);
$sessionData['isPvtVoidPatron'] = isset($_SESSION["isPvtVoidPatron"]);
// Capture all Patreon campaign session IDs
$sessionData['patreonCampaigns'] = [];
foreach(PatreonCampaign::cases() as $campaign) {
$sessionID = $campaign->SessionID();
$sessionData['patreonCampaigns'][$sessionID] = isset($_SESSION[$sessionID]);
}
// Load friend list if user is logged in (for friend hand visibility checks)
$sessionData['friendList'] = [];
$friendsListParam = TryGet("friendsList", "");
if (!empty($friendsListParam)) {
try {
$sessionData['friendList'] = json_decode($friendsListParam, true) ?? [];
} catch (Exception $e) {
// friendsList parameter parsing failed
}
}
// Release session lock BEFORE SSE loop to prevent deadlock
if (session_status() === PHP_SESSION_ACTIVE) {
session_write_close();
}
if ($playerID == 3) {
UpdateSpectatorPresence($gameName, $sessionData['userName'] ?? 'Anonymous');
}
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$lastUpdate = 0;
$isGamePlayer = $playerID == 1 || $playerID == 2;
// Typing state tracking — pushed via named SSE event, no polling needed
$lastTypingCheckTime = 0.0;
$typingCheckInterval = 1.5; // seconds between checks
$lastTypingState = false;
// Send initial full game state
$cacheVal = intval(GetCachePiece($gameName, 1));
$lastUpdate = $cacheVal;
$initialState = BuildGameStateResponse($gameName, $playerID, $authKey, $sessionData, true);
if (is_string($initialState)) {
// Error occurred
echo ("data: " . json_encode(["error" => $initialState]) . "\n\n");
ob_flush();
flush();
exit;
}
echo ("data: " . json_encode($initialState) . "\n\n");
ob_flush();
flush();
$sleepMs = 50;
$otherP = $playerID == 1 ? 2 : 1;
$lastFileCheckTime = microtime(true);
$fileCheckInterval = 30.0;
$gameFileExists = true;
$lastConnectionCheck = microtime(true);
$connectionCheckInterval = 2.0;
$lastSpectatorRefresh = microtime(true);
$spectatorRefreshInterval = 30.0;
$rateLimitStartInterval = microtime(true);
$rateLimitProcessCount = 0;
$loopStartTimeMs = round(microtime(true) * 1000);
while (true) {
$currentRealTime = microtime(true);
// Check client connection more frequently to detect refreshes/disconnects
if ($currentRealTime - $lastConnectionCheck >= $connectionCheckInterval) {
if (connection_aborted()) exit;
$lastConnectionCheck = $currentRealTime;
}
if ($playerID == 3 && $currentRealTime - $lastSpectatorRefresh >= $spectatorRefreshInterval) {
UpdateSpectatorPresence($gameName, $sessionData['userName'] ?? 'Anonymous');
$lastSpectatorRefresh = $currentRealTime;
}
$cacheStr = GetCachePiece($gameName, 1);
$lastUpdateTime = GetCachePiece($gameName, 6);
// Check if game file still exists
if ($currentRealTime - $lastFileCheckTime >= $fileCheckInterval || $lastUpdateTime == "" || $cacheStr === "") {
if (!file_exists("./Games/" . $gameName . "/GameFile.txt")) {
SendContent(["error" => "Game no longer exists"]);
exit;
}
$lastFileCheckTime = $currentRealTime;
}
// Check if game is over (status 99)
$gameStatus = intval(GetCachePiece($gameName, 14));
if ($gameStatus == 99) {
// Send final state before exiting
$finalState = BuildGameStateResponse($gameName, $playerID, $authKey, $sessionData, false);
if (!is_string($finalState)) {
SendContent($finalState);
}
exit;
}
// Check for game state updates
$cacheVal = intval($cacheStr);
$timeout = 60 * 1000; //seconds
$inactive = 1000 * $currentRealTime - intval($lastUpdateTime) > $timeout;
$previouslyInactive = GetCachePiece($gameName, 17);
if ($cacheVal > $lastUpdate || $inactive && $previouslyInactive == 0) {
error_log("Time3: " . 1000 * $currentRealTime - intval($lastUpdateTime));
$lastUpdate = $cacheVal;
if ($inactive) SetCachePiece($gameName, 17, 1);
else SetCachePiece($gameName, 17, 0);
// Build and send full game state
$gameState = BuildGameStateResponse($gameName, $playerID, $authKey, $sessionData, false, $inactive);
if (is_string($gameState)) {
SendContent(["error" => $gameState]);
exit;
}
SendContent($gameState);
set_time_limit(120);
}
// Push typing state as a named SSE event so the frontend can update without
// any polling. Checks every $typingCheckInterval seconds; only emits when
// the state actually changes — zero cost for games where nobody is typing.
if ($isGamePlayer && ($currentRealTime - $lastTypingCheckTime >= $typingCheckInterval)) {
$lastTypingCheckTime = $currentRealTime;
$typingCacheKey = "typing_" . md5($gameName) . "_player_" . $otherP;
$opponentIsTyping = false;
if (extension_loaded('apcu') && ini_get('apc.enabled')) {
$opponentIsTyping = @apcu_fetch($typingCacheKey) !== false;
}
if ($opponentIsTyping !== $lastTypingState) {
$lastTypingState = $opponentIsTyping;
echo "event: typing\n";
echo "data: " . json_encode(["opponentIsTyping" => $opponentIsTyping]) . "\n\n";
ob_flush();
flush();
}
}
usleep(intval($sleepMs * 1000));
}
function SendContent($jsonContent) {
global $rateLimitStartInterval, $rateLimitProcessCount;
$currentRealTime = microtime(true);
if($currentRealTime - $rateLimitStartInterval > 1.0) {
// Reset rate limit counters every second
$rateLimitStartInterval = $currentRealTime;
$rateLimitProcessCount = 0;
} else {
$rateLimitProcessCount++;
if($rateLimitProcessCount > 5) {
SendContent(["error" => "Too many game updates in last second. A likely logic error has occurred."]);
exit;
}
}
echo ("data: " . json_encode($jsonContent) . "\n\n");
ob_flush();
flush();
}