Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : * This file is part of 0 A.D.
3 : *
4 : * 0 A.D. is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 2 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * 0 A.D. is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 : */
17 :
18 : #include "precompiled.h"
19 :
20 : #include "VisualReplay.h"
21 :
22 : #include "lib/code_generation.h"
23 : #include "lib/debug.h"
24 : #include "lib/file/file_system.h"
25 : #include "lib/path.h"
26 : #include "lib/posix/posix_types.h"
27 : #include "lib/status.h"
28 : #include "lib/sysdep/filesystem.h"
29 : #include "network/NetClient.h"
30 : #include "network/NetServer.h"
31 : #include "ps/CLogger.h"
32 : #include "ps/CStr.h"
33 : #include "ps/Game.h"
34 : #include "ps/GameSetup/CmdLineArgs.h"
35 : #include "ps/GameSetup/Paths.h"
36 : #include "ps/Profiler2.h"
37 : #include "ps/Pyrogenesis.h"
38 : #include "scriptinterface/JSON.h"
39 : #include "scriptinterface/Object.h"
40 : #include "scriptinterface/Request.h"
41 :
42 : #include <SDL_events.h>
43 : #include <SDL_quit.h>
44 : #include <filesystem>
45 : #include <fstream>
46 : #include <iterator>
47 : #include <js/Array.h>
48 : #include <js/PropertyAndElement.h>
49 : #include <js/RootingAPI.h>
50 : #include <js/Value.h>
51 : #include <map>
52 : #include <string>
53 : #include <system_error>
54 : #include <tuple>
55 : #include <utility>
56 : #include <vector>
57 :
58 : /**
59 : * Filter too short replays (value in seconds).
60 : */
61 : const std::uint8_t minimumReplayDuration = 3;
62 :
63 0 : OsPath VisualReplay::GetDirectoryPath()
64 : {
65 0 : return Paths(g_CmdLineArgs).UserData() / "replays" / PS_SERIALIZATION_VERSION;
66 : }
67 :
68 0 : OsPath VisualReplay::GetCacheFilePath()
69 : {
70 0 : return GetDirectoryPath() / L"replayCache.json";
71 : }
72 :
73 0 : OsPath VisualReplay::GetTempCacheFilePath()
74 : {
75 0 : return GetDirectoryPath() / L"replayCache_temp.json";
76 : }
77 :
78 0 : bool VisualReplay::StartVisualReplay(const OsPath& directory)
79 : {
80 0 : ENSURE(!g_NetServer);
81 0 : ENSURE(!g_NetClient);
82 0 : ENSURE(!g_Game);
83 :
84 0 : const OsPath replayFile = VisualReplay::GetDirectoryPath() / directory / L"commands.txt";
85 :
86 0 : if (!std::filesystem::is_regular_file(replayFile.string()))
87 : return false;
88 :
89 0 : g_Game = new CGame(false);
90 0 : return g_Game->StartVisualReplay(replayFile);
91 : }
92 :
93 0 : bool VisualReplay::ReadCacheFile(const Script::Interface& scriptInterface, JS::MutableHandleObject cachedReplaysObject)
94 : {
95 0 : if (!std::filesystem::is_regular_file(GetCacheFilePath().string()))
96 : return false;
97 :
98 0 : std::ifstream cacheStream(OsString(GetCacheFilePath()));
99 0 : CStr cacheStr((std::istreambuf_iterator<char>(cacheStream)), std::istreambuf_iterator<char>());
100 0 : cacheStream.close();
101 :
102 0 : Script::Request rq(scriptInterface);
103 :
104 0 : JS::RootedValue cachedReplays(rq.cx);
105 0 : if (Script::ParseJSON(rq, cacheStr, &cachedReplays))
106 : {
107 0 : cachedReplaysObject.set(&cachedReplays.toObject());
108 0 : bool isArray;
109 0 : if (JS::IsArrayObject(rq.cx, cachedReplaysObject, &isArray) && isArray)
110 0 : return true;
111 : }
112 :
113 0 : LOGWARNING("The replay cache file is corrupted, it will be deleted");
114 0 : std::error_code ec{};
115 0 : std::filesystem::remove(GetCacheFilePath().string(), ec);
116 0 : return false;
117 0 : }
118 :
119 0 : void VisualReplay::StoreCacheFile(const Script::Interface& scriptInterface, JS::HandleObject replays)
120 : {
121 0 : Script::Request rq(scriptInterface);
122 :
123 0 : JS::RootedValue replaysRooted(rq.cx, JS::ObjectValue(*replays));
124 0 : std::ofstream cacheStream(OsString(GetTempCacheFilePath()), std::ofstream::out | std::ofstream::trunc);
125 0 : cacheStream << Script::StringifyJSON(rq, &replaysRooted);
126 0 : cacheStream.close();
127 :
128 0 : std::error_code ec{};
129 0 : std::filesystem::remove(GetCacheFilePath().string(), ec);
130 0 : if (RenameFile(GetTempCacheFilePath(), GetCacheFilePath()))
131 0 : LOGERROR("Could not store the replay cache");
132 0 : }
133 :
134 0 : JS::HandleObject VisualReplay::ReloadReplayCache(const Script::Interface& scriptInterface, bool compareFiles)
135 : {
136 0 : PROFILE2("ReloadReplayCache");
137 0 : Script::Request rq(scriptInterface);
138 :
139 : // Maps the filename onto the index, mtime and size
140 0 : using replayCacheMap = std::map<OsPath, std::tuple<std::uint32_t, std::uint64_t, off_t>>;
141 :
142 0 : replayCacheMap fileList;
143 :
144 0 : JS::RootedObject cachedReplaysObject(rq.cx);
145 0 : if (ReadCacheFile(scriptInterface, &cachedReplaysObject))
146 : {
147 : // Create list of files included in the cache
148 0 : std::uint32_t cacheLength = 0;
149 0 : JS::GetArrayLength(rq.cx, cachedReplaysObject, &cacheLength);
150 0 : for (std::uint32_t j = 0; j < cacheLength; ++j)
151 : {
152 0 : JS::RootedValue replay(rq.cx);
153 0 : JS_GetElement(rq.cx, cachedReplaysObject, j, &replay);
154 :
155 0 : JS::RootedValue file(rq.cx);
156 0 : OsPath fileName;
157 0 : double fileSize{0};
158 0 : double fileMtime{0};
159 0 : Script::GetProperty(rq, replay, "directory", fileName);
160 0 : Script::GetProperty(rq, replay, "fileSize", fileSize);
161 0 : Script::GetProperty(rq, replay, "fileMTime", fileMtime);
162 :
163 0 : fileList[fileName] = std::make_tuple(j, fileMtime, fileSize);
164 0 : }
165 : }
166 :
167 0 : JS::RootedObject replays(rq.cx, JS::NewArrayObject(rq.cx, 0));
168 0 : DirectoryNames directories;
169 :
170 0 : if (GetDirectoryEntries(GetDirectoryPath(), nullptr, &directories) != INFO::OK)
171 0 : return replays;
172 :
173 0 : bool newReplays = false;
174 0 : std::vector<std::uint32_t> copyFromOldCache;
175 : // Specifies where the next replay should be kept
176 0 : std::uint32_t i = 0;
177 :
178 0 : for (const OsPath& directory : directories)
179 : {
180 : // This cannot use IsQuitRequested(), because the current loop and that function both run in the main thread.
181 : // So SDL events are not processed unless called explicitly here.
182 0 : if (SDL_QuitRequested())
183 : // Don't return, because we want to save our progress
184 : break;
185 :
186 0 : const OsPath replayFile = GetDirectoryPath() / directory / L"commands.txt";
187 :
188 0 : bool isNew = true;
189 0 : replayCacheMap::iterator it = fileList.find(directory);
190 0 : if (it != fileList.end())
191 : {
192 0 : if (compareFiles)
193 : {
194 0 : if (!std::filesystem::is_regular_file(replayFile.string()))
195 0 : continue;
196 0 : CFileInfo fileInfo;
197 0 : GetFileInfo(replayFile, &fileInfo);
198 0 : if (static_cast<std::uint64_t>(fileInfo.MTime()) == std::get<1>(it->second) &&
199 0 : (off_t)fileInfo.Size() == std::get<2>(it->second))
200 : {
201 : isNew = false;
202 : }
203 0 : }
204 : else
205 : isNew = false;
206 : }
207 :
208 0 : if (isNew)
209 : {
210 0 : JS::RootedValue replayData(rq.cx, LoadReplayData(scriptInterface, directory));
211 0 : if (replayData.isNull())
212 : {
213 0 : if (!std::filesystem::is_regular_file(replayFile.string()))
214 0 : continue;
215 0 : CFileInfo fileInfo;
216 0 : GetFileInfo(replayFile, &fileInfo);
217 :
218 0 : Script::CreateObject(
219 : rq,
220 : &replayData,
221 0 : "directory", directory.string(),
222 0 : "fileMTime", static_cast<double>(fileInfo.MTime()),
223 0 : "fileSize", static_cast<double>(fileInfo.Size()));
224 0 : }
225 0 : JS_SetElement(rq.cx, replays, i++, replayData);
226 0 : newReplays = true;
227 0 : }
228 : else
229 0 : copyFromOldCache.push_back(std::get<0>(it->second));
230 0 : }
231 :
232 0 : debug_printf(
233 : "Loading %lu cached replays, removed %lu outdated entries, loaded %i new entries\n",
234 0 : (unsigned long)fileList.size(), (unsigned long)(fileList.size() - copyFromOldCache.size()), i);
235 :
236 0 : if (!newReplays && fileList.empty())
237 0 : return replays;
238 :
239 : // No replay was changed, so just return the cache
240 0 : if (!newReplays && fileList.size() == copyFromOldCache.size())
241 0 : return cachedReplaysObject;
242 :
243 0 : {
244 : // Copy the replays from the old cache that are not deleted
245 0 : if (!copyFromOldCache.empty())
246 0 : for (std::uint32_t j : copyFromOldCache)
247 : {
248 0 : JS::RootedValue replay(rq.cx);
249 0 : JS_GetElement(rq.cx, cachedReplaysObject, j, &replay);
250 0 : JS_SetElement(rq.cx, replays, i++, replay);
251 0 : }
252 : }
253 0 : StoreCacheFile(scriptInterface, replays);
254 0 : return replays;
255 0 : }
256 :
257 0 : JS::Value VisualReplay::GetReplays(const Script::Interface& scriptInterface, bool compareFiles)
258 : {
259 0 : PROFILE2("GetReplays");
260 :
261 0 : Script::Request rq(scriptInterface);
262 0 : JS::RootedObject replays(rq.cx, ReloadReplayCache(scriptInterface, compareFiles));
263 : // Only take entries with data
264 0 : JS::RootedValueVector replaysWithoutNullEntries{rq.cx};
265 :
266 0 : std::uint32_t replaysLength = 0;
267 0 : JS::GetArrayLength(rq.cx, replays, &replaysLength);
268 0 : for (std::uint32_t j = 0; j < replaysLength; ++j)
269 : {
270 0 : JS::RootedValue replay(rq.cx);
271 0 : JS_GetElement(rq.cx, replays, j, &replay);
272 0 : if (!Script::HasProperty(rq, replay, "attribs"))
273 0 : continue;
274 0 : if (!replaysWithoutNullEntries.append(replay))
275 0 : throw std::runtime_error{"Append failed"};
276 0 : }
277 0 : return JS::ObjectValue(*JS::NewArrayObject(rq.cx, replaysWithoutNullEntries));
278 0 : }
279 :
280 : /**
281 : * Move the cursor backwards until a newline was read or the beginning of the file was found.
282 : * Either way the cursor points to the beginning of a newline.
283 : *
284 : * @return The current cursor position or -1 on error.
285 : */
286 0 : inline off_t goBackToLineBeginning(std::istream* replayStream, const OsPath& fileName, off_t fileSize)
287 : {
288 0 : int currentPos;
289 0 : char character;
290 0 : for (int characters = 0; characters < 10000; ++characters)
291 : {
292 0 : currentPos = (int) replayStream->tellg();
293 :
294 : // Stop when reached the beginning of the file
295 0 : if (currentPos == 0)
296 : return currentPos;
297 :
298 0 : if (!replayStream->good())
299 : {
300 0 : LOGERROR("Unknown error when returning to the last line ({} of {}) of {}", currentPos,
301 : fileSize, fileName.string8());
302 0 : return -1;
303 : }
304 :
305 : // Stop when reached newline
306 0 : replayStream->get(character);
307 0 : if (character == '\n')
308 0 : return currentPos;
309 :
310 : // Otherwise go back one character.
311 : // Notice: -1 will set the cursor back to the most recently read character.
312 0 : replayStream->seekg(-2, std::ios_base::cur);
313 : }
314 :
315 0 : LOGERROR("Infinite loop when going back to a line beginning in {}", fileName.string8());
316 0 : return -1;
317 : }
318 :
319 : /**
320 : * Compute game duration in seconds. Assume constant turn length.
321 : * Find the last line that starts with "turn" by reading the file backwards.
322 : *
323 : * @return seconds or -1 on error
324 : */
325 0 : inline int getReplayDuration(std::istream* replayStream, const OsPath& fileName, off_t fileSize)
326 : {
327 0 : CStr type;
328 :
329 : // Move one character before the file-end
330 0 : replayStream->seekg(-2, std::ios_base::end);
331 :
332 : // Infinite loop protection, should never occur.
333 : // There should be about 5 lines to read until a turn is found.
334 0 : for (int linesRead = 1; linesRead < 1000; ++linesRead)
335 : {
336 0 : off_t currentPosition = goBackToLineBeginning(replayStream, fileName, fileSize);
337 :
338 : // Read error or reached file beginning. No turns exist.
339 0 : if (currentPosition < 1)
340 : return -1;
341 :
342 0 : if (!replayStream->good())
343 : {
344 0 : LOGERROR("Read error when determining replay duration at {} of {} in {}",
345 : currentPosition - 2, fileSize, fileName.string8());
346 0 : return -1;
347 : }
348 :
349 : // Found last turn, compute duration.
350 0 : if (currentPosition + 4 < fileSize && (*replayStream >> type).good() && type == "turn")
351 : {
352 0 : std::uint32_t turn = 0, turnLength = 0;
353 0 : *replayStream >> turn >> turnLength;
354 0 : return (turn+1) * turnLength / 1000; // add +1 as turn numbers starts with 0
355 : }
356 :
357 : // Otherwise move cursor back to the character before the last newline
358 0 : replayStream->seekg(currentPosition - 2, std::ios_base::beg);
359 : }
360 :
361 0 : LOGERROR("Infinite loop when determining replay duration for {}", fileName.string8());
362 0 : return -1;
363 0 : }
364 :
365 0 : JS::Value VisualReplay::LoadReplayData(const Script::Interface& scriptInterface, const OsPath& directory)
366 : {
367 : // The directory argument must not be constant, otherwise concatenating will fail
368 0 : const OsPath replayFile = GetDirectoryPath() / directory / L"commands.txt";
369 :
370 0 : if (!std::filesystem::is_regular_file(replayFile.string()))
371 0 : return JS::NullValue();
372 :
373 : // Get file size and modification date
374 0 : CFileInfo fileInfo;
375 0 : GetFileInfo(replayFile, &fileInfo);
376 0 : const off_t fileSize = fileInfo.Size();
377 :
378 0 : if (fileSize == 0)
379 0 : return JS::NullValue();
380 :
381 0 : std::ifstream* replayStream = new std::ifstream(OsString(replayFile));
382 :
383 0 : CStr type;
384 0 : if (!(*replayStream >> type).good())
385 : {
386 0 : LOGERROR("Couldn't open {}.", replayFile.string8());
387 0 : SAFE_DELETE(replayStream);
388 0 : return JS::NullValue();
389 : }
390 :
391 0 : if (type != "start")
392 : {
393 0 : LOGWARNING("The replay {} doesn't begin with 'start'!", replayFile.string8());
394 0 : SAFE_DELETE(replayStream);
395 0 : return JS::NullValue();
396 : }
397 :
398 : // Parse header / first line
399 0 : CStr header;
400 0 : std::getline(*replayStream, header);
401 0 : Script::Request rq(scriptInterface);
402 0 : JS::RootedValue attribs(rq.cx);
403 0 : if (!Script::ParseJSON(rq, header, &attribs))
404 : {
405 0 : LOGERROR("Couldn't parse replay header of {}", replayFile.string8());
406 0 : SAFE_DELETE(replayStream);
407 0 : return JS::NullValue();
408 : }
409 :
410 : // Ensure "turn" after header
411 0 : if (!(*replayStream >> type).good() || type != "turn")
412 : {
413 0 : SAFE_DELETE(replayStream);
414 0 : return JS::NullValue(); // there are no turns at all
415 : }
416 :
417 : // Don't process files of rejoined clients
418 0 : std::uint32_t turn = 1;
419 0 : *replayStream >> turn;
420 0 : if (turn != 0)
421 : {
422 0 : SAFE_DELETE(replayStream);
423 0 : return JS::NullValue();
424 : }
425 :
426 0 : int duration = getReplayDuration(replayStream, replayFile, fileSize);
427 :
428 0 : SAFE_DELETE(replayStream);
429 :
430 : // Ensure minimum duration
431 0 : if (duration < minimumReplayDuration)
432 0 : return JS::NullValue();
433 :
434 : // Return the actual data
435 0 : JS::RootedValue replayData(rq.cx);
436 :
437 0 : Script::CreateObject(
438 : rq,
439 : &replayData,
440 0 : "directory", directory.string(),
441 0 : "fileSize", static_cast<double>(fileSize),
442 0 : "fileMTime", static_cast<double>(fileInfo.MTime()),
443 : "duration", duration);
444 :
445 0 : Script::SetProperty(rq, replayData, "attribs", attribs);
446 :
447 0 : return replayData;
448 0 : }
449 :
450 0 : bool VisualReplay::DeleteReplay(const OsPath& replayDirectory)
451 : {
452 0 : if (replayDirectory.empty())
453 : return false;
454 :
455 0 : const OsPath directory = GetDirectoryPath() / replayDirectory;
456 0 : return DirectoryExists(directory) && DeleteDirectory(directory) == INFO::OK;
457 0 : }
458 :
459 0 : JS::Value VisualReplay::GetReplayAttributes(const Script::Interface& scriptInterface, const OsPath& directoryName)
460 : {
461 : // Create empty JS object
462 0 : Script::Request rq(scriptInterface);
463 0 : JS::RootedValue attribs(rq.cx);
464 0 : Script::CreateObject(rq, &attribs);
465 :
466 : // Return empty object if file doesn't exist
467 0 : const OsPath replayFile = GetDirectoryPath() / directoryName / L"commands.txt";
468 0 : if (!std::filesystem::is_regular_file(replayFile.string()))
469 0 : return attribs;
470 :
471 : // Open file
472 0 : std::istream* replayStream = new std::ifstream(OsString(replayFile));
473 0 : CStr type, line;
474 0 : ENSURE((*replayStream >> type).good() && type == "start");
475 :
476 : // Read and return first line
477 0 : std::getline(*replayStream, line);
478 0 : Script::ParseJSON(rq, line, &attribs);
479 0 : SAFE_DELETE(replayStream);;
480 0 : return attribs;
481 0 : }
482 :
483 0 : void VisualReplay::AddReplayToCache(const Script::Interface& scriptInterface, const CStrW& directoryName)
484 : {
485 0 : PROFILE2("AddReplayToCache");
486 0 : Script::Request rq(scriptInterface);
487 :
488 0 : JS::RootedValue replayData(rq.cx, LoadReplayData(scriptInterface, OsPath(directoryName)));
489 0 : if (replayData.isNull())
490 0 : return;
491 :
492 0 : JS::RootedObject cachedReplaysObject(rq.cx);
493 0 : if (!ReadCacheFile(scriptInterface, &cachedReplaysObject))
494 0 : cachedReplaysObject = JS::NewArrayObject(rq.cx, 0);
495 :
496 0 : std::uint32_t cacheLength = 0;
497 0 : JS::GetArrayLength(rq.cx, cachedReplaysObject, &cacheLength);
498 0 : JS_SetElement(rq.cx, cachedReplaysObject, cacheLength, replayData);
499 :
500 0 : StoreCacheFile(scriptInterface, cachedReplaysObject);
501 0 : }
502 :
503 0 : bool VisualReplay::HasReplayMetadata(const OsPath& directoryName)
504 : {
505 0 : const OsPath filePath(GetDirectoryPath() / directoryName / L"metadata.json");
506 :
507 0 : if (!std::filesystem::is_regular_file(filePath.string()))
508 : return false;
509 :
510 0 : CFileInfo fileInfo;
511 0 : GetFileInfo(filePath, &fileInfo);
512 :
513 0 : return fileInfo.Size() > 0;
514 0 : }
515 :
516 0 : JS::Value VisualReplay::GetReplayMetadata(const Script::Interface& scriptInterface, const OsPath& directoryName)
517 : {
518 0 : if (!HasReplayMetadata(directoryName))
519 0 : return JS::NullValue();
520 :
521 0 : Script::Request rq(scriptInterface);
522 0 : JS::RootedValue metadata(rq.cx);
523 :
524 0 : std::ifstream* stream = new std::ifstream(OsString(GetDirectoryPath() / directoryName / L"metadata.json"));
525 0 : ENSURE(stream->good());
526 0 : CStr line;
527 0 : std::getline(*stream, line);
528 0 : stream->close();
529 0 : SAFE_DELETE(stream);
530 0 : Script::ParseJSON(rq, line, &metadata);
531 :
532 0 : return metadata;
533 0 : }
|