diff --git a/src/Api/PubnubApi/Builder/UriUtil.cs b/src/Api/PubnubApi/Builder/UriUtil.cs index b04673a70..ed89e779d 100644 --- a/src/Api/PubnubApi/Builder/UriUtil.cs +++ b/src/Api/PubnubApi/Builder/UriUtil.cs @@ -3,10 +3,11 @@ using System.Globalization; using System.Linq; using System.Text; +using PubnubApi.EndPoint; namespace PubnubApi { - public class UriUtil + public static class UriUtil { public static string EncodeUriComponent(string s, PNOperationType type, bool ignoreComma, bool ignoreColon, bool ignorePercent2fEncode) { @@ -77,13 +78,7 @@ public static string EncodeUriComponent(string s, PNOperationType type, bool ign } else { - string escapeChar = System.Uri.EscapeDataString(ch.ToString()); -#if NET35 || NET40 - if (escapeChar == ch.ToString() && IsUnsafeToEncode(ch, ignoreComma, ignoreColon)) - { - escapeChar = string.Format(CultureInfo.InvariantCulture, "%{0}{1}", ToHex(ch / 16), ToHex(ch % 16)); - } -#endif + string escapeChar = Uri.EscapeDataString(ch.ToString()); o.Append(escapeChar); } } @@ -162,7 +157,7 @@ private static int ConvertToUtf32(string s, int index) } // Check if the character at index is a high surrogate. - int temp1 = (int)s[index] - HighSurrogateStart; + int temp1 = s[index] - HighSurrogateStart; if (temp1 >= 0 && temp1 <= 0x7ff) { // Found a surrogate char. @@ -171,7 +166,7 @@ private static int ConvertToUtf32(string s, int index) // Found a high surrogate. if (index < s.Length - 1) { - int temp2 = (int)s[index + 1] - LowSurrogateStart; + int temp2 = s[index + 1] - LowSurrogateStart; if (temp2 >= 0 && temp2 <= 0x3ff) { // Found a low surrogate. @@ -196,12 +191,33 @@ private static int ConvertToUtf32(string s, int index) } // Not a high-surrogate or low-surrogate. Genereate the UTF32 value for the BMP characters. - return (int)s[index]; + return s[index]; } public static string BuildQueryString(Dictionary queryStringParamMap) { - return string.Join("&", queryStringParamMap?.OrderBy(kvp => kvp.Key, StringComparer.Ordinal).Select(kvp => string.Format(CultureInfo.InvariantCulture, "{0}={1}", kvp.Key, kvp.Value)).ToArray()); + return string.Join("&", queryStringParamMap?.OrderBy(kvp => kvp.Key, StringComparer.Ordinal).Select(kvp => string.Format(CultureInfo.InvariantCulture, "{0}={1}", kvp.Key, kvp.Value)).ToArray() ?? Array.Empty()); + } + + public static string GetFileUrl(string fileId, string fileName, string channel, PNConfiguration pnConfiguration, Pubnub pubnub, TokenManager tokenmanager) + { + var requestParameters = new RequestParameter() + { + RequestType = Constants.GET, + PathSegment = [ + "v1", + "files", + pnConfiguration.SubscribeKey, + "channels", + channel, + "files", + fileId, + fileName + ], + Query = new Dictionary() + }; + var transportRequest = pubnub.transportMiddleware.PreapareTransportRequest(requestParameter:requestParameters, PNOperationType.PNFileUrlOperation); + return transportRequest.RequestUrl; } } } diff --git a/src/Api/PubnubApi/Builder/UrlRequestBuilder.cs b/src/Api/PubnubApi/Builder/UrlRequestBuilder.cs deleted file mode 100644 index 6f8bb8fd2..000000000 --- a/src/Api/PubnubApi/Builder/UrlRequestBuilder.cs +++ /dev/null @@ -1,2283 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Globalization; -using PubnubApi.Security.Crypto.Common; -using PubnubApi.Security.Crypto; -using PubnubApi.Security.Crypto.Cryptors; -using System.Collections.Concurrent; -using System.Reflection; - -namespace PubnubApi -{ - public sealed class UrlRequestBuilder : IUrlRequestBuilder - { - private ConcurrentDictionary pubnubConfig { get; } = new ConcurrentDictionary(); - private readonly IJsonPluggableLibrary jsonLib ; - private readonly IPubnubUnitTest pubnubUnitTest; - private readonly IPubnubLog pubnubLog; - private readonly string pubnubInstanceId; - private readonly EndPoint.TokenManager tokenMgr; - - public UrlRequestBuilder(PNConfiguration config, IJsonPluggableLibrary jsonPluggableLibrary, IPubnubUnitTest pubnubUnitTest, IPubnubLog log, EndPoint.TokenManager pubnubTokenMgr, string pnInstanceId) - { - pubnubConfig.AddOrUpdate(pnInstanceId, config, (k, o) => config); - this.jsonLib = jsonPluggableLibrary; - this.pubnubUnitTest = pubnubUnitTest; - this.pubnubLog = log; - this.tokenMgr = pubnubTokenMgr; - this.pubnubInstanceId = string.IsNullOrEmpty(pnInstanceId) ? "" : pnInstanceId; - } - - Uri IUrlRequestBuilder.BuildTimeRequest(string requestMethod, string requestBody, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNTimeOperation; - - List url = new List(); - url.Add("time"); - url.Add("0"); - - Dictionary requestQueryStringParams = new Dictionary(); - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildMultiChannelSubscribeRequest(string requestMethod, string requestBody, string[] channels, string[] channelGroups, long timetoken, int region, string channelsJsonState, Dictionary initialSubscribeUrlParams, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNSubscribeOperation; - string channelForUrl = (channels.Length > 0) ? string.Join(",", channels.OrderBy(x => x).ToArray()) : ","; - - List url = new List(); - url.Add("v2"); - url.Add("subscribe"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add(channelForUrl); - url.Add("0"); - - Dictionary internalInitialSubscribeUrlParams = new Dictionary(); - if (initialSubscribeUrlParams != null) - { - internalInitialSubscribeUrlParams = initialSubscribeUrlParams; - } - - Dictionary requestQueryStringParams = new Dictionary(internalInitialSubscribeUrlParams); - - if (!requestQueryStringParams.ContainsKey("filter-expr") && pubnubConfig.ContainsKey(pubnubInstanceId) && !string.IsNullOrEmpty(pubnubConfig[pubnubInstanceId].FilterExpression)) - { - requestQueryStringParams.Add("filter-expr", UriUtil.EncodeUriComponent(pubnubConfig[pubnubInstanceId].FilterExpression, currentType, false, false, false)); - } - - if (!requestQueryStringParams.ContainsKey("ee") && pubnubConfig.ContainsKey(pubnubInstanceId) && pubnubConfig[pubnubInstanceId].EnableEventEngine) - { - requestQueryStringParams.Add("ee", ""); - } - - if (!requestQueryStringParams.ContainsKey("tt")) - { - requestQueryStringParams.Add("tt", timetoken.ToString(CultureInfo.InvariantCulture)); - } - - if (!requestQueryStringParams.ContainsKey("tr") && region > 0) - { - requestQueryStringParams.Add("tr", region.ToString(CultureInfo.InvariantCulture)); - } - - if (pubnubConfig.ContainsKey(pubnubInstanceId) && pubnubConfig[pubnubInstanceId].PresenceTimeout != 0) - { - requestQueryStringParams.Add("heartbeat", pubnubConfig[pubnubInstanceId].PresenceTimeout.ToString(CultureInfo.InvariantCulture)); - } - - if (channelGroups != null && channelGroups.Length > 0 && channelGroups[0] != "") - { - requestQueryStringParams.Add("channel-group", UriUtil.EncodeUriComponent(string.Join(",", channelGroups.OrderBy(x => x).ToArray()), currentType, false, false, false)); - } - - if (channelsJsonState != "{}" && channelsJsonState != "") - { - requestQueryStringParams.Add("state", UriUtil.EncodeUriComponent(channelsJsonState, currentType, false, false, false)); - } - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildMultiChannelLeaveRequest(string requestMethod, string requestBody, string[] channels, string[] channelGroups, string jsonUserState, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.Leave; - string multiChannel = (channels != null && channels.Length > 0) ? string.Join(",", channels.OrderBy(x => x).ToArray()) : ","; - - List url = new List(); - url.Add("v2"); - url.Add("presence"); - url.Add("sub_key"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("channel"); - url.Add(multiChannel); - url.Add("leave"); - - Dictionary requestQueryStringParams = new Dictionary(); - - if (pubnubConfig.ContainsKey(pubnubInstanceId) && pubnubConfig[pubnubInstanceId].PresenceTimeout != 0) - { - requestQueryStringParams.Add("heartbeat", pubnubConfig[pubnubInstanceId].PresenceTimeout.ToString(CultureInfo.InvariantCulture)); - } - - string channelsJsonState = jsonUserState; - if (channelsJsonState != "{}" && channelsJsonState != "") - { - requestQueryStringParams.Add("state", UriUtil.EncodeUriComponent(channelsJsonState, currentType, false, false, false)); - } - - if (channelGroups != null && channelGroups.Length > 0) - { - requestQueryStringParams.Add("channel-group", UriUtil.EncodeUriComponent(string.Join(",", channelGroups.OrderBy(x => x).ToArray()),currentType, false, false, false)); - } - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildPublishRequest(string requestMethod, string requestBody, string channel, object originalMessage, bool storeInHistory, int ttl, Dictionary userMetaData, Dictionary additionalUrlParams, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNPublishOperation; - - List url = new List(); - url.Add("publish"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].PublishKey : ""); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("0"); - url.Add(channel); - url.Add("0"); - if (requestMethod.ToUpperInvariant() == "GET") - { - string message = JsonEncodePublishMsg(originalMessage, currentType); - url.Add(message); - } - - Dictionary additionalUrlParamsDic = new Dictionary(); - if (additionalUrlParams != null) - { - additionalUrlParamsDic = additionalUrlParams; - } - - Dictionary requestQueryStringParams = new Dictionary(additionalUrlParamsDic); - - if (userMetaData != null) - { - string jsonMetaData = jsonLib.SerializeToJsonString(userMetaData); - requestQueryStringParams.Add("meta", UriUtil.EncodeUriComponent(jsonMetaData, currentType, false, false, false)); - } - - if (storeInHistory && ttl >= 0) - { - requestQueryStringParams.Add("tt1", ttl.ToString(CultureInfo.InvariantCulture)); - } - - if (!storeInHistory) - { - requestQueryStringParams.Add("store", "0"); - } - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - bool allowPAMv3Sign = requestMethod.ToUpperInvariant() != "POST"; - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, allowPAMv3Sign); - } - - Uri IUrlRequestBuilder.BuildSignalRequest(string requestMethod, string requestBody, string channel, object originalMessage, Dictionary userMetaData, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNSignalOperation; - - List url = new List(); - url.Add("signal"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].PublishKey : ""); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("0"); - url.Add(channel); - url.Add("0"); - if (requestMethod.ToUpperInvariant() == "GET") - { - string message = JsonEncodePublishMsg(originalMessage, currentType); - url.Add(message); - } - - Dictionary requestQueryStringParams = new Dictionary(); - if (userMetaData != null) - { - string jsonMetaData = jsonLib.SerializeToJsonString(userMetaData); - requestQueryStringParams.Add("meta", UriUtil.EncodeUriComponent(jsonMetaData, currentType, false, false, false)); - } - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildHereNowRequest(string requestMethod, string requestBody, string[] channels, string[] channelGroups, bool showUUIDList, bool includeUserState, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNHereNowOperation; - string channel = (channels != null && channels.Length > 0) ? string.Join(",", channels.OrderBy(x => x).ToArray()) : ","; - - List url = new List(); - url.Add("v2"); - url.Add("presence"); - url.Add("sub_key"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("channel"); - url.Add(channel); - - int disableUUID = showUUIDList ? 0 : 1; - int userState = includeUserState ? 1 : 0; - - Dictionary requestQueryStringParams = new Dictionary(); - - string commaDelimitedchannelGroup = (channelGroups != null) ? string.Join(",", channelGroups.OrderBy(x => x).ToArray()) : ""; - if (!string.IsNullOrEmpty(commaDelimitedchannelGroup) && commaDelimitedchannelGroup.Trim().Length > 0) - { - requestQueryStringParams.Add("channel-group", UriUtil.EncodeUriComponent(commaDelimitedchannelGroup, currentType, false, false, false)); - } - - requestQueryStringParams.Add("disable_uuids", disableUUID.ToString(CultureInfo.InvariantCulture)); - requestQueryStringParams.Add("state", userState.ToString(CultureInfo.InvariantCulture)); - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildHistoryRequest(string requestMethod, string requestBody, string channel, long start, long end, int count, bool reverse, bool includeToken, bool includeMeta, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNHistoryOperation; - - List url = new List(); - url.Add("v2"); - url.Add("history"); - url.Add("sub-key"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("channel"); - url.Add(channel); - - Dictionary requestQueryStringParams = new Dictionary(); - - requestQueryStringParams.Add("count", (count <= -1) ? "100" : count.ToString(CultureInfo.InvariantCulture)); - - if (reverse) - { - requestQueryStringParams.Add("reverse", "true"); - } - if (start != -1) - { - requestQueryStringParams.Add("start", start.ToString(CultureInfo.InvariantCulture)); - } - if (end != -1) - { - requestQueryStringParams.Add("end", end.ToString(CultureInfo.InvariantCulture)); - } - - if (includeToken) - { - requestQueryStringParams.Add("include_token", "true"); - } - - if (includeMeta) - { - requestQueryStringParams.Add("include_meta", "true"); - } - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach(KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildFetchRequest(string requestMethod, string requestBody, string[] channels, long start, long end, int count, bool reverse, bool includeMeta, bool includeMessageActions, bool includeUuid, bool includeMessageType, Dictionary externalQueryParam) - { - string channel = (channels != null && channels.Length > 0) ? string.Join(",", channels.OrderBy(x => x).ToArray()) : ""; - - PNOperationType currentType = PNOperationType.PNFetchHistoryOperation; - - List url = new List(); - url.Add("v3"); - url.Add(includeMessageActions ? "history-with-actions" : "history"); - url.Add("sub-key"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("channel"); - url.Add(channel); - - Dictionary requestQueryStringParams = new Dictionary(); - - requestQueryStringParams.Add("max", (count <= -1) ? (includeMessageActions || (channels != null && channels.Length > 1) ? "25" : "100") : count.ToString(CultureInfo.InvariantCulture)); - - if (reverse) - { - requestQueryStringParams.Add("reverse", "true"); - } - if (start != -1) - { - requestQueryStringParams.Add("start", start.ToString(CultureInfo.InvariantCulture)); - } - if (end != -1) - { - requestQueryStringParams.Add("end", end.ToString(CultureInfo.InvariantCulture)); - } - - if (includeMeta) - { - requestQueryStringParams.Add("include_meta", "true"); - } - - if (includeUuid) - { - requestQueryStringParams.Add("include_uuid", "true"); - } - - if (includeMessageType) - { - requestQueryStringParams.Add("include_message_type", "true"); - } - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildMessageCountsRequest(string requestMethod, string requestBody, string[] channels, long[] timetokens, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNMessageCountsOperation; - string channel = (channels != null && channels.Length > 0) ? string.Join(",", channels) : ""; - - List url = new List(); - url.Add("v3"); - url.Add("history"); - url.Add("sub-key"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("message-counts"); - if (!string.IsNullOrEmpty(channel)) - { - url.Add(UriUtil.EncodeUriComponent(channel, currentType, true, false, false)); - } - - Dictionary requestQueryStringParams = new Dictionary(); - - if (timetokens != null && timetokens.Length > 0) - { - string tt = string.Join(",", timetokens.Select(x => x.ToString(CultureInfo.InvariantCulture)).ToArray()); - if (timetokens.Length == 1) - { - requestQueryStringParams.Add("timetoken", tt); - } - else - { - requestQueryStringParams.Add("channelsTimetoken", UriUtil.EncodeUriComponent(tt, currentType, false, false, false)); - } - } - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildDeleteMessageRequest(string requestMethod, string requestBody, string channel, long start, long end, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNDeleteMessageOperation; - - List url = new List(); - url.Add("v3"); - url.Add("history"); - url.Add("sub-key"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("channel"); - url.Add(channel); - - Dictionary requestQueryStringParams = new Dictionary(); - - if (start != -1) - { - requestQueryStringParams.Add("start", start.ToString(CultureInfo.InvariantCulture)); - } - if (end != -1) - { - requestQueryStringParams.Add("end", end.ToString(CultureInfo.InvariantCulture)); - } - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildWhereNowRequest(string requestMethod, string requestBody, string uuid, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNWhereNowOperation; - - List url = new List(); - url.Add("v2"); - url.Add("presence"); - url.Add("sub_key"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("uuid"); - url.Add(uuid); - - Dictionary requestQueryStringParams = new Dictionary(); - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildGrantV2AccessRequest(string requestMethod, string requestBody, string channelsCommaDelimited, string channelGroupsCommaDelimited, string targetUuidsCommaDelimited, string authKeysCommaDelimited, bool read, bool write, bool delete, bool manage, bool get, bool update, bool join, long ttl, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNAccessManagerGrant; - - List url = new List(); - url.Add("v2"); - url.Add("auth"); - url.Add("grant"); - url.Add("sub-key"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - - Dictionary requestQueryStringParams = new Dictionary(); - - if (!string.IsNullOrEmpty(authKeysCommaDelimited)) - { - requestQueryStringParams.Add("auth", UriUtil.EncodeUriComponent(authKeysCommaDelimited, currentType, false, false, false)); - } - - if (!string.IsNullOrEmpty(channelsCommaDelimited)) - { - requestQueryStringParams.Add("channel", UriUtil.EncodeUriComponent(channelsCommaDelimited, currentType, false, false, false)); - } - - if (!string.IsNullOrEmpty(channelGroupsCommaDelimited)) - { - requestQueryStringParams.Add("channel-group", UriUtil.EncodeUriComponent(channelGroupsCommaDelimited, currentType, false, false, false)); - } - - if (!string.IsNullOrEmpty(targetUuidsCommaDelimited)) - { - requestQueryStringParams.Add("target-uuid", UriUtil.EncodeUriComponent(targetUuidsCommaDelimited, currentType, false, false, false)); - } - - if (ttl > -1) - { - requestQueryStringParams.Add("ttl", ttl.ToString(CultureInfo.InvariantCulture)); - } - - requestQueryStringParams.Add("r", Convert.ToInt32(read).ToString(CultureInfo.InvariantCulture)); - requestQueryStringParams.Add("w", Convert.ToInt32(write).ToString(CultureInfo.InvariantCulture)); - requestQueryStringParams.Add("d", Convert.ToInt32(delete).ToString(CultureInfo.InvariantCulture)); - requestQueryStringParams.Add("m", Convert.ToInt32(manage).ToString(CultureInfo.InvariantCulture)); - requestQueryStringParams.Add("g", Convert.ToInt32(get).ToString(CultureInfo.InvariantCulture)); - requestQueryStringParams.Add("u", Convert.ToInt32(update).ToString(CultureInfo.InvariantCulture)); - requestQueryStringParams.Add("j", Convert.ToInt32(join).ToString(CultureInfo.InvariantCulture)); - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildGrantV3AccessRequest(string requestMethod, string requestBody, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNAccessManagerGrantToken; - - List url = new List(); - url.Add("v3"); - url.Add("pam"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("grant"); - - Dictionary requestQueryStringParams = new Dictionary(); - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildRevokeV3AccessRequest(string requestMethod, string requestBody, string token, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNAccessManagerRevokeToken; - - List url = new List(); - url.Add("v3"); - url.Add("pam"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("grant"); - url.Add(token); - - Dictionary requestQueryStringParams = new Dictionary(); - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildAuditAccessRequest(string requestMethod, string requestBody, string channel, string channelGroup, string authKeysCommaDelimited, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNAccessManagerAudit; - - List url = new List(); - url.Add("v2"); - url.Add("auth"); - url.Add("audit"); - url.Add("sub-key"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - - Dictionary requestQueryStringParams = new Dictionary(); - - if (!string.IsNullOrEmpty(authKeysCommaDelimited)) - { - requestQueryStringParams.Add("auth", UriUtil.EncodeUriComponent(authKeysCommaDelimited, currentType, false, false, false)); - } - - if (!string.IsNullOrEmpty(channel)) - { - requestQueryStringParams.Add("channel", UriUtil.EncodeUriComponent(channel, currentType, false, false, false)); - } - - if (!string.IsNullOrEmpty(channelGroup)) - { - requestQueryStringParams.Add("channel-group", UriUtil.EncodeUriComponent(channelGroup, currentType, false, false, false)); - } - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildGetUserStateRequest(string requestMethod, string requestBody, string channelsCommaDelimited, string channelGroupsCommaDelimited, string uuid, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNGetStateOperation; - - List url = new List(); - url.Add("v2"); - url.Add("presence"); - url.Add("sub_key"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("channel"); - - if (string.IsNullOrEmpty(channelsCommaDelimited) || channelsCommaDelimited.Trim().Length <= 0) - { - url.Add(","); - } - else - { - url.Add(channelsCommaDelimited); - } - - url.Add("uuid"); - url.Add(uuid); - - Dictionary requestQueryStringParams = new Dictionary(); - - if (!string.IsNullOrEmpty(channelGroupsCommaDelimited) && channelGroupsCommaDelimited.Trim().Length > 0) - { - requestQueryStringParams.Add("channel-group", UriUtil.EncodeUriComponent(channelGroupsCommaDelimited, currentType, false, false, false)); - } - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildSetUserStateRequest(string requestMethod, string requestBody, string channelsCommaDelimited, string channelGroupsCommaDelimited, string uuid, string jsonUserState, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNSetStateOperation; - string internalChannelsCommaDelimited; - - if (string.IsNullOrEmpty(channelsCommaDelimited) || channelsCommaDelimited.Trim().Length <= 0) - { - internalChannelsCommaDelimited = ","; - } - else - { - internalChannelsCommaDelimited = channelsCommaDelimited; - } - - List url = new List(); - url.Add("v2"); - url.Add("presence"); - url.Add("sub_key"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("channel"); - url.Add(internalChannelsCommaDelimited); - url.Add("uuid"); - url.Add(uuid); - url.Add("data"); - - Dictionary requestQueryStringParams = new Dictionary(); - - if (!string.IsNullOrEmpty(channelGroupsCommaDelimited) && channelGroupsCommaDelimited.Trim().Length > 0) - { - requestQueryStringParams.Add("state", UriUtil.EncodeUriComponent(jsonUserState, currentType, false, false, false)); - requestQueryStringParams.Add("channel-group", UriUtil.EncodeUriComponent(channelGroupsCommaDelimited, currentType, false, false, false)); - } - else - { - requestQueryStringParams.Add("state", UriUtil.EncodeUriComponent(jsonUserState, currentType, false, false, false)); - } - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildAddChannelsToChannelGroupRequest(string requestMethod, string requestBody, string channelsCommaDelimited, string nameSpace, string groupName, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNAddChannelsToGroupOperation; - - List url = new List(); - url.Add("v1"); - url.Add("channel-registration"); - url.Add("sub-key"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - if (!string.IsNullOrEmpty(nameSpace) && nameSpace.Trim().Length > 0) - { - url.Add("namespace"); - url.Add(nameSpace); - } - url.Add("channel-group"); - url.Add(groupName); - - Dictionary requestQueryStringParams = new Dictionary(); - - requestQueryStringParams.Add("add", UriUtil.EncodeUriComponent(channelsCommaDelimited, currentType,false, false, false)); - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildRemoveChannelsFromChannelGroupRequest(string requestMethod, string requestBody, string channelsCommaDelimited, string nameSpace, string groupName, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNRemoveGroupOperation; - - bool groupNameAvailable = false; - bool nameSpaceAvailable = false; - bool channelAvaiable = false; - - List url = new List(); - url.Add("v1"); - url.Add("channel-registration"); - url.Add("sub-key"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - if (!string.IsNullOrEmpty(nameSpace) && nameSpace.Trim().Length > 0) - { - nameSpaceAvailable = true; - url.Add("namespace"); - url.Add(nameSpace); - } - - if (!string.IsNullOrEmpty(groupName) && groupName.Trim().Length > 0) - { - groupNameAvailable = true; - url.Add("channel-group"); - url.Add(groupName); - } - - if (!String.IsNullOrEmpty(channelsCommaDelimited)) - { - channelAvaiable = true; - } - - if (nameSpaceAvailable && groupNameAvailable && !channelAvaiable) - { - url.Add("remove"); - } - else if (nameSpaceAvailable && !groupNameAvailable && !channelAvaiable) - { - url.Add("remove"); - } - else if (!nameSpaceAvailable && groupNameAvailable && !channelAvaiable) - { - url.Add("remove"); - } - - Dictionary requestQueryStringParams = new Dictionary(); - - if (channelAvaiable) - { - requestQueryStringParams.Add("remove", UriUtil.EncodeUriComponent(channelsCommaDelimited, currentType, false, false, false)); - } - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildGetChannelsForChannelGroupRequest(string requestMethod, string requestBody, string nameSpace, string groupName, bool limitToChannelGroupScopeOnly, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.ChannelGroupGet; - - bool groupNameAvailable = false; - bool nameSpaceAvailable = false; - - List url = new List(); - url.Add("v1"); - url.Add("channel-registration"); - url.Add("sub-key"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - if (!string.IsNullOrEmpty(nameSpace) && nameSpace.Trim().Length > 0) - { - nameSpaceAvailable = true; - url.Add("namespace"); - url.Add(nameSpace); - } - if (limitToChannelGroupScopeOnly) - { - url.Add("channel-group"); - } - else - { - if (!string.IsNullOrEmpty(groupName) && groupName.Trim().Length > 0) - { - groupNameAvailable = true; - url.Add("channel-group"); - url.Add(groupName); - } - - if (!nameSpaceAvailable && !groupNameAvailable) - { - url.Add("namespace"); - } - else if (nameSpaceAvailable && !groupNameAvailable) - { - url.Add("channel-group"); - } - } - - Dictionary requestQueryStringParams = new Dictionary(); - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildGetAllChannelGroupRequest(string requestMethod, string requestBody, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.ChannelGroupAllGet; - - List url = new List(); - url.Add("v1"); - url.Add("channel-registration"); - url.Add("sub-key"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("channel-group"); - - Dictionary requestQueryStringParams = new Dictionary(); - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildRegisterDevicePushRequest(string requestMethod, string requestBody, string channel, PNPushType pushType, string pushToken, PushEnvironment environment, string deviceTopic, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PushRegister; - - List url = new List(); - if (pushType == PNPushType.APNS2) - { - url.Add("v2"); - url.Add("push"); - url.Add("sub-key"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("devices-apns2"); - url.Add(pushToken); - } - else - { - url.Add("v1"); - url.Add("push"); - url.Add("sub-key"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("devices"); - url.Add(pushToken); - } - - Dictionary requestQueryStringParams = new Dictionary(); - if (pushType == PNPushType.APNS2) - { - requestQueryStringParams.Add("environment", environment.ToString().ToLowerInvariant()); - requestQueryStringParams.Add("topic", UriUtil.EncodeUriComponent(deviceTopic, currentType, false, false, false)); - } - else - { - requestQueryStringParams.Add("type", pushType.ToString().ToLowerInvariant()); - } - requestQueryStringParams.Add("add", UriUtil.EncodeUriComponent(channel, currentType, false, false, false)); - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildUnregisterDevicePushRequest(string requestMethod, string requestBody, PNPushType pushType, string pushToken, PushEnvironment environment, string deviceTopic, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PushUnregister; - - List url = new List(); - if (pushType == PNPushType.APNS2) - { - url.Add("v2"); - url.Add("push"); - url.Add("sub-key"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("devices-apns2"); - url.Add(pushToken); - url.Add("remove"); - } - else - { - url.Add("v1"); - url.Add("push"); - url.Add("sub-key"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("devices"); - url.Add(pushToken); - url.Add("remove"); - } - - Dictionary requestQueryStringParams = new Dictionary(); - if (pushType == PNPushType.APNS2) - { - requestQueryStringParams.Add("environment", environment.ToString().ToLowerInvariant()); - requestQueryStringParams.Add("topic", UriUtil.EncodeUriComponent(deviceTopic, currentType, false, false, false)); - } - else - { - requestQueryStringParams.Add("type", pushType.ToString().ToLowerInvariant()); - } - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildRemoveChannelPushRequest(string requestMethod, string requestBody, string channel, PNPushType pushType, string pushToken, PushEnvironment environment, string deviceTopic, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PushRemove; - - List url = new List(); - if (pushType == PNPushType.APNS2) - { - url.Add("v2"); - url.Add("push"); - url.Add("sub-key"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("devices-apns2"); - url.Add(pushToken); - } - else - { - url.Add("v1"); - url.Add("push"); - url.Add("sub-key"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("devices"); - url.Add(pushToken); - } - - Dictionary requestQueryStringParams = new Dictionary(); - if (pushType == PNPushType.APNS2) - { - requestQueryStringParams.Add("environment", environment.ToString().ToLowerInvariant()); - requestQueryStringParams.Add("topic", UriUtil.EncodeUriComponent(deviceTopic, currentType, false, false, false)); - } - else - { - requestQueryStringParams.Add("type", pushType.ToString().ToLowerInvariant()); - } - requestQueryStringParams.Add("remove", UriUtil.EncodeUriComponent(channel, currentType, false, false, false)); - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildGetChannelsPushRequest(string requestMethod, string requestBody, PNPushType pushType, string pushToken, PushEnvironment environment, string deviceTopic, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PushGet; - - List url = new List(); - if (pushType == PNPushType.APNS2) - { - url.Add("v2"); - url.Add("push"); - url.Add("sub-key"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("devices-apns2"); - url.Add(pushToken); - } - else - { - url.Add("v1"); - url.Add("push"); - url.Add("sub-key"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("devices"); - url.Add(pushToken); - } - - Dictionary requestQueryStringParams = new Dictionary(); - - if (pushType == PNPushType.APNS2) - { - requestQueryStringParams.Add("environment", environment.ToString().ToLowerInvariant()); - requestQueryStringParams.Add("topic", UriUtil.EncodeUriComponent(deviceTopic, currentType, false, false, false)); - } - else - { - requestQueryStringParams.Add("type", pushType.ToString().ToLowerInvariant()); - } - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildPresenceHeartbeatRequest(string requestMethod, string requestBody, string[] channels, string[] channelGroups, string jsonUserState) - { - PNOperationType currentType = PNOperationType.PNHeartbeatOperation; - - string multiChannel = (channels != null && channels.Length > 0) ? string.Join(",", channels.OrderBy(x => x).ToArray()) : ","; - - List url = new List(); - url.Add("v2"); - url.Add("presence"); - url.Add("sub_key"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("channel"); - url.Add(multiChannel); - url.Add("heartbeat"); - - Dictionary requestQueryStringParams = new Dictionary(); - - string channelsJsonState = jsonUserState; - if (channelsJsonState != "{}" && channelsJsonState != "") - { - requestQueryStringParams.Add("state", UriUtil.EncodeUriComponent(channelsJsonState, currentType, false, false, false)); - } - - if (channelGroups != null && channelGroups.Length > 0) - { - requestQueryStringParams.Add("channel-group", UriUtil.EncodeUriComponent(string.Join(",", channelGroups.OrderBy(x => x).ToArray()), currentType, false, false, false)); - } - - if (pubnubConfig.ContainsKey(pubnubInstanceId) && pubnubConfig[pubnubInstanceId].PresenceTimeout != 0) - { - requestQueryStringParams.Add("heartbeat", pubnubConfig[pubnubInstanceId].PresenceTimeout.ToString(CultureInfo.InvariantCulture)); - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildSetUuidMetadataRequest(string requestMethod, string requestBody, string uuid, bool includeCustom, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNSetUuidMetadataOperation; - - List url = new List(); - url.Add("v2"); - url.Add("objects"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("uuids"); - url.Add(string.IsNullOrEmpty(uuid) ? "" : uuid); - - Dictionary requestQueryStringParams = new Dictionary(); - if (includeCustom) - { - requestQueryStringParams.Add("include", "custom"); - } - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildDeleteUuidMetadataRequest(string requestMethod, string requestBody, string uuid, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNDeleteUuidMetadataOperation; - - List url = new List(); - url.Add("v2"); - url.Add("objects"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("uuids"); - url.Add(string.IsNullOrEmpty(uuid) ? "" : uuid); - - Dictionary requestQueryStringParams = new Dictionary(); - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildGetAllUuidMetadataRequest(string requestMethod, string requestBody, string start, string end, int limit, bool includeCount, bool includeCustom, string filter, List sort, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNGetAllUuidMetadataOperation; - - List url = new List(); - url.Add("v2"); - url.Add("objects"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("uuids"); - - Dictionary requestQueryStringParams = new Dictionary(); - if (!string.IsNullOrEmpty(start)) - { - requestQueryStringParams.Add("start", UriUtil.EncodeUriComponent(start, currentType, false, false, false)); - } - if (!string.IsNullOrEmpty(end)) - { - requestQueryStringParams.Add("end", UriUtil.EncodeUriComponent(end, currentType, false, false, false)); - } - if (limit >= 0) - { - requestQueryStringParams.Add("limit", limit.ToString(CultureInfo.InvariantCulture)); - } - if (includeCount) - { - requestQueryStringParams.Add("count", "true"); - } - if (includeCustom) - { - requestQueryStringParams.Add("include", "custom"); - } - if (!string.IsNullOrEmpty(filter)) - { - requestQueryStringParams.Add("filter", UriUtil.EncodeUriComponent(filter, currentType, false, false, false)); - } - if (sort != null && sort.Count > 0) - { - requestQueryStringParams.Add("sort", UriUtil.EncodeUriComponent(string.Join(",",sort.ToArray()), currentType, false, false, false)); - } - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildGetSingleUuidMetadataRequest(string requestMethod, string requestBody, string uuid, bool includeCustom, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNGetUuidMetadataOperation; - - List url = new List(); - url.Add("v2"); - url.Add("objects"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("uuids"); - url.Add(string.IsNullOrEmpty(uuid) ? "": uuid); - - Dictionary requestQueryStringParams = new Dictionary(); - if (includeCustom) - { - requestQueryStringParams.Add("include", "custom"); - } - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildSetChannelMetadataRequest(string requestMethod, string requestBody, string channel, bool includeCustom, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNSetChannelMetadataOperation; - - List url = new List(); - url.Add("v2"); - url.Add("objects"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("channels"); - url.Add(string.IsNullOrEmpty(channel) ? "" : channel); - - Dictionary requestQueryStringParams = new Dictionary(); - if (includeCustom) - { - requestQueryStringParams.Add("include", "custom"); - } - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildDeleteChannelMetadataRequest(string requestMethod, string requestBody, string channel, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNDeleteChannelMetadataOperation; - - List url = new List(); - url.Add("v2"); - url.Add("objects"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("channels"); - url.Add(string.IsNullOrEmpty(channel) ? "" : channel); - - Dictionary requestQueryStringParams = new Dictionary(); - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildGetAllChannelMetadataRequest(string requestMethod, string requestBody, string start, string end, int limit, bool includeCount, bool includeCustom, string filter, List sort, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNGetAllChannelMetadataOperation; - - List url = new List(); - url.Add("v2"); - url.Add("objects"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("channels"); - - Dictionary requestQueryStringParams = new Dictionary(); - if (!string.IsNullOrEmpty(start)) - { - requestQueryStringParams.Add("start", UriUtil.EncodeUriComponent(start, currentType, false, false, false)); - } - if (!string.IsNullOrEmpty(end)) - { - requestQueryStringParams.Add("end", UriUtil.EncodeUriComponent(end, currentType, false, false, false)); - } - if (limit >= 0) - { - requestQueryStringParams.Add("limit", limit.ToString(CultureInfo.InvariantCulture)); - } - if (includeCount) - { - requestQueryStringParams.Add("count", "true"); - } - if (includeCustom) - { - requestQueryStringParams.Add("include", "custom"); - } - if (!string.IsNullOrEmpty(filter)) - { - requestQueryStringParams.Add("filter", UriUtil.EncodeUriComponent(filter, currentType, false, false, false)); - } - if (sort != null && sort.Count > 0) - { - requestQueryStringParams.Add("sort", UriUtil.EncodeUriComponent(string.Join(",", sort.ToArray()), currentType, false, false, false)); - } - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildGetSingleChannelMetadataRequest(string requestMethod, string requestBody, string channel, bool includeCustom, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNGetChannelMetadataOperation; - - List url = new List(); - url.Add("v2"); - url.Add("objects"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("channels"); - url.Add(string.IsNullOrEmpty(channel) ? "" : channel); - - Dictionary requestQueryStringParams = new Dictionary(); - if (includeCustom) - { - requestQueryStringParams.Add("include", "custom"); - } - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildMembershipSetRemoveManageUserRequest(PNOperationType type, string requestMethod, string requestBody, string uuid, string start, string end, int limit, bool includeCount, string includeOptions, List sort, Dictionary externalQueryParam) - { - PNOperationType currentType = type; - - List url = new List(); - url.Add("v2"); - url.Add("objects"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("uuids"); - url.Add(string.IsNullOrEmpty(uuid) ? "" : uuid); - url.Add("channels"); - - Dictionary requestQueryStringParams = new Dictionary(); - if (!string.IsNullOrEmpty(start)) - { - requestQueryStringParams.Add("start", UriUtil.EncodeUriComponent(start, currentType, false, false, false)); - } - if (!string.IsNullOrEmpty(end)) - { - requestQueryStringParams.Add("end", UriUtil.EncodeUriComponent(end, currentType, false, false, false)); - } - if (limit >= 0) - { - requestQueryStringParams.Add("limit", limit.ToString(CultureInfo.InvariantCulture)); - } - if (includeCount) - { - requestQueryStringParams.Add("count", "true"); - } - if (!string.IsNullOrEmpty(includeOptions)) - { - requestQueryStringParams.Add("include", UriUtil.EncodeUriComponent(includeOptions, currentType, false, false, false)); - } - if (sort != null && sort.Count > 0) - { - requestQueryStringParams.Add("sort", UriUtil.EncodeUriComponent(string.Join(",", sort.ToArray()), currentType, false, false, false)); - } - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildMemberAddUpdateRemoveChannelRequest(string requestMethod, string requestBody, string channel, string start, string end, int limit, bool includeCount, string includeOptions, List sort, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNManageChannelMembersOperation; - - List url = new List(); - url.Add("v2"); - url.Add("objects"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("channels"); - url.Add(string.IsNullOrEmpty(channel) ? "" : channel); - url.Add("uuids"); - - Dictionary requestQueryStringParams = new Dictionary(); - if (!string.IsNullOrEmpty(start)) - { - requestQueryStringParams.Add("start", UriUtil.EncodeUriComponent(start, currentType, false, false, false)); - } - if (!string.IsNullOrEmpty(end)) - { - requestQueryStringParams.Add("end", UriUtil.EncodeUriComponent(end, currentType, false, false, false)); - } - if (limit >= 0) - { - requestQueryStringParams.Add("limit", limit.ToString(CultureInfo.InvariantCulture)); - } - if (includeCount) - { - requestQueryStringParams.Add("count", "true"); - } - if (!string.IsNullOrEmpty(includeOptions)) - { - requestQueryStringParams.Add("include", UriUtil.EncodeUriComponent(includeOptions, currentType, false, false, false)); - } - if (sort != null && sort.Count > 0) - { - requestQueryStringParams.Add("sort", UriUtil.EncodeUriComponent(string.Join(",", sort.ToArray()), currentType, false, false, false)); - } - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildGetAllMembershipsRequest(string requestMethod, string requestBody, string uuid, string start, string end, int limit, bool includeCount, string includeOptions, string filter, List sort, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNGetMembershipsOperation; - - List url = new List(); - url.Add("v2"); - url.Add("objects"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("uuids"); - url.Add(string.IsNullOrEmpty(uuid) ? "" : uuid); - url.Add("channels"); - - Dictionary requestQueryStringParams = new Dictionary(); - if (!string.IsNullOrEmpty(start)) - { - requestQueryStringParams.Add("start", UriUtil.EncodeUriComponent(start, currentType, false, false, false)); - } - if (!string.IsNullOrEmpty(end)) - { - requestQueryStringParams.Add("end", UriUtil.EncodeUriComponent(end, currentType, false, false, false)); - } - if (limit >= 0) - { - requestQueryStringParams.Add("limit", limit.ToString(CultureInfo.InvariantCulture)); - } - if (includeCount) - { - requestQueryStringParams.Add("count", "true"); - } - if (!string.IsNullOrEmpty(includeOptions)) - { - requestQueryStringParams.Add("include", UriUtil.EncodeUriComponent(includeOptions, currentType, false, false, false)); - } - if (!string.IsNullOrEmpty(filter)) - { - requestQueryStringParams.Add("filter", UriUtil.EncodeUriComponent(filter, currentType, false, false, false)); - } - if (sort != null && sort.Count > 0) - { - requestQueryStringParams.Add("sort", UriUtil.EncodeUriComponent(string.Join(",", sort.ToArray()), currentType, false, false, false)); - } - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildGetAllMembersRequest(string requestMethod, string requestBody, string channel, string start, string end, int limit, bool includeCount, string includeOptions, string filter, List sort, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNGetChannelMembersOperation; - - List url = new List(); - url.Add("v2"); - url.Add("objects"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("channels"); - url.Add(string.IsNullOrEmpty(channel) ? "" : channel); - url.Add("uuids"); - - Dictionary requestQueryStringParams = new Dictionary(); - if (!string.IsNullOrEmpty(start)) - { - requestQueryStringParams.Add("start", UriUtil.EncodeUriComponent(start, currentType, false, false, false)); - } - if (!string.IsNullOrEmpty(end)) - { - requestQueryStringParams.Add("end", UriUtil.EncodeUriComponent(end, currentType, false, false, false)); - } - if (limit >= 0) - { - requestQueryStringParams.Add("limit", limit.ToString(CultureInfo.InvariantCulture)); - } - if (includeCount) - { - requestQueryStringParams.Add("count", "true"); - } - if (!string.IsNullOrEmpty(includeOptions)) - { - requestQueryStringParams.Add("include", UriUtil.EncodeUriComponent(includeOptions, currentType, false, false, false)); - } - if (!string.IsNullOrEmpty(filter)) - { - requestQueryStringParams.Add("filter", UriUtil.EncodeUriComponent(filter, currentType, false, false, false)); - } - if (sort != null && sort.Count > 0) - { - requestQueryStringParams.Add("sort", UriUtil.EncodeUriComponent(string.Join(",", sort.ToArray()), currentType, false, false, false)); - } - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildAddMessageActionRequest(string requestMethod, string requestBody, string channel, long messageTimetoken, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNAddMessageActionOperation; - - List url = new List(); - url.Add("v1"); - url.Add("message-actions"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("channel"); - url.Add(channel); - url.Add("message"); - url.Add(messageTimetoken.ToString(CultureInfo.InvariantCulture)); - - Dictionary requestQueryStringParams = new Dictionary(); - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildRemoveMessageActionRequest(string requestMethod, string requestBody, string channel, long messageTimetoken, long actionTimetoken, string messageActionUuid, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNRemoveMessageActionOperation; - - List url = new List(); - url.Add("v1"); - url.Add("message-actions"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("channel"); - url.Add(channel); - url.Add("message"); - url.Add(messageTimetoken.ToString(CultureInfo.InvariantCulture)); - url.Add("action"); - url.Add(actionTimetoken.ToString(CultureInfo.InvariantCulture)); - - Dictionary requestQueryStringParams = new Dictionary(); - if (messageActionUuid != null) - { - requestQueryStringParams.Add("uuid", UriUtil.EncodeUriComponent(messageActionUuid, currentType, false, false, false)); - } - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildGetMessageActionsRequest(string requestMethod, string requestBody, string channel, long start, long end, int limit, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNGetMessageActionsOperation; - - List url = new List(); - url.Add("v1"); - url.Add("message-actions"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("channel"); - url.Add(channel); - - Dictionary requestQueryStringParams = new Dictionary(); - if (start >= 0) - { - requestQueryStringParams.Add("start", start.ToString(CultureInfo.InvariantCulture)); - } - if (end >= 0) - { - requestQueryStringParams.Add("end", end.ToString(CultureInfo.InvariantCulture)); - } - if (limit >= 0) - { - requestQueryStringParams.Add("limit", limit.ToString(CultureInfo.InvariantCulture)); - } - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildGenerateFileUploadUrlRequest(string requestMethod, string requestBody, string channel, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNGenerateFileUploadUrlOperation; - - List url = new List(); - url.Add("v1"); - url.Add("files"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("channels"); - url.Add(channel); - url.Add("generate-upload-url"); - - Dictionary requestQueryStringParams = new Dictionary(); - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildPublishFileMessageRequest(string requestMethod, string requestBody, string channel, object originalMessage, bool storeInHistory, int ttl, Dictionary userMetaData, Dictionary additionalUrlParams, Dictionary externalQueryParam) - { - PNOperationType currentType = PNOperationType.PNPublishFileMessageOperation; - - List url = new List(); - url.Add("v1"); - url.Add("files"); - url.Add("publish-file"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].PublishKey : ""); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("0"); - url.Add(channel); - url.Add("0"); - if (requestMethod.ToUpperInvariant() == "GET") - { - string message = JsonEncodePublishMsg(originalMessage, currentType); - url.Add(message); - } - - Dictionary additionalUrlParamsDic = new Dictionary(); - if (additionalUrlParams != null) - { - additionalUrlParamsDic = additionalUrlParams; - } - - Dictionary requestQueryStringParams = new Dictionary(additionalUrlParamsDic); - - if (userMetaData != null) - { - string jsonMetaData = jsonLib.SerializeToJsonString(userMetaData); - requestQueryStringParams.Add("meta", UriUtil.EncodeUriComponent(jsonMetaData, currentType, false, false, false)); - } - - if (storeInHistory && ttl >= 0) - { - requestQueryStringParams.Add("tt1", ttl.ToString(CultureInfo.InvariantCulture)); - } - - if (!storeInHistory) - { - requestQueryStringParams.Add("store", "0"); - } - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildGetFileUrlOrDeleteReqest(string requestMethod, string requestBody, string channel, string fileId, string fileName, Dictionary externalQueryParam, PNOperationType operationType) - { - PNOperationType currentType = operationType; - - List url = new List(); - url.Add("v1"); - url.Add("files"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("channels"); - url.Add(channel); - url.Add("files"); - url.Add(fileId); - url.Add(fileName); - - Dictionary requestQueryStringParams = new Dictionary(); - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - Uri IUrlRequestBuilder.BuildListFilesReqest(string requestMethod, string requestBody, string channel, int limit, string nextToken, Dictionary externalQueryParam, PNOperationType operationType) - { - PNOperationType currentType = operationType; - - List url = new List(); - url.Add("v1"); - url.Add("files"); - url.Add(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].SubscribeKey : ""); - url.Add("channels"); - url.Add(channel); - url.Add("files"); - - Dictionary requestQueryStringParams = new Dictionary(); - requestQueryStringParams.Add("limit", (limit <= -1) ? "100" : limit.ToString(CultureInfo.InvariantCulture)); - if (!string.IsNullOrEmpty(nextToken)) - { - requestQueryStringParams.Add("next", nextToken); - } - - if (externalQueryParam != null && externalQueryParam.Count > 0) - { - foreach (KeyValuePair kvp in externalQueryParam) - { - if (!requestQueryStringParams.ContainsKey(kvp.Key)) - { - requestQueryStringParams.Add(kvp.Key, UriUtil.EncodeUriComponent(kvp.Value.ToString(), currentType, false, false, false)); - } - } - } - - string queryString = BuildQueryString(currentType, requestQueryStringParams); - - return BuildRestApiRequest(requestMethod, requestBody, url, currentType, queryString, true); - } - - - private Dictionary GenerateCommonQueryParams(PNOperationType type, string uuid) - { - long timeStamp = TranslateUtcDateTimeToSeconds(DateTime.UtcNow); - string requestid = Guid.NewGuid().ToString(); - - if (pubnubUnitTest != null) - { - timeStamp = pubnubUnitTest.Timetoken; - requestid = string.IsNullOrEmpty(pubnubUnitTest.RequestId) ? "" : pubnubUnitTest.RequestId; - } - - Dictionary ret = new Dictionary(); - if (pubnubUnitTest != null && pubnubConfig.ContainsKey(pubnubInstanceId)) - { - if (pubnubUnitTest.IncludeUuid) - { - ret.Add("uuid", UriUtil.EncodeUriComponent(pubnubConfig[pubnubInstanceId].UserId, PNOperationType.PNSubscribeOperation, false, false, true)); - } - - if (pubnubUnitTest.IncludePnsdk) - { - ret.Add("pnsdk", UriUtil.EncodeUriComponent(Pubnub.Version, PNOperationType.PNSubscribeOperation, false, false, true)); - } - } - else - { - ret.Add("uuid", UriUtil.EncodeUriComponent(uuid != null ? uuid : - (pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].UserId.ToString() : ""), - PNOperationType.PNSubscribeOperation, false, false, true)); - ret.Add("pnsdk", UriUtil.EncodeUriComponent(Pubnub.Version, PNOperationType.PNSubscribeOperation, false, false, true)); - } - - if (pubnubConfig != null) - { - if (pubnubConfig.ContainsKey(pubnubInstanceId) && pubnubConfig[pubnubInstanceId].IncludeRequestIdentifier) - { - ret.Add("requestid", requestid); - } - - if (pubnubConfig.ContainsKey(pubnubInstanceId) && pubnubConfig[pubnubInstanceId].IncludeInstanceIdentifier && !string.IsNullOrEmpty(pubnubInstanceId) && pubnubInstanceId.Trim().Length > 0) - { - ret.Add("instanceid", pubnubInstanceId); - } - - if (pubnubConfig.ContainsKey(pubnubInstanceId) && !string.IsNullOrEmpty(pubnubConfig[pubnubInstanceId].SecretKey)) - { - ret.Add("timestamp", timeStamp.ToString(CultureInfo.InvariantCulture)); - } - - if (type != PNOperationType.PNTimeOperation - && type != PNOperationType.PNAccessManagerGrant && type != PNOperationType.PNAccessManagerGrantToken && type != PNOperationType.PNAccessManagerRevokeToken && type != PNOperationType.ChannelGroupGrantAccess - && type != PNOperationType.PNAccessManagerAudit && type != PNOperationType.ChannelGroupAuditAccess) - { - if (tokenMgr != null && !string.IsNullOrEmpty(tokenMgr.AuthToken) && tokenMgr.AuthToken.Trim().Length > 0) - { - ret.Add("auth", UriUtil.EncodeUriComponent(tokenMgr.AuthToken, type, false, false, false)); - } - else if (pubnubConfig.ContainsKey(pubnubInstanceId) && !string.IsNullOrEmpty(pubnubConfig[pubnubInstanceId].AuthKey) && pubnubConfig[pubnubInstanceId].AuthKey.Trim().Length > 0) - { - ret.Add("auth", UriUtil.EncodeUriComponent(pubnubConfig[pubnubInstanceId].AuthKey, type, false, false, false)); - } - } - } - - return ret; - } - - private string GeneratePAMv2Signature(string queryStringToSign, string partialUrl, PNOperationType opType) - { - string signature = ""; - StringBuilder string_to_sign = new StringBuilder(); - if (pubnubConfig.ContainsKey(pubnubInstanceId)) - { - string_to_sign.Append(pubnubConfig[pubnubInstanceId].SubscribeKey).Append('\n').Append(pubnubConfig[pubnubInstanceId].PublishKey).Append('\n'); - string_to_sign.Append(partialUrl).Append('\n'); - string_to_sign.Append(queryStringToSign); - - signature = Util.PubnubAccessManagerSign(pubnubConfig[pubnubInstanceId].SecretKey, string_to_sign.ToString()); - if (this.pubnubLog != null && this.pubnubConfig != null) - { - LoggingMethod.WriteToLog(pubnubLog, "string_to_sign = " + string_to_sign, pubnubConfig[pubnubInstanceId].LogVerbosity); - LoggingMethod.WriteToLog(pubnubLog, "signature = " + signature, pubnubConfig[pubnubInstanceId].LogVerbosity); - } - else - { - System.Diagnostics.Debug.WriteLine("string_to_sign = " + string_to_sign); - System.Diagnostics.Debug.WriteLine("signature = " + signature); - } - } - return signature; - } - - private string GeneratePAMv3Signature(string method, string requestBody, string queryStringToSign, string partialUrl, PNOperationType opType) - { - string signature = ""; - StringBuilder string_to_sign = new StringBuilder(); - if (pubnubConfig.ContainsKey(pubnubInstanceId)) - { - string_to_sign.AppendFormat(CultureInfo.InvariantCulture, "{0}\n", method.ToUpperInvariant()); - string_to_sign.AppendFormat(CultureInfo.InvariantCulture, "{0}\n", pubnubConfig[pubnubInstanceId].PublishKey); - string_to_sign.AppendFormat(CultureInfo.InvariantCulture, "{0}\n", partialUrl); - string_to_sign.AppendFormat(CultureInfo.InvariantCulture, "{0}\n", queryStringToSign); - string_to_sign.Append(requestBody); - - signature = Util.PubnubAccessManagerSign(pubnubConfig[pubnubInstanceId].SecretKey, string_to_sign.ToString()); - signature = string.Format(CultureInfo.InvariantCulture, "v2.{0}", signature.TrimEnd(new[] { '=' })); - if (this.pubnubLog != null && this.pubnubConfig != null) - { - LoggingMethod.WriteToLog(pubnubLog, "string_to_sign = " + string_to_sign, pubnubConfig[pubnubInstanceId].LogVerbosity); - LoggingMethod.WriteToLog(pubnubLog, "signature = " + signature, pubnubConfig[pubnubInstanceId].LogVerbosity); - } - else - { - System.Diagnostics.Debug.WriteLine("string_to_sign = " + string_to_sign); - System.Diagnostics.Debug.WriteLine("signature = " + signature); - } - } - return signature; - } - - private string BuildQueryString(PNOperationType type, Dictionary queryStringParamDic) - { - string queryString = ""; - - try - { - Dictionary internalQueryStringParamDic = new Dictionary(); - if (queryStringParamDic != null) - { - internalQueryStringParamDic = queryStringParamDic; - } - - string qsUuid = internalQueryStringParamDic.ContainsKey("uuid") ? internalQueryStringParamDic["uuid"] : null; - - Dictionary commonQueryStringParams = GenerateCommonQueryParams(type, qsUuid); - Dictionary queryStringParams = new Dictionary(commonQueryStringParams.Concat(internalQueryStringParamDic).GroupBy(item => item.Key).ToDictionary(item => item.Key, item => item.First().Value)); - - queryString = string.Join("&", queryStringParams.OrderBy(kvp => kvp.Key, StringComparer.Ordinal).Select(kvp => string.Format(CultureInfo.InvariantCulture, "{0}={1}", kvp.Key, kvp.Value)).ToArray()); - - } - catch (Exception ex) - { - LoggingMethod.WriteToLog(pubnubLog, "UrlRequestBuilder => BuildQueryString error " + ex, pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].LogVerbosity : PNLogVerbosity.BODY); - } - - return queryString; - } - - private Uri BuildRestApiRequest(string requestMethod, string requestBody, List urlComponents, PNOperationType type, string queryString, bool isPamV3Sign) - { - StringBuilder url = new StringBuilder(); - - if (pubnubConfig.ContainsKey(pubnubInstanceId) && pubnubConfig[pubnubInstanceId].Secure) - { - url.Append("https://"); - } - else - { - url.Append("http://"); - } - - url.Append(pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].Origin : ""); - - for (int componentIndex = 0; componentIndex < urlComponents.Count; componentIndex++) - { - url.Append('/'); - - if ((type == PNOperationType.PNPublishOperation || type == PNOperationType.PNPublishFileMessageOperation) && componentIndex == urlComponents.Count - 1) - { - url.Append(UriUtil.EncodeUriComponent(urlComponents[componentIndex], type, false, true, false)); - } - else if (type == PNOperationType.PNAccessManagerRevokeToken) - { - url.Append(UriUtil.EncodeUriComponent(urlComponents[componentIndex], type, false, false, false)); - } - else - { - url.Append(UriUtil.EncodeUriComponent(urlComponents[componentIndex], type, true, false, false)); - } - } - - url.Append('?'); - url.Append(queryString); - System.Diagnostics.Debug.WriteLine("sb = " + url); - Uri requestUri = new Uri(url.ToString()); - - if (type == PNOperationType.PNPublishOperation || type == PNOperationType.PNPublishFileMessageOperation || type == PNOperationType.PNSubscribeOperation || type == PNOperationType.Presence) - { - ForceCanonicalPathAndQuery(requestUri); - } - System.Diagnostics.Debug.WriteLine("Uri = " + requestUri.ToString()); - - if (pubnubConfig.ContainsKey(pubnubInstanceId) && pubnubConfig[pubnubInstanceId].SecretKey.Length > 0) - { - StringBuilder partialUrl = new StringBuilder(); - partialUrl.Append(requestUri.AbsolutePath); - - string signature; - if (isPamV3Sign) - { - signature = GeneratePAMv3Signature(requestMethod, requestBody, queryString, partialUrl.ToString(), type); - } - else - { - signature = GeneratePAMv2Signature(queryString, partialUrl.ToString(), type); - } - string queryStringWithSignature = string.Format(CultureInfo.InvariantCulture, "{0}&signature={1}", queryString, signature); - UriBuilder uriBuilder = new UriBuilder(requestUri); - uriBuilder.Query = queryStringWithSignature; - - requestUri = uriBuilder.Uri; - } - - return requestUri; - } - - private string JsonEncodePublishMsg(object originalMessage, PNOperationType opType) - { - string message = jsonLib.SerializeToJsonString(originalMessage); - - if (pubnubConfig.ContainsKey(pubnubInstanceId) && (pubnubConfig[pubnubInstanceId].CryptoModule != null || pubnubConfig[pubnubInstanceId].CipherKey.Length > 0) && opType != PNOperationType.PNSignalOperation) - { - pubnubConfig[pubnubInstanceId].CryptoModule ??= new CryptoModule(new LegacyCryptor(pubnubConfig[pubnubInstanceId].CipherKey, pubnubConfig[pubnubInstanceId].UseRandomInitializationVector, pubnubLog), null); - string encryptMessage = pubnubConfig[pubnubInstanceId].CryptoModule.Encrypt(message); - message = jsonLib.SerializeToJsonString(encryptMessage); - } - - return message; - } - - private void ForceCanonicalPathAndQuery(Uri requestUri) - { -#if !NETSTANDARD10 && !NETSTANDARD11 && !NETSTANDARD12 && !WP81 - LoggingMethod.WriteToLog(pubnubLog, "Inside ForceCanonicalPathAndQuery = " + requestUri.ToString(), pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].LogVerbosity : PNLogVerbosity.NONE); - try - { - FieldInfo flagsFieldInfo = typeof(Uri).GetField("m_Flags", BindingFlags.Instance | BindingFlags.NonPublic); - if (flagsFieldInfo != null) - { - ulong flags = (ulong)flagsFieldInfo.GetValue(requestUri); - flags &= ~((ulong)0x30); // Flags.PathNotCanonical|Flags.QueryNotCanonical - flagsFieldInfo.SetValue(requestUri, flags); - } - } - catch (Exception ex) - { - LoggingMethod.WriteToLog(pubnubLog, "Exception Inside ForceCanonicalPathAndQuery = " + ex, pubnubConfig.ContainsKey(pubnubInstanceId) ? pubnubConfig[pubnubInstanceId].LogVerbosity : PNLogVerbosity.BODY); - } -#endif - } - - public static long TranslateUtcDateTimeToSeconds(DateTime dotNetUTCDateTime) - { - TimeSpan timeSpan = dotNetUTCDateTime - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - long timeStamp = Convert.ToInt64(timeSpan.TotalSeconds); - return timeStamp; - } - - } -} diff --git a/src/Api/PubnubApi/EndPoint/Files/GenerateFileUploadUrlOperation.cs b/src/Api/PubnubApi/EndPoint/Files/GenerateFileUploadUrlOperation.cs index e0d60ec94..ef5d00586 100644 --- a/src/Api/PubnubApi/EndPoint/Files/GenerateFileUploadUrlOperation.cs +++ b/src/Api/PubnubApi/EndPoint/Files/GenerateFileUploadUrlOperation.cs @@ -54,15 +54,15 @@ public void Execute(PNCallback callback) throw new ArgumentException("Missing File Name"); } - GenerateFileUploadUrl(this.queryParam, callback); + GenerateFileUploadUrl(callback); } public async Task> ExecuteAsync() { - return await GenerateFileUploadUrl(this.queryParam).ConfigureAwait(false); + return await GenerateFileUploadUrl(); } - private void GenerateFileUploadUrl(Dictionary externalQueryParam, PNCallback callback) + private void GenerateFileUploadUrl(PNCallback callback) { RequestState requestState = new RequestState(); requestState.ResponseType = PNOperationType.PNGenerateFileUploadUrlOperation; @@ -77,6 +77,7 @@ private void GenerateFileUploadUrl(Dictionary externalQueryParam var transportResponse = t.Result; if (transportResponse.Error == null) { var responseString = Encoding.UTF8.GetString(transportResponse.Content); + requestState.GotJsonResponse = true; if (!string.IsNullOrEmpty(responseString)) { List result = ProcessJsonResponse(requestState, responseString); ProcessResponseCallbacks(result, requestState); @@ -93,7 +94,7 @@ private void GenerateFileUploadUrl(Dictionary externalQueryParam }); } - private async Task> GenerateFileUploadUrl(Dictionary externalQueryParam) + private async Task> GenerateFileUploadUrl() { PNResult returnValue = new PNResult(); if (string.IsNullOrEmpty(sendFileName)) { @@ -110,20 +111,21 @@ private async Task> GenerateFileUploadUr requestState.EndPointOperation = this; var requestParameter = CreateRequestParameter(); - Tuple JsonAndStatusTuple; var transportRequest = PubnubInstance.transportMiddleware.PreapareTransportRequest(requestParameter: requestParameter, operationType: PNOperationType.PNGenerateFileUploadUrlOperation); var transportResponse = await PubnubInstance.transportMiddleware.Send(transportRequest: transportRequest); if (transportResponse.Error == null) { var responseString = Encoding.UTF8.GetString(transportResponse.Content); PNStatus errorStatus = GetStatusIfError(requestState, responseString); + Tuple jsonAndStatusTuple; if (errorStatus == null) { + requestState.GotJsonResponse = true; PNStatus status = new StatusBuilder(config, jsonLibrary).CreateStatusResponse(requestState.ResponseType, PNStatusCategory.PNAcknowledgmentCategory, requestState, transportResponse.StatusCode, null); - JsonAndStatusTuple = new Tuple(responseString, status); + jsonAndStatusTuple = new Tuple(responseString, status); } else { - JsonAndStatusTuple = new Tuple(string.Empty, errorStatus); + jsonAndStatusTuple = new Tuple(string.Empty, errorStatus); } - returnValue.Status = JsonAndStatusTuple.Item2; - string json = JsonAndStatusTuple.Item1; + returnValue.Status = jsonAndStatusTuple.Item2; + string json = jsonAndStatusTuple.Item1; if (!string.IsNullOrEmpty(json)) { List resultList = ProcessJsonResponse(requestState, json); ResponseBuilder responseBuilder = new ResponseBuilder(config, jsonLibrary, pubnubLog); @@ -162,7 +164,6 @@ private RequestParameter CreateRequestParameter() } } } - Dictionary messageEnvelope = new Dictionary(); if (!string.IsNullOrEmpty(sendFileName)) { messageEnvelope.Add("name", sendFileName); diff --git a/src/Api/PubnubApi/EventEngine/Common/EventEmitter.cs b/src/Api/PubnubApi/EventEngine/Common/EventEmitter.cs index 3f142def4..a6bccc71b 100644 --- a/src/Api/PubnubApi/EventEngine/Common/EventEmitter.cs +++ b/src/Api/PubnubApi/EventEngine/Common/EventEmitter.cs @@ -252,10 +252,8 @@ public void EmitEvent(object e) 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() }; - - IUrlRequestBuilder urlBuilder = new UrlRequestBuilder(configuration, jsonLibrary, null, log, tokenManager, (instance != null) ? instance.InstanceId : ""); - Uri fileUrlRequest = urlBuilder.BuildGetFileUrlOrDeleteReqest("GET", "", fileMessage.Channel, fileMessage.File.Id, fileMessage.File.Name, null, PNOperationType.PNGenerateFileUploadUrlOperation); - fileMessage.File.Url = fileUrlRequest.ToString(); + fileMessage.File.Url = UriUtil.GetFileUrl(fileName: fileMessage.File.Name, fileId: fileMessage.File.Id, channel:fileMessage.Channel, + pnConfiguration:configuration, pubnub:instance, tokenmanager:tokenManager); } } } else { diff --git a/src/Api/PubnubApi/PubnubCoreBase.cs b/src/Api/PubnubApi/PubnubCoreBase.cs index d37148785..6b44294ec 100644 --- a/src/Api/PubnubApi/PubnubCoreBase.cs +++ b/src/Api/PubnubApi/PubnubCoreBase.cs @@ -761,9 +761,10 @@ private void ResponseToUserCallback(List result, PNOperationType type if (fileObjDic != null && fileObjDic.ContainsKey("id") && fileObjDic.ContainsKey("name")) { fileMessage.File = new PNFile { Id = fileObjDic["id"].ToString(), Name = fileObjDic["name"].ToString() }; - IUrlRequestBuilder urlBuilder = new UrlRequestBuilder(currentConfig, jsonLib, unitTest, currentLog, (PubnubInstance != null && !string.IsNullOrEmpty(PubnubInstance.InstanceId) && PubnubTokenMgrCollection.ContainsKey(PubnubInstance.InstanceId)) ? PubnubTokenMgrCollection[PubnubInstance.InstanceId] : null, (PubnubInstance != null) ? PubnubInstance.InstanceId : ""); - Uri fileUrlRequest = urlBuilder.BuildGetFileUrlOrDeleteReqest("GET", "", fileMessage.Channel, fileMessage.File.Id, fileMessage.File.Name, null, type); - fileMessage.File.Url = fileUrlRequest.ToString(); + PubnubTokenMgrCollection.TryGetValue( + PubnubInstance.InstanceId ?? "", out var tokenManager); + fileMessage.File.Url = UriUtil.GetFileUrl(fileName: fileMessage.File.Name, fileId: fileMessage.File.Id, channel:fileMessage.Channel, + pnConfiguration:currentConfig, pubnub:PubnubInstance, tokenmanager: tokenManager); } } } @@ -967,341 +968,6 @@ protected string[] GetCurrentSubscriberChannelGroups() } #endregion -#region "Build, process and send request" - internal protected async Task> UrlProcessRequest(Uri requestUri, RequestState pubnubRequestState, bool terminateCurrentSubRequest) - { - return await UrlProcessRequest(requestUri, pubnubRequestState, terminateCurrentSubRequest, null).ConfigureAwait(false); - } - -#pragma warning disable - internal protected async Task> UrlProcessRequest(Uri requestUri, RequestState pubnubRequestState, bool terminateCurrentSubRequest, byte[] postOrPatchData) -#pragma warning restore - { - return await UrlProcessRequest(requestUri, pubnubRequestState, terminateCurrentSubRequest, postOrPatchData,"").ConfigureAwait(false); - } - - internal protected async Task> UrlProcessRequest(Uri requestUri, RequestState pubnubRequestState, bool terminateCurrentSubRequest, byte[] postOrPatchData, string contentType) - { - string channel = ""; - PNConfiguration currentConfig; - IPubnubLog currentLog; - - try - { - if (terminateCurrentSubRequest) - { - TerminateCurrentSubscriberRequest(); - } - - if (PubnubInstance == null) - { - System.Diagnostics.Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "DateTime {0}, PubnubInstance is null. Exiting UrlProcessRequest", DateTime.Now.ToString(CultureInfo.InvariantCulture))); - return new Tuple("", null); - } - - if (pubnubRequestState != null) - { - channel = (pubnubRequestState.Channels != null && pubnubRequestState.Channels.Length > 0) ? string.Join(",", pubnubRequestState.Channels.OrderBy(x => x).ToArray()) : ","; - - if (ChannelRequest.ContainsKey(PubnubInstance.InstanceId) && !channel.Equals(",", StringComparison.OrdinalIgnoreCase) && !ChannelRequest[PubnubInstance.InstanceId].ContainsKey(channel) && (pubnubRequestState.ResponseType == PNOperationType.PNSubscribeOperation || pubnubRequestState.ResponseType == PNOperationType.Presence)) - { - if (pubnubConfig.TryGetValue(PubnubInstance.InstanceId, out currentConfig) && pubnubLog.TryGetValue(PubnubInstance.InstanceId, out currentLog)) - { - LoggingMethod.WriteToLog(currentLog, string.Format(CultureInfo.InvariantCulture, "DateTime {0}, UrlProcessRequest ChannelRequest PubnubInstance.InstanceId Channel NOT matching", DateTime.Now.ToString(CultureInfo.InvariantCulture)), currentConfig.LogVerbosity); - } - return new Tuple("", null); - } - } - -#if !NET35 && !NET40 && !NET45 && !NET461 && !NET48 && !NETSTANDARD10 - //do nothing -#else - // Create Request - HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri); - request = pubnubHttp.SetServicePointConnectionLimit(pubnubRequestState, request); - request = pubnubHttp.SetNoCache(request); - request = pubnubHttp.SetProxy(request); - request = pubnubHttp.SetTimeout(pubnubRequestState, request); - request = pubnubHttp.SetServicePointSetTcpKeepAlive(pubnubRequestState, request); - request = pubnubHttp.SetTcpKeepAlive(request); - if (string.IsNullOrEmpty(contentType)) - { - contentType = "application/json"; - } - request.ContentType = contentType; - - pubnubRequestState.Request = request; - - if (pubnubRequestState.ResponseType == PNOperationType.PNSubscribeOperation || pubnubRequestState.ResponseType == PNOperationType.Presence) - { - ChannelRequest[PubnubInstance.InstanceId].AddOrUpdate(channel, pubnubRequestState.Request, (key, oldState) => pubnubRequestState.Request); - } -#endif - - if (pubnubConfig.TryGetValue(PubnubInstance.InstanceId, out currentConfig) && pubnubLog.TryGetValue(PubnubInstance.InstanceId, out currentLog)) - { - LoggingMethod.WriteToLog(currentLog, string.Format(CultureInfo.InvariantCulture, "DateTime {0}, Request={1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), requestUri.ToString()), currentConfig.LogVerbosity); - } - - if (pubnubRequestState != null && pubnubRequestState.ResponseType == PNOperationType.PNSubscribeOperation) - { - SubscribeRequestTracker.AddOrUpdate(PubnubInstance.InstanceId, DateTime.Now, (key, oldState) => DateTime.Now); - } - - string jsonString = ""; -#if !NET35 && !NET40 && !NET45 && !NET461 && !NET48 && !NETSTANDARD10 - if (pubnubRequestState != null && pubnubRequestState.UsePostMethod) - { - jsonString = await pubnubHttp.SendRequestAndGetJsonResponseWithPOST(requestUri, pubnubRequestState, null, postOrPatchData, contentType).ConfigureAwait(false); - } - else if (pubnubRequestState != null && pubnubRequestState.UsePatchMethod) - { - jsonString = await pubnubHttp.SendRequestAndGetJsonResponseWithPATCH(requestUri, pubnubRequestState, null, postOrPatchData, contentType).ConfigureAwait(false); - } - else - { - jsonString = await pubnubHttp.SendRequestAndGetJsonResponse(requestUri, pubnubRequestState, null).ConfigureAwait(false); - } -#else - if (pubnubRequestState != null && pubnubRequestState.UsePostMethod) - { - jsonString = await pubnubHttp.SendRequestAndGetJsonResponseWithPOST(requestUri, pubnubRequestState, request, postOrPatchData, contentType).ConfigureAwait(false); - } - else if (pubnubRequestState != null && pubnubRequestState.UsePatchMethod) - { - jsonString = await pubnubHttp.SendRequestAndGetJsonResponseWithPATCH(requestUri, pubnubRequestState, request, postOrPatchData, contentType).ConfigureAwait(false); - } - else - { - jsonString = await pubnubHttp.SendRequestAndGetJsonResponse(requestUri, pubnubRequestState, request).ConfigureAwait(false); - } -#endif - - if (SubscribeDisconnected.ContainsKey(PubnubInstance.InstanceId) && SubscribeDisconnected[PubnubInstance.InstanceId]) - { - if (pubnubConfig.TryGetValue(PubnubInstance.InstanceId, out currentConfig) && pubnubLog.TryGetValue(PubnubInstance.InstanceId, out currentLog)) - { - LoggingMethod.WriteToLog(currentLog, string.Format(CultureInfo.InvariantCulture, "DateTime {0},Received JSON but SubscribeDisconnected = {1} for request={2}", DateTime.Now.ToString(CultureInfo.InvariantCulture), jsonString, requestUri), currentConfig.LogVerbosity); - } - throw new OperationCanceledException("Disconnected"); - } - - if (pubnubConfig.TryGetValue(PubnubInstance.InstanceId, out currentConfig) && pubnubLog.TryGetValue(PubnubInstance.InstanceId, out currentLog)) - { - LoggingMethod.WriteToLog(currentLog, string.Format(CultureInfo.InvariantCulture, "DateTime {0}, JSON= {1} for request={2}", DateTime.Now.ToString(CultureInfo.InvariantCulture), jsonString, requestUri), currentConfig.LogVerbosity); - } - PNStatus errStatus = GetStatusIfError(pubnubRequestState, jsonString); - if (errStatus == null && pubnubRequestState != null) - { - PNStatus status = new StatusBuilder(currentConfig, jsonLib).CreateStatusResponse(pubnubRequestState.ResponseType, PNStatusCategory.PNAcknowledgmentCategory, pubnubRequestState, (int)HttpStatusCode.OK, null); - return new Tuple(jsonString, status); - } - else - { - jsonString = ""; - return new Tuple(jsonString, errStatus); - } - } - catch (Exception ex) - { - string errorMessage = ex.Message; - string exceptionMessage = ""; - Exception innerEx = null; - WebException webEx = null; - PNStatus status = null; - - if (ex.InnerException != null) - { - if (ex is WebException) - { - webEx = ex as WebException; - exceptionMessage = webEx.ToString(); - } - else - { - innerEx = ex.InnerException; - exceptionMessage = innerEx.ToString(); - } - } - else - { - innerEx = ex; - exceptionMessage = innerEx.ToString(); - } - - if (exceptionMessage.IndexOf("The request was aborted: The request was canceled", StringComparison.CurrentCultureIgnoreCase) == -1 - && exceptionMessage.IndexOf("Machine suspend mode enabled. No request will be processed.", StringComparison.CurrentCultureIgnoreCase) == -1 - && (pubnubRequestState.ResponseType == PNOperationType.PNSubscribeOperation && exceptionMessage.IndexOf("The operation has timed out", StringComparison.CurrentCultureIgnoreCase) == -1) - && exceptionMessage.IndexOf("A task was canceled", StringComparison.CurrentCultureIgnoreCase) == -1 - && errorMessage.IndexOf("The operation was canceled", StringComparison.CurrentCultureIgnoreCase) == -1) - { - PNStatusCategory category = PNStatusCategoryHelper.GetPNStatusCategory(webEx == null ? innerEx : webEx); - if (PubnubInstance != null && pubnubConfig.TryGetValue(PubnubInstance.InstanceId, out currentConfig)) - { - status = new StatusBuilder(currentConfig, jsonLib).CreateStatusResponse(pubnubRequestState.ResponseType, category, pubnubRequestState, (int)HttpStatusCode.NotFound, new PNException(ex)); - if (pubnubRequestState != null && pubnubRequestState.PubnubCallback != null) - { - pubnubRequestState.PubnubCallback.OnResponse(default(T), status); - } - else - { - Announce(status); - } - } - - if (PubnubInstance != null && pubnubConfig.TryGetValue(PubnubInstance.InstanceId, out currentConfig) && pubnubLog.TryGetValue(PubnubInstance.InstanceId, out currentLog)) - { - LoggingMethod.WriteToLog(currentLog, string.Format(CultureInfo.InvariantCulture, "DateTime {0} PubnubBaseCore UrlProcessRequest Exception={1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), webEx != null ? webEx.ToString() : exceptionMessage), currentConfig.LogVerbosity); - } - } - - return new Tuple("", status); - } - } - - internal protected async Task> UrlProcessRequestForStream(Uri requestUri, RequestState pubnubRequestState, bool terminateCurrentSubRequest, string contentType) - { - string channel = ""; - PNConfiguration currentConfig; - IPubnubLog currentLog; - - try - { - if (terminateCurrentSubRequest) - { - TerminateCurrentSubscriberRequest(); - } - - if (PubnubInstance == null) - { - System.Diagnostics.Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "DateTime {0}, PubnubInstance is null. Exiting UrlProcessRequest", DateTime.Now.ToString(CultureInfo.InvariantCulture))); - return new Tuple(null, null); - } - - if (pubnubRequestState != null) - { - channel = (pubnubRequestState.Channels != null && pubnubRequestState.Channels.Length > 0) ? string.Join(",", pubnubRequestState.Channels.OrderBy(x => x).ToArray()) : ","; - - if (ChannelRequest.ContainsKey(PubnubInstance.InstanceId) && !channel.Equals(",", StringComparison.OrdinalIgnoreCase) && !ChannelRequest[PubnubInstance.InstanceId].ContainsKey(channel) && (pubnubRequestState.ResponseType == PNOperationType.PNSubscribeOperation || pubnubRequestState.ResponseType == PNOperationType.Presence)) - { - if (pubnubConfig.TryGetValue(PubnubInstance.InstanceId, out currentConfig) && pubnubLog.TryGetValue(PubnubInstance.InstanceId, out currentLog)) - { - LoggingMethod.WriteToLog(currentLog, string.Format(CultureInfo.InvariantCulture, "DateTime {0}, UrlProcessRequest ChannelRequest PubnubInstance.InstanceId Channel NOT matching", DateTime.Now.ToString(CultureInfo.InvariantCulture)), currentConfig.LogVerbosity); - } - return new Tuple(null, null); - } - } - -#if !NET35 && !NET40 && !NET45 && !NET461 && !NET48 && !NETSTANDARD10 - //do nothing -#else - // Create Request - HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri); - - request = pubnubHttp.SetNoCache(request); - request = pubnubHttp.SetProxy(request); - request = pubnubHttp.SetTimeout(pubnubRequestState, request); - if (string.IsNullOrEmpty(contentType)) - { - contentType = "application/json"; - } - request.ContentType = contentType; - - pubnubRequestState.Request = request; - - if (pubnubRequestState.ResponseType == PNOperationType.PNSubscribeOperation || pubnubRequestState.ResponseType == PNOperationType.Presence) - { - ChannelRequest[PubnubInstance.InstanceId].AddOrUpdate(channel, pubnubRequestState.Request, (key, oldState) => pubnubRequestState.Request); - } -#endif - - if (pubnubConfig.TryGetValue(PubnubInstance.InstanceId, out currentConfig) && pubnubLog.TryGetValue(PubnubInstance.InstanceId, out currentLog)) - { - LoggingMethod.WriteToLog(currentLog, string.Format(CultureInfo.InvariantCulture, "DateTime {0}, Request={1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), requestUri.ToString()), currentConfig.LogVerbosity); - } - - if (pubnubRequestState != null && pubnubRequestState.ResponseType == PNOperationType.PNSubscribeOperation) - { - SubscribeRequestTracker.AddOrUpdate(PubnubInstance.InstanceId, DateTime.Now, (key, oldState) => DateTime.Now); - } - - byte[] streamBytes; -#if !NET35 && !NET40 && !NET45 && !NET461 && !NET48 && !NETSTANDARD10 - streamBytes = await pubnubHttp.SendRequestAndGetStreamResponse(requestUri, pubnubRequestState, null).ConfigureAwait(false); -#else - streamBytes = await pubnubHttp.SendRequestAndGetStreamResponse(requestUri, pubnubRequestState, request).ConfigureAwait(false); -#endif - if (streamBytes != null && pubnubConfig.TryGetValue(PubnubInstance.InstanceId, out currentConfig) && pubnubLog.TryGetValue(PubnubInstance.InstanceId, out currentLog)) - { - LoggingMethod.WriteToLog(currentLog, string.Format(CultureInfo.InvariantCulture, "DateTime {0}, Stream length= {1} for request={2}", DateTime.Now.ToString(CultureInfo.InvariantCulture), streamBytes.Length, requestUri), currentConfig.LogVerbosity); - } - PNStatus errStatus = GetStatusIfError(pubnubRequestState, null); - if (errStatus == null && pubnubRequestState != null) - { - PNStatus status = new StatusBuilder(currentConfig, jsonLib).CreateStatusResponse(pubnubRequestState.ResponseType, PNStatusCategory.PNAcknowledgmentCategory, pubnubRequestState, (int)HttpStatusCode.OK, null); - return new Tuple(streamBytes, status); - } - else - { - return new Tuple(null, errStatus); - } - } - catch (Exception ex) - { - string errorMessage = ex.Message; - string exceptionMessage = ""; - Exception innerEx = null; - WebException webEx = null; - PNStatus status = null; - - if (ex.InnerException != null) - { - if (ex is WebException) - { - webEx = ex as WebException; - exceptionMessage = webEx.ToString(); - } - else - { - innerEx = ex.InnerException; - exceptionMessage = innerEx.ToString(); - } - } - else - { - innerEx = ex; - exceptionMessage = innerEx.ToString(); - } - - if (exceptionMessage.IndexOf("The request was aborted: The request was canceled", StringComparison.CurrentCultureIgnoreCase) == -1 - && exceptionMessage.IndexOf("Machine suspend mode enabled. No request will be processed.", StringComparison.CurrentCultureIgnoreCase) == -1 - && (pubnubRequestState.ResponseType == PNOperationType.PNSubscribeOperation && exceptionMessage.IndexOf("The operation has timed out", StringComparison.CurrentCultureIgnoreCase) == -1) - && exceptionMessage.IndexOf("A task was canceled", StringComparison.CurrentCultureIgnoreCase) == -1 - && errorMessage.IndexOf("The operation was canceled", StringComparison.CurrentCultureIgnoreCase) == -1) - { - PNStatusCategory category = PNStatusCategoryHelper.GetPNStatusCategory(webEx == null ? innerEx : webEx); - if (PubnubInstance != null && pubnubConfig.TryGetValue(PubnubInstance.InstanceId, out currentConfig)) - { - status = new StatusBuilder(currentConfig, jsonLib).CreateStatusResponse(pubnubRequestState.ResponseType, category, pubnubRequestState, (int)HttpStatusCode.NotFound, new PNException(ex)); - if (pubnubRequestState != null && pubnubRequestState.PubnubCallback != null) - { - pubnubRequestState.PubnubCallback.OnResponse(default(T), status); - } - else - { - Announce(status); - } - } - - if (PubnubInstance != null && pubnubConfig.TryGetValue(PubnubInstance.InstanceId, out currentConfig) && pubnubLog.TryGetValue(PubnubInstance.InstanceId, out currentLog)) - { - LoggingMethod.WriteToLog(currentLog, string.Format(CultureInfo.InvariantCulture, "DateTime {0} PubnubBaseCore UrlProcessRequest Exception={1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), webEx != null ? webEx.ToString() : exceptionMessage), currentConfig.LogVerbosity); - } - } - - return new Tuple(null, status); - } - } internal protected List ProcessJsonResponse(RequestState asyncRequestState, string jsonString) { List result = new List(); @@ -1670,8 +1336,6 @@ protected void ProcessResponseCallbacks(List result, RequestState } } -#endregion - protected string BuildJsonUserState(string channel, string channelGroup, bool local) { Dictionary channelUserStateDictionary = null; diff --git a/src/Api/PubnubApi/Transport/HttpClientService.cs b/src/Api/PubnubApi/Transport/HttpClientService.cs index 1291658c2..fb707b60d 100644 --- a/src/Api/PubnubApi/Transport/HttpClientService.cs +++ b/src/Api/PubnubApi/Transport/HttpClientService.cs @@ -57,9 +57,6 @@ public async Task PostRequest(TransportRequest transportReque { postData.Headers.Add(transportRequestHeader.Key, transportRequestHeader.Value); } - // if (transportRequest.Headers.TryGetValue("Content-Type", out var header)) - // if (!string.IsNullOrEmpty(header)) - // postData.Headers.Add("Content-Type", header); } HttpRequestMessage requestMessage = new HttpRequestMessage(method: HttpMethod.Post, requestUri: transportRequest.RequestUrl) { Content = postData }; var httpResult = await _httpClient.SendAsync(request: requestMessage, cancellationToken: transportRequest.CancellationToken); @@ -82,30 +79,54 @@ public async Task PostRequest(TransportRequest transportReque public async Task PutRequest(TransportRequest transportRequest) { - if (transportRequest.Timeout.HasValue) _httpClient.Timeout = (TimeSpan)transportRequest.Timeout; - HttpContent postData = null; - - if (!string.IsNullOrEmpty(transportRequest.BodyContentString)) { - postData = new StringContent(transportRequest.BodyContentString, Encoding.UTF8, "application/json"); - } else if (transportRequest.BodyContentBytes != null) { - postData = new ByteArrayContent(transportRequest.FormData); - postData.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream"); - } - HttpRequestMessage requestMessage = new HttpRequestMessage(method: HttpMethod.Put, requestUri: transportRequest.RequestUrl) { Content = postData }; - if (transportRequest.Headers.Keys.Count > 0) { - foreach (var kvp in transportRequest.Headers) { - requestMessage.Headers.Add(kvp.Key, kvp.Value); + TransportResponse transportResponse; + try + { + HttpContent putData = null; + + if (!string.IsNullOrEmpty(transportRequest.BodyContentString)) + { + putData = new StringContent(transportRequest.BodyContentString, Encoding.UTF8, "application/json"); } + else if (transportRequest.BodyContentBytes != null) + { + putData = new ByteArrayContent(transportRequest.FormData); + foreach (var transportRequestHeader in transportRequest.Headers) + { + putData.Headers.Add(transportRequestHeader.Key, transportRequestHeader.Value); + } + } + + HttpRequestMessage requestMessage = + new HttpRequestMessage(method: HttpMethod.Put, requestUri: transportRequest.RequestUrl) + { Content = putData }; + if (transportRequest.Headers.Keys.Count > 0) + { + foreach (var kvp in transportRequest.Headers) + { + requestMessage.Headers.Add(kvp.Key, kvp.Value); + } + } + + var httpResult = await _httpClient.SendAsync(request: requestMessage, + cancellationToken: transportRequest.CancellationToken); + var responseContent = await httpResult.Content.ReadAsByteArrayAsync(); + transportResponse = new TransportResponse() + { + StatusCode = (int)httpResult.StatusCode, + Content = responseContent, + Headers = httpResult.Headers.ToDictionary(h => h.Key, h => h.Value), + RequestUrl = httpResult.RequestMessage?.RequestUri?.AbsolutePath + }; } - var httpResult = await _httpClient.SendAsync(request: requestMessage, cancellationToken: transportRequest.CancellationToken); - var responseContent = await httpResult.Content.ReadAsByteArrayAsync(); - var response = new TransportResponse() { - StatusCode = (int)httpResult.StatusCode, - Content = responseContent, - Headers = httpResult.Headers.ToDictionary(h => h.Key, h => h.Value), - RequestUrl = httpResult.RequestMessage?.RequestUri?.AbsolutePath - }; - return response; + catch (Exception e) + { + transportResponse = new TransportResponse() { + RequestUrl = transportRequest.RequestUrl, + Error = e + }; + } + return transportResponse; } public async Task DeleteRequest(TransportRequest transportRequest) @@ -138,30 +159,56 @@ public async Task DeleteRequest(TransportRequest transportReq public async Task PatchRequest(TransportRequest transportRequest) { - if (transportRequest.Timeout.HasValue) _httpClient.Timeout = (TimeSpan)transportRequest.Timeout; - HttpContent patchData = null; - - if (!string.IsNullOrEmpty(transportRequest.BodyContentString)) { - patchData = new StringContent(transportRequest.BodyContentString, Encoding.UTF8, "application/json"); - } else if (transportRequest.BodyContentBytes != null) { - patchData = new ByteArrayContent(transportRequest.FormData); - patchData.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream"); - } - HttpRequestMessage requestMessage = new HttpRequestMessage(new HttpMethod("PATCH"), requestUri: transportRequest.RequestUrl) { Content = patchData }; - if (transportRequest.Headers.Keys.Count > 0) { - foreach (var kvp in transportRequest.Headers) { - requestMessage.Headers.Add(kvp.Key, kvp.Value); + TransportResponse transportResponse; + try + { + HttpContent patchData = null; + + if (!string.IsNullOrEmpty(transportRequest.BodyContentString)) + { + patchData = new StringContent(transportRequest.BodyContentString, Encoding.UTF8, + "application/json"); + } + else if (transportRequest.BodyContentBytes != null) + { + patchData = new ByteArrayContent(transportRequest.FormData); + foreach (var transportRequestHeader in transportRequest.Headers) + { + patchData.Headers.Add(transportRequestHeader.Key, transportRequestHeader.Value); + } + } + + HttpRequestMessage requestMessage = + new HttpRequestMessage(new HttpMethod("PATCH"), requestUri: transportRequest.RequestUrl) + { Content = patchData }; + if (transportRequest.Headers.Keys.Count > 0) + { + foreach (var kvp in transportRequest.Headers) + { + requestMessage.Headers.Add(kvp.Key, kvp.Value); + } } + + var httpResult = await _httpClient.SendAsync(request: requestMessage, + cancellationToken: transportRequest.CancellationToken); + var responseContent = await httpResult.Content.ReadAsByteArrayAsync(); + transportResponse = new TransportResponse() + { + StatusCode = (int)httpResult.StatusCode, + Content = responseContent, + Headers = httpResult.Headers.ToDictionary(h => h.Key, h => h.Value), + RequestUrl = httpResult.RequestMessage?.RequestUri?.AbsolutePath + }; } - var httpResult = await _httpClient.SendAsync(request: requestMessage, cancellationToken: transportRequest.CancellationToken); - var responseContent = await httpResult.Content.ReadAsByteArrayAsync(); - var response = new TransportResponse() { - StatusCode = (int)httpResult.StatusCode, - Content = responseContent, - Headers = httpResult.Headers.ToDictionary(h => h.Key, h => h.Value), - RequestUrl = httpResult.RequestMessage?.RequestUri?.AbsolutePath - }; - return response; + catch (Exception e) + { + transportResponse = new TransportResponse() { + RequestUrl = transportRequest.RequestUrl, + Error = e + }; + } + + return transportResponse; } } } diff --git a/src/Api/PubnubApiPCL/PubnubApiPCL.csproj b/src/Api/PubnubApiPCL/PubnubApiPCL.csproj index 456f7d420..c207f42cc 100644 --- a/src/Api/PubnubApiPCL/PubnubApiPCL.csproj +++ b/src/Api/PubnubApiPCL/PubnubApiPCL.csproj @@ -56,9 +56,6 @@ Builder\UriUtil.cs - - Builder\UrlRequestBuilder.cs - Builder\UrlParameterConverter.cs diff --git a/src/Api/PubnubApiUWP/PubnubApiUWP.csproj b/src/Api/PubnubApiUWP/PubnubApiUWP.csproj index 172da5dd3..cadc52467 100644 --- a/src/Api/PubnubApiUWP/PubnubApiUWP.csproj +++ b/src/Api/PubnubApiUWP/PubnubApiUWP.csproj @@ -165,9 +165,6 @@ Builder\UriUtil.cs - - Builder\UrlRequestBuilder.cs - Builder\UrlParameterConverter.cs diff --git a/src/Api/PubnubApiUnity/PubnubApiUnity.csproj b/src/Api/PubnubApiUnity/PubnubApiUnity.csproj index 969c6f6a0..7997afcf7 100644 --- a/src/Api/PubnubApiUnity/PubnubApiUnity.csproj +++ b/src/Api/PubnubApiUnity/PubnubApiUnity.csproj @@ -2,7 +2,7 @@ net6.0;netstandard1.3;netstandard1.4;netstandard2.0 - 9.0 + default true True pubnub.snk @@ -56,9 +56,6 @@ Builder\UriUtil.cs - - Builder\UrlRequestBuilder.cs - Builder\UrlParameterConverter.cs