public async Task Run()
        {
            var factory = new ConnectionFactory {
                HostName = _rabbitOptions.Host, Port = _rabbitOptions.Port
            };

            _connection = factory.CreateConnection();
            _channel    = _connection.CreateModel();

            _channel.ExchangeDeclare(_rabbitOptions.ExchangeName, ExchangeType.Topic);


            CreateQueueConsumer("notifications.broadcast", (sender, args) =>
            {
                var content = Encoding.UTF8.GetString(args.Body.ToArray());

                OnNotificationReceived?.Invoke(this,
                                               new NotificationReceivedEventArgs(NotificationType.Broadcast, content));
            });

            CreateQueueConsumer("notifications.direct", (sender, args) =>
            {
                var content = Encoding.UTF8.GetString(args.Body.ToArray());

                OnNotificationReceived?.Invoke(this,
                                               new NotificationReceivedEventArgs(NotificationType.Direct, content));
            });

            await Task.Yield();
        }
        private void OnPushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args)
        {
            Dictionary <string, object> data = new Dictionary <string, object>();

            if (args.NotificationType == PushNotificationType.Raw)
            {
                foreach (var pair in JsonConvert.DeserializeObject <Dictionary <string, string> >(args.RawNotification.Content))
                {
                    data.Add(pair.Key, pair.Value);
                }
            }
            else if (args.NotificationType == PushNotificationType.Toast)
            {
                foreach (XmlAttribute attribute in args.ToastNotification.Content.DocumentElement.Attributes)
                {
                    data.Add(attribute.Name, attribute.Value);
                }
            }
            else if (args.NotificationType == PushNotificationType.Tile || args.NotificationType == PushNotificationType.TileFlyout)
            {
                foreach (XmlAttribute attribute in args.TileNotification.Content.DocumentElement.Attributes)
                {
                    data.Add(attribute.Name, attribute.Value);
                }
            }

            OnNotificationReceived?.Invoke(CrossPushNotification.Current, new PushNotificationDataEventArgs(data));

            CrossPushNotification.Current.NotificationHandler?.OnReceived(data);
        }
Ejemplo n.º 3
0
        private async Task HandleMessageReceived(MessageBase message)
        {
            if (message.Id.HasValue)
            {
                var id = message.Id.Value;
                TaskCompletionSource <MessageBase> pendingInvocationTcs;
                lock (_pendingInvocationsLock)
                {
                    _pendingInvocations.TryGetValue(id, out pendingInvocationTcs);
                }

                if (pendingInvocationTcs != null)
                {
                    lock (_pendingInvocationsLock)
                    {
                        _pendingInvocations.Remove(id);
                    }

                    pendingInvocationTcs.SetResult(message);
                }
                else
                {
                    Console.WriteLine("WARNING: V8DebugClient received message with no corresponding pending invocation. ID: " + id);
                }
            }
            else
            {
                // Since this message doesn't correspond to any invocation, just pass it
                // upstream to the consumer of the client
                await OnNotificationReceived?.Invoke(message);
            }
        }
Ejemplo n.º 4
0
        public ZeroMqNotificationReader Init()
        {
            if (Initialized)
            {
                throw new InvalidOperationException($"{nameof(ZeroMqNotificationReader)} already initialized.");
            }

            var completionSource = new TaskCompletionSource <object>();
            var token            = _source.Token;

            _receiveTask = Task.Factory.StartNew(() =>
            {
                var timeout = TimeSpan.FromSeconds(1);

                using (var subSocket = new SubscriberSocket(EndPoint))
                {
                    try
                    {
                        subSocket.Options.ReceiveHighWatermark = 1000;
                        subSocket.SubscribeToAnyTopic();

                        while (!token.IsCancellationRequested)
                        {
                            var zMessage        = new NetMQMessage(2);
                            var messageReceived = subSocket.TryReceiveMultipartMessage(timeout, ref zMessage, 2);
                            completionSource.TrySetResult(null);

                            if (!messageReceived)
                            {
                                continue;
                            }

                            var topic = zMessage.Pop().ConvertToString(Encoding.UTF8);
                            var json  = zMessage.Pop().ConvertToString(Encoding.UTF8);

                            OnNotificationReceived?.Invoke(topic, json);
                        }
                    }
                    catch (Exception e)
                    {
                        OnError?.Invoke(e);
                    }
                }
            }, TaskCreationOptions.LongRunning);

            _receiveTask.ContinueWith(t =>
            {
                // Propagate exception from initialization if occured
                if (t.Exception != null)
                {
                    completionSource.TrySetException(t.Exception);
                }
            });

            completionSource.Task.GetAwaiter().GetResult();

            Initialized = true;
            return(this);
        }
Ejemplo n.º 5
0
        private async void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (Authenticated)
            {
                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Add("Authorization", AuthToken);

                var response = await client.GetAsync($"https://vrchat.com/api/1/auth/user/notifications?apiKey={GlobalVars.ApiKey}");

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var resp = JsonConvert.DeserializeObject <List <NotificationResponse> >(await response.Content.ReadAsStringAsync());

                    foreach (var res in resp)
                    {
                        double result = DateTime.Now.Subtract(res.created_at).TotalSeconds;

                        var amount = Math.Round(result, 0);

                        if (amount < 200)
                        {
                            switch (res.type.Convert())
                            {
                            default:
                                OnNotificationReceived?.Invoke(this, new NotificationEventArgs(res.type.Convert(), res.message, this.GetAPIUserByID(res.senderUserId).Result));
                                break;

                            case NotificationType.friendRequest:
                                OnFriendshipRequestReceived?.Invoke(this, new NotificationEventArgs(res.type.Convert(), res.message, this.GetAPIUserByID(res.senderUserId).Result));
                                break;

                            case NotificationType.invite:
                                OnInviteReceived?.Invoke(this, new NotificationEventArgs(res.type.Convert(), res.message, this.GetAPIUserByID(res.senderUserId).Result));
                                break;

                            case NotificationType.requestInvite:
                                OnRequestInvite?.Invoke(this, new NotificationEventArgs(res.type.Convert(), res.message, this.GetAPIUserByID(res.senderUserId).Result));
                                break;
                            }
                        }
                    }
                }
            }
        }
 public void NotificationReceived(NotificationInfo notificationInfo)
 {
     OnNotificationReceived?.Invoke(null, notificationInfo);
 }
Ejemplo n.º 7
0
 internal void NotifyReceived(NotificationEventArgs e)
 {
     OnNotificationReceived?.Invoke(this, e);
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Watch for device responses and notifications
        /// </summary>
        /// <returns></returns>
        private async Task Watch()
        {
            await Task.Factory.StartNew(async() =>
            {
                //while device is connected
                while (_tcpClient != null)
                {
                    lock (_syncLock)
                    {
                        if (_tcpClient != null)
                        {
                            //automatic re-connection
                            if (!_tcpClient.IsConnected())
                            {
                                _tcpClient.ConnectAsync(Hostname, Port).Wait();
                            }

                            if (_tcpClient.IsConnected())
                            {
                                //there is data avaiblable in the pipe
                                if (_tcpClient.Client.Available > 0)
                                {
                                    byte[] bytes = new byte[_tcpClient.Client.Available];

                                    //read datas
                                    _tcpClient.Client.Receive(bytes);

                                    try
                                    {
                                        string datas = Encoding.UTF8.GetString(bytes);
                                        if (!string.IsNullOrEmpty(datas))
                                        {
                                            //get every messages in the pipe
                                            foreach (string entry in datas.Split(new string[] { Constants.LineSeparator },
                                                                                 StringSplitOptions.RemoveEmptyEntries))
                                            {
                                                CommandResult commandResult =
                                                    JsonConvert.DeserializeObject <CommandResult>(entry, Constants.DeviceSerializerSettings);
                                                if (commandResult != null && commandResult.Id != 0)
                                                {
                                                    ICommandResultHandler commandResultHandler;
                                                    lock (_currentCommandResults)
                                                    {
                                                        commandResultHandler = _currentCommandResults[commandResult.Id];
                                                    }

                                                    if (commandResult.Error == null)
                                                    {
                                                        commandResult = (CommandResult)JsonConvert.DeserializeObject(entry, commandResultHandler.ResultType, Constants.DeviceSerializerSettings);
                                                        commandResultHandler.SetResult(commandResult);
                                                    }
                                                    else
                                                    {
                                                        commandResultHandler.SetError(commandResult.Error);
                                                    }
                                                }
                                                else
                                                {
                                                    NotificationResult notificationResult =
                                                        JsonConvert.DeserializeObject <NotificationResult>(entry,
                                                                                                           Constants.DeviceSerializerSettings);

                                                    if (notificationResult != null && notificationResult.Method != null)
                                                    {
                                                        if (notificationResult.Params != null)
                                                        {
                                                            //save properties
                                                            foreach (KeyValuePair <PROPERTIES, object> property in
                                                                     notificationResult.Params)
                                                            {
                                                                this[property.Key] = property.Value;
                                                            }
                                                        }

                                                        //notification result
                                                        OnNotificationReceived?.Invoke(this,
                                                                                       new NotificationReceivedEventArgs(notificationResult));
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        OnError?.Invoke(this, new UnhandledExceptionEventArgs(ex, false));
                                    }
                                }
                            }
                        }
                    }

                    await Task.Delay(100);
                }
            }, TaskCreationOptions.LongRunning);
        }
Ejemplo n.º 9
0
 protected virtual void OnNotificationReceivedEvent(NotificationEventArgs args) =>
 OnNotificationReceived?.Invoke(this, args);
Ejemplo n.º 10
0
        /// <summary>
        /// Watch for device responses and notifications
        /// </summary>
        /// <returns></returns>
        private async Task Watch()
        {
            await Task.Factory.StartNew(async() =>
            {
                //while device is connected
                while (_tcpClient != null)
                {
                    lock (_syncLock)
                    {
                        //there is data avaiblable in the pipe
                        if (_tcpClient.Client.Available > 0)
                        {
                            byte[] bytes = new byte[_tcpClient.Client.Available];

                            //read datas
                            _tcpClient.Client.Receive(bytes);

                            try
                            {
                                string datas = Encoding.UTF8.GetString(bytes);
                                if (!string.IsNullOrEmpty(datas))
                                {
                                    //get every messages in the pipe
                                    foreach (string entry in datas.Split(new string[] { Constantes.LineSeparator }, StringSplitOptions.RemoveEmptyEntries))
                                    {
                                        CommandResult commandResult = JsonConvert.DeserializeObject <CommandResult>(entry, _serializerSettings);

                                        if (commandResult != null && commandResult.Result != null)
                                        {
                                            //command result
                                            _currentCommandResults[commandResult.Id] = commandResult;
                                        }
                                        else if (commandResult != null && commandResult.Error != null)
                                        {
                                            //error result
                                            OnCommandError?.Invoke(this, new CommandErrorEventArgs(commandResult.Error));
                                        }
                                        else
                                        {
                                            NotificationResult notificationResult = JsonConvert.DeserializeObject <NotificationResult>(entry, _serializerSettings);

                                            if (notificationResult != null && notificationResult.Method != null)
                                            {
                                                if (notificationResult.Params != null)
                                                {
                                                    //save properties
                                                    foreach (KeyValuePair <PROPERTIES, object> property in notificationResult.Params)
                                                    {
                                                        this[property.Key] = property.Value;
                                                    }
                                                }

                                                //notification result
                                                OnNotificationReceived?.Invoke(this, new NotificationReceivedEventArgs(notificationResult));
                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine($"Error while reading through pipe : {ex.Message}");
                            }
                        }
                    }
                    await Task.Delay(100);
                }
            }, TaskCreationOptions.LongRunning);
        }