Пример #1
0
        public void HandlesValidChannelJoined()
        {
            var channels = new List <Channel>
            {
                new Channel {
                    Id = "CHANID1", IsMember = false
                },
                new Channel {
                    Id = "CHANID2", IsMember = true
                }
            };

            var mockState = SetupChannelsMock(channels);

            var message = new ChannelJoined
            {
                Type    = EventType.ChannelJoined,
                Channel = new Channel {
                    Id = "CHANID1", IsMember = true
                }
            };

            RunHandler(message, mockState);

            Assert.True(channels.All(c => c.IsMember));
        }
Пример #2
0
        private async Task IrcMessageReceived(object sender, IrcMessageRecievedEventArgs e)
        {
            //Console.WriteLine($"{e.Prefix,-64}{e.Command,-16}{e.Parameters}");
            switch (e.Command)
            {
            case "001":
                Connected?.Invoke(this);
                break;

            case "PING":
                await ircClient.SendIrcMessage("PONG :tmi.twitch.tv");

                break;

            case "PRIVMSG":
                ChatMessageReceived?.Invoke(this, new ChatMessageReceivedEventArgs(this, e.Prefix, e.Parameters));
                break;

            case "JOIN":
                TwitchChannel channel = new TwitchChannel(e.Parameters.Replace("#", null), this);
                joinedChannels.Add(channel);
                ChannelJoined?.Invoke(this, new ChannelJoinedEventArgs(channel));
                break;
            }
        }
Пример #3
0
 private void _tcc1_ChatterChanged(object sender, TwitchChatChatterChangedEventArgs e)
 {
     if (!e.HasParted && e.Username == e.ClientCredentials.Username)
     {
         ChannelJoined?.Invoke(this, new ChatConnectionChannelJoinedEventArgs(_botaccount, _channel));
     }
 }
Пример #4
0
        void JoinChannel(string channelname)
        {
            ChatChannel channel = new ChatChannel(channelname, this);

            lock (channellock)
                channels[channelname] = channel;
            ChannelJoined?.Invoke(channel);
        }
Пример #5
0
        private void ChannelJoined(ChannelJoined message)
        {
            var createdMessage = new ChannelCreated
            {
                Channel = message.Channel
            };

            ChannelCreated(createdMessage);
        }
Пример #6
0
        void LocalUser_JoinedChannel(object sender, IrcChannelEventArgs e)
        {
            e.Channel.MessageReceived += SpeedRunsLive_MessageReceived;

            if (e.Channel == RaceChannel)
            {
                e.Channel.ModesChanged      += RaiseUserListRefreshed;
                e.Channel.UserJoined        += RaiseUserListRefreshed;
                e.Channel.UserKicked        += RaiseUserListRefreshed;
                e.Channel.UserLeft          += RaiseUserListRefreshed;
                e.Channel.UsersListReceived += RaiseUserListRefreshed;
                e.Channel.UsersListReceived += Channel_UsersListReceived;
                RaceChannel.TopicChanged    += RaceChannel_TopicChanged;
                RaceChannel.UserKicked      += RaceChannel_UserKicked;
            }

            if (e.Channel == LiveSplitChannel)
            {
                e.Channel.UsersListReceived += Channel_UsersListReceived;
            }

            ChannelJoined?.Invoke(this, e.Channel.Name);
        }
Пример #7
0
 internal void RaiseChannelJoined(KgsChannel channel)
 {
     ChannelJoined?.Invoke(channel);
 }
Пример #8
0
 private void HandleChannelJoinedEvent(string channelName)
 {
     ChannelJoined?.Invoke(this, new ChannelJoinedEventArgs {
         ChannelName = channelName
     });
 }
Пример #9
0
 public void OnChannelJoined(ChannelJoined callback)
 {
     channelJoined = callback;
 }
Пример #10
0
 protected virtual void OnChannelJoined(TmiMessage msg)
 {
     ChannelJoined?.Invoke(this, new ChannelConnectionChangedEventArgs(msg.Parameters[0]));
 }
Пример #11
0
 private void RaiseChannelJoined(string channel, string uuid)
 {
     ChannelJoined?.Invoke(this, new PresenceEventArgs(channel, uuid));
 }
Пример #12
0
        public async Task RunAsync(string id)
        {
start:
            if (IsConnected)
            {
                return;
            }
            websocket_cts = new CancellationTokenSource();
            var Authenticator = RacetimeAPI.Instance.Authenticator;

            using (ws = new ClientWebSocket())
            {
                IsConnected = true;

                if (await Authenticator.Authorize())
                {
                    SendSystemMessage($"Authorization successful. Hello, {Authenticator.Identity?.Name}");
                    Authorized?.Invoke(this, null);
                }
                else
                {
                    SendSystemMessage(Authenticator.Error, true);
                    AuthenticationFailed?.Invoke(this, new EventArgs());
                    ConnectionError++;
                    goto cleanup;
                }
                //opening the socket
                ws.Options.SetRequestHeader("Authorization", $"Bearer {Authenticator.AccessToken}");
                try
                {
                    await ws.ConnectAsync(new Uri(FullSocketRoot + "ws/o/race/" + id), websocket_cts.Token);
                }
                catch (WebSocketException wex)
                {
                    ConnectionError++;
                    goto cleanup;
                }

                //initial command to sync LiveSplit
                if (ws.State == WebSocketState.Open)
                {
                    ChannelJoined?.Invoke(this, new EventArgs());
                    SendSystemMessage($"Joined Channel '{id}'");
                    try
                    {
                        ArraySegment <byte> bytesToSend = new ArraySegment <byte>(Encoding.UTF8.GetBytes("{ \"action\":\"getrace\" }"));
                        ws.SendAsync(bytesToSend, WebSocketMessageType.Text, true, CancellationToken.None);
                        await ReceiveAndProcess();

                        if (Race.StartedAt != DateTime.MaxValue)
                        {
                            Model.CurrentState.Run.Offset = DateTime.UtcNow - Race.StartedAt;
                        }
                        else
                        {
                            Model.CurrentState.Run.Offset = -Race.StartDelay;
                        }
                    }
                    catch (Exception ex)
                    {
                        SendSystemMessage("Unable to obtain Race information. Try reloading");
                        //Authenticator.AccessToken = null;
                        //Authenticator.RefreshToken = null;

                        goto cleanup;
                    }
                    try
                    {
                        var rf = new StandardComparisonGeneratorsFactory();

                        if (ConnectionError >= 0) //don't load after every reconnect
                        {
                            SendSystemMessage("Loading chat history...");
                            ArraySegment <byte> otherBytesToSend = new ArraySegment <byte>(Encoding.UTF8.GetBytes("{ \"action\":\"gethistory\" }"));
                            ws.SendAsync(otherBytesToSend, WebSocketMessageType.Text, true, CancellationToken.None);
                            await ReceiveAndProcess();
                        }
                    }
                    catch
                    {
                        SendSystemMessage("Unable to load chat history");
                    }
                }

                ConnectionError = -1;

                while (ws.State == WebSocketState.Open && !websocket_cts.IsCancellationRequested)
                {
                    try
                    {
                        await ReceiveAndProcess();
                    }
                    catch (Exception ex)
                    {
                    }
                }


                switch (ws.State)
                {
                case WebSocketState.CloseSent:
                case WebSocketState.CloseReceived:
                case WebSocketState.Closed:
                    ConnectionError = -1;
                    break;

                default:
                case WebSocketState.Aborted:
                    if (!websocket_cts.IsCancellationRequested)
                    {
                        ConnectionError++;
                    }

                    break;
                }
            }

cleanup:
            IsConnected = false;

            if (ConnectionError >= 0)
            {
                SendSystemMessage($"Auto-reconnect in {reconnectDelays[Math.Min(reconnectDelays.Length-1,ConnectionError)]}s...");
                await Task.Delay(reconnectDelays[Math.Min(reconnectDelays.Length - 1, ConnectionError)] * 1000);

                goto start;
            }
            else
            {
                SendSystemMessage("Disconnect");
            }

            websocket_cts.Dispose();

            Disconnected?.Invoke(this, new EventArgs());
        }
Пример #13
0
 /// <summary>
 ///     Raises the <see cref="ChannelJoined"/> event.
 /// </summary>
 /// <param name="e">The <see cref="EventArgs"/> instance holding the event data.</param>
 internal void OnChannelJoined(IrcUserEventArgs e)
 {
     ChannelJoined?.Invoke(this, e);
 }
Пример #14
0
 protected virtual void OnChannelJoined(string channel)
 {
     _joinedChannels.Add(channel);
     ChannelJoined?.Invoke(this, new ChannelJoinedEventArgs(channel));
 }
Пример #15
0
 public void OnChannelJoined(ChannelJoined callback)
 {
     channelJoined = callback;
 }
Пример #16
0
 }
                        System.Diagnostics.Debug.WriteLine(" -> Not found error, attempting to reinitialize");
                        //  disconnect
                        //System.Diagnostics.Debug.WriteLine(" -> -> uninitialize");
                        //Uninitialize();
                        //  reconnect
                        System.Diagnostics.Debug.WriteLine(" -> -> reinitialize");
                        Initialize(_UserId, _AuthKey, false, _PushData);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(string.Format("*** ChatService.Initialize - Exception: {0}", ex));
                    }
                }

                if (status.Category == PNStatusCategory.PNConnectedCategory)
                {
                    System.Diagnostics.Debug.WriteLine(" -> Connected");
                    // this is expected for a subscribe, this means there is no error or issue whatsoever
                    // reset fail count
                    _FailCount = 0;
                }
                else if (status.Category == PNStatusCategory.PNReconnectedCategory)
                {
                    System.Diagnostics.Debug.WriteLine(" -> Reconnected");
                    // this usually occurs if subscribe temporarily fails but reconnects. This means
                    // there was an error but there is no longer any issue
                }
                else if (status.Category == PNStatusCategory.PNDisconnectedCategory)
                {
                    System.Diagnostics.Debug.WriteLine(" -> Disconnected");
                    // this is the expected category for an unsubscribe. This means there
                    // was no error in unsubscribing from everything
                }
                else if (status.Category == PNStatusCategory.PNUnexpectedDisconnectCategory)
                {
                    System.Diagnostics.Debug.WriteLine(" -> Unexpected disconnected");
                    // this is usually an issue with the internet connection, this is an error, handle appropriately
                }
                else if (status.Category == PNStatusCategory.PNAccessDeniedCategory)
                {
                    System.Diagnostics.Debug.WriteLine(" -> Access Denied");
                    // this means that PAM does allow this client to subscribe to this
                    // channel and channel group configuration. This is another explicit error
                }
            }
        }

        #endregion Callbacks

        #region Operations

        public void GetHistory(long timeStamp)
        {
            try
            {
                if (!Initialized || string.IsNullOrEmpty(_UserId)) return;
                _Pubnub.History()
                    .Channel(_UserId)
                    .Start(timeStamp)
                    .Count(20)
                    .Async(new PNHistoryResultExt((result, status) =>
                    {
                        if ((result.Messages == null) || (result.Messages.Count == 0)) return;
                        foreach (var message in result.Messages)
                        {
                            //  let listeners know
                            MessageReceived?.Invoke(this, new MessageEventArgs(message.Entry.ToString()));
                        }
                    }));
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(string.Format("*** ChatService.GetHistory - Exception: {0}", ex));
            }
        }

        public void Publish(string to, string message, object state)
        {
            try
            {
                if (!Initialized || string.IsNullOrEmpty(_UserId)) throw new ArgumentException("Cannot publish before initialize.");

                //  publish message
                _Pubnub.Publish()
                    .Channel(to)
                    .Message(message)
                    .Async(new PNPublishResultExt((result, status) =>
                    {
                        if (message == null) return;
                        //  get the message
                        PublishComplete?.Invoke(this, new MessageEventArgs(message)
                        {
                            State = state,
                            Success = !status.Error,
                            Timestamp = new DateTime(result.Timetoken)
                        });
                    }));
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(string.Format("*** ChatService.Publish - Exception: {0}", ex));
            }
        }

        #endregion Operations

        #region Event Triggers

        private void RaiseChannelJoined(string channel, string uuid)
        {
            ChannelJoined?.Invoke(this, new PresenceEventArgs(channel, uuid));
        }

        private void RaiseChannelLeft(string channel, string uuid)
        {
            ChannelLeft?.Invoke(this, new PresenceEventArgs(channel, uuid));
        }

        private void RaiseChannelTimeout(string channel, string uuid)
        {
            ChannelTimeout?.Invoke(this, new PresenceEventArgs(channel, uuid));
        }

        private void RaiseChannelState(string channel, string uuid, ChatState state)
        {
            ChannelState?.Invoke(this, new PresenceEventArgs(channel, uuid, state));
        }

        #endregion Event Triggers

        #region Cleanup

        public void Dispose()
        {
            if (_Disposed) return;
            //  TODO: check this - it looks dodgy
            SubscribeCallbackExt listenerSubscribeCallack = new SubscribeCallbackExt((pubnubObj, message) => { }, (pubnubObj, presence) => { }, (pubnubObj, status) => { });
            _Pubnub.AddListener(listenerSubscribeCallack);
            // some time later
            _Pubnub.RemoveListener(listenerSubscribeCallack);
            _Pubnub.Destroy();
            _Disposed = true;
        }

        #endregion Cleanup
    }
}


Пример #17
0
 private Task Client_ChannelJoined(object sender, ChannelJoinedEventArgs e)
 {
     ChannelJoined?.Invoke(this, e);
     return(Task.CompletedTask);
 }