Repository navigation
Expand file tree
/
Copy pathCustomControl1.cs
More file actions
387 lines (326 loc) · 12.8 KB
/
Copy pathCustomControl1.cs
File metadata and controls
387 lines (326 loc) · 12.8 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
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
using Exiled.API.Features;
using Exiled.API.Interfaces;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
namespace WeeklyPlaytime
{
public class WeeklyPlaytime : Plugin<Config>
{
public override string Author => "秋风拂过发梢";
public override string Name => "WeeklyPlaytime";
public override Version Version => new Version(1, 3, 0);
private static readonly string PlaytimeFilePath =
Path.Combine(Paths.Configs, "WeeklyPlaytime", "playtime.csv");
// userId -> (Nickname, PlayTime)
private readonly Dictionary<string, (string Nickname, TimeSpan PlayTime)> _playtimes =
new Dictionary<string, (string, TimeSpan)>();
// userId -> SessionStartUtc
private readonly Dictionary<string, DateTime> _sessionStarts =
new Dictionary<string, DateTime>();
// 线程锁,防止多线程事件同时操作字典
private readonly object _syncRoot = new object();
public override void OnEnabled()
{
try
{
string dir = Path.GetDirectoryName(PlaytimeFilePath);
if (!string.IsNullOrEmpty(dir))
Directory.CreateDirectory(dir);
LoadPlaytimes();
Exiled.Events.Handlers.Player.Verified += OnPlayerVerified;
Exiled.Events.Handlers.Player.Destroying += OnPlayerDestroying;
Exiled.Events.Handlers.Server.RoundEnded += OnRoundEnded;
Log.Info($"作者 {Author}, 插件 {Name} 启动, 版本 {Version}.");
Log.Info($"已加载玩家数据: {_playtimes.Count} 条.");
}
catch (Exception ex)
{
Log.Error($"插件 {Name} 启动时出错: {ex}");
}
}
public override void OnDisabled()
{
try
{
Exiled.Events.Handlers.Player.Verified -= OnPlayerVerified;
Exiled.Events.Handlers.Player.Destroying -= OnPlayerDestroying;
Exiled.Events.Handlers.Server.RoundEnded -= OnRoundEnded;
// 禁用前强制保存一次
SavePlaytimes();
Log.Info($"作者 {Author}, 插件 {Name} 关闭, 版本 {Version}.");
}
catch (Exception ex)
{
Log.Error($"插件 {Name} 关闭时出错: {ex}");
}
}
private void OnPlayerVerified(Exiled.Events.EventArgs.Player.VerifiedEventArgs ev)
{
string userId = ev.Player.UserId;
string nickname = ev.Player.Nickname ?? string.Empty;
lock (_syncRoot)
{
_sessionStarts[userId] = DateTime.UtcNow;
if (_playtimes.TryGetValue(userId, out var existing))
{
// 更新昵称,保留已有时长
_playtimes[userId] = (nickname, existing.PlayTime);
}
else
{
// 新玩家
_playtimes[userId] = (nickname, TimeSpan.Zero);
}
}
}
private void OnPlayerDestroying(Exiled.Events.EventArgs.Player.DestroyingEventArgs ev)
{
UpdatePlaytime(ev.Player.UserId);
// 如果你想玩家下线就立刻写盘,可以打开这一行(但会稍微频繁一点)
// SavePlaytimes();
}
private void OnRoundEnded(Exiled.Events.EventArgs.Server.RoundEndedEventArgs ev)
{
try
{
foreach (var player in Player.List)
{
if (player.IsVerified)
UpdatePlaytime(player.UserId);
}
SavePlaytimes();
}
catch (Exception ex)
{
Log.Error($"回合结束时更新游玩时间失败: {ex}");
}
}
/// <summary>
/// 根据当前时间刷新指定玩家本局时长,并重置 session 起点。
/// </summary>
private void UpdatePlaytime(string userId)
{
DateTime now = DateTime.UtcNow;
lock (_syncRoot)
{
DateTime startTime;
if (!_sessionStarts.TryGetValue(userId, out startTime))
return;
TimeSpan sessionTime = now - startTime;
if (sessionTime < TimeSpan.Zero)
sessionTime = TimeSpan.Zero;
(string Nickname, TimeSpan PlayTime) data;
if (_playtimes.TryGetValue(userId, out data))
{
_playtimes[userId] = (data.Nickname, data.PlayTime + sessionTime);
}
else
{
// 理论上不会出现,防御性处理
_playtimes[userId] = (string.Empty, sessionTime);
}
_sessionStarts[userId] = now;
}
}
private void LoadPlaytimes()
{
if (!File.Exists(PlaytimeFilePath))
return;
try
{
using (var fs = new FileStream(PlaytimeFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var reader = new StreamReader(fs, Encoding.UTF8))
{
int lineNumber = 0;
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
lineNumber++;
if (string.IsNullOrWhiteSpace(line))
continue;
string[] fields = ParseCsvLine(line);
if (fields.Length < 3)
continue;
string userId = fields[0];
string nickname = UnescapeCsvField(fields[1]);
TimeSpan time;
if (!TimeSpan.TryParse(fields[2], out time))
continue;
lock (_syncRoot)
{
_playtimes[userId] = (nickname, time);
}
}
}
}
catch (Exception ex)
{
Log.Error($"加载游戏时间数据失败: {ex}");
}
}
/// <summary>
/// 将当前内存中的 playtime 快照到文件。
/// </summary>
private void SavePlaytimes()
{
Dictionary<string, (string Nickname, TimeSpan PlayTime)> snapshot;
// 先把数据复制一份,避免长时间持锁
lock (_syncRoot)
{
snapshot = _playtimes.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value);
}
try
{
string dir = Path.GetDirectoryName(PlaytimeFilePath);
if (!string.IsNullOrEmpty(dir))
Directory.CreateDirectory(dir);
string tempFilePath = Path.Combine(dir, "playtime_temp.csv");
using (var fs = new FileStream(tempFilePath, FileMode.Create, FileAccess.Write, FileShare.Read))
using (var writer = new StreamWriter(fs, Encoding.UTF8))
{
foreach (var kvp in snapshot)
{
string escapedNickname = EscapeCsvField(kvp.Value.Nickname);
// 使用 "c" 标准 TimeSpan 格式,解析更稳
string timeString = kvp.Value.PlayTime.ToString("c");
writer.WriteLine(string.Format("{0},{1},{2}", kvp.Key, escapedNickname, timeString));
}
}
SafeReplaceFile(tempFilePath, PlaytimeFilePath, maxRetries: 5, retryDelayMs: 300);
}
catch (Exception ex)
{
Log.Error($"保存游戏时间数据失败: {ex}");
}
}
#region CSV helpers
private string EscapeCsvField(string field)
{
if (field == null)
field = string.Empty;
bool needQuotes = field.Contains(",") ||
field.Contains("\"") ||
field.Contains("\n") ||
field.Contains("\r");
if (!needQuotes)
return field;
// 双引号转义为两个双引号
string escaped = field.Replace("\"", "\"\"");
return "\"" + escaped + "\"";
}
private string UnescapeCsvField(string field)
{
if (string.IsNullOrEmpty(field))
return string.Empty;
// 这里不用 ^1,兼容 C# 7
if (field.Length >= 2 && field[0] == '"' && field[field.Length - 1] == '"')
{
field = field.Substring(1, field.Length - 2);
field = field.Replace("\"\"", "\"");
}
return field;
}
/// <summary>
/// 简单 CSV 行解析,支持双引号包裹以及转义双引号。
/// 只需要兼容本插件自己写出的格式即可。
/// </summary>
private string[] ParseCsvLine(string line)
{
List<string> fields = new List<string>();
StringBuilder current = new StringBuilder();
bool inQuotes = false;
for (int i = 0; i < line.Length; i++)
{
char c = line[i];
if (c == '"')
{
if (inQuotes)
{
// 看看是不是转义双引号 ("")
if (i + 1 < line.Length && line[i + 1] == '"')
{
current.Append('"');
i++; // 跳过第二个双引号
}
else
{
// 结束引号
inQuotes = false;
}
}
else
{
// 开始引号
inQuotes = true;
}
}
else if (c == ',' && !inQuotes)
{
// 字段结束
fields.Add(current.ToString());
current.Length = 0;
}
else
{
current.Append(c);
}
}
// 最后一个字段
fields.Add(current.ToString());
return fields.ToArray();
}
#endregion
#region File helpers
private void SafeReplaceFile(string sourceFile, string destinationFile, int maxRetries = 5, int retryDelayMs = 300)
{
int attempt = 0;
bool success = false;
while (attempt < maxRetries && !success)
{
try
{
attempt++;
if (File.Exists(destinationFile))
File.Delete(destinationFile);
File.Move(sourceFile, destinationFile);
success = true;
}
catch (IOException)
{
if (attempt >= maxRetries) break;
Thread.Sleep(retryDelayMs);
}
catch (UnauthorizedAccessException)
{
if (attempt >= maxRetries) break;
Thread.Sleep(retryDelayMs);
}
}
// 清理残留 temp 文件
if (File.Exists(sourceFile))
{
try { File.Delete(sourceFile); }
catch { /* 忽略清理错误 */ }
}
if (!success)
{
Log.Error(string.Format("无法替换游戏时间文件,尝试次数: {0}", maxRetries));
}
}
#endregion
}
public class Config : IConfig
{
[Description("是否启用插件")]
public bool IsEnabled { get; set; } = true;
[Description("调试模式")]
public bool Debug { get; set; } = false;
}
}