Example #1
0
        public GetSpaceOperation(PNConfiguration pubnubConfig, IJsonPluggableLibrary jsonPluggableLibrary, IPubnubUnitTest pubnubUnit, IPubnubLog log, EndPoint.TelemetryManager telemetryManager, Pubnub instance) : base(pubnubConfig, jsonPluggableLibrary, pubnubUnit, log, telemetryManager, instance)
        {
            config             = pubnubConfig;
            jsonLibrary        = jsonPluggableLibrary;
            unit               = pubnubUnit;
            pubnubLog          = log;
            pubnubTelemetryMgr = telemetryManager;

            if (instance != null)
            {
                if (!ChannelRequest.ContainsKey(instance.InstanceId))
                {
                    ChannelRequest.GetOrAdd(instance.InstanceId, new ConcurrentDictionary <string, HttpWebRequest>());
                }
                if (!ChannelInternetStatus.ContainsKey(instance.InstanceId))
                {
                    ChannelInternetStatus.GetOrAdd(instance.InstanceId, new ConcurrentDictionary <string, bool>());
                }
                if (!ChannelGroupInternetStatus.ContainsKey(instance.InstanceId))
                {
                    ChannelGroupInternetStatus.GetOrAdd(instance.InstanceId, new ConcurrentDictionary <string, bool>());
                }
            }
        }
Example #2
0
        public static void ThenAuditPushChannelProvisionsShouldReturnSuccess()
        {
            server.ClearRequests();

            receivedMessage = false;
            currentTestCase = "ThenAuditPushChannelProvisionsShouldReturnSuccess";

            if (PubnubCommon.EnableStubTest)
            {
                Assert.Ignore("Cannot run static unit test on AuditPushChannelProvisions");
                return;
            }

            PNConfiguration config = new PNConfiguration
            {
                SubscribeKey = PubnubCommon.SubscribeKey,
                Uuid         = "mytestuuid",
                Secure       = false
            };

            server.RunOnHttps(false);

            pubnub = createPubNubInstance(config);

            manualResetEventWaitTimeout = (PubnubCommon.EnableStubTest) ? 1000 : 310 * 1000;

            mrePush = new ManualResetEvent(false);

            pubnub.AuditPushChannelProvisions().DeviceId("4e71acc275a8eeb400654d923724c073956661455697c92ca6c5438f2c19aa7b").PushType(PNPushType.APNS).Async(new UTAuditPushChannel());
            mrePush.WaitOne(manualResetEventWaitTimeout);

            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
            Assert.IsTrue(receivedMessage, "AuditPushChannelProvisions Failed");
        }
Example #3
0
    void Start()
    {
        //Brings up Team Selectoin Menue
        Team_Selector.SetActive(true);
        Blue_HUD.SetActive(false);
        Red_HUD.SetActive(false);

        while (TeamSelectStatus == true)
        {
        }

        //Brings up HUD for coresponding team
        if (BlueTeamSelect == false)
        {
            Blue_HUD.SetActive(false);
            Red_HUD.SetActive(true);
        }
        else
        {
            Blue_HUD.SetActive(true);
            Red_HUD.SetActive(false);
        }

        //Changes Controller Material to match team
        if (BlueTeamSelect == false)
        {
            controllerRend.material = controllerRed;
        }
        else
        {
            controllerRend.material = controllerBlue;
        }

        _mlSpatialMapper.gameObject.transform.position   = _camera.gameObject.transform.position;
        _mlSpatialMapper.gameObject.transform.localScale = _bounded ? _boundedExtentsSize : _boundlessExtentsSize;

        // Initializing a new pubnub Connection
        PNConfiguration pnConfiguration = new PNConfiguration();

        pnConfiguration.PublishKey         = "pub-c-86694f64-f8a5-4dea-a382-d99cef5f71e9";
        pnConfiguration.SubscribeKey       = "sub-c-ef60f02c-80b8-11e9-bc4f-82f4a771f4c5";
        pnConfiguration.LogVerbosity       = PNLogVerbosity.BODY;
        pnConfiguration.UUID               = "GameMNGR";
        pnConfiguration.ReconnectionPolicy = PNReconnectionPolicy.LINEAR;

        PubNub pubnub = new PubNub(pnConfiguration);

        //Sets up Subscriber Callback which handles received messages
        pubnub.SubscribeCallback += (sender, e) => {
            SubscribeEventEventArgs mea = e as SubscribeEventEventArgs;

            if (mea.MessageResult != null)
            {
                if (mea.MessageResult.Payload == "BumperPress")
                {
                    CubeRenderer.enabled = false;
                }
                else
                {
                    CubeRenderer.enabled = true;
                }
            }
        };

        //Subscribes to channels in list
        pubnub.Subscribe()
        .Channels(new List <string>()
        {
            "cube"
        })
        .Execute();
    }
Example #4
0
 public FireOperation(PNConfiguration pubnubConfig, IJsonPluggableLibrary jsonPluggableLibrary) : base(pubnubConfig, jsonPluggableLibrary, null)
 {
     config      = pubnubConfig;
     jsonLibrary = jsonPluggableLibrary;
 }
        public void TestCBORTokensCommon()
        {
            string t1 = "p0F2AkF0Gl2AX-JDdHRsCkNyZXOkRGNoYW6gQ2dycKBDdXNyoWl1LTMzNTIwNTUPQ3NwY6Fpcy0xNzA3OTgzGB9DcGF0pERjaGFuoENncnCgQ3VzcqBDc3BjoERtZXRhoENzaWdYINqGs2EyEMHPZrp6znVqTBzXNBAD_31hUH3JuUSWE2A6";
            string t2 = "p0F2AkF0Gl2AaMlDdHRsCkNyZXOkRGNoYW6gQ2dycKBDdXNyoWl1LTE5NzQxMDcPQ3NwY6Fpcy0yMzExMDExGB9DcGF0pERjaGFuoENncnCgQ3VzcqBDc3BjoERtZXRhoENzaWdYIO1ti19DLbEKK-s_COJPlM1xtZCpP8K4sV51nvRPTIxf";
            string t3 = "p0F2AkF0Gl2CEiRDdHRsA0NyZXOkRGNoYW6gQ2dycKBDdXNyoW50ZXN0dXNlcl8xNjY2ORgfQ3NwY6FvdGVzdHNwYWNlXzE1MDExGB9DcGF0pERjaGFuoENncnCgQ3VzcqBDc3BjoERtZXRhoENzaWdYIMqDoIOYPP9ULfXKLDK3eoGQ-C8nJxPTWFCDAc-Flxu7";
            string t4 = "p0F2AkF0Gl2CEiVDdHRsA0NyZXOkRGNoYW6gQ2dycKBDdXNyoENzcGOgQ3BhdKREY2hhbqBDZ3JwoEN1c3KhY14uKhgfQ3NwY6FjXi4qGB9EbWV0YaBDc2lnWCDfqMStM0r1GgghNjt1MPeSaA0ADTw6aGsuQgMT3jYylg==";

            PNConfiguration pnConfiguration = new PNConfiguration();

            PubNubUnity pnUnity = new PubNubUnity(pnConfiguration, null, null);

            pnConfiguration.StoreTokensOnGrant = true;
            pnConfiguration.SecretKey          = "";

            PubNub pn = new PubNub(pnConfiguration);

            pn.SetTokens(new List <string> {
                t1, t2, t3, t4
            });

            GrantResourcesWithPermissions g = pn.GetTokens();

            Assert.IsTrue(g.Channels.Count.Equals(0));
            Assert.IsTrue(g.Groups.Count.Equals(0));
            Assert.IsTrue(g.ChannelsPattern.Count.Equals(0));
            Assert.IsTrue(g.GroupsPattern.Count.Equals(0));
            foreach (KeyValuePair <string, UserSpacePermissionsWithToken> kvp in g.Users)
            {
                Debug.Log(kvp.Key + "===>" + kvp.Value);
                UserSpacePermissionsWithToken u;

                if (g.Users.TryGetValue(kvp.Key, out u))
                {
                    Debug.Log(kvp.Key + "=======>" + u.Token);
                }
            }
            UserSpacePermissionsWithToken u1;

            if (g.Users.TryGetValue("testuser_16669", out u1))
            {
                Debug.Log("testuser_16669 =======>" + u1.Token);
            }
            else
            {
                Debug.Log("testuser_16669 not found");
            }
            Debug.Log(g.Users.ContainsKey("testuser_16669"));
            Debug.Log(g.Users.ContainsKey("u-1974107"));
            Debug.Log(g.Users.ContainsKey("u-3352055"));
            Assert.IsTrue(g.Users["testuser_16669"].BitMaskPerms.Equals(31));
            Assert.IsTrue(g.Users["testuser_16669"].TTL.Equals(3));
            Assert.IsTrue(g.Users["testuser_16669"].Timestamp.Equals(1568805412));

            Assert.IsTrue(g.Users["testuser_16669"].Token.Equals(t3));
            Assert.IsTrue(g.Users["testuser_16669"].Permissions.Read.Equals(true));
            Assert.IsTrue(g.Users["testuser_16669"].Permissions.Write.Equals(true));
            Assert.IsTrue(g.Users["testuser_16669"].Permissions.Delete.Equals(true));
            Assert.IsTrue(g.Users["testuser_16669"].Permissions.Create.Equals(true));
            Assert.IsTrue(g.Users["testuser_16669"].Permissions.Manage.Equals(true));

            Assert.IsTrue(g.Spaces["testspace_15011"].Token.Equals(t3));
            Assert.IsTrue(g.Spaces["testspace_15011"].Permissions.Read.Equals(true));
            Assert.IsTrue(g.Spaces["testspace_15011"].Permissions.Write.Equals(true));
            Assert.IsTrue(g.Spaces["testspace_15011"].Permissions.Delete.Equals(true));
            Assert.IsTrue(g.Spaces["testspace_15011"].Permissions.Create.Equals(true));
            Assert.IsTrue(g.Spaces["testspace_15011"].Permissions.Manage.Equals(true));

            Assert.IsTrue(g.Users["u-1974107"].Token.Equals(t2));
            Assert.IsTrue(g.Spaces["s-1707983"].Token.Equals(t1));

            Assert.IsTrue(g.UsersPattern["^.*"].Token.Equals(t4));
            Assert.IsTrue(g.SpacesPattern["^.*"].Token.Equals(t4));

            GrantResourcesWithPermissions g2 = pn.GetTokensByResource(PNResourceType.PNUsers);

            Assert.IsTrue(g2.Users["testuser_16669"].BitMaskPerms.Equals(31));
            Assert.IsTrue(g2.Users["testuser_16669"].TTL.Equals(3));
            Assert.IsTrue(g2.Users["testuser_16669"].Timestamp.Equals(1568805412));

            Assert.IsTrue(g2.Users["testuser_16669"].Token.Equals(t3));
            Assert.IsTrue(g2.Users["testuser_16669"].Permissions.Read.Equals(true));
            Assert.IsTrue(g2.Users["testuser_16669"].Permissions.Write.Equals(true));
            Assert.IsTrue(g2.Users["testuser_16669"].Permissions.Delete.Equals(true));
            Assert.IsTrue(g2.Users["testuser_16669"].Permissions.Create.Equals(true));
            Assert.IsTrue(g2.Users["testuser_16669"].Permissions.Manage.Equals(true));
            Assert.IsTrue(g2.Users["u-1974107"].Token.Equals(t2));
            Assert.IsTrue(g2.UsersPattern["^.*"].Token.Equals(t4));

            GrantResourcesWithPermissions g3 = pn.GetTokensByResource(PNResourceType.PNSpaces);

            Assert.IsTrue(g3.Spaces["testspace_15011"].BitMaskPerms.Equals(31));
            Assert.IsTrue(g3.Spaces["testspace_15011"].TTL.Equals(3));
            Assert.IsTrue(g3.Spaces["testspace_15011"].Timestamp.Equals(1568805412));

            Assert.IsTrue(g3.Spaces["testspace_15011"].Token.Equals(t3));
            Assert.IsTrue(g3.Spaces["testspace_15011"].Permissions.Read.Equals(true));
            Assert.IsTrue(g3.Spaces["testspace_15011"].Permissions.Write.Equals(true));
            Assert.IsTrue(g3.Spaces["testspace_15011"].Permissions.Delete.Equals(true));
            Assert.IsTrue(g3.Spaces["testspace_15011"].Permissions.Create.Equals(true));
            Assert.IsTrue(g3.Spaces["testspace_15011"].Permissions.Manage.Equals(true));
            Assert.IsTrue(g3.Spaces["s-1707983"].Token.Equals(t1));
            Assert.IsTrue(g3.SpacesPattern["^.*"].Token.Equals(t4));

            string g4 = pn.GetToken("testspace_15011", PNResourceType.PNSpaces);

            Debug.Log("g4" + g4);
            Assert.IsTrue(g4.Equals(t3));
            string g5 = pn.GetToken("testuser_16669", PNResourceType.PNUsers);

            Assert.IsTrue(g5.Equals(t3));
            string g6 = pn.GetToken("^.*", PNResourceType.PNSpaces);

            Assert.IsTrue(g6.Equals(t4));
            string g7 = pn.GetToken("^.*", PNResourceType.PNUsers);

            Assert.IsTrue(g7.Equals(t4));
            string g8 = pn.GetToken("NONEXISTENT", PNResourceType.PNSpaces);

            Assert.IsTrue(g8.Equals(t4));
            string g9 = pn.GetToken("NONEXISTENT", PNResourceType.PNUsers);

            Assert.IsTrue(g9.Equals(t4));
        }
        public static async Task ThenWithAsyncGetAllChannelGroupShouldReturnSuccess()
#endif
        {
            server.ClearRequests();
            if (!PubnubCommon.PAMServerSideRun)
            {
                Assert.Ignore("Ignored due to requied secret key to get all CGs");
            }
            currentUnitTestCase = "ThenGetAllChannelGroupShouldReturnSuccess";

            receivedChannelGroupMessage = false;

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                Uuid         = "mytestuuid",
            };

            if (PubnubCommon.PAMServerSideRun)
            {
                config.SecretKey = PubnubCommon.SecretKey;
            }
            else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey)
            {
                config.AuthKey = authKey;
            }
            pubnub = createPubNubInstance(config);

            string expected = "{\"status\": 200, \"payload\": {\"namespace\": \"\", \"groups\": [\"" + channelGroupName + "\", \"hello_my_group1\"]}, \"service\": \"channel-registry\", \"error\": false}";

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(string.Format("/v1/channel-registration/sub-key/{0}/channel-group", PubnubCommon.SubscribeKey))
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("timestamp", "1356998400")
                              .WithParameter("uuid", config.Uuid)
                              .WithParameter("signature", "qnMQZkath89WEZaFGFmYaODIJqscq97l4TlvkVKHx_0=")
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            channelGroupManualEvent = new ManualResetEvent(false);

#if NET40
            PNResult <PNChannelGroupsListAllResult> cgListAllResult = Task.Factory.StartNew(async() => await pubnub.ListChannelGroups().ExecuteAsync()).Result.Result;
#else
            PNResult <PNChannelGroupsListAllResult> cgListAllResult = await pubnub.ListChannelGroups().ExecuteAsync();
#endif
            Debug.WriteLine("PNStatus={0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(cgListAllResult.Status));

            if (cgListAllResult.Result != null)
            {
                Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(cgListAllResult.Result));
                if (cgListAllResult.Status.StatusCode == 200 && !cgListAllResult.Status.Error)
                {
                    receivedChannelGroupMessage = true;
                }
            }

            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
            Assert.IsTrue(receivedChannelGroupMessage, "WhenChannelGroupIsRequested -> ThenGetChannelListShouldReturnSuccess failed.");
        }
        public static async Task ThenWithAsyncRemoveChannelShouldReturnSuccess()
#endif
        {
            server.ClearRequests();

            currentUnitTestCase = "ThenRemoveChannelShouldReturnSuccess";
            string channelName = "hello_my_channel";

            receivedChannelGroupMessage = false;

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                Uuid         = "mytestuuid",
            };

            if (PubnubCommon.PAMServerSideRun)
            {
                config.SecretKey = PubnubCommon.SecretKey;
            }
            else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey)
            {
                config.AuthKey = authKey;
            }
            pubnub = createPubNubInstance(config);

            string expected = "{\"status\": 200, \"message\": \"OK\", \"service\": \"channel-registry\", \"error\": false}";

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(string.Format("/v1/channel-registration/sub-key/{0}/channel-group/{1}", PubnubCommon.SubscribeKey, channelGroupName))
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("remove", channelName)
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("timestamp", "1356998400")
                              .WithParameter("uuid", config.Uuid)
                              .WithParameter("signature", "bTwraHYh6dEMi44y-WgHslZdKSltsMySX5cg0uHt9tE=")
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            channelGroupManualEvent = new ManualResetEvent(false);

#if NET40
            PNResult <PNChannelGroupsRemoveChannelResult> cgRemoveChannelResult = Task.Factory.StartNew(async() => await pubnub.RemoveChannelsFromChannelGroup().Channels(new[] { channelName }).ChannelGroup(channelGroupName).ExecuteAsync()).Result.Result;
#else
            PNResult <PNChannelGroupsRemoveChannelResult> cgRemoveChannelResult = await pubnub.RemoveChannelsFromChannelGroup().Channels(new[] { channelName }).ChannelGroup(channelGroupName).ExecuteAsync();
#endif
            Debug.WriteLine("PNStatus={0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(cgRemoveChannelResult.Status));

            if (cgRemoveChannelResult.Result != null)
            {
                Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(cgRemoveChannelResult.Result));
                if (cgRemoveChannelResult.Status.StatusCode == 200 && cgRemoveChannelResult.Result.Message.ToLower() == "ok" &&
                    cgRemoveChannelResult.Result.Service == "channel-registry" && !cgRemoveChannelResult.Status.Error &&
                    cgRemoveChannelResult.Result.ChannelGroup == channelGroupName)
                {
                    receivedChannelGroupMessage = true;
                }
            }

            pubnub.Destroy();

            pubnub.PubnubUnitTest = null;
            pubnub = null;
            Assert.IsTrue(receivedChannelGroupMessage, "WhenChannelGroupIsRequested -> ThenWithAsyncRemoveChannelShouldReturnSuccess failed.");
        }
        public static void ThenSendFileShouldReturnSuccess()
        {
            server.ClearRequests();

            receivedMessage = false;
            bool receivedEvent = false;

            SubscribeCallbackExt eventListener = new SubscribeCallbackExt(
                delegate(Pubnub pnObj, PNFileEventResult eventResult)
            {
                receivedEvent = true;
                System.Diagnostics.Debug.WriteLine("FILE EVENT: " + pubnub.JsonPluggableLibrary.SerializeToJsonString(eventResult));
            },
                delegate(Pubnub pnObj, PNStatus status)
            {
            }
                );

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                //CipherKey = "enigma",
                Uuid   = "mytestuuid",
                Secure = false
            };

            if (PubnubCommon.PAMServerSideRun)
            {
                config.SecretKey = PubnubCommon.SecretKey;
            }
            else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey)
            {
                config.AuthKey = authKey;
            }
            pubnub = createPubNubInstance(config);
            pubnub.AddListener(eventListener);

            mre = new ManualResetEvent(false);
            pubnub.Subscribe <string>().Channels(new string[] { channelName }).Execute();
            mre.WaitOne(2000);

            string expected = "{\"status\": 200, \"message\": \"OK\", \"service\": \"channel-registry\", \"error\": false}";

            mre = new ManualResetEvent(false);

            string fileId   = "";
            string fileName = "";

            receivedMessage = false;
            string targetFileUpload = @"C:\Pandu\pubnub\word_test.txt";

            //string targetFileDownload = @"c:\pandu\temp\pandu_test.gif";
            pubnub.SendFile().Channel(channelName).File(targetFileUpload).CipherKey("enigma").Message("This is my sample file")
            .Execute(new PNFileUploadResultExt((result, status) =>
            {
                if (result != null)
                {
                    System.Diagnostics.Debug.WriteLine("SendFile result = " + pubnub.JsonPluggableLibrary.SerializeToJsonString(result));
                    fileId          = result.FileId;
                    fileName        = result.FileName;
                    receivedMessage = true;
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("SendFile failed = " + pubnub.JsonPluggableLibrary.SerializeToJsonString(status));
                }
                mre.Set();
            }));
            Thread.Sleep(1000);
            mre.WaitOne();

            receivedMessage = false;
            mre             = new ManualResetEvent(false);
            pubnub.ListFiles().Channel(channelName)
            .Execute(new PNListFilesResultExt((result, status) =>
            {
                if (result != null)
                {
                    System.Diagnostics.Debug.WriteLine("ListFiles result = " + pubnub.JsonPluggableLibrary.SerializeToJsonString(result));
                    receivedMessage = true;
                }
                mre.Set();
            }));
            Thread.Sleep(1000);
            mre.WaitOne();


            if (receivedMessage)
            {
                receivedMessage = false;
                mre             = new ManualResetEvent(false);
                pubnub.DownloadFile().Channel(channelName).FileId(fileId).FileName(fileName).Execute(new PNDownloadFileResultExt((result, status) =>
                {
                    if (result != null && result.FileBytes != null && result.FileBytes.Length > 0)
                    {
                        System.Diagnostics.Debug.WriteLine("DownloadFile result = " + result.FileBytes.Length);
                        receivedMessage = true;
                        //System.IO.File.WriteAllBytes(targetFileDownload, result.FileBytes);
                    }
                    mre.Set();
                }));
                mre.WaitOne();
            }

            if (receivedMessage)
            {
                receivedMessage = false;
                mre             = new ManualResetEvent(false);
                pubnub.DeleteFile().Channel(channelName).FileId(fileId).FileName(fileName)
                .Execute(new PNDeleteFileResultExt((result, status) =>
                {
                    if (result != null)
                    {
                        System.Diagnostics.Debug.WriteLine("DeleteFile result = " + pubnub.JsonPluggableLibrary.SerializeToJsonString(result));
                        receivedMessage = true;
                    }
                    mre.Set();
                }));
                Thread.Sleep(1000);
                mre.WaitOne();
            }

            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
            Assert.IsTrue(receivedMessage && receivedEvent, "WhenFileIsRequested -> TheSendFileShouldReturnSuccess failed.");
        }
        public static void ThenMultiSubscribeShouldReturnConnectStatus()
        {
            server.ClearRequests();

            bool receivedMessage = false;

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                Uuid         = "mytestuuid",
                AuthKey      = authKey,
                Secure       = false
            };

            server.RunOnHttps(false);

            ManualResetEvent  subscribeManualEvent = new ManualResetEvent(false);
            SubscribeCallback listenerSubCallack   = new SubscribeCallbackExt(
                (o, m) => { if (m != null)
                            {
                                Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(m));
                            }
                },
                (o, p) => { /* Catch the presence events */ },
                (o, s) => {
                Console.WriteLine("SubscribeCallback: PNStatus: " + s.StatusCode.ToString());
                if (s.StatusCode != 200 || s.Error)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    if (s.ErrorData != null)
                    {
                        Console.WriteLine(s.ErrorData.Information);
                    }
                    Console.ForegroundColor = ConsoleColor.White;
                }
                else if (s.StatusCode == 200 &&
                         (s.AffectedChannelGroups != null && s.AffectedChannelGroups.Contains(channelGroupName1) && s.AffectedChannelGroups.Contains(channelGroupName2)) &&
                         s.Category == PNStatusCategory.PNConnectedCategory)
                {
                    receivedMessage = true;
                    subscribeManualEvent.Set();
                }
            });

            pubnub = createPubNubInstance(config);
            pubnub.AddListener(listenerSubCallack);

            manualResetEventWaitTimeout = 310 * 1000;

            channelGroupName1 = "hello_my_group1";
            channelGroupName2 = "hello_my_group2";

            string channelName1 = "hello_my_channel1";
            string channelName2 = "hello_my_channel2";

            string expected = "{\"status\": 200, \"message\": \"OK\", \"service\": \"channel-registry\", \"error\": false}";

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(string.Format("/v1/channel-registration/sub-key/{0}/channel-group/{1}", PubnubCommon.SubscribeKey, channelGroupName1))
                              .WithParameter("add", channelName1)
                              .WithParameter("auth", config.AuthKey)
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("uuid", config.Uuid)
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            ManualResetEvent channelGroupManualEvent = new ManualResetEvent(false);

            pubnub.AddChannelsToChannelGroup().Channels(new [] { channelName1 }).ChannelGroup(channelGroupName1)
            .Async(new PNChannelGroupsAddChannelResultExt((r, s) => {
                try
                {
                    Console.WriteLine("PNStatus={0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(s));
                    if (r != null)
                    {
                        Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r));
                        if (s.StatusCode == 200 && s.Error == false && (s.AffectedChannelGroups.Contains(channelGroupName1) || s.AffectedChannelGroups.Contains(channelGroupName2)))
                        {
                            receivedMessage = true;
                        }
                    }
                }
                catch { /* ignore */ }
                finally { channelGroupManualEvent.Set(); }
            }));
            channelGroupManualEvent.WaitOne(manualResetEventWaitTimeout);

            if (receivedMessage)
            {
                receivedMessage = false;

                expected = "{\"status\": 200, \"message\": \"OK\", \"service\": \"channel-registry\", \"error\": false}";

                server.AddRequest(new Request()
                                  .WithMethod("GET")
                                  .WithPath(string.Format("/v1/channel-registration/sub-key/{0}/channel-group/{1}", PubnubCommon.SubscribeKey, channelGroupName2))
                                  .WithParameter("add", channelName2)
                                  .WithParameter("auth", config.AuthKey)
                                  .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                                  .WithParameter("requestid", "myRequestId")
                                  .WithParameter("uuid", config.Uuid)
                                  .WithResponse(expected)
                                  .WithStatusCode(System.Net.HttpStatusCode.OK));

                channelGroupManualEvent = new ManualResetEvent(false);
                pubnub.AddChannelsToChannelGroup().Channels(new [] { channelName2 }).ChannelGroup(channelGroupName2)
                .Async(new PNChannelGroupsAddChannelResultExt((r, s) => {
                    try
                    {
                        Console.WriteLine("PNStatus={0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(s));
                        if (r != null)
                        {
                            Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r));
                            if (s.StatusCode == 200 && s.Error == false && (s.AffectedChannelGroups.Contains(channelGroupName1) || s.AffectedChannelGroups.Contains(channelGroupName2)))
                            {
                                receivedMessage = true;
                            }
                        }
                    }
                    catch { /* ignore */ }
                    finally { channelGroupManualEvent.Set(); }
                }));
                channelGroupManualEvent.WaitOne(manualResetEventWaitTimeout);
            }

            if (receivedMessage)
            {
                receivedMessage = false;

                expected = "{\"t\":{\"t\":\"14839022442039237\",\"r\":7},\"m\":[]}";

                server.AddRequest(new Request()
                                  .WithMethod("GET")
                                  .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, ","))
                                  .WithParameter("auth", config.AuthKey)
                                  .WithParameter("channel-group", "hello_my_group1,hello_my_group2")
                                  .WithParameter("heartbeat", "300")
                                  .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                                  .WithParameter("requestid", "myRequestId")
                                  .WithParameter("tt", "0")
                                  .WithParameter("uuid", config.Uuid)
                                  .WithResponse(expected)
                                  .WithStatusCode(System.Net.HttpStatusCode.OK));

                expected = "{}";

                server.AddRequest(new Request()
                                  .WithMethod("GET")
                                  .WithPath(String.Format("/v2/subscribe/{0}/{1}/0", PubnubCommon.SubscribeKey, ","))
                                  .WithResponse(expected)
                                  .WithStatusCode(System.Net.HttpStatusCode.OK));


                pubnub.Subscribe <string>().ChannelGroups(new [] { channelGroupName1, channelGroupName2 }).Execute();
                subscribeManualEvent.WaitOne(manualResetEventWaitTimeout); //Wait for Connect Status
            }

            Thread.Sleep(1000);

            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;

            Assert.IsTrue(receivedMessage, "WhenSubscribedToAChannelGroup --> ThenMultiSubscribeShouldReturnConnectStatusFailed");
        }
        public static void Init()
        {
            UnitTestLog unitLog = new Tests.UnitTestLog();

            unitLog.LogLevel = MockServer.LoggingMethod.Level.Verbose;
            server           = Server.Instance();
            MockServer.LoggingMethod.MockServerLog = unitLog;
            server.Start();

            if (!PubnubCommon.PAMEnabled)
            {
                return;
            }

            bool receivedGrantMessage = false;

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                SecretKey    = PubnubCommon.SecretKey,
                Uuid         = "mytestuuid",
                Secure       = false
            };

            server.RunOnHttps(false);

            pubnub = createPubNubInstance(config);
            manualResetEventWaitTimeout = (PubnubCommon.EnableStubTest) ? 1000 : 310 * 1000;

            ManualResetEvent grantManualEvent = new ManualResetEvent(false);

            string expected = "{\"message\":\"Success\",\"payload\":{\"level\":\"user\",\"subscribe_key\":\"demo-36\",\"ttl\":20,\"channel\":\"hello_my_channel\",\"auths\":{\"myAuth\":{\"r\":1,\"w\":1,\"m\":1}}},\"service\":\"Access Manager\",\"status\":200}";

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(string.Format("/v2/auth/grant/sub-key/{0}", PubnubCommon.SubscribeKey))
                              .WithParameter("auth", authKey)
                              .WithParameter("channel", "hello_my_channel")
                              .WithParameter("channel-group", "hello_my_group%2Chello_my_group1%2Chello_my_group2")
                              .WithParameter("m", "1")
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("r", "1")
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("timestamp", "1356998400")
                              .WithParameter("ttl", "20")
                              .WithParameter("uuid", config.Uuid)
                              .WithParameter("w", "1")
                              .WithParameter("signature", "oiUrVMZSf7NEGk6M9JrvpnffmMEy7wWLgYGHwMztIlU=")
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            pubnub.Grant().AuthKeys(new [] { authKey }).ChannelGroups(new [] { channelGroupName, channelGroupName1, channelGroupName2 }).Channels(new [] { channelName }).Read(true).Write(true).Manage(true).TTL(20)
            .Async(new PNAccessManagerGrantResultExt(
                       (r, s) =>
            {
                try
                {
                    if (r != null && s.StatusCode == 200 && !s.Error)
                    {
                        Console.WriteLine("PNAccessManagerGrantResult={0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(r));

                        if (r.ChannelGroups != null && r.ChannelGroups.Count > 0)
                        {
                            foreach (KeyValuePair <string, Dictionary <string, PNAccessManagerKeyData> > channelGroupKP in r.ChannelGroups)
                            {
                                receivedGrantMessage = false;

                                string channelGroup = channelGroupKP.Key;
                                var read            = r.ChannelGroups[channelGroup][authKey].ReadEnabled;
                                var write           = r.ChannelGroups[channelGroup][authKey].WriteEnabled;
                                var manage          = r.ChannelGroups[channelGroup][authKey].ManageEnabled;

                                if (read && write && manage)
                                {
                                    receivedGrantMessage = true;
                                }
                                else
                                {
                                    receivedGrantMessage = false;
                                    break;
                                }
                            }
                        }
                        if (r.Channels != null && r.Channels.Count > 0)
                        {
                            foreach (KeyValuePair <string, Dictionary <string, PNAccessManagerKeyData> > channelKP in r.Channels)
                            {
                                receivedGrantMessage = false;

                                string channel = channelKP.Key;
                                var read       = r.Channels[channel][authKey].ReadEnabled;
                                var write      = r.Channels[channel][authKey].WriteEnabled;
                                var manage     = r.Channels[channel][authKey].ManageEnabled;

                                if (read && write && manage)
                                {
                                    receivedGrantMessage = true;
                                }
                                else
                                {
                                    receivedGrantMessage = false;
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("PNStatus={0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(s));
                    }
                }
                catch { /* ignore */ }
                finally
                {
                    grantManualEvent.Set();
                }
            }));
            Thread.Sleep(1000);
            grantManualEvent.WaitOne(manualResetEventWaitTimeout);

            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;

            Assert.IsTrue(receivedGrantMessage, "WhenSubscribedToAChannelGroup Grant access failed.");
        }
Example #11
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.PageHomeView);

            string channelName      = Intent.GetStringExtra("Channel");
            string channelGroupName = Intent.GetStringExtra("ChannelGroup");

            bool   enableSSL = Convert.ToBoolean((Intent.GetStringExtra("SslOn")));
            string cipher    = (Intent.GetStringExtra("Cipher"));

            string ssl = "";

            if (enableSSL)
            {
                ssl = "SSL,";
            }

            if (!String.IsNullOrWhiteSpace(cipher))
            {
                cipher = " Cipher";
            }

            string head = String.Format("{0}{1}", ssl, cipher);

            pubnub = LaunchScreen.pubnub;

            config                    = pubnub.PNConfig;
            config.PubnubLog          = new LocalLog();
            config.LogVerbosity       = PNLogVerbosity.BODY;
            config.ReconnectionPolicy = PNReconnectionPolicy.LINEAR;

            listener = new SubscribeCallbackExt(
                (o, m) =>
            {
                if (m != null)
                {
                    Display(pubnub.JsonPluggableLibrary.SerializeToJsonString(m.Message));
                }
            },
                (o, p) =>
            {
                if (p != null)
                {
                    Display(p.Event);
                }
            },
                (o, s) =>
            {
                if (s != null)
                {
                    Display(s.Category + " " + s.Operation + " " + s.StatusCode);
                }
            });

            Title        = head;
            this.m_Title = this.m_DrawerTitle = this.Title;

            TextView txtSubscribedChannel = FindViewById <TextView> (Resource.Id.newChannels);

            txtSubscribedChannel.Text = channelName;
            channel = txtSubscribedChannel.Text;

            TextView txtSubscribedChannelGroup = FindViewById <TextView> (Resource.Id.newChannelGroups);

            txtSubscribedChannelGroup.Text = channelGroupName;
            channelGroup = txtSubscribedChannelGroup.Text;

            TextView txtViewLog = FindViewById <TextView> (Resource.Id.txtViewLog);

            txtViewLog.Text = "";
            try {
                this.m_Drawer                = this.FindViewById <DrawerLayout> (Resource.Id.drawer_layout);
                this.m_DrawerList            = this.FindViewById <ListView> (Resource.Id.left_drawer);
                this.m_DrawerList.Adapter    = new ArrayAdapter <string> (this, Resource.Layout.ItemMenu, Sections);
                this.m_DrawerList.ItemClick += (sender, args) => ListItemClicked(args.Position);

                this.m_Drawer.SetDrawerShadow(Resource.Drawable.drawer_shadow_dark, (int)GravityFlags.Start);
                //DrawerToggle is the animation that happens with the indicator next to the actionbar
                this.m_DrawerToggle = new MyActionBarDrawerToggle(this, this.m_Drawer,
                                                                  Resource.Drawable.ic_drawer_light,
                                                                  Resource.String.drawer_open,
                                                                  Resource.String.drawer_close);
                //Display the current fragments title and update the options menu
                this.m_DrawerToggle.DrawerClosed += (o, args) => {
                    this.ActionBar.Title = this.m_Title;
                    this.InvalidateOptionsMenu();
                };
                //Display the drawer title and update the options menu
                this.m_DrawerToggle.DrawerOpened += (o, args) => {
                    this.ActionBar.Title = this.m_DrawerTitle;
                    this.InvalidateOptionsMenu();
                };
                //Set the drawer lister to be the toggle.
                this.m_Drawer.SetDrawerListener(this.m_DrawerToggle);

                //if first time you will want to go ahead and click first item.
                this.ActionBar.SetDisplayHomeAsUpEnabled(true);
                this.ActionBar.SetHomeButtonEnabled(true);
            } catch (Exception ex) {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }
        }
Example #12
0
        public static void ThenComplexMessageObjectShouldReturnSuccessCodeAndInfo()
        {
            server.ClearRequests();

            bool receivedPublishMessage = false;
            long publishTimetoken       = 0;

            string channel = "hello_my_channel";
            object message = new PubnubDemoObject();

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                Uuid         = "mytestuuid4",
                Secure       = false
            };

            server.RunOnHttps(false);

            pubnub = createPubNubInstance(config);

            string expected = "[1, \"Sent\", \"14715459088445832\"]";

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(String.Format("/publish/{0}/{1}/0/{2}/0/%7B%22VersionID%22:3.4%2C%22Timetoken%22:%2213601488652764619%22%2C%22OperationName%22:%22Publish%22%2C%22Channels%22:%5B%22ch1%22%5D%2C%22DemoMessage%22:%7B%22DefaultMessage%22:%22~!%40%23%24%25%5E%26*()_%2B%20%601234567890-%3D%20qwertyuiop%5B%5D%5C%5C%20%7B%7D%7C%20asdfghjkl%3B'%20:%5C%22%20zxcvbnm%2C.%2F%20%3C%3E%3F%20%22%7D%2C%22CustomMessage%22:%7B%22DefaultMessage%22:%22Welcome%20to%20the%20world%20of%20Pubnub%20for%20Publish%20and%20Subscribe.%20Hah!%22%7D%2C%22SampleXml%22:%5B%7B%22ID%22:%22ABCD123%22%2C%22Name%22:%7B%22First%22:%22John%22%2C%22Middle%22:%22P.%22%2C%22Last%22:%22Doe%22%7D%2C%22Address%22:%7B%22Street%22:%22123%20Duck%20Street%22%2C%22City%22:%22New%20City%22%2C%22State%22:%22New%20York%22%2C%22Country%22:%22United%20States%22%7D%7D%2C%7B%22ID%22:%22ABCD456%22%2C%22Name%22:%7B%22First%22:%22Peter%22%2C%22Middle%22:%22Z.%22%2C%22Last%22:%22Smith%22%7D%2C%22Address%22:%7B%22Street%22:%2212%20Hollow%20Street%22%2C%22City%22:%22Philadelphia%22%2C%22State%22:%22Pennsylvania%22%2C%22Country%22:%22United%20States%22%7D%7D%5D%7D", PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, channel))
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("uuid", config.Uuid)
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            manualResetEventWaitTimeout = 310 * 1000;

            ManualResetEvent publishManualEvent = new ManualResetEvent(false);

            pubnub.Publish().Channel(channel).Message(message)
            .Async(new PNPublishResultExt((r, s) =>
            {
                if (r != null && s.StatusCode == 200 && !s.Error)
                {
                    publishTimetoken       = r.Timetoken;
                    receivedPublishMessage = true;
                }
                publishManualEvent.Set();
            }));
            publishManualEvent.WaitOne(manualResetEventWaitTimeout);

            if (!receivedPublishMessage)
            {
                Assert.IsTrue(receivedPublishMessage, "Complex Object Publish Failed");
            }
            else
            {
                receivedPublishMessage = false;

                if (!PubnubCommon.EnableStubTest)
                {
                    Thread.Sleep(1000);
                }

                expected = Resource.ComplexMessage;

                server.AddRequest(new Request()
                                  .WithMethod("GET")
                                  .WithPath(String.Format("/v2/history/sub-key/{0}/channel/{1}", PubnubCommon.SubscribeKey, channel))
                                  .WithParameter("count", "100")
                                  .WithParameter("end", "14715459088445832")
                                  .WithParameter("include_token", "true")
                                  .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                                  .WithParameter("requestid", "myRequestId")
                                  .WithParameter("uuid", config.Uuid)
                                  .WithResponse(expected)
                                  .WithStatusCode(System.Net.HttpStatusCode.OK));

                Console.WriteLine("WhenAMessageIsPublished-ThenComplexMessageObjectShouldReturnSuccessCodeAndInfo - Publish OK. Now checking detailed history");

                ManualResetEvent historyManualEvent = new ManualResetEvent(false);

                pubnub.History().Channel(channel)
                .End(PubnubCommon.EnableStubTest ? 14715459088445832 : publishTimetoken)
                .Reverse(false)
                .IncludeTimetoken(true)
                .Async(new PNHistoryResultExt(
                           (r, s) =>
                {
                    Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r));
                    receivedPublishMessage = true;
                    historyManualEvent.Set();
                }));

                historyManualEvent.WaitOne(manualResetEventWaitTimeout);

                Assert.IsTrue(receivedPublishMessage, "Unable to match the successful unencrypt object Publish");
            }
            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
        }
Example #13
0
        public static void ThenSecretKeyWithEncryptPublishShouldReturnSuccessCodeAndInfo()
        {
            server.ClearRequests();

            bool receivedPublishMessage = false;
            long publishTimetoken       = 0;

            string channel = "hello_my_channel";
            string message = messageForSecretEncryptPublish;

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                SecretKey    = PubnubCommon.SecretKey,
                CipherKey    = "enigma",
                Uuid         = "mytestuuid",
                Secure       = false
            };

            server.RunOnHttps(false);

            pubnub = createPubNubInstance(config);

            string expected = "[1, \"Sent\", \"14715438956854374\"]";

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(String.Format("/publish/{0}/{1}/0/{2}/0/{3}", PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, channel, "%22f42pIQcWZ9zbTbH8cyLwB%2FtdvRxjFLOYcBNMVKeHS54%3D%22"))
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("timestamp", "1356998400")
                              .WithParameter("uuid", config.Uuid)
                              .WithParameter("signature", "tcFpCYsp1uiqyWCZxvdJp7KXEXjyvCFnH6F4UjJ6mds=")
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            manualResetEventWaitTimeout = 310 * 1000;

            ManualResetEvent publishManualEvent = new ManualResetEvent(false);

            pubnub.Publish().Channel(channel).Message(message)
            .Async(new PNPublishResultExt((r, s) =>
            {
                if (r != null && s.StatusCode == 200 && !s.Error)
                {
                    publishTimetoken       = r.Timetoken;
                    receivedPublishMessage = true;
                }
                publishManualEvent.Set();
            }));
            publishManualEvent.WaitOne(manualResetEventWaitTimeout);

            if (!receivedPublishMessage)
            {
                Assert.IsTrue(receivedPublishMessage, "Secret Encrypt Publish Failed");
            }
            else
            {
                receivedPublishMessage = false;

                if (!PubnubCommon.EnableStubTest)
                {
                    Thread.Sleep(1000);
                }

                expected = "[[\"f42pIQcWZ9zbTbH8cyLwB/tdvRxjFLOYcBNMVKeHS54=\"],14715438956854374,14715438956854374]";

                server.AddRequest(new Request()
                                  .WithMethod("GET")
                                  .WithPath(String.Format("/v2/history/sub-key/{0}/channel/{1}", PubnubCommon.SubscribeKey, channel))
                                  .WithParameter("count", "100")
                                  .WithParameter("end", "14715438956854374")
                                  .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                                  .WithParameter("requestid", "myRequestId")
                                  .WithParameter("timestamp", "1356998400")
                                  .WithParameter("uuid", config.Uuid)
                                  .WithParameter("signature", "WyHIBPHildY1gtERK5uDGqX8RyKnrqQFegoOoHizsV4=")
                                  .WithResponse(expected)
                                  .WithStatusCode(System.Net.HttpStatusCode.OK));

                ManualResetEvent historyManualEvent = new ManualResetEvent(false);

                pubnub.History().Channel(channel)
                .End(PubnubCommon.EnableStubTest ? 14715438956854374 : publishTimetoken)
                .Reverse(false)
                .IncludeTimetoken(false)
                .Async(new PNHistoryResultExt(
                           (r, s) =>
                {
                    Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r));
                    receivedPublishMessage = true;
                    historyManualEvent.Set();
                }));

                historyManualEvent.WaitOne(manualResetEventWaitTimeout);

                Assert.IsTrue(receivedPublishMessage, "Unable to decrypt the successful Secret key Publish");
            }

            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
        }
Example #14
0
        public static void ThenEncryptPublishShouldReturnSuccessCodeAndInfo()
        {
            server.ClearRequests();

            bool receivedPublishMessage = false;
            long publishTimetoken       = 0;

            string channel = "hello_my_channel";
            string message = messageForEncryptPublish;

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                CipherKey    = "enigma",
                Uuid         = "mytestuuid",
                Secure       = false
            };

            server.RunOnHttps(false);

            pubnub = createPubNubInstance(config);

            string expected = "[1,\"Sent\",\"14715426119520817\"]";

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(String.Format("/publish/{0}/{1}/0/{2}/0/{3}", PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, channel, "%22%2BBY5%2FmiAA8aeuhVl4d13Kg%3D%3D%22"))
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("uuid", config.Uuid)
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            manualResetEventWaitTimeout = 310 * 1000;

            ManualResetEvent publishManualEvent = new ManualResetEvent(false);

            pubnub.Publish().Channel(channel).Message(message)
            .Async(new PNPublishResultExt((r, s) =>
            {
                if (r != null && s.StatusCode == 200 && !s.Error)
                {
                    publishTimetoken       = r.Timetoken;
                    receivedPublishMessage = true;
                    publishManualEvent.Set();
                }
                else
                {
                    publishManualEvent.Set();
                }
            }));
            publishManualEvent.WaitOne(manualResetEventWaitTimeout);

            if (!receivedPublishMessage)
            {
                Assert.IsTrue(receivedPublishMessage, "Encrypt Publish Failed");
            }
            else
            {
                receivedPublishMessage = false;

                if (!PubnubCommon.EnableStubTest)
                {
                    Thread.Sleep(1000);
                }

                expected = "[[\"+BY5/miAA8aeuhVl4d13Kg==\"],14715426119520817,14715426119520817]";

                server.AddRequest(new Request()
                                  .WithMethod("GET")
                                  .WithPath(String.Format("/v2/history/sub-key/{0}/channel/{1}", PubnubCommon.SubscribeKey, channel))
                                  .WithParameter("count", "100")
                                  .WithParameter("end", "14715426119520817")
                                  .WithParameter("include_token", "true")
                                  .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                                  .WithParameter("requestid", "myRequestId")
                                  .WithParameter("uuid", config.Uuid)
                                  .WithResponse(expected)
                                  .WithStatusCode(System.Net.HttpStatusCode.OK));

                ManualResetEvent historyManualEvent = new ManualResetEvent(false);

                pubnub.History().Channel(channel)
                .End(PubnubCommon.EnableStubTest ? 14715426119520817 : publishTimetoken)
                .Reverse(false)
                .IncludeTimetoken(true)
                .Async(new PNHistoryResultExt(
                           (r, s) =>
                {
                    Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r));
                    receivedPublishMessage = true;
                    historyManualEvent.Set();
                }));

                historyManualEvent.WaitOne(manualResetEventWaitTimeout);

                Assert.IsTrue(receivedPublishMessage, "Unable to decrypt the successful Publish");
            }

            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
        }
Example #15
0
        public static void ThenEncryptObjectPublishShouldReturnSuccessCodeAndInfoWithSSL()
        {
            server.ClearRequests();

            bool receivedPublishMessage = false;
            long publishTimetoken       = 0;

            string channel = "hello_my_channel";
            object message = new SecretCustomClass();

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                CipherKey    = "enigma",
                Uuid         = "mytestuuid",
                Secure       = true
            };

            server.RunOnHttps(true);

            pubnub = createPubNubInstance(config);

            string expected = "[1,\"Sent\",\"14715322883933786\"]";

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(String.Format("/publish/{0}/{1}/0/{2}/0/{3}", PubnubCommon.PublishKey, PubnubCommon.SubscribeKey, channel, "%22nQTUCOeyWWgWh5NRLhSlhIingu92WIQ6RFloD9rOZsTUjAhD7AkMaZJVgU7l28e2%22"))
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("uuid", config.Uuid)
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            manualResetEventWaitTimeout = 310 * 1000;

            ManualResetEvent publishManualEvent = new ManualResetEvent(false);

            pubnub.Publish().Channel(channel).Message(message)
            .Async(new PNPublishResultExt((r, s) =>
            {
                if (r != null && s.StatusCode == 200 && !s.Error)
                {
                    publishTimetoken       = r.Timetoken;
                    receivedPublishMessage = true;
                }
                publishManualEvent.Set();
            }));
            publishManualEvent.WaitOne(manualResetEventWaitTimeout);

            if (!receivedPublishMessage)
            {
                Assert.IsTrue(receivedPublishMessage, "Encrypt Object Publish Failed with SSL");
            }
            else
            {
                receivedPublishMessage = false;

                if (!PubnubCommon.EnableStubTest)
                {
                    Thread.Sleep(1000);
                }

                expected = "[[\"nQTUCOeyWWgWh5NRLhSlhIingu92WIQ6RFloD9rOZsTUjAhD7AkMaZJVgU7l28e2\"],14715325858469956,14715325858469956]";

                server.AddRequest(new Request()
                                  .WithMethod("GET")
                                  .WithPath(String.Format("/v2/history/sub-key/{0}/channel/{1}", PubnubCommon.SubscribeKey, channel))
                                  .WithParameter("count", "100")
                                  .WithParameter("end", "14715325228931129")
                                  .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                                  .WithParameter("requestid", "myRequestId")
                                  .WithParameter("uuid", config.Uuid)
                                  .WithResponse(expected)
                                  .WithStatusCode(System.Net.HttpStatusCode.OK));

                ManualResetEvent historyManualEvent = new ManualResetEvent(false);

                pubnub.History().Channel(channel)
                .End(PubnubCommon.EnableStubTest ? 14715325228931129 : publishTimetoken)
                .Count(100)
                .Reverse(false)
                .IncludeTimetoken(false)
                .Async(new PNHistoryResultExt(
                           (r, s) =>
                {
                    Console.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r));
                    receivedPublishMessage = true;
                    historyManualEvent.Set();
                }));

                historyManualEvent.WaitOne(manualResetEventWaitTimeout);

                Assert.IsTrue(receivedPublishMessage, "Unable to match the successful encrypt object Publish with SSL");
            }
            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
        }
Example #16
0
        public static void ThenDeleteFileShouldReturnSuccess()
        {
            server.ClearRequests();

            receivedMessage = false;

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                CipherKey    = "enigma",
                Uuid         = "mytestuuid",
                Secure       = false
            };

            if (PubnubCommon.PAMServerSideRun)
            {
                config.SecretKey = PubnubCommon.SecretKey;
            }
            else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey)
            {
                config.AuthKey = authKey;
            }
            pubnub = createPubNubInstance(config);

            string expected = "";

            receivedMessage = false;
            PNResult <PNListFilesResult> listFilesResponse = pubnub.ListFiles().Channel(channelName).ExecuteAsync().Result;

            if (listFilesResponse.Result != null && listFilesResponse.Result.FilesList != null && listFilesResponse.Result.FilesList.Count > 0 && !listFilesResponse.Status.Error)
            {
                List <PNFileResult> filesList = listFilesResponse.Result.FilesList;
                foreach (var file in filesList)
                {
                    PNResult <PNDeleteFileResult> deleteFileResponse = pubnub.DeleteFile().Channel(channelName).FileId(file.Id).FileName(file.Name).ExecuteAsync().Result;
                    PNDeleteFileResult            deleteFileResult   = deleteFileResponse.Result;
                    if (deleteFileResult != null)
                    {
                        System.Diagnostics.Debug.WriteLine(string.Format("File Id={0}, Name={1} => deleted successfully", file.Id, file.Name));
                    }
                }
                receivedMessage = true;
            }
            else
            {
                PNResult <PNDeleteFileResult> deleteFileResponse = pubnub.DeleteFile().Channel(channelName).FileId("test_file_id").FileName("test_file_name.test").ExecuteAsync().Result;
                PNDeleteFileResult            deleteFileResult   = deleteFileResponse.Result;
                if (deleteFileResult != null)
                {
                    System.Diagnostics.Debug.WriteLine("File Id=test_file_id, Name=test_file_name.test => deleted successfully");
                    receivedMessage = true;
                }
            }


            mre             = new ManualResetEvent(false);
            receivedMessage = false;
            pubnub.DeleteFile().Channel(channelName).FileId("8f83d951-7850-40fb-9688-d2d825b14722").FileName("word_test.txt")
            .Execute(new PNDeleteFileResultExt((result, status) =>
            {
                if (result != null)
                {
                    System.Diagnostics.Debug.WriteLine("result = " + pubnub.JsonPluggableLibrary.SerializeToJsonString(result));
                    receivedMessage = true;
                }
                mre.Set();
            }));
            Thread.Sleep(1000);
            mre.WaitOne();

            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
            Assert.IsTrue(receivedMessage, "WhenFileIsRequested -> ThenListFilesShouldReturnSuccess failed.");
        }
Example #17
0
        public static async Task ThenWithAsyncDeleteFileShouldReturnSuccess()
#endif
        {
            server.ClearRequests();

            receivedMessage = false;

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                CipherKey    = "enigma",
                Uuid         = "mytestuuid",
                Secure       = false
            };

            if (PubnubCommon.PAMServerSideRun)
            {
                config.SecretKey = PubnubCommon.SecretKey;
            }
            else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey)
            {
                config.AuthKey = authKey;
            }
            pubnub = createPubNubInstance(config);

            string expected = "";

            receivedMessage = false;
#if NET40
            PNResult <PNListFilesResult> listFilesResponse = Task.Factory.StartNew(async() => await pubnub.ListFiles().Channel(channelName).ExecuteAsync()).Result.Result;
#else
            PNResult <PNListFilesResult> listFilesResponse = await pubnub.ListFiles().Channel(channelName).ExecuteAsync();
#endif
            if (listFilesResponse.Result != null && listFilesResponse.Result.FilesList != null && listFilesResponse.Result.FilesList.Count > 0 && !listFilesResponse.Status.Error)
            {
                List <PNFileResult> filesList = listFilesResponse.Result.FilesList;
                foreach (var file in filesList)
                {
#if NET40
                    PNResult <PNDeleteFileResult> deleteFileResponse = Task.Factory.StartNew(async() => await pubnub.DeleteFile().Channel(channelName).FileId(file.Id).FileName(file.Name).ExecuteAsync()).Result.Result;
#else
                    PNResult <PNDeleteFileResult> deleteFileResponse = await pubnub.DeleteFile().Channel(channelName).FileId(file.Id).FileName(file.Name).ExecuteAsync();
#endif
                    PNDeleteFileResult deleteFileResult = deleteFileResponse.Result;
                    if (deleteFileResult != null)
                    {
                        System.Diagnostics.Debug.WriteLine(string.Format("File Id={0}, Name={1} => deleted successfully", file.Id, file.Name));
                    }
                }
                receivedMessage = true;
            }
            else
            {
#if NET40
                PNResult <PNDeleteFileResult> deleteFileResponse = Task.Factory.StartNew(async() => await pubnub.DeleteFile().Channel(channelName).FileId("test_file_id").FileName("test_file_name.test").ExecuteAsync()).Result.Result;
#else
                PNResult <PNDeleteFileResult> deleteFileResponse = await pubnub.DeleteFile().Channel(channelName).FileId("test_file_id").FileName("test_file_name.test").ExecuteAsync();
#endif
                PNDeleteFileResult deleteFileResult = deleteFileResponse.Result;
                if (deleteFileResult != null)
                {
                    System.Diagnostics.Debug.WriteLine("File Id=test_file_id, Name=test_file_name.test => deleted successfully");
                    receivedMessage = true;
                }
            }

            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
            Assert.IsTrue(receivedMessage, "WhenFileIsRequested -> ThenWithAsyncDeleteFileShouldReturnSuccess failed.");
        }
Example #18
0
 public OtherOperation(PNConfiguration pubnubConfig) : base(pubnubConfig)
 {
     config = pubnubConfig;
 }
Example #19
0
        public void TestBuildPresenceHeartbeatRequestCommon(string[] channelGroups, string[] channels, string userState,
                                                            bool ssl, string authKey)
        {
            string uuid = "customuuid";

            PNConfiguration pnConfiguration = new PNConfiguration();

            pnConfiguration.Origin           = EditorCommon.Origin;
            pnConfiguration.SubscribeKey     = EditorCommon.SubscribeKey;
            pnConfiguration.PublishKey       = EditorCommon.PublishKey;
            pnConfiguration.Secure           = ssl;
            pnConfiguration.CipherKey        = "enigma";
            pnConfiguration.LogVerbosity     = PNLogVerbosity.BODY;
            pnConfiguration.PresenceTimeout  = 60;
            pnConfiguration.PresenceInterval = 30;
            pnConfiguration.AuthKey          = authKey;
            pnConfiguration.UUID             = uuid;

            PubNubUnity pnUnity = new PubNubUnity(pnConfiguration, null, null);

            string authKeyString = "";

            if (!string.IsNullOrEmpty(authKey))
            {
                authKeyString = string.Format("&auth={0}", pnConfiguration.AuthKey);
            }

            string cgStr = "";
            string cg    = "";

            if (channelGroups != null)
            {
                cg    = string.Join(",", channelGroups);
                cgStr = string.Format("&channel-group={0}", Utility.EncodeUricomponent(cg, PNOperationType.PNSubscribeOperation, true, false));
            }

            string chStr = ",";
            string ch    = "";

            if (channels != null)
            {
                ch    = string.Join(",", channels);
                chStr = ch;
            }

            Uri uri = BuildRequests.BuildPresenceHeartbeatRequest(ch, cg, userState, pnUnity);

            //https://ps.pndsn.com/v2/presence/sub_key/demo-36/channel/user_state_channel/heartbeat?uuid=customuuid&state={"k":"v"}&auth=authKey&pnsdk=PubNub-CSharp-UnityIOS/3.6.9.0

            string expected = string.Format("http{0}://{1}/v2/presence/sub_key/{2}/channel/{3}/heartbeat?uuid={4}{5}{6}{9}{7}&pnsdk={8}",
                                            ssl?"s":"", EditorCommon.Origin,
                                            EditorCommon.SubscribeKey,
                                            chStr,
                                            uuid,
                                            (userState == "")?"":"&state=",
                                            Utility.EncodeUricomponent(userState, PNOperationType.PNSubscribeOperation, false, false),
                                            authKeyString,
                                            Utility.EncodeUricomponent(pnUnity.Version, PNOperationType.PNSubscribeOperation, false, true),
                                            cgStr
                                            );
            string received = uri.OriginalString;

            EditorCommon.LogAndCompare(expected, received);
        }
Example #20
0
        public void TestPNinGenerateGuid()
        {
            PNConfiguration pnConfig = new PNConfiguration();

            Assert.IsTrue(pnConfig.UUID.Contains("pn-"));
        }
        public static async Task ThenWithAsyncGetChannelListShouldReturnSuccess()
#endif
        {
            server.ClearRequests();

            currentUnitTestCase = "ThenGetChannelListShouldReturnSuccess";

            receivedChannelGroupMessage = false;

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                Uuid         = "mytestuuid",
            };

            if (PubnubCommon.PAMServerSideRun)
            {
                config.SecretKey = PubnubCommon.SecretKey;
            }
            else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey)
            {
                config.AuthKey = authKey;
            }
            pubnub = createPubNubInstance(config);

            string expected = "{\"status\": 200, \"payload\": {\"channels\": [\"" + channelName + "\"], \"group\": \"" + channelGroupName + "\"}, \"service\": \"channel-registry\", \"error\": false}";

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath(string.Format("/v1/channel-registration/sub-key/{0}/channel-group/{1}", PubnubCommon.SubscribeKey, channelGroupName))
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("timestamp", "1356998400")
                              .WithParameter("uuid", config.Uuid)
                              .WithParameter("signature", "03YaQgvhwhQ9wMg3RLSYolTDzOpuuGoRzE5a7sEMLds=")
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

            channelGroupManualEvent = new ManualResetEvent(false);

#if NET40
            PNResult <PNChannelGroupsAllChannelsResult> cgAllChannelsResult = Task.Factory.StartNew(async() => await pubnub.ListChannelsForChannelGroup().ChannelGroup(channelGroupName).ExecuteAsync()).Result.Result;
#else
            PNResult <PNChannelGroupsAllChannelsResult> cgAllChannelsResult = await pubnub.ListChannelsForChannelGroup().ChannelGroup(channelGroupName).ExecuteAsync();
#endif
            Debug.WriteLine("PNStatus={0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(cgAllChannelsResult.Status));

            if (cgAllChannelsResult.Result != null)
            {
                Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(cgAllChannelsResult.Result));
                if (cgAllChannelsResult.Status.StatusCode == 200 && !cgAllChannelsResult.Status.Error &&
                    cgAllChannelsResult.Result.ChannelGroup == channelGroupName && cgAllChannelsResult.Result.Channels.Count > 0)
                {
                    receivedChannelGroupMessage = true;
                }
            }

            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
            Assert.IsTrue(receivedChannelGroupMessage, "WhenChannelGroupIsRequested -> ThenWithAsyncGetChannelListShouldReturnSuccess failed.");
        }
        public void TestBuildPublishRequestCommonWithTTL(bool sendMeta, bool ssl, bool storeInHistory, string secretKey, string cipherKey, string authKey, int ttl, bool replicate)
        {
            string channel   = "publish_channel";
            string message   = "Test message";
            string uuid      = "customuuid";
            string signature = "0";

            PNConfiguration pnConfiguration = new PNConfiguration();

            pnConfiguration.Origin           = EditorCommon.Origin;
            pnConfiguration.SubscribeKey     = EditorCommon.SubscribeKey;
            pnConfiguration.PublishKey       = EditorCommon.PublishKey;
            pnConfiguration.SecretKey        = secretKey;
            pnConfiguration.Secure           = ssl;
            pnConfiguration.CipherKey        = "enigma";
            pnConfiguration.LogVerbosity     = PNLogVerbosity.BODY;
            pnConfiguration.PresenceTimeout  = 60;
            pnConfiguration.PresenceInterval = 30;
            pnConfiguration.AuthKey          = authKey;
            pnConfiguration.UUID             = uuid;

            PubNubUnity pnUnity = new PubNubUnity(pnConfiguration, null, null);

            string authKeyString = "";

            if (!string.IsNullOrEmpty(authKey))
            {
                authKeyString = string.Format("&auth={0}", pnConfiguration.AuthKey);
            }

            string meta     = "";
            string metadata = "{\"region\":\"east\"}";

            if (sendMeta)
            {
                meta = string.Format("&meta={0}", Utility.EncodeUricomponent(metadata, PNOperationType.PNPublishOperation, false, false));
            }
            else
            {
                metadata = "";
            }

            string originalMessage = Helpers.JsonEncodePublishMsg(message, cipherKey, pnUnity.JsonLibrary, new PNLoggingMethod(pnConfiguration.LogVerbosity));

            if (secretKey.Length > 0)
            {
                StringBuilder stringToSign = new StringBuilder();
                stringToSign
                .Append(EditorCommon.PublishKey)
                .Append('/')
                .Append(EditorCommon.SubscribeKey)
                .Append('/')
                .Append(secretKey)
                .Append('/')
                .Append(channel)
                .Append('/')
                .Append(originalMessage);      // 1

                // Sign Message
                //signature = Utility.Md5 (stringToSign.ToString ());
                PubnubCrypto pnCrypto = new PubnubCrypto(cipherKey, new PNLoggingMethod(PNLogVerbosity.BODY));
                signature = pnCrypto.ComputeHashRaw(stringToSign.ToString());
            }

            Uri uri = BuildRequests.BuildPublishRequest(channel, originalMessage, storeInHistory, metadata, 0, ttl, false, replicate, pnUnity);

            string ttlStr = (ttl == -1) ? "" : string.Format("&ttl={0}", ttl.ToString());

            //http://ps.pndsn.com/publish/demo-36/demo-36/0/publish_channel/0?uuid=customuuid&auth=authKey&pnsdk=PubNub-CSharp-UnityOSX/3.6.9.0
            string expected = string.Format("http{0}://{1}/publish/{2}/{3}/{4}/{5}/0/{6}?uuid={7}&seqn=0{8}{12}{13}{11}{9}&pnsdk={10}",
                                            ssl?"s":"", pnConfiguration.Origin, EditorCommon.PublishKey, EditorCommon.SubscribeKey, signature, channel,
                                            Utility.EncodeUricomponent(originalMessage, PNOperationType.PNPublishOperation, false, false),
                                            uuid, storeInHistory?"":"&store=0", authKeyString,
                                            Utility.EncodeUricomponent(pnUnity.Version, PNOperationType.PNPublishOperation, false, false),
                                            meta,
                                            ttlStr,
                                            replicate?"":"&norep=true"
                                            );

            string received = uri.OriginalString;

            EditorCommon.LogAndCompare(expected, received);
        }
Example #23
0
        public static async Task ThenItShouldReturnTimeStamp()
#endif
        {
            server.ClearRequests();

            currentUnitTestCase = "ThenItShouldReturnTimeStamp";
            timeReceived        = false;
            mreTime             = new ManualResetEvent(false);

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                Uuid         = "mytestuuid",
                Secure       = false
            };

            server.RunOnHttps(false);

            pubnub = createPubNubInstance(config);

            string expected = "[14725889985315301]";

            server.AddRequest(new Request()
                              .WithMethod("GET")
                              .WithPath("/time/0")
                              .WithParameter("pnsdk", PubnubCommon.EncodedSDK)
                              .WithParameter("requestid", "myRequestId")
                              .WithParameter("uuid", config.Uuid)
                              .WithResponse(expected)
                              .WithStatusCode(System.Net.HttpStatusCode.OK));

#if NET40
            pubnub.Time().Execute(new PNTimeResultExt((result, status) =>
            {
                try
                {
                    Debug.WriteLine("PNStatus={0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(status));

                    if (result != null)
                    {
                        Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(result));

                        if (status.StatusCode == 200 && status.Error == false)
                        {
                            if (PubnubCommon.EnableStubTest)
                            {
                                if (expectedTime == result.Timetoken)
                                {
                                    timeReceived = true;
                                }
                            }
                            else if (result.Timetoken > 0)
                            {
                                timeReceived = true;
                            }
                        }
                    }
                }
                catch { /* ignone */ }
                finally
                {
                    mreTime.Set();
                }
            }));
            mreTime.WaitOne(310 * 1000);
#else
            PNResult <PNTimeResult> timeResult = await pubnub.Time().ExecuteAsync();

            if (timeResult.Result != null)
            {
                Debug.WriteLine(string.Format("ASYNC RESULT = {0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(timeResult.Result)));
                if (timeResult.Status.StatusCode == 200 && timeResult.Status.Error == false)
                {
                    if (PubnubCommon.EnableStubTest)
                    {
                        if (expectedTime == timeResult.Result.Timetoken)
                        {
                            timeReceived = true;
                        }
                    }
                    else if (timeResult.Result.Timetoken > 0)
                    {
                        timeReceived = true;
                    }
                }
            }
#endif



            pubnub.Destroy();
            pubnub = null;

            Assert.IsTrue(timeReceived, "time() Failed");
        }
Example #24
0
 public SetStateOperation(PNConfiguration pubnubConfig) : base(pubnubConfig)
 {
     config = pubnubConfig;
 }
Example #25
0
 public FireOperation(PNConfiguration pubnubConfig) : base(pubnubConfig)
 {
     config = pubnubConfig;
 }
Example #26
0
        public static void AtUserLevel()
        {
            bool receivedAuditMessage = false;

            if (!PubnubCommon.PAMEnabled)
            {
                Assert.Ignore("PAM not enabled; CleanupGrant -> AtUserLevel.");
                return;
            }

            if (!PubnubCommon.EnableStubTest)
            {
                receivedAuditMessage = false;
                PNConfiguration config = new PNConfiguration
                {
                    PublishKey   = PubnubCommon.PublishKey,
                    SubscribeKey = PubnubCommon.SubscribeKey,
                    SecretKey    = PubnubCommon.SecretKey,
                    Uuid         = "mytestuuid"
                };

                pubnub = createPubNubInstance(config);
                ManualResetEvent auditManualEvent = new ManualResetEvent(false);
                pubnub.Audit().Execute(new PNAccessManagerAuditResultExt((r, s) => {
                    try
                    {
                        Debug.WriteLine("PNStatus={0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(s));

                        if (r != null)
                        {
                            Debug.WriteLine("PNAccessManagerAuditResult={0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(r));
                            if (s.StatusCode == 200 && s.Error == false)
                            {
                                if (!String.IsNullOrEmpty(r.Channel))
                                {
                                    var channels = r.Channel.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                                    Debug.WriteLine("CleanupGrant / AtUserLevel / UserCallbackForCleanUpAccess - Channel Count = {0}", channels.Length);
                                    foreach (string channelName in channels)
                                    {
                                        if (r.AuthKeys != null)
                                        {
                                            foreach (string authKey in r.AuthKeys.Keys)
                                            {
                                                Debug.WriteLine("Auth Key = " + authKey);
                                                ManualResetEvent revokeManualEvent = new ManualResetEvent(false);
                                                pubnub.Grant().Channels(new[] { channelName }).AuthKeys(new[] { authKey }).Read(false).Write(false).Manage(false)
                                                .Execute(new PNAccessManagerGrantResultExt((r1, s1) =>
                                                {
                                                    try
                                                    {
                                                        Debug.WriteLine("PNStatus={0}", pubnub.JsonPluggableLibrary.SerializeToJsonString(s1));

                                                        if (r1 != null)
                                                        {
                                                            Debug.WriteLine(pubnub.JsonPluggableLibrary.SerializeToJsonString(r1));
                                                        }
                                                    }
                                                    catch { /* ignore */ }
                                                    finally
                                                    {
                                                        revokeManualEvent.Set();
                                                    }
                                                }));
                                                revokeManualEvent.WaitOne();
                                            }
                                        }
                                    }
                                }

                                if (r.Level == "subkey")
                                {
                                    receivedAuditMessage = true;
                                }
                            }
                        }
                    }
                    catch { /* ignore */ }
                    finally
                    {
                        auditManualEvent.Set();
                    }
                }));
                auditManualEvent.WaitOne(manualResetEventWaitTimeout);
                pubnub.Destroy();
                pubnub = null;
                Assert.IsTrue(receivedAuditMessage, "CleanupGrant -> AtUserLevel failed.");
            }
            else
            {
                Assert.Ignore("Only for live test; CleanupGrant -> AtUserLevel.");
            }
        }
Example #27
0
 public FireOperation(PNConfiguration pubnubConfig, IJsonPluggableLibrary jsonPluggableLibrary, IPubnubUnitTest pubnubUnit) : base(pubnubConfig, jsonPluggableLibrary, pubnubUnit)
 {
     config      = pubnubConfig;
     jsonLibrary = jsonPluggableLibrary;
     unit        = pubnubUnit;
 }
    void Start()
    {
        // Use this for initialization
        PNConfiguration pnConfiguration = new PNConfiguration();

        pnConfiguration.PublishKey   = "demo";
        pnConfiguration.SubscribeKey = "demo";
        pnConfiguration.LogVerbosity = PNLogVerbosity.BODY;
        pnConfiguration.UUID         = "user-1";
        pubnub = new PubNub(pnConfiguration);

        // Add Listener to Submit button to send messages
        Button btn = SubmitButton.GetComponent <Button>();

        btn.onClick.AddListener(TaskOnClick);

        // Fetch the maxMessagesToDisplay messages sent on the given PubNub channel
        pubnub.FetchMessages()
        .Channels(new List <string> {
            channel
        })
        .Count(maxMessagesToDisplay)
        .Async((result, status) =>
        {
            if (status.Error)
            {
                Debug.Log(string.Format(
                              " FetchMessages Error: {0} {1} {2}",
                              status.StatusCode, status.ErrorData, status.Category
                              ));
            }
            else
            {
                foreach (KeyValuePair <string, List <PNMessageResult> > kvp in result.Channels)
                {
                    foreach (PNMessageResult pnMessageResult in kvp.Value)
                    {
                        // Format data into readable format
                        JSONInformation chatmessage = JsonUtility.FromJson <JSONInformation>(pnMessageResult.Payload.ToString());

                        // Call the function to display the message in plain text
                        CreateChat(chatmessage);
                    }
                }
            }
        });

        // This is the subscribe callback function where data is recieved that is sent on the channel
        pubnub.SubscribeCallback += (sender, e) =>
        {
            SubscribeEventEventArgs message = e as SubscribeEventEventArgs;
            if (message.MessageResult != null)
            {
                // Format data into a readable format
                JSONInformation chatmessage = JsonUtility.FromJson <JSONInformation>(message.MessageResult.Payload.ToString());

                // Call the function to display the message in plain text
                CreateChat(chatmessage);

                // When a new chat is created, remove the first chat and transform all the messages on the page up
                SyncChat();
            }
        };

        // Subscribe to a PubNub channel to receive messages when they are sent on that channel
        pubnub.Subscribe()
        .Channels(new List <string>()
        {
            channel
        })
        .WithPresence()
        .Execute();
    }
Example #29
0
using PE.Plugins.PubnubChat.Models;

using PubnubApi;

using System;

namespace PE.Plugins.PubnubChat
{
    public enum ChatState
    {
        None,
        Waiting,
        Typing,
        InCall
    }

    public class ChatService : IChatService, IDisposable
    {
        #region Events

        public event InitializationChangedEventHandler InitializedChanged;
        public event EventHandler ConnectedChanged;
        public event EventHandler<MessageEventArgs> MessageReceived;
        public event EventHandler<PresenceEventArgs> ChannelJoined;
        public event EventHandler<PresenceEventArgs> ChannelLeft;
        public event EventHandler<PresenceEventArgs> ChannelTimeout;
        public event EventHandler<PresenceEventArgs> ChannelState;
        public event EventHandler<MessageEventArgs> PublishComplete;

        #endregion Events

        #region Fields

        private Pubnub _Pubnub;

        private readonly string _PublishKey = string.Empty;
        private readonly string _SubscribeKey = string.Empty;

        private SubscribeCallbackExt _ListenerSubscribeCallack;

        private string _UserId = string.Empty;
        private string _AuthKey = string.Empty;
        private bool _Disposed = false;

        private int _FailCount = 0;

        private string _PushData = string.Empty;

        #endregion Fields

        #region Constructors

        public ChatService(ChatConfiguration configuration)
        {
            _PublishKey = configuration.PublishKey;
            _SubscribeKey = configuration.SubscribeKey;
        }

        ~ChatService()
        {
            Dispose();
        }

        #endregion Constructors

        #region Properties

        public bool Connected { get; private set; }

        public bool Initialized { get; private set; } = false;

        #endregion Properties

        #region Init

        public void Initialize(string userId, string authKey = null, bool reset = true, string push = "")
        {
            System.Diagnostics.Debug.WriteLine($"*** {GetType().Name}.Uninitialize - Initializing Chat for user {_UserId}, Reset: {reset}");
            if (reset) _FailCount = 0;
            //  we can only initialize if the user is registered
            if (string.IsNullOrEmpty(userId)) return;
            _UserId = userId;
            _AuthKey = authKey;
            _PushData = push;

            PNConfiguration config = new PNConfiguration();
            config.PublishKey = _PublishKey;
            config.SubscribeKey = _SubscribeKey;
            config.Uuid = _UserId;
            config.Secure = true;
            config.HeartbeatNotificationOption = PNHeartbeatNotificationOption.All;
            if (!string.IsNullOrEmpty(authKey)) config.AuthKey = authKey;

            _Pubnub = new Pubnub(config);

            _ListenerSubscribeCallack = new SubscribeCallbackExt(
                (pubnub, message) => OnMessageReceived(pubnub, message),
                (pubnub, presence) => OnPresenceReceived(pubnub, presence),
                (pubnub, status) => OnStatusReceived(pubnub, status));

            _Pubnub.AddListener(_ListenerSubscribeCallack);

            //  create and subscribe to the lobby channel
            _Pubnub
                .Subscribe<string>()
                .Channels(new string[] { _UserId })
                .WithPresence()
                .Execute();

            //  add push if necessary
            if (!string.IsNullOrEmpty(_PushData))
            {
                var data = _PushData.Split(new char[] { '|' });
                if (data.Length != 2) throw new ArgumentException("Push initialization data.");

                var type = (PNPushType)Enum.Parse(typeof(PNPushType), data[0]);

                _Pubnub.AddPushNotificationsOnChannels()
                    .PushType(type)
                    .Channels(new string[] { _UserId })
                    //.DeviceId(data[1])
                    .DeviceId(data[1])
                    .Async(new AddPushChannelCallback());
                }
            Initialized = true;
            InitializedChanged?.Invoke(Initialized);
        }

        public void Uninitialize()
        {
            //  this can be called before Initialize
            if (_Pubnub == null) return;
            try
            {
                System.Diagnostics.Debug.WriteLine($"*** {GetType().Name}.Uninitialize - Uninitializing Chat for user {_UserId}");
                _Pubnub.RemoveListener(_ListenerSubscribeCallack);
                _Pubnub.Unsubscribe<string>().Channels(new string[] { _UserId }).Execute();
                //  TODO: consider removing push channel association here
                Initialized = false;
                InitializedChanged?.Invoke(Initialized);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"{ GetType().Name}.Uninitialize - Exception: { ex}");
            }
        }

        #endregion Init

        #region Callbacks

        private void OnMessageReceived(Pubnub pubnub, PNMessageResult<object> result)
        {
            try
            {
                MessageReceived?.Invoke(this, new MessageEventArgs(result.Message.ToString()));
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"*** {GetType().Name}.MessageReceived - Unable to deserialize message: { result.Message}\r\n\tException: { ex}");
            }
        }

        private void OnPresenceReceived(Pubnub pubnub, PNPresenceEventResult result)
        {
            System.Diagnostics.Debug.WriteLine($"*** { GetType().Name}.OnPresenceReceived\r\n -> Event: { result.Event}");
            {
                // handle incoming presence data 
                if (result.Event.Equals("join"))
                {
                    RaiseChannelJoined(result.Channel, result.Uuid);
                }
                else if (result.Event.Equals("leave"))
                {
                    RaiseChannelLeft(result.Channel, result.Uuid);
                }
                else if (result.Event.Equals("state-change"))
                {
                    //  listen for status events - eg: typing, etc
                    if ((result.State == null) || (result.State.Count == 0)) return;
                    foreach (var key in result.State.Keys)
                    {
                        var state = (ChatState)Enum.Parse(typeof(ChatState), result.State[key].ToString());
                        RaiseChannelState(result.Channel, result.Uuid, state);
                    }
                }
                else if (result.Event.Equals("timeout"))
                {
                }
                else if (result.Event.Equals("interval"))
                {
                    //  find the ids that have joined
                    if ((result.Join != null) && (result.Join.Length > 0))
                    {
                        foreach (var uuid in result.Join) RaiseChannelJoined(result.Channel, uuid);
                    }
                    if ((result.Leave != null) && (result.Leave.Length > 0))
                    {
                        foreach (var uuid in result.Leave) RaiseChannelJoined(result.Channel, uuid);
                    }
                }
                else if (result.HereNowRefresh)
                {
                    //  TODO: request state for channels
                    //GetState();
                }
            }
        }

        private void OnStatusReceived(Pubnub pubnub, PNStatus status)
        {
            {
                System.Diagnostics.Debug.WriteLine($"*** {GetType().Name}.OnStatusReceived\r\n -> Operation: { status.Operation}\r\n -> Category: { status.Category}\r\n -> Error: { status.Error}\r\n -> Data: { status.ErrorData}\r\n -> Status Code: { status.StatusCode}");

                if (status.Operation == PNOperationType.PNHeartbeatOperation)
                {
                    Connected = !status.Error;
                    ConnectedChanged?.Invoke(this, new EventArgs());
                }

                if ((status.Operation == PNOperationType.PNSubscribeOperation) && (status.Category == PNStatusCategory.PNUnknownCategory) && (status.StatusCode == 404))
                {
                    try
                    {
                        _FailCount++;
                        if (_FailCount > 3)
Example #30
0
        public static async Task ThenWithAsyncSendFileShouldReturnSuccess()
#endif
        {
            server.ClearRequests();

            receivedMessage = false;
            bool receivedEvent = false;

            SubscribeCallbackExt eventListener = new SubscribeCallbackExt(
                delegate(Pubnub pnObj, PNFileEventResult eventResult)
            {
                receivedEvent = true;
                System.Diagnostics.Debug.WriteLine("FILE EVENT: " + pubnub.JsonPluggableLibrary.SerializeToJsonString(eventResult));
            },
                delegate(Pubnub pnObj, PNStatus status)
            {
            }
                );

            PNConfiguration config = new PNConfiguration
            {
                PublishKey   = PubnubCommon.PublishKey,
                SubscribeKey = PubnubCommon.SubscribeKey,
                //CipherKey = "enigma",
                Uuid   = "mytestuuid",
                Secure = false
            };

            if (PubnubCommon.PAMServerSideRun)
            {
                config.SecretKey = PubnubCommon.SecretKey;
            }
            else if (!string.IsNullOrEmpty(authKey) && !PubnubCommon.SuppressAuthKey)
            {
                config.AuthKey = authKey;
            }
            pubnub = createPubNubInstance(config);
            pubnub.AddListener(eventListener);

            mre = new ManualResetEvent(false);
            pubnub.Subscribe <string>().Channels(new string[] { channelName }).Execute();
            mre.WaitOne(2000);

            string expected = "{\"status\": 200, \"message\": \"OK\", \"service\": \"channel-registry\", \"error\": false}";

            mre = new ManualResetEvent(false);

            string fileId   = "";
            string fileName = "";

            receivedMessage = false;
            string targetFileUpload = @"C:\Pandu\pubnub\word_test.txt";
            Dictionary <string, object> myInternalMsg = new Dictionary <string, object>();

            myInternalMsg.Add("color", "red");
            myInternalMsg.Add("name", "John Doe");
#if NET40
            PNResult <PNFileUploadResult> sendFileResult = Task.Factory.StartNew(async() => await pubnub.SendFile().Channel(channelName).File(targetFileUpload).Message(myInternalMsg).ExecuteAsync()).Result.Result;
#else
            PNResult <PNFileUploadResult> sendFileResult = await pubnub.SendFile().Channel(channelName).File(targetFileUpload).Message(myInternalMsg).ExecuteAsync();
#endif
            if (sendFileResult.Result != null && !string.IsNullOrEmpty(sendFileResult.Result.FileId) && sendFileResult.Result.Timetoken > 0)
            {
                System.Diagnostics.Debug.WriteLine("SendFile result = " + pubnub.JsonPluggableLibrary.SerializeToJsonString(sendFileResult.Result));
                fileId          = sendFileResult.Result.FileId;
                fileName        = sendFileResult.Result.FileName;
                receivedMessage = true;
            }

            receivedMessage = false;
            mre             = new ManualResetEvent(false);
            pubnub.ListFiles().Channel(channelName)
            .Execute(new PNListFilesResultExt((result, status) =>
            {
                if (result != null)
                {
                    System.Diagnostics.Debug.WriteLine("ListFiles result = " + pubnub.JsonPluggableLibrary.SerializeToJsonString(result));
                    receivedMessage = true;
                }
                mre.Set();
            }));
            Thread.Sleep(1000);
            mre.WaitOne();


            if (receivedMessage)
            {
                receivedMessage = false;
                mre             = new ManualResetEvent(false);
                pubnub.DownloadFile().Channel(channelName).FileId(fileId).FileName(fileName).Execute(new PNDownloadFileResultExt((result, status) =>
                {
                    if (result != null && result.FileBytes != null && result.FileBytes.Length > 0)
                    {
                        System.Diagnostics.Debug.WriteLine("DownloadFile result = " + result.FileBytes.Length);
                        receivedMessage = true;
                    }
                    mre.Set();
                }));
                mre.WaitOne();
            }

            if (receivedMessage)
            {
                receivedMessage = false;
                mre             = new ManualResetEvent(false);
                pubnub.DeleteFile().Channel(channelName).FileId(fileId).FileName(fileName)
                .Execute(new PNDeleteFileResultExt((result, status) =>
                {
                    if (result != null)
                    {
                        System.Diagnostics.Debug.WriteLine("DeleteFile result = " + pubnub.JsonPluggableLibrary.SerializeToJsonString(result));
                        receivedMessage = true;
                    }
                    mre.Set();
                }));
                Thread.Sleep(1000);
                mre.WaitOne();
            }

            pubnub.Destroy();
            pubnub.PubnubUnitTest = null;
            pubnub = null;
            Assert.IsTrue(receivedMessage && receivedEvent, "WhenFileIsRequested -> ThenWithAsyncSendFileShouldReturnSuccess failed.");
        }