internal async Task WhenStateMachineIsInitialised_And_LocalDeviceIdIsEmpty_But_StateMachineState_is_loaded_ShouldResetLocalDevice_And_StateMachineState() { // Arrange const string initialClientId = "123"; var options = new ClientOptions(ValidKey) { TransportFactory = new FakeTransportFactory(), SkipInternetCheck = true, ClientId = initialClientId }; var mobileDevice = new FakeMobileDevice(); var setupRealtime = new AblyRealtime(options, mobileDevice: mobileDevice); setupRealtime.Push.InitialiseStateMachine(); setupRealtime.Push.StateMachine.CurrentState = new ActivationStateMachine.WaitingForNewPushDeviceDetails(setupRealtime.Push.StateMachine); setupRealtime.Push.StateMachine.PendingEvents.Enqueue(new ActivationStateMachine.CalledActivate()); setupRealtime.Push.StateMachine.PersistState(); var testRealtime = new AblyRealtime(options, mobileDevice: mobileDevice); // We let the RestClient create the local device. testRealtime.RestClient.Device.Id = null; testRealtime.Push.InitialiseStateMachine(); var stateMachine = testRealtime.Push.StateMachine; stateMachine.CurrentState.Should().BeOfType <ActivationStateMachine.NotActivated>(); stateMachine.PendingEvents.Should().BeEmpty(); stateMachine.LocalDevice.Id.Should().NotBeEmpty(); stateMachine.LocalDevice.DeviceSecret.Should().NotBeEmpty(); }
private async Task CloseAndWaitToReconnect(AblyRealtime client, ProtocolMessage protocolMessage = null) { protocolMessage = protocolMessage ?? new ProtocolMessage(ProtocolMessage.MessageAction.Connected); LastCreatedTransport.Listener.OnTransportEvent(TransportState.Closed); await new ConnectionAwaiter(client.Connection, ConnectionState.Connecting).Wait(); await client.FakeProtocolMessageReceived(protocolMessage); }
static void Main(string[] args) { Console.WriteLine("Hello World!"); var options = new ClientOptions { AuthCallback = async tokenParams => { return(await GetTokenRequestStringFromYourServer()); // or return a TokenDetails object // return await GetTokenDetailsFromYourServer(); } }; var client = new AblyRealtime(options); client.Connection.Once(ConnectionState.Connected, change => { Console.WriteLine("connected"); }); client.Connection.On(x => { Console.WriteLine(x.Reason.ToString()); }); Console.ReadLine(); }
private async void Subscribe_Click(object sender, RoutedEventArgs e) { string channelName = this.channelBox.Text.Trim(); if (string.IsNullOrEmpty(channelName)) { return; } string key = RealtimeChat.Properties.Settings.Default.ApiKey; string clientId = RealtimeChat.Properties.Settings.Default.ClientId; var options = new ClientOptions(key) { UseBinaryProtocol = true, Tls = true, AutoConnect = false, ClientId = clientId }; this.client = new AblyRealtime(options); this.client.Connection.ConnectionStateChanged += this.connection_ConnectionStateChanged; this.client.Connect(); this.channel = this.client.Channels.Get(channelName); this.channel.StateChanged += channel_ChannelStateChanged; this.channel.Subscribe(Handler); this.channel.Presence.Subscribe(Presence_MessageReceived); await channel.AttachAsync(); await channel.Presence.EnterAsync(new PresenceData() { Data = new [] { "data1", "data2" } }); }
public void TestCanConnectToAbly() { // Act bool result = AblyRealtime.CanConnectToAbly(); Assert.True(result); }
public AblySession(EventHandler <string> handler, string publicAddress) { _ably = new AblyRealtime("NYAqNA.AD_snA:CgTo0xPWXieVEH-h"); _handlers = new List <EventHandler <string> >(); _handlers.Add(handler); _publicAddress = publicAddress; }
private void Subscribe_Click(object sender, RoutedEventArgs e) { string channelName = this.channelBox.Text.Trim(); if (string.IsNullOrEmpty(channelName)) { return; } string key = RealtimeChat.Properties.Settings.Default.ApiKey; string clientId = RealtimeChat.Properties.Settings.Default.ClientId; AblyRealtimeOptions options = new AblyRealtimeOptions(key) { UseBinaryProtocol = false, Tls = true, AutoConnect = false, ClientId = clientId }; this.client = new AblyRealtime(options); this.client.Connection.ConnectionStateChanged += this.connection_ConnectionStateChanged; this.client.Connect(); this.channel = this.client.Channels.Get(channelName); this.channel.ChannelStateChanged += channel_ChannelStateChanged; this.channel.MessageReceived += this.channel_MessageReceived; this.channel.Presence.MessageReceived += this.Presence_MessageReceived; this.channel.Attach(); this.channel.Presence.Enter(null, null); }
internal RealtimeChannels(AblyRealtime realtimeClient, Connection connection, IMobileDevice mobileDevice = null) { _realtimeClient = realtimeClient; Logger = realtimeClient.Logger; connection.InternalStateChanged += ConnectionStateChange; _mobileDevice = mobileDevice; }
public async Task EncryptionExample2() { var @params = Crypto.GetDefaultParams(); ChannelOptions options = new ChannelOptions(@params); var realtime = new AblyRealtime("{{API_KEY}}"); var channel = realtime.Channels.Get("{{RANDOM_CHANNEL_NAME}}", options); }
public async Task WhenConnectedMessageContainsClientId_AuthClientIdShouldBeTheSame() { // Arrange var options = new ClientOptions(ValidKey) { TransportFactory = new FakeTransportFactory(), SkipInternetCheck = true }; var mobileDevice = new FakeMobileDevice(); var realtime = new AblyRealtime(options, mobileDevice: mobileDevice); const string newClientId = "testId"; var localDevice = realtime.Device; localDevice.ClientId.Should().BeNull(); // Act realtime.FakeProtocolMessageReceived(new ProtocolMessage(ProtocolMessage.MessageAction.Connected) { ConnectionDetails = new ConnectionDetails { ClientId = newClientId }, }); await realtime.WaitForState(ConnectionState.Connected); // Assert realtime.Auth.ClientId.Should().Be(newClientId); localDevice.ClientId.Should().Be(newClientId); mobileDevice.GetPreference(PersistKeys.Device.ClientId, PersistKeys.Device.SharedName).Should().Be(newClientId); }
public async Task HistoryExample2() { var realtime = new AblyRealtime("{{API_KEY}}"); var channel = realtime.Channels.Get("{{RANDOM_CHANNEL_NAME}}"); await channel.AttachAsync(); PaginatedResult <Message> resultPage = await channel.HistoryAsync(untilAttach : true); Message lastMessage = resultPage.Items[0]; Console.WriteLine("Last message before attach: " + lastMessage.Data); //Part of the _paginated_result sample PaginatedResult <Message> firstPage = await channel.HistoryAsync(null); Message firstMessage = firstPage.Items[0]; Console.WriteLine("Page 0 item 0: " + firstMessage.Data); if (firstPage.HasNext) { var nextPage = await firstPage.NextAsync(); Console.WriteLine("Page 1 item 1:" + nextPage.Items[1].Data); Console.WriteLine("More pages?: " + nextPage.HasNext); } }
public async Task <bool> InitializeAsync() { var task = new TaskCompletionSource <bool>(); _client = new AblyRealtime(new ClientOptions() { Key = AblyApiKey, EchoMessages = false // prevent messages the client sends echoing back }); _client.Connection.On(args => { if (args.Current == IO.Ably.Realtime.ConnectionState.Connected) { // channels don't get automatically reattached // if the connection drop, so do that manually foreach (var channel in _client.Channels) { channel.Attach(); } _channel = _client.Channels.Get("general"); _channel.Subscribe(MessageEvent, (IO.Ably.Message msg) => { Console.WriteLine(msg.ClientId); }); task.SetResult(true); } if (args.Current == IO.Ably.Realtime.ConnectionState.Disconnected) { _client.Connect(); } }); return(await task.Task.ConfigureAwait(false)); }
public async Task UsingWebsocket4NetTransport() { var options = new ClientOptions(); options.TransportFactory = new WebSocketTransport.WebSocketTransportFactory(); var client = new AblyRealtime(options); }
internal Connection(AblyRealtime realtimeClient, Func <DateTimeOffset> nowFunc, ILogger logger = null) : base(logger) { Now = nowFunc; FallbackHosts = realtimeClient?.Options?.FallbackHosts.Shuffle().ToList(); RealtimeClient = realtimeClient; RegisterWithOSNetworkStateEvents(HandleNetworkStateChange); }
private void SendLeaveMessageAfterFirstSyncMessageReceived(AblyRealtime client, string clientId) { var transport = client.GetTestTransport(); int syncMessageCount = 0; transport.AfterDataReceived = message => { if (message.Action == ProtocolMessage.MessageAction.Sync) { syncMessageCount++; if (syncMessageCount == 1) { var leaveMessage = new ProtocolMessage(ProtocolMessage.MessageAction.Presence, _channelName) { Presence = new[] { new PresenceMessage(PresenceAction.Leave, clientId) { ConnectionId = $"{client.Connection.Id}", Id = $"{client.Connection.Id}-#{clientId}:0", Timestamp = Config.Now(), } } }; transport.FakeReceivedMessage(leaveMessage); } } }; }
public AblyClientService(IConfiguration _configuration) { var realtime = new AblyRealtime(_configuration.GetValue <string>("ably")); realtime.Connect(); Client = realtime; }
public async Task EncryptionExample3() { var realtime = new AblyRealtime("{{API_KEY}}"); byte[] key = Crypto.GenerateRandomKey(keyLength: 128); ChannelOptions options = new ChannelOptions(key); var channel = realtime.Channels.Get("{{RANDOM_CHANNEL_NAME}}", options); }
public void ChannelSample3() { AblyRealtime realtime = new AblyRealtime("{{API_KEY}}"); var channel = realtime.Channels.Get("chatroom"); channel.Subscribe(message => Console.WriteLine("Message received:" + message.Data)); channel.Publish("action", "boom"); }
public void InitializeClient() { // If you do not have an API key, [sign up for a free API key now](ht tps://www.ably.io/signup) var realtimeBasic = new AblyRealtime(PlaceholderKey); var realtimeToken = new AblyRealtime(new ClientOptions { Token = "token" }); }
public static void EncryptionExample3() { var realtime = new AblyRealtime("{{API_KEY}}"); byte[] key = Crypto.GenerateRandomKey(128); var options = new ChannelOptions(key); var channel = realtime.Channels.Get("{{RANDOM_CHANNEL_NAME}}", options); }
internal Connection(AblyRealtime realtimeClient, Func <DateTimeOffset> nowFunc, ILogger logger = null) : base(logger) { Now = nowFunc; RealtimeClient = realtimeClient; RegisterWithOsNetworkStateEvents(HandleNetworkStateChange); }
private static async Task WaitForConnectingOrSuspended(AblyRealtime client) { await Task.WhenAll( new ConnectionAwaiter(client.Connection, ConnectionState.Connecting, ConnectionState.Suspended).Wait (), Task.Delay(10)); }
public static void FakeMessageReceived(this AblyRealtime client, Message message, string channel = null) { client.FakeProtocolMessageReceived( new ProtocolMessage(ProtocolMessage.MessageAction.Message) { Messages = new[] { message }, Channel = channel }); }
public void UsesSameClientOptionsAsRestClient() { var options = new ClientOptions(ValidKey); var client = new AblyRealtime(options); client.Options.Should().BeSameAs(client.RestClient.Options); }
internal Connection(AblyRealtime realtimeClient, Func <DateTimeOffset> nowFunc, ILogger logger = null) : base(logger) { Now = nowFunc; Logger = logger ?? IO.Ably.DefaultLogger.LoggerInstance; FallbackHosts = Defaults.FallbackHosts.Shuffle().ToList(); RealtimeClient = realtimeClient; RegisterWithOSNetworkStateEvents(HandleNetworkStateChange); }
internal async Task WhenClientIdChangesAfterRegisteringDevice_StateMachineShouldReceive_GotPushDeviceDetailsEvent() { // Arrange const string newClientId = "testId"; var options = new ClientOptions(ValidKey) { TransportFactory = new FakeTransportFactory(), SkipInternetCheck = true }; var mobileDevice = new FakeMobileDevice(); async Task <AblyResponse> HandleRequestFunc(AblyRequest request) { if (request.Url.Contains("/push/deviceRegistrations")) { return(new AblyResponse() { TextResponse = JObject.FromObject(new { clientId = newClientId, deviceIdentityToken = new { token = "token" } }).ToString() }); } return(new AblyResponse() { TextResponse = "{}" }); } var realtime = new AblyRealtime(options, (clientOptions, device) => GetRestClient(HandleRequestFunc, options, device), mobileDevice); // Setup the local device var localDevice = PushTestHelpers.GetRegisteredLocalDevice(realtime.RestClient); realtime.RestClient.Device = localDevice; localDevice.ClientId.Should().BeNull(); realtime.Push.InitialiseStateMachine(); var taskAwaiter = new TaskCompletionAwaiter(); var stateMachine = realtime.Push.StateMachine; stateMachine.CurrentState = new ActivationStateMachine.WaitingForPushDeviceDetails(stateMachine); // We trigger the GotPushDeviceDetails event await stateMachine.HandleEvent(new ActivationStateMachine.GotPushDeviceDetails()); // From here we expect the stateMachine to move to WaitingForDeviceRegistration and try to register the Device // The registration will hit our mocked rest client above and return a localDevice with a new clientId. // Once the clientId is received we should expect to receive GotPushDeviceDetails event and the new clientId to be persisted realtime.Push.StateMachine.ProcessingEventCallback = @event => { // Check we received the correct event @event.Should().BeOfType <ActivationStateMachine.GotPushDeviceDetails>(); taskAwaiter.Done(); }; (await taskAwaiter).Should().BeTrue(); mobileDevice.GetPreference(PersistKeys.Device.ClientId, PersistKeys.Device.SharedName).Should().Be(newClientId); }
internal AblyRealtime GetRealtimeClient(ClientOptions options = null, Func <AblyRequest, Task <AblyResponse> > handleRequestFunc = null, IMobileDevice mobileDevice = null) { var clientOptions = options ?? new ClientOptions(ValidKey); clientOptions.SkipInternetCheck = true; // This is for the Unit tests var client = new AblyRealtime(clientOptions, (opts, device) => GetRestClient(handleRequestFunc, clientOptions, device), mobileDevice); return(client); }
/// <summary> /// Initialises the Apple MobileDevice implementation and the AblyRealtime client that is used to subscribe to the Apple notification service. /// Use this method to initialise your AblyRealtime if you want to register the device for push notifications. /// </summary> /// <param name="ablyClientOptions">ClientOptions used to initialise the AblyRealtime instanced used to setup the ActivationStat.</param> /// <param name="callbacks">Optional callbacks class. It's especially useful to subscribe/unsubscribe to push channels when a device is activated / deactivated.</param> /// <returns>Initialised Ably instance which supports push notification registrations.</returns> public static IRealtimeClient Initialise(ClientOptions ablyClientOptions, PushCallbacks callbacks = null) { var mobileDevice = new AppleMobileDevice(callbacks, DefaultLogger.LoggerInstance); IoC.MobileDevice = mobileDevice; _realtimeInstance = new AblyRealtime(ablyClientOptions, mobileDevice); _realtimeInstance.Push.InitialiseStateMachine(); return(_realtimeInstance); }
public static Task FakeMessageReceived(this AblyRealtime client, Message message, string channel = null) { return (client.ConnectionManager.OnTransportMessageReceived( new ProtocolMessage(ProtocolMessage.MessageAction.Message) { Messages = new[] { message }, Channel = channel })); }
private void InitializeAbly() { _clientOptions = new ClientOptions { Key = _apiKey, // this will disable the library trying to subscribe to network state notifications AutomaticNetworkStateMonitoring = false, AutoConnect = false, // this will make sure to post callbacks on UnitySynchronization Context Main Thread CustomContext = SynchronizationContext.Current }; _ably = new AblyRealtime(_clientOptions); _ably.Connection.On(args => { LogAndDisplay($"Connection State is <b>{args.Current}</b>"); _connectionStatus.GetComponentInChildren <Text>().text = args.Current.ToString(); var connectionStatusBtnImage = _connectionStatus.GetComponent <Image>(); switch (args.Current) { case ConnectionState.Initialized: connectionStatusBtnImage.color = Color.white; break; case ConnectionState.Connecting: connectionStatusBtnImage.color = Color.gray; break; case ConnectionState.Connected: connectionStatusBtnImage.color = Color.green; break; case ConnectionState.Disconnected: connectionStatusBtnImage.color = Color.yellow; break; case ConnectionState.Closing: connectionStatusBtnImage.color = Color.yellow; break; case ConnectionState.Closed: case ConnectionState.Failed: case ConnectionState.Suspended: connectionStatusBtnImage.color = Color.red; break; default: throw new ArgumentOutOfRangeException(); } _isConnected = args.Current == ConnectionState.Connected; _ablyChannelUiConsole.EnableUiComponents(_isConnected); _ablyPresenceUiConsole.EnableUiComponents(_isConnected); _connectButton.GetComponentInChildren <Text>().text = _isConnected ? "Disconnect" : "Connect"; }); }