-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathClassicWebStats.cs
More file actions
315 lines (285 loc) · 13 KB
/
ClassicWebStats.cs
File metadata and controls
315 lines (285 loc) · 13 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
/*
* Copyright (c) 2024 DexrnZacAttack
* This file is part of ClassicWebStats.
* https://github.com/DexrnZacAttack/ClassicWebStats
*
* Licensed under the MIT License. See LICENSE file for details.
*/
//reference System.dll
//reference System.Runtime.Serialization.dll
//reference System.Core.dll
using MCGalaxy;
using MCGalaxy.Config;
using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace ClassicWebStats
{
public static class Stats
{
public static int PlayerCount { get; set; }
public static JsonArray Players { get; set; }
public static string Started { get; set; }
public static string Uptime { get; set; }
public static JsonObject MainMap { get; set; }
}
public class CStatsWebServer
{
private static readonly HttpListener listener = new HttpListener();
public static string pluginName = "";
public static string pluginCreator = "";
public static string pluginVersion = "";
private static JsonArray GetPlayersStats(List<Player> players)
{
JsonArray playerArray = new JsonArray();
foreach (var player in players)
{
TimeSpan joinTime = DateTime.UtcNow.Subtract(player.SessionStartTime);
playerArray.Add(new JsonObject {
{ "Name", new JsonObject {
{ "Name", player.name },
{ "FullName", player.FullName },
{ "DisplayName", player.DisplayName },
{ "ColoredDisplayName", player.ColoredName },
{ "Prefix", player.prefix },
{ "Title", player.title },
{ "TitleColor", player.titlecolor }
}},
{ "AFK", player.IsAfk },
{ "LastActionTime", player.LastAction.ToUnixTime().ToString() },
{ "Group", player.group.Name },
{ "GroupColored", player.group.ColoredName },
{ "Rank", player.Rank.ToString() },
{ "Client", player.Session.ClientName() },
{ "Skin", player.SkinName },
{ "JoinTime", player.SessionStartTime.ToUnixTime().ToString() },
{ "OnlineTime", string.Format("{0:D2}:{1:D2}:{2:D2}", joinTime.Hours, joinTime.Minutes, joinTime.Seconds) },
{ "Map", player.level.name },
{ "Coordinates", new JsonObject {
{ "Block", new JsonObject {
{ "X", player.Pos.FeetBlockCoords.X },
{ "Y", player.Pos.FeetBlockCoords.Y },
{ "Z", player.Pos.FeetBlockCoords.Z }
}},
{ "Unit", new JsonObject {
{ "X", player.Pos.X },
{ "Y", player.Pos.Y },
{ "Z", player.Pos.Z }
}}
}},
{ "HeldBlock", new JsonObject {
{ "Name", Block.GetName(player, player.ClientHeldBlock) },
{ "Id", (int)player.ClientHeldBlock }
}},
});
};
return playerArray;
}
private static void GetCurrentStats()
{
// get players online
Player fakePlayer = new Player("Test");
Stats.Players = GetPlayersStats(PlayerInfo.GetOnlineCanSee(fakePlayer, LevelPermission.Guest).ToList());
// get player count
Stats.PlayerCount = PlayerInfo.Online.Count;
Stats.Started = Server.StartTime.ToUnixTime().ToString();
TimeSpan uptime = DateTime.UtcNow.Subtract(Server.StartTime);
Stats.Uptime = string.Format("{0:D2}:{1:D2}:{2:D2}", uptime.Hours, uptime.Minutes, uptime.Seconds);
Stats.MainMap = new JsonObject
{
{ "Name", Server.mainLevel.name },
{ "Players", GetPlayersStats(Server.mainLevel.players) },
{ "Bounds", new JsonObject {
{ "Width", (int)Server.mainLevel.Width },
{ "Length", (int)Server.mainLevel.Length },
{ "Height", (int)Server.mainLevel.Height }
}},
{ "SpawnPos", new JsonObject {
{ "Block", new JsonObject {
{ "X", Server.mainLevel.SpawnPos.FeetBlockCoords.X },
{ "Y", Server.mainLevel.SpawnPos.FeetBlockCoords.Y },
{ "Z", Server.mainLevel.SpawnPos.FeetBlockCoords.Z }
}},
{ "Unit", new JsonObject {
{ "X", Server.mainLevel.SpawnPos.X },
{ "Y", Server.mainLevel.SpawnPos.Y },
{ "Z", Server.mainLevel.SpawnPos.Z }
}}
}}
};
}
public static void StartWebServer()
{
// TODO: NEEDS CLEANUP
string url = "http://localhost:8081/";
listener.Prefixes.Add(url);
listener.Start();
Logger.Log(LogType.Debug, "Listening on {0}", url);
Task.Run(() =>
{
while (listener.IsListening)
{
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
response.Headers.Add("Server", pluginName + " " + pluginVersion + " on " + Server.SoftwareNameVersioned + ";");
if (request.Url.AbsolutePath.StartsWith("/level/"))
{
string rem = request.Url.AbsolutePath.Substring("/level/".Length);
if (rem.Contains("/map"))
{
string mapName = rem.Substring(0, rem.IndexOf("/map"));
if (!LevelInfo.MapExists(mapName))
{
var error = new JsonObject
{
{ "Error", "Map does not exist." },
};
var json = Encoding.UTF8.GetBytes(Json.SerialiseObject(error));
response.ContentType = "application/json";
response.ContentLength64 = json.Length;
response.OutputStream.Write(json, 0, json.Length);
response.OutputStream.Close();
continue;
}
byte[] blockBuf = ClassicMap.GetTopBlocks(Level.Load(mapName));
byte[] buffer;
using (var ms = new MemoryStream())
{
using (var gs = new GZipStream(ms, CompressionMode.Compress))
{
gs.Write(blockBuf, 0, blockBuf.Length);
}
buffer = ms.ToArray();
}
response.ContentType = "application/octet-stream";
response.AddHeader("Content-Disposition", "attachment; filename=\"" + mapName + "_map.dat.gz\"");
response.ContentLength64 = buffer.Length;
response.OutputStream.Write(buffer, 0, buffer.Length);
response.OutputStream.Close();
}
else if (rem.Contains("/bounds"))
{
string mapName = rem.Substring(0, rem.IndexOf("/bounds"));
if (!LevelInfo.MapExists(mapName))
{
var error = new JsonObject
{
{ "Error", "Map does not exist." },
};
var errorJson = Encoding.UTF8.GetBytes(Json.SerialiseObject(error));
response.ContentType = "application/json";
response.ContentLength64 = errorJson.Length;
response.OutputStream.Write(errorJson, 0, errorJson.Length);
response.OutputStream.Close();
continue;
}
var bounds = ClassicMap.GetBounds(Level.Load(mapName));
var msg = new JsonObject
{
{ "Width", (int)bounds["Width"] },
{ "Length", (int)bounds["Length"] },
{ "Height", (int)bounds["Height"] }
};
var boundsJson = Encoding.UTF8.GetBytes(Json.SerialiseObject(msg));
response.ContentType = "application/json";
response.ContentLength64 = boundsJson.Length;
response.OutputStream.Write(boundsJson, 0, boundsJson.Length);
response.OutputStream.Close();
} else
{
Logger.Log(LogType.UserActivity, "Unknown page:", request.Url.AbsolutePath);
}
}
else
{
GetCurrentStats();
var stats = new JsonObject
{
{ "PlayerCount", Stats.PlayerCount },
{ "Started", Stats.Started },
{ "Uptime", Stats.Uptime },
{ "Players", Stats.Players },
{ "MainMap", Stats.MainMap },
};
string json = Json.SerialiseObject(stats);
byte[] buffer = Encoding.UTF8.GetBytes(json);
response.ContentType = "application/json";
response.ContentLength64 = buffer.Length;
response.OutputStream.Write(buffer, 0, buffer.Length);
response.OutputStream.Close();
}
}
});
}
public static void StopWebServer()
{
if (listener.IsListening)
{
listener.Stop();
listener.Close();
}
}
}
public static class ClassicMap
{
// modified version of danilwhale's code from when we were testing map image gen
public static byte[] GetTopBlocks(Level level)
{
var width = level.Width;
var length = level.Length;
var height = level.Height;
var blocks = new byte[width * length];
Parallel.For(0, width, x =>
{
for (var z = (ushort)0; z < length; z++)
{
int index = x + width * z;
for (var y = height - 1; y >= 0; y--)
{
var block = Block.ToRaw(level.GetBlock((ushort)x, (ushort)y, z));
if (block != Block.Air)
{
blocks[index] = (byte)block;
break;
}
}
}
});
return blocks;
}
public static Dictionary<string, ushort> GetBounds(Level level)
{
return new Dictionary<string, ushort>
{
{ "Width", level.Width },
{ "Length", level.Length },
{ "Height", level.Height }
};
}
}
public sealed class ClassicWebStats : Plugin
{
public override string name { get { return "Classic Web Stats"; } }
public override string creator { get { return "DexrnZacAttack"; } }
public override string MCGalaxy_Version { get { return "1.2.0.0"; } }
public override void Load(bool startup)
{
CStatsWebServer.pluginName = name;
CStatsWebServer.pluginCreator = creator;
CStatsWebServer.pluginVersion = MCGalaxy_Version;
CStatsWebServer.StartWebServer();
Logger.Log(LogType.Debug, "{0} {1} loaded.", name, MCGalaxy_Version);
}
public override void Unload(bool shutdown)
{
CStatsWebServer.StopWebServer();
Logger.Log(LogType.Debug, "{0} {1} unloaded.", name, MCGalaxy_Version);
}
}
}