-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BackupManagement.cs
269 lines (242 loc) · 12.3 KB
/
BackupManagement.cs
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Modules.Commands;
using CounterStrikeSharp.API.Modules.Utils;
using CounterStrikeSharp.API.Core.Attributes.Registration;
using CounterStrikeSharp.API.Modules.Timers;
using System.Text.Json;
namespace MatchZy
{
public partial class MatchZy
{
public bool isStopCommandAvailable = true;
public bool pauseAfterRoundRestore = true;
public string lastBackupFileName = "";
public bool isRoundRestoring = false;
public Dictionary<string, bool> stopData = new Dictionary<string, bool> {
{ "ct", false },
{ "t", false }
};
public void SetupRoundBackupFile() {
string backupFilePrefix = $"matchzy_{liveMatchId}_{matchConfig.CurrentMapNumber}";
Server.ExecuteCommand($"mp_backup_round_file {backupFilePrefix}");
}
[ConsoleCommand("css_stop", "Restore the backup of the current round (Both teams need to type .stop to restore the current round)")]
public void OnStopCommand(CCSPlayerController? player, CommandInfo? command) {
if (player == null) return;
Log($"[!stop command] Sent by: {player.UserId}, TeamNum: {player.TeamNum}, connectedPlayers: {connectedPlayers}");
if (isStopCommandAvailable && isMatchLive) {
if (IsHalfTimePhase())
{
ReplyToUserCommand(player, "你不能使用这个指令在半场.");
return;
}
if (IsPostGamePhase())
{
ReplyToUserCommand(player, "你不能使用这个指令在游戏结束后.");
return;
}
if (IsTacticalTimeoutActive())
{
ReplyToUserCommand(player, "你不能使用这个指令在技术暂停中.");
return;
}
string stopTeamName = "";
string remainingStopTeam = "";
if (player.TeamNum == 2) {
stopTeamName = reverseTeamSides["TERRORIST"].teamName;
remainingStopTeam = reverseTeamSides["CT"].teamName;
if (!stopData["t"]) {
stopData["t"] = true;
}
} else if (player.TeamNum == 3) {
stopTeamName = reverseTeamSides["CT"].teamName;
remainingStopTeam = reverseTeamSides["TERRORIST"].teamName;
if (!stopData["ct"]) {
stopData["ct"] = true;
}
} else {
return;
}
if (stopData["t"] && stopData["ct"]) {
if (lastBackupFileName != "") {
RestoreRoundBackup(player, lastBackupFileName);
} else {
// This should not happen, lastBackupFileName should not be empty in a live game!
Log($"[OnStopCommand] lastBackupFileName not found, unable to restore round!");
}
} else {
Server.PrintToChatAll($"{chatPrefix} {ChatColors.Green}{stopTeamName}{ChatColors.Default} 想要将游戏回溯到当前回合的开始 {ChatColors.Green}{remainingStopTeam}{ChatColors.Default}, 可输入 !stop 同意.");
}
}
}
[ConsoleCommand("css_restore", "Restores the specified round")]
public void OnRestoreCommand(CCSPlayerController? player, CommandInfo command) {
if (IsPlayerAdmin(player, "css_restore", "@css/config")) {
if (command.ArgCount >= 2) {
string commandArg = command.ArgByIndex(1);
HandleRestoreCommand(player, commandArg);
}
else {
ReplyToUserCommand(player, $"请使用: !restore <回合数>");
}
} else {
SendPlayerNotAdminMessage(player);
}
}
private void HandleRestoreCommand(CCSPlayerController? player, string commandArg) {
if (!IsPlayerAdmin(player, "css_restore", "@css/config")) {
SendPlayerNotAdminMessage(player);
return;
}
if (!isMatchLive) return;
if (!string.IsNullOrWhiteSpace(commandArg)) {
if (int.TryParse(commandArg, out int roundNumber) && roundNumber >= 0) {
string round = roundNumber.ToString("D2");
string requiredBackupFileName = $"matchzy_{liveMatchId}_{matchConfig.CurrentMapNumber}_round{round}.txt";
RestoreRoundBackup(player, requiredBackupFileName, round);
}
else {
ReplyToUserCommand(player, $"回合数数值无效,请指定一个有效的非负数。 请使用: !restore <回合数>");
}
}
else {
ReplyToUserCommand(player, $"请使用: !restore <回合数>");
}
}
private void RestoreRoundBackup(CCSPlayerController? player, string fileName, string round="") {
if (IsHalfTimePhase())
{
ReplyToUserCommand(player, "您不能在半场时加载备份.");
return;
}
if (IsPostGamePhase())
{
ReplyToUserCommand(player, "您不能在游戏结束后时加载备份.");
return;
}
if (IsTacticalTimeoutActive())
{
ReplyToUserCommand(player, "您不能在战术暂停时加载备份.");
return;
}
if (!File.Exists(Path.Join(Server.GameDirectory + "/csgo/", fileName))) {
ReplyToUserCommand(player, $"备份文件 {fileName} 不存在, 请确保您正在还原有效的备份.");
return;
}
var gameRules = Utilities.FindAllEntitiesByDesignerName<CCSGameRulesProxy>("cs_gamerules").First().GameRules!;
// We set active timeouts to false so that timeout does not start after the round has been restored.
// This is to prevent any buggish behaviour with timeouts (like incorrect timeout used showing, or force-unpausing the match once timeout ends)
gameRules.CTTimeOutActive = gameRules.TerroristTimeOutActive = false;
Server.ExecuteCommand($"mp_backup_restore_load_file {fileName}");
(int t1score, int t2score) = GetTeamsScore();
if (round == "") {
round = (t1score + t2score).ToString("D2");
}
string matchZyBackupFileName = $"matchzy_data_backup_{liveMatchId}_{matchConfig.CurrentMapNumber}_round_{round}.json";
string filePath = Server.GameDirectory + "/csgo/MatchZyDataBackup/" + matchZyBackupFileName;
if (File.Exists(filePath)) {
Dictionary<string, string> backupData = new();
try {
using (StreamReader fileReader = File.OpenText(filePath)) {
string jsonContent = fileReader.ReadToEnd();
if (!string.IsNullOrEmpty(jsonContent)) {
JsonSerializerOptions options = new()
{
AllowTrailingCommas = true,
};
backupData = JsonSerializer.Deserialize<Dictionary<string, string>>(jsonContent, options) ?? new Dictionary<string, string>();
}
else {
// Handle the case where the JSON content is empty or null
backupData = new Dictionary<string, string>();
}
}
isRoundRestoring = true;
foreach (var kvp in backupData) {
if (kvp.Key == "team1_side") {
// This means round is being restored after sides were swapped, hence we swap sides in our records as well!
if (kvp.Value == "CT" && teamSides[matchzyTeam1] != "CT") {
SwapSidesInTeamData(false);
} else if (kvp.Value == "TERRORIST" && teamSides[matchzyTeam1] != "TERRORIST") {
SwapSidesInTeamData(false);
}
// Server.ExecuteCommand($"mp_teamname_1 {matchzyTeam1.teamName}");
// Server.ExecuteCommand($"mp_teamname_2 {matchzyTeam2.teamName}");
}
if (kvp.Key == "TerroristTimeOuts")
{
gameRules.TerroristTimeOuts = int.Parse(kvp.Value);
}
if (kvp.Key == "CTTimeOuts")
{
gameRules.CTTimeOuts = int.Parse(kvp.Value);
}
}
}
catch (Exception e) {
Log($"[RestoreRoundBackup FATAL] An error occurred: {e.Message}");
}
}
else {
Log($"[RestoreRoundBackup FATAL] Required backup data file does not exist! File: {filePath}");
}
Server.PrintToChatAll($"{chatPrefix} 备份文件恢复成功 文件名: {fileName}");
if (pauseAfterRoundRestore) {
Server.ExecuteCommand("mp_pause_match;");
stopData["ct"] = false;
stopData["t"] = false;
isPaused = true;
unpauseData["pauseTeam"] = "RoundRestore";
if (pausedStateTimer == null) {
pausedStateTimer = AddTimer(chatTimerDelay, SendPausedStateMessage, TimerFlags.REPEAT);
}
}
}
public void CreateMatchZyRoundDataBackup()
{
if (!isMatchLive) return;
try
{
(int t1score, int t2score) = GetTeamsScore();
string round = (t1score + t2score).ToString("D2");
string matchZyBackupFileName = $"matchzy_data_backup_{liveMatchId}_{matchConfig.CurrentMapNumber}_round_{round}.json";
string filePath = Server.GameDirectory + "/csgo/MatchZyDataBackup/" + matchZyBackupFileName;
string? directoryPath = Path.GetDirectoryName(filePath);
if (directoryPath != null)
{
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
}
var gameRules = Utilities.FindAllEntitiesByDesignerName<CCSGameRulesProxy>("cs_gamerules").First().GameRules!;
Dictionary<string, string> roundData = new()
{
{ "matchid", liveMatchId.ToString() },
{ "mapnumber", matchConfig.CurrentMapNumber.ToString() },
{ "team1_name", matchzyTeam1.teamName },
{ "team1_flag", matchzyTeam1.teamFlag },
{ "team1_tag", matchzyTeam1.teamTag },
{ "team1_side", teamSides[matchzyTeam1] },
{ "team2_name", matchzyTeam2.teamName },
{ "team2_flag", matchzyTeam2.teamFlag },
{ "team2_tag", matchzyTeam2.teamTag },
{ "team2_side", teamSides[matchzyTeam2] },
{ "TerroristTimeOuts", gameRules.TerroristTimeOuts.ToString()},
{ "CTTimeOuts", gameRules.CTTimeOuts.ToString() },
};
JsonSerializerOptions options = new()
{
WriteIndented = true,
};
string defaultJson = JsonSerializer.Serialize(roundData, options);
File.WriteAllText(filePath, defaultJson);
}
catch (Exception e)
{
Log($"[CreateMatchZyRoundDataBackup FATAL] Error creating the JSON file: {e.Message}");
}
}
}
}