示例#1
0
        private void Publish(string channel, object message, bool storeInHistory, int ttl, Dictionary <string, object> metaData, Dictionary <string, object> externalQueryParam, PNCallback <PNPublishResult> callback)
        {
            if (string.IsNullOrEmpty(channel) || string.IsNullOrEmpty(channel.Trim()) || message == null)
            {
                PNStatus status = new PNStatus();
                status.Error     = true;
                status.ErrorData = new PNErrorData("Missing Channel or Message", new ArgumentException("Missing Channel or Message"));
                callback.OnResponse(null, status);
                return;
            }

            if (string.IsNullOrEmpty(config.PublishKey) || string.IsNullOrEmpty(config.PublishKey.Trim()) || config.PublishKey.Length <= 0)
            {
                PNStatus status = new PNStatus();
                status.Error     = true;
                status.ErrorData = new PNErrorData("Invalid publish key", new MissingMemberException("Invalid publish key"));
                callback.OnResponse(null, status);
                return;
            }

            if (callback == null)
            {
                return;
            }

            IUrlRequestBuilder urlBuilder = new UrlRequestBuilder(config, jsonLibrary, unit, pubnubLog, pubnubTelemetryMgr);

            urlBuilder.PubnubInstanceId = (PubnubInstance != null) ? PubnubInstance.InstanceId : "";
            Uri request = urlBuilder.BuildPublishRequest(channel, message, storeInHistory, ttl, metaData, httpPost, null, externalQueryParam);

            RequestState <PNPublishResult> requestState = new RequestState <PNPublishResult>();

            requestState.Channels          = new [] { channel };
            requestState.ResponseType      = PNOperationType.PNPublishOperation;
            requestState.PubnubCallback    = callback;
            requestState.Reconnect         = false;
            requestState.EndPointOperation = this;

            string json = "";

            if (this.httpPost)
            {
                requestState.UsePostMethod = true;
                string postMessage = JsonEncodePublishMsg(message);
                json = UrlProcessRequest <PNPublishResult>(request, requestState, false, postMessage);
            }
            else
            {
                json = UrlProcessRequest <PNPublishResult>(request, requestState, false);
            }

            if (!string.IsNullOrEmpty(json))
            {
                List <object> result = ProcessJsonResponse <PNPublishResult>(requestState, json);
                ProcessResponseCallbacks(result, requestState);
            }

            CleanUp();
        }
示例#2
0
        public void Execute(PNCallback <PNPublishResult> callback)
        {
            if (string.IsNullOrEmpty(this.channelName) || string.IsNullOrEmpty(channelName.Trim()) || this.msg == null)
            {
                throw new ArgumentException("Missing Channel or Message");
            }

            if (string.IsNullOrEmpty(config.PublishKey) || string.IsNullOrEmpty(config.PublishKey.Trim()) || config.PublishKey.Length <= 0)
            {
                throw new MissingMemberException("Invalid publish key");
            }

            if (string.IsNullOrEmpty(config.SubscribeKey) || string.IsNullOrEmpty(config.SubscribeKey.Trim()) || config.SubscribeKey.Length <= 0)
            {
                throw new MissingMemberException("Invalid subscribe key");
            }

            if (callback == null)
            {
                throw new ArgumentException("Missing userCallback");
            }

#if NETFX_CORE || WINDOWS_UWP || UAP || NETSTANDARD10 || NETSTANDARD11 || NETSTANDARD12
            Task.Factory.StartNew(() =>
            {
                this.savedCallback = callback;
                try
                {
                    Signal(this.channelName, this.msg, null, this.queryParam, callback);
                }
                catch (Exception ex)
                {
                    PNStatus unexpectedExceptionStatus = new PNStatus {
                        Error = true, ErrorData = new PNErrorData("Unexpected exception", ex)
                    };
                    callback.OnResponse(null, unexpectedExceptionStatus);
                }
            }, CancellationToken.None, TaskCreationOptions.PreferFairness, TaskScheduler.Default).ConfigureAwait(false);
#else
            new Thread(() =>
            {
                this.savedCallback = callback;
                try
                {
                    Signal(this.channelName, this.msg, null, this.queryParam, callback);
                }
                catch (Exception ex)
                {
                    PNStatus unexpectedExceptionStatus = new PNStatus {
                        Error = true, ErrorData = new PNErrorData("Unexpected exception", ex)
                    };
                    callback.OnResponse(null, unexpectedExceptionStatus);
                }
            })
            {
                IsBackground = true
            }.Start();
#endif
        }
        private void Publish(string channel, long messageTimetoken, PNMessageAction messageAction, Dictionary <string, object> externalQueryParam, PNCallback <PNAddMessageActionResult> callback)
        {
            if (string.IsNullOrEmpty(channel) || string.IsNullOrEmpty(channel.Trim()) || messageAction == null)
            {
                PNStatus status = new PNStatus();
                status.Error     = true;
                status.ErrorData = new PNErrorData("Missing Channel or MessageAction", new ArgumentException("Missing Channel or MessageAction"));
                callback.OnResponse(null, status);
                return;
            }

            if (string.IsNullOrEmpty(config.SubscribeKey) || string.IsNullOrEmpty(config.SubscribeKey.Trim()) || config.SubscribeKey.Length <= 0)
            {
                PNStatus status = new PNStatus();
                status.Error     = true;
                status.ErrorData = new PNErrorData("Invalid subscribe key", new MissingMemberException("Invalid subscribe key"));
                callback.OnResponse(null, status);
                return;
            }

            if (callback == null)
            {
                return;
            }

            string requestMethodName = "POST";
            string postMessage       = jsonLibrary.SerializeToJsonString(messageAction);

            byte[]             postData   = Encoding.UTF8.GetBytes(postMessage);
            IUrlRequestBuilder urlBuilder = new UrlRequestBuilder(config, jsonLibrary, unit, pubnubLog, pubnubTelemetryMgr, (PubnubInstance != null) ? PubnubInstance.InstanceId : "");

            Uri request = urlBuilder.BuildAddMessageActionRequest(requestMethodName, postMessage, channel, messageTimetoken, externalQueryParam);

            RequestState <PNAddMessageActionResult> requestState = new RequestState <PNAddMessageActionResult>();

            requestState.Channels          = new[] { channel };
            requestState.ResponseType      = PNOperationType.PNAddMessageActionOperation;
            requestState.PubnubCallback    = callback;
            requestState.Reconnect         = false;
            requestState.EndPointOperation = this;
            requestState.UsePostMethod     = true;

            UrlProcessRequest(request, requestState, false, postData).ContinueWith(r =>
            {
                string json = r.Result.Item1;
                if (!string.IsNullOrEmpty(json))
                {
                    List <object> result = ProcessJsonResponse(requestState, json);

                    ProcessResponseCallbacks(result, requestState);
                }
                CleanUp();
            }, TaskContinuationOptions.ExecuteSynchronously).Wait();
        }
示例#4
0
        private void ProcessFileDownloadRequest(Dictionary <string, object> externalQueryParam, PNCallback <PNDownloadFileResult> callback)
        {
            IUrlRequestBuilder urlBuilder = new UrlRequestBuilder(config, jsonLibrary, unit, pubnubLog, pubnubTelemetryMgr, (PubnubInstance != null) ? PubnubInstance.InstanceId : "");

            Uri request = urlBuilder.BuildGetFileUrlOrDeleteReqest("GET", "", this.channelName, this.currentFileId, this.currentFileName, externalQueryParam, PNOperationType.PNDownloadFileOperation);

            RequestState <PNDownloadFileResult> requestState = new RequestState <PNDownloadFileResult>();

            requestState.ResponseType      = PNOperationType.PNDownloadFileOperation;
            requestState.PubnubCallback    = callback;
            requestState.Reconnect         = false;
            requestState.EndPointOperation = this;

            byte[] item1Bytes = null;
            UrlProcessRequestForStream(request, requestState, false, "").ContinueWith(r =>
            {
                item1Bytes = r.Result.Item1;
                if (item1Bytes != null)
                {
                    byte[] outputBytes      = null;
                    string currentCipherKey = !string.IsNullOrEmpty(this.currentFileCipherKey) ? this.currentFileCipherKey : config.CipherKey;
                    if (currentCipherKey.Length > 0)
                    {
                        try
                        {
                            PubnubCrypto aes = new PubnubCrypto(currentCipherKey, config, pubnubLog, null);
                            outputBytes      = aes.Decrypt(item1Bytes, true);
                            LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0}, Stream length (after Decrypt)= {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), item1Bytes.Length), config.LogVerbosity);
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine(ex.ToString());
                        }
                    }
                    else
                    {
                        outputBytes = item1Bytes;
                    }
                    PNDownloadFileResult result = new PNDownloadFileResult();
                    result.FileBytes            = outputBytes;
                    result.FileName             = currentFileName;
                    callback.OnResponse(result, r.Result.Item2);
                }
                else
                {
                    if (r.Result.Item2 != null)
                    {
                        callback.OnResponse(null, r.Result.Item2);
                    }
                }
            }, TaskContinuationOptions.ExecuteSynchronously).Wait();
        }
        private void GetMessageActions(string channel, long start, long end, int limit, Dictionary <string, object> externalQueryParam, PNCallback <PNGetMessageActionsResult> callback)
        {
            if (string.IsNullOrEmpty(channel) || string.IsNullOrEmpty(channel.Trim()))
            {
                PNStatus status = new PNStatus();
                status.Error     = true;
                status.ErrorData = new PNErrorData("Missing Channel or MessageAction", new ArgumentException("Missing Channel or MessageAction"));
                callback.OnResponse(null, status);
                return;
            }

            if (string.IsNullOrEmpty(config.SubscribeKey) || string.IsNullOrEmpty(config.SubscribeKey.Trim()) || config.SubscribeKey.Length <= 0)
            {
                PNStatus status = new PNStatus();
                status.Error     = true;
                status.ErrorData = new PNErrorData("Invalid subscribe key", new MissingMemberException("Invalid publish key"));
                callback.OnResponse(null, status);
                return;
            }

            if (callback == null)
            {
                return;
            }

            IUrlRequestBuilder urlBuilder = new UrlRequestBuilder(config, jsonLibrary, unit, pubnubLog, pubnubTelemetryMgr, (PubnubInstance != null) ? PubnubInstance.InstanceId : "");

            Uri request = urlBuilder.BuildGetMessageActionsRequest("GET", "", channel, start, end, limit, externalQueryParam);

            RequestState <PNGetMessageActionsResult> requestState = new RequestState <PNGetMessageActionsResult>();

            requestState.Channels          = new[] { channel };
            requestState.ResponseType      = PNOperationType.PNGetMessageActionsOperation;
            requestState.PubnubCallback    = callback;
            requestState.Reconnect         = false;
            requestState.EndPointOperation = this;

            UrlProcessRequest(request, requestState, false).ContinueWith(r =>
            {
                string json = r.Result.Item1;
                if (!string.IsNullOrEmpty(json))
                {
                    List <object> result = ProcessJsonResponse(requestState, json);

                    ProcessResponseCallbacks(result, requestState);
                }

                CleanUp();
            }, TaskContinuationOptions.ExecuteSynchronously).Wait();
        }
示例#6
0
        private void ProcessListFilesRequest(Dictionary <string, object> externalQueryParam, PNCallback <PNListFilesResult> callback)
        {
            IUrlRequestBuilder urlBuilder = new UrlRequestBuilder(config, jsonLibrary, unit, pubnubLog, pubnubTelemetryMgr, (PubnubInstance != null) ? PubnubInstance.InstanceId : "");

            Uri request = urlBuilder.BuildListFilesReqest("GET", "", this.channelName, this.limitFileCount, this.nextFileBatchToken, externalQueryParam, PNOperationType.PNListFilesOperation);

            RequestState <PNListFilesResult> requestState = new RequestState <PNListFilesResult>();

            requestState.ResponseType      = PNOperationType.PNListFilesOperation;
            requestState.PubnubCallback    = callback;
            requestState.Reconnect         = false;
            requestState.EndPointOperation = this;

            requestState.UsePostMethod = false;
            UrlProcessRequest(request, requestState, false).ContinueWith(r =>
            {
                string json = r.Result.Item1;
                if (!string.IsNullOrEmpty(json))
                {
                    List <object> result = ProcessJsonResponse(requestState, json);
                    ProcessResponseCallbacks(result, requestState);
                }
                else
                {
                    if (r.Result.Item2 != null)
                    {
                        callback.OnResponse(null, r.Result.Item2);
                    }
                }
            }, TaskContinuationOptions.ExecuteSynchronously).Wait();
        }
        private void GetSingleChannelMetadata(string spaceId, bool includeCustom, Dictionary <string, object> externalQueryParam, PNCallback <PNGetChannelMetadataResult> callback)
        {
            IUrlRequestBuilder urlBuilder = new UrlRequestBuilder(config, jsonLibrary, unit, pubnubLog, pubnubTelemetryMgr, (PubnubInstance != null) ? PubnubInstance.InstanceId : "");

            Uri request = urlBuilder.BuildGetSingleChannelMetadataRequest("GET", "", spaceId, includeCustom, externalQueryParam);

            RequestState <PNGetChannelMetadataResult> requestState = new RequestState <PNGetChannelMetadataResult>();

            requestState.ResponseType      = PNOperationType.PNGetChannelMetadataOperation;
            requestState.PubnubCallback    = callback;
            requestState.Reconnect         = false;
            requestState.EndPointOperation = this;

            requestState.UsePostMethod = false;
            UrlProcessRequest(request, requestState, false).ContinueWith(r =>
            {
                string json = r.Result.Item1;
                if (!string.IsNullOrEmpty(json))
                {
                    List <object> result = ProcessJsonResponse(requestState, json);
                    ProcessResponseCallbacks(result, requestState);
                }
                else
                {
                    if (r.Result.Item2 != null)
                    {
                        callback.OnResponse(null, r.Result.Item2);
                    }
                }
            }, TaskContinuationOptions.ExecuteSynchronously).Wait();
        }
示例#8
0
        private void ProcessGetFileUrl(Dictionary <string, object> externalQueryParam, PNCallback <PNFileUrlResult> callback)
        {
            IUrlRequestBuilder urlBuilder = new UrlRequestBuilder(config, jsonLibrary, unit, pubnubLog, pubnubTelemetryMgr, (PubnubInstance != null) ? PubnubInstance.InstanceId : "");

            Uri request = urlBuilder.BuildGetFileUrlOrDeleteReqest("GET", "", this.channelName, this.currentFileId, this.currentFileName, externalQueryParam, PNOperationType.PNFileUrlOperation);

            PNFileUrlResult result = new PNFileUrlResult();

            result.Url = request.ToString();

            PNStatus status = new PNStatus {
                Error = false, StatusCode = 200
            };

            callback.OnResponse(result, status);
        }
示例#9
0
        private void GetMembershipsList(string uuid, PNPageObject page, int limit, bool includeCount, string includeOptions, string filter, List <string> sort, Dictionary <string, object> externalQueryParam, PNCallback <PNMembershipsResult> callback)
        {
            if (string.IsNullOrEmpty(uuid))
            {
                uuid = config.Uuid;
            }

            PNPageObject internalPage;

            if (page == null)
            {
                internalPage = new PNPageObject();
            }
            else
            {
                internalPage = page;
            }

            IUrlRequestBuilder urlBuilder = new UrlRequestBuilder(config, jsonLibrary, unit, pubnubLog, pubnubTelemetryMgr, (PubnubInstance != null) ? PubnubInstance.InstanceId : "");

            Uri request = urlBuilder.BuildGetAllMembershipsRequest("GET", "", uuid, internalPage.Next, internalPage.Prev, limit, includeCount, includeOptions, filter, sort, externalQueryParam);

            RequestState <PNMembershipsResult> requestState = new RequestState <PNMembershipsResult>();

            requestState.ResponseType      = PNOperationType.PNGetMembershipsOperation;
            requestState.PubnubCallback    = callback;
            requestState.Reconnect         = false;
            requestState.EndPointOperation = this;

            requestState.UsePostMethod = false;
            UrlProcessRequest(request, requestState, false).ContinueWith(r =>
            {
                string json = r.Result.Item1;
                if (!string.IsNullOrEmpty(json))
                {
                    List <object> result = ProcessJsonResponse(requestState, json);
                    ProcessResponseCallbacks(result, requestState);
                }
                else
                {
                    if (r.Result.Item2 != null)
                    {
                        callback.OnResponse(null, r.Result.Item2);
                    }
                }
            }, TaskContinuationOptions.ExecuteSynchronously).Wait();
        }
        private void ProcessMembersOperationRequest(string spaceId, List <PNChannelMember> setMemberList, List <string> removeMemberList, PNPageObject page, int limit, bool includeCount, string includeOptions, List <string> sort, Dictionary <string, object> externalQueryParam, PNCallback <PNChannelMembersResult> callback)
        {
            PNPageObject internalPage;

            if (page == null)
            {
                internalPage = new PNPageObject();
            }
            else
            {
                internalPage = page;
            }

            RequestState <PNChannelMembersResult> requestState = new RequestState <PNChannelMembersResult>();

            requestState.ResponseType      = PNOperationType.PNManageChannelMembersOperation;
            requestState.PubnubCallback    = callback;
            requestState.Reconnect         = false;
            requestState.EndPointOperation = this;

            requestState.UsePatchMethod = true;
            Dictionary <string, object> messageEnvelope = new Dictionary <string, object>();

            if (setMemberList != null)
            {
                List <Dictionary <string, object> > setMemberFormatList = new List <Dictionary <string, object> >();
                for (int index = 0; index < setMemberList.Count; index++)
                {
                    Dictionary <string, object> currentMemberFormat = new Dictionary <string, object>();
                    currentMemberFormat.Add("uuid", new Dictionary <string, string> {
                        { "id", setMemberList[index].Uuid }
                    });
                    if (setMemberList[index].Custom != null)
                    {
                        currentMemberFormat.Add("custom", setMemberList[index].Custom);
                    }
                    setMemberFormatList.Add(currentMemberFormat);
                }
                if (setMemberFormatList.Count > 0)
                {
                    messageEnvelope.Add("set", setMemberFormatList);
                }
            }
            if (removeMemberList != null)
            {
                List <Dictionary <string, Dictionary <string, string> > > removeMemberFormatList = new List <Dictionary <string, Dictionary <string, string> > >();
                for (int index = 0; index < removeMemberList.Count; index++)
                {
                    Dictionary <string, Dictionary <string, string> > currentMemberFormat = new Dictionary <string, Dictionary <string, string> >();
                    if (!string.IsNullOrEmpty(removeMemberList[index]))
                    {
                        currentMemberFormat.Add("uuid", new Dictionary <string, string> {
                            { "id", removeMemberList[index] }
                        });
                        removeMemberFormatList.Add(currentMemberFormat);
                    }
                }
                if (removeMemberFormatList.Count > 0)
                {
                    messageEnvelope.Add("delete", removeMemberFormatList);
                }
            }
            string patchMessage = jsonLibrary.SerializeToJsonString(messageEnvelope);

            IUrlRequestBuilder urlBuilder = new UrlRequestBuilder(config, jsonLibrary, unit, pubnubLog, pubnubTelemetryMgr, (PubnubInstance != null) ? PubnubInstance.InstanceId : "");
            Uri request = urlBuilder.BuildMemberAddUpdateRemoveChannelRequest("PATCH", patchMessage, spaceId, internalPage.Next, internalPage.Prev, limit, includeCount, includeOptions, sort, externalQueryParam);

            UrlProcessRequest(request, requestState, false, patchMessage).ContinueWith(r =>
            {
                string json = r.Result.Item1;
                if (!string.IsNullOrEmpty(json))
                {
                    List <object> result = ProcessJsonResponse(requestState, json);
                    ProcessResponseCallbacks(result, requestState);
                }
                else
                {
                    if (r.Result.Item2 != null)
                    {
                        callback.OnResponse(null, r.Result.Item2);
                    }
                }
            }, TaskContinuationOptions.ExecuteSynchronously).Wait();
        }
示例#11
0
        private void Signal(string channel, object message, Dictionary <string, object> metaData, Dictionary <string, object> externalQueryParam, PNCallback <PNPublishResult> callback)
        {
            if (string.IsNullOrEmpty(channel) || string.IsNullOrEmpty(channel.Trim()) || message == null)
            {
                PNStatus status = new PNStatus {
                    Error = true, ErrorData = new PNErrorData("Missing Channel or Message", new ArgumentException("Missing Channel or Message"))
                };
                callback.OnResponse(null, status);
                return;
            }

            if (string.IsNullOrEmpty(config.PublishKey) || string.IsNullOrEmpty(config.PublishKey.Trim()) || config.PublishKey.Length <= 0)
            {
                PNStatus status = new PNStatus {
                    Error = true, ErrorData = new PNErrorData("Invalid publish key", new ArgumentException("Invalid publish key"))
                };
                callback.OnResponse(null, status);
                return;
            }

            if (string.IsNullOrEmpty(config.SubscribeKey) || string.IsNullOrEmpty(config.SubscribeKey.Trim()) || config.SubscribeKey.Length <= 0)
            {
                PNStatus status = new PNStatus {
                    Error = true, ErrorData = new PNErrorData("Invalid subscribe key", new ArgumentException("Invalid subscribe key"))
                };
                callback.OnResponse(null, status);
                return;
            }

            IUrlRequestBuilder urlBuilder = new UrlRequestBuilder(config, jsonLibrary, unit, pubnubLog, pubnubTelemetryMgr, (PubnubInstance != null) ? PubnubInstance.InstanceId : "");

            Uri request = urlBuilder.BuildSignalRequest("GET", "", channel, message, metaData, externalQueryParam);

            RequestState <PNPublishResult> requestState = new RequestState <PNPublishResult>();

            requestState.Channels          = new[] { channel };
            requestState.ResponseType      = PNOperationType.PNSignalOperation;
            requestState.PubnubCallback    = callback;
            requestState.Reconnect         = false;
            requestState.EndPointOperation = this;

            UrlProcessRequest(request, requestState, false).ContinueWith(r =>
            {
                string json = r.Result.Item1;
                if (!string.IsNullOrEmpty(json))
                {
                    List <object> result = ProcessJsonResponse(requestState, json);

                    if (result != null && result.Count >= 3)
                    {
                        int signalStatus;
                        Int32.TryParse(result[0].ToString(), out signalStatus);
                        if (signalStatus == 1)
                        {
                            ProcessResponseCallbacks(result, requestState);
                        }
                        else
                        {
                            PNStatusCategory category = PNStatusCategoryHelper.GetPNStatusCategory(400, result[1].ToString());
                            PNStatus status           = new StatusBuilder(config, jsonLibrary).CreateStatusResponse <PNPublishResult>(PNOperationType.PNSignalOperation, category, requestState, 400, new PNException(json));
                            if (requestState.PubnubCallback != null)
                            {
                                requestState.PubnubCallback.OnResponse(default(PNPublishResult), status);
                            }
                        }
                    }
                    else
                    {
                        ProcessResponseCallbacks(result, requestState);
                    }
                }
            }, TaskContinuationOptions.ExecuteSynchronously).Wait();
        }
示例#12
0
        private void Fire(string channel, object message, bool storeInHistory, int ttl, Dictionary <string, object> metaData, Dictionary <string, object> externalQueryParam, PNCallback <PNPublishResult> callback)
        {
            if (string.IsNullOrEmpty(channel) || string.IsNullOrEmpty(channel.Trim()) || message == null)
            {
                PNStatus status = new PNStatus {
                    Error = true, ErrorData = new PNErrorData("Missing Channel or Message", new ArgumentException("Missing Channel or Message"))
                };
                callback.OnResponse(null, status);
                return;
            }

            if (string.IsNullOrEmpty(config.PublishKey) || string.IsNullOrEmpty(config.PublishKey.Trim()) || config.PublishKey.Length <= 0)
            {
                PNStatus status = new PNStatus {
                    Error = true, ErrorData = new PNErrorData("Invalid publish key", new ArgumentException("Invalid publish key"))
                };
                callback.OnResponse(null, status);
                return;
            }

            if (callback == null)
            {
                return;
            }

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

            urlParam.Add("norep", "true");

            string             requestMethodName = (this.httpPost) ? "POST" : "GET";
            IUrlRequestBuilder urlBuilder        = new UrlRequestBuilder(config, jsonLibrary, unit, pubnubLog, pubnubTelemetryMgr, (PubnubInstance != null) ? PubnubInstance.InstanceId : "");

            Uri request = urlBuilder.BuildPublishRequest(requestMethodName, "", channel, message, storeInHistory, ttl, metaData, urlParam, externalQueryParam);

            RequestState <PNPublishResult> requestState = new RequestState <PNPublishResult>();

            requestState.Channels          = new [] { channel };
            requestState.ResponseType      = PNOperationType.PNFireOperation;
            requestState.PubnubCallback    = callback;
            requestState.Reconnect         = false;
            requestState.EndPointOperation = this;

            string json = "";

            if (this.httpPost)
            {
                requestState.UsePostMethod = true;
                Dictionary <string, object> messageEnvelope = new Dictionary <string, object>();
                messageEnvelope.Add("message", message);
                string postMessage = jsonLibrary.SerializeToJsonString(messageEnvelope);
                UrlProcessRequest(request, requestState, false, postMessage).ContinueWith(r =>
                {
                    json = r.Result.Item1;
                }, TaskContinuationOptions.ExecuteSynchronously).Wait();
            }
            else
            {
                UrlProcessRequest(request, requestState, false).ContinueWith(r =>
                {
                    json = r.Result.Item1;
                }, TaskContinuationOptions.ExecuteSynchronously).Wait();
            }

            if (!string.IsNullOrEmpty(json))
            {
                List <object> result = ProcessJsonResponse <PNPublishResult>(requestState, json);
                if (result != null && result.Count >= 3)
                {
                    int publishStatus;
                    Int32.TryParse(result[0].ToString(), out publishStatus);
                    if (publishStatus == 1)
                    {
                        ProcessResponseCallbacks(result, requestState);
                    }
                    else
                    {
                        PNStatusCategory category = PNStatusCategoryHelper.GetPNStatusCategory(400, result[1].ToString());
                        PNStatus         status   = new StatusBuilder(config, jsonLibrary).CreateStatusResponse <PNPublishResult>(PNOperationType.PNFireOperation, category, requestState, 400, new PNException(json));
                        if (requestState.PubnubCallback != null)
                        {
                            requestState.PubnubCallback.OnResponse(default(PNPublishResult), status);
                        }
                    }
                }
                else
                {
                    ProcessResponseCallbacks(result, requestState);
                }
            }
        }
示例#13
0
        private void ProcessFileUpload(Dictionary <string, object> externalQueryParam, PNCallback <PNFileUploadResult> callback)
        {
            PNResult <PNGenerateFileUploadUrlResult> generateFileUploadUrl       = GenerateFileUploadUrl(externalQueryParam).Result;
            PNGenerateFileUploadUrlResult            generateFileUploadUrlResult = generateFileUploadUrl.Result;
            PNStatus generateFileUploadUrlStatus = generateFileUploadUrl.Status;

            if (generateFileUploadUrlStatus.Error || generateFileUploadUrlResult == null)
            {
                PNStatus errStatus = new PNStatus {
                    Error = true, ErrorData = new PNErrorData("Error in GenerateFileUploadUrl. Try again.", new ArgumentException("Error in GenerateFileUploadUrl. Try again."))
                };
                if (callback != null)
                {
                    callback.OnResponse(null, errStatus);
                }
                return;
            }
            LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} GenerateFileUploadUrl OK.", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);

            RequestState <PNFileUploadResult> requestState = new RequestState <PNFileUploadResult>();

            requestState.ResponseType      = PNOperationType.PNFileUploadOperation;
            requestState.PubnubCallback    = callback;
            requestState.Reconnect         = false;
            requestState.EndPointOperation = this;

            requestState.UsePostMethod = true;

            byte[] sendFileByteArray = GetByteArrayFromFilePath(sendFileFullPath);


            string dataBoundary     = String.Format("----------{0:N}", Guid.NewGuid());
            string contentType      = "multipart/form-data; boundary=" + dataBoundary;
            string currentCipherKey = !string.IsNullOrEmpty(this.currentFileCipherKey) ? this.currentFileCipherKey : config.CipherKey;

            byte[] postData = GetMultipartFormData(sendFileByteArray, generateFileUploadUrlResult.FileName, generateFileUploadUrlResult.FileUploadRequest.FormFields, dataBoundary, currentCipherKey, config, pubnubLog);

            string json;

            UrlProcessRequest(new Uri(generateFileUploadUrlResult.FileUploadRequest.Url), requestState, false, postData, contentType).ContinueWith(r =>
            {
                json = r.Result.Item1;
                if (!string.IsNullOrEmpty(json) && string.Compare(json, "{}", StringComparison.CurrentCultureIgnoreCase) == 0)
                {
                    LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} GenerateFileUploadUrl -> file upload OK.", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);
                    //do internal publish after successful file upload

                    Dictionary <string, object> publishPayload = new Dictionary <string, object>();
                    if (this.publishMessage != null && !string.IsNullOrEmpty(this.publishMessage.ToString()))
                    {
                        publishPayload.Add("message", this.publishMessage);
                    }
                    publishPayload.Add("file", new Dictionary <string, string> {
                        { "id", generateFileUploadUrlResult.FileId },
                        { "name", generateFileUploadUrlResult.FileName }
                    });

                    int publishFileRetryLimit = config.FileMessagePublishRetryLimit;
                    int currentFileRetryCount = 0;
                    bool publishFailed        = false;
                    do
                    {
                        currentFileRetryCount += 1;
                        PNResult <PNPublishFileMessageResult> publishFileMessageResponse = PublishFileMessage(publishPayload, queryParam).Result;
                        PNPublishFileMessageResult publishFileMessage = publishFileMessageResponse.Result;
                        PNStatus publishFileMessageStatus             = publishFileMessageResponse.Status;
                        if (!publishFileMessageStatus.Error && publishFileMessage != null)
                        {
                            publishFailed             = false;
                            PNFileUploadResult result = new PNFileUploadResult();
                            result.Timetoken          = publishFileMessage.Timetoken;
                            result.FileId             = generateFileUploadUrlResult.FileId;
                            result.FileName           = generateFileUploadUrlResult.FileName;
                            LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} GenerateFileUploadUrl -> file upload -> PublishFileMessage -> OK.", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);
                            r.Result.Item2.Error = false;
                            callback.OnResponse(result, r.Result.Item2);
                        }
                        else
                        {
                            publishFailed = true;
                            if (currentFileRetryCount == publishFileRetryLimit)
                            {
                                callback.OnResponse(null, publishFileMessageStatus);
                            }
                            LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} PublishFileMessage Failed. currentFileRetryCount={1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), currentFileRetryCount), config.LogVerbosity);
#if !NET35 && !NET40
                            Task.Delay(1000).Wait();
#else
                            Thread.Sleep(1000);
#endif
                        }
                    }while (publishFailed && currentFileRetryCount <= publishFileRetryLimit);
                }
                else
                {
                    if (r.Result.Item2 != null)
                    {
                        callback.OnResponse(null, r.Result.Item2);
                    }
                }
            }, TaskContinuationOptions.ExecuteSynchronously).Wait();
        }
示例#14
0
        private void ProcessFileMessagePublish(Dictionary <string, object> externalQueryParam, PNCallback <PNPublishFileMessageResult> callback)
        {
            if (string.IsNullOrEmpty(this.channelName) || string.IsNullOrEmpty(this.channelName.Trim()))
            {
                PNStatus status = new PNStatus();
                status.Error     = true;
                status.ErrorData = new PNErrorData("Missing Channel or Message", new ArgumentException("Missing Channel or Message"));
                callback.OnResponse(null, status);
                return;
            }

            Dictionary <string, object> publishPayload = new Dictionary <string, object>();

            if (this.msg != null && !string.IsNullOrEmpty(this.msg.ToString()))
            {
                publishPayload.Add("message", this.msg);
            }
            publishPayload.Add("file", new Dictionary <string, string> {
                { "id", currentFileId },
                { "name", currentFileName }
            });

            RequestState <PNPublishFileMessageResult> requestState = new RequestState <PNPublishFileMessageResult>();

            requestState.ResponseType      = PNOperationType.PNPublishFileMessageOperation;
            requestState.PubnubCallback    = callback;
            requestState.Reconnect         = false;
            requestState.EndPointOperation = this;


            IUrlRequestBuilder urlBuilder = new UrlRequestBuilder(config, jsonLibrary, unit, pubnubLog, pubnubTelemetryMgr, (PubnubInstance != null) ? PubnubInstance.InstanceId : "");
            Uri request = urlBuilder.BuildPublishFileMessageRequest("GET", "", this.channelName, publishPayload, this.storeInHistory, this.ttl, this.userMetadata, null, externalQueryParam);

            string json = "";

            UrlProcessRequest(request, requestState, false).ContinueWith(r =>
            {
                json = r.Result.Item1;
            }, TaskContinuationOptions.ExecuteSynchronously).Wait();

            if (!string.IsNullOrEmpty(json))
            {
                List <object> result = ProcessJsonResponse(requestState, json);

                if (result != null && result.Count >= 3)
                {
                    int publishStatus;
                    Int32.TryParse(result[0].ToString(), out publishStatus);
                    if (publishStatus == 1)
                    {
                        ProcessResponseCallbacks(result, requestState);
                    }
                    else
                    {
                        PNStatusCategory category = PNStatusCategoryHelper.GetPNStatusCategory(400, result[1].ToString());
                        PNStatus         status   = new StatusBuilder(config, jsonLibrary).CreateStatusResponse <PNPublishFileMessageResult>(PNOperationType.PNPublishFileMessageOperation, category, requestState, 400, new PNException(json));
                        if (requestState.PubnubCallback != null)
                        {
                            requestState.PubnubCallback.OnResponse(default(PNPublishFileMessageResult), status);
                        }
                    }
                }
                else
                {
                    ProcessResponseCallbacks(result, requestState);
                }
            }
        }