diff --git a/routes/Chat.cs b/routes/Chat.cs new file mode 100644 index 0000000..04e1cc6 --- /dev/null +++ b/routes/Chat.cs @@ -0,0 +1,11 @@ +namespace Stella.Routes +{ + public class Chat + { + [ServerAPI.GET("/chat/thread")] + public List ThreadGet() + { + return []; + } + } +} \ No newline at end of file diff --git a/routes/Leaderboards.cs b/routes/Leaderboards.cs new file mode 100644 index 0000000..846d7d7 --- /dev/null +++ b/routes/Leaderboards.cs @@ -0,0 +1,6 @@ +namespace Stella.Routes +{ + public class Leaderboards + { + } +} \ No newline at end of file diff --git a/routes/Matchmaking.cs b/routes/Matchmaking.cs new file mode 100644 index 0000000..692d35a --- /dev/null +++ b/routes/Matchmaking.cs @@ -0,0 +1,214 @@ +using MongoDB.Driver; +using Stella.Models; +using Stella.Routes.API; + +namespace Stella.Routes +{ + public class Matchmaking + { + [ServerAPI.PUT("/match/player/vrmovementmode")] + public IResult ReturnVRMovementMode() + { + return Results.Ok(); + } + + [ServerAPI.PUT("/match/player/statusvisibility")] + public IResult ReturnStatusVisibility() + { + return Results.Ok(); + } + + [ServerAPI.PUT("/match/player/photonregionpings")] + public IResult ReturnPhotonRegionPings() + { + return Results.Ok(); + } + + [ServerAPI.POST("/match/player/login")] // return 409 for "This account is already logged in somewhere else!" error + public IResult ReturnLogin() + { + return Results.Ok(); + } + + [ServerAPI.POST("/match/roominstance/{roomInstanceId}/reportjoinresult")] // return 409 for "This account is already logged in somewhere else!" error + public IResult ReturnReportJoinResult(long roomInstanceId) + { + return Results.Ok(); + } + + [ServerAPI.POST("/match/player/heartbeat")] + [ServerAPI.UseAuthorization] + public async Task ReturnHeartbeat(MongoDB.User user) + { + PlayerPresence presence = new() + { + StatusVisibility = PlayerStatusVisibility.Public, + AppVersion = BuildConstants.Version, + DeviceClass = DeviceClass.VR, + IsOnline = true, + PlayerId = user.AccountId, + RoomInstance = user.OtherData.RoomInstance, + VRMovementMode = VRMovementMode.WALK + }; + + await NotificationHub.SendWebsocket(user.AccountId, new + { + Id = PushNotificationId.PresenceHeartbeatResponse, + Msg = presence + }); + + return presence; + } + + [ServerAPI.POST("/match/goto/room/{roomName}")] + [ServerAPI.UseAuthorization] + public async Task ReturnGotoRoom(string roomName, MongoDB.User user) + { + MongoDB.RoomDetailsMongoDB room; + if (roomName.Equals("dormroom", StringComparison.CurrentCultureIgnoreCase)) + { + room = MongoDB.roomsCollection.Find(u => u.Room.RoomId == user.OtherData.DormRoomId).FirstOrDefault(); + } + else + { + + room = MongoDB.roomsCollection.Find(u => u.Room.Name == roomName).FirstOrDefault(); + } + + RoomInstance roomInstance = new() + { + RoomId = room.Room.RoomId, + Name = room.Room.Name.StartsWith("@") ? room.Room.Name : "^" + room.Room.Name, + DataBlob = "", + IsFull = false, + IsInProgress = false, + IsPrivate = false, + Location = room.Scenes[0].RoomSceneLocationId, + MaxCapacity = room.Scenes[0].MaxPlayers, + PhotonRegionId = "us", + PhotonRoomId = $"stella.{"" + room.Room.Name}", + RoomInstanceId = room.Room.RoomId, + SubRoomId = 1 + }; + + MatchmakingResponseDTO response = new() + { + ErrorCode = MatchmakingErrorCode.Success, + RoomInstance = roomInstance + }; + + MongoDB.usersCollection.UpdateOne( + u => u.AccountId == user.AccountId, + Builders.Update.Set(u => u.OtherData.RoomInstance, roomInstance) + ); + + await NotificationHub.SendWebsocket(user.AccountId, new + { + Id = "PresenceUpdate", + Msg = response + }); + + await NotificationHub.SendWebsocket(user.AccountId, new + { + Id = "RoomInstanceUpdate", + Msg = response + }); + + return response; + } + + [ServerAPI.POST("/match/goto/room/{roomName}/{roomScene}")] + [ServerAPI.UseAuthorization] + public async Task ReturnGotoRoomScene(string roomName, string roomScene, MongoDB.User user) + { + MongoDB.RoomDetailsMongoDB room = MongoDB.roomsCollection.Find(u => u.Room.Name == roomName).FirstOrDefault(); + + int sceneIndex = room.Scenes.FindIndex(s => s.Name.Equals(roomScene, StringComparison.CurrentCultureIgnoreCase)); + + RoomInstance roomInstance = new() + { + RoomId = room.Room.RoomId, + Name = "^" + room.Room.Name, + DataBlob = "", + IsFull = false, + IsInProgress = false, + IsPrivate = false, + Location = room.Scenes[sceneIndex].RoomSceneLocationId, + MaxCapacity = room.Scenes[sceneIndex].MaxPlayers, + PhotonRegionId = "us", + PhotonRoomId = $"stella.{"^" + room.Room.Name}", + RoomInstanceId = room.Room.RoomId + (sceneIndex + 10000), + SubRoomId = 1 + }; + + MatchmakingResponseDTO response = new() + { + ErrorCode = MatchmakingErrorCode.Success, + RoomInstance = roomInstance + }; + + MongoDB.usersCollection.UpdateOne( + u => u.AccountId == user.AccountId, + Builders.Update.Set(u => u.OtherData.RoomInstance, roomInstance) + ); + + await NotificationHub.SendWebsocket(user.AccountId, new + { + Id = "PresenceUpdate", + Msg = response + }); + + await NotificationHub.SendWebsocket(user.AccountId, new + { + Id = "RoomInstanceUpdate", + Msg = response + }); + + return response; + } + + [ServerAPI.POST("/match/goto/none")] + [ServerAPI.UseAuthorization] + public async Task ReturnNone(MongoDB.User user) + { + MatchmakingResponseDTO response = new() + { + ErrorCode = MatchmakingErrorCode.Success, + RoomInstance = new RoomInstance + { + RoomId = 1, + Name = $"^@{user.Username}'s Dorm", + DataBlob = "", + IsFull = false, + IsInProgress = false, + IsPrivate = false, + Location = "76d98498-60a1-430c-ab76-b54a29b7a163", + MaxCapacity = 20, + PhotonRegionId = "us", + PhotonRoomId = $"stella.{$"^@{user.Username}'s Dorm"}", + RoomInstanceId = 1, + SubRoomId = 1 + } + }; + + MongoDB.usersCollection.UpdateOne( + u => u.AccountId == user.AccountId, + Builders.Update.Set(u => u.OtherData.RoomInstance, response.RoomInstance) + ); + + await NotificationHub.SendWebsocket(user.AccountId, new + { + Id = "PresenceUpdate", + Msg = response + }); + + await NotificationHub.SendWebsocket(user.AccountId, new + { + Id = "RoomInstanceUpdate", + Msg = response + }); + + return response; + } + } +} \ No newline at end of file diff --git a/routes/NameServer.cs b/routes/NameServer.cs new file mode 100644 index 0000000..3d31522 --- /dev/null +++ b/routes/NameServer.cs @@ -0,0 +1,34 @@ +using Stella.Models; + +namespace Stella.Routes +{ + public class NS + { + [ServerAPI.GET("/")] + public NameServerResponse NameServer() + { + return new NameServerResponse + { + Accounts = "http://ns.stellaonline.org", + API = "http://ns.stellaonline.org", // dont add /api because every call to this service to this already does + Auth = "http://ns.stellaonline.org/auth", + CDN = "http://ns.stellaonline.org/cdn", + Chat = "http://ns.stellaonline.org/chat", + Clubs = "http://ns.stellaonline.org/clubs", + Commerce = "http://ns.stellaonline.org/commerce", + DataCollection = "http://ns.stellaonline.org/datacollection", + Images = "http://ns.stellaonline.org/img", + Leaderboard = "http://ns.stellaonline.org", + Link = "http://ns.stellaonline.org/link", + Matchmaking = "http://ns.stellaonline.org/match", + Moderation = "http://ns.stellaonline.org/moderation", + Notifications = "http://ns.stellaonline.org/notify", + PlatformNotifications = "http://ns.stellaonline.org/platformnotifications", + RoomComments = "http://ns.stellaonline.org/roomcomments", + Rooms = "http://ns.stellaonline.org/rooms", + Storage = "http://ns.stellaonline.org/storage", + WWW = "http://stellaonline.org" + }; + } + } +} \ No newline at end of file diff --git a/routes/NotificationHub.cs b/routes/NotificationHub.cs new file mode 100644 index 0000000..a3cba6a --- /dev/null +++ b/routes/NotificationHub.cs @@ -0,0 +1,131 @@ +using Microsoft.AspNetCore.Mvc.ModelBinding; +using MongoDB.Driver.Core.Connections; +using Stella.Models; +using System.Net.WebSockets; +using System.Text; +using System.Text.Json; + +namespace Stella.Routes +{ + public class NotificationHub + { + private static readonly Dictionary Connections = []; + + [ServerAPI.POST("/notify/hub/v1/negotiate")] + public async Task Negotiate(HttpContext ctx) + { + var response = new + { + negotiateVersion = 0, + accessToken = JsonWebToken.Generate(new() { + { "sub", "1" }, + { "role", "client" }, + { "iat", DateTime.UtcNow.ToUnixTime() } + }, TimeSpan.FromSeconds(6)), + availableTransports = new[] + { + new { + transport = "WebSockets", + transferFormats = new[] { + "Text" + } + } + } + }; + + ctx.Response.ContentType = "application/json"; + await ctx.Response.WriteAsync(JsonSerializer.Serialize(response)); + } + + [ServerAPI.MAP("/notify/hub/v1")] + [ServerAPI.UseAuthorization] + public async Task SignalR(HttpContext ctx, MongoDB.User user) + { + IDictionary? info = JsonWebToken.VerifyAndDecode(ctx.Request.Headers.Authorization); + if (info == null) + { + return; + } + + using WebSocket ws = await ctx.WebSockets.AcceptWebSocketAsync(); + Connections[user.AccountId] = ws; + + byte[] buffer = new byte[4096]; + + try + { + while (ws.State == WebSocketState.Open) + { + WebSocketReceiveResult r = await ws.ReceiveAsync(buffer, CancellationToken.None); + + if (r.MessageType == WebSocketMessageType.Close) + break; + + string msg = Encoding.UTF8.GetString(buffer, 0, r.Count); + + if (!msg.EndsWith("\x1E")) + break; + + msg = msg[..^1]; // remove the \x1E + + using var doc = JsonDocument.Parse(msg); + + var root = doc.RootElement; + + if (root.TryGetProperty("protocol", out _)) + { + byte[] bytes = Encoding.UTF8.GetBytes("{}\x1E"); + await ws.SendAsync(bytes, WebSocketMessageType.Text, true, CancellationToken.None); + continue; + } + + if (root.TryGetProperty("type", out var t) && t.GetInt32() == 6) + { + byte[] bytes = Encoding.UTF8.GetBytes("{\"type\":6}\x1E"); + await ws.SendAsync(bytes, WebSocketMessageType.Text, true, CancellationToken.None); + continue; + } + } + } + finally + { + Connections.Remove(user.AccountId); + } + } + + public static async Task SendWebsocket(long id, object json) + { + if (!Connections.TryGetValue(id, out var ws)) + { + Console.WriteLine(id); + return; + } + + if (ws.State != WebSocketState.Open) + return; + + string inner = JsonSerializer.Serialize(json).Replace("\"", "\\u0022"); + + string outMessage = $"{{\"type\":1,\"invocationId\":\"{id}\",\"nonblocking\":true,\"target\":\"Notification\",\"arguments\":[\"{inner}\"],\"item\":\"\",\"result\":\"200 OK\",\"error\":\"\"}}\x1E"; + + await ws.SendAsync(outMessage, WebSocketMessageType.Text, true, CancellationToken.None); + } + + public static async Task SendWebsocket(object json) + { + foreach (var kvp in Connections) + { + var ws = kvp.Value; + + if (ws.State != WebSocketState.Open) + continue; + + string inner = JsonSerializer.Serialize(json).Replace("\"", "\\u0022"); + + string outMessage = $"{{\"type\":1,\"invocationId\":\"{kvp.Key}\",\"nonblocking\":true,\"target\":\"Notification\",\"arguments\":[\"{inner}\"],\"item\":\"\",\"result\":\"200 OK\",\"error\":\"\"}}\x1E"; + + await ws.SendAsync(outMessage, WebSocketMessageType.Text, true, CancellationToken.None); + } + } + } +} \ No newline at end of file