Exemplo n.º 1
0
        private static bool IsOperationTypeForPercent2fEncode(PNOperationType type)
        {
            bool ret;

            switch (type)
            {
            case PNOperationType.PNHereNowOperation:
            case PNOperationType.PNHistoryOperation:
            case PNOperationType.PNFetchHistoryOperation:
            case PNOperationType.Leave:
            case PNOperationType.PNHeartbeatOperation:
            case PNOperationType.PushRegister:
            case PNOperationType.PushRemove:
            case PNOperationType.PushGet:
            case PNOperationType.PushUnregister:
                ret = true;
                break;

            default:
                ret = false;
                break;
            }

            return(ret);
        }
Exemplo n.º 2
0
        internal bool CheckInternetStatus <T>(bool systemActive, PNOperationType type, PNCallback <T> callback, string[] channels, string[] channelGroups)
        {
            if (unit != null)
            {
                return(unit.InternetAvailable);
            }
            else
            {
                Task[] tasks = new Task[1];

                tasks[0] = Task.Factory.StartNew(async() => await CheckClientNetworkAvailability(CallbackClientNetworkStatus, type, callback, channels, channelGroups).ConfigureAwait(false));
                tasks[0].ConfigureAwait(false);
                try
                {
                    Task.WaitAll(tasks);
                }
                catch (AggregateException ae) {
                    foreach (var ie in ae.InnerExceptions)
                    {
                        LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} AggregateException CheckInternetStatus Error: {1} {2} ", DateTime.Now.ToString(CultureInfo.InvariantCulture), ie.GetType().Name, ie.Message), pubnubConfig.LogVerbosity);
                    }
                }

                return(networkStatus);
            }
        }
Exemplo n.º 3
0
        private Dictionary <string, string> GenerateCommonQueryParams(PNOperationType type)
        {
            long   timeStamp = TranslateUtcDateTimeToSeconds(DateTime.UtcNow);
            string requestid = Guid.NewGuid().ToString();

            if (pubnubUnitTest != null)
            {
                timeStamp = pubnubUnitTest.Timetoken;
                requestid = string.IsNullOrEmpty(pubnubUnitTest.RequestId) ? "" : pubnubUnitTest.RequestId;
            }

            Dictionary <string, string> ret = new Dictionary <string, string>();

            ret.Add("uuid", this.pubnubConfig.Uuid);
            ret.Add("pnsdk", new UriUtil().EncodeUriComponent(Pubnub.Version, PNOperationType.PNSubscribeOperation, false, true));
            ret.Add("requestid", requestid);
            if (!string.IsNullOrEmpty(pubnubConfig.SecretKey))
            {
                ret.Add("timestamp", timeStamp.ToString());
            }

            if (type != PNOperationType.PNTimeOperation &&
                type != PNOperationType.PNAccessManagerGrant && type != PNOperationType.ChannelGroupGrantAccess &&
                type != PNOperationType.PNAccessManagerAudit && type != PNOperationType.ChannelGroupAuditAccess)
            {
                if (!string.IsNullOrEmpty(this.pubnubConfig.AuthKey))
                {
                    ret.Add("auth", new UriUtil().EncodeUriComponent(this.pubnubConfig.AuthKey, type, false, false));
                }
            }

            return(ret);
        }
Exemplo n.º 4
0
        Uri IUrlRequestBuilder.BuildGetUserStateRequest(string channelsCommaDelimited, string channelGroupsCommaDelimited, string uuid)
        {
            PNOperationType currentType = PNOperationType.PNGetStateOperation;

            if (string.IsNullOrEmpty(channelsCommaDelimited) && channelsCommaDelimited.Trim().Length <= 0)
            {
                channelsCommaDelimited = ",";
            }

            List <string> url = new List <string>();

            url.Add("v2");
            url.Add("presence");
            url.Add("sub_key");
            url.Add(pubnubConfig.SubscribeKey);
            url.Add("channel");
            url.Add(channelsCommaDelimited);
            url.Add("uuid");
            url.Add(uuid);

            Dictionary <string, string> requestQueryStringParams = new Dictionary <string, string>();

            if (!string.IsNullOrEmpty(channelGroupsCommaDelimited) && channelGroupsCommaDelimited.Trim().Length > 0)
            {
                requestQueryStringParams.Add("channel-group", new UriUtil().EncodeUriComponent(channelGroupsCommaDelimited, currentType, false, false));
            }

            string queryString = BuildQueryString(currentType, url, requestQueryStringParams);
            string queryParams = string.Format("?{0}", queryString);

            return(BuildRestApiRequest <Uri>(url, currentType, queryParams));
        }
Exemplo n.º 5
0
        public static object DecodeMessage(string cipherKey, object element, PNOperationType pnOperationType, PubNubUnity pnUnity)
        {
            PubnubCrypto aes            = new PubnubCrypto(cipherKey, pnUnity.PNLog);
            string       decryptMessage = "";

            try {
                decryptMessage = aes.Decrypt(element.ToString());
            }
            catch (Exception ex) {
                decryptMessage = "**DECRYPT ERROR**";
                PNStatus pnStatus = CreatePNStatus(
                    PNStatusCategory.PNDecryptionErrorCategory,
                    string.Format("{0}, {1}", decryptMessage, element.ToString()),
                    ex,
                    true,
                    PNOperationType.PNSubscribeOperation,
                    pnUnity.SubscriptionInstance.AllChannels,
                    pnUnity.SubscriptionInstance.AllChannelGroups,
                    null,
                    pnUnity
                    );
                pnUnity.SubWorker.CreateEventArgsAndRaiseEvent(pnStatus);
            }
            object decodeMessage = (decryptMessage == "**DECRYPT ERROR**") ? decryptMessage : pnUnity.JsonLibrary.DeserializeToObject(decryptMessage);

            return(decodeMessage);
        }
Exemplo n.º 6
0
        internal bool RemoveDuplicatesCheckAlreadySubscribedAndGetChannelsCommon(PNOperationType type, List <string> channelsOrChannelGroups, bool isChannelGroup, bool unsubscribeCheck, ref List <ChannelEntity> channelEntities)
        {
            bool bReturn = false;

            if (channelsOrChannelGroups.Count > 0)
            {
                channelsOrChannelGroups = channelsOrChannelGroups.Where(x => !string.IsNullOrEmpty(x)).ToList();

                if (channelsOrChannelGroups.Count != channelsOrChannelGroups.Distinct().Count())
                {
                    channelsOrChannelGroups = channelsOrChannelGroups.Distinct().ToList();
                    #if (ENABLE_PUBNUB_LOGGING)
                    this.PubNubInstance.PNLog.WriteToLog(string.Format("RemoveDuplicatesCheckAlreadySubscribedAndGetChannelsCommon: distinct channelsOrChannelGroups len={0}, channelsOrChannelGroups = {1}", channelsOrChannelGroups.Count, string.Join(",", channelsOrChannelGroups.ToArray())), PNLoggingMethod.LevelInfo);

                    string channel = string.Join(",", Helpers.GetDuplicates(channelsOrChannelGroups).Distinct <string> ().ToArray <string> ());

                    this.PubNubInstance.PNLog.WriteToLog(string.Format("RemoveDuplicatesCheckAlreadySubscribedAndGetChannelsCommon: duplicates channelsOrChannelGroups {0}", channel), PNLoggingMethod.LevelInfo);
                    #endif
                }
                #if (ENABLE_PUBNUB_LOGGING)
                this.PubNubInstance.PNLog.WriteToLog(string.Format("RemoveDuplicatesCheckAlreadySubscribedAndGetChannelsCommon: channelsOrChannelGroups len={0}, channelsOrChannelGroups = {1}", channelsOrChannelGroups.Count, string.Join(",", channelsOrChannelGroups.ToArray())), PNLoggingMethod.LevelInfo);
                #endif

                bReturn = CreateChannelEntityAndAddToSubscribe(type, channelsOrChannelGroups, isChannelGroup, unsubscribeCheck, ref channelEntities, PubNubInstance);
            }
            #if (ENABLE_PUBNUB_LOGGING)
            else
            {
                this.PubNubInstance.PNLog.WriteToLog(string.Format("RemoveDuplicatesCheckAlreadySubscribedAndGetChannelsCommon: channelsOrChannelGroups len <=0"), PNLoggingMethod.LevelInfo);
            }
            #endif
            return(bReturn);
        }
Exemplo n.º 7
0
        private static string EndpointNameForOperation(PNOperationType type)
        {
            string endpoint = "";

            switch (type)
            {
            case PNOperationType.PNPublishOperation:
                endpoint = "l_pub";
                break;

            case PNOperationType.PNHistoryOperation:
            case PNOperationType.PNFireOperation:
            case PNOperationType.PNDeleteMessageOperation:
                endpoint = "l_hist";
                break;

            case PNOperationType.PNUnsubscribeOperation:
            case PNOperationType.PNWhereNowOperation:
            case PNOperationType.PNHereNowOperation:
            case PNOperationType.PNHeartbeatOperation:
            case PNOperationType.PNSetStateOperation:
            case PNOperationType.PNGetStateOperation:
                endpoint = "l_pres";
                break;

            case PNOperationType.PNAddChannelsToGroupOperation:
            case PNOperationType.PNRemoveChannelsFromGroupOperation:
            case PNOperationType.PNChannelGroupsOperation:
            case PNOperationType.PNRemoveGroupOperation:
            case PNOperationType.PNChannelsForGroupOperation:
                endpoint = "l_cg";
                break;

            case PNOperationType.PushGet:
            case PNOperationType.PushRegister:
            case PNOperationType.PushRemove:
            case PNOperationType.PushUnregister:
                endpoint = "l_push";
                break;

            case PNOperationType.PNAccessManagerAudit:
            case PNOperationType.PNAccessManagerGrant:
                endpoint = "l_pam";
                break;

            case PNOperationType.PNTimeOperation:
                endpoint = "l_time";
                break;

            case PNOperationType.PNMessageCountsOperation:
                endpoint = "l_mc";
                break;

            default:
                endpoint = "";
                break;
            }

            return(endpoint);
        }
 public void StoreLatency(long latencyMillisec, PNOperationType type)
 {
     try
     {
         string latencyEndPoint = EndpointNameForOperation(type);
         if (latencyMillisec > 0 && !string.IsNullOrEmpty(latencyEndPoint))
         {
             double epochMillisec = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
             if (dicEndpointLatency.ContainsKey(latencyEndPoint))
             {
                 dicEndpointLatency[latencyEndPoint].AddOrUpdate(epochMillisec, latencyMillisec, (key, oldValue) => latencyMillisec);
             }
             else
             {
                 ConcurrentDictionary <double, long> elapsedInfo = new ConcurrentDictionary <double, long>();
                 elapsedInfo.Add(epochMillisec, latencyMillisec);
                 dicEndpointLatency.Add(latencyEndPoint, elapsedInfo);
             }
             System.Diagnostics.Debug.WriteLine(string.Format("{0} latency = {1}", type, latencyMillisec));
         }
     }
     catch (Exception ex)
     {
         LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0}, TelemetryManager - StoreLatency error: {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), ex), pubnubConfig.LogVerbosity);
     }
 }
Exemplo n.º 9
0
 public QueueStorage(object callback, PNOperationType operationType, object operationParams, PubNubUnity pn)
 {
     this.Callback        = callback;
     this.OperationType   = operationType;
     this.OperationParams = operationParams;
     this.PubNubInstance  = pn;
 }
Exemplo n.º 10
0
        Uri IUrlRequestBuilder.BuildAddChannelsToChannelGroupRequest(string channelsCommaDelimited, string nameSpace, string groupName)
        {
            PNOperationType currentType = PNOperationType.PNAddChannelsToGroupOperation;

            List <string> url = new List <string>();

            url.Add("v1");
            url.Add("channel-registration");
            url.Add("sub-key");
            url.Add(pubnubConfig.SubscribeKey);
            if (!string.IsNullOrEmpty(nameSpace) && nameSpace.Trim().Length > 0)
            {
                url.Add("namespace");
                url.Add(nameSpace);
            }
            url.Add("channel-group");
            url.Add(groupName);

            Dictionary <string, string> requestQueryStringParams = new Dictionary <string, string>();

            requestQueryStringParams.Add("add", new UriUtil().EncodeUriComponent(channelsCommaDelimited, currentType, false, false, false));

            string queryString = BuildQueryString(currentType, url, requestQueryStringParams);
            string queryParams = string.Format("?{0}", queryString);

            return(BuildRestApiRequest <Uri>(url, currentType, queryParams));
        }
Exemplo n.º 11
0
        Uri IUrlRequestBuilder.BuildAuditAccessRequest(string channel, string channelGroup, string authKeysCommaDelimited)
        {
            PNOperationType currentType = PNOperationType.PNAccessManagerAudit;

            List <string> url = new List <string>();

            url.Add("v2");
            url.Add("auth");
            url.Add("audit");
            url.Add("sub-key");
            url.Add(pubnubConfig.SubscribeKey);

            Dictionary <string, string> requestQueryStringParams = new Dictionary <string, string>();

            if (!string.IsNullOrEmpty(authKeysCommaDelimited))
            {
                requestQueryStringParams.Add("auth", new UriUtil().EncodeUriComponent(authKeysCommaDelimited, currentType, false, false, false));
            }

            if (!string.IsNullOrEmpty(channel))
            {
                requestQueryStringParams.Add("channel", new UriUtil().EncodeUriComponent(channel, currentType, false, false, false));
            }

            if (!string.IsNullOrEmpty(channelGroup))
            {
                requestQueryStringParams.Add("channel-group", new UriUtil().EncodeUriComponent(channelGroup, currentType, false, false, false));
            }

            string queryString = BuildQueryString(currentType, url, requestQueryStringParams);
            string queryParams = string.Format("?{0}", queryString);

            return(BuildRestApiRequest <Uri>(url, currentType, queryParams));
        }
Exemplo n.º 12
0
        Uri IUrlRequestBuilder.BuildDeleteMessageRequest(string channel, long start, long end)
        {
            PNOperationType currentType = PNOperationType.PNDeleteMessageOperation;

            List <string> url = new List <string>();

            url.Add("v3");
            url.Add("history");
            url.Add("sub-key");
            url.Add(pubnubConfig.SubscribeKey);
            url.Add("channel");
            url.Add(channel);

            Dictionary <string, string> requestQueryStringParams = new Dictionary <string, string>();

            if (start != -1)
            {
                requestQueryStringParams.Add("start", start.ToString().ToLower());
            }
            if (end != -1)
            {
                requestQueryStringParams.Add("end", end.ToString().ToLower());
            }

            string queryString = BuildQueryString(currentType, url, requestQueryStringParams);
            string queryParams = string.Format("?{0}", queryString);

            return(BuildRestApiRequest <Uri>(url, currentType, queryParams));
        }
Exemplo n.º 13
0
        Uri IUrlRequestBuilder.BuildRemoveChannelsFromChannelGroupRequest(string channelsCommaDelimited, string nameSpace, string groupName)
        {
            PNOperationType currentType = PNOperationType.PNRemoveGroupOperation;

            bool groupNameAvailable = false;
            bool nameSpaceAvailable = false;
            bool channelAvaiable    = false;

            List <string> url = new List <string>();

            url.Add("v1");
            url.Add("channel-registration");
            url.Add("sub-key");
            url.Add(pubnubConfig.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 <string, string> requestQueryStringParams = new Dictionary <string, string>();

            if (channelAvaiable)
            {
                requestQueryStringParams.Add("remove", new UriUtil().EncodeUriComponent(channelsCommaDelimited, currentType, false, false, false));
            }

            string queryString = BuildQueryString(currentType, url, requestQueryStringParams);
            string queryParams = string.Format("?{0}", queryString);

            return(BuildRestApiRequest <Uri>(url, currentType, queryParams));
        }
Exemplo n.º 14
0
        private Dictionary <string, string> GenerateCommonQueryParams(PNOperationType type)
        {
            long   timeStamp = TranslateUtcDateTimeToSeconds(DateTime.UtcNow);
            string requestid = Guid.NewGuid().ToString();

            if (pubnubUnitTest != null)
            {
                timeStamp = pubnubUnitTest.Timetoken;
                requestid = string.IsNullOrEmpty(pubnubUnitTest.RequestId) ? "" : pubnubUnitTest.RequestId;
            }

            Dictionary <string, string> ret = new Dictionary <string, string>();

            ret.Add("uuid", this.pubnubConfig.Uuid);
            ret.Add("pnsdk", new UriUtil().EncodeUriComponent(Pubnub.Version, PNOperationType.PNSubscribeOperation, false, false, true));

            if (pubnubConfig != null)
            {
                if (pubnubConfig.IncludeRequestIdentifier)
                {
                    ret.Add("requestid", requestid);
                }

                if (pubnubConfig.IncludeInstanceIdentifier && !string.IsNullOrEmpty(pubnubInstanceId) && pubnubInstanceId.Trim().Length > 0)
                {
                    ret.Add("instanceid", pubnubInstanceId);
                }

                if (pubnubConfig.EnableTelemetry && telemetryMgr != null)
                {
                    Dictionary <string, string> opsLatency = telemetryMgr.GetOperationsLatency();
                    if (opsLatency != null && opsLatency.Count > 0)
                    {
                        foreach (string key in opsLatency.Keys)
                        {
                            ret.Add(key, opsLatency[key]);
                        }
                    }
                }

                if (!string.IsNullOrEmpty(pubnubConfig.SecretKey))
                {
                    ret.Add("timestamp", timeStamp.ToString());
                }

                if (type != PNOperationType.PNTimeOperation &&
                    type != PNOperationType.PNAccessManagerGrant && type != PNOperationType.ChannelGroupGrantAccess &&
                    type != PNOperationType.PNAccessManagerAudit && type != PNOperationType.ChannelGroupAuditAccess)
                {
                    if (!string.IsNullOrEmpty(this.pubnubConfig.AuthKey))
                    {
                        ret.Add("auth", new UriUtil().EncodeUriComponent(this.pubnubConfig.AuthKey, type, false, false, false));
                    }
                }
            }

            return(ret);
        }
Exemplo n.º 15
0
 public void Enqueue(object callback, PNOperationType operationType, object operationParams, PubNubUnity pn)
 {
     #if (ENABLE_PUBNUB_LOGGING)
     pn.PNLog.WriteToLog(string.Format("Queuing {0}", operationType), PNLoggingMethod.LevelInfo);
     #endif
     QueueStorage qs = new QueueStorage(callback, operationType, (object)operationParams, pn);
     q.Enqueue(qs);
     Reset();
 }
Exemplo n.º 16
0
        public void StoreLatency(long startTime, long endTime, PNOperationType operationType)
        {
            float latency = (endTime - startTime) / 10000000f; // seconds

            //TODO Add delete history
            switch (operationType)
            {
            case PNOperationType.PNTimeOperation:
                TimeLatency.Add(DateTime.UtcNow.Ticks, latency);
                break;

            case PNOperationType.PNPublishOperation:
                PublishLatency.Add(DateTime.UtcNow.Ticks, latency);
                break;

            case PNOperationType.PNWhereNowOperation:
            case PNOperationType.PNHereNowOperation:
            case PNOperationType.PNLeaveOperation:
            case PNOperationType.PNSetStateOperation:
            case PNOperationType.PNGetStateOperation:
                PresenceLatency.Add(DateTime.UtcNow.Ticks, latency);
                break;

            case PNOperationType.PNRemoveAllPushNotificationsOperation:
            case PNOperationType.PNAddPushNotificationsOnChannelsOperation:
            case PNOperationType.PNPushNotificationEnabledChannelsOperation:
            case PNOperationType.PNRemovePushNotificationsFromChannelsOperation:
                MobilePushLatency.Add(DateTime.UtcNow.Ticks, latency);
                break;

            case PNOperationType.PNMessageCountsOperation:
                MessageCountsLatency.Add(DateTime.UtcNow.Ticks, latency);
                break;

            case PNOperationType.PNFetchMessagesOperation:
            case PNOperationType.PNHistoryOperation:
                HistoryLatency.Add(DateTime.UtcNow.Ticks, latency);
                break;

            case PNOperationType.PNAddChannelsToGroupOperation:
            case PNOperationType.PNChannelGroupsOperation:
            case PNOperationType.PNChannelsForGroupOperation:
            case PNOperationType.PNRemoveChannelsFromGroupOperation:
            case PNOperationType.PNRemoveGroupOperation:
                ChannelGroupsLatency.Add(DateTime.UtcNow.Ticks, latency);
                break;

            default:
                break;
            }
        }
Exemplo n.º 17
0
        Uri IUrlRequestBuilder.BuildTimeRequest()
        {
            PNOperationType currentType = PNOperationType.PNTimeOperation;

            List <string> url = new List <string>();

            url.Add("time");
            url.Add("0");

            string queryString = BuildQueryString(currentType, url, null);
            string queryParams = string.Format("?{0}", queryString);

            return(BuildRestApiRequest <Uri>(url, currentType, queryParams));
        }
Exemplo n.º 18
0
        Uri IUrlRequestBuilder.BuildMultiChannelSubscribeRequest(string[] channels, string[] channelGroups, long timetoken, string channelsJsonState, Dictionary <string, string> initialSubscribeUrlParams)
        {
            PNOperationType currentType   = PNOperationType.PNSubscribeOperation;
            string          channelForUrl = (channels.Length > 0) ? string.Join(",", channels.OrderBy(x => x).ToArray()) : ",";

            List <string> url = new List <string>();

            url.Add("v2");
            url.Add("subscribe");
            url.Add(pubnubConfig.SubscribeKey);
            url.Add(channelForUrl);
            url.Add("0");

            if (initialSubscribeUrlParams == null)
            {
                initialSubscribeUrlParams = new Dictionary <string, string>();
            }

            Dictionary <string, string> requestQueryStringParams = new Dictionary <string, string>(initialSubscribeUrlParams);

            if (!requestQueryStringParams.ContainsKey("filter-expr") && !string.IsNullOrEmpty(pubnubConfig.FilterExpression))
            {
                requestQueryStringParams.Add("filter-expr", new UriUtil().EncodeUriComponent(pubnubConfig.FilterExpression, currentType, false, false, false));
            }

            if (!requestQueryStringParams.ContainsKey("tt"))
            {
                requestQueryStringParams.Add("tt", timetoken.ToString());
            }

            if (pubnubConfig.PresenceTimeout != 0)
            {
                requestQueryStringParams.Add("heartbeat", pubnubConfig.PresenceTimeout.ToString());
            }

            if (channelGroups != null && channelGroups.Length > 0 && channelGroups[0] != "")
            {
                requestQueryStringParams.Add("channel-group", new UriUtil().EncodeUriComponent(string.Join(",", channelGroups.OrderBy(x => x).ToArray()), currentType, false, false, false));
            }

            if (channelsJsonState != "{}" && channelsJsonState != "")
            {
                requestQueryStringParams.Add("state", new UriUtil().EncodeUriComponent(channelsJsonState, currentType, false, false, false));
            }

            string queryString = BuildQueryString(currentType, url, requestQueryStringParams);
            string queryParams = string.Format("?{0}", queryString);

            return(BuildRestApiRequest <Uri>(url, currentType, queryParams));
        }
Exemplo n.º 19
0
        protected int GetTimeoutInSecondsForResponseType(PNOperationType type)
        {
            int timeout;

            if (type == PNOperationType.PNSubscribeOperation || type == PNOperationType.Presence)
            {
                timeout = pubnubConfig.SubscribeTimeout;
            }
            else
            {
                timeout = pubnubConfig.NonSubscribeRequestTimeout;
            }
            return(timeout);
        }
Exemplo n.º 20
0
        private static void ParseCheckSocketConnectException <T>(Exception ex, PNOperationType type, PNCallback <T> callback, Action <bool> internalcallback)
        {
            PNStatusCategory errorCategory = PNStatusCategoryHelper.GetPNStatusCategory(ex);
            StatusBuilder    statusBuilder = new StatusBuilder(pubnubConfig, jsonLib);
            PNStatus         status        = statusBuilder.CreateStatusResponse <T>(type, errorCategory, null, (int)System.Net.HttpStatusCode.NotFound, new PNException(ex));

            if (callback != null)
            {
                callback.OnResponse(default(T), status);
            }

            LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} ParseCheckSocketConnectException Error. {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), ex.Message), pubnubConfig.LogVerbosity);
            internalcallback(false);
        }
Exemplo n.º 21
0
        Uri IUrlRequestBuilder.BuildGetChannelsForChannelGroupRequest(string nameSpace, string groupName, bool limitToChannelGroupScopeOnly)
        {
            PNOperationType currentType = PNOperationType.ChannelGroupGet;

            bool groupNameAvailable = false;
            bool nameSpaceAvailable = false;

            List <string> url = new List <string>();

            url.Add("v1");
            url.Add("channel-registration");
            url.Add("sub-key");
            url.Add(pubnubConfig.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 <string, string> requestQueryStringParams = new Dictionary <string, string>();

            string queryString = BuildQueryString(currentType, url, requestQueryStringParams);
            string queryParams = string.Format("?{0}", queryString);

            return(BuildRestApiRequest <Uri>(url, currentType, queryParams));
        }
Exemplo n.º 22
0
        private string GenerateSignature(PNOperationType type, string queryStringToSign, string partialUrl)
        {
            string        signature      = "";
            StringBuilder string_to_sign = new StringBuilder();

            string_to_sign.Append(this.pubnubConfig.SubscribeKey).Append("\n").Append(this.pubnubConfig.PublishKey).Append("\n");
            string_to_sign.Append(partialUrl.ToString()).Append("\n");
            string_to_sign.Append(queryStringToSign);

            PubnubCrypto pubnubCrypto = new PubnubCrypto(this.pubnubConfig.CipherKey, this.pubnubConfig);

            signature = pubnubCrypto.PubnubAccessManagerSign(this.pubnubConfig.SecretKey, string_to_sign.ToString());
            System.Diagnostics.Debug.WriteLine("string_to_sign = " + string_to_sign.ToString());
            System.Diagnostics.Debug.WriteLine("signature = " + signature);
            return(signature);
        }
Exemplo n.º 23
0
        protected PubNubNonSubBuilder(PubNubUnity pn, PNOperationType pnOperationType)
        {
            PubNubInstance     = pn;
            this.OperationType = pnOperationType;

            #if (ENABLE_PUBNUB_LOGGING)
            this.PubNubInstance.PNLog.WriteToLog(string.Format("{0} constructor", pnOperationType.ToString()), PNLoggingMethod.LevelInfo);
            #endif

            this.RunRequest += delegate(QueueManager qm) {
                RunWebRequest(qm);
            };
            this.CreateResponse += delegate(object deSerializedResult, RequestState pnRequestState) {
                CreatePubNubResponse(deSerializedResult, pnRequestState);
            };
        }
Exemplo n.º 24
0
        Uri IUrlRequestBuilder.BuildPublishRequest(string channel, object originalMessage, bool storeInHistory, int ttl, Dictionary <string, object> userMetaData, bool usePOST, Dictionary <string, string> additionalUrlParams)
        {
            bool            enableJsonEncodingForPublish = true; //by default. added placeholder for future for direct json input
            PNOperationType currentType = PNOperationType.PNPublishOperation;

            List <string> url = new List <string>();

            url.Add("publish");
            url.Add(pubnubConfig.PublishKey);
            url.Add(pubnubConfig.SubscribeKey);
            url.Add("0");
            url.Add(channel);
            url.Add("0");
            if (!usePOST)
            {
                string message = enableJsonEncodingForPublish ? JsonEncodePublishMsg(originalMessage) : originalMessage.ToString();
                url.Add(message);
            }

            if (additionalUrlParams == null)
            {
                additionalUrlParams = new Dictionary <string, string>();
            }

            Dictionary <string, string> requestQueryStringParams = new Dictionary <string, string>(additionalUrlParams);

            if (userMetaData != null)
            {
                string jsonMetaData = jsonLib.SerializeToJsonString(userMetaData);
                requestQueryStringParams.Add("meta", new UriUtil().EncodeUriComponent(jsonMetaData, currentType, false, false, false));
            }

            if (storeInHistory && ttl >= 0)
            {
                requestQueryStringParams.Add("tt1", ttl.ToString());
            }

            if (!storeInHistory)
            {
                requestQueryStringParams.Add("store", "0");
            }

            string queryString = BuildQueryString(currentType, url, requestQueryStringParams);
            string queryParams = string.Format("?{0}", queryString);

            return(BuildRestApiRequest <Uri>(url, currentType, queryParams));
        }
Exemplo n.º 25
0
        private string BuildQueryString(PNOperationType type, List <string> urlComponentList, Dictionary <string, string> queryStringParamDic)
        {
            string queryString = "";

            try
            {
                if (queryStringParamDic == null)
                {
                    queryStringParamDic = new Dictionary <string, string>();
                }

                Dictionary <string, string> commonQueryStringParams = GenerateCommonQueryParams(type);
                Dictionary <string, string> queryStringParams       = new Dictionary <string, string>(commonQueryStringParams.Concat(queryStringParamDic).GroupBy(item => item.Key).ToDictionary(item => item.Key, item => item.First().Value));

                string queryToSign = string.Join("&", queryStringParams.OrderBy(kvp => kvp.Key).Select(kvp => string.Format("{0}={1}", kvp.Key, kvp.Value)).ToArray());

                if (this.pubnubConfig.SecretKey.Length > 0)
                {
                    StringBuilder partialUrl = new StringBuilder();
                    for (int componentIndex = 0; componentIndex < urlComponentList.Count; componentIndex++)
                    {
                        partialUrl.Append("/");
                        if (type == PNOperationType.PNPublishOperation && componentIndex == urlComponentList.Count - 1)
                        {
                            partialUrl.Append(new UriUtil().EncodeUriComponent(urlComponentList[componentIndex], type, false, true, false));
                        }
                        else
                        {
                            partialUrl.Append(new UriUtil().EncodeUriComponent(urlComponentList[componentIndex], type, true, false, false));
                        }
                    }

                    string signature = GenerateSignature(queryToSign, partialUrl.ToString());
                    queryString = string.Format("{0}&signature={1}", queryToSign, signature);
                }
                else
                {
                    queryString = queryToSign;
                }
            }
            catch (Exception ex)
            {
                LoggingMethod.WriteToLog(pubnubLog, "UrlRequestBuilder => BuildQueryString error " + ex, pubnubConfig.LogVerbosity);
            }

            return(queryString);
        }
Exemplo n.º 26
0
        Uri IUrlRequestBuilder.BuildWhereNowRequest(string uuid)
        {
            PNOperationType currentType = PNOperationType.PNWhereNowOperation;

            List <string> url = new List <string>();

            url.Add("v2");
            url.Add("presence");
            url.Add("sub_key");
            url.Add(pubnubConfig.SubscribeKey);
            url.Add("uuid");
            url.Add(uuid);

            string queryString = BuildQueryString(currentType, url, null);
            string queryParams = string.Format("?{0}", queryString);

            return(BuildRestApiRequest <Uri>(url, currentType, queryParams));
        }
Exemplo n.º 27
0
        internal static bool CheckInternetStatus <T>(bool systemActive, PNOperationType type, PNCallback <T> callback, string[] channels, string[] channelGroups)
        {
            if (unit != null)
            {
                return(unit.InternetAvailable);
            }
            else
            {
                try
                {
#if NETFX_CORE || WINDOWS_UWP || UAP || NETSTANDARD10 || NETSTANDARD11 || NETSTANDARD12
                    Task[] tasks = new Task[1];
                    tasks[0] = Task.Factory.StartNew(async() =>
                    {
                        await CheckClientNetworkAvailability(CallbackClientNetworkStatus, type, callback, channels, channelGroups).ConfigureAwait(false);
                    }, CancellationToken.None, TaskCreationOptions.PreferFairness, TaskScheduler.Default);
                    tasks[0].ConfigureAwait(false);
                    Task.WaitAll(tasks);
#else
                    Thread networkCheckThread = new Thread(async() =>
                    {
                        await CheckClientNetworkAvailability(CallbackClientNetworkStatus, type, callback, channels, channelGroups).ConfigureAwait(false);
                    })
                    {
                        IsBackground = true
                    };
                    networkCheckThread.Start();
                    networkCheckThread.Join(pubnubConfig.NonSubscribeRequestTimeout * 1000);
#endif
                }
                catch (AggregateException ae) {
                    foreach (var ie in ae.InnerExceptions)
                    {
                        LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} AggregateException CheckInternetStatus Error: {1} {2} ", DateTime.Now.ToString(CultureInfo.InvariantCulture), ie.GetType().Name, ie.Message), pubnubConfig.LogVerbosity);
                    }
                }
                catch (Exception ex)
                {
                    LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} Exception CheckInternetStatus Error: {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), ex.Message), pubnubConfig.LogVerbosity);
                }

                return(networkStatus);
            }
        }
Exemplo n.º 28
0
        static StringBuilder EncodeURL(List <string> urlComponents, PNOperationType type)
        {
            StringBuilder url = new StringBuilder();

            // Generate URL with UTF-8 Encoding
            for (int componentIndex = 0; componentIndex < urlComponents.Count; componentIndex++)
            {
                url.Append("/");
                if (type == PNOperationType.PNPublishOperation && componentIndex == urlComponents.Count - 1)
                {
                    url.Append(Utility.EncodeUricomponent(urlComponents[componentIndex].ToString(), type, false, false));
                }
                else
                {
                    url.Append(Utility.EncodeUricomponent(urlComponents[componentIndex].ToString(), type, true, false));
                }
            }
            return(url);
        }
Exemplo n.º 29
0
        public async Task StoreLatency(long latencyMillisec, PNOperationType type)
        {
            await Task.Factory.StartNew(() =>
            {
                try
                {
                    string latencyEndPoint = EndpointNameForOperation(type);
                    if (latencyMillisec > 0 && !string.IsNullOrEmpty(latencyEndPoint))
                    {
                        if (dicEndpointLatency == null)
                        {
                            dicEndpointLatency = new ConcurrentDictionary <string, ConcurrentDictionary <double, long> >();
                        }

                        double epochMillisec = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
                        if (dicEndpointLatency.ContainsKey(latencyEndPoint) && dicEndpointLatency[latencyEndPoint] != null && dicEndpointLatency[latencyEndPoint].Keys.Count > 0)
                        {
                            if (epochMillisec - dicEndpointLatency[latencyEndPoint].Keys.Max() > 500)
                            {
                                lock (operationLatencyDataLock)
                                {
                                    dicEndpointLatency[latencyEndPoint].AddOrUpdate(epochMillisec, latencyMillisec, (key, oldValue) => latencyMillisec);
                                }
                            }
                        }
                        else
                        {
                            lock (operationLatencyDataLock)
                            {
                                ConcurrentDictionary <double, long> elapsedInfo = new ConcurrentDictionary <double, long>();
                                elapsedInfo.AddOrUpdate(epochMillisec, latencyMillisec, (o, n) => latencyMillisec);
                                dicEndpointLatency.AddOrUpdate(latencyEndPoint, elapsedInfo, (o, n) => elapsedInfo);
                            }
                        }
                        LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0}, TelemetryManager - StoreLatency {1} latency = {2}", DateTime.Now.ToString(CultureInfo.InvariantCulture), type, latencyMillisec), pubnubConfig.LogVerbosity);
                    }
                }
                catch (Exception ex)
                {
                    LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0}, TelemetryManager - StoreLatency error: {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), ex), pubnubConfig.LogVerbosity);
                }
            }, CancellationToken.None, TaskCreationOptions.PreferFairness, TaskScheduler.Default).ConfigureAwait(false);
        }
Exemplo n.º 30
0
        public static string EncodeUricomponent(string s, PNOperationType type, bool ignoreComma, bool ignorePercent2fEncode)
        {
            string        encodedUri = "";
            StringBuilder o          = new StringBuilder();

            foreach (char ch in s)
            {
                if (IsUnsafe(ch, ignoreComma))
                {
                    o.Append('%');
                    o.Append(ToHex(ch / 16));
                    o.Append(ToHex(ch % 16));
                }
                else
                {
                    if (ch == ',' && ignoreComma)
                    {
                        o.Append(ch.ToString());
                    }
                    else if (Char.IsSurrogate(ch))
                    {
                        o.Append(ch);
                    }
                    else
                    {
                        string escapeChar = System.Uri.EscapeDataString(ch.ToString());
                        o.Append(escapeChar);
                    }
                }
            }
            encodedUri = o.ToString();
            if (type == PNOperationType.PNHereNowOperation || type == PNOperationType.PNHistoryOperation || type == PNOperationType.PNLeaveOperation || type == PNOperationType.PNPresenceHeartbeatOperation ||
                type == PNOperationType.PNAddPushNotificationsOnChannelsOperation || type == PNOperationType.PNRemovePushNotificationsFromChannelsOperation || type == PNOperationType.PNPushNotificationEnabledChannelsOperation || type == PNOperationType.PNRemoveAllPushNotificationsOperation
                )
            {
                if (!ignorePercent2fEncode)
                {
                    encodedUri = encodedUri.Replace("%2F", "%252F");
                }
            }

            return(encodedUri);
        }