diff --git a/src/Api/PubnubApi/Builder/ResponseBuilder.cs b/src/Api/PubnubApi/Builder/ResponseBuilder.cs index 937039e9c..4b365f56b 100644 --- a/src/Api/PubnubApi/Builder/ResponseBuilder.cs +++ b/src/Api/PubnubApi/Builder/ResponseBuilder.cs @@ -7,12 +7,16 @@ internal class ResponseBuilder private readonly PNConfiguration config; private readonly IJsonPluggableLibrary jsonLib; private readonly IPubnubLog pubnubLog; + private readonly NewtonsoftJsonDotNet newtonsoftJsonDotNet; + private readonly EventDeserializer eventDeserializer; public ResponseBuilder(PNConfiguration pubnubConfig, IJsonPluggableLibrary jsonPluggableLibrary, IPubnubLog log) { config = pubnubConfig; jsonLib = jsonPluggableLibrary; pubnubLog = log; + newtonsoftJsonDotNet = new NewtonsoftJsonDotNet(config, pubnubLog); + eventDeserializer = new EventDeserializer(jsonLib, newtonsoftJsonDotNet); } public T JsonToObject(List result, bool internalObject) @@ -25,11 +29,15 @@ public T JsonToObject(List result, bool internalObject) } else { - NewtonsoftJsonDotNet jsonNewtonLib = new NewtonsoftJsonDotNet(config, pubnubLog); - ret = jsonNewtonLib.DeserializeToObject(result); + ret = newtonsoftJsonDotNet.DeserializeToObject(result); } return ret; } + + public T GetEventResultObject(IDictionary jsonFields) + { + return eventDeserializer.Deserialize(jsonFields); + } } } diff --git a/src/Api/PubnubApi/EventEngine/Common/EventEmitter.cs b/src/Api/PubnubApi/EventEngine/Common/EventEmitter.cs index 6ead8486c..c898962b5 100644 --- a/src/Api/PubnubApi/EventEngine/Common/EventEmitter.cs +++ b/src/Api/PubnubApi/EventEngine/Common/EventEmitter.cs @@ -36,37 +36,52 @@ public EventEmitter(PNConfiguration configuration, List liste private TimetokenMetadata GetTimetokenMetadata(object t) { Dictionary ttOriginMetaData = jsonLibrary.ConvertToDictionaryObject(t); - if (ttOriginMetaData != null && ttOriginMetaData.Count > 0) { + if (ttOriginMetaData != null && ttOriginMetaData.Count > 0) + { TimetokenMetadata ttMeta = new TimetokenMetadata(); - foreach (string metaKey in ttOriginMetaData.Keys) { - if (metaKey.ToLowerInvariant().Equals("t", StringComparison.OrdinalIgnoreCase)) { + foreach (string metaKey in ttOriginMetaData.Keys) + { + if (metaKey.ToLowerInvariant().Equals("t", StringComparison.OrdinalIgnoreCase)) + { long timetoken; _ = Int64.TryParse(ttOriginMetaData[metaKey].ToString(), out timetoken); ttMeta.Timetoken = timetoken; - } else if (metaKey.ToLowerInvariant().Equals("r", StringComparison.OrdinalIgnoreCase)) { + } + else if (metaKey.ToLowerInvariant().Equals("r", StringComparison.OrdinalIgnoreCase)) + { ttMeta.Region = ttOriginMetaData[metaKey].ToString(); } } + return ttMeta; } + return null; } public void AddListener(SubscribeCallback listener, string[] channels, string[] groups) { - foreach (var c in channels.Where(c => !c.EndsWith("-pnpres"))) { - if (channelListenersMap.ContainsKey(c)) { + foreach (var c in channels.Where(c => !c.EndsWith("-pnpres"))) + { + if (channelListenersMap.ContainsKey(c)) + { channelListenersMap[c].Add(listener); - } else { + } + else + { channelListenersMap[c] = new List { listener }; } } - foreach (var cg in groups.Where(cg => !cg.EndsWith("-pnpres"))) { - if (channelGroupListenersMap.ContainsKey(cg)) { + foreach (var cg in groups.Where(cg => !cg.EndsWith("-pnpres"))) + { + if (channelGroupListenersMap.ContainsKey(cg)) + { channelGroupListenersMap[cg].Add(listener); - } else { + } + else + { channelGroupListenersMap[cg] = new List { listener }; } } @@ -74,13 +89,18 @@ public void AddListener(SubscribeCallback listener, string[] channels, string[] public void RemoveListener(SubscribeCallback listener, string[] channels, string[] groups) { - foreach (var c in channels.Where(c => !c.EndsWith("-pnpres"))) { - if (channelListenersMap.ContainsKey(c)) { + foreach (var c in channels.Where(c => !c.EndsWith("-pnpres"))) + { + if (channelListenersMap.ContainsKey(c)) + { channelListenersMap[c].Remove(listener); } } - foreach (var cg in groups.Where(cg => !cg.EndsWith("-pnpres"))) { - if (channelGroupListenersMap.ContainsKey(cg)) { + + foreach (var cg in groups.Where(cg => !cg.EndsWith("-pnpres"))) + { + if (channelGroupListenersMap.ContainsKey(cg)) + { channelGroupListenersMap[cg].Remove(listener); } } @@ -88,234 +108,340 @@ public void RemoveListener(SubscribeCallback listener, string[] channels, string public void EmitEvent(object e) { + var jsonFields = new Dictionary(); var eventData = e as Message; - string currentMessageChannel = eventData.Channel; - string currentMessageChannelGroup = eventData.SubscriptionMatch; - if (currentMessageChannel.Replace("-pnpres", "") == currentMessageChannelGroup?.Replace("-pnpres", "")) { + string currentMessageChannel = eventData?.Channel; + jsonFields.Add("channel", currentMessageChannel); + + string currentMessageChannelGroup = eventData?.SubscriptionMatch; + jsonFields.Add("channelGroup", currentMessageChannelGroup); + + if (currentMessageChannel?.Replace("-pnpres", "") == currentMessageChannelGroup?.Replace("-pnpres", "")) + { currentMessageChannelGroup = ""; + jsonFields["channelGroup"] = currentMessageChannelGroup; } + object payload; - string payloadAsString = eventData.Payload as string; - if (payloadAsString != null) { + string payloadAsString = eventData?.Payload as string; + if (payloadAsString != null) + { var jsonObject = jsonLibrary.BuildJsonObject(payloadAsString.ToString()); payload = jsonObject ?? payloadAsString; - } else { - payload = eventData.Payload; } + else + { + payload = eventData?.Payload; + } + List payloadContainer = new List(); //First item always message - if (currentMessageChannel.Contains("-pnpres") || currentMessageChannel.Contains(".*-pnpres")) { + if (currentMessageChannel.Contains("-pnpres") || currentMessageChannel.Contains(".*-pnpres")) + { payloadContainer.Add(payload); - } else if (eventData.MessageType == 2) //Objects Simplification events + jsonFields.Add("payload", payload); + } + else if (eventData.MessageType == 2) //Objects Simplification events { - double objectsVersion = -1; - Dictionary objectsDic = payload as Dictionary ?? (payload as JObject).ToObject>(); - if (objectsDic != null - && objectsDic.ContainsKey("source") - && objectsDic.ContainsKey("version") - && objectsDic["source"].ToString() == "objects" - && Double.TryParse(objectsDic["version"].ToString().Trim(), NumberStyles.Number, CultureInfo.InvariantCulture, out objectsVersion)) { + Dictionary appContextEventFields = payload as Dictionary ?? (payload as JObject)?.ToObject>(); + if (appContextEventFields != null + && appContextEventFields.ContainsKey("source") + && appContextEventFields.ContainsKey("version") + && appContextEventFields["source"].ToString() == "objects" + && Double.TryParse(appContextEventFields["version"]?.ToString()?.Trim(), NumberStyles.Number, CultureInfo.InvariantCulture, out var objectsVersion)) + { if (objectsVersion.CompareTo(2D) == 0) //Process only version=2 for Objects Simplification. Ignore 1. { payloadContainer.Add(payload); + jsonFields.Add("payload", payload); } } - } else { + } + else + { if ((configuration.CryptoModule != null || configuration.CipherKey.Length > 0) && (eventData.MessageType == 0 || eventData.MessageType == 4)) //decrypt the subscriber message if cipherkey is available { string decryptMessage = ""; configuration.CryptoModule ??= new CryptoModule(new AesCbcCryptor(configuration.CipherKey, log), new List() { new LegacyCryptor(configuration.CipherKey, configuration.UseRandomInitializationVector) }); - try { + try + { decryptMessage = configuration.CryptoModule.Decrypt(payload.ToString()); - } catch (Exception ex) { + } + catch (Exception ex) + { decryptMessage = "**DECRYPT ERROR**"; - LoggingMethod.WriteToLog( - log, - string.Format( - CultureInfo.InvariantCulture, - "Failed to decrypt message on channel {0} in ResponseToUserCallback due to exception={1}.\nMessage might be not encrypted, returning as is...", - currentMessageChannel, - ex - ), - configuration.LogVerbosity - ); + LoggingMethod.WriteToLog(log, $"Failed to decrypt message on channel {currentMessageChannel} due to exception={ex}.\n Message might be not encrypted", configuration.LogVerbosity); } + object decodeMessage = jsonLibrary.DeserializeToObject((decryptMessage == "**DECRYPT ERROR**") ? jsonLibrary.SerializeToJsonString(payload) : decryptMessage); payloadContainer.Add(decodeMessage); - } else { + jsonFields.Add("payload", decodeMessage); + } + else + { string payloadJson = jsonLibrary.SerializeToJsonString(payload); object payloadJObject = jsonLibrary.BuildJsonObject(payloadJson); - if (payloadJObject == null) { + if (payloadJObject == null) + { payloadContainer.Add(payload); - } else { + jsonFields.Add("payload", payload); + } + else + { payloadContainer.Add(payloadJObject); + jsonFields.Add("payload", payloadJObject); } } } - object userMetaData = eventData.UserMetadata; - + var userMetaData = eventData.UserMetadata; payloadContainer.Add(userMetaData); //Second one always user meta data - - payloadContainer.Add(GetTimetokenMetadata(eventData.PublishMetadata).Timetoken); //Third one always Timetoken - + jsonFields.Add("userMetadata", userMetaData); + payloadContainer.Add(GetTimetokenMetadata(eventData.PublishMetadata).Timetoken); //Third one always Timetoken - 2 + jsonFields.Add("publishTimetoken", GetTimetokenMetadata(eventData.PublishMetadata).Timetoken); payloadContainer.Add(eventData.IssuingClientId); //Fourth one always Publisher - + jsonFields.Add("userId", eventData.IssuingClientId); // - 3 + payloadContainer.Add(currentMessageChannelGroup); - payloadContainer.Add(currentMessageChannel); - if (eventData.MessageType == 1) { - payloadContainer.Add(eventData.CustomMessageType); - ResponseBuilder responseBuilder = new ResponseBuilder(configuration, jsonLibrary, log); - PNMessageResult pnMessageResult = responseBuilder.JsonToObject>(payloadContainer, true); - if (pnMessageResult != null) { - PNSignalResult signalMessage = new PNSignalResult { - Channel = pnMessageResult.Channel, - Message = pnMessageResult.Message, - Subscription = pnMessageResult.Subscription, - Timetoken = pnMessageResult.Timetoken, - UserMetadata = pnMessageResult.UserMetadata, - Publisher = pnMessageResult.Publisher - }; - foreach (var listener in listeners) { - listener?.Signal(instance, signalMessage); - } - if (!string.IsNullOrEmpty(signalMessage.Channel) && channelListenersMap.ContainsKey(signalMessage.Channel)) { - foreach (var l in channelListenersMap[signalMessage.Channel]) { - l?.Signal(instance, signalMessage); + switch (eventData.MessageType) + { + case 1: + { + payloadContainer.Add(eventData.CustomMessageType); + jsonFields.Add("customMessageType", eventData.CustomMessageType); + ResponseBuilder responseBuilder = new ResponseBuilder(configuration, jsonLibrary, log); + PNMessageResult pnMessageResult = responseBuilder.GetEventResultObject>(jsonFields); + if (pnMessageResult != null) + { + PNSignalResult signalMessage = new PNSignalResult + { + Channel = pnMessageResult.Channel, + Message = pnMessageResult.Message, + Subscription = pnMessageResult.Subscription, + Timetoken = pnMessageResult.Timetoken, + UserMetadata = pnMessageResult.UserMetadata, + Publisher = pnMessageResult.Publisher + }; + foreach (var listener in listeners) + { + listener?.Signal(instance, signalMessage); } - } - if (!string.IsNullOrEmpty(signalMessage.Subscription) && channelGroupListenersMap.ContainsKey(signalMessage.Subscription)) { - foreach (var l in channelGroupListenersMap[signalMessage.Subscription]) { - l?.Signal(instance, signalMessage); + + if (!string.IsNullOrEmpty(signalMessage.Channel) && channelListenersMap.ContainsKey(signalMessage.Channel)) + { + foreach (var l in channelListenersMap[signalMessage.Channel]) + { + l?.Signal(instance, signalMessage); + } + } + + if (!string.IsNullOrEmpty(signalMessage.Subscription) && channelGroupListenersMap.ContainsKey(signalMessage.Subscription)) + { + foreach (var l in channelGroupListenersMap[signalMessage.Subscription]) + { + l?.Signal(instance, signalMessage); + } } } + + break; } - } else if (eventData.MessageType == 2) { - ResponseBuilder responseBuilder = new ResponseBuilder(configuration, jsonLibrary, log); - PNObjectEventResult objectApiEvent = responseBuilder.JsonToObject(payloadContainer, true); - if (objectApiEvent != null) { - foreach (var listener in listeners) { - listener?.ObjectEvent(instance, objectApiEvent); - } - if (!string.IsNullOrEmpty(objectApiEvent.Channel) && channelListenersMap.ContainsKey(objectApiEvent.Channel)) { - foreach (var l in channelListenersMap[objectApiEvent.Channel]) { - l?.ObjectEvent(instance, objectApiEvent); + case 2: + { + ResponseBuilder responseBuilder = new ResponseBuilder(configuration, jsonLibrary, log); + PNObjectEventResult objectApiEvent = responseBuilder.GetEventResultObject(jsonFields); + if (objectApiEvent != null) + { + foreach (var listener in listeners) + { + listener?.ObjectEvent(instance, objectApiEvent); } - } - if (!string.IsNullOrEmpty(objectApiEvent.Subscription) && channelGroupListenersMap.ContainsKey(objectApiEvent.Subscription)) { - foreach (var l in channelGroupListenersMap[objectApiEvent.Subscription]) { - l?.ObjectEvent(instance, objectApiEvent); + + if (!string.IsNullOrEmpty(objectApiEvent.Channel) && channelListenersMap.ContainsKey(objectApiEvent.Channel)) + { + foreach (var l in channelListenersMap[objectApiEvent.Channel]) + { + l?.ObjectEvent(instance, objectApiEvent); + } + } + + if (!string.IsNullOrEmpty(objectApiEvent.Subscription) && channelGroupListenersMap.ContainsKey(objectApiEvent.Subscription)) + { + foreach (var l in channelGroupListenersMap[objectApiEvent.Subscription]) + { + l?.ObjectEvent(instance, objectApiEvent); + } } } + + break; } - } else if (eventData.MessageType == 3) { - ResponseBuilder responseBuilder = new ResponseBuilder(configuration, jsonLibrary, log); - PNMessageActionEventResult messageActionEvent = responseBuilder.JsonToObject(payloadContainer, true); - if (messageActionEvent != null) { - foreach (var listener in listeners) { - listener?.MessageAction(instance, messageActionEvent); - } - if (!string.IsNullOrEmpty(messageActionEvent.Channel) && channelListenersMap.ContainsKey(messageActionEvent.Channel)) { - foreach (var l in channelListenersMap[messageActionEvent.Channel]) { - l?.MessageAction(instance, messageActionEvent); + case 3: + { + ResponseBuilder responseBuilder = new ResponseBuilder(configuration, jsonLibrary, log); + PNMessageActionEventResult messageActionEvent = responseBuilder.GetEventResultObject(jsonFields); + if (messageActionEvent != null) + { + foreach (var listener in listeners) + { + listener?.MessageAction(instance, messageActionEvent); } - } - if (!string.IsNullOrEmpty(messageActionEvent.Subscription) && channelGroupListenersMap.ContainsKey(messageActionEvent.Subscription)) { - foreach (var l in channelGroupListenersMap[messageActionEvent.Subscription]) { - l?.MessageAction(instance, messageActionEvent); + + if (!string.IsNullOrEmpty(messageActionEvent.Channel) && channelListenersMap.ContainsKey(messageActionEvent.Channel)) + { + foreach (var l in channelListenersMap[messageActionEvent.Channel]) + { + l?.MessageAction(instance, messageActionEvent); + } + } + + if (!string.IsNullOrEmpty(messageActionEvent.Subscription) && channelGroupListenersMap.ContainsKey(messageActionEvent.Subscription)) + { + foreach (var l in channelGroupListenersMap[messageActionEvent.Subscription]) + { + l?.MessageAction(instance, messageActionEvent); + } } } + + break; } - } else if (eventData.MessageType == 4) { - payloadContainer.Add(eventData.CustomMessageType); - ResponseBuilder responseBuilder = new ResponseBuilder(configuration, jsonLibrary, log); - PNMessageResult pnFileResult = responseBuilder.JsonToObject>(payloadContainer, true); - if (pnFileResult != null) { - PNFileEventResult fileMessage = new PNFileEventResult { - Channel = pnFileResult.Channel, - Subscription = pnFileResult.Subscription, - Timetoken = pnFileResult.Timetoken, - Publisher = pnFileResult.Publisher, - CustomMessageType = pnFileResult.CustomMessageType, - }; - Dictionary pnMsgObjDic = jsonLibrary.ConvertToDictionaryObject(pnFileResult.Message); - if (pnMsgObjDic != null && pnMsgObjDic.Count > 0) { - if (pnMsgObjDic.ContainsKey("message") && pnMsgObjDic["message"] != null) { - fileMessage.Message = pnMsgObjDic["message"]; + case 4: + { + payloadContainer.Add(eventData.CustomMessageType); + ResponseBuilder responseBuilder = new ResponseBuilder(configuration, jsonLibrary, log); + PNMessageResult filesEvent = responseBuilder.GetEventResultObject>(jsonFields); + if (filesEvent != null) + { + PNFileEventResult fileMessage = new PNFileEventResult + { + Channel = filesEvent.Channel, + Subscription = filesEvent.Subscription, + Timetoken = filesEvent.Timetoken, + Publisher = filesEvent.Publisher, + CustomMessageType = filesEvent.CustomMessageType, + }; + Dictionary fileEventMessageField = jsonLibrary.ConvertToDictionaryObject(filesEvent.Message); + if (fileEventMessageField is { Count: > 0 }) + { + if (fileEventMessageField.ContainsKey("message") && fileEventMessageField["message"] != null) + { + fileMessage.Message = fileEventMessageField["message"]; + } + + if (fileEventMessageField.TryGetValue("file", out var fileField)) + { + Dictionary fileDetailFields = jsonLibrary.ConvertToDictionaryObject(fileField); + if (fileDetailFields != null && fileDetailFields.ContainsKey("id") && fileDetailFields.ContainsKey("name")) + { + fileMessage.File = new PNFile { Id = fileDetailFields["id"].ToString(), Name = fileDetailFields["name"].ToString() }; + fileMessage.File.Url = UriUtil.GetFileUrl(fileName: fileMessage.File.Name, fileId: fileMessage.File.Id, channel: fileMessage.Channel, + pnConfiguration: configuration, pubnub: instance, tokenmanager: tokenManager); + } + } } - if (pnMsgObjDic.ContainsKey("file")) { - Dictionary fileObjDic = jsonLibrary.ConvertToDictionaryObject(pnMsgObjDic["file"]); - if (fileObjDic != null && fileObjDic.ContainsKey("id") && fileObjDic.ContainsKey("name")) { - fileMessage.File = new PNFile { Id = fileObjDic["id"].ToString(), Name = fileObjDic["name"].ToString() }; - fileMessage.File.Url = UriUtil.GetFileUrl(fileName: fileMessage.File.Name, fileId: fileMessage.File.Id, channel:fileMessage.Channel, - pnConfiguration:configuration, pubnub:instance, tokenmanager:tokenManager); + else + { + if (filesEvent.Message != null) + { + fileMessage.Message = filesEvent.Message; } } - } else { - if (pnFileResult.Message != null) { - fileMessage.Message = pnFileResult.Message; + + foreach (var listener in listeners) + { + listener?.File(instance, fileMessage); } - } - foreach (var listener in listeners) { - listener?.File(instance, fileMessage); - } - if (!string.IsNullOrEmpty(fileMessage.Channel) && channelListenersMap.ContainsKey(fileMessage.Channel)) { - foreach (var l in channelListenersMap[fileMessage.Channel]) { - l?.File(instance, fileMessage); + + if (!string.IsNullOrEmpty(fileMessage.Channel) && channelListenersMap.ContainsKey(fileMessage.Channel)) + { + foreach (var l in channelListenersMap[fileMessage.Channel]) + { + l?.File(instance, fileMessage); + } } - } - if (!string.IsNullOrEmpty(fileMessage.Subscription) && channelGroupListenersMap.ContainsKey(fileMessage.Subscription)) { - foreach (var l in channelGroupListenersMap[fileMessage.Subscription]) { - l?.File(instance, fileMessage); + + if (!string.IsNullOrEmpty(fileMessage.Subscription) && channelGroupListenersMap.ContainsKey(fileMessage.Subscription)) + { + foreach (var l in channelGroupListenersMap[fileMessage.Subscription]) + { + l?.File(instance, fileMessage); + } } } + + break; } - } else if (currentMessageChannel.Contains("-pnpres")) { - ResponseBuilder responseBuilder = new ResponseBuilder(configuration, jsonLibrary, log); - PNPresenceEventResult presenceEvent = responseBuilder.JsonToObject(payloadContainer, true); - if (presenceEvent != null) { - foreach (var listener in listeners) { - listener?.Presence(instance, presenceEvent); - } - if (!string.IsNullOrEmpty(presenceEvent.Channel) && channelListenersMap.ContainsKey(presenceEvent.Channel)) { - foreach (var l in channelListenersMap[presenceEvent.Channel]) { - l?.Presence(instance, presenceEvent); - } - } - if (!string.IsNullOrEmpty(presenceEvent.Subscription) && channelGroupListenersMap.ContainsKey(presenceEvent.Subscription)) { - foreach (var l in channelGroupListenersMap[presenceEvent.Subscription]) { - l?.Presence(instance, presenceEvent); + default: + { + if (currentMessageChannel.Contains("-pnpres")) + { + ResponseBuilder responseBuilder = new ResponseBuilder(configuration, jsonLibrary, log); + PNPresenceEventResult presenceEvent = responseBuilder.GetEventResultObject(jsonFields); + if (presenceEvent != null) + { + foreach (var listener in listeners) + { + listener?.Presence(instance, presenceEvent); + } + + if (!string.IsNullOrEmpty(presenceEvent.Channel) && channelListenersMap.ContainsKey(presenceEvent.Channel)) + { + foreach (var l in channelListenersMap[presenceEvent.Channel]) + { + l?.Presence(instance, presenceEvent); + } + } + + if (!string.IsNullOrEmpty(presenceEvent.Subscription) && channelGroupListenersMap.ContainsKey(presenceEvent.Subscription)) + { + foreach (var l in channelGroupListenersMap[presenceEvent.Subscription]) + { + l?.Presence(instance, presenceEvent); + } + } } } - } + else + { + payloadContainer.Add(eventData.CustomMessageType); + ResponseBuilder responseBuilder = new ResponseBuilder(configuration, jsonLibrary, log); + PNMessageResult userMessage = responseBuilder.GetEventResultObject>(jsonFields); + try + { + if (userMessage != null) + { + foreach (var listener in listeners) + { + listener?.Message(instance, userMessage); + } - } else { - payloadContainer.Add(eventData.CustomMessageType); - ResponseBuilder responseBuilder = new ResponseBuilder(configuration, jsonLibrary, log); - PNMessageResult message = responseBuilder.JsonToObject>(payloadContainer, true); - try - { - if (message != null) { - foreach (var listener in listeners) { - listener?.Message(instance, message); - } - if (!string.IsNullOrEmpty(message.Channel) && channelListenersMap.ContainsKey(message.Channel)) { - foreach (var l in channelListenersMap[message.Channel]) { - l?.Message(instance, message); + if (!string.IsNullOrEmpty(userMessage.Channel) && channelListenersMap.ContainsKey(userMessage.Channel)) + { + foreach (var l in channelListenersMap[userMessage.Channel]) + { + l?.Message(instance, userMessage); + } + } + + if (!string.IsNullOrEmpty(userMessage.Subscription) && channelGroupListenersMap.ContainsKey(userMessage.Subscription)) + { + foreach (var l in channelGroupListenersMap[userMessage.Subscription]) + { + l?.Message(instance, userMessage); + } + } } } - if (!string.IsNullOrEmpty(message.Subscription) && channelGroupListenersMap.ContainsKey(message.Subscription)) { - foreach (var l in channelGroupListenersMap[message.Subscription]) { - l?.Message(instance, message); - } + catch (Exception ex) + { + LoggingMethod.WriteToLog(this.log, $"Listener call back execution encounters error: {ex.Message}\n{ex?.StackTrace}", configuration.LogVerbosity); } } - } - catch (Exception ex) - { - LoggingMethod.WriteToLog(this.log, $"Listener call back execution encounters error: {ex.Message}\n{ex?.StackTrace}", configuration.LogVerbosity); + + break; } } } diff --git a/src/Api/PubnubApi/JsonDataParse/DeserializeToInternalObjectUtility.cs b/src/Api/PubnubApi/JsonDataParse/DeserializeToInternalObjectUtility.cs index 65a4c166d..a8156684f 100644 --- a/src/Api/PubnubApi/JsonDataParse/DeserializeToInternalObjectUtility.cs +++ b/src/Api/PubnubApi/JsonDataParse/DeserializeToInternalObjectUtility.cs @@ -905,24 +905,6 @@ public static T DeserializeToInternalObject(IJsonPluggableLibrary jsonPlug, L #endregion } - else if (typeof(T) == typeof(PNObjectEventResult)) - { - #region "PNObjectEventResult" - - PNObjectEventResult result = PNObjectEventJsonDataParse.GetObject(jsonPlug, listObject); - ret = (T)Convert.ChangeType(result, typeof(PNObjectEventResult), CultureInfo.InvariantCulture); - - #endregion - } - else if (typeof(T) == typeof(PNMessageActionEventResult)) - { - #region "PNMessageActionEventResult" - - PNMessageActionEventResult result = PNMessageActionEventJsonDataParse.GetObject(jsonPlug, listObject); - ret = (T)Convert.ChangeType(result, typeof(PNMessageActionEventResult), CultureInfo.InvariantCulture); - - #endregion - } else if (typeof(T) == typeof(PNAddMessageActionResult)) { #region "PNAddMessageActionResult" diff --git a/src/Api/PubnubApi/JsonDataParse/EventDeserializer.cs b/src/Api/PubnubApi/JsonDataParse/EventDeserializer.cs new file mode 100644 index 000000000..223aa9a94 --- /dev/null +++ b/src/Api/PubnubApi/JsonDataParse/EventDeserializer.cs @@ -0,0 +1,146 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Reflection; + +namespace PubnubApi; + +public class EventDeserializer +{ + private readonly IJsonPluggableLibrary jsonLibrary; + private readonly NewtonsoftJsonDotNet newtonSoftJsonLibrary; // the default serializer of sdk + + public EventDeserializer(IJsonPluggableLibrary jsonLibrary, NewtonsoftJsonDotNet newtonSoftJsonLibrary) + { + this.jsonLibrary = jsonLibrary; + this.newtonSoftJsonLibrary = newtonSoftJsonLibrary; + } + + public T Deserialize(IDictionary json) + { + T response = default(T); + var typeInfo = typeof(T); + if (typeInfo.GetTypeInfo().IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(PNMessageResult<>)) + { + response = newtonSoftJsonLibrary.DeserializeMessageResultEvent(json); + } + else if (typeof(T) == typeof(PNObjectEventResult)) + { + PNObjectEventResult objectEvent = PNObjectEventJsonDataParse.GetObject(jsonLibrary, json); + response = (T)Convert.ChangeType(objectEvent, typeof(PNObjectEventResult), CultureInfo.InvariantCulture); + } + else if (typeof(T) == typeof(PNPresenceEventResult)) + { + PNPresenceEventResult presenceEvent = DeserializePresenceEvent(json); + response = (T)Convert.ChangeType(presenceEvent, typeof(PNPresenceEventResult), CultureInfo.InvariantCulture); + } + + else if (typeof(T) == typeof(PNMessageActionEventResult)) + { + PNMessageActionEventResult messageActionEvent = PNMessageActionEventJsonDataParse.GetObject(jsonLibrary, json); + response = (T)Convert.ChangeType(messageActionEvent, typeof(PNMessageActionEventResult), CultureInfo.InvariantCulture); + } + + return response; + } + + private PNPresenceEventResult DeserializePresenceEvent(IDictionary jsonFields) + { + Dictionary presenceDicObj = jsonLibrary.ConvertToDictionaryObject(jsonFields["payload"]); + + PNPresenceEventResult presenceEvent = null; + + if (presenceDicObj != null) + { + presenceEvent = new PNPresenceEventResult(); + presenceEvent.Event = presenceDicObj["action"].ToString(); + long presenceTimeStamp; + if (Int64.TryParse(presenceDicObj["timestamp"].ToString(), out presenceTimeStamp)) + { + presenceEvent.Timestamp = presenceTimeStamp; + } + + if (presenceDicObj.TryGetValue("uuid", out var value)) + { + presenceEvent.Uuid = value.ToString(); + } + + if (Int32.TryParse(presenceDicObj["occupancy"].ToString(), out var presenceOccupany)) + { + presenceEvent.Occupancy = presenceOccupany; + } + + if (presenceDicObj.TryGetValue("data", out var presenceEventDataField)) + { + if (presenceEventDataField is Dictionary presenceData) + { + presenceEvent.State = presenceData; + } + } + + if (Int64.TryParse(jsonFields["publishTimetoken"].ToString(), out var presenceTimetoken)) + { + presenceEvent.Timetoken = presenceTimetoken; + } + + presenceEvent.Channel = jsonFields["channel"]?.ToString(); + presenceEvent.Channel = presenceEvent.Channel?.Replace("-pnpres", ""); + + + presenceEvent.Subscription = jsonFields["channelGroup"]?.ToString(); + presenceEvent.Subscription = presenceEvent.Subscription?.Replace("-pnpres", ""); + + + if (jsonFields["userMetadata"] != null) + { + presenceEvent.UserMetadata = jsonFields["userMetadata"]; + } + + if (presenceEvent.Event != null && presenceEvent.Event.ToLowerInvariant() == "interval") + { + if (presenceDicObj.TryGetValue("join", out var joinUserList)) + { + List joinDeltaList = joinUserList as List; + if (joinDeltaList is { Count: > 0 }) + { + presenceEvent.Join = joinDeltaList.Select(x => x.ToString()).ToArray(); + } + } + + if (presenceDicObj.ContainsKey("timeout")) + { + List timeoutDeltaList = presenceDicObj["timeout"] as List; + if (timeoutDeltaList != null && timeoutDeltaList.Count > 0) + { + presenceEvent.Timeout = timeoutDeltaList.Select(x => x.ToString()).ToArray(); + } + } + + if (presenceDicObj.ContainsKey("leave")) + { + List leaveDeltaList = presenceDicObj["leave"] as List; + if (leaveDeltaList != null && leaveDeltaList.Count > 0) + { + presenceEvent.Leave = leaveDeltaList.Select(x => x.ToString()).ToArray(); + } + } + + if (presenceDicObj.ContainsKey("here_now_refresh")) + { + string hereNowRefreshStr = presenceDicObj["here_now_refresh"].ToString(); + if (!string.IsNullOrEmpty(hereNowRefreshStr)) + { + bool boolHereNowRefresh = false; + if (Boolean.TryParse(hereNowRefreshStr, out boolHereNowRefresh)) + { + presenceEvent.HereNowRefresh = boolHereNowRefresh; + } + } + } + } + } + + return presenceEvent; + } +} \ No newline at end of file diff --git a/src/Api/PubnubApi/JsonDataParse/PNMessageActionEventJsonDataParse.cs b/src/Api/PubnubApi/JsonDataParse/PNMessageActionEventJsonDataParse.cs index 1d2ea877c..a036dc32f 100644 --- a/src/Api/PubnubApi/JsonDataParse/PNMessageActionEventJsonDataParse.cs +++ b/src/Api/PubnubApi/JsonDataParse/PNMessageActionEventJsonDataParse.cs @@ -5,11 +5,11 @@ namespace PubnubApi { internal static class PNMessageActionEventJsonDataParse { - internal static PNMessageActionEventResult GetObject(IJsonPluggableLibrary jsonPlug, List listObject) + internal static PNMessageActionEventResult GetObject(IJsonPluggableLibrary jsonPlug, IDictionary listObject) { PNMessageActionEventResult result = null; - Dictionary msgActionEventDicObj = jsonPlug.ConvertToDictionaryObject(listObject[0]); + Dictionary msgActionEventDicObj = jsonPlug.ConvertToDictionaryObject(listObject["payload"]); if (msgActionEventDicObj != null) { result = new PNMessageActionEventResult(); @@ -43,12 +43,10 @@ internal static PNMessageActionEventResult GetObject(IJsonPluggableLibrary jsonP }; } } - result.Uuid = listObject[3].ToString(); - result.Subscription = listObject[4]?.ToString(); - result.Channel = listObject[5]?.ToString(); - + result.Uuid = listObject["userId"]?.ToString(); + result.Subscription = listObject["channelGroup"]?.ToString(); + result.Channel = listObject["channel"]?.ToString(); } - return result; } } diff --git a/src/Api/PubnubApi/JsonDataParse/PNObjectEventJsonDataParse.cs b/src/Api/PubnubApi/JsonDataParse/PNObjectEventJsonDataParse.cs index 1cf47116a..b942b8752 100644 --- a/src/Api/PubnubApi/JsonDataParse/PNObjectEventJsonDataParse.cs +++ b/src/Api/PubnubApi/JsonDataParse/PNObjectEventJsonDataParse.cs @@ -5,31 +5,25 @@ namespace PubnubApi { internal static class PNObjectEventJsonDataParse { - internal static PNObjectEventResult GetObject(IJsonPluggableLibrary jsonPlug, List listObject) + internal static PNObjectEventResult GetObject(IJsonPluggableLibrary jsonPlug, IDictionary jsonFields) { PNObjectEventResult result = null; - Dictionary objectEventDicObj = (listObject != null && listObject.Count > 0) ? jsonPlug.ConvertToDictionaryObject(listObject[0]) : null; + Dictionary objectEventDicObj = jsonFields is { Count: > 0 } ? jsonPlug.ConvertToDictionaryObject(jsonFields["payload"]) : null; if (objectEventDicObj != null) { - if (result == null) - { - result = new PNObjectEventResult(); - } + result = new PNObjectEventResult(); if (objectEventDicObj.ContainsKey("event") && objectEventDicObj["event"] != null) { result.Event = objectEventDicObj["event"].ToString(); } - if (listObject.Count > 2) + if (Int64.TryParse(jsonFields["publishTimetoken"]?.ToString(), out var objectEventTimeStamp)) { - long objectEventTimeStamp; - if (Int64.TryParse(listObject[2].ToString(), out objectEventTimeStamp)) - { - result.Timestamp = objectEventTimeStamp; - } + result.Timestamp = objectEventTimeStamp; } + if (objectEventDicObj.ContainsKey("type") && objectEventDicObj["type"] != null) { @@ -38,58 +32,58 @@ internal static PNObjectEventResult GetObject(IJsonPluggableLibrary jsonPlug, Li if (objectEventDicObj.ContainsKey("data") && objectEventDicObj["data"] != null) { - Dictionary dataDic = objectEventDicObj["data"] as Dictionary; - if (dataDic != null) + Dictionary dataFields = objectEventDicObj["data"] as Dictionary; + if (dataFields != null) { - if (result.Type.ToLowerInvariant() == "uuid" && dataDic.ContainsKey("id")) + if (result.Type?.ToLowerInvariant() == "uuid" && dataFields.ContainsKey("id")) { result.UuidMetadata = new PNUuidMetadataResult { - Uuid = dataDic["id"] != null ? dataDic["id"].ToString() : null, - Name = (dataDic.ContainsKey("name") && dataDic["name"] != null) ? dataDic["name"].ToString() : null, - ExternalId = (dataDic.ContainsKey("externalId") && dataDic["externalId"] != null) ? dataDic["externalId"].ToString() : null, - ProfileUrl = (dataDic.ContainsKey("profileUrl") && dataDic["profileUrl"] != null) ? dataDic["profileUrl"].ToString() : null, - Email = (dataDic.ContainsKey("email") && dataDic["email"] != null) ? dataDic["email"].ToString() : null, - Custom = (dataDic.ContainsKey("custom") && dataDic["custom"] != null) ? jsonPlug.ConvertToDictionaryObject(dataDic["custom"]) : null, - Updated = (dataDic.ContainsKey("updated") && dataDic["updated"] != null) ? dataDic["updated"].ToString() : null + Uuid = dataFields["id"]?.ToString(), + Name = (dataFields.ContainsKey("name") && dataFields["name"] != null) ? dataFields["name"].ToString() : null, + ExternalId = (dataFields.ContainsKey("externalId") && dataFields["externalId"] != null) ? dataFields["externalId"].ToString() : null, + ProfileUrl = (dataFields.ContainsKey("profileUrl") && dataFields["profileUrl"] != null) ? dataFields["profileUrl"].ToString() : null, + Email = (dataFields.ContainsKey("email") && dataFields["email"] != null) ? dataFields["email"].ToString() : null, + Custom = (dataFields.ContainsKey("custom") && dataFields["custom"] != null) ? jsonPlug.ConvertToDictionaryObject(dataFields["custom"]) : null, + Updated = (dataFields.ContainsKey("updated") && dataFields["updated"] != null) ? dataFields["updated"].ToString() : null }; } - else if (result.Type.ToLowerInvariant() == "channel" && dataDic.ContainsKey("id")) + else if (result.Type.ToLowerInvariant() == "channel" && dataFields.ContainsKey("id")) { result.ChannelMetadata = new PNChannelMetadataResult { - Channel = dataDic["id"] != null ? dataDic["id"].ToString() : null, - Name = (dataDic.ContainsKey("name") && dataDic["name"] != null) ? dataDic["name"].ToString() : null, - Description = (dataDic.ContainsKey("description") && dataDic["description"] != null) ? dataDic["description"].ToString() : null, - Custom = (dataDic.ContainsKey("custom") && dataDic["custom"] != null) ? jsonPlug.ConvertToDictionaryObject(dataDic["custom"]) : null, - Updated = (dataDic.ContainsKey("updated") && dataDic["updated"] != null) ? dataDic["updated"].ToString() : null + Channel = dataFields["id"]?.ToString(), + Name = (dataFields.ContainsKey("name") && dataFields["name"] != null) ? dataFields["name"].ToString() : null, + Description = (dataFields.ContainsKey("description") && dataFields["description"] != null) ? dataFields["description"].ToString() : null, + Custom = (dataFields.ContainsKey("custom") && dataFields["custom"] != null) ? jsonPlug.ConvertToDictionaryObject(dataFields["custom"]) : null, + Updated = (dataFields.ContainsKey("updated") && dataFields["updated"] != null) ? dataFields["updated"].ToString() : null }; } - else if (result.Type.ToLowerInvariant() == "membership" && dataDic.ContainsKey("uuid") && dataDic.ContainsKey("channel")) + else if (result.Type.ToLowerInvariant() == "membership" && dataFields.ContainsKey("uuid") && dataFields.ContainsKey("channel")) { - Dictionary uuidMetadataIdDic = dataDic["uuid"] as Dictionary; - if (uuidMetadataIdDic != null && uuidMetadataIdDic.ContainsKey("id")) + Dictionary userMetadataFields = dataFields["uuid"] as Dictionary; + if (userMetadataFields != null && userMetadataFields.ContainsKey("id")) { result.UuidMetadata = new PNUuidMetadataResult { - Uuid = uuidMetadataIdDic["id"] != null ? uuidMetadataIdDic["id"].ToString() : null + Uuid = userMetadataFields["id"]?.ToString() }; } - Dictionary channelMetadataIdDic = dataDic["channel"] as Dictionary; - if (channelMetadataIdDic != null && channelMetadataIdDic.ContainsKey("id")) + Dictionary channelMetadataFields = dataFields["channel"] as Dictionary; + if (channelMetadataFields != null && channelMetadataFields.ContainsKey("id")) { result.ChannelMetadata = new PNChannelMetadataResult { - Channel = channelMetadataIdDic["id"] != null ? channelMetadataIdDic["id"].ToString() : null + Channel = channelMetadataFields["id"]?.ToString() }; } } } } - result.Subscription = listObject[4]?.ToString(); - result.Channel = listObject[5].ToString(); + result.Subscription = jsonFields["channelGroup"]?.ToString(); + result.Channel = jsonFields["channel"].ToString(); } return result; diff --git a/src/Api/PubnubApi/NewtonsoftJsonDotNet.cs b/src/Api/PubnubApi/NewtonsoftJsonDotNet.cs index 68511b36d..f9e84796a 100644 --- a/src/Api/PubnubApi/NewtonsoftJsonDotNet.cs +++ b/src/Api/PubnubApi/NewtonsoftJsonDotNet.cs @@ -341,6 +341,81 @@ private T DeserializeMessageToObjectBasedOnPlatform(List listObject) return ret; } + internal T DeserializeMessageResultEvent(IDictionary jsonFields) + { + T response = default(T); + Type dataType = typeof(T).GetTypeInfo().GenericTypeArguments[0]; + Type generic = typeof(PNMessageResult<>); + Type specific = generic.MakeGenericType(dataType); + + var content = jsonFields["payload"]; + ConstructorInfo ci = specific.GetTypeInfo().DeclaredConstructors.FirstOrDefault(); + if (ci != null) + { + object message = ci.Invoke(new object[] { }); + PropertyInfo dataProp = specific.GetRuntimeProperty("Message"); + object userMessage = null; + + if (content.GetType() == typeof(JValue)) + { + JValue jsonValue = content as JValue; + userMessage = jsonValue.Value; + userMessage = ConvertToDataType(dataType, userMessage); + + dataProp.SetValue(message, userMessage, null); + } + else if (content.GetType() == typeof(JObject) || + content.GetType() == typeof(JArray)) + { + JToken token = content as JToken; + if (dataProp.PropertyType == typeof(string)) + { + userMessage = JsonConvert.SerializeObject(token, defaultJsonSerializerSettings); + } + else + { + userMessage = token.ToObject(dataProp.PropertyType, JsonSerializer.Create()); + } + + dataProp.SetValue(message, userMessage, null); + } + else if (content.GetType() == typeof(System.String)) + { + userMessage = content as string; + dataProp.SetValue(message, userMessage, null); + } + + PropertyInfo timeProp = specific.GetRuntimeProperty("Timetoken"); + long timetoken; + Int64.TryParse(jsonFields["publishTimetoken"].ToString(), out timetoken); + timeProp.SetValue(message, timetoken, null); + + PropertyInfo publisherProp = specific.GetRuntimeProperty("Publisher"); + string publisherValue = (jsonFields["userId"] != null) ? jsonFields["userId"].ToString() : ""; + publisherProp.SetValue(message, publisherValue, null); + + PropertyInfo channelNameProp = specific.GetRuntimeProperty("Channel"); + channelNameProp.SetValue(message, jsonFields["channel"]?.ToString(), null); + + PropertyInfo subsciptionProp = specific.GetRuntimeProperty("Subscription"); + subsciptionProp.SetValue(message, jsonFields["channelGroup"]?.ToString(), null); + + PropertyInfo customMessageType = specific.GetRuntimeProperty("CustomMessageType"); + customMessageType.SetValue(message, jsonFields["customMessageType"], null); + + if (jsonFields["userMetadata"] != null) + { + PropertyInfo userMetadataProp = specific.GetRuntimeProperty("UserMetadata"); + userMetadataProp.SetValue(message, jsonFields["userMetadata"], null); + } + + + response = (T)Convert.ChangeType(message, specific, CultureInfo.InvariantCulture); + } + + return response; + } + public virtual T DeserializeToObject(List listObject) { T ret = default(T); diff --git a/src/Api/PubnubApi/PubnubCoreBase.cs b/src/Api/PubnubApi/PubnubCoreBase.cs index 680f201dd..3f8d433ad 100644 --- a/src/Api/PubnubApi/PubnubCoreBase.cs +++ b/src/Api/PubnubApi/PubnubCoreBase.cs @@ -586,11 +586,11 @@ private void ResponseToUserCallback(List result, PNOperationType type } object payload = currentMessage.Payload; + var jsonFields = new Dictionary(); - List payloadContainer = new List(); //First item always message if (currentMessageChannel.Contains("-pnpres") || currentMessageChannel.Contains(".*-pnpres")) { - payloadContainer.Add(payload); + jsonFields.Add("payload", payload); } else if (currentMessage.MessageType == 2) //Objects Simplification events { @@ -604,7 +604,7 @@ private void ResponseToUserCallback(List result, PNOperationType type { if (objectsVersion.CompareTo(2D) == 0) //Process only version=2 for Objects Simplification. Ignore 1. { - payloadContainer.Add(payload); + jsonFields.Add("payload", payload); } else { @@ -659,7 +659,7 @@ private void ResponseToUserCallback(List result, PNOperationType type ); } object decodeMessage = jsonLib.DeserializeToObject((decryptMessage == "**DECRYPT ERROR**") ? jsonLib.SerializeToJsonString(payload) : decryptMessage); - payloadContainer.Add(decodeMessage); + jsonFields.Add("payload", decodeMessage); } else { @@ -667,31 +667,31 @@ private void ResponseToUserCallback(List result, PNOperationType type object payloadJObject = jsonLib.BuildJsonObject(payloadJson); if (payloadJObject == null) { - payloadContainer.Add(payload); + jsonFields.Add("payload", payload); } else { - payloadContainer.Add(payloadJObject); + jsonFields.Add("payload", payloadJObject); } } } object userMetaData = currentMessage.UserMetadata; + jsonFields.Add("userMetadata", userMetaData); - payloadContainer.Add(userMetaData); //Second one always user meta data + jsonFields.Add("publishTimetoken", currentMessage.PublishTimetokenMetadata.Timetoken); - payloadContainer.Add(currentMessage.PublishTimetokenMetadata.Timetoken); //Third one always Timetoken + jsonFields.Add("userId", currentMessage.IssuingClientId); - payloadContainer.Add(currentMessage.IssuingClientId); //Fourth one always Publisher - - payloadContainer.Add(currentMessageChannelGroup); - - payloadContainer.Add(currentMessageChannel); + jsonFields.Add("channelGroup", currentMessageChannelGroup); + + jsonFields.Add("channel", currentMessageChannel); if (currentMessage.MessageType == 1) { + jsonFields.Add("customMessageType", currentMessage.CustomMessageType); ResponseBuilder responseBuilder = new ResponseBuilder(currentConfig, jsonLib, currentLog); - PNMessageResult pnMessageResult = responseBuilder.JsonToObject>(payloadContainer, true); + PNMessageResult pnMessageResult = responseBuilder.GetEventResultObject>(jsonFields); if (pnMessageResult != null) { PNSignalResult signalMessage = new PNSignalResult @@ -710,7 +710,7 @@ private void ResponseToUserCallback(List result, PNOperationType type else if (currentMessage.MessageType == 2) { ResponseBuilder responseBuilder = new ResponseBuilder(currentConfig, jsonLib, currentLog); - PNObjectEventResult objectApiEvent = responseBuilder.JsonToObject(payloadContainer, true); + PNObjectEventResult objectApiEvent = responseBuilder.GetEventResultObject(jsonFields); if (objectApiEvent != null) { Announce(objectApiEvent); @@ -719,39 +719,39 @@ private void ResponseToUserCallback(List result, PNOperationType type else if (currentMessage.MessageType == 3) { ResponseBuilder responseBuilder = new ResponseBuilder(currentConfig, jsonLib, currentLog); - PNMessageActionEventResult msgActionEventEvent = responseBuilder.JsonToObject(payloadContainer, true); - if (msgActionEventEvent != null) + PNMessageActionEventResult messageActionEvent = responseBuilder.GetEventResultObject(jsonFields); + if (messageActionEvent != null) { - Announce(msgActionEventEvent); + Announce(messageActionEvent); } } else if (currentMessage.MessageType == 4) { - payloadContainer.Add(currentMessage.CustomMessageType); + jsonFields.Add("customMessageType", currentMessage.CustomMessageType); ResponseBuilder responseBuilder = new ResponseBuilder(currentConfig, jsonLib, currentLog); - PNMessageResult pnFileResult = responseBuilder.JsonToObject>(payloadContainer, true); - if (pnFileResult != null) + PNMessageResult filesEvent = responseBuilder.GetEventResultObject>(jsonFields); + if (filesEvent != null) { PNFileEventResult fileMessage = new PNFileEventResult { - Channel = pnFileResult.Channel, - Subscription = pnFileResult.Subscription, - Timetoken = pnFileResult.Timetoken, - Publisher = pnFileResult.Publisher, + Channel = filesEvent.Channel, + Subscription = filesEvent.Subscription, + Timetoken = filesEvent.Timetoken, + Publisher = filesEvent.Publisher, }; - Dictionary pnMsgObjDic = jsonLib.ConvertToDictionaryObject(pnFileResult.Message); - if (pnMsgObjDic != null && pnMsgObjDic.Count > 0) + Dictionary fileEventMessageField = jsonLib.ConvertToDictionaryObject(filesEvent.Message); + if (fileEventMessageField != null && fileEventMessageField.Count > 0) { - if (pnMsgObjDic.ContainsKey("message") && pnMsgObjDic["message"]!= null) + if (fileEventMessageField.ContainsKey("message") && fileEventMessageField["message"]!= null) { - fileMessage.Message = pnMsgObjDic["message"]; + fileMessage.Message = fileEventMessageField["message"]; } - if (pnMsgObjDic.ContainsKey("file")) + if (fileEventMessageField.ContainsKey("file")) { - Dictionary fileObjDic = jsonLib.ConvertToDictionaryObject(pnMsgObjDic["file"]); - if (fileObjDic != null && fileObjDic.ContainsKey("id") && fileObjDic.ContainsKey("name")) + Dictionary fileDetailFields = jsonLib.ConvertToDictionaryObject(fileEventMessageField["file"]); + if (fileDetailFields != null && fileDetailFields.ContainsKey("id") && fileDetailFields.ContainsKey("name")) { - fileMessage.File = new PNFile { Id = fileObjDic["id"].ToString(), Name = fileObjDic["name"].ToString() }; + fileMessage.File = new PNFile { Id = fileDetailFields["id"].ToString(), Name = fileDetailFields["name"].ToString() }; PubnubTokenMgrCollection.TryGetValue( PubnubInstance.InstanceId ?? "", out var tokenManager); fileMessage.File.Url = UriUtil.GetFileUrl(fileName: fileMessage.File.Name, fileId: fileMessage.File.Id, channel:fileMessage.Channel, @@ -761,9 +761,9 @@ private void ResponseToUserCallback(List result, PNOperationType type } else { - if (pnFileResult.Message != null) + if (filesEvent.Message != null) { - fileMessage.Message = pnFileResult.Message; + fileMessage.Message = filesEvent.Message; } } Announce(fileMessage); @@ -772,7 +772,7 @@ private void ResponseToUserCallback(List result, PNOperationType type else if (currentMessageChannel.Contains("-pnpres")) { ResponseBuilder responseBuilder = new ResponseBuilder(currentConfig, jsonLib, currentLog); - PNPresenceEventResult presenceEvent = responseBuilder.JsonToObject(payloadContainer, true); + PNPresenceEventResult presenceEvent = responseBuilder.GetEventResultObject(jsonFields); if (presenceEvent != null) { Announce(presenceEvent); @@ -782,11 +782,11 @@ private void ResponseToUserCallback(List result, PNOperationType type { if (currentConfig != null && currentLog != null) { - LoggingMethod.WriteToLog(currentLog, string.Format(CultureInfo.InvariantCulture, "DateTime: {0}, ResponseToUserCallback - payload = {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), jsonLib.SerializeToJsonString(payloadContainer)), currentConfig.LogVerbosity); + LoggingMethod.WriteToLog(currentLog, string.Format(CultureInfo.InvariantCulture, "DateTime: {0}, ResponseToUserCallback", DateTime.Now.ToString(CultureInfo.InvariantCulture)), currentConfig.LogVerbosity); } - payloadContainer.Add(currentMessage.CustomMessageType); + jsonFields.Add("customMessageType", currentMessage.CustomMessageType); ResponseBuilder responseBuilder = new ResponseBuilder(currentConfig, jsonLib, currentLog); - PNMessageResult userMessage = responseBuilder.JsonToObject>(payloadContainer, true); + PNMessageResult userMessage = responseBuilder.GetEventResultObject>(jsonFields); if (userMessage != null) { Announce(userMessage); diff --git a/src/Api/PubnubApiPCL/PubnubApiPCL.csproj b/src/Api/PubnubApiPCL/PubnubApiPCL.csproj index a5c2af288..ab5a625bb 100644 --- a/src/Api/PubnubApiPCL/PubnubApiPCL.csproj +++ b/src/Api/PubnubApiPCL/PubnubApiPCL.csproj @@ -302,6 +302,7 @@ Added support for Type field in membership APIs. JsonDataParse\DeserializeToInternalObjectUtility.cs + diff --git a/src/Api/PubnubApiUWP/PubnubApiUWP.csproj b/src/Api/PubnubApiUWP/PubnubApiUWP.csproj index 105fef7f7..ab43cdf19 100644 --- a/src/Api/PubnubApiUWP/PubnubApiUWP.csproj +++ b/src/Api/PubnubApiUWP/PubnubApiUWP.csproj @@ -417,6 +417,7 @@ Added support for Type field in membership APIs. JsonDataParse\DeserializeToInternalObjectUtility.cs + diff --git a/src/Api/PubnubApiUnity/PubnubApiUnity.csproj b/src/Api/PubnubApiUnity/PubnubApiUnity.csproj index ed0d66ae7..c30177980 100644 --- a/src/Api/PubnubApiUnity/PubnubApiUnity.csproj +++ b/src/Api/PubnubApiUnity/PubnubApiUnity.csproj @@ -226,6 +226,7 @@ JsonDataParse\DeserializeToInternalObjectUtility.cs + RetryConfiguration.cs