forked from MS2Community/Maple2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebController.cs
More file actions
424 lines (355 loc) · 17.6 KB
/
WebController.cs
File metadata and controls
424 lines (355 loc) · 17.6 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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Threading.Tasks;
using Maple2.Database.Model.Ranking;
using Maple2.Database.Storage;
using Maple2.Model.Enum;
using Maple2.Model.Game;
using Maple2.PacketLib.Tools;
using Maple2.Server.Web.Packet;
using Maple2.Tools;
using Maple2.Tools.Extensions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Serilog;
using Enum = System.Enum;
namespace Maple2.Server.Web.Controllers;
[Route("")]
public class WebController : ControllerBase {
private readonly WebStorage webStorage;
private readonly GameStorage gameStorage;
private readonly IMemoryCache cache;
private static readonly TimeSpan RankingCacheDuration = TimeSpan.FromHours(1);
public WebController(WebStorage webStorage, GameStorage gameStorage, IMemoryCache cache) {
this.webStorage = webStorage;
this.gameStorage = gameStorage;
this.cache = cache;
}
[HttpPost("irrq.aspx")]
public async Task<IResult> Rankings() {
Stream bodyStream = Request.Body;
var memoryStream = new MemoryStream();
await bodyStream.CopyToAsync(memoryStream);
memoryStream.Position = 0; // reset position to beginning of stream before returning
if (memoryStream.Length == 0) {
return Results.BadRequest("Request was empty");
}
IByteReader packet = new ByteReader(memoryStream.ToArray());
var type = packet.Read<GameRankingType>();
int unknown = packet.ReadInt(); // start page maybe?
long accountId = packet.ReadLong();
long characterId = packet.ReadLong();
long characterIdSearch = packet.ReadLong(); // parameter
int rankingId = packet.ReadInt(); // boss ranking id like 23200007
int seasonId = packet.ReadInt(); // defined in season xmls
string userName = packet.ReadUnicodeStringWithLength(); // search string
if (!Enum.IsDefined(typeof(GameRankingType), type)) {
Log.Logger.Debug("Unimplemented ranking type: {Type}", type);
return Results.BadRequest($"Invalid ranking type: {type}");
}
Log.Logger.Debug("[Request]Rankings: type={Type}, unknown={unknown} accountId={AccountId} characterId={CharacterId}, characterIdSearch={characterIdSearch}, rankingId={RankingId}, seasonId={seasonId}, userName={UserName}", type, unknown, accountId, characterId, characterIdSearch, rankingId, seasonId, userName);
ByteWriter pWriter = type switch {
GameRankingType.Trophy => Trophy(userName),
GameRankingType.PersonalTrophy => PersonalTrophy(characterId),
GameRankingType.GuildTrophy => GuildTrophy(userName),
GameRankingType.PersonalGuildTrophy => PersonalGuildTrophy(characterId),
_ => new ByteWriter(),
};
return Results.File(ZlibCompress(pWriter), "application/octet-stream");
}
[HttpPost("ruq.aspx")]
public async Task<IResult> Info() {
Stream bodyStream = Request.Body;
var memoryStream = new MemoryStream();
await bodyStream.CopyToAsync(memoryStream);
memoryStream.Position = 0; // reset position to beginning of stream before returning
if (memoryStream.Length == 0) {
return Results.BadRequest("Request was empty");
}
IByteReader packet = new ByteReader(memoryStream.ToArray());
int header = packet.ReadInt(); // 0?
long accountId = packet.ReadLong();
long characterId = packet.ReadLong();
int unknown = packet.ReadInt(); // 5 if mentee ?
if (unknown != 5) {
Log.Logger.Debug("Unimplemented info type: {Type}", unknown);
return Results.BadRequest($"Invalid info type: {unknown}");
}
return Results.File(ZlibCompress(MenteeList(accountId, characterId)), "application/octet-stream");
}
[HttpPost("urq.aspx")]
public async Task<IResult> Upload() {
Stream bodyStream = Request.Body;
var memoryStream = new MemoryStream();
await bodyStream.CopyToAsync(memoryStream);
memoryStream.Position = 0; // reset position to beginning of stream before returning
if (memoryStream.Length == 0) {
return Results.BadRequest("Request was empty");
}
IByteReader packet = new ByteReader(memoryStream.ToArray());
packet.ReadInt();
var type = (UgcType) packet.ReadInt();
long accountId = packet.ReadLong();
long characterId = packet.ReadLong();
long ugcUid = packet.ReadLong();
int id = packet.ReadInt(); // item id, guild id, others?
packet.ReadInt();
packet.ReadLong();
byte[] fileBytes = packet.ReadBytes(packet.Available);
Log.Logger.Debug("Upload: type={Type}, accountId={AccountId}, characterId={CharacterId}, ugcUid={UgcUid}, id={Id}", type, accountId, characterId, ugcUid, id);
UgcResource? resource = null;
if (ugcUid != 0) {
using WebStorage.Request db = webStorage.Context();
resource = db.GetUgc(ugcUid);
if (resource == null) {
return Results.NotFound($"{ugcUid} does not exist.");
}
}
if (type is UgcType.ItemIcon or UgcType.Item or UgcType.BlueprintIcon or UgcType.LayoutBlueprint && resource == null) {
return Results.BadRequest("Invalid UGC resource.");
}
return type switch {
UgcType.ProfileAvatar => UploadProfileAvatar(fileBytes, characterId),
UgcType.Item or UgcType.Mount or UgcType.Furniture => UploadItem(fileBytes, id, ugcUid, resource!),
UgcType.ItemIcon => UploadItemIcon(fileBytes, id, ugcUid, resource!),
UgcType.Banner => UploadBanner(fileBytes, id, ugcUid),
UgcType.GuildEmblem => HandleGuildEmblem(fileBytes, id, ugcUid),
UgcType.GuildBanner => HandleGuildBanner(fileBytes, id, ugcUid),
UgcType.BlueprintIcon => HandleBlueprintIcon(fileBytes, ugcUid, resource!),
UgcType.LayoutBlueprint => HandleBlueprintPreview(fileBytes, ugcUid, resource!),
_ => HandleUnknownMode(type),
};
}
#region Ugc
private static IResult UploadProfileAvatar(byte[] fileBytes, long characterId) {
string filePath = Path.Combine(Paths.WEB_DATA_DIR, "profiles", characterId.ToString());
try {
// Deleting old files in the character folder
if (Path.Exists(filePath)) {
Directory.Delete(filePath, true);
}
Directory.CreateDirectory(filePath);
} catch (Exception ex) {
Log.Error(ex, "Failed preparing directory: {Path}", filePath);
return Results.Problem("Internal Server Error", statusCode: 500);
}
string uniqueFileName = Guid.NewGuid().ToString();
System.IO.File.WriteAllBytes(Path.Combine(filePath, $"{uniqueFileName}.png"), fileBytes);
return Results.Text($"0,data/profiles/avatar/{characterId}/{uniqueFileName}.png");
}
private IResult UploadItem(byte[] fileBytes, int itemId, long ugcId, UgcResource resource) {
string filePath = Path.Combine(Paths.WEB_DATA_DIR, "items", itemId.ToString());
try {
Directory.CreateDirectory(filePath);
} catch (Exception ex) {
Log.Error(ex, "Failed preparing directory: {Path}", filePath);
return Results.Problem("Internal Server Error", statusCode: 500);
}
using WebStorage.Request db = webStorage.Context();
string ugcPath = $"item/ms2/01/{itemId}/{resource.Id}.m2u";
db.UpdatePath(ugcId, ugcPath);
System.IO.File.WriteAllBytes(Path.Combine(filePath, $"{resource.Id}.m2u"), fileBytes);
return Results.Text($"0,{ugcPath}");
}
private IResult UploadItemIcon(byte[] fileBytes, int itemId, long ugcId, UgcResource resource) {
string filePath = Path.Combine(Paths.WEB_DATA_DIR, "itemicon", itemId.ToString());
try {
Directory.CreateDirectory(filePath);
} catch (Exception ex) {
Log.Error(ex, "Failed preparing directory: {Path}", filePath);
return Results.Problem("Internal Server Error", statusCode: 500);
}
//TODO: Verify that the item exists in the database
string ugcPath = $"itemicon/ms2/01/{itemId}/{resource.Id}.png";
System.IO.File.WriteAllBytes(Path.Combine(filePath, $"{ugcId}.png"), fileBytes);
return Results.Text($"0,{ugcPath}");
}
private IResult UploadBanner(byte[] fileBytes, int bannerId, long ugcId) {
string filePath = Path.Combine(Paths.WEB_DATA_DIR, "banner", bannerId.ToString());
try {
Directory.CreateDirectory(filePath);
} catch (Exception ex) {
Log.Error(ex, "Failed preparing directory: {Path}", filePath);
return Results.Problem("Internal Server Error", statusCode: 500);
}
using WebStorage.Request db = webStorage.Context();
string ugcPath = $"banner/ms2/01/{bannerId}/{ugcId}.m2u";
db.UpdatePath(ugcId, ugcPath);
System.IO.File.WriteAllBytes(Path.Combine(filePath, $"{ugcId}.m2u"), fileBytes);
return Results.Text($"0,{ugcPath}");
}
private IResult HandleGuildEmblem(byte[] fileBytes, int guildId, long ugcId) {
string filePath = Path.Combine(Paths.WEB_DATA_DIR, "guildmark", guildId.ToString());
try {
Directory.CreateDirectory(filePath);
} catch (Exception ex) {
Log.Error(ex, "Failed preparing directory: {Path}", filePath);
return Results.Problem("Internal Server Error", statusCode: 500);
}
using WebStorage.Request db = webStorage.Context();
string ugcPath = $"guildmark/ms2/01/{guildId}/{ugcId}.png";
db.UpdatePath(ugcId, ugcPath);
System.IO.File.WriteAllBytes(Path.Combine(filePath, $"{ugcId}.png"), fileBytes);
return Results.Text($"0,{ugcPath}");
}
private IResult HandleGuildBanner(byte[] fileBytes, int guildId, long ugcId) {
string filePath = Path.Combine(Paths.WEB_DATA_DIR, "guildmark", guildId.ToString(), "banner");
try {
Directory.CreateDirectory(filePath);
} catch (Exception ex) {
Log.Error(ex, "Failed preparing directory: {Path}", filePath);
return Results.Problem("Internal Server Error", statusCode: 500);
}
using WebStorage.Request db = webStorage.Context();
string ugcPath = $"guildmark/ms2/01/{guildId}/banner/{ugcId}.png";
db.UpdatePath(ugcId, ugcPath);
System.IO.File.WriteAllBytes(Path.Combine(filePath, $"{ugcId}.png"), fileBytes);
return Results.Text($"0,{ugcPath}");
}
private IResult HandleBlueprintIcon(byte[] fileBytes, long ugcUid, UgcResource resource) {
string filePath = Path.Combine(Paths.WEB_DATA_DIR, "blueprint", ugcUid.ToString());
try {
Directory.CreateDirectory(filePath);
} catch (Exception ex) {
Log.Error(ex, "Failed preparing directory: {Path}", filePath);
return Results.Problem("Internal Server Error", statusCode: 500);
}
string ugcPath = $"blueprint/ms2/01/{ugcUid}/{resource.Id}_icon.png";
System.IO.File.WriteAllBytes(Path.Combine(filePath, $"{resource.Id}_icon.png"), fileBytes);
return Results.Text($"0,{ugcPath}");
}
private IResult HandleBlueprintPreview(byte[] fileBytes, long ugcUid, UgcResource resource) {
string filePath = Path.Combine(Paths.WEB_DATA_DIR, "blueprint", ugcUid.ToString());
try {
Directory.CreateDirectory(filePath);
} catch (Exception ex) {
Log.Error(ex, "Failed preparing directory: {Path}", filePath);
return Results.Problem("Internal Server Error", statusCode: 500);
}
using WebStorage.Request db = webStorage.Context();
string ugcPath = $"blueprint/ms2/01/{ugcUid}/{resource.Id}.png";
db.UpdatePath(ugcUid, ugcPath);
System.IO.File.WriteAllBytes(Path.Combine(filePath, $"{resource.Id}.png"), fileBytes);
return Results.Text($"0,{ugcPath}");
}
private static IResult HandleUnknownMode(UgcType mode) {
Log.Logger.Warning("Invalid upload mode: {Mode}", mode);
return Results.BadRequest($"Invalid upload mode: {mode}");
}
#endregion
#region Ranking
public ByteWriter Trophy(string userName) {
string cacheKey = $"Trophy_{userName ?? "all"}";
if (!cache.TryGetValue(cacheKey, out byte[]? cachedData)) {
List<TrophyRankInfo> rankInfos = [];
using GameStorage.Request db = gameStorage.Context();
if (!string.IsNullOrEmpty(userName)) {
TrophyRankInfo? info = db.GetTrophyRankInfo(userName);
if (info != null) {
rankInfos.Add(info);
}
} else {
IList<TrophyRankInfo> infos = db.GetTrophyRankings();
rankInfos.AddRange(infos);
}
ByteWriter writer = InGameRankPacket.Trophy(rankInfos);
cachedData = writer.Buffer[..writer.Length];
cache.Set(cacheKey, cachedData, RankingCacheDuration);
}
var result = new ByteWriter();
result.WriteBytes(cachedData!);
return result;
}
public ByteWriter PersonalTrophy(long characterId) {
string cacheKey = $"PersonalTrophy_{characterId}";
if (!cache.TryGetValue(cacheKey, out byte[]? cachedData)) {
using GameStorage.Request db = gameStorage.Context();
TrophyRankInfo? info = db.GetTrophyRankInfo(characterId);
ByteWriter writer = InGameRankPacket.PersonalRank(GameRankingType.PersonalTrophy, info?.Rank ?? 0);
cachedData = writer.Buffer[..writer.Length];
cache.Set(cacheKey, cachedData, RankingCacheDuration);
}
var result = new ByteWriter();
result.WriteBytes(cachedData!);
return result;
}
public ByteWriter GuildTrophy(string userName) {
if (!string.IsNullOrEmpty(userName)) {
string cacheKey = $"GuildTrophy_{userName}";
if (!cache.TryGetValue(cacheKey, out byte[]? cachedData)) {
// Search by guild name, check full rankings cache first then fall back to DB
IList<GuildTrophyRankInfo> rankings = GetCachedGuildTrophyRankings();
GuildTrophyRankInfo? cached = rankings.FirstOrDefault(r =>
r.Name.Equals(userName, StringComparison.OrdinalIgnoreCase));
ByteWriter writer;
if (cached != null) {
writer = InGameRankPacket.GuildTrophy([cached]);
} else {
using GameStorage.Request db = gameStorage.Context();
GuildTrophyRankInfo? info = db.GetGuildTrophyRankInfo(userName);
writer = InGameRankPacket.GuildTrophy(info != null ? new[] { info } : []);
}
cachedData = writer.Buffer[..writer.Length];
cache.Set(cacheKey, cachedData, RankingCacheDuration);
}
var result = new ByteWriter();
result.WriteBytes(cachedData!);
return result;
}
return InGameRankPacket.GuildTrophy(GetCachedGuildTrophyRankings());
}
public ByteWriter PersonalGuildTrophy(long characterId) {
string cacheKey = $"PersonalGuildTrophy_{characterId}";
if (!cache.TryGetValue(cacheKey, out byte[]? cachedData)) {
using GameStorage.Request db = gameStorage.Context();
long guildId = db.GetGuildIdByCharacterId(characterId);
ByteWriter writer;
if (guildId == 0) {
writer = InGameRankPacket.PersonalRank(GameRankingType.PersonalGuildTrophy, 0);
} else {
// Check cached rankings for this guild's rank
IList<GuildTrophyRankInfo> rankings = GetCachedGuildTrophyRankings();
GuildTrophyRankInfo? cached = rankings.FirstOrDefault(r => r.GuildId == guildId);
writer = InGameRankPacket.PersonalRank(GameRankingType.PersonalGuildTrophy, cached?.Rank ?? 0);
}
cachedData = writer.Buffer[..writer.Length];
cache.Set(cacheKey, cachedData, RankingCacheDuration);
}
var result = new ByteWriter();
result.WriteBytes(cachedData!);
return result;
}
private IList<GuildTrophyRankInfo> GetCachedGuildTrophyRankings() {
const string cacheKey = "GuildTrophyRankings";
if (!cache.TryGetValue(cacheKey, out IList<GuildTrophyRankInfo>? rankings)) {
using GameStorage.Request db = gameStorage.Context();
rankings = db.GetGuildTrophyRankings();
cache.Set(cacheKey, rankings, RankingCacheDuration);
}
return rankings!;
}
#endregion
public ByteWriter MenteeList(long accountId, long characterId) {
using GameStorage.Request db = gameStorage.Context();
IList<long> list = db.GetMentorList(accountId, characterId);
IList<PlayerInfo> players = [];
foreach (long menteeId in list) {
PlayerInfo? playerInfo = db.GetPlayerInfo(menteeId);
if (playerInfo != null) {
players.Add(playerInfo);
}
}
return MentorPacket.MenteeList(players);
}
private static byte[] ZlibCompress(ByteWriter writer) {
using var outputStream = new MemoryStream();
using (var zlibStream = new ZLibStream(outputStream, CompressionLevel.Optimal, leaveOpen: true)) {
zlibStream.Write(writer.Buffer, 0, writer.Length);
}
return outputStream.ToArray();
}
}