From 8a4375b200e3eb6b70bd402863db976e1e86931a Mon Sep 17 00:00:00 2001 From: SlejmUr Date: Mon, 16 Oct 2023 21:42:01 +0200 Subject: [PATCH] Transition (#30) * transition to MWS * Now its build lobby/chat ws send fixed * using now fixed * hopefully now good * now it somehow connects to wss??? i aint say no for this but ok.. * both handling now the new isconnecting * Fixed for trying to use Debug, Beta at all time Fixed Party Controller not reading Namespace Fixed noupdate would disable Debug --- DS_Server/DS_Server.csproj | 2 + DS_Server/MiddleMan.cs | 1 - DS_Server/MiddleManStarter.cs | 3 +- PayCheckServerLib/HTTPAttribute.cs | 14 - PayCheckServerLib/Helpers/GSController.cs | 33 +- PayCheckServerLib/Helpers/PartyController.cs | 9 +- PayCheckServerLib/PayCheckServerLib.csproj | 4 +- PayCheckServerLib/Responses/BasicResponse.cs | 38 +- PayCheckServerLib/Responses/Challenge.cs | 21 +- PayCheckServerLib/Responses/CloudSave.cs | 73 ++-- PayCheckServerLib/Responses/Currency.cs | 16 +- PayCheckServerLib/Responses/Custom.cs | 18 +- PayCheckServerLib/Responses/DLCs.cs | 19 +- PayCheckServerLib/Responses/Entitlements.cs | 21 +- PayCheckServerLib/Responses/Friends.cs | 20 +- PayCheckServerLib/Responses/GameSessions.cs | 35 +- PayCheckServerLib/Responses/IAM.cs | 76 ++-- PayCheckServerLib/Responses/Items.cs | 17 +- PayCheckServerLib/Responses/LobbyBlocked.cs | 15 +- PayCheckServerLib/Responses/MatchTickets.cs | 18 +- PayCheckServerLib/Responses/Orders.cs | 18 +- PayCheckServerLib/Responses/Parties.cs | 78 ++-- PayCheckServerLib/Responses/Session.cs | 29 +- PayCheckServerLib/Responses/Social.cs | 26 +- PayCheckServerLib/Responses/Telemetry.cs | 10 +- .../Responses/VersionResponse.cs | 38 +- PayCheckServerLib/ServerManager.cs | 76 +++- PayCheckServerLib/Servers/GSTATICServer.cs | 41 -- PayCheckServerLib/Servers/PC3Server.cs | 360 ------------------ PayCheckServerLib/WSController/ChatControl.cs | 58 ++- .../WSController/LobbyControl.cs | 129 +++++-- .../WSController/MiddleManControl.cs | 36 +- 32 files changed, 646 insertions(+), 706 deletions(-) delete mode 100644 PayCheckServerLib/HTTPAttribute.cs delete mode 100644 PayCheckServerLib/Servers/GSTATICServer.cs delete mode 100644 PayCheckServerLib/Servers/PC3Server.cs diff --git a/DS_Server/DS_Server.csproj b/DS_Server/DS_Server.csproj index 5d6c433..8f8113a 100644 --- a/DS_Server/DS_Server.csproj +++ b/DS_Server/DS_Server.csproj @@ -9,6 +9,8 @@ + + diff --git a/DS_Server/MiddleMan.cs b/DS_Server/MiddleMan.cs index f920d0d..eceb33b 100644 --- a/DS_Server/MiddleMan.cs +++ b/DS_Server/MiddleMan.cs @@ -16,7 +16,6 @@ public override void OnWsConnecting(HttpRequest request) request.SetHeader("Upgrade", "websocket"); request.SetHeader("Connection", "Upgrade"); request.SetHeader("Sec-WebSocket-Key", Convert.ToBase64String(WsNonce)); - request.SetHeader("Sec-WebSocket-Protocol", "chat, superchat"); request.SetHeader("Sec-WebSocket-Version", "13"); request.SetHeader("MiddleMan", Id.ToString()); request.SetBody(); diff --git a/DS_Server/MiddleManStarter.cs b/DS_Server/MiddleManStarter.cs index 70b3e0f..d5e2146 100644 --- a/DS_Server/MiddleManStarter.cs +++ b/DS_Server/MiddleManStarter.cs @@ -1,5 +1,6 @@ using NetCoreServer; using System.Security.Authentication; +using ModdableWebServer.Helper; namespace DS_Server { @@ -9,7 +10,7 @@ public class MiddleManStarter static List DS_UDPServers = new List(); public static void Start() { - var context = new SslContext(SslProtocols.Tls12, PayCheckServerLib.PC3Server.GetCert()); + var context = new SslContext(SslProtocols.Tls12, CertHelper.GetCert("cert.pfx","cert")); Client = new MiddleManClient(context, PayCheckServerLib.Helpers.ConfigHelper.ServerConfig.Hosting.IP, 443); Client.Connect(); DS_UDPServers.Add(new("127.0.0.1", 6969)); // THIS is a Qos Server diff --git a/PayCheckServerLib/HTTPAttribute.cs b/PayCheckServerLib/HTTPAttribute.cs deleted file mode 100644 index 833e61b..0000000 --- a/PayCheckServerLib/HTTPAttribute.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace PayCheckServerLib -{ - public class HTTPAttribute : Attribute - { - public string method; - public string url; - - public HTTPAttribute(string method, string url) - { - this.method = method; - this.url = url; - } - } -} diff --git a/PayCheckServerLib/Helpers/GSController.cs b/PayCheckServerLib/Helpers/GSController.cs index a7a451d..982892f 100644 --- a/PayCheckServerLib/Helpers/GSController.cs +++ b/PayCheckServerLib/Helpers/GSController.cs @@ -1,8 +1,11 @@ -using Newtonsoft.Json; +using ModdableWebServer; +using ModdableWebServer.Helper; +using Newtonsoft.Json; using PayCheckServerLib.Jsons.GS; using PayCheckServerLib.Jsons.PartyStuff; using PayCheckServerLib.Responses; using PayCheckServerLib.WSController; +using static PayCheckServerLib.Jsons.GS.OnMatchFound; namespace PayCheckServerLib.Helpers { @@ -15,7 +18,7 @@ public class GSController public static Dictionary Sessions = new(); public static Dictionary Tickets = new(); // Here we making a Full created Match - public static void Make(MatchTickets.TicketReqJson ticketReq, PC3Server.PC3Session session, string NameSpace) + public static void Make(MatchTickets.TicketReqJson ticketReq, ServerStruct serverStruct, string NameSpace) { var party = PartyController.PartySaves.Where(x => x.Value.Id == ticketReq.sessionId).FirstOrDefault().Value; if (party == null) @@ -52,7 +55,7 @@ public static void Make(MatchTickets.TicketReqJson ticketReq, PC3Server.PC3Sessi Version = 1 }; Debugger.PrintDebug("gs!!"); - var team = new Team() + var team = new Jsons.GS.Team() { Parties = new(), UserIDs = new() @@ -97,14 +100,16 @@ public static void Make(MatchTickets.TicketReqJson ticketReq, PC3Server.PC3Sessi }; Debugger.PrintDebug("OnSessionInvited"); // Maybe can be much better this but atleast works - foreach (var vs_ui in session.WSSServer.WSUserIds) + foreach (var key in LobbyControl.LobbyUsers.Keys) { + var splitted = key.Split("_"); + string vs_ui = splitted[1]; foreach (var uid in team.UserIDs) { if (uid == vs_ui) { Debugger.PrintDebug("GS_Session OnSessionInvited sent to " + vs_ui); - LobbyControl.SendToLobby(kv, session.GetWSLobby(vs_ui, NameSpace)); + LobbyControl.SendToLobby(kv, LobbyControl.GetLobbyUser(vs_ui, NameSpace)); } } } @@ -148,7 +153,7 @@ public static GameSession JoinSession(string id, string UserId, string NameSpace return session; } - public static GameSession Patch(PatchGameSessions patchGameSessions, string id, PC3Server.PC3Session pcSession, string NameSpace) + public static GameSession Patch(PatchGameSessions patchGameSessions, string id, ServerStruct serverStruct, string NameSpace) { if (!Sessions.TryGetValue(NameSpace + "_" + id, out var session)) { @@ -157,13 +162,14 @@ public static GameSession Patch(PatchGameSessions patchGameSessions, string id, } //send stuff to middleman var random = new Random(); - var mlist = pcSession.MiddleMans; - int index = random.Next(mlist.Count); - var middleMan = mlist[index]; + int rand = random.Next(0, MiddleManControl.MiddleMans.Count); + var MiddleMan = MiddleManControl.MiddleMans.ElementAt(rand); + //todo get client info string Req = "DSInfoReq-END-" + "eu-central-1," + "624677," + session.Id + "," + NameSpace; Debugger.PrintDebug("Sending to middleman"); - middleMan.Send(Req); + var x = MiddleMan.Value; + WebSocketSender.SendWebSocketText(x, Req); //recieve back here? // PLEASE if you know how to wait better than this, make a PR! while (!DSInfoSentList.Contains(NameSpace + "_" + id)) @@ -228,14 +234,17 @@ public static GameSession Patch(PatchGameSessions patchGameSessions, string id, }; // Maybe can be much better this but atleast works - foreach (var vs_ui in pcSession.WSSServer.WSUserIds) + + foreach (var key in LobbyControl.LobbyUsers.Keys) { + var splitted = key.Split("_"); + string vs_ui = splitted[1]; foreach (var uid in session.Members) { if (uid.Id == vs_ui) { Debugger.PrintDebug("GS_Session OnSessionInvited sent to " + vs_ui); - LobbyControl.SendToLobby(kv, pcSession.GetWSLobby(vs_ui, NameSpace)); + LobbyControl.SendToLobby(kv, LobbyControl.GetLobbyUser(vs_ui, NameSpace)); } } } diff --git a/PayCheckServerLib/Helpers/PartyController.cs b/PayCheckServerLib/Helpers/PartyController.cs index c0a8c4b..8790dd6 100644 --- a/PayCheckServerLib/Helpers/PartyController.cs +++ b/PayCheckServerLib/Helpers/PartyController.cs @@ -1,4 +1,5 @@ -using Newtonsoft.Json; +using ModdableWebServer; +using Newtonsoft.Json; using PayCheckServerLib.Jsons.PartyStuff; namespace PayCheckServerLib.Helpers @@ -88,7 +89,9 @@ public static PartyPost.Response CreateParty(PartyPostReq partyPost, string name LeaderId = rsp.LeaderId, Members = rsp.Members, UpdatedAt = rsp.UpdatedAt, - version = rsp.Version + version = rsp.Version, + NameSpace = nameSpace, + Attributes = rsp.Attributes }; PartySaves.Add(code, saved); Debugger.PrintInfo("New Party made!"); @@ -134,7 +137,7 @@ public static PartyPost.Response UpdateParty(string PartyId, PartyPatch body) return ParsePartyToRSP(party); } - public static void LeftParty(string PartyId, string UserId, PC3Server.PC3Session session) + public static void LeftParty(string PartyId, string UserId, ServerStruct serverStruct) { var party = PartySaves.Where(x => x.Value.Id == PartyId).FirstOrDefault().Value; if (party == null) diff --git a/PayCheckServerLib/PayCheckServerLib.csproj b/PayCheckServerLib/PayCheckServerLib.csproj index 8ead2d5..80a340e 100644 --- a/PayCheckServerLib/PayCheckServerLib.csproj +++ b/PayCheckServerLib/PayCheckServerLib.csproj @@ -34,12 +34,14 @@ - + + + True diff --git a/PayCheckServerLib/Responses/BasicResponse.cs b/PayCheckServerLib/Responses/BasicResponse.cs index 1beeb31..ac98f0e 100644 --- a/PayCheckServerLib/Responses/BasicResponse.cs +++ b/PayCheckServerLib/Responses/BasicResponse.cs @@ -1,4 +1,7 @@ -using NetCoreServer; +using ModdableWebServer; +using ModdableWebServer.Attributes; +using ModdableWebServer.Helper; +using NetCoreServer; using Newtonsoft.Json; using PayCheckServerLib.Helpers; using PayCheckServerLib.Jsons; @@ -7,8 +10,17 @@ namespace PayCheckServerLib.Responses { public class BasicResponse { + [HTTP("HEAD", "/generate_204")] + public static bool Generate204(HttpRequest _, ServerStruct serverStruct) + { + serverStruct.Response.MakeOkResponse(204); + serverStruct.SendResponse(); + return true; + } + + [HTTP("GET", "/qosm/public/qos")] - public static bool QOSM_Public_QOS(HttpRequest request, PC3Server.PC3Session session) + public static bool QOSM_Public_QOS(HttpRequest _, ServerStruct serverStruct) { ResponseCreator response = new ResponseCreator(); response.SetHeader("Content-Type", "application/json"); @@ -31,16 +43,17 @@ public static bool QOSM_Public_QOS(HttpRequest request, PC3Server.PC3Session ses } response.SetBody(JsonConvert.SerializeObject(rsp, Formatting.Indented)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("GET", "/basic/v1/public/misc/time")] - public static bool Time(HttpRequest request, PC3Server.PC3Session session) + public static bool Time(HttpRequest _, ServerStruct serverStruct) { - if (session.Headers.ContainsKey("cookie")) + if (serverStruct.Headers.ContainsKey("cookie")) { - var tokens = TokenHelper.ReadFromHeader(session.Headers); + var tokens = TokenHelper.ReadFromHeader(serverStruct.Headers); Debugger.PrintDebug($"{tokens.AccessToken.UserId}({tokens.AccessToken.Name}) Is still in the server!"); } @@ -52,29 +65,32 @@ public static bool Time(HttpRequest request, PC3Server.PC3Session session) CurrentTime = DateTime.UtcNow.ToString("o") }; response.SetBody(JsonConvert.SerializeObject(rsp)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("GET", "/lobby/v1/messages")] - public static bool LobbyMessages(HttpRequest request, PC3Server.PC3Session session) + public static bool LobbyMessages(HttpRequest _, ServerStruct serverStruct) { ResponseCreator response = new ResponseCreator(); response.SetHeader("Content-Type", "application/json"); response.SetBody(File.ReadAllBytes("Files/messages.json")); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("GET", "/iam/v3/location/country")] - public static bool Country(HttpRequest request, PC3Server.PC3Session session) + public static bool Country(HttpRequest _, ServerStruct serverStruct) { ResponseCreator response = new ResponseCreator(); response.SetHeader("Content-Type", "application/json"); response.SetBody(File.ReadAllBytes("Files/Country.json")); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } } diff --git a/PayCheckServerLib/Responses/Challenge.cs b/PayCheckServerLib/Responses/Challenge.cs index 2e48702..1534589 100644 --- a/PayCheckServerLib/Responses/Challenge.cs +++ b/PayCheckServerLib/Responses/Challenge.cs @@ -1,4 +1,7 @@ -using NetCoreServer; +using ModdableWebServer; +using ModdableWebServer.Attributes; +using ModdableWebServer.Helper; +using NetCoreServer; using Newtonsoft.Json; using PayCheckServerLib.Helpers; using PayCheckServerLib.Jsons; @@ -9,20 +12,21 @@ namespace PayCheckServerLib.Responses public class Challenge { [HTTP("GET", "/challenge/v1/public/namespaces/{namespace}/users/{userId}/eligibility")] - public static bool ChallengeEligibility(HttpRequest _, PC3Server.PC3Session session) + public static bool ChallengeEligibility(HttpRequest _, ServerStruct serverStruct) { ResponseCreator creator = new(); creator.SetBody("{\n \"isComply\": true\n}"); - session.SendResponse(creator.GetResponse()); + serverStruct.Response = creator.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("GET", "/challenge/v1/public/namespaces/{namespace}/users/me/records?limit={limit}&offset={offset}")] - public static bool ChallengeRecordsSplit(HttpRequest _, PC3Server.PC3Session session) + public static bool ChallengeRecordsSplit(HttpRequest _, ServerStruct serverStruct) { - var offset = int.Parse(session.HttpParam["offset"]); - var limit = int.Parse(session.HttpParam["limit"]); - var auth = session.Headers["authorization"].Replace("Bearer ", ""); + var offset = int.Parse(serverStruct.Parameters["offset"]); + var limit = int.Parse(serverStruct.Parameters["limit"]); + var auth = serverStruct.Headers["authorization"].Replace("Bearer ", ""); var token = TokenHelper.ReadToken(auth); ResponseCreator creator = new(); var challenges = JsonConvert.DeserializeObject>(File.ReadAllText("Files/ChallengeRecords.json")) ?? throw new Exception("ChallengeRecords is null!"); @@ -35,7 +39,8 @@ public static bool ChallengeRecordsSplit(HttpRequest _, PC3Server.PC3Session ses } creator.SetBody(JsonConvert.SerializeObject(challenges)); - session.SendResponse(creator.GetResponse()); + serverStruct.Response = creator.GetResponse(); + serverStruct.SendResponse(); return true; } } diff --git a/PayCheckServerLib/Responses/CloudSave.cs b/PayCheckServerLib/Responses/CloudSave.cs index 0cc44cf..c414c5d 100644 --- a/PayCheckServerLib/Responses/CloudSave.cs +++ b/PayCheckServerLib/Responses/CloudSave.cs @@ -3,13 +3,16 @@ using PayCheckServerLib.Helpers; using PayCheckServerLib.Jsons; using PayCheckServerLib.Jsons.Basic; +using ModdableWebServer; +using ModdableWebServer.Attributes; +using ModdableWebServer.Helper; namespace PayCheckServerLib.Responses { public class CloudSave { [HTTP("GET", "/cloudsave/v1/namespaces/{namespace}/records/title-data")] - public static bool TitleData(HttpRequest _, PC3Server.PC3Session session) + public static bool TitleData(HttpRequest _, ServerStruct serverStruct) { ResponseCreator response = new(); TitleData title = new() @@ -18,30 +21,32 @@ public static bool TitleData(HttpRequest _, PC3Server.PC3Session session) CreatedAt = "2023-06-23T07:21:11.604Z", UpdatedAt = "2023-06-23T07:21:11.604Z", Key = "title-data", - Namespace = session.HttpParam["namespace"], + Namespace = serverStruct.Parameters["namespace"], Value = new() { { "TitleData", "My Fancy Title Data" } } }; response.SetBody(JsonConvert.SerializeObject(title)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("GET", "/cloudsave/v1/namespaces/{namespace}/records/news-feed")] - public static bool NewsFeed(HttpRequest _, PC3Server.PC3Session session) + public static bool NewsFeed(HttpRequest _, ServerStruct serverStruct) { ResponseCreator response = new(); //todo: // make into json C# and replace namespace response.SetBody(File.ReadAllText("./Files/NewsFeed.json")); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("GET", "/cloudsave/v1/namespaces/{namespace}/records/infamy-translation-table")] - public static bool InfamyTranslationTable(HttpRequest _, PC3Server.PC3Session session) + public static bool InfamyTranslationTable(HttpRequest _, ServerStruct serverStruct) { ResponseCreator response = new(); //InfamyTranslationTable.Basic; @@ -50,7 +55,7 @@ public static bool InfamyTranslationTable(HttpRequest _, PC3Server.PC3Session se CreatedAt = "2023-06-27T12:18:00.00Z", UpdatedAt = "2023-06-27T12:18:00.00Z", Key = "infamy-translation-table", - Namespace = session.HttpParam["namespace"], + Namespace = serverStruct.Parameters["namespace"], SetBy = "SERVER", Value = new() { @@ -62,12 +67,13 @@ public static bool InfamyTranslationTable(HttpRequest _, PC3Server.PC3Session se var infamylist = JsonConvert.DeserializeObject>(File.ReadAllText("Files/BasicInfamyTable.json")) ?? throw new Exception("BasicInfamyTable is null!"); table.Value.InfamyTranslationTable = infamylist; response.SetBody(JsonConvert.SerializeObject(table)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("POST", "/cloudsave/v1/namespaces/{namespace}/records/bulk")] - public static bool RecordsBulk(HttpRequest request, PC3Server.PC3Session session) + public static bool RecordsBulk(HttpRequest request, ServerStruct serverStruct) { var req = JsonConvert.DeserializeObject(request.Body) ?? throw new Exception("WeaponsTableREQ is null!"); ResponseCreator response = new(); @@ -107,36 +113,39 @@ public static bool RecordsBulk(HttpRequest request, PC3Server.PC3Session session } response.SetBody(JsonConvert.SerializeObject(weaponsTable)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("GET", "/cloudsave/v1/namespaces/{namespace}/records/meta-events")] - public static bool MetaEvents(HttpRequest _, PC3Server.PC3Session session) + public static bool MetaEvents(HttpRequest _, ServerStruct serverStruct) { ResponseCreator response = new(); //todo: // make into json C# and replace namespace response.SetBody(File.ReadAllText("Files/MetaEvents.json")); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("GET", "/cloudsave/v1/namespaces/{namespace}/records/security-firm-rotation")] - public static bool SecurityFirmRotation(HttpRequest _, PC3Server.PC3Session session) + public static bool SecurityFirmRotation(HttpRequest _, ServerStruct serverStruct) { ResponseCreator response = new(); //todo: // make into json C# and replace namespace response.SetBody(File.ReadAllText("Files/FirmRotation.json")); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("GET", "/cloudsave/v1/namespaces/{namespace}/users/{userId}/records/PlatformBlockedPlayerData")] - public static bool PlatformBlockedPlayerData(HttpRequest _, PC3Server.PC3Session session) + public static bool PlatformBlockedPlayerData(HttpRequest _, ServerStruct serverStruct) { - var userID = session.HttpParam["userId"]; + var userID = serverStruct.Parameters["userId"]; ResponseCreator response = new(404); ErrorMSG errorMSG = new() { @@ -144,22 +153,23 @@ public static bool PlatformBlockedPlayerData(HttpRequest _, PC3Server.PC3Session ErrorMessage = $"unable to get_player_record: player record not found, user ID: {userID}, key: PlatformBlockedPlayerData" }; response.SetBody(JsonConvert.SerializeObject(errorMSG)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("GET", "/cloudsave/v1/namespaces/{namespace}/users/{userId}/records/progressionsavegame")] - public static bool ProgressionsavegameGET(HttpRequest _, PC3Server.PC3Session session) + public static bool ProgressionsavegameGET(HttpRequest _, ServerStruct serverStruct) { - var userID = session.HttpParam["userId"]; + var userID = serverStruct.Parameters["userId"]; var response = new ResponseCreator(); - if (SaveHandler.IsUserExist(userID, session.HttpParam["namespace"])) + if (SaveHandler.IsUserExist(userID, serverStruct.Parameters["namespace"])) { Progression.Basic? save = null; try { - save = Progression.Basic.FromJson(SaveHandler.ReadUserSTR(userID, session.HttpParam["namespace"])); + save = Progression.Basic.FromJson(SaveHandler.ReadUserSTR(userID, serverStruct.Parameters["namespace"])); save.ProgressionSaveGame.LastTimeEventCheck = TimeHelper.GetEpochTime(); } catch @@ -175,11 +185,12 @@ public static bool ProgressionsavegameGET(HttpRequest _, PC3Server.PC3Session se Value = save, IsPublic = false, Key = "progressionsavegame", - Namespace = session.HttpParam["namespace"], + Namespace = serverStruct.Parameters["namespace"], SetBy = "CLIENT" }; response.SetBody(JsonConvert.SerializeObject(saveRSP, Progression.Converter.Settings)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } response = new ResponseCreator(404); @@ -189,17 +200,18 @@ public static bool ProgressionsavegameGET(HttpRequest _, PC3Server.PC3Session se ErrorMessage = $"unable to get_player_record: player record not found, user ID: {userID}, key: progressionsavegame" }; response.SetBody(JsonConvert.SerializeObject(error)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("POST", "/cloudsave/v1/namespaces/{namespace}/users/{userId}/records/progressionsavegame")] - public static bool ProgressionsavegamePOST(HttpRequest request, PC3Server.PC3Session session) + public static bool ProgressionsavegamePOST(HttpRequest request, ServerStruct serverStruct) { - var userID = session.HttpParam["userId"]; - SaveHandler.SaveUser(userID, session.HttpParam["namespace"], request.BodyBytes); + var userID = serverStruct.Parameters["userId"]; + SaveHandler.SaveUser(userID, serverStruct.Parameters["namespace"], request.BodyBytes); if (ConfigHelper.ServerConfig.Saves.SaveRequest) - SaveHandler.SaveUser_Request(userID, session.HttpParam["namespace"], request.Body); + SaveHandler.SaveUser_Request(userID, serverStruct.Parameters["namespace"], request.Body); Progression.Basic? save = null; try @@ -220,12 +232,13 @@ public static bool ProgressionsavegamePOST(HttpRequest request, PC3Server.PC3Ses Value = save, IsPublic = false, Key = "progressionsavegame", - Namespace = session.HttpParam["namespace"], + Namespace = serverStruct.Parameters["namespace"], SetBy = "CLIENT" }; ResponseCreator response = new(); response.SetBody(JsonConvert.SerializeObject(saveRSP, Progression.Converter.Settings)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } } diff --git a/PayCheckServerLib/Responses/Currency.cs b/PayCheckServerLib/Responses/Currency.cs index 0e03013..3021fc7 100644 --- a/PayCheckServerLib/Responses/Currency.cs +++ b/PayCheckServerLib/Responses/Currency.cs @@ -1,4 +1,7 @@ -using NetCoreServer; +using ModdableWebServer; +using ModdableWebServer.Attributes; +using ModdableWebServer.Helper; +using NetCoreServer; using Newtonsoft.Json; using PayCheckServerLib.Helpers; using PayCheckServerLib.Jsons; @@ -8,11 +11,11 @@ namespace PayCheckServerLib.Responses public class Currency { [HTTP("GET", "/platform/public/namespaces/{namespace}/users/{userId}/wallets/{currency}")] - public static bool GetUserCurrency(HttpRequest request, PC3Server.PC3Session session) + public static bool GetUserCurrency(HttpRequest request, ServerStruct serverStruct) { - var userID = session.HttpParam["userId"]; - var currencyType = session.HttpParam["currency"]; - var nspace = session.HttpParam["namespace"]; + var userID = serverStruct.Parameters["userId"]; + var currencyType = serverStruct.Parameters["currency"]; + var nspace = serverStruct.Parameters["namespace"]; var currencySymbol = currencyType == "CRED" ? "CREDITS" : currencyType; // return fake data for now Debugger.PrintDebug(String.Format("{0}_{1}_{2}", nspace, userID, currencyType)); @@ -51,7 +54,8 @@ public static bool GetUserCurrency(HttpRequest request, PC3Server.PC3Session ses WalletStatus = "ACTIVE" }; response.SetBody(JsonConvert.SerializeObject(currencyReponse)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } } diff --git a/PayCheckServerLib/Responses/Custom.cs b/PayCheckServerLib/Responses/Custom.cs index 991a54d..c94ee96 100644 --- a/PayCheckServerLib/Responses/Custom.cs +++ b/PayCheckServerLib/Responses/Custom.cs @@ -1,4 +1,7 @@ -using NetCoreServer; +using ModdableWebServer; +using ModdableWebServer.Attributes; +using ModdableWebServer.Helper; +using NetCoreServer; using PayCheckServerLib.Helpers; namespace PayCheckServerLib.Responses @@ -6,16 +9,17 @@ namespace PayCheckServerLib.Responses public class Custom { [HTTP("POST", "/register?username={username}&platformId={pid}&platformType={ptype}&nspace={nspace}")] - public static bool RegisterUser(HttpRequest request, PC3Server.PC3Session session) + public static bool RegisterUser(HttpRequest _, ServerStruct serverStruct) { - var username = session.HttpParam["username"]; - var platformId = session.HttpParam["pid"]; - var platformType = session.HttpParam["ptype"]; + var username = serverStruct.Parameters["username"]; + var platformId = serverStruct.Parameters["pid"]; + var platformType = serverStruct.Parameters["ptype"]; var platform = (TokenHelper.TokenPlatform)uint.Parse(platformType); - var nspace = session.HttpParam["nspace"]; + var nspace = serverStruct.Parameters["nspace"]; UserController.RegisterUser(platformId, platform, username, nspace); - session.SendResponse(session.Response.MakeOkResponse()); + serverStruct.Response.MakeOkResponse(); + serverStruct.SendResponse(); return true; } } diff --git a/PayCheckServerLib/Responses/DLCs.cs b/PayCheckServerLib/Responses/DLCs.cs index bcd0df6..117ab90 100644 --- a/PayCheckServerLib/Responses/DLCs.cs +++ b/PayCheckServerLib/Responses/DLCs.cs @@ -1,4 +1,7 @@ -using NetCoreServer; +using ModdableWebServer; +using ModdableWebServer.Attributes; +using ModdableWebServer.Helper; +using NetCoreServer; using Newtonsoft.Json; using PayCheckServerLib.Jsons.Basic; @@ -23,26 +26,27 @@ public partial class DLC_Value - [HTTP("PUT", "/platform/public/namespaces/{namespace}/users/{UserId}/dlc/steam/sync")] - public static bool PUT_DLC_SteamSync(HttpRequest request, PC3Server.PC3Session session) + [HTTP("PUT", "/platform/public/namespaces/{namespace}/users/{userid}/dlc/steam/sync")] + public static bool PUT_DLC_SteamSync(HttpRequest _, ServerStruct serverStruct) { //var body = JsonConvert.DeserializeObject(request.Body); ResponseCreator response = new ResponseCreator(204); response.SetHeader("Content-Type", "application/json"); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); ; return true; } [HTTP("GET", "/cloudsave/v1/namespaces/{namespace}/records/dlc-entitlements")] - public static bool GETdlcentitlements(HttpRequest request, PC3Server.PC3Session session) + public static bool GETdlcentitlements(HttpRequest _, ServerStruct serverStruct) { TopLevel dlc = new() { SetBy = "SERVER", CreatedAt = "2023-09-25T12:01:02.096Z", Key = "dlc-entitlements", - Namespace = session.HttpParam["namespace"], + Namespace = serverStruct.Parameters["namespace"], UpdatedAt = "2023-09-25T12:01:02.096Z", Value = new() { @@ -55,7 +59,8 @@ public static bool GETdlcentitlements(HttpRequest request, PC3Server.PC3Session ResponseCreator response = new ResponseCreator(); response.SetHeader("Content-Type", "application/json"); response.SetBody(JsonConvert.SerializeObject(dlc)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } } diff --git a/PayCheckServerLib/Responses/Entitlements.cs b/PayCheckServerLib/Responses/Entitlements.cs index 6914f6a..7a0e29d 100644 --- a/PayCheckServerLib/Responses/Entitlements.cs +++ b/PayCheckServerLib/Responses/Entitlements.cs @@ -1,4 +1,7 @@ -using NetCoreServer; +using ModdableWebServer; +using ModdableWebServer.Attributes; +using ModdableWebServer.Helper; +using NetCoreServer; using Newtonsoft.Json; using PayCheckServerLib.Jsons; using PayCheckServerLib.Jsons.Basic; @@ -8,7 +11,7 @@ namespace PayCheckServerLib.Responses public class Entitlements { [HTTP("GET", "/platform/public/namespaces/{namespace}/users/{userId}/entitlements?limit={limit}")] - public static bool GetUserEntitlements(HttpRequest _, PC3Server.PC3Session session) + public static bool GetUserEntitlements(HttpRequest _, ServerStruct serverStruct) { try { @@ -17,7 +20,7 @@ public static bool GetUserEntitlements(HttpRequest _, PC3Server.PC3Session sessi var newentitlements = new List(); foreach (var entitlement in entitlements.Data) { - entitlement.UserId = session.HttpParam["userId"]; + entitlement.UserId = serverStruct.Parameters["userId"]; newentitlements.Add(entitlement); } DataPaging payload = new() @@ -32,7 +35,8 @@ public static bool GetUserEntitlements(HttpRequest _, PC3Server.PC3Session sessi } }; responsecreator.SetBody(JsonConvert.SerializeObject(payload)); - session.SendResponse(responsecreator.GetResponse()); + serverStruct.Response = responsecreator.GetResponse(); + serverStruct.SendResponse(); return true; } catch (Exception ex) @@ -43,7 +47,7 @@ public static bool GetUserEntitlements(HttpRequest _, PC3Server.PC3Session sessi } [HTTP("GET", "/platform/public/namespaces/{namespace}/users/{userId}/entitlements?itemId={itemid}&limit={limit}")] - public static bool GetUserEntitlementsByItemId(HttpRequest _, PC3Server.PC3Session session) + public static bool GetUserEntitlementsByItemId(HttpRequest _, ServerStruct serverStruct) { try { @@ -52,9 +56,9 @@ public static bool GetUserEntitlementsByItemId(HttpRequest _, PC3Server.PC3Sessi var newentitlements = new List(); foreach (var entitlement in entitlements.Data) { - if (entitlement.ItemId == session.HttpParam["itemid"]) + if (entitlement.ItemId == serverStruct.Parameters["itemid"]) { - entitlement.UserId = session.HttpParam["userId"]; + entitlement.UserId = serverStruct.Parameters["userId"]; newentitlements.Add(entitlement); } @@ -71,7 +75,8 @@ public static bool GetUserEntitlementsByItemId(HttpRequest _, PC3Server.PC3Sessi } }; responsecreator.SetBody(JsonConvert.SerializeObject(payload)); - session.SendResponse(responsecreator.GetResponse()); + serverStruct.Response = responsecreator.GetResponse(); + serverStruct.SendResponse(); return true; } catch (Exception ex) diff --git a/PayCheckServerLib/Responses/Friends.cs b/PayCheckServerLib/Responses/Friends.cs index f0cc42d..3689336 100644 --- a/PayCheckServerLib/Responses/Friends.cs +++ b/PayCheckServerLib/Responses/Friends.cs @@ -1,4 +1,7 @@ -using NetCoreServer; +using ModdableWebServer; +using ModdableWebServer.Attributes; +using ModdableWebServer.Helper; +using NetCoreServer; using Newtonsoft.Json; using PayCheckServerLib.Helpers; using PayCheckServerLib.Jsons; @@ -8,9 +11,9 @@ namespace PayCheckServerLib.Responses public class Friends { [HTTP("GET", "/friends/namespaces/{namespace}/me/platforms")] - public static bool MePlatforms(HttpRequest _, PC3Server.PC3Session session) + public static bool MePlatforms(HttpRequest _, ServerStruct serverStruct) { - var auth = session.Headers["authorization"].Replace("Bearer ", ""); + var auth = serverStruct.Headers["authorization"].Replace("Bearer ", ""); var token = TokenHelper.ReadToken(auth); var MainUser = UserController.GetUser(token.UserId, token.Namespace) ?? throw new Exception("MainUser is null!"); ResponseCreator response = new(); @@ -20,14 +23,15 @@ public static bool MePlatforms(HttpRequest _, PC3Server.PC3Session session) Data = MainUser.Friends }; response.SetBody(JsonConvert.SerializeObject(friends)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("POST", "/friends/namespaces/{namespace}/users/{userId}/add/bulk")] - public static bool FriendAddBulk(HttpRequest request, PC3Server.PC3Session session) + public static bool FriendAddBulk(HttpRequest request, ServerStruct serverStruct) { - var auth = session.Headers["authorization"].Replace("Bearer ", ""); + var auth = serverStruct.Headers["authorization"].Replace("Bearer ", ""); var token = TokenHelper.ReadToken(auth); var MainUser = UserController.GetUser(token.UserId, token.Namespace) ?? throw new Exception("MainUser is null!"); var friends = JsonConvert.DeserializeObject(request.Body)!.FriendIds; @@ -63,8 +67,8 @@ public static bool FriendAddBulk(HttpRequest request, PC3Server.PC3Session sessi MainUser.Friends.Add(data); } - ResponseCreator response = new(204); - session.SendResponse(response.GetResponse()); + serverStruct.Response = new ResponseCreator(204).GetResponse(); + serverStruct.SendResponse(); return true; } } diff --git a/PayCheckServerLib/Responses/GameSessions.cs b/PayCheckServerLib/Responses/GameSessions.cs index c492aa4..62a2dce 100644 --- a/PayCheckServerLib/Responses/GameSessions.cs +++ b/PayCheckServerLib/Responses/GameSessions.cs @@ -3,22 +3,25 @@ using PayCheckServerLib.Helpers; using PayCheckServerLib.Jsons.GS; using PayCheckServerLib.WSController; +using ModdableWebServer; +using ModdableWebServer.Attributes; +using ModdableWebServer.Helper; namespace PayCheckServerLib.Responses { public class GameSessions { [HTTP("GET", "/session/v1/public/namespaces/{namespace}/gamesessions/{sessionid}")] - public static bool GETGameSessions(HttpRequest _, PC3Server.PC3Session session) + public static bool GETGameSessions(HttpRequest _, ServerStruct serverStruct) { - var auth = session.Headers["authorization"].Replace("Bearer ", ""); + var auth = serverStruct.Headers["authorization"].Replace("Bearer ", ""); var token = TokenHelper.ReadToken(auth); ResponseCreator response = new(); response.SetHeader("Content-Type", "application/json"); - var gs = GSController.GetGameSession(session.HttpParam["sessionid"], session.HttpParam["namespace"]); + var gs = GSController.GetGameSession(serverStruct.Parameters["sessionid"], serverStruct.Parameters["namespace"]); response.SetBody(JsonConvert.SerializeObject(gs)); - session.SendResponse(response.GetResponse()); - + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); if (GSController.MatchFoundSent.Contains(token.UserId)) return true; @@ -57,20 +60,21 @@ public static bool GETGameSessions(HttpRequest _, PC3Server.PC3Session session) { "payload", LobbyControl.Base64Encode(JsonConvert.SerializeObject(onMatchFound)) }, { "sentAt", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ") }, }; - LobbyControl.SendToLobby(kv, session.GetWSLobby(token.UserId, token.Namespace)); + LobbyControl.SendToLobby(kv, LobbyControl.GetLobbyUser(token.UserId, token.Namespace)); GSController.MatchFoundSent.Add(token.UserId); Debugger.PrintDebug("MatchFoundSent!"); return true; } [HTTP("PATCH", "/session/v1/public/namespaces/{namespace}/gamesessions/{sessionid}")] - public static bool PATCHGameSessions(HttpRequest _, PC3Server.PC3Session session) + public static bool PATCHGameSessions(HttpRequest _, ServerStruct serverStruct) { Debugger.PrintDebug("PATCH! gamesessions"); ResponseCreator response = new(); response.SetHeader("Content-Type", "application/json"); //response.SetBody(JsonConvert.SerializeObject(gamesessions)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); //OnDSStatusChanged @@ -78,15 +82,16 @@ public static bool PATCHGameSessions(HttpRequest _, PC3Server.PC3Session session } [HTTP("POST", "/session/v1/public/namespaces/{namespace}/gamesessions/{sessionid}/join")] - public static bool JoinToGameSessions(HttpRequest _, PC3Server.PC3Session session) + public static bool JoinToGameSessions(HttpRequest _, ServerStruct serverStruct) { - var auth = session.Headers["authorization"].Replace("Bearer ", ""); + var auth = serverStruct.Headers["authorization"].Replace("Bearer ", ""); var token = TokenHelper.ReadToken(auth); - var gs = GSController.JoinSession(session.HttpParam["sessionid"], token.UserId, session.HttpParam["namespace"]); + var gs = GSController.JoinSession(serverStruct.Parameters["sessionid"], token.UserId, serverStruct.Parameters["namespace"]); ResponseCreator response = new(); response.SetHeader("Content-Type", "application/json"); response.SetBody(JsonConvert.SerializeObject(gs)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); //Send OnSessionMembersChanged, OnSessionJoined OnSessionJoined onSessionJoined = new() @@ -102,7 +107,7 @@ public static bool JoinToGameSessions(HttpRequest _, PC3Server.PC3Session sessio { "payload", LobbyControl.Base64Encode(JsonConvert.SerializeObject(onSessionJoined)) }, { "sentAt", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ") }, }; - LobbyControl.SendToLobby(kv, session.GetWSLobby(token.UserId, token.Namespace)); + LobbyControl.SendToLobby(kv, LobbyControl.GetLobbyUser(token.UserId, token.Namespace)); OnSessionMembersChanged onSessionMembersChanged = new() @@ -165,12 +170,12 @@ public static bool JoinToGameSessions(HttpRequest _, PC3Server.PC3Session sessio }; //OnMemeberChanged to full team? - LobbyControl.SendToLobby(kv, session.GetWSLobby(token.UserId, token.Namespace)); + LobbyControl.SendToLobby(kv, LobbyControl.GetLobbyUser(token.UserId, token.Namespace)); return true; } [HTTP("DELETE", "/session/v1/public/namespaces/{namespace}/gamesessions/{sessionid}/leave")] - public static bool LeaveGameSessions(HttpRequest _, PC3Server.PC3Session session) + public static bool LeaveGameSessions(HttpRequest _, ServerStruct serverStruct) { return false; } diff --git a/PayCheckServerLib/Responses/IAM.cs b/PayCheckServerLib/Responses/IAM.cs index 186379a..423c680 100644 --- a/PayCheckServerLib/Responses/IAM.cs +++ b/PayCheckServerLib/Responses/IAM.cs @@ -4,13 +4,16 @@ using PayCheckServerLib.Jsons; using PayCheckServerLib.Jsons.Basic; using System.Web; +using ModdableWebServer; +using ModdableWebServer.Attributes; +using ModdableWebServer.Helper; namespace PayCheckServerLib.Responses { public class IAM { [HTTP("POST", "/iam/v3/oauth/platforms/steam/token")] - public static bool SteamToken(HttpRequest request, PC3Server.PC3Session session) + public static bool SteamToken(HttpRequest request, ServerStruct serverStruct) { ResponseCreator response = new(); if (ConfigHelper.ServerConfig.InDevFeatures.UsePWInsteadSteamToken) @@ -27,7 +30,8 @@ public static bool SteamToken(HttpRequest request, PC3Server.PC3Session session) to get game to allow email + password auth */ response.SetBody(JsonConvert.SerializeObject(new IAM_SteamError())); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } Debugger.PrintDebug(request.Body); @@ -50,7 +54,7 @@ to get game to allow email + password auth var steamId = UserIdHelper.GetSteamIDFromAUTH(platform_token); Debugger.PrintInfo("User with SteamID try to log in: " + steamId); - var (access_token, refresh_token) = UserController.LoginUser(steamId, TokenHelper.TokenPlatform.Steam, session.Headers["namespace"]); + var (access_token, refresh_token) = UserController.LoginUser(steamId, TokenHelper.TokenPlatform.Steam, serverStruct.Headers["namespace"]); response.SetHeader("Content-Type", "application/json"); response.SetHeader("Connection", "keep-alive"); @@ -69,7 +73,7 @@ to get game to allow email + password auth ExpiresIn = 360000, IsComply = true, Jflgs = 1, - Namespace = session.Headers["namespace"], + Namespace = serverStruct.Headers["namespace"], NamespaceRoles = new() { new NamespaceRole() @@ -89,16 +93,17 @@ to get game to allow email + password auth UserId = access_token.UserId }; response.SetBody(JsonConvert.SerializeObject(LoginToken)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("POST", "/iam/v3/oauth/platforms/device/token")] - public static bool DeviceToken(HttpRequest request, PC3Server.PC3Session session) + public static bool DeviceToken(HttpRequest request, ServerStruct serverStruct) { var deviceid = request.Body.Split('=')[1]; Debugger.PrintDebug(deviceid); - var (access_token, refresh_token) = UserController.LoginUser(deviceid, TokenHelper.TokenPlatform.Device, session.Headers["namespace"]); + var (access_token, refresh_token) = UserController.LoginUser(deviceid, TokenHelper.TokenPlatform.Device, serverStruct.Headers["namespace"]); ResponseCreator response = new(); response.SetHeader("Content-Type", "application/json"); @@ -114,7 +119,7 @@ public static bool DeviceToken(HttpRequest request, PC3Server.PC3Session session ExpiresIn = 360000, IsComply = true, Jflgs = 4, - Namespace = session.Headers["namespace"], + Namespace = serverStruct.Headers["namespace"], NamespaceRoles = new() { new NamespaceRole() @@ -133,13 +138,14 @@ public static bool DeviceToken(HttpRequest request, PC3Server.PC3Session session UserId = access_token.UserId }; response.SetBody(JsonConvert.SerializeObject(token)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("POST", "/iam/v3/oauth/platforms/live/token")] - public static bool LiveToken(HttpRequest request, PC3Server.PC3Session session) + public static bool LiveToken(HttpRequest request, ServerStruct serverStruct) { var splitted = request.Body.Split("&"); Dictionary bodyTokens = new(); @@ -153,7 +159,7 @@ public static bool LiveToken(HttpRequest request, PC3Server.PC3Session session) Debugger.PrintDebug(platform_token); platform_token = platform_token.Replace("XBL3.0%20x%3D", ""); platform_token = platform_token.Split(";")[0]; - var (access_token, refresh_token) = UserController.LoginUser(platform_token, TokenHelper.TokenPlatform.Live, session.Headers["namespace"]); + var (access_token, refresh_token) = UserController.LoginUser(platform_token, TokenHelper.TokenPlatform.Live, serverStruct.Headers["namespace"]); ResponseCreator response = new(); response.SetHeader("Content-Type", "application/json"); @@ -169,7 +175,7 @@ public static bool LiveToken(HttpRequest request, PC3Server.PC3Session session) ExpiresIn = 360000, IsComply = true, Jflgs = 4, - Namespace = session.Headers["namespace"], + Namespace = serverStruct.Headers["namespace"], NamespaceRoles = new() { new NamespaceRole() @@ -188,13 +194,14 @@ public static bool LiveToken(HttpRequest request, PC3Server.PC3Session session) UserId = access_token.UserId }; response.SetBody(JsonConvert.SerializeObject(token)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } // Logging in with email + password, also links steam to nebula account on official servers [HTTP("POST", "/iam/v3/authenticateWithLink")] - public static bool AuthenticateWithLink(HttpRequest request, PC3Server.PC3Session session) + public static bool AuthenticateWithLink(HttpRequest request, ServerStruct serverStruct) { var param = HttpUtility.ParseQueryString(request.Body); // either username or email entered @@ -205,7 +212,7 @@ public static bool AuthenticateWithLink(HttpRequest request, PC3Server.PC3Sessio var client_id = param["client_id"]; // request does not have a device id, client_id will do for now - var (access_token, refresh_token) = UserController.LoginUser(client_id!, TokenHelper.TokenPlatform.Device, session.Headers["namespace"]); + var (access_token, refresh_token) = UserController.LoginUser(client_id!, TokenHelper.TokenPlatform.Device, serverStruct.Headers["namespace"]); ResponseCreator response = new(); response.SetHeader("Content-Type", "application/json"); @@ -241,15 +248,16 @@ public static bool AuthenticateWithLink(HttpRequest request, PC3Server.PC3Sessio UserId = access_token.UserId }; response.SetBody(JsonConvert.SerializeObject(token)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("GET", "/iam/v3/public/users/me")] - public static bool UsersMe(HttpRequest _, PC3Server.PC3Session session) + public static bool UsersMe(HttpRequest _, ServerStruct serverStruct) { - var auth = session.Headers["authorization"].Replace("Bearer ", ""); + var auth = serverStruct.Headers["authorization"].Replace("Bearer ", ""); var token = TokenHelper.ReadToken(auth); ResponseCreator response = new(); response.SetHeader("Content-Type", "application/json"); @@ -264,7 +272,7 @@ public static bool UsersMe(HttpRequest _, PC3Server.PC3Session session) EmailAddress = $"{token.Name}@pd3_emu.com", EmailVerified = true, Enabled = true, - Namespace = session.Headers["namespace"], + Namespace = serverStruct.Headers["namespace"], OldEmailAddress = $"{token.Name}@pd3_emu.com", PhoneVerified = true, Permissions = new(), @@ -281,12 +289,13 @@ public static bool UsersMe(HttpRequest _, PC3Server.PC3Session session) Roles = new() { "2251438839e948d783ec0e5281daf05" } }; response.SetBody(JsonConvert.SerializeObject(me)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("POST", "/iam/v3/public/namespaces/{namespace}/users/bulk/basic")] - public static bool BulkBasic(HttpRequest request, PC3Server.PC3Session session) + public static bool BulkBasic(HttpRequest request, ServerStruct serverStruct) { var req = JsonConvert.DeserializeObject(request.Body) ?? throw new Exception("BulkBasic is null!"); ResponseCreator response = new(); @@ -309,21 +318,22 @@ public static bool BulkBasic(HttpRequest request, PC3Server.PC3Session session) } else { - if (user.Namespace == session.Headers["namespace"]) + if (user.Namespace == serverStruct.Headers["namespace"]) bulk.Data.Add(user.UserData); } } response.SetBody(JsonConvert.SerializeObject(bulk)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("GET", "/iam/v3/public/namespaces/{namespace}/users?query={uname}&by=displayName&limit=100&offset=0")] - public static bool UsersQuery(HttpRequest _, PC3Server.PC3Session session) + public static bool UsersQuery(HttpRequest _, ServerStruct serverStruct) { //Idk what is this but works - var username = session.HttpParam["uname"]; + var username = serverStruct.Parameters["uname"]; username = username.Split("&")[0].Split("=")[1]; //magix shit end Debugger.PrintDebug("UserName to search: " + username); @@ -344,7 +354,7 @@ public static bool UsersQuery(HttpRequest _, PC3Server.PC3Session session) foreach (var item in UserController.GetUsers()) { - if (item.Namespace != session.HttpParam["namespace"]) + if (item.Namespace != serverStruct.Parameters["namespace"]) continue; if (item.UserData.DisplayName.Contains(username)) @@ -363,12 +373,13 @@ public static bool UsersQuery(HttpRequest _, PC3Server.PC3Session session) } response.SetBody(JsonConvert.SerializeObject(dataSearch)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("POST", "/iam/v3/public/namespaces/{namespace}/platforms/steam/users?rawPUID=true")] - public static bool GetSteamUsersWithPID(HttpRequest request, PC3Server.PC3Session session) + public static bool GetSteamUsersWithPID(HttpRequest request, ServerStruct serverStruct) { var req = JsonConvert.DeserializeObject(request.Body); ResponseCreator response = new(); @@ -383,10 +394,10 @@ public static bool GetSteamUsersWithPID(HttpRequest request, PC3Server.PC3Sessio foreach (var id in req.platformUserIds) { - //can replace the headers to session.HttpParam["namespace"] and will works too - if (UserController.CheckUser(id, TokenHelper.TokenPlatform.Steam, session.Headers["namespace"])) + //can replace the headers to serverStruct.Parameters["namespace"] and will works too + if (UserController.CheckUser(id, TokenHelper.TokenPlatform.Steam, serverStruct.Headers["namespace"])) { - var user = UserController.GetUser(id, TokenHelper.TokenPlatform.Steam, session.Headers["namespace"]); + var user = UserController.GetUser(id, TokenHelper.TokenPlatform.Steam, serverStruct.Headers["namespace"]); steamUsers.userIdPlatforms.Add(new() { platformId = "steam", @@ -399,7 +410,8 @@ public static bool GetSteamUsersWithPID(HttpRequest request, PC3Server.PC3Sessio } response.SetBody(JsonConvert.SerializeObject(steamUsers)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } } diff --git a/PayCheckServerLib/Responses/Items.cs b/PayCheckServerLib/Responses/Items.cs index 75a9ed8..6783433 100644 --- a/PayCheckServerLib/Responses/Items.cs +++ b/PayCheckServerLib/Responses/Items.cs @@ -1,4 +1,7 @@ -using NetCoreServer; +using ModdableWebServer; +using ModdableWebServer.Attributes; +using ModdableWebServer.Helper; +using NetCoreServer; using Newtonsoft.Json; using PayCheckServerLib.Jsons; using PayCheckServerLib.Jsons.Basic; @@ -8,7 +11,7 @@ namespace PayCheckServerLib.Responses public class Items { [HTTP("GET", "/platform/public/namespaces/{namespace}/items/byCriteria?limit={limit}&includeSubCategoryItem=false")] - public static bool GetItemsByCriteria(HttpRequest _, PC3Server.PC3Session session) + public static bool GetItemsByCriteria(HttpRequest _, ServerStruct serverStruct) { ResponseCreator creator = new(); var items = JsonConvert.DeserializeObject>(File.ReadAllText("./Files/Items.json")); @@ -18,12 +21,13 @@ public static bool GetItemsByCriteria(HttpRequest _, PC3Server.PC3Session sessio item.UpdatedAt = timeMrFreeman; } creator.SetBody(JsonConvert.SerializeObject(items)); - session.SendResponse(creator.GetResponse()); + serverStruct.Response = creator.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("GET", "/platform/public/namespaces/{namespace}/items/byCriteria?tags={tags}&limit={limit}&includeSubCategoryItem=false")] - public static bool GetItemsByCriteriaByTags(HttpRequest _, PC3Server.PC3Session session) + public static bool GetItemsByCriteriaByTags(HttpRequest _, ServerStruct serverStruct) { ResponseCreator creator = new(); var items = JsonConvert.DeserializeObject>(File.ReadAllText("./Files/Items.json")) ?? throw new Exception("Items is null!"); @@ -34,7 +38,7 @@ public static bool GetItemsByCriteriaByTags(HttpRequest _, PC3Server.PC3Session item.UpdatedAt = timeMrFreeman; if (item.Tags != null) { - if (item.Tags.Contains(session.HttpParam["tags"])) + if (item.Tags.Contains(serverStruct.Parameters["tags"])) { finalitems.Add(item); } @@ -46,7 +50,8 @@ public static bool GetItemsByCriteriaByTags(HttpRequest _, PC3Server.PC3Session Paging = { } }; creator.SetBody(JsonConvert.SerializeObject(tosend)); - session.SendResponse(creator.GetResponse()); + serverStruct.Response = creator.GetResponse(); + serverStruct.SendResponse(); return true; } } diff --git a/PayCheckServerLib/Responses/LobbyBlocked.cs b/PayCheckServerLib/Responses/LobbyBlocked.cs index da2ebba..45109c3 100644 --- a/PayCheckServerLib/Responses/LobbyBlocked.cs +++ b/PayCheckServerLib/Responses/LobbyBlocked.cs @@ -1,24 +1,29 @@ -using NetCoreServer; +using ModdableWebServer; +using ModdableWebServer.Attributes; +using ModdableWebServer.Helper; +using NetCoreServer; namespace PayCheckServerLib.Responses { public class LobbyBlocked { [HTTP("GET", "/lobby/v1/public/player/namespaces/{namespace}/users/me/blocked-by")] - public static bool Blocked(HttpRequest request, PC3Server.PC3Session session) + public static bool Blocked(HttpRequest _, ServerStruct serverStruct) { ResponseCreator response = new(); response.SetBody("{\r\n \"data\": []\r\n}"); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("GET", "/lobby/v1/public/player/namespaces/{namespace}/users/me/blocked")] - public static bool BlockedBy(HttpRequest request, PC3Server.PC3Session session) + public static bool BlockedBy(HttpRequest _, ServerStruct serverStruct) { ResponseCreator response = new(); response.SetBody("{\r\n \"data\": []\r\n}"); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } } diff --git a/PayCheckServerLib/Responses/MatchTickets.cs b/PayCheckServerLib/Responses/MatchTickets.cs index ad2df20..cd734d7 100644 --- a/PayCheckServerLib/Responses/MatchTickets.cs +++ b/PayCheckServerLib/Responses/MatchTickets.cs @@ -2,6 +2,9 @@ using Newtonsoft.Json; using PayCheckServerLib.Helpers; using PayCheckServerLib.WSController; +using ModdableWebServer; +using ModdableWebServer.Attributes; +using ModdableWebServer.Helper; namespace PayCheckServerLib.Responses { @@ -30,20 +33,21 @@ public class WSS_OnMatchmakingStarted } [HTTP("POST", "/match2/v1/namespaces/{namespace}/match-tickets")] - public static bool Tickets(HttpRequest request, PC3Server.PC3Session session) + public static bool Tickets(HttpRequest request, ServerStruct serverStruct) { - var auth = session.Headers["authorization"].Replace("Bearer ", ""); + var auth = serverStruct.Headers["authorization"].Replace("Bearer ", ""); var token = TokenHelper.ReadToken(auth); var ticket = JsonConvert.DeserializeObject(request.Body); var ticketId = UserIdHelper.CreateNewID(); TicketRspJson ticketRsp = new() { matchTicketID = ticketId, - queueTime = 2 + queueTime = 5 }; ResponseCreator response = new(); response.SetBody(JsonConvert.SerializeObject(ticketRsp)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); Debugger.PrintDebug("OnMatchmakingStarted YEET"); //Store Both and send into Lobby WSS @@ -53,7 +57,7 @@ public static bool Tickets(HttpRequest request, PC3Server.PC3Session session) PartyID = ticket.sessionId, CreatedAt = DateTime.UtcNow.ToString("o"), MatchPool = ticket.matchPool, - Namespace = session.Headers["namespace"] + Namespace = serverStruct.Headers["namespace"] }; Dictionary resp = new() { @@ -65,8 +69,8 @@ public static bool Tickets(HttpRequest request, PC3Server.PC3Session session) { "payload", LobbyControl.Base64Encode(JsonConvert.SerializeObject(onMatchmakingStarted)) }, { "sentAt", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ") } }; - LobbyControl.SendToLobby(resp, session.GetWSLobby(token.UserId, token.Namespace)); - GSController.Make(ticket, session, session.Headers["namespace"]); + LobbyControl.SendToLobby(resp, LobbyControl.GetLobbyUser(token.UserId, token.Namespace)); + GSController.Make(ticket, serverStruct, serverStruct.Headers["namespace"]); GSController.Tickets.Add(token.UserId, ticketId); /* * Need to check what happens at this stage. diff --git a/PayCheckServerLib/Responses/Orders.cs b/PayCheckServerLib/Responses/Orders.cs index c832f93..bfec7f3 100644 --- a/PayCheckServerLib/Responses/Orders.cs +++ b/PayCheckServerLib/Responses/Orders.cs @@ -1,4 +1,7 @@ -using NetCoreServer; +using ModdableWebServer; +using ModdableWebServer.Attributes; +using ModdableWebServer.Helper; +using NetCoreServer; using Newtonsoft.Json; using PayCheckServerLib.Jsons; using PayCheckServerLib.Jsons.Basic; @@ -33,7 +36,7 @@ public static string GenOrderNumber() } [HTTP("POST", "/platform/public/namespaces/{namespace}/users/{userid}/orders")] - public static bool UserOrders(HttpRequest request, PC3Server.PC3Session session) + public static bool UserOrders(HttpRequest request, ServerStruct serverStruct) { //ResponseCreator response = new ResponseCreator(); //OrdersJsonPayload payload = new() { @@ -45,7 +48,7 @@ public static bool UserOrders(HttpRequest request, PC3Server.PC3Session session) var body = JsonConvert.DeserializeObject(request.Body) ?? throw new Exception("UserOrders -> body is null!"); if (!Directory.Exists("Orders")) { Directory.CreateDirectory("Orders"); } - File.WriteAllText($"Orders/{session.HttpParam["namespace"]}_{session.HttpParam["userid"]}_{body.ItemId}", request.Body); + File.WriteAllText($"Orders/{serverStruct.Parameters["namespace"]}_{serverStruct.Parameters["userid"]}_{body.ItemId}", request.Body); ResponseCreator response = new(); var ordernumber = GenOrderNumber(); @@ -53,8 +56,8 @@ public static bool UserOrders(HttpRequest request, PC3Server.PC3Session session) Order order = new() { OrderNo = ordernumber, - Namespace = session.HttpParam["namespace"], - UserId = session.HttpParam["userid"], + Namespace = serverStruct.Parameters["namespace"], + UserId = serverStruct.Parameters["userid"], ItemId = item.ItemId, Sandbox = false, Quantity = body.Quantity, @@ -71,7 +74,7 @@ public static bool UserOrders(HttpRequest request, PC3Server.PC3Session session) CurrencySymbol = body.CurrencyCode, // CASH = Cash, GOLD = CStacks CurrencyType = (body.CurrencyCode == "CASH" || body.CurrencyCode == "GOLD") ? "VIRTUAL" : "REAL", - Namespace = session.HttpParam["namespace"], + Namespace = serverStruct.Parameters["namespace"], Decimals = 0 }, // will be like this until i can confirm they are the same type ~HW12Dev @@ -94,7 +97,8 @@ public static bool UserOrders(HttpRequest request, PC3Server.PC3Session session) PaymentProvider = "WALLET" }; response.SetBody(JsonConvert.SerializeObject(order)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } } diff --git a/PayCheckServerLib/Responses/Parties.cs b/PayCheckServerLib/Responses/Parties.cs index 65bda60..a7fd34b 100644 --- a/PayCheckServerLib/Responses/Parties.cs +++ b/PayCheckServerLib/Responses/Parties.cs @@ -5,24 +5,28 @@ using PayCheckServerLib.Jsons.PartyStuff; using PayCheckServerLib.Jsons.WSS; using PayCheckServerLib.WSController; +using ModdableWebServer; +using ModdableWebServer.Attributes; +using ModdableWebServer.Helper; namespace PayCheckServerLib.Responses { public class Parties { [HTTP("POST", "/session/v1/public/namespaces/{namespace}/party")] - public static bool Party(HttpRequest request, PC3Server.PC3Session session) + public static bool Party(HttpRequest request, ServerStruct serverStruct) { - var auth = session.Headers["authorization"].Replace("Bearer ", ""); + var auth = serverStruct.Headers["authorization"].Replace("Bearer ", ""); var token = TokenHelper.ReadToken(auth); var body = JsonConvert.DeserializeObject(request.Body); var rsp = PartyController.CreateParty(body, token.Namespace); ResponseCreator response = new(); response.SetBody(JsonConvert.SerializeObject(rsp)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); //send notif to user to party created - var wss_sess = session.GetWSLobby(token.UserId, token.Namespace); + var wss_sess = LobbyControl.GetLobbyUser(token.UserId, token.Namespace); OnPartyCreated pld = new() { Code = rsp.Code, @@ -54,21 +58,22 @@ public static bool Party(HttpRequest request, PC3Server.PC3Session session) } }; - ChatControl.SendToChat(JsonConvert.SerializeObject(topic), session.GetWSChat(token.UserId, token.Namespace)); + ChatControl.SendToChat(JsonConvert.SerializeObject(topic), ChatControl.GetChatUser(token.UserId, token.Namespace)); return true; } [HTTP("PATCH", "/session/v1/public/namespaces/{namespace}/parties/{partyid}")] - public static bool PATCH_Parties(HttpRequest request, PC3Server.PC3Session session) + public static bool PATCH_Parties(HttpRequest request, ServerStruct serverStruct) { - var auth = session.Headers["authorization"].Replace("Bearer ", ""); + var auth = serverStruct.Headers["authorization"].Replace("Bearer ", ""); var token = TokenHelper.ReadToken(auth); var body = JsonConvert.DeserializeObject(request.Body); - PartyPost.Response rsp = PartyController.UpdateParty(session.HttpParam["partyid"], body); + PartyPost.Response rsp = PartyController.UpdateParty(serverStruct.Parameters["partyid"], body); ResponseCreator response = new(); - response.SetBody(JsonConvert.SerializeObject(rsp)); - session.SendResponse(response.GetResponse()); + response.SetBody(JsonConvert.SerializeObject(rsp, Formatting.Indented)); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); OnPartyUpdated pld = new() { Code = rsp.Code, @@ -92,7 +97,7 @@ public static bool PATCH_Parties(HttpRequest request, PC3Server.PC3Session sessi IsFull = rsp.IsFull, LeaderId = rsp.LeaderId, Members = new(), - Namespace = session.HttpParam["namespace"], + Namespace = serverStruct.Parameters["namespace"], UpdatedAt = rsp.UpdatedAt, Version = rsp.Version }; @@ -120,12 +125,14 @@ public static bool PATCH_Parties(HttpRequest request, PC3Server.PC3Session sessi List ids = new(); rsp.Members.ForEach(m => ids.Add(m.Id)); - foreach (var id in session.WSSServer.WSUserIds) + foreach (var id in LobbyControl.LobbyUsers.Keys) { - if (ids.Contains(id)) + var splitted = id.Split("_"); + + if (ids.Contains(splitted[1])) { - Debugger.PrintDebug(id); - LobbyControl.SendToLobby(resp, session.GetWSLobby(id, token.Namespace)); + Debugger.PrintDebug(splitted[1]); + LobbyControl.SendToLobby(resp, LobbyControl.GetLobbyUser(splitted[1], token.Namespace)); } } @@ -134,16 +141,17 @@ public static bool PATCH_Parties(HttpRequest request, PC3Server.PC3Session sessi [HTTP("DELETE", "/session/v1/public/namespaces/{namespace}/parties/{partyid}/users/me/leave")] - public static bool LeaveParties(HttpRequest request, PC3Server.PC3Session session) + public static bool LeaveParties(HttpRequest request, ServerStruct serverStruct) { //This response sadly KILLING THE GAME (Even without emu) // SBZ PLEASE FIX! - var auth = session.Headers["authorization"].Replace("Bearer ", ""); + var auth = serverStruct.Headers["authorization"].Replace("Bearer ", ""); var token = TokenHelper.ReadToken(auth); ResponseCreator response = new(204); - session.SendResponse(response.GetResponse()); - PartyController.LeftParty(session.HttpParam["partyid"], token.UserId, session); - var party = PartyController.PartySaves.Where(x => x.Value.Id == session.HttpParam["partyid"]).FirstOrDefault().Value; + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); + PartyController.LeftParty(serverStruct.Parameters["partyid"], token.UserId, serverStruct); + var party = PartyController.PartySaves.Where(x => x.Value.Id == serverStruct.Parameters["partyid"]).FirstOrDefault().Value; if (party == null) { Debugger.PrintError("NO Code???? WHAT THE FUCK"); @@ -162,15 +170,15 @@ public static bool LeaveParties(HttpRequest request, PC3Server.PC3Session sessio UserId = token.UserId } }; - ChatControl.SendToChat(JsonConvert.SerializeObject(topic), session.GetWSChat(token.UserId, token.Namespace)); + ChatControl.SendToChat(JsonConvert.SerializeObject(topic), ChatControl.GetChatUser(token.UserId, token.Namespace)); return true; } [HTTP("POST", "/session/v1/public/namespaces/{namespace}/parties/{partyid}/users/me/join")] - public static bool JoinParties(HttpRequest request, PC3Server.PC3Session session) + public static bool JoinParties(HttpRequest request, ServerStruct serverStruct) { - var party = PartyController.PartySaves.Where(x => x.Value.Id == session.HttpParam["partyid"]).FirstOrDefault().Value; + var party = PartyController.PartySaves.Where(x => x.Value.Id == serverStruct.Parameters["partyid"]).FirstOrDefault().Value; if (party == null) { Debugger.PrintError("NO Code???? WHAT THE FUCK"); @@ -179,12 +187,13 @@ public static bool JoinParties(HttpRequest request, PC3Server.PC3Session session var rsp = PartyController.ParsePartyToRSP(party); ResponseCreator response = new(); response.SetBody(JsonConvert.SerializeObject(rsp)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("POST", "/session/v1/public/namespaces/{namespace}/parties/{partyid}/users/me/reject")] - public static bool RejectParties(HttpRequest request, PC3Server.PC3Session session) + public static bool RejectParties(HttpRequest request, ServerStruct serverStruct) { /* var body = JsonConvert.DeserializeObject(request.Body); @@ -202,7 +211,7 @@ public class UsersMeJoinCode } [HTTP("POST", "/session/v1/public/namespaces/{namespace}/parties/users/me/join/code")] - public static bool JoinPartyByCode(HttpRequest request, PC3Server.PC3Session session) + public static bool JoinPartyByCode(HttpRequest request, ServerStruct serverStruct) { var body = JsonConvert.DeserializeObject(request.Body); @@ -211,7 +220,8 @@ public static bool JoinPartyByCode(HttpRequest request, PC3Server.PC3Session ses var rsp = PartyController.ParsePartyToRSP(saved); ResponseCreator response = new(); response.SetBody(JsonConvert.SerializeObject(rsp)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); } else { @@ -220,29 +230,31 @@ public static bool JoinPartyByCode(HttpRequest request, PC3Server.PC3Session ses Attributes = new Dictionary() { { "id", body.Code }, - { "namespace", session.HttpParam["namespace"] } + { "namespace", serverStruct.Parameters["namespace"] } }, ErrorCode = 20041, - ErrorMessage = $"No party with ID [{body.Code}] exists in namespace [{session.HttpParam["namespace"]}]", - Message = $"No party with ID [{body.Code}] exists in namespace [{session.HttpParam["namespace"]}]", + ErrorMessage = $"No party with ID [{body.Code}] exists in namespace [{serverStruct.Parameters["namespace"]}]", + Message = $"No party with ID [{body.Code}] exists in namespace [{serverStruct.Parameters["namespace"]}]", Name = "PartyNotFound" }; ResponseCreator response = new(404); response.SetBody(JsonConvert.SerializeObject(error)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); } return true; } [HTTP("POST", "/session/v1/public/namespaces/{namespace}/parties/{partyid}/invite")] - public static bool InviteOtherPlayer(HttpRequest request, PC3Server.PC3Session session) + public static bool InviteOtherPlayer(HttpRequest request, ServerStruct serverStruct) { /* var body = JsonConvert.DeserializeObject(request.Body); ResponseCreator response = new(); response.SetBody(JsonConvert.SerializeObject("")); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); */ return false; } diff --git a/PayCheckServerLib/Responses/Session.cs b/PayCheckServerLib/Responses/Session.cs index 2059c71..8896217 100644 --- a/PayCheckServerLib/Responses/Session.cs +++ b/PayCheckServerLib/Responses/Session.cs @@ -1,4 +1,7 @@ -using NetCoreServer; +using ModdableWebServer; +using ModdableWebServer.Attributes; +using ModdableWebServer.Helper; +using NetCoreServer; using Newtonsoft.Json; using PayCheckServerLib.Jsons.Basic; @@ -7,9 +10,9 @@ namespace PayCheckServerLib.Responses public class Session { [HTTP("GET", "/session/v1/public/namespaces/{namespace}/users/me/attributes")] - public static bool GETSessionAttributes(HttpRequest _, PC3Server.PC3Session session) + public static bool GETSessionAttributes(HttpRequest _, ServerStruct serverStruct) { - var auth = session.Headers["authorization"].Replace("Bearer ", ""); + var auth = serverStruct.Headers["authorization"].Replace("Bearer ", ""); var token = TokenHelper.ReadToken(auth); ResponseCreator response = new(); AttribSuccess success = new() @@ -28,14 +31,15 @@ public static bool GETSessionAttributes(HttpRequest _, PC3Server.PC3Session sess UserId = token.UserId }; response.SetBody(JsonConvert.SerializeObject(success)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("POST", "/session/v1/public/namespaces/{namespace}/users/me/attributes")] - public static bool POSTSessionAttributes(HttpRequest request, PC3Server.PC3Session session) + public static bool POSTSessionAttributes(HttpRequest request, ServerStruct serverStruct) { - var auth = session.Headers["authorization"].Replace("Bearer ", ""); + var auth = serverStruct.Headers["authorization"].Replace("Bearer ", ""); var token = TokenHelper.ReadToken(auth); var req = JsonConvert.DeserializeObject(request.Body) ?? throw new Exception("POSTSessionAttributes -> req is null!"); ResponseCreator response = new(); @@ -49,12 +53,13 @@ public static bool POSTSessionAttributes(HttpRequest request, PC3Server.PC3Sessi UserId = token.UserId }; response.SetBody(JsonConvert.SerializeObject(success)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("GET", "/session/v1/public/namespaces/{namespace}/users/me/parties")] - public static bool SessionsParties(HttpRequest _, PC3Server.PC3Session session) + public static bool SessionsParties(HttpRequest _, ServerStruct serverStruct) { ResponseCreator response = new(); response.SetHeader("Content-Type", "application/json"); @@ -70,12 +75,13 @@ public static bool SessionsParties(HttpRequest _, PC3Server.PC3Session session) Data = new() }; response.SetBody(JsonConvert.SerializeObject(gamesessions)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("GET", "/session/v1/public/namespaces/{namespace}/users/me/gamesessions")] - public static bool Sessionsgamesessions(HttpRequest _, PC3Server.PC3Session session) + public static bool Sessionsgamesessions(HttpRequest _, ServerStruct serverStruct) { ResponseCreator response = new(); response.SetHeader("Content-Type", "application/json"); @@ -91,7 +97,8 @@ public static bool Sessionsgamesessions(HttpRequest _, PC3Server.PC3Session sess Data = new() }; response.SetBody(JsonConvert.SerializeObject(gamesessions)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } } diff --git a/PayCheckServerLib/Responses/Social.cs b/PayCheckServerLib/Responses/Social.cs index e9044e3..d530e08 100644 --- a/PayCheckServerLib/Responses/Social.cs +++ b/PayCheckServerLib/Responses/Social.cs @@ -3,28 +3,32 @@ using PayCheckServerLib.Helpers; using PayCheckServerLib.Jsons; using PayCheckServerLib.Jsons.Basic; +using ModdableWebServer; +using ModdableWebServer.Attributes; +using ModdableWebServer.Helper; namespace PayCheckServerLib.Responses { public class Social { [HTTP("PUT", "/social/v1/public/namespaces/{namespace}/users/{userId}/statitems/value/bulk")] - public static bool PutStatItemsBulk(HttpRequest request, PC3Server.PC3Session session) + public static bool PutStatItemsBulk(HttpRequest request, ServerStruct serverStruct) { - var auth = session.Headers["authorization"].Replace("Bearer ", ""); + var auth = serverStruct.Headers["authorization"].Replace("Bearer ", ""); var token = TokenHelper.ReadToken(auth); var statReq = JsonConvert.DeserializeObject>(request.Body); var rsp = UserStatController.AddStat(statReq, token); ResponseCreator responsecreator = new ResponseCreator(); responsecreator.SetBody(JsonConvert.SerializeObject(rsp)); - session.SendResponse(responsecreator.GetResponse()); + serverStruct.Response = responsecreator.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("GET", "/social/v1/public/namespaces/{namespace}/users/{userId}/statitems?limit={limit}&offset=0")] - public static bool GetUserStatItems(HttpRequest request, PC3Server.PC3Session session) + public static bool GetUserStatItems(HttpRequest _, ServerStruct serverStruct) { - var auth = session.Headers["authorization"].Replace("Bearer ", ""); + var auth = serverStruct.Headers["authorization"].Replace("Bearer ", ""); var token = TokenHelper.ReadToken(auth); var stat = UserStatController.GetStat(token.UserId, token.Namespace); @@ -36,16 +40,17 @@ public static bool GetUserStatItems(HttpRequest request, PC3Server.PC3Session se Paging = { } }; response.SetBody(JsonConvert.SerializeObject(responsedata)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("GET", "/social/v1/public/namespaces/{namespace}/users/{userId}/statitems?statCodes={statcode}&limit=20&offset=0")] - public static bool GetUserStatItemsInfamy(HttpRequest request, PC3Server.PC3Session session) + public static bool GetUserStatItemsInfamy(HttpRequest _, ServerStruct serverStruct) { - var auth = session.Headers["authorization"].Replace("Bearer ", ""); + var auth = serverStruct.Headers["authorization"].Replace("Bearer ", ""); var token = TokenHelper.ReadToken(auth); - var statcode = session.HttpParam["statcode"]; + var statcode = serverStruct.Parameters["statcode"]; ResponseCreator response = new ResponseCreator(); DataPaging responsedata = new() { @@ -63,7 +68,8 @@ public static bool GetUserStatItemsInfamy(HttpRequest request, PC3Server.PC3Sess } response.SetBody(JsonConvert.SerializeObject(responsedata)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } } diff --git a/PayCheckServerLib/Responses/Telemetry.cs b/PayCheckServerLib/Responses/Telemetry.cs index 32e705a..786a14f 100644 --- a/PayCheckServerLib/Responses/Telemetry.cs +++ b/PayCheckServerLib/Responses/Telemetry.cs @@ -1,11 +1,14 @@ -using NetCoreServer; +using ModdableWebServer; +using ModdableWebServer.Attributes; +using ModdableWebServer.Helper; +using NetCoreServer; namespace PayCheckServerLib.Responses { public class Telemetry { [HTTP("POST", "/game-telemetry/v1/protected/events")] - public static bool ProtectedEvents(HttpRequest request, PC3Server.PC3Session session) + public static bool ProtectedEvents(HttpRequest request, ServerStruct serverStruct) { if (!Directory.Exists("Telemetry")) { Directory.CreateDirectory("Telemetry"); } try @@ -16,7 +19,8 @@ public static bool ProtectedEvents(HttpRequest request, PC3Server.PC3Session ses { Debugger.PrintError(String.Format("Exception occurred while writing telemetry: {0}", e.ToString())); } - session.SendResponse(session.Response.MakeOkResponse()); + serverStruct.Response.MakeOkResponse(); + serverStruct.SendResponse(); return true; } } diff --git a/PayCheckServerLib/Responses/VersionResponse.cs b/PayCheckServerLib/Responses/VersionResponse.cs index b293220..523dd1a 100644 --- a/PayCheckServerLib/Responses/VersionResponse.cs +++ b/PayCheckServerLib/Responses/VersionResponse.cs @@ -1,4 +1,7 @@ -using NetCoreServer; +using ModdableWebServer; +using ModdableWebServer.Attributes; +using ModdableWebServer.Helper; +using NetCoreServer; using Newtonsoft.Json; using PayCheckServerLib.Jsons; using System.Text.RegularExpressions; @@ -7,7 +10,7 @@ namespace PayCheckServerLib.Responses { public class VersionResponse { - static bool GenericVersionResponse(HttpRequest request, PC3Server.PC3Session session) + static bool GenericVersionResponse(HttpRequest request, ServerStruct serverStruct) { ResponseCreator response = new ResponseCreator(); @@ -44,50 +47,51 @@ static bool GenericVersionResponse(HttpRequest request, PC3Server.PC3Session ses }; response.SetBody(JsonConvert.SerializeObject(version)); - session.SendResponse(response.GetResponse()); + serverStruct.Response = response.GetResponse(); + serverStruct.SendResponse(); return true; } [HTTP("GET", "/iam/version")] - public static bool IamVersion(HttpRequest request, PC3Server.PC3Session session) { return GenericVersionResponse(request, session); } + public static bool IamVersion(HttpRequest request, ServerStruct serverStruct) { return GenericVersionResponse(request, serverStruct); } [HTTP("GET", "/agreement/version")] - public static bool AgreementVersion(HttpRequest request, PC3Server.PC3Session session) { return GenericVersionResponse(request, session); } + public static bool AgreementVersion(HttpRequest request, ServerStruct serverStruct) { return GenericVersionResponse(request, serverStruct); } [HTTP("GET", "/basic/version")] - public static bool BasicVersion(HttpRequest request, PC3Server.PC3Session session) { return GenericVersionResponse(request, session); } + public static bool BasicVersion(HttpRequest request, ServerStruct serverStruct) { return GenericVersionResponse(request, serverStruct); } [HTTP("GET", "/platform/version")] - public static bool PlatformVersion(HttpRequest request, PC3Server.PC3Session session) { return GenericVersionResponse(request, session); } + public static bool PlatformVersion(HttpRequest request, ServerStruct serverStruct) { return GenericVersionResponse(request, serverStruct); } [HTTP("GET", "/social/version")] - public static bool SocialVersion(HttpRequest request, PC3Server.PC3Session session) { return GenericVersionResponse(request, session); } + public static bool SocialVersion(HttpRequest request, ServerStruct serverStruct) { return GenericVersionResponse(request, serverStruct); } [HTTP("GET", "/leaderboard/version")] - public static bool LeaderboardVersion(HttpRequest request, PC3Server.PC3Session session) { return GenericVersionResponse(request, session); } + public static bool LeaderboardVersion(HttpRequest request, ServerStruct serverStruct) { return GenericVersionResponse(request, serverStruct); } [HTTP("GET", "/achievement/version")] - public static bool AchievementVersion(HttpRequest request, PC3Server.PC3Session session) { return GenericVersionResponse(request, session); } + public static bool AchievementVersion(HttpRequest request, ServerStruct serverStruct) { return GenericVersionResponse(request, serverStruct); } [HTTP("GET", "/cloudsave/version")] - public static bool CloudSaveVersion(HttpRequest request, PC3Server.PC3Session session) { return GenericVersionResponse(request, session); } + public static bool CloudSaveVersion(HttpRequest request, ServerStruct serverStruct) { return GenericVersionResponse(request, serverStruct); } [HTTP("GET", "/ugc/version")] - public static bool UGCVersion(HttpRequest request, PC3Server.PC3Session session) { return GenericVersionResponse(request, session); } + public static bool UGCVersion(HttpRequest request, ServerStruct serverStruct) { return GenericVersionResponse(request, serverStruct); } [HTTP("GET", "/lobby/version")] - public static bool LobbyVersion(HttpRequest request, PC3Server.PC3Session session) { return GenericVersionResponse(request, session); } + public static bool LobbyVersion(HttpRequest request, ServerStruct serverStruct) { return GenericVersionResponse(request, serverStruct); } [HTTP("GET", "/group/version")] - public static bool GroupVersion(HttpRequest request, PC3Server.PC3Session session) { return GenericVersionResponse(request, session); } + public static bool GroupVersion(HttpRequest request, ServerStruct serverStruct) { return GenericVersionResponse(request, serverStruct); } [HTTP("GET", "/qosm/version")] - public static bool QOSMVersion(HttpRequest request, PC3Server.PC3Session session) { return GenericVersionResponse(request, session); } + public static bool QOSMVersion(HttpRequest request, ServerStruct serverStruct) { return GenericVersionResponse(request, serverStruct); } [HTTP("GET", "/dsmcontroller/version")] - public static bool DSMControllerVersion(HttpRequest request, PC3Server.PC3Session session) { return GenericVersionResponse(request, session); } + public static bool DSMControllerVersion(HttpRequest request, ServerStruct serverStruct) { return GenericVersionResponse(request, serverStruct); } [HTTP("GET", "/game-telemetry/version")] - public static bool GameTelemetryVerion(HttpRequest request, PC3Server.PC3Session session) { return GenericVersionResponse(request, session); } + public static bool GameTelemetryVerion(HttpRequest request, ServerStruct serverStruct) { return GenericVersionResponse(request, serverStruct); } } } diff --git a/PayCheckServerLib/ServerManager.cs b/PayCheckServerLib/ServerManager.cs index 2034f80..0bb8dd8 100644 --- a/PayCheckServerLib/ServerManager.cs +++ b/PayCheckServerLib/ServerManager.cs @@ -1,10 +1,14 @@ -using PayCheckServerLib.Helpers; +using ModdableWebServer.Helper; +using ModdableWebServer.Servers; +using NetCoreServer; +using PayCheckServerLib.Helpers; +using System.Diagnostics; +using System.Reflection; namespace PayCheckServerLib { public class ServerManager { - static GSTATICServer.GSServer STATICServer; /// /// Use this to check if update finished (Either Cancelled or Success) /// @@ -16,34 +20,90 @@ public static void Pre() { Debugger.PrintDebug("GiveMeMoney Cheat Activated"); } + if (ArgumentHandler.Debug) + DebugPrinter.PrintToConsole = true; + else + DebugPrinter.PrintToConsole = false; + if (ArgumentHandler.NoUpdate) { UpdateFinished?.Invoke(null, true); return; } + if (ConfigHelper.ServerConfig.EnableAutoUpdate || ArgumentHandler.ForceUpdate) Updater.CheckForJsonUpdates(); UpdateFinished?.Invoke(null, true); } - + static WSS_Server? server = null; + static HTTP_Server? gserver = null; public static void Start() { if (ConfigHelper.ServerConfig.Hosting.WSS) - PC3Server.Start(ConfigHelper.ServerConfig.Hosting.IP, 443); + { + var context = CertHelper.GetContext( System.Security.Authentication.SslProtocols.Tls12 , "cert.pfx", "cert"); + server = new(context, ConfigHelper.ServerConfig.Hosting.IP, 443); + server.ReceivedFailed += ReceivedFailed; + server.Started += Server_Started; + server.Stopped += Server_Stopped; + server.HTTP_AttributeToMethods.Merge(Assembly.GetAssembly(typeof(ConfigHelper))); + server.WS_AttributeToMethods = AttributeMethodHelper.UrlWSLoader(Assembly.GetAssembly(typeof(ConfigHelper))); + server.WSError += WSError; + server.Start(); + } if (ConfigHelper.ServerConfig.Hosting.Gstatic) { - STATICServer = new GSTATICServer.GSServer(ConfigHelper.ServerConfig.Hosting.IP, 80); - STATICServer.Start(); + gserver = new(ConfigHelper.ServerConfig.Hosting.IP, 80); + gserver.AttributeToMethods.Merge(Assembly.GetAssembly(typeof(ConfigHelper))); + gserver.Start(); } } public static void Stop() { if (ConfigHelper.ServerConfig.Hosting.WSS) - PC3Server.Stop(); + server?.Stop(); if (ConfigHelper.ServerConfig.Hosting.Gstatic) - STATICServer.Stop(); + gserver?.Stop(); + server = null; + gserver = null; + } + + #region Actions + private static void Server_Stopped(object? sender, EventArgs e) + { + Console.WriteLine("HTTPS Server stopped!"); + } + + private static void Server_Started(object? sender, (string address, int port) e) + { + Console.WriteLine("HTTPS Server started!"); + } + + private static void ReceivedFailed(object? sender, HttpRequest request) + { + File.AppendAllText("REQUESTED.txt", request.Url + "\n" + request.Method + "\n" + request.Body + "\n"); + Debugger.logger.Debug(request.Url + "\n" + request); + Console.WriteLine("something isnt good"); + } + private static void WSError(object? sender, string error) + { + Console.WriteLine("WSError! " + error); + Debugger.PrintDebug($"Server reported error: {error}"); + StackTrace st = new StackTrace(true); + for (int i = 0; i < st.FrameCount; i++) + { + var sf = st.GetFrame(i); + if (sf == null) + continue; + Debugger.PrintDebug(""); + Debugger.PrintDebug($"Method: " + sf.GetMethod()); + Debugger.PrintDebug($"File: " + sf.GetFileName()); + Debugger.PrintDebug($"Line Number: " + sf.GetFileLineNumber()); + Debugger.PrintDebug(""); + } } + #endregion } } diff --git a/PayCheckServerLib/Servers/GSTATICServer.cs b/PayCheckServerLib/Servers/GSTATICServer.cs deleted file mode 100644 index 614a913..0000000 --- a/PayCheckServerLib/Servers/GSTATICServer.cs +++ /dev/null @@ -1,41 +0,0 @@ -using NetCoreServer; -using System.Net.Sockets; - -namespace PayCheckServerLib -{ - public class GSTATICServer - { - public class GSServer : HttpServer - { - public GSServer(string address, int port) : base(address, port) { } - - protected override TcpSession CreateSession() { return new GSSession(this); } - - protected override void OnError(SocketError error) - { - Console.WriteLine($"HTTP session caught an error: {error}"); - } - public class GSSession : HttpSession - { - public GSSession(HttpServer server) : base(server) { } - - protected override void OnReceivedRequest(HttpRequest request) - { - // Show HTTP request content - Console.WriteLine("GS Sent!"); - SendResponse(this.Response.MakeOkResponse(204)); - } - - protected override void OnReceivedRequestError(HttpRequest request, string error) - { - Console.WriteLine($"Request error: {error}"); - } - - protected override void OnError(SocketError error) - { - Console.WriteLine($"HTTP session caught an error: {error}"); - } - } - } - } -} diff --git a/PayCheckServerLib/Servers/PC3Server.cs b/PayCheckServerLib/Servers/PC3Server.cs deleted file mode 100644 index 49d19b1..0000000 --- a/PayCheckServerLib/Servers/PC3Server.cs +++ /dev/null @@ -1,360 +0,0 @@ -using NetCoreServer; -using PayCheckServerLib.Helpers; -using PayCheckServerLib.WSController; -using System.Diagnostics; -using System.Net.Sockets; -using System.Reflection; -using System.Security.Authentication; -using System.Security.Cryptography.X509Certificates; -using System.Text; -using static PayCheckServerLib.TokenHelper; - -namespace PayCheckServerLib -{ - public class PC3Server - { - public static X509Certificate GetCert() - { - //read the cert.pfx - X509Certificate2 cert = new(File.ReadAllBytes($"cert.pfx"), "cert"); - return cert; - } - - static PC3WSSServer? server = null; - static Dictionary<(string url, string method), MethodInfo> HttpServerThingy = new(); - public static void Start(string IP, int Port) - { - HttpServerThingy.Clear(); - var context = new SslContext(SslProtocols.Tls12, GetCert()); - server = new PC3WSSServer(context, IP, Port); - Console.WriteLine("[HTTPS] Server Started on https://" + IP + ":" + Port); - server.Start(); - var methods = Assembly.GetExecutingAssembly().GetTypes().SelectMany(x => x.GetMethods()).ToArray(); - var basemethods = methods.Where(x => x.GetCustomAttribute() != null && x.ReturnType == typeof(bool)).ToArray(); - foreach (var method in basemethods) - { - if (method == null) - continue; - var httpAttr = method.GetCustomAttribute(); - if (httpAttr == null) - continue; - Debugger.PrintDebug(method.Name + $" ({httpAttr.url}) ({httpAttr.method}) is added as an URL", "HTTPServer"); - HttpServerThingy.Add((httpAttr.url, httpAttr.method), method); - } - } - - public static void Stop() - { - server?.Stop(); - server?.Dispose(); - server = null; - Console.WriteLine("[HTTPS] Server Stopped"); - } - - public class PC3Session : WssSession - { - HttpRequest? _request; - public HttpRequest? LastRequest() - { - return _request; - } - public WSEnum WS_ID = WSEnum.IDK; - public enum WSEnum - { - IDK = -1, - Lobby, - Chat, - MiddleMan - } - - - public List MiddleMans = new(); - - public PC3Session? GetWSLobby(string UserId, string NameSpace) - { - if (UserId == null) - Debugger.PrintError("UserId is null! (Parameter)"); - - if (WSSServer.WSS_Stuff.TryGetValue($"{NameSpace}_{UserId}_lobby", out var value)) - { - return value; - } - Debugger.PrintError($"User({NameSpace}_{UserId}_lobby) not found in WSS_Stuff!"); - return null; - } - - public PC3Session? GetWSChat(string UserId, string NameSpace) - { - if (UserId == null) - Debugger.PrintError("UserId is null! (Parameter)"); - - if (WSSServer.WSS_Stuff.TryGetValue($"{NameSpace}_{UserId}_chat", out var value)) - { - return value; - } - Debugger.PrintError($"User({NameSpace}_{UserId}_chat) not found in WSS_Stuff!"); - return null; - } - - public PC3WSSServer WSSServer => (PC3WSSServer)Server; - - public string WSUserId = ""; - public TokenHelper.Token Token = new(); - public PC3Session(WssServer server) : base(server) { } - public Dictionary Headers = new(); - public Dictionary HttpParam = new(); - - public override void OnWsConnected(HttpRequest request) - { - Headers.Clear(); - for (int i = 0; i < request.Headers; i++) - { - var headerpart = request.Header(i); - Headers.Add(headerpart.Item1.ToLower(), headerpart.Item2); - } - string id = ""; - //There is a bug where this LobbySession empty and it contains the bearer token :) - ONLY ON RELEASE - // On beta there is an actual ID. - if (Headers.ContainsKey("x-ab-lobbysessionid") && Headers["x-ab-lobbysessionid"].Contains("Bearer")) - { - id = Headers["x-ab-lobbysessionid"].Replace("Authorization: Bearer ", ""); - } - else if (Headers.ContainsKey("middleman")) - { - WSUserId = "MiddleManId-" + Headers["middleman"]; - WS_ID = WSEnum.MiddleMan; - MiddleMans.Add(this); - Debugger.PrintInfo(WSUserId + " joined to " + WS_ID); - return; - } - else - { - id = Headers["authorization"].Replace("Bearer ", ""); - } - var token = TokenHelper.ReadToken(id); - if (request.Url == "/lobby/") - { - WS_ID = WSEnum.Lobby; - WSUserId = token.UserId; - Token = token; - var serv = (PC3WSSServer)this.Server; - serv.WSUserIds.Add(WSUserId); - if (WSSServer.WSS_Stuff.ContainsKey(token.Namespace + "_" + token.UserId + "_" + WS_ID.ToString().ToLower())) - { - Debugger.PrintWarn("The fuck? This User now wants to to join to WS again! " + WS_ID); - } - WSSServer.WSS_Stuff.Add(token.Namespace + "_" + token.UserId + "_" + WS_ID.ToString().ToLower(), this); - var x = "type: connectNotif\r\nloginType: NewRegister\r\nreconnectFromCode: 5000\r\nlobbySessionID: ee62822a8428424d9a408f6385484ae5"; - SendBinaryAsync(Encoding.UTF8.GetBytes(x)); - } - if (request.Url == "/chat/") - { - WS_ID = WSEnum.Chat; - WSUserId = token.UserId; - Token = token; - if (WSSServer.WSS_Stuff.ContainsKey(token.Namespace + "_" + token.UserId + "_" + WS_ID.ToString().ToLower())) - { - Debugger.PrintWarn("The fuck? This User now wants to to join to WS again! " + WS_ID); - } - WSSServer.WSS_Stuff.Add(token.Namespace + "_" + token.UserId + "_" + WS_ID.ToString().ToLower(), this); - var x = "CaSr{\"jsonrpc\":\"2.0\",\"method\":\"eventConnected\",\"params\":{\"sessionId\":\"9f51a15b940b4c538cc48281950de549\"}}CaEd"; - SendBinaryAsync(Encoding.UTF8.GetBytes(x)); - } - Debugger.PrintInfo(WSUserId + " joined to " + WS_ID); - foreach (var wss_stuff in WSSServer.WSS_Stuff) - { - Debugger.PrintInfo(wss_stuff.Key); - } - } - - public override void OnWsDisconnecting() - { - Console.WriteLine(Token.Namespace + " " + WSUserId + " " + WS_ID + " quit"); - if (WS_ID == WSEnum.Lobby) - { - var user = UserController.GetUser(WSUserId); - if (user != null) - { - user.Status.activity = "nil"; - user.Status.availability = "offline"; - user.Status.platform = "nil"; - user.Status.lastSeenAt = DateTime.UtcNow.ToString("O"); - UserController.SaveUser(user); - Dictionary rsp = new() - { - { "type", "userStatusNotif" }, - { "userID", WSUserId }, - { "availability", "offline" }, - { "activity", "nil" }, - { "platform", "nil" }, - { "lastSeenAt", user.Status.lastSeenAt }, - }; - foreach (var id in WSSServer.WSUserIds) - { - if (id == WSUserId) - continue; - LobbyControl.SendToLobby(rsp, GetWSLobby(id, Token.Namespace)); - } - } - else - { - Debugger.PrintWarn($"User not found! ({WSUserId}) WSS Continue "); - } - } - WSSServer.WSS_Stuff.Remove(Token.Namespace + "_" + WSUserId + "_" + WS_ID.ToString().ToLower()); - var serv = (PC3WSSServer)Server; - serv.WSUserIds.Remove(Token.Namespace + "_" + WSUserId); - WSUserId = ""; - } - - public override void OnWsError(string error) - { - Debugger.PrintError($"Request error: {error}"); - } - - - public override void OnWsReceived(byte[] buffer, long offset, long size) - { - var buf = buffer[..(int)size]; - var buf2 = buffer.Take((int)size).ToArray(); - if (size == 0) - { - //Debugger.PrintInfo("Nothing was sent to WSS"); - return; - } - Debugger.PrintInfo(WSUserId + " on " + WS_ID + " WSS Recieved!"); - Debugger.logger.Debug(offset + " " + size); - Debugger.logger.Debug(BitConverter.ToString(buffer)); - switch (WS_ID) - { - case WSEnum.Lobby: - LobbyControl.Control(buffer, offset, size, this); - return; - case WSEnum.Chat: - ChatControl.Control(buffer, offset, size, this); - return; - case WSEnum.MiddleMan: - MiddleManControl.Control(buffer, offset, size, this); - return; - case WSEnum.IDK: - default: - Debugger.PrintInfo("We received WS Stuff but we dont know which!"); - return; - - } - } - - protected override void OnReceivedRequest(HttpRequest request) - { - Headers.Clear(); - for (int i = 0; i < request.Headers; i++) - { - var headerpart = request.Header(i); - if (!Headers.ContainsKey(headerpart.Item1.ToLower())) - Headers.Add(headerpart.Item1.ToLower(), headerpart.Item2); - } - string url = request.Url; - url = Uri.UnescapeDataString(url); - // Show HTTP request content - if (Headers.ContainsKey("upgrade")) - { - base.OnReceivedRequest(request); - return; - } - - Debugger.PrintDebug(url); - - _request = request; - bool Sent = false; - foreach (var item in HttpServerThingy) - { - if ((UrlHelper.Match(url, item.Key.url, out HttpParam) || item.Key.url == url) && request.Method == item.Key.method) - { - Debugger.logger.Debug(url + "\n" + request); - Debugger.PrintInfo("Url Called function: " + item.Value.Name); - bool ret = (bool)item.Value.Invoke(this, new object[] { request, this })!; - Sent = ret; - break; - } - - } - - if (!Sent) - { - File.AppendAllText("REQUESTED.txt", url + "\n" + request.Method + "\n" + request.Body + "\n"); - Debugger.logger.Debug(url + "\n" + request); - Console.WriteLine("something isnt good"); - } - else - { - //Everything went fine! - } - //SendResponse(Response.MakeOkResponse()); - } - - protected override void OnReceivedRequestError(HttpRequest request, string error) - { - Debugger.PrintError($"Request error: {error}"); - } - - protected override void OnError(SocketError error) - { - Debugger.PrintDebug($"HTTPS session caught an error: {error}"); - StackTrace st = new StackTrace(true); - for (int i = 0; i < st.FrameCount; i++) - { - var sf = st.GetFrame(i); - if (sf == null) - continue; - Debugger.PrintDebug(""); - Debugger.PrintDebug($"Method: " + sf.GetMethod()); - Debugger.PrintDebug($"File: " + sf.GetFileName()); - Debugger.PrintDebug($"Line Number: " + sf.GetFileLineNumber()); - Debugger.PrintDebug(""); - } - } - - } - - public class PC3WSSServer : WssServer - { - public List WSUserIds; - public Dictionary WSS_Stuff = new(); - public PC3WSSServer(SslContext context, string address, int port) : base(context, address, port) - { - WSUserIds = new(); - } - - PC3Session? session; - - public PC3Session? GetSession() - { - return session; - } - - protected override SslSession CreateSession() - { - session = new PC3Session(this); - return session; - } - - - protected override void OnError(SocketError error) - { - Debugger.PrintDebug($"Server reported error: {error}"); - StackTrace st = new StackTrace(true); - for (int i = 0; i < st.FrameCount; i++) - { - var sf = st.GetFrame(i); - if (sf == null) - continue; - Debugger.PrintDebug(""); - Debugger.PrintDebug($"Method: " + sf.GetMethod()); - Debugger.PrintDebug($"File: " + sf.GetFileName()); - Debugger.PrintDebug($"Line Number: " + sf.GetFileLineNumber()); - Debugger.PrintDebug(""); - } - } - } - } -} \ No newline at end of file diff --git a/PayCheckServerLib/WSController/ChatControl.cs b/PayCheckServerLib/WSController/ChatControl.cs index 5517f53..ba22779 100644 --- a/PayCheckServerLib/WSController/ChatControl.cs +++ b/PayCheckServerLib/WSController/ChatControl.cs @@ -1,18 +1,60 @@ -using Newtonsoft.Json; +using ModdableWebServer; +using ModdableWebServer.Attributes; +using ModdableWebServer.Helper; +using Newtonsoft.Json; using PayCheckServerLib.Helpers; using PayCheckServerLib.Jsons.WSS; using System.Text; -using static PayCheckServerLib.PC3Server; namespace PayCheckServerLib.WSController { public class ChatControl { - public static void Control(byte[] buffer, long offset, long size, PC3Session session) + [WS("/chat/")] + public static void Chat(WebSocketStruct socketStruct) + { + Debugger.PrintDebug("Chat"); + var auth_token = socketStruct.Request.Headers["authorization"].Replace("Bearer ", ""); + var token = TokenHelper.ReadToken(auth_token); + var key = $"{token.Namespace}_{token.UserId}"; + if (socketStruct.IsConnected) + { + if (!ChatUsers.ContainsKey(key)) + { + var x = "CaSr{\"jsonrpc\":\"2.0\",\"method\":\"eventConnected\",\"params\":{\"sessionId\":\"9f51a15b940b4c538cc48281950de549\"}}CaEd"; + socketStruct.SendWebSocketByteArray(Encoding.UTF8.GetBytes(x)); + ChatUsers.Add(key, socketStruct); + } + } + else if (!socketStruct.IsConnecting) + { + ChatUsers.Remove(key); + } + + if (socketStruct.WSRequest != null) + { + Control(socketStruct.WSRequest.Value.buffer, socketStruct.WSRequest.Value.offset, socketStruct.WSRequest.Value.size, socketStruct); + } + + } + + public static Dictionary ChatUsers = new(); + + public static WebSocketStruct? GetChatUser(string UserId, string NameSpace) + { + var key = $"{NameSpace}_{UserId}"; + if (ChatUsers.TryGetValue(key, out var webSocketStruct)) + { + return webSocketStruct; + } + return null; + } + + public static void Control(byte[] buffer, long offset, long size, WebSocketStruct socketStruct) { if (size == 0) return; - buffer = buffer.Take((int)size).ToArray(); + buffer = buffer.Skip((int)offset).Take((int)size).ToArray(); if (!Directory.Exists("Chat")) { Directory.CreateDirectory("Chat"); } File.WriteAllBytes("Chat/" + DateTime.Now.ToString("s").Replace(":", "-") + ".bytes", buffer); var str = Encoding.UTF8.GetString(buffer); @@ -33,7 +75,7 @@ public static void Control(byte[] buffer, long offset, long size, PC3Session ses }; var resp = "CaSr" + JsonConvert.SerializeObject(rsp) + "CaEd"; Console.WriteLine("Sending back: " + resp); - session.SendTextAsync(resp); + socketStruct.SendWebSocketByteArray(Encoding.UTF8.GetBytes(resp)); } return; case "actionQueryTopicById": @@ -72,7 +114,7 @@ public static void Control(byte[] buffer, long offset, long size, PC3Session ses } var resp = "CaSr" + JsonConvert.SerializeObject(rsp) + "CaEd"; Console.WriteLine("Sending back: " + resp); - session.SendTextAsync(resp); + socketStruct.SendWebSocketByteArray(Encoding.UTF8.GetBytes(resp)); } return; default: @@ -81,10 +123,10 @@ public static void Control(byte[] buffer, long offset, long size, PC3Session ses } } - public static void SendToChat(string Json, PC3Session session) + public static void SendToChat(string Json, WebSocketStruct? socketStruct) { var resp = "CaSr" + Json + "CaEd"; - session.SendTextAsync(resp); + socketStruct?.SendWebSocketByteArray(Encoding.UTF8.GetBytes(resp)); } } } diff --git a/PayCheckServerLib/WSController/LobbyControl.cs b/PayCheckServerLib/WSController/LobbyControl.cs index cb7da13..fab4d2e 100644 --- a/PayCheckServerLib/WSController/LobbyControl.cs +++ b/PayCheckServerLib/WSController/LobbyControl.cs @@ -1,8 +1,10 @@ -using Newtonsoft.Json; +using ModdableWebServer; +using ModdableWebServer.Attributes; +using ModdableWebServer.Helper; +using Newtonsoft.Json; using PayCheckServerLib.Helpers; using PayCheckServerLib.Jsons; using System.Text; -using static PayCheckServerLib.PC3Server; namespace PayCheckServerLib.WSController { @@ -13,7 +15,85 @@ public static string Base64Encode(string plainText) var plainTextBytes = Encoding.UTF8.GetBytes(plainText); return Convert.ToBase64String(plainTextBytes); } - public static void Control(byte[] buffer, long offset, long size, PC3Session session) + + [WS("/lobby/")] + public static void Lobby(WebSocketStruct socketStruct) + { + Debugger.PrintDebug("LOBBY"); + string auth_token; + if (socketStruct.Request.Headers.ContainsKey("x-ab-lobbysessionid") && socketStruct.Request.Headers["x-ab-lobbysessionid"].Contains("Bearer")) + { + auth_token = socketStruct.Request.Headers["x-ab-lobbysessionid"].Replace("Authorization: Bearer ", ""); + } + else + { + auth_token = socketStruct.Request.Headers["authorization"].Replace("Bearer ", ""); + } + var token = TokenHelper.ReadToken(auth_token); + var key = $"{token.Namespace}_{token.UserId}"; + if (socketStruct.IsConnected) + { + if (!LobbyUsers.ContainsKey(key)) + { + var x = "type: connectNotif\r\nloginType: NewRegister\r\nreconnectFromCode: 5000\r\nlobbySessionID: ee62822a8428424d9a408f6385484ae5"; + socketStruct.SendWebSocketByteArray(Encoding.UTF8.GetBytes(x)); + LobbyUsers.Add(key, socketStruct); + } + } + else if (!socketStruct.IsConnecting) + { + var user = UserController.GetUser(token.UserId); + if (user != null) + { + user.Status.activity = "nil"; + user.Status.availability = "offline"; + user.Status.platform = "nil"; + user.Status.lastSeenAt = DateTime.UtcNow.ToString("O"); + UserController.SaveUser(user); + Dictionary rsp = new() + { + { "type", "userStatusNotif" }, + { "userID", token.UserId }, + { "availability", "offline" }, + { "activity", "nil" }, + { "platform", "nil" }, + { "lastSeenAt", user.Status.lastSeenAt }, + }; + foreach (var id in LobbyUsers.Keys) + { + //split + var splitted = id.Split("_"); + + if (splitted[1] == token.UserId) + continue; + if (splitted[0] != token.Namespace) + continue; + + SendToLobby(rsp, GetLobbyUser(id, token.Namespace)); + } + } + LobbyUsers.Remove(key); + } + + if (socketStruct.WSRequest != null) + { + Control(socketStruct.WSRequest.Value.buffer, socketStruct.WSRequest.Value.offset, socketStruct.WSRequest.Value.size, socketStruct, token); + } + + } + + public static Dictionary LobbyUsers = new(); + + public static WebSocketStruct? GetLobbyUser(string UserId, string NameSpace) + { + var key = $"{NameSpace}_{UserId}"; + if (LobbyUsers.TryGetValue(key, out var webSocketStruct)) + { + return webSocketStruct; + } + return null; + } + public static void Control(byte[] buffer, long offset, long size, WebSocketStruct socketStruct, TokenHelper.Token token) { if (size == 0) return; @@ -30,15 +110,14 @@ public static void Control(byte[] buffer, long offset, long size, PC3Session ses if (string.IsNullOrEmpty(item) || item == "\n") continue; var kv2 = item.Split(": "); - Console.WriteLine(item); kv.Add(kv2[0], kv2[1]); } Debugger.PrintWebsocket("KVs done!"); - SwitchingType(kv, session); + SwitchingType(kv, socketStruct, token); //Now doing some magic here for stuff. } - static void SwitchingType(Dictionary kv, PC3Session session) + static void SwitchingType(Dictionary kv, WebSocketStruct socketStruct, TokenHelper.Token token) { try { @@ -51,10 +130,10 @@ static void SwitchingType(Dictionary kv, PC3Session session) rsp.Add("type", "setUserStatusResponse"); rsp.Add("id", kv["id"]); rsp.Add("code", "0"); - user = UserController.GetUser(session.WSUserId); + user = UserController.GetUser(token.UserId); if (user == null) { - Debugger.PrintWarn($"User not found! ({session.WSUserId}) WSS Cannot continue"); + Debugger.PrintWarn($"User not found! ({token.UserId}) WSS Cannot continue"); new Exception("UserId is null"); break; } @@ -63,20 +142,26 @@ static void SwitchingType(Dictionary kv, PC3Session session) user.Status.platform = kv["platform"]; user.Status.lastSeenAt = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"); UserController.SaveUser(user); - SendToLobby(rsp, session); + SendToLobby(rsp, socketStruct); rsp.Remove("type"); rsp.Remove("code"); rsp.Add("type", "userStatusNotif"); - rsp.Add("userID", session.WSUserId); + rsp.Add("userID", token.UserId); rsp.Add("activity", kv["activity"]); rsp.Add("availability", kv["availability"]); rsp.Add("platform", kv["platform"]); rsp.Add("lastSeenAt", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")); - foreach (var id in session.WSSServer.WSUserIds) + foreach (var id in LobbyUsers.Keys) { - if (id == session.WSUserId) + //split + var splitted = id.Split("_"); + + if (splitted[1] == token.UserId) + continue; + if (splitted[0] != token.Namespace) continue; - SendToLobby(rsp, session.GetWSLobby(id, session.Token.Namespace)); + + SendToLobby(rsp, GetLobbyUser(id, token.Namespace)); } break; case "joinDefaultChannelRequest": @@ -84,30 +169,30 @@ static void SwitchingType(Dictionary kv, PC3Session session) rsp.Add("id", kv["id"]); rsp.Add("channelSlug", "default-channel"); rsp.Add("code", "0"); - SendToLobby(rsp, session); + SendToLobby(rsp, socketStruct); break; case "listIncomingFriendsRequest": rsp.Add("type", "listIncomingFriendsResponse"); rsp.Add("id", kv["id"]); rsp.Add("code", "0"); rsp.Add("friendsId", "[]"); - SendToLobby(rsp, session); + SendToLobby(rsp, socketStruct); break; case "listOutgoingFriendsRequest": rsp.Add("type", "listOutgoingFriendsResponse"); rsp.Add("id", kv["id"]); rsp.Add("code", "0"); rsp.Add("friendsId", "[]"); - SendToLobby(rsp, session); + SendToLobby(rsp, socketStruct); break; case "friendsStatusRequest": rsp.Add("type", "friendsStatusResponse"); rsp.Add("id", kv["id"]); rsp.Add("code", "0"); - user = UserController.GetUser(session.WSUserId); + user = UserController.GetUser(token.UserId); if (user == null) { - Debugger.PrintWarn($"User not found! ({session.WSUserId}) WSS Cannot continue"); + Debugger.PrintWarn($"User not found! ({token.UserId}) WSS Cannot continue"); throw new Exception("UserId is null"); } List friendsId = new(); @@ -123,7 +208,7 @@ static void SwitchingType(Dictionary kv, PC3Session session) var fuser = UserController.GetUser(fud); if (fuser == null) { - Debugger.PrintWarn($"User not found! ({session.WSUserId}) WSS Cannot continue"); + Debugger.PrintWarn($"User not found! ({token.UserId}) WSS Cannot continue"); throw new Exception("UserId is null"); } availability.Add(fuser.Status.availability); @@ -137,7 +222,7 @@ static void SwitchingType(Dictionary kv, PC3Session session) rsp.Add("activity", ListToStr(activity)); rsp.Add("platform", ListToStr(platform)); rsp.Add("lastSeenAt", ListToStr(lastSeenAt)); - SendToLobby(rsp, session); + SendToLobby(rsp, socketStruct); break; default: Debugger.PrintWebsocket("Not sending back anything: " + kv["type"]); @@ -161,7 +246,7 @@ public static string ListToStr(List list) where T : class } - public static void SendToLobby(Dictionary kv, PC3Session? session) + public static void SendToLobby(Dictionary kv, WebSocketStruct? socketStruct) { Debugger.PrintDebug("SendToLobby Called!"); var str = ""; @@ -172,7 +257,7 @@ public static void SendToLobby(Dictionary kv, PC3Session? sessio str = str.Remove(str.Length - 1); Debugger.PrintDebug(str); - session?.SendBinaryAsync(str); + socketStruct?.SendWebSocketByteArray(Encoding.UTF8.GetBytes(str)); } } } diff --git a/PayCheckServerLib/WSController/MiddleManControl.cs b/PayCheckServerLib/WSController/MiddleManControl.cs index 49e3e4d..999693c 100644 --- a/PayCheckServerLib/WSController/MiddleManControl.cs +++ b/PayCheckServerLib/WSController/MiddleManControl.cs @@ -1,18 +1,45 @@ -using Newtonsoft.Json; +using ModdableWebServer.Attributes; +using ModdableWebServer; +using Newtonsoft.Json; using PayCheckServerLib.Helpers; using PayCheckServerLib.Jsons.GS; using System.Text; -using static PayCheckServerLib.PC3Server; +using ModdableWebServer.Helper; namespace PayCheckServerLib.WSController { public class MiddleManControl { - public static void Control(byte[] buffer, long offset, long size, PC3Session session) + [WS("/middleman")] + public static void MiddleMan(WebSocketStruct socketStruct) + { + var key = "MiddleManId-" + socketStruct.Request.Headers["middleman"]; + if (socketStruct.IsConnected) + { + if (!MiddleMans.ContainsKey(key)) + { + MiddleMans.Add(key, socketStruct); + } + } + else + { + MiddleMans.Remove(key); + } + + if (socketStruct.WSRequest != null) + { + Control(socketStruct.WSRequest.Value.buffer, socketStruct.WSRequest.Value.offset, socketStruct.WSRequest.Value.size, socketStruct); + } + + } + + public static Dictionary MiddleMans = new(); + + public static void Control(byte[] buffer, long offset, long size, WebSocketStruct socketStruct) { if (size == 0) return; - buffer = buffer.Take((int)size).ToArray(); + buffer = buffer.Skip((int)offset).Take((int)size).ToArray(); var Data = Encoding.UTF8.GetString(buffer); var dataSplit = Data.Split("-END-"); var func = dataSplit[0]; @@ -24,6 +51,7 @@ public static void Control(byte[] buffer, long offset, long size, PC3Session ses var ds = JsonConvert.DeserializeObject(data); GSController.DSInfo.Add(ds.SessionId, ds); GSController.DSInfoSentList.Add(ds.SessionId); + socketStruct.SendWebSocketText(returnData); break; default: break;