-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathDataStore.cs
More file actions
293 lines (253 loc) · 8.88 KB
/
DataStore.cs
File metadata and controls
293 lines (253 loc) · 8.88 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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Backtrace.Unity.Common;
using Il2CppSystem.Linq;
using ProjectM;
using ProjectM.Network;
using Unity.Collections;
using Unity.Mathematics;
using UnityEngine.Jobs;
using Random = System.Random;
namespace Killfeed;
public class DataStore
{
public record struct PlayerStatistics(ulong SteamId, string LastName, int Kills, int Deaths, int CurrentStreak,
int HighestStreak, string LastClanName, int CurrentLevel, int MaxLevel)
{
// lol yikes
private static string SafeCSVName(string s) => s.Replace(",", "");
public string ToCsv() => $"{SteamId},{SafeCSVName(LastName)},{Kills},{Deaths},{CurrentStreak},{HighestStreak},{SafeCSVName(LastClanName)},{CurrentLevel},{MaxLevel}";
public static PlayerStatistics Parse(string csv)
{
// intentionally naieve and going to blow up so I'll catch it and not get an object for that player and log it
var split = csv.Split(',');
return new PlayerStatistics()
{
SteamId = ulong.Parse(split[0]),
LastName = split[1],
Kills = int.Parse(split[2]),
Deaths = int.Parse(split[3]),
CurrentStreak = int.Parse(split[4]),
HighestStreak = int.Parse(split[5]),
LastClanName = split.Length > 6 ? split[6] : "",
CurrentLevel = split.Length > 7 ? int.Parse(split[7]) : -1,
MaxLevel = split.Length > 8 ? int.Parse(split[8]) : -1
};
}
public string FormattedName
{
get
{
var name = Markup.Highlight(LastName);
if (Settings.IncludeLevel)
{
return Settings.UseMaxLevel ? $"{name} ({Markup.Secondary(MaxLevel)}*)" : $"{name} ({Markup.Secondary(CurrentLevel)})";
}
else
{
return $"{name}";
}
}
}
}
public record struct EventData(ulong VictimId, ulong KillerId, float3 Location, long Timestamp, int VictimLevel, int KillerLevel)
{
public string ToCsv() => $"{VictimId},{KillerId},{Location.x},{Location.y},{Location.z},{Timestamp},{VictimLevel},{KillerLevel}";
public static EventData Parse(string csv)
{
var split = csv.Split(',');
return new EventData()
{
VictimId = ulong.Parse(split[0]),
KillerId = ulong.Parse(split[1]),
Location = new float3(float.Parse(split[2]), float.Parse(split[3]), float.Parse(split[4])),
Timestamp = long.Parse(split[5]),
VictimLevel = split.Length > 6 ? int.Parse(split[6]) : 0,
KillerLevel = split.Length > 7 ? int.Parse(split[7]) : 0,
};
}
}
public static List<EventData> Events = new();
public static Dictionary<ulong, PlayerStatistics> PlayerDatas = new();
private static readonly Random _rand = new();
private static EventData GenerateTestEvent() => new()
{
VictimId = (ulong)_rand.NextInt64(),
KillerId = (ulong)_rand.NextInt64(),
Location = new float3((float)_rand.NextDouble(), (float)_rand.NextDouble(), (float)_rand.NextDouble()),
Timestamp = DateTime.UtcNow.AddMinutes(_rand.Next(-10000, 10000)).Ticks
};
public static void GenerateNTestData(int count)
{
for (var i = 0; i < count; i++)
{
Events.Add(GenerateTestEvent());
}
}
private const string EVENTS_FILE_NAME = "events.v1.csv";
private const string EVENTS_FILE_PATH = $"BepInEx/config/Killfeed/{EVENTS_FILE_NAME}";
private const string STATS_FILE_NAME = "stats.v1.csv";
private const string STATS_FILE_PATH = $"BepInEx/config/Killfeed/{STATS_FILE_NAME}";
public static void WriteToDisk()
{
var dir = Path.GetDirectoryName(EVENTS_FILE_PATH);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
// TODO: Ideally this appends events and is smarter
using StreamWriter eventsFile = new StreamWriter(EVENTS_FILE_PATH, append: false);
foreach (var eventData in Events)
{
eventsFile.WriteLine(eventData.ToCsv());
}
using StreamWriter statsFile = new StreamWriter(STATS_FILE_PATH, append: false);
foreach (var playerData in PlayerDatas.Values)
{
statsFile.WriteLine(playerData.ToCsv());
}
}
public static void LoadFromDisk()
{
// can't think of how they would not be newed but let's be sure we don't duplicate data
Events.Clear();
PlayerDatas.Clear();
// let's assume maybe it can be empty or not exist and we don't care
LoadEventData();
LoadPlayerData();
}
private static void LoadEventData()
{
if (!File.Exists(EVENTS_FILE_PATH))
{
return;
}
using StreamReader eventsFile = new StreamReader(EVENTS_FILE_PATH);
while (!eventsFile.EndOfStream)
{
var line = eventsFile.ReadLine();
if (string.IsNullOrWhiteSpace(line)) continue;
try
{
Events.Add(EventData.Parse(line));
}
catch (Exception)
{
Plugin.Logger.LogError($"Failed to parse event line: \"{line}\"");
}
}
}
private static void LoadPlayerData()
{
if (!File.Exists(STATS_FILE_PATH)) return;
using StreamReader statsFile = new StreamReader(STATS_FILE_PATH);
while (!statsFile.EndOfStream)
{
var line = statsFile.ReadLine();
if (string.IsNullOrWhiteSpace(line)) continue;
try
{
var playerData = PlayerStatistics.Parse(line);
if (PlayerDatas.TryGetValue(playerData.SteamId, out PlayerStatistics data))
{
Plugin.Logger.LogWarning($"Duplicate player data found, overwriting {data} with {playerData}");
}
PlayerDatas[playerData.SteamId] = playerData;
}
catch (Exception)
{
Plugin.Logger.LogError($"Failed to parse player line: \"{line}\"");
}
}
}
public static void RegisterKillEvent(PlayerCharacter victim, PlayerCharacter killer, float3 location, int victimLevel, int killerLevel)
{
var victimUser = victim.UserEntity.Read<User>();
var killerUser = killer.UserEntity.Read<User>();
Plugin.Logger.LogWarning($"{victimLevel} {killerLevel}");
var newEvent = new EventData(victimUser.PlatformId, killerUser.PlatformId, location, DateTime.UtcNow.Ticks, victimLevel, killerLevel);
Events.Add(newEvent);
PlayerStatistics UpsertName(ulong steamId, string name, string clanName, int level)
{
if (PlayerDatas.TryGetValue(steamId, out var player))
{
player.LastName = name;
player.LastClanName = clanName;
player.CurrentLevel = level;
player.MaxLevel = Math.Max(player.MaxLevel, level);
PlayerDatas[steamId] = player;
}
else
{
PlayerDatas[steamId] = new PlayerStatistics() { LastName = name, SteamId = steamId, LastClanName = clanName, CurrentLevel = level, MaxLevel = level };
}
return PlayerDatas[steamId];
}
var victimData = UpsertName(victimUser.PlatformId, victimUser.CharacterName.ToString(), victim.SmartClanName.ToString(), victimLevel);
var killerData = UpsertName(killerUser.PlatformId, killerUser.CharacterName.ToString(), killer.SmartClanName.ToString(), killerLevel);
RecordKill(killerUser.PlatformId);
var lostStreak = RecordDeath(victimUser.PlatformId);
AnnounceKill(victimData, killerData, lostStreak);
// TODO: Very bad, but going to save to disk each kill for nice hiccup of lag
// while this is naieve and whole file, in append or WAL this might be better
WriteToDisk();
}
private static void AnnounceKill(PlayerStatistics victimUser, PlayerStatistics killerUser, int lostStreakAmount)
{
if (!Settings.AnnounceKills) return;
var victimName = victimUser.FormattedName;
var killerName = killerUser.FormattedName;
var message = lostStreakAmount > Settings.AnnounceKillstreakLostMinimum
? $"{killerName} ended {victimName}'s {Markup.Secondary(lostStreakAmount)} kill streak!"
: $"{killerName} killed {victimName}!";
var killMsg = killerUser.CurrentStreak switch
{
5 => $"<size=18>{killerName} is on a killing spree!",
10 => $"<size=19>{killerName} is on a rampage!",
15 => $"<size=20>{killerName} is dominating!",
20 => $"<size=21>{killerName} is unstoppable!",
25 => $"<size=22>{killerName} is godlike!",
30 => $"<size=24>{killerName} is WICKED SICK!",
_ => null
};
var announceMessage = new FixedString512Bytes(Markup.Prefix + message);
ServerChatUtils.SendSystemMessageToAllClients(VWorld.Server.EntityManager, ref announceMessage);
if (!string.IsNullOrEmpty(killMsg) && Settings.AnnounceKillstreak)
{
var killMessage = new FixedString512Bytes(Markup.Prefix + killMsg);
ServerChatUtils.SendSystemMessageToAllClients(VWorld.Server.EntityManager, ref killMessage);
}
}
private static int RecordDeath(ulong platformId)
{
var lostStreak = 0;
if (PlayerDatas.TryGetValue(platformId, out var player))
{
player.Deaths++;
lostStreak = player.CurrentStreak;
player.CurrentStreak = 0;
PlayerDatas[platformId] = player;
}
else
{
PlayerDatas[platformId] = new PlayerStatistics() { Deaths = 1, SteamId = platformId };
}
return lostStreak;
}
private static void RecordKill(ulong steamId)
{
if (PlayerDatas.TryGetValue(steamId, out var player))
{
player.Kills++;
player.CurrentStreak++;
player.HighestStreak = math.max(player.HighestStreak, player.CurrentStreak);
PlayerDatas[steamId] = player;
}
else
{
PlayerDatas[steamId] = new PlayerStatistics() { Kills = 1, CurrentStreak = 1, HighestStreak = 1, SteamId = steamId };
}
}
}