Added full chain of P&L notifications

This commit is contained in:
Falkvinge
2017-05-16 08:13:16 +02:00
parent c61bff3866
commit cc40100824
7 changed files with 204 additions and 18 deletions
+25
View File
@@ -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)
@@ -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;
+13 -1
View File
@@ -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<FrontendMalfunctions,bool> _activeAlarms;
internal static WebSocketServer SocketServer { get { return _socketServer; } }
+34 -14
View File
@@ -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)
+27 -3
View File
@@ -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,
+1
View File
@@ -195,6 +195,7 @@
<Compile Include="Communications\Payload\PayloadEnvelope.cs" />
<Compile Include="Communications\Payload\NotificationPayload.cs" />
<Compile Include="Security\Impersonation.cs" />
<Compile Include="SocketMessage.cs" />
<Compile Include="Support\BlockchainTransaction.cs" />
<Compile Include="Support\ErrorMessages.cs" />
<Compile Include="Support\LogEntries\ImpersonationLogEntry.cs" />
+100
View File
@@ -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<SocketMessage>
{
}
[Serializable]
public class SocketMessageBase<T>
{
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("&#x0;", "");
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("&#x0;", "");
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; }
}
}