Example #1
0
        public static async Task BayeuxDemoAsync()
        {
            // Create the client settings.
            var endpoint = new Uri("https://localhost:8000/faye");
            var settings = new BayeuxClientSettings(endpoint)
            {
                Logger = new ConsoleLogger()
            };

            // Create the client.
            using (var client = new BayeuxClient(settings))
            {
                // Connect to server.
                await client.Connect();

                var extensions = new Dictionary <string, object>();
                //extensions.Add("access_token", "abc123");
                // Additional extensions can be added as needed

                // Subscribe to channel.
                await client.Subscribe("/test",
                                       message => Console.WriteLine("Message received: {0}", message.Channel),
                                       extensions);
            }
        }
Example #2
0
        public async Task Too_long_connect_delay_causes_unauthorized_error_in_Workspace_API()
        {
            var httpPost =
                new AgentApiHttpPoster(
                    new HttpClientHttpPost(await InitHttpClient()),
                    BaseUrl);

            //var initResponse = await httpClient.PostAsync(
            //    BaseURL + "/workspace/v3/initialize-workspace",
            //    new StringContent(""));
            //initResponse.EnsureSuccessStatusCode();

            var bayeuxClient = new BayeuxClient(new HttpLongPollingTransportOptions()
            {
                HttpPost = httpPost,
                Uri      = BaseUrl + "/workspace/v3/notifications",
            });

            using (bayeuxClient)
            {
                await bayeuxClient.Start();

                await bayeuxClient.Subscribe("/**");

                Thread.Sleep(TimeSpan.FromSeconds(11));
            }
        }
Example #3
0
        public async Task <bool> Run(CancellationToken token)
        {
            try
            {
                // Connect to the Gitter Faye endpoint.
                _bayeux.Connect();

                // Get the current user (the bot).
                var user = await _broker.GetCurrentUser();

                _log.Information("Current user is {0}.", user.Username);

                // Subscribe to rooms.
                var rooms = await _broker.GetRooms();

                foreach (var room in rooms)
                {
                    _bayeux.Subscribe($"/api/v1/rooms/{room.Id}/chatMessages", message => { MessageReceived(user, room, message); });
                    _log.Information("Subscribed to {0} ({1}).", room.Name, room.Id);
                }

                // Subscribe to room events for the current user.
                _bayeux.Subscribe($"/api/v1/user/{user.Id}/rooms", raw =>
                {
                    var envelope = ((JObject)raw.Data).ToObject <Envelope <GitterRoom> >();
                    if (envelope.Operation == null || !envelope.Operation.Equals("create", StringComparison.OrdinalIgnoreCase))
                    {
                        // Subscribe to messages in this channel.
                        var room = envelope.Model.CreateRoom();
                        _bayeux.Subscribe($"/api/v1/rooms/{envelope.Model.Id}/chatMessages", message => { MessageReceived(user, room, message); });
                        _log.Information("Subscribed to {0} ({1}).", room.Name, room.Id);
                    }
                });

                // Wait for disconnect.
                token.WaitHandle.WaitOne(Timeout.Infinite);

                // Don't stop the application.
                return(true);
            }
            finally
            {
                _bayeux.Disconnect();
            }
        }
 public async Task Subscribe_throws_exception_when_not_connected()
 {
     var httpPoster   = new Mock <IHttpPost>();
     var bayeuxClient = new BayeuxClient(new HttpLongPollingTransportOptions()
     {
         HttpPost = httpPoster.Object, Uri = "none"
     });
     await bayeuxClient.Subscribe("dummy");
 }
Example #5
0
        public IObservable <RealtimeUserPresence> SubscribeToUserPresence(string roomId)
        {
            return(Observable.Create <RealtimeUserPresence>(o =>
            {
                _client.Subscribe($"/api/v1/rooms/{roomId}", message =>
                {
                    try
                    {
                        var realtimeUserPresence = JsonConvert.DeserializeObject <RealtimeUserPresence>(message.Data.ToString());
                        o.OnNext(realtimeUserPresence);
                    }
                    catch (Exception e)
                    {
                        var exception = new Exception($"Cannot create object from response {message.Data.ToString()}", e);
                        o.OnError(exception);
                    }
                });

                return () => { };
            }));
        }
Example #6
0
        // response: {"timestamp":1536851691737,"status":500,"error":"Internal Server Error",
        // "message":"java.lang.IllegalArgumentException: Invalid channel id: pepe",
        // "path":"/statistics/v3/notifications"}
        public async Task Subscribe_invalid_channel_id()
        {
            var httpClient = await InitHttpClient();

            var bayeuxClient = new BayeuxClient(new HttpLongPollingTransportOptions()
            {
                HttpClient = httpClient,
                Uri        = BaseUrl + "/statistics/v3/notifications",
            });
            await bayeuxClient.Start();

            await bayeuxClient.Subscribe("pepe");
        }
Example #7
0
        public static void Main(string[] args)
        {
            // Create the client settings.
            var endpoint = new Uri("http://localhost:8000/faye");
            var settings = new BayeuxClientSettings(endpoint)
            {
                Logger = new ConsoleLogger()
            };

            // Create the client.
            using (var client = new BayeuxClient(settings))
            {
                // Connect to server.
                client.Connect();

                // Subscribe to channel.
                client.Subscribe("/test", message => Console.WriteLine("Message received: {0}", message.Channel));

                // Wait for exit.
                Console.WriteLine("Press ANY key to quit.");
                Console.ReadKey(true);
            }
        }
        protected override async Task StartImplAsync(UpdateResult result, CancellationToken cancellationToken)
        {
            httpClient.DefaultRequestHeaders.Remove("x-api-key");
            httpClient.DefaultRequestHeaders.Add("x-api-key", ApiKey);

            var token = await AuthApi.Authenticate(httpClient, ApiBaseUrl, new AuthApi.PasswordGrantTypeCredentials()
            {
                ClientId     = ClientId,
                ClientSecret = ClientSecret,
                UserName     = UserName,
                Password     = Password,
            }); // TODO: missing cancellationToken as a parameter here

            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            var initResponse = await PostAsync("/workspace/v3/initialize-workspace", null, cancellationToken);

            bayeuxClient = new BayeuxClient(new HttpLongPollingTransportOptions()
            {
                HttpClient = httpClient,
                Uri        = ApiBaseUrl + "/workspace/v3/notifications"
            });

            bayeuxClient.EventReceived += (e, args) =>
            {
                Debug.WriteLine($"Event received on channel {args.Channel} with data\n{args.Data}");
                UpdateTree(result2 =>
                           result2.MessageToChildren = args);
            };

            bayeuxClient.ConnectionStateChanged += (e, args) =>
                                                   Debug.WriteLine($"Bayeux connection state changed to {args.ConnectionState}");

            await bayeuxClient.Start(cancellationToken);

            await bayeuxClient.Subscribe("/**", cancellationToken);
        }
Example #9
0
        public static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();

            Console.WriteLine("1 - subscribe to channel");
            Console.WriteLine("q - unsubscribe from channel");
            Console.WriteLine("2 - subscribe to channel");
            Console.WriteLine("w - unsubscribe from channel");
            Console.WriteLine("x - exit");
            Console.WriteLine("");
            Console.WriteLine("");

            ServerEndpoint = new Uri(args [0]);

            BayeuxClient client = new BayeuxClient(ServerEndpoint);

            client.DataReceived += (object sender, BayeuxClient.DataReceivedEventArgs e) => {
                if (e.Data.ContainsKey("color"))
                {
                    Console.WriteLine("Received color : " + e.Data ["color"]);
                }
                else if (e.Data.ContainsKey("status"))
                {
                    Console.WriteLine("Received status : " + e.Data ["status"]);
                }
                else
                {
                    Console.WriteLine("Received unknown message");
                }
            };

            client.Subscribe("/devices/51251481d988b43c45000002");
            client.Connect();

            ConsoleKeyInfo key = Console.ReadKey();

            while (key.KeyChar != 'x')
            {
                if (key.KeyChar == '1')
                {
                    client.Subscribe("/devices/51251481d988b43c45000002");
                }

                if (key.KeyChar == 'q')
                {
                    client.Unsubscribe("/devices/51251481d988b43c45000002");
                }

                if (key.KeyChar == '2')
                {
                    client.Subscribe("/devices/512518fcd988b43c45000003");
                }

                if (key.KeyChar == 'w')
                {
                    client.Unsubscribe("/devices/512518fcd988b43c45000003");
                }

                if (key.KeyChar == '*')
                {
                    client.Subscribe("/dees/*");
                }

                if (key.KeyChar == 'i')
                {
                    client.Unsubscribe("/devices/*");
                }

                key = Console.ReadKey();
            }

            client.Disconnect();
            Console.WriteLine("Waiting to disconnect");
            client.WaitFor(BayeuxClient.ClientStateEnum.Disconnected);
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }