private void OnJoinGameResult(object sender, ClientListener <JoinGameMessage> .TArg e)
        {
            //Получение позиции игрока в игре
            uint?myPlayerPosition = e.Arg.MyPosition;

            //Проверка позиции игрока
            if (myPlayerPosition == null)
            {
                //Если присоединение не удалось, то разрываем соединение
                OnJoin?.Invoke(null);
                tcpClient.Dispose();
                return;
            }

            //Если присоединение успешно
            OnJoin?.Invoke(e.Arg);

            //Если есть противник, то начинаем игру
            if (e.Arg.EnemyName != null)
            {
                joinGameListener.Stop();
                OnStart?.Invoke();
                playGameListener.Start();
            }
        }
Esempio n. 2
0
 public static void Create(int port, GetData gd, OnJoin join, OnLeft left)
 {
     connects = new Dictionary<ushort, TcpClientm>();
     Socket = new TcpListener(IPAddress.Any, port);
     _gd = gd;
     _join = join;
     _left = left;
 }
Esempio n. 3
0
        /// <summary>
        /// Verarbeitet das Betreten eines Users eines Channels
        /// </summary>
        /// <seealso cref="OnJoin"/>
        private void _connection_OnJoin(object sender, JoinEventArgs e)
        {
            Log.Information("{Nickname} hat den Raum {Channel} betreten", e.Who, e.Channel);
            MaintainUser(e.Who);

            ThreadPool.QueueUserWorkItem(x =>
            {
                OnJoin?.Invoke(this, e);
            });
        }
 private void JoinGame(string playerName)
 {
     if (!tcpClient.Connected)
     {
         OnJoin?.Invoke(null);
         return;
     }
     try
     {
         //Отправка имени игрока:
         TextMessage textMessage = new TextMessage(playerName);
         tcpClient.Send(textMessage);
         joinGameListener.Start();
     }
     catch (Exception)
     {
         OnJoin?.Invoke(null);
     }
 }
Esempio n. 5
0
        void OnNewConnection(NetworkEvent netEvent)
        {
            ConnectionId newCId = netEvent.ConnectionId;

            ConnectionIds.Add(newCId);

            if (NodeState == State.Uninitialized)
            {
                OnJoin.TryInvoke(newCId);

                // Add server as a connection on the client end
                ConnectionIds.Add(new ConnectionId(0));
                NodeState = State.Client;
            }
            else if (NodeState == State.Server)
            {
                OnJoin.TryInvoke(newCId);
                foreach (var id in ConnectionIds)
                {
                    if (id.id == 0 || id.id == newCId.id)
                    {
                        continue;
                    }

                    byte[] payload;

                    // Announce the new connection to the old ones and vice-versa
                    payload = new UniStreamWriter().WriteShort(newCId.id).Bytes;
                    Send(Packet.From(this).To(id).With(ReservedTags.ClientJoined, payload), true);

                    payload = new UniStreamWriter().WriteShort(id.id).Bytes;
                    Send(Packet.From(this).To(newCId).With(ReservedTags.ClientJoined, payload), true);
                }
            }

            m_ConnectCallback.TryInvoke(newCId);
            m_ConnectCallback = null;
        }
Esempio n. 6
0
 private static void RichPresence_OnActivityJoin(string secret)
 {
     OnJoin?.Invoke(secret);
 }
        /// <summary>
        /// Dequeues all the messages from Discord and invokes appropriate methods. This will process the message and update the internal state before invoking the events. Returns the messages that were invoked and in the order they were invoked.
        /// </summary>
        /// <returns>Returns the messages that were invoked and in the order they were invoked.</returns>
        public IMessage[] Invoke()
        {
            //Dequeue all the messages and process them
            IMessage[] messages = connection.DequeueMessages();
            for (int i = 0; i < messages.Length; i++)
            {
                //Do a bit of pre-processing
                var message = messages[i];
                HandleMessage(message);

                //Invoke the appropriate methods
                switch (message.Type)
                {
                case MessageType.Ready:
                    if (OnReady != null)
                    {
                        OnReady.Invoke(this, message as ReadyMessage);
                    }
                    break;

                case MessageType.Close:
                    if (OnClose != null)
                    {
                        OnClose.Invoke(this, message as CloseMessage);
                    }
                    break;

                case MessageType.Error:
                    if (OnError != null)
                    {
                        OnError.Invoke(this, message as ErrorMessage);
                    }
                    break;

                case MessageType.PresenceUpdate:
                    if (OnPresenceUpdate != null)
                    {
                        OnPresenceUpdate.Invoke(this, message as PresenceMessage);
                    }
                    break;

                case MessageType.Subscribe:
                    if (OnSubscribe != null)
                    {
                        OnSubscribe.Invoke(this, message as SubscribeMessage);
                    }
                    break;

                case MessageType.Unsubscribe:
                    if (OnUnsubscribe != null)
                    {
                        OnUnsubscribe.Invoke(this, message as UnsubscribeMessage);
                    }
                    break;

                case MessageType.Join:
                    if (OnJoin != null)
                    {
                        OnJoin.Invoke(this, message as JoinMessage);
                    }
                    break;

                case MessageType.Spectate:
                    if (OnSpectate != null)
                    {
                        OnSpectate.Invoke(this, message as SpectateMessage);
                    }
                    break;

                case MessageType.JoinRequest:
                    if (OnJoinRequested != null)
                    {
                        OnJoinRequested.Invoke(this, message as JoinRequestMessage);
                    }
                    break;

                case MessageType.ConnectionEstablished:
                    if (OnConnectionEstablished != null)
                    {
                        OnConnectionEstablished.Invoke(this, message as ConnectionEstablishedMessage);
                    }
                    break;

                case MessageType.ConnectionFailed:
                    if (OnConnectionFailed != null)
                    {
                        OnConnectionFailed.Invoke(this, message as ConnectionFailedMessage);
                    }
                    break;

                default:
                    //This in theory can never happen, but its a good idea as a reminder to update this part of the library if any new messages are implemented.
                    Logger.Error("Message was queued with no appropriate handle! {0}", message.Type);
                    break;
                }
            }

            //Finally, return the messages
            return(messages);
        }
Esempio n. 8
0
        protected void ParseMessage(byte[] bytes)
        {
            if (previousCode == 0)
            {
                byte code = bytes[0];

                if (code == Protocol.JOIN_ROOM)
                {
                    var offset = 1;

                    SessionId = System.Text.Encoding.UTF8.GetString(bytes, offset + 1, bytes[offset]);
                    offset   += SessionId.Length + 1;

                    SerializerId = System.Text.Encoding.UTF8.GetString(bytes, offset + 1, bytes[offset]);
                    offset      += SerializerId.Length + 1;

                    if (SerializerId == "schema")
                    {
                        serializer = new SchemaSerializer <T>();
                    }
                    else if (SerializerId == "fossil-delta")
                    {
                        serializer = (ISerializer <T>) new FossilDeltaSerializer();
                    }

                    // TODO: use serializer defined by the back-end.
                    // serializer = (Colyseus.Serializer) new FossilDeltaSerializer();

                    if (bytes.Length > offset)
                    {
                        serializer.Handshake(bytes, offset);
                    }

                    if (OnJoin != null)
                    {
                        OnJoin.Invoke(this, new EventArgs());
                    }
                }
                else if (code == Protocol.JOIN_ERROR)
                {
                    var message = System.Text.Encoding.UTF8.GetString(bytes, 2, bytes[1]);
                    OnError.Invoke(this, new ErrorEventArgs(message));
                }
                else if (code == Protocol.LEAVE_ROOM)
                {
                    Leave();
                }
                else
                {
                    previousCode = code;
                }
            }
            else
            {
                if (previousCode == Protocol.ROOM_STATE)
                {
                    SetState(bytes);
                }
                else if (previousCode == Protocol.ROOM_STATE_PATCH)
                {
                    Patch(bytes);
                }
                else if (previousCode == Protocol.ROOM_DATA)
                {
                    var message = MsgPack.Deserialize <object>(new MemoryStream(bytes));
                    OnMessage.Invoke(this, new MessageEventArgs(message));
                }
                previousCode = 0;
            }
        }
Esempio n. 9
0
        protected async void ParseMessage(byte[] bytes)
        {
            if (previousCode == 0)
            {
                byte code = bytes[0];

                if (code == Protocol.JOIN_ROOM)
                {
                    var offset = 1;

                    SerializerId = System.Text.Encoding.UTF8.GetString(bytes, offset + 1, bytes[offset]);
                    offset      += SerializerId.Length + 1;

                    if (SerializerId == "schema")
                    {
                        serializer = new SchemaSerializer <T>();
                    }
                    else if (SerializerId == "fossil-delta")
                    {
                        serializer = (ISerializer <T>) new FossilDeltaSerializer();
                    }

                    if (bytes.Length > offset)
                    {
                        serializer.Handshake(bytes, offset);
                    }

                    OnJoin?.Invoke();
                }
                else if (code == Protocol.JOIN_ERROR)
                {
                    var message = System.Text.Encoding.UTF8.GetString(bytes, 2, bytes[1]);
                    OnError?.Invoke(message);
                }
                else if (code == Protocol.ROOM_DATA_SCHEMA)
                {
                    Type messageType = Schema.Context.GetInstance().Get(bytes[1]);

                    var message = (Schema.Schema)Activator.CreateInstance(messageType);
                    message.Decode(bytes, new Schema.Iterator {
                        Offset = 2
                    });

                    OnMessage?.Invoke(message);
                }
                else if (code == Protocol.LEAVE_ROOM)
                {
                    await Leave();
                }
                else
                {
                    previousCode = code;
                }
            }
            else
            {
                if (previousCode == Protocol.ROOM_STATE)
                {
                    SetState(bytes);
                }
                else if (previousCode == Protocol.ROOM_STATE_PATCH)
                {
                    Patch(bytes);
                }
                else if (previousCode == Protocol.ROOM_DATA)
                {
                    var message = MsgPack.Deserialize <object>(new MemoryStream(bytes));
                    OnMessage?.Invoke(message);
                }
                previousCode = 0;
            }
        }
Esempio n. 10
0
 void Room_OnJoin(object sender, EventArgs e)
 {
     Debug.Log("Joined room!");
     OnJoin?.Invoke(sender, e);
 }
        protected async void ParseMessage(byte[] bytes)
        {
            byte code = bytes[0];

            Debug.Log("BYTE =>" + code);

            if (code == Protocol.JOIN_ROOM)
            {
                var offset = 1;

                SerializerId = System.Text.Encoding.UTF8.GetString(bytes, offset + 1, bytes[offset]);
                offset      += SerializerId.Length + 1;

                if (SerializerId == "schema")
                {
                    serializer = new SchemaSerializer <T>();
                }
                else if (SerializerId == "fossil-delta")
                {
                    serializer = (ISerializer <T>) new FossilDeltaSerializer();
                }

                if (bytes.Length > offset)
                {
                    serializer.Handshake(bytes, offset);
                }

                OnJoin?.Invoke();

                // Acknowledge JOIN_ROOM
                await Connection.Send(new byte[] { Protocol.JOIN_ROOM });
            }
            else if (code == Protocol.ERROR)
            {
                Schema.Iterator it = new Schema.Iterator {
                    Offset = 1
                };
                var errorCode    = Decode.DecodeNumber(bytes, it);
                var errorMessage = Decode.DecodeString(bytes, it);
                OnError?.Invoke((int)errorCode, errorMessage);
            }
            else if (code == Protocol.ROOM_DATA_SCHEMA)
            {
                Type messageType = Schema.Context.GetInstance().Get(bytes[1]);

                var message = (Schema.Schema)Activator.CreateInstance(messageType);
                message.Decode(bytes, new Schema.Iterator {
                    Offset = 2
                });

                IMessageHandler handler = null;
                OnMessageHandlers.TryGetValue("s" + message.GetType(), out handler);

                if (handler != null)
                {
                    handler.Invoke(message);
                }
                else
                {
                    Debug.LogError("room.OnMessage not registered for Schema message: " + message.GetType());
                }
            }
            else if (code == Protocol.LEAVE_ROOM)
            {
                await Leave();
            }
            else if (code == Protocol.ROOM_STATE)
            {
                Debug.Log("ROOM_STATE");
                SetState(bytes, 1);
            }
            else if (code == Protocol.ROOM_STATE_PATCH)
            {
                Debug.Log("ROOM_STATE_PATCH");
                Patch(bytes, 1);
            }
            else if (code == Protocol.ROOM_DATA)
            {
                IMessageHandler handler = null;
                object          type;

                Schema.Iterator it = new Schema.Iterator {
                    Offset = 1
                };

                if (Decode.NumberCheck(bytes, it))
                {
                    type = Decode.DecodeNumber(bytes, it);
                    OnMessageHandlers.TryGetValue("i" + type, out handler);
                }
                else
                {
                    type = Decode.DecodeString(bytes, it);
                    OnMessageHandlers.TryGetValue(type.ToString(), out handler);
                }

                if (handler != null)
                {
                    //
                    // MsgPack deserialization can be optimized:
                    // https://github.com/deniszykov/msgpack-unity3d/issues/23
                    //
                    var message = (bytes.Length > it.Offset)
                                                ? MsgPack.Deserialize(handler.Type, new MemoryStream(bytes, it.Offset, bytes.Length - it.Offset, false))
                                                : null;

                    handler.Invoke(message);
                }
                else
                {
                    Debug.LogError("room.OnMessage not registered for: " + type);
                }
            }
        }
Esempio n. 12
0
 public void Join()
 {
     OnJoin?.Invoke(this, DateTime.Now);
 }
Esempio n. 13
0
 private void ProcessJoinCommand(string[] tokens)
 {
     OnJoin?.Invoke(Rfc2812Util.UserFromString(tokens[0]), RemoveLeadingColon(tokens[2]));
     //Trace.WriteLine("Join", "IRC");
 }
Esempio n. 14
0
 public void HandleJoin()
 {
     OnJoin?.Invoke(this);
 }
Esempio n. 15
0
 public void ProcessJoinCommand(IrcMessage ircMessage)
 {
     OnJoin?.Invoke(Rfc2812Util.UserFromString(ircMessage.From), ircMessage.Target);
 }
Esempio n. 16
0
        protected async void ParseMessage(byte[] bytes)
        {
            byte code = bytes[0];

            if (code == Protocol.JOIN_ROOM)
            {
                var offset = 1;

                SerializerId = System.Text.Encoding.UTF8.GetString(bytes, offset + 1, bytes[offset]);
                offset      += SerializerId.Length + 1;

                if (SerializerId == "schema")
                {
                    serializer = new SchemaSerializer <T>();
                }
//				else if (SerializerId == "fossil-delta")
//				{
//					serializer = (ISerializer<T>) new FossilDeltaSerializer();
//				}

                if (bytes.Length > offset)
                {
                    serializer.Handshake(bytes, offset);
                }

                OnJoin?.Invoke();

                // Acknowledge JOIN_ROOM
                await Connection.Send(new object[] { Protocol.JOIN_ROOM });
            }
            else if (code == Protocol.JOIN_ERROR)
            {
                var message = System.Text.Encoding.UTF8.GetString(bytes, 2, bytes[1]);
                OnError?.Invoke(message);
            }
            else if (code == Protocol.ROOM_DATA_SCHEMA)
            {
                Type messageType = Schema.Context.GetInstance().Get(bytes[1]);

                var message = (Schema.Schema)Activator.CreateInstance(messageType);
                message.Decode(bytes, new Schema.Iterator {
                    Offset = 2
                });

                OnMessage?.Invoke(message);
            }
            else if (code == Protocol.LEAVE_ROOM)
            {
                await Leave();
            }
            else if (code == Protocol.ROOM_STATE)
            {
                SetState(bytes, 1);
            }
            else if (code == Protocol.ROOM_STATE_PATCH)
            {
                Patch(bytes, 1);
            }
            else if (code == Protocol.ROOM_DATA)
            {
                // TODO: de-serialize message with an offset, to avoid creating a new buffer
                var message = MsgPack.Deserialize <object>(new MemoryStream(
                                                               ArrayUtils.SubArray(bytes, 1, bytes.Length - 1)
                                                               ));
                OnMessage?.Invoke(message);
            }
        }
Esempio n. 17
0
        public static void TimerElapsed()
        {
            var eventTime = Trim(DateTime.UtcNow);

            try
            {
                List <Downloader.MemberData> membercache;
                if (File.Exists($"{BASE_DIR}/membercache.csv"))
                {
                    membercache = Downloader.ParseMemberData(File.ReadAllText($"{BASE_DIR}/membercache.csv")).ToList();
                }
                else
                {
                    membercache = new List <Downloader.MemberData>();
                }
                string result = Client.GetStringAsync($"http://services.runescape.com/m=clan-hiscores/members_lite.ws?clanName={Downloader.CLAN_NAME}").GetAwaiter().GetResult();
                if (result != null && !result.StartsWith("Clanmate"))
                {
                    return;
                }
                if (result != null && result.Length > 0)
                {
                    File.WriteAllText($"{BASE_DIR}/membercache.csv", result);
                }
                var current = Downloader.ParseMemberData(result).ToList();
                if (membercache.Count > 0 && current.Count > 0)
                {
                    var leave = Downloader.MemberData.Diff(membercache, current);
                    var join  = Downloader.MemberData.Diff(current, membercache);
                    if (leave.Count > 0 && join.Count == 0)
                    {
                        foreach (var leaver in leave)
                        {
                            OnLeave?.Invoke(leaver.Name);
                        }
                    }
                    else if (leave.Count == 0 && join.Count > 0)
                    {
                        foreach (var joiner in join)
                        {
                            OnJoin?.Invoke(joiner.Name);
                        }
                    }
                    else
                    {
                        for (int i = join.Count - 1; i >= 0; i--)
                        {
                            for (int j = leave.Count - 1; j >= 0; j--)
                            {
                                var joiner = join[i];
                                var leaver = leave[j];

                                if (joiner.Rank == leaver.Rank && joiner.ClanXP == leaver.ClanXP && joiner.ClanKills == leaver.ClanKills)
                                {
                                    join.RemoveAt(i);
                                    leave.RemoveAt(j);
                                    OnNamechange?.Invoke(leaver.Name, joiner.Name);
                                    break;
                                }
                            }
                        }

                        if (join.Count > 0)
                        {
                            join.ForEach((item) => OnJoin?.Invoke(item.Name));
                        }
                        if (leave.Count > 0)
                        {
                            leave.ForEach((item) => OnLeave?.Invoke(item.Name));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            if (!Paused && !Updating && (Force || eventTime.Minute % 10 == 0))
            {
                Force    = false;
                Updating = true;
                try
                {
                    var profiles = Downloader.GetProfiles(Client, Downloader.GetClanList(Client));

                    string[] cappers = Downloader.GetCappersList(profiles);

                    var message = new StringBuilder();

                    foreach (var capper in cappers)
                    {
                        if (!CappedList.Contains(capper))
                        {
                            CappedList.Add(capper);
                            if (CappedMessages.Count > 0)
                            {
                                message.Append(string.Format(CappedMessages[Random.Next(0, CappedMessages.Count)], capper) + "\n");
                            }
                        }
                    }

                    if (message.Length > 0 && UpdateChannel != 0)
                    {
                        PostMessageAsync(UpdateChannel, message.ToString()).GetAwaiter().GetResult();
                    }
                    new Thread(() =>
                    {
                        string[] items = Downloader.GetItems(Client, profiles);
                        if (ItemChannel > 0)
                        {
                            try
                            {
                                var builder = new StringBuilder();
                                foreach (var item in items)
                                {
                                    if (builder.Length + item.Length + 1 >= 2000)
                                    {
                                        PostMessageAsync(ItemChannel, builder.ToString()).GetAwaiter().GetResult();
                                        builder.Clear();
                                    }
                                    builder.Append(item);
                                }
                                if (builder.Length > 0)
                                {
                                    PostMessageAsync(ItemChannel, builder.ToString()).GetAwaiter().GetResult();
                                }
                            }
                            catch { }
                        }
                        string[] achievements = Downloader.GetAchievements(Client, profiles);
                        if (AchievementWebhook != null && !Cache)
                        {
                            try
                            {
                                var builder = new StringBuilder();
                                foreach (var achievement in achievements)
                                {
                                    if (builder.Length + achievement.Length + 1 >= 2000)
                                    {
                                        AchievementWebhook.SendMessageAsync(builder.ToString());
                                        builder.Clear();
                                    }
                                    builder.Append(achievement);
                                }
                                if (builder.Length > 0)
                                {
                                    AchievementWebhook.SendMessageAsync(builder.ToString());
                                }
                            }
                            catch { }
                        }
                        Cache = false;
                    }).Start();
                }
                catch (Exception e) { Console.WriteLine(e.Message); }
                CappedList.Sort();
                WriteCookies();
                Updating = false;
                Console.WriteLine(new LogMessage(LogSeverity.Info, "Timer", $"Update finished in {(DateTime.UtcNow - eventTime).TotalMilliseconds}ms."));
            }
            if (eventTime == CurrentResetDate)
            {
                if (ResetChannel != 0)
                {
                    PostMessageAsync(ResetChannel, ResetMessage).GetAwaiter().GetResult();
                }
                if (ListChannel != 0)
                {
                    var      message = new StringBuilder();
                    string[] cappers = CappedList.ToArray();

                    message.Append($"**__Capped citizens for the week of {CurrentResetDate.ToShortDateString()}__**\n");

                    foreach (var capper in cappers)
                    {
                        message.Append($"{capper}\n");
                    }
                    PostMessageAsync(ListChannel, message.ToString()).GetAwaiter().GetResult();
                }
                WriteCookies();
                ProgressDate();
                CappedList.Clear();
            }
        }
Esempio n. 18
0
        private async Task OnGuildJoin(SocketGuild guild)
        {
            await Task.Run(async() =>
            {
                try
                {
                    DatabaseContext context = new DatabaseContext();


                    if (!(context.Auth.Any(o => o.Serverid == guild.Id) && (!(context.OnJoin.Any(o => o.Serverid == guild.Id)))))
                    {
                        string warning = null;
                        try
                        {
                            if (guild.Roles.Any(x => x.Name == "Fork-Mods"))
                            {
                                foreach (var Role in guild.Roles.Where(x => x.Name == "Fork-Mods"))
                                {
                                    await Role.DeleteAsync();
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            warning +=
                                $"`Fork-Mods` role detected, please move my role above the `Fork-Mods` role and authenticate using `$auth [token]` then run `$rec` to clean it." +
                                Environment.NewLine;
                        }

                        try
                        {
                            if (guild.TextChannels.Any(x => x.Name == "Fork-Bot"))
                            {
                                foreach (var Chan in guild.Channels.Where(x => x.Name == "Fork-Bot"))
                                {
                                    await Chan.DeleteAsync();
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            warning +=
                                $"`Fork-Bot` channel detected, please move my role above the `Fork-Mods` role and authenticate using `$auth [token]` then run `$rec` to clean it." +
                                Environment.NewLine;
                        }

                        if (warning == null)
                        {
                            ulong origin = (ulong)GuildPermission.Speak + (ulong)GuildPermission.SendTTSMessages +
                                           (ulong)GuildPermission.SendMessages + (ulong)GuildPermission.ViewChannel +
                                           (ulong)GuildPermission.EmbedLinks + (ulong)GuildPermission.Connect +
                                           (ulong)GuildPermission.AttachFiles + (ulong)GuildPermission.AddReactions;
                            GuildPermissions perms = new GuildPermissions(origin);
                            //Color Colorr = new Color(21, 22, 34);
                            var roleee = await guild.CreateRoleAsync("Fork-Mods", perms, null, false, false, null);
                            var vChan  = await guild.CreateTextChannelAsync("Fork-Bot");
                            await vChan.AddPermissionOverwriteAsync(roleee, AdminPermissions());
                            await vChan.AddPermissionOverwriteAsync(guild.EveryoneRole, NoPermissions());

                            var ebd   = new EmbedBuilder();
                            ebd.Color = Color.Green;
                            ebd.WithCurrentTimestamp();
                            ebd.WithAuthor($"Fork Server Management", guild.CurrentUser.GetAvatarUrl());
                            ebd.WithDescription(
                                "Hello there," +
                                Environment.NewLine +
                                "I'm Fork Bot if you don't know me, I can help you control your Fork Minecraft servers and display their status in Discord." +
                                Environment.NewLine +
                                "I made a private channel for you, please use `$auth [token]` to link this Discord server with your Fork app." +
                                Environment.NewLine +
                                "You can check for your token in Fork app settings.");
                            //var ownerr = KKK.Client.GetGuild(guild.Id).OwnerId;
                            await vChan.SendMessageAsync($"<@{guild.OwnerId}>", false, ebd.Build());
                            var msgg = await vChan.SendMessageAsync(null, false,
                                                                    BotTools.Embed("Don't remove this message, this message will be updated continuously and display the status of you Fork servers.", 20));
                            using (var contextt = new DatabaseContext())
                            {
                                OnJoin newset    = new OnJoin();
                                newset.Serverid  = guild.Id;
                                newset.Roleid    = roleee.Id;
                                newset.Channelid = vChan.Id;
                                newset.Messageid = msgg.Id;
                                contextt.Add(newset);
                                contextt.SaveChanges();
                            }
                        }
                        else
                        {
                            var ebd   = new EmbedBuilder();
                            ebd.Color = Color.Red;
                            ebd.WithCurrentTimestamp();
                            ebd.WithAuthor($"Error", guild.CurrentUser.GetAvatarUrl());
                            ebd.WithDescription(warning);
                            //var ownerr = KKK.Client.GetGuild(guild.Id).OwnerId;
                            await guild.DefaultChannel.SendMessageAsync($"<@{guild.OwnerId}>", false, ebd.Build());
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            });
        }
Esempio n. 19
0
 public void UserJoin(User nick)
 {
     OnJoin.Fire(this, new UserEventArgs(nick));
 }
        /// <summary>
        ///     The function that will be called when the <see cref="colyseusConnection" /> receives a message
        /// </summary>
        /// <param name="bytes">The message as provided from the <see cref="colyseusConnection" /></param>
        protected async void ParseMessage(byte[] bytes)
        {
            byte code = bytes[0];

            if (code == ColyseusProtocol.JOIN_ROOM)
            {
                int offset = 1;

                SerializerId = Encoding.UTF8.GetString(bytes, offset + 1, bytes[offset]);
                offset      += SerializerId.Length + 1;

                if (SerializerId == "schema")
                {
                    try
                    {
                        serializer = new ColyseusSchemaSerializer <T>();
                    }
                    catch (Exception e)
                    {
                        DisplaySerializerErrorHelp(e,
                                                   "Consider using the \"schema-codegen\" and providing the same room state for matchmaking instead of \"" +
                                                   typeof(T).Name + "\"");
                    }
                }
                else if (SerializerId == "fossil-delta")
                {
                    Debug.LogError(
                        "FossilDelta Serialization has been deprecated. It is highly recommended that you update your code to use the Schema Serializer. Otherwise, you must use an earlier version of the Colyseus plugin");
                }
                else
                {
                    try
                    {
                        serializer = (IColyseusSerializer <T>) new ColyseusNoneSerializer();
                    }
                    catch (Exception e)
                    {
                        DisplaySerializerErrorHelp(e,
                                                   "Consider setting state in the server-side using \"this.setState(new " + typeof(T).Name +
                                                   "())\"");
                    }
                }

                if (bytes.Length > offset)
                {
                    serializer.Handshake(bytes, offset);
                }

                OnJoin?.Invoke();

                // Acknowledge JOIN_ROOM
                await colyseusConnection.Send(new[] { ColyseusProtocol.JOIN_ROOM });
            }
            else if (code == ColyseusProtocol.ERROR)
            {
                Iterator it = new Iterator {
                    Offset = 1
                };
                float  errorCode    = Decode.DecodeNumber(bytes, it);
                string errorMessage = Decode.DecodeString(bytes, it);
                OnError?.Invoke((int)errorCode, errorMessage);
            }
            else if (code == ColyseusProtocol.ROOM_DATA_SCHEMA)
            {
                Iterator it = new Iterator {
                    Offset = 1
                };
                float typeId = Decode.DecodeNumber(bytes, it);

                Type          messageType = ColyseusContext.GetInstance().Get(typeId);
                Schema.Schema message     = (Schema.Schema)Activator.CreateInstance(messageType);

                message.Decode(bytes, it);

                IColyseusMessageHandler handler = null;
                OnMessageHandlers.TryGetValue("s" + message.GetType(), out handler);

                if (handler != null)
                {
                    handler.Invoke(message);
                }
                else
                {
                    Debug.LogWarning("room.OnMessage not registered for Schema of type: '" + message.GetType() + "'");
                }
            }
            else if (code == ColyseusProtocol.LEAVE_ROOM)
            {
                await Leave();
            }
            else if (code == ColyseusProtocol.ROOM_STATE)
            {
                Debug.Log("ROOM_STATE");
                SetState(bytes, 1);
            }
            else if (code == ColyseusProtocol.ROOM_STATE_PATCH)
            {
                Patch(bytes, 1);
            }
            else if (code == ColyseusProtocol.ROOM_DATA)
            {
                IColyseusMessageHandler handler = null;
                object type;

                Iterator it = new Iterator {
                    Offset = 1
                };

                if (Decode.NumberCheck(bytes, it))
                {
                    type = Decode.DecodeNumber(bytes, it);
                    OnMessageHandlers.TryGetValue("i" + type, out handler);
                }
                else
                {
                    type = Decode.DecodeString(bytes, it);
                    OnMessageHandlers.TryGetValue(type.ToString(), out handler);
                }

                if (handler != null)
                {
                    //
                    // MsgPack deserialization can be optimized:
                    // https://github.com/deniszykov/msgpack-unity3d/issues/23
                    //
                    object message = bytes.Length > it.Offset
                        ? MsgPack.Deserialize(handler.Type,
                                              new MemoryStream(bytes, it.Offset, bytes.Length - it.Offset, false))
                        : null;

                    handler.Invoke(message);
                }
                else
                {
                    Debug.LogWarning("room.OnMessage not registered for: '" + type + "'");
                }
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Processes the message, updating our internal state and then invokes the events.
        /// </summary>
        /// <param name="message"></param>
        private void ProcessMessage(IMessage message)
        {
            if (message == null)
            {
                return;
            }
            switch (message.Type)
            {
            //We got a update, so we will update our current presence
            case MessageType.PresenceUpdate:
                lock (_sync)
                {
                    PresenceMessage pm = message as PresenceMessage;
                    if (pm != null)
                    {
                        //We need to merge these presences together
                        if (CurrentPresence == null)
                        {
                            CurrentPresence = pm.Presence;
                        }
                        else if (pm.Presence == null)
                        {
                            CurrentPresence = null;
                        }
                        else
                        {
                            CurrentPresence.Merge(pm.Presence);
                        }

                        //Update the message
                        pm.Presence = CurrentPresence;
                    }
                }

                break;

            //Update our configuration
            case MessageType.Ready:
                ReadyMessage rm = message as ReadyMessage;
                if (rm != null)
                {
                    lock (_sync)
                    {
                        Configuration = rm.Configuration;
                        CurrentUser   = rm.User;
                    }

                    //Resend our presence and subscription
                    SynchronizeState();
                }
                break;

            //Update the request's CDN for the avatar helpers
            case MessageType.JoinRequest:
                if (Configuration != null)
                {
                    //Update the User object within the join request if the current Cdn
                    JoinRequestMessage jrm = message as JoinRequestMessage;
                    if (jrm != null)
                    {
                        jrm.User.SetConfiguration(Configuration);
                    }
                }
                break;

            case MessageType.Subscribe:
                lock (_sync)
                {
                    SubscribeMessage sub = message as SubscribeMessage;
                    Subscription |= sub.Event;
                }
                break;

            case MessageType.Unsubscribe:
                lock (_sync)
                {
                    UnsubscribeMessage unsub = message as UnsubscribeMessage;
                    Subscription &= ~unsub.Event;
                }
                break;

            //We got a message we dont know what to do with.
            default:
                break;
            }

            //Invoke the appropriate methods
            switch (message.Type)
            {
            case MessageType.Ready:
                if (OnReady != null)
                {
                    OnReady.Invoke(this, message as ReadyMessage);
                }
                break;

            case MessageType.Close:
                if (OnClose != null)
                {
                    OnClose.Invoke(this, message as CloseMessage);
                }
                break;

            case MessageType.Error:
                if (OnError != null)
                {
                    OnError.Invoke(this, message as ErrorMessage);
                }
                break;

            case MessageType.PresenceUpdate:
                if (OnPresenceUpdate != null)
                {
                    OnPresenceUpdate.Invoke(this, message as PresenceMessage);
                }
                break;

            case MessageType.Subscribe:
                if (OnSubscribe != null)
                {
                    OnSubscribe.Invoke(this, message as SubscribeMessage);
                }
                break;

            case MessageType.Unsubscribe:
                if (OnUnsubscribe != null)
                {
                    OnUnsubscribe.Invoke(this, message as UnsubscribeMessage);
                }
                break;

            case MessageType.Join:
                if (OnJoin != null)
                {
                    OnJoin.Invoke(this, message as JoinMessage);
                }
                break;

            case MessageType.Spectate:
                if (OnSpectate != null)
                {
                    OnSpectate.Invoke(this, message as SpectateMessage);
                }
                break;

            case MessageType.JoinRequest:
                if (OnJoinRequested != null)
                {
                    OnJoinRequested.Invoke(this, message as JoinRequestMessage);
                }
                break;

            case MessageType.ConnectionEstablished:
                if (OnConnectionEstablished != null)
                {
                    OnConnectionEstablished.Invoke(this, message as ConnectionEstablishedMessage);
                }
                break;

            case MessageType.ConnectionFailed:
                if (OnConnectionFailed != null)
                {
                    OnConnectionFailed.Invoke(this, message as ConnectionFailedMessage);
                }
                break;

            default:
                //This in theory can never happen, but its a good idea as a reminder to update this part of the library if any new messages are implemented.
                Logger.Error("Message was queued with no appropriate handle! {0}", message.Type);
                break;
            }
        }
Esempio n. 22
0
        protected async void ParseMessage(byte[] bytes)
        {
            byte code = bytes[0];

            if (code == Protocol.JOIN_ROOM)
            {
                var offset = 1;

                SerializerId = System.Text.Encoding.UTF8.GetString(bytes, offset + 1, bytes[offset]);
                offset      += SerializerId.Length + 1;

                if (SerializerId == "schema")
                {
                    try
                    {
                        serializer = new SchemaSerializer <T>();
                    }
                    catch (Exception e)
                    {
                        DisplaySerializerErrorHelp(e, "Consider using the \"schema-codegen\" and providing the same room state for matchmaking instead of \"" + typeof(T).Name + "\"");
                    }
                }
                else if (SerializerId == "fossil-delta")
                {
                    try
                    {
                        serializer = (ISerializer <T>) new FossilDeltaSerializer();
                    } catch (Exception e)
                    {
                        DisplaySerializerErrorHelp(e, "Consider using \"IndexedDictionary<string, object>\" instead of \"" + typeof(T).Name + "\" for matchmaking.");
                    }
                }
                else
                {
                    try
                    {
                        serializer = (ISerializer <T>) new NoneSerializer();
                    }
                    catch (Exception e)
                    {
                        DisplaySerializerErrorHelp(e, "Consider setting state in the server-side using \"this.setState(new " + typeof(T).Name + "())\"");
                    }
                }

                if (bytes.Length > offset)
                {
                    serializer.Handshake(bytes, offset);
                }

                OnJoin?.Invoke();

                // Acknowledge JOIN_ROOM
                await Connection.Send(new byte[] { Protocol.JOIN_ROOM });
            }
            else if (code == Protocol.ERROR)
            {
                Schema.Iterator it = new Schema.Iterator {
                    Offset = 1
                };
                var errorCode    = Decode.DecodeNumber(bytes, it);
                var errorMessage = Decode.DecodeString(bytes, it);
                OnError?.Invoke((int)errorCode, errorMessage);
            }
            else if (code == Protocol.ROOM_DATA_SCHEMA)
            {
                Schema.Iterator it = new Schema.Iterator {
                    Offset = 1
                };
                var typeId = Decode.DecodeNumber(bytes, it);

                Type messageType = Schema.Context.GetInstance().Get(typeId);
                var  message     = (Schema.Schema)Activator.CreateInstance(messageType);

                message.Decode(bytes, it);

                IMessageHandler handler = null;
                OnMessageHandlers.TryGetValue("s" + message.GetType(), out handler);

                if (handler != null)
                {
                    handler.Invoke(message);
                }
                else
                {
                    Debug.LogWarning("room.OnMessage not registered for Schema of type: '" + message.GetType() + "'");
                }
            }
            else if (code == Protocol.LEAVE_ROOM)
            {
                await Leave();
            }
            else if (code == Protocol.ROOM_STATE)
            {
                Debug.Log("ROOM_STATE");
                SetState(bytes, 1);
            }
            else if (code == Protocol.ROOM_STATE_PATCH)
            {
                Debug.Log("ROOM_STATE_PATCH");
                Patch(bytes, 1);
            }
            else if (code == Protocol.ROOM_DATA)
            {
                IMessageHandler handler = null;
                object          type;

                Schema.Iterator it = new Schema.Iterator {
                    Offset = 1
                };

                if (Decode.NumberCheck(bytes, it))
                {
                    type = Decode.DecodeNumber(bytes, it);
                    OnMessageHandlers.TryGetValue("i" + type, out handler);
                }
                else
                {
                    type = Decode.DecodeString(bytes, it);
                    OnMessageHandlers.TryGetValue(type.ToString(), out handler);
                }

                if (handler != null)
                {
                    //
                    // MsgPack deserialization can be optimized:
                    // https://github.com/deniszykov/msgpack-unity3d/issues/23
                    //
                    var message = (bytes.Length > it.Offset)
                                                ? MsgPack.Deserialize(handler.Type, new MemoryStream(bytes, it.Offset, bytes.Length - it.Offset, false))
                                                : null;

                    handler.Invoke(message);
                }
                else
                {
                    Debug.LogWarning("room.OnMessage not registered for: '" + type + "'");
                }
            }
        }
Esempio n. 23
0
        void OnMessageReceived(NetworkEvent netEvent, bool reliable)
        {
            var bytes  = netEvent.GetDataAsByteArray();
            var packet = Packet.Deserialize(bytes);

            // If packet is null, it is a "raw" byte array message.
            // Forward it to everyone
            if (packet == null)
            {
                OnGetBytes.TryInvoke(netEvent.ConnectionId, bytes, reliable);
                foreach (var r in ConnectionIds)
                {
                    // Forward to everyone except the original sender and the server
                    if (r == CId || r == netEvent.ConnectionId)
                    {
                        continue;
                    }
                    Send(Packet.From(CId).To(r).With(ReservedTags.PacketForwarding, packet.Serialize()), true);
                }
                return;
            }


            string reservedTag = packet.Tag.StartsWith("reserved") ? packet.Tag : string.Empty;

            // If is not a reserved message
            if (reservedTag == string.Empty)
            {
                OnGetPacket.TryInvoke(netEvent.ConnectionId, packet, reliable);

                if (NodeState != State.Server)
                {
                    return;
                }

                // The server tries to broadcast the packet to everyone else listed as recipients
                foreach (var r in packet.Recipients)
                {
                    // Forward to everyone except the original sender and the server
                    if (r == CId.id || r == netEvent.ConnectionId.id)
                    {
                        continue;
                    }
                    Send(Packet.From(CId).To(r).With(ReservedTags.PacketForwarding, packet.Serialize()), true);
                }
                return;
            }

            // handle reserved messages
            switch (reservedTag)
            {
            case ReservedTags.ServerStopped:
                OnServerStopped.TryInvoke();
                break;

            case ReservedTags.ClientJoined:
                ConnectionIds.Add(netEvent.ConnectionId);
                OnJoin.TryInvoke(netEvent.ConnectionId);
                break;

            case ReservedTags.ClientLeft:
                ConnectionIds.Remove(netEvent.ConnectionId);
                OnLeave.TryInvoke(netEvent.ConnectionId);
                break;

            case ReservedTags.PacketForwarding:
                OnGetPacket.TryInvoke(netEvent.ConnectionId, packet, reliable);
                break;
            }
        }
Esempio n. 24
0
        public void Bind(Host host)
        {
            _host = host;
            _host.AddHandler((short)LobbyMessages.RoomCreated, (m, c) => {
                if (RoomCreated != null)
                {
                    var ds        = DataStorage.CreateForRead(m.Body);
                    var roomToken = new Token();
                    roomToken.ReadFromDs(ds);

                    RoomCreated.Invoke(roomToken);
                }
            });
            _host.AddHandler((short)LobbyMessages.PlayerLeaved, (m, c) => {
                if (OnPlayerLeaved != null)
                {
                    var ds          = DataStorage.CreateForRead(m.Body);
                    var playerToken = new Token();
                    playerToken.ReadFromDs(ds);
                    OnPlayerLeaved.Invoke(playerToken);
                }
            });
            _host.AddHandler((short)LobbyMessages.SuccesfullyLeaved, (m, c) => {
                if (OnLeave != null)
                {
                    OnLeave.Invoke();
                }
            });
            _host.AddHandler((short)LobbyMessages.PlayerJoined, (m, c) => {
                if (OnPlayerJoined != null)
                {
                    var ds          = DataStorage.CreateForRead(m.Body);
                    var playerToken = new Token();
                    playerToken.ReadFromDs(ds);
                    OnPlayerJoined.Invoke(playerToken);
                }
            });
            _host.AddHandler((short)LobbyMessages.SuccesfullyJoined, (m, c) => {
                if (OnJoin != null)
                {
                    OnJoin.Invoke();
                }
            });
            _host.AddHandler((short)LobbyMessages.GameStarted, (m, c) => {
                if (OnGameStarted != null)
                {
                    var ds     = DataStorage.CreateForRead(m.Body);
                    _roomToken = new Token();
                    _roomToken.ReadFromDs(ds);
                    OnGameStarted.Invoke();
                }
            });
            _host.AddHandler((short)LobbyMessages.GetRoomsResponse, (m, c) => {
                if (OnRoomInfoRecieved != null)
                {
                    var roomTokens = new List <Token>();
                    roomTokens.FillDeserialize(m.Body);
                    OnRoomInfoRecieved.Invoke(roomTokens);
                }
            });
        }