diff --git a/Backend/BackendLoop.cs b/Backend/BackendLoop.cs index f227f551..f2b3daf7 100644 --- a/Backend/BackendLoop.cs +++ b/Backend/BackendLoop.cs @@ -5,10 +5,12 @@ using System.Net; using System.Threading; using Mono.Unix; using Mono.Unix.Native; +using NBitcoin.Protocol.Behaviors; using Newtonsoft.Json.Linq; using Swarmops.Backend.SocketServices; using Swarmops.Common.ExtensionMethods; using Swarmops.Database; +using Swarmops.Logic; using Swarmops.Logic.Communications; using Swarmops.Logic.Communications.Payload; using Swarmops.Logic.Communications.Resolution; @@ -875,6 +877,29 @@ namespace Swarmops.Backend } + public static void ProcessMetapackage(SocketMessage message) + { + switch (message.MessageType) + { + case "ProfitLossChanged": + // Broadcast message to recalculate P&L + JObject downstream = new JObject(); + downstream["MessageType"] = "RecalculateOrganizationProfitLoss"; + downstream["OrganizationId"] = message.OrganizationId.ToString(CultureInfo.InvariantCulture); + Broadcast(downstream); + break; + default: + // Unhandled. Exception? + break; + } + } + + + private static void Broadcast(JObject json) + { + _socketServer.WebSocketServices.Broadcast(json.ToString()); + } + // ------------------------------- BLOCKCHAIN.INFO WEB SOCKET INTERFACE CODE ------------------------- public static void OnBlockchainOpen(object sender, EventArgs args) diff --git a/Backend/SocketServices/BackendServices.cs b/Backend/SocketServices/BackendServices.cs index da965d0f..f2a311d5 100644 --- a/Backend/SocketServices/BackendServices.cs +++ b/Backend/SocketServices/BackendServices.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json.Linq; +using Swarmops.Logic; using Swarmops.Logic.Security; using WebSocketSharp; using WebSocketSharp.Server; @@ -38,6 +39,9 @@ namespace Swarmops.Backend.SocketServices case "AddBitcoinAddress": BackendLoop.AddBitcoinAddress((string) json["Address"]); break; + case "Metapackage": + BackendLoop.ProcessMetapackage(SocketMessage.FromXml((string) json["XmlData"])); + break; default: // do nothing; break; diff --git a/FrontSocket/FrontendLoop.cs b/FrontSocket/FrontendLoop.cs index 9829bab7..c71ab4bb 100644 --- a/FrontSocket/FrontendLoop.cs +++ b/FrontSocket/FrontendLoop.cs @@ -13,6 +13,7 @@ using Swarmops.Common.Enums; using Swarmops.Logic.Communications; using Swarmops.Logic.Communications.Payload; using Swarmops.Common.ExtensionMethods; +using Swarmops.Logic; using Swarmops.Logic.Security; using Swarmops.Logic.Structure; using Swarmops.Logic.Support; @@ -343,7 +344,7 @@ namespace Swarmops.Frontend.Socket { Console.WriteLine(" - Backend socket error: " + args.Message); - // TODO: Try reconnecting + // TODO: Try reconnecting if closed or never opened } @@ -408,6 +409,17 @@ namespace Swarmops.Frontend.Socket return false; } + + public static void SendMessageUpstream(SocketMessage message) + { + JObject json = new JObject(); + json["ServerRequest"] = "Metapackage"; + json["XmlData"] = message.ToXml(); + + _backendSocket.Send(json.ToString()); + } + + private static Dictionary _activeAlarms; internal static WebSocketServer SocketServer { get { return _socketServer; } } diff --git a/FrontSocket/FrontendServices.cs b/FrontSocket/FrontendServices.cs index 09919187..a28ebdda 100644 --- a/FrontSocket/FrontendServices.cs +++ b/FrontSocket/FrontendServices.cs @@ -6,6 +6,7 @@ using System.Text; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using Swarmops.Frontend.Socket; +using Swarmops.Logic; using Swarmops.Logic.Security; using WebSocketSharp; using WebSocketSharp.Server; @@ -39,6 +40,9 @@ namespace Swarmops.Frontend.Socket case "AddBitcoinAddress": FrontendLoop.AddBitcoinAddress((string) json["Address"]); break; + case "Metapackage": + ProcessMetapackage((string) json["XmlData"]); + break; case "Ping": // TODO: Request heartbeat from backend // Sessions.Broadcast("{\"messageType\":\"Heartbeat\"}"); @@ -49,30 +53,46 @@ namespace Swarmops.Frontend.Socket } } + + private void ProcessMetapackage(string xmlData) + { + SocketMessage message = SocketMessage.FromXml(xmlData); + + // Most should just be sent straight to backend. Some could possibly be processed already here. + + switch (message.MessageType) + { + case "...": + // some future to-be-defined processing + break; + + default: + // we're not handling here, send to backend + FrontendLoop.SendMessageUpstream(message); + break; + } + } + protected override void OnOpen() { Console.WriteLine(" * Attempted socket connection"); string authBase64 = Context.QueryString["Auth"]; - // TODO: Check for valid system authority token - authBase64 = Uri.UnescapeDataString (authBase64); // Defensive programming - % sign does not exist in base64 so this won't ever collapse a working encoding - _authority = Authority.FromEncryptedXml (authBase64); + if (Authority.IsSystemAuthorityTokenValid(authBase64)) + { + _authority = null; // System authority + } + else + { + _authority = Authority.FromEncryptedXml(authBase64); + this.Sessions.RegisterSession(this, this._authority); // Only register non-system sessions + Console.WriteLine(" - - authenticated: " + this._authority.Person.Canonical); + } - Console.WriteLine(" - - authenticated: " + this._authority.Person.Canonical); - - this.Sessions.RegisterSession(this, this._authority); - base.OnOpen(); - - JObject json = new JObject(); - json ["MessageType"] = json["messageType"] = "AnnualProfitLossCents"; - json["ProfitLossCents"] = this._authority.Organization.GetProfitLossCents().ToString(CultureInfo.InvariantCulture); - json["OrganizationId"] = this._authority.Organization.Identity; - - this.Send(json.ToString()); } protected override void OnClose (CloseEventArgs e) diff --git a/Logic/Financial/FinancialTransaction.cs b/Logic/Financial/FinancialTransaction.cs index 3d749481..71ccdf2c 100644 --- a/Logic/Financial/FinancialTransaction.cs +++ b/Logic/Financial/FinancialTransaction.cs @@ -265,8 +265,11 @@ namespace Swarmops.Logic.Financial private FinancialTransactionRow AddRow (int financialAccountId, Int64 amountCents, int personId) { - if (DateTime.Year <= - FinancialAccount.FromIdentity (financialAccountId).Organization.Parameters.FiscalBooksClosedUntilYear) + // private function that actually executes the row adding + + FinancialAccount account = FinancialAccount.FromIdentity(financialAccountId); + + if (DateTime.Year <= account.Organization.Parameters.FiscalBooksClosedUntilYear) { // Recurse down into continuation transactions to write row in first nonclosed year @@ -293,8 +296,29 @@ namespace Swarmops.Logic.Financial return newRow; } - return FinancialTransactionRow.FromIdentityAggressive (SwarmDb.GetDatabaseForWriting() + FinancialTransactionRow addedRow = FinancialTransactionRow.FromIdentityAggressive (SwarmDb.GetDatabaseForWriting() .CreateFinancialTransactionRow (Identity, financialAccountId, amountCents, personId)); + + // If we're running from web, and this was a P&L account, then also notify the server that the P&L has changed + // (doing this here means that the server can get pinged multiple times, but that's more defensive coding than + // having to remember doing it everywhere at the UI level) + + if (account.AccountType == FinancialAccountType.Income || account.AccountType == FinancialAccountType.Cost) + { + if (SupportFunctions.OperatingTopology == OperatingTopology.FrontendWeb) + { + SocketMessage newMessage = new SocketMessage + { + MessageType = "ProfitLossChanged", + OrganizationId = account.Organization.Identity, + FinancialTransactionId = this.Identity + }; + + newMessage.SendUpstream(); + } + } + + return addedRow; } public void AddDocument (string serverFileName, string originalFileName, Int64 fileSize, string description, diff --git a/Logic/Logic.csproj b/Logic/Logic.csproj index ff915372..7791cb78 100644 --- a/Logic/Logic.csproj +++ b/Logic/Logic.csproj @@ -195,6 +195,7 @@ + diff --git a/Logic/SocketMessage.cs b/Logic/SocketMessage.cs new file mode 100644 index 00000000..3903130a --- /dev/null +++ b/Logic/SocketMessage.cs @@ -0,0 +1,100 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Swarmops.Logic.Support; +using System.Xml.Serialization; +using Newtonsoft.Json.Linq; +using Swarmops.Logic.Security; +using WebSocketSharp; + + +namespace Swarmops.Logic +{ + [Serializable] + public class SocketMessage : SocketMessageBase + { + + } + + + [Serializable] + public class SocketMessageBase + { + public static T FromXml(string xml) // 'T' might not work here, like it didn't in ToXml() + { + // Compensate for stupid Mono encoding bugs + + if (xml.StartsWith("?")) + { + xml = xml.Substring(1); + } + + xml = xml.Replace("�", ""); + xml = xml.Replace("\x00", ""); + + XmlSerializer serializer = new XmlSerializer(typeof(T)); + + MemoryStream stream = new MemoryStream(); + byte[] xmlBytes = Encoding.UTF8.GetBytes(xml); + stream.Write(xmlBytes, 0, xmlBytes.Length); + + stream.Position = 0; + T result = (T)serializer.Deserialize(stream); + stream.Close(); + + return result; + } + public virtual string ToXml() + { + XmlSerializer serializer = new XmlSerializer(GetType()); + + MemoryStream stream = new MemoryStream(); + serializer.Serialize(stream, this); + + byte[] xmlBytes = stream.GetBuffer(); + string xml = Encoding.UTF8.GetString(xmlBytes); + + xml = xml.Replace("�", ""); + xml = xml.Replace("\x00", ""); + + return xml; + } + + public void SendUpstream() + { + if (SupportFunctions.OperatingTopology != OperatingTopology.FrontendWeb) + { + throw new InvalidOperationException("From web only"); + } + + + using ( + WebSocket socket = + new WebSocket("ws://localhost:" + SystemSettings.WebsocketPortFrontend + "/Front?Auth=" + + Uri.EscapeDataString(Authority.GetSystemAuthorityToken("Financial")))) + { + socket.Connect(); + + JObject data = new JObject(); + data["ServerRequest"] = "Metapackage"; + data["XmlData"] = this.ToXml(); + socket.Send(data.ToString()); + socket.Ping(); // wait a little little while for send to work + socket.Close(); + } + } + + + public string MessageType { get; set; } + public int OrganizationId { get; set; } + public int FinancialTransactionId { get; set; } + public int FinancialAccountId { get; set; } + public int GeographyId { get; set; } + public int PersonId { get; set; } + public string XmlData { get; set; } + } + +}