コード例 #1
0
 public void AddReturnsExpected(
     UnixTimestamp timestamp1,
     UnixTimestamp timestamp2)
 {
     var expected = timestamp1 + timestamp2;
     Assert.Equal(expected, timestamp1.Add(timestamp2));
 }
コード例 #2
0
        public void CanAddTwoUnixTimestamps(
            UnixTimestamp a,
            UnixTimestamp b)
        {
            var expected = new UnixTimestamp(a.SecondsSinceEpoch + b.SecondsSinceEpoch);
            var actual = a + b;

            Assert.Equal(expected, actual);
        }
コード例 #3
0
ファイル: UnixTimestamp.cs プロジェクト: AnotherAltr/Rc.Core
        public static bool TryParse(string value, out UnixTimestamp result)
        {
            result = new UnixTimestamp();

            long seconds;
            if (!long.TryParse(value, out seconds))
                return false;

            result = new UnixTimestamp(seconds);
            return true;
        }
コード例 #4
0
ファイル: C_Parser.cs プロジェクト: danij/IRCService.NET
        public override void Parse(string[] spaceSplit, string[] colonSplit, 
            string fullRow)
        {
            if (spaceSplit.Count() < 4)
            {
                return;
            }
            if (spaceSplit[0].Length != 5)
            {
                return;
            }

            var user = Service.GetUser(spaceSplit[0]);
            if (user == null)
            {
                Service.AddLog("Unknown user " + spaceSplit[0] + " creates channel "
                    + spaceSplit[2]);
                return;
            }

            UnixTimestamp creationTimestamp = 
                new UnixTimestamp(Convert.ToInt32(spaceSplit[3]));
            string[] channels = spaceSplit[2].Split(',');

            IChannel currentChannel;

            foreach (string item in channels)
            {
                currentChannel = Service.GetChannel(item);
                if (currentChannel == null)
                {
                    currentChannel = Service.CreateChannel(item, creationTimestamp);
                    Service.SendActionToPlugins(p => p.OnNewChannel(currentChannel));
                }
                else
                {
                    (currentChannel as Channel).CreationTimeStamp = creationTimestamp;
                }

                if (user.Server.GetChannel(item) == null)
                {
                    (user.Server as Server).AddChannel(currentChannel);
                }

                if ((currentChannel as Channel).AddUser(user, true, false, false))
                {
                    Service.SendActionToPlugins(
                        p => p.OnChannelJoin(currentChannel, user),
                        user.Plugin
                    );
                }
            }
        }
コード例 #5
0
ファイル: Channel.cs プロジェクト: danij/IRCService.NET
 /// <summary>
 /// Default constructor
 /// </summary>
 /// <param name="name"></param>
 /// <param name="creationTimeStamp"></param>
 public Channel(IRCService service, string name, 
     UnixTimestamp creationTimeStamp = null)
 {
     Name = name;
     Key = "";
     modes = 0;
     Limit = 0;
     Service = service;
     if (creationTimestamp == null)
     {
         creationTimestamp = UnixTimestamp.CurrentTimestamp();
     }
     creationTimestamp = creationTimeStamp;
     bans = new List<Ban>();
     invitations = new List<IUser>();
 }
コード例 #6
0
ファイル: User.cs プロジェクト: danij/IRCService.NET
 /// <summary>
 /// Default constructor
 /// </summary>
 /// <param name="server"></param>
 /// <param name="numeric"></param>
 /// <param name="nick"></param>
 /// <param name="ident"></param>
 /// <param name="host"></param>
 /// <param name="name"></param>
 /// <param name="connectionTimestamp"></param>
 /// <param name="base64IP"></param>
 public User(IServer server, string numeric, string nick, string ident, 
     string host, string name, UnixTimestamp connectionTimestamp, 
     string base64IP, IRCServicePlugin plugin = null)
 {
     Numeric = numeric;
     Nick = nick;
     Ident = ident;
     Host = host;
     Name = name;
     Base64IP = base64IP;
     Server = server;
     ConnectionTimestamp = connectionTimestamp;
     FakeIdent = "";
     FakeHost = "";
     Login = "";
     Plugin = plugin;
     channels = new Dictionary<string, ChannelEntry>
         (StringComparer.OrdinalIgnoreCase);
     if (Server.IsControlled)
     {
         action = new UserAction(this);
     }
 }
コード例 #7
0
ファイル: Server.cs プロジェクト: danij/IRCService.NET
 /// <summary>
 /// Constructs a new Server
 /// </summary>
 /// <param name="service">The service that the server belongs to</param>
 /// <param name="numeric">The servers numeric</param>
 /// <param name="name">The servers name</param>
 /// <param name="description">The servers description</param>
 /// <param name="created">The servers creation timestamp</param>
 /// <param name="maxUsers">The maximum ammount of users on the server (1-262143)</param>
 /// <param name="controlled">Is the server controlled by the service?</param>
 /// <param name="upLink">Tbe servers uplink</param>
 public Server(IRCService service, string numeric, string name, 
     string description, UnixTimestamp created, int maxUsers,
     bool controlled, IServer upLink)
 {
     Service = service;
     Numeric = numeric;
     Name = name;
     Description = description;
     Created = created;
     MaxUsers = maxUsers;
     if (MaxUsers < 0)
     {
         MaxUsers = 1;
     }
     if (MaxUsers > 262143)
     {
         MaxUsers = 262143;
     }
     UpLink = upLink;
     IsControlled = controlled;
     users = new Dictionary<string, IUser>();
     channels = new Dictionary<string, IChannel>(StringComparer.CurrentCultureIgnoreCase);
     ChannelEntries = new Dictionary<IChannel, IEnumerable<ChannelEntry>>();
 }
コード例 #8
0
 public void ToStringReturnsExpected(
     UnixTimestamp sut)
 {
     Assert.Equal(sut.SecondsSinceEpoch.ToString(CultureInfo.InvariantCulture), sut.ToString());
 }
コード例 #9
0
        public override void Compose(ServerPacket packet)
        {
            packet.WriteInteger(Tickets.Count);
            foreach (ModerationTicket Ticket in Tickets)
            {
                packet.WriteInteger(Ticket.Id);                                                                                             // Id
                packet.WriteInteger(Ticket.GetStatus(Id));                                                                                  // Tab ID
                packet.WriteInteger(Ticket.Type);                                                                                           // Type
                packet.WriteInteger(Ticket.Category);                                                                                       // Category
                packet.WriteInteger(Convert.ToInt32((DateTime.Now - UnixTimestamp.FromUnixTimestamp(Ticket.Timestamp)).TotalMilliseconds)); // This should fix the overflow?
                packet.WriteInteger(Ticket.Priority);                                                                                       // Priority
                packet.WriteInteger(Ticket.Sender == null ? 0 : Ticket.Sender.Id);                                                          // Sender ID
                packet.WriteInteger(1);
                packet.WriteString(Ticket.Sender == null ? string.Empty : Ticket.Sender.Username);                                          // Sender Name
                packet.WriteInteger(Ticket.Reported == null ? 0 : Ticket.Reported.Id);                                                      // Reported ID
                packet.WriteString(Ticket.Reported == null ? string.Empty : Ticket.Reported.Username);                                      // Reported Name
                packet.WriteInteger(Ticket.Moderator == null ? 0 : Ticket.Moderator.Id);                                                    // Moderator ID
                packet.WriteString(Ticket.Moderator == null ? string.Empty : Ticket.Moderator.Username);                                    // Mod Name
                packet.WriteString(Ticket.Issue);                                                                                           // Issue
                packet.WriteInteger(Ticket.Room == null ? 0 : Ticket.Room.Id);                                                              // Room Id
                packet.WriteInteger(0);                                                                                                     //LOOP
            }

            packet.WriteInteger(UserPresets.Count);
            foreach (string pre in UserPresets)
            {
                packet.WriteString(pre);
            }

            /*base.WriteInteger(UserActionPresets.Count);
             * foreach (KeyValuePair<string, List<ModerationPresetActionMessages>> Cat in UserActionPresets.ToList())
             * {
             *  base.WriteString(Cat.Key);
             *  base.WriteBoolean(true);
             *  base.WriteInteger(Cat.Value.Count);
             *  foreach (ModerationPresetActionMessages Preset in Cat.Value.ToList())
             *  {
             *      base.WriteString(Preset.Caption);
             *      base.WriteString(Preset.MessageText);
             *      base.WriteInteger(Preset.BanTime); // Account Ban Hours
             *      base.WriteInteger(Preset.IPBanTime); // IP Ban Hours
             *      base.WriteInteger(Preset.MuteTime); // Mute in Hours
             *      base.WriteInteger(0);//Trading lock duration
             *      base.WriteString(Preset.Notice + "\n\nPlease Note: Avatar ban is an IP ban!");
             *      base.WriteBoolean(false);//Show HabboWay
             *  }
             * }*/

            // TODO: Figure out
            packet.WriteInteger(0);
            {
                //Loop a string.
            }

            packet.WriteBoolean(true); // Ticket right
            packet.WriteBoolean(true); // Chatlogs
            packet.WriteBoolean(true); // User actions alert etc
            packet.WriteBoolean(true); // Kick users
            packet.WriteBoolean(true); // Ban users
            packet.WriteBoolean(true); // Caution etc
            packet.WriteBoolean(true); // Love you, Tom

            packet.WriteInteger(RoomPresets.Count);
            foreach (string pre in RoomPresets)
            {
                packet.WriteString(pre);
            }
        }
コード例 #10
0
        public void SameUnixTimestampReturnsExpectedEquality(
            [Frozen] long secondsSinceEpoch)
        {
            var timestamp1 = new UnixTimestamp(secondsSinceEpoch);
            var timestamp2 = new UnixTimestamp(secondsSinceEpoch);

            Assert.True(timestamp1 == timestamp2);
        }
コード例 #11
0
ファイル: UnixTimestamp.cs プロジェクト: AnotherAltr/Rc.Core
 /// <summary>
 /// Adds the specified <see cref="UnixTimestamp" /> to this instance
 /// and returns a new instance of UnixTimestamp
 /// </summary>
 public UnixTimestamp Add(UnixTimestamp unixTimestamp)
 {
     return new UnixTimestamp(secondsSinceEpoch + unixTimestamp);
 }
コード例 #12
0
        public void Parse(GameClient session, ClientPacket packet)
        {
            if (session == null || session.GetHabbo() == null || !session.GetHabbo().InRoom)
            {
                return;
            }

            var room = session.GetHabbo().CurrentRoom;

            if (room == null)
            {
                return;
            }

            var user = room.GetRoomUserManager().GetRoomUserByHabbo(session.GetHabbo().Id);

            if (user == null)
            {
                return;
            }

            var message = StringCharFilter.Escape(packet.PopString());

            if (message.Length > 100)
            {
                message = message.Substring(0, 100);
            }

            var colour = packet.PopInt();

            ChatStyle style = null;

            if (!PlusEnvironment.GetGame().GetChatManager().GetChatStyles().TryGetStyle(colour, out style) ||
                style.RequiredRight.Length > 0 && !session.GetHabbo().GetPermissions().HasRight(style.RequiredRight))
            {
                colour = 0;
            }

            user.UnIdle();

            if (PlusEnvironment.GetUnixTimestamp() < session.GetHabbo().FloodTime&& session.GetHabbo().FloodTime != 0)
            {
                return;
            }

            if (session.GetHabbo().TimeMuted > 0)
            {
                session.SendPacket(new MutedComposer(session.GetHabbo().TimeMuted));
                return;
            }

            if (!session.GetHabbo().GetPermissions().HasRight("room_ignore_mute") && room.CheckMute(session))
            {
                session.SendWhisper("Oops, you're currently muted.");
                return;
            }

            user.LastBubble = session.GetHabbo().CustomBubbleId == 0 ? colour : session.GetHabbo().CustomBubbleId;

            if (!session.GetHabbo().GetPermissions().HasRight("mod_tool"))
            {
                int muteTime;
                if (user.IncrementAndCheckFlood(out muteTime))
                {
                    session.SendPacket(new FloodControlComposer(muteTime));
                    return;
                }
            }

            PlusEnvironment.GetGame().GetChatManager().GetLogs()
            .StoreChatlog(new ChatlogEntry(session.GetHabbo().Id, room.Id, message, UnixTimestamp.GetNow(), session.GetHabbo(), room));

            if (message.StartsWith(":", StringComparison.CurrentCulture) && PlusEnvironment.GetGame().GetChatManager().GetCommands().Parse(session, message))
            {
                return;
            }

            if (PlusEnvironment.GetGame().GetChatManager().GetFilter().CheckBannedWords(message))
            {
                session.GetHabbo().BannedPhraseCount++;
                if (session.GetHabbo().BannedPhraseCount >= Convert.ToInt32(PlusEnvironment.GetSettingsManager().TryGetValue("room.chat.filter.banned_phrases.chances")))
                {
                    PlusEnvironment.GetGame().GetModerationManager().BanUser("System", ModerationBanType.Username, session.GetHabbo().Username,
                                                                             "Spamming banned phrases (" + message + ")", PlusEnvironment.GetUnixTimestamp() + 78892200);
                    session.Disconnect();
                    return;
                }

                session.SendPacket(new ChatComposer(user.VirtualId, message, 0, colour));
                return;
            }

            if (!session.GetHabbo().GetPermissions().HasRight("word_filter_override"))
            {
                message = PlusEnvironment.GetGame().GetChatManager().GetFilter().CheckMessage(message);
            }

            PlusEnvironment.GetGame().GetQuestManager().ProgressUserQuest(session, QuestType.SocialChat);

            user.OnChat(user.LastBubble, message, false);
        }
コード例 #13
0
 public static CharacterInfo GenerateNullCharacter(uint uint_0)
 {
     return(new CharacterInfo(null, 0, 0, "Unknown", string.Empty, "BoomBang", 1, string.Empty, string.Empty, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, UnixTimestamp.GetCurrent(), UnixTimestamp.GetCurrent()));
 }
コード例 #14
0
        public static void HandleRegister(Client pClient, MsgRegister pMsg)
        {
            Client trash;

            if (pMsg.CancelRequest)
            {
                try
                {
                    pClient.Disconnect();
                }
                catch
                {
                    ServerKernel.Players.TryRemove(pClient.Identity, out trash);
                    ServerKernel.CharacterCreation.TryRemove(pClient.Identity, out trash);
                    ServerKernel.CharacterCreation.TryRemove(pClient.AccountIdentity, out trash);
                }
                return;
            }

            if (ServerKernel.CharacterCreation.TryGetValue(pClient.AccountIdentity, out trash))
            {
                trash = null;

                if (CheckName(pMsg.Name))
                {
                    var pRepository = new CharacterRepository();
                    if (pRepository.AccountHasCharacter(pClient.AccountIdentity))
                    {
                        //DisconnectWithMsg(pClient, ServerMessages.CharacterCreation.AccountHasCharacter);
                        pClient.Send(ServerMessages.CharacterCreation.AccountHasCharacter);
                        return;
                    }
                    if (pRepository.CharacterExists(pMsg.Name))
                    {
                        //DisconnectWithMsg(pClient, ServerMessages.CharacterCreation.NameTaken);
                        pClient.Send(ServerMessages.CharacterCreation.NameTaken);
                        return;
                    }

                    ProfessionType profession = ((ProfessionType)pMsg.Profession > ProfessionType.INTERN_TAOIST
                        ? ProfessionType.INTERN_TAOIST
                        : (ProfessionType)(pMsg.Profession / 10 * 10));
                    if (!Enum.IsDefined(typeof(BodyType), pMsg.Body) ||
                        !Enum.IsDefined(typeof(ProfessionType), profession))
                    {
                        // The client is a proxy exploiting the server. Disconnect the client.
                        DisconnectWithMsg(pClient, ServerMessages.CharacterCreation.AccessDenied);
                        return;
                    }

                    switch (profession)
                    {
                    case ProfessionType.INTERN_ARCHER:
                    case ProfessionType.INTERN_NINJA:
                    case ProfessionType.INTERN_TAOIST:
                    case ProfessionType.INTERN_TROJAN:
                    case ProfessionType.INTERN_WARRIOR:
                    case ProfessionType.INTERN_MONK:
                        break;

                    default:
                    {
                        DisconnectWithMsg(pClient, ServerMessages.CharacterCreation.AccessDenied);
                        return;
                    }
                    }

                    ushort hair     = 410;
                    uint   lookface = 0;
                    if (pMsg.Body == (ushort)BodyType.THIN_MALE || pMsg.Body == (ushort)BodyType.HEAVY_MALE)
                    {
                        if ((pMsg.Profession / 10) == 5)
                        {
                            lookface = (uint)(new Random().Next(103, 107));
                        }
                        else if ((pMsg.Profession / 10) == 6)
                        {
                            lookface = (uint)(new Random().Next(109, 113));
                        }
                        else
                        {
                            lookface = (uint)(new Random().Next(1, 102));
                        }
                    }
                    else
                    {
                        hair = 410;
                        if ((pMsg.Profession / 10) == 5)
                        {
                            lookface = (uint)(new Random().Next(291, 295));
                        }
                        else if ((pMsg.Profession / 10) == 6)
                        {
                            lookface = (uint)(new Random().Next(300, 304));
                        }
                        else
                        {
                            lookface = (uint)(new Random().Next(201, 290));
                        }
                    }

                    #region Initial HairStyle and Lookface for monks
                    switch (profession)
                    {
                    case ProfessionType.INTERN_MONK:
                        if (pMsg.Body == (ushort)BodyType.THIN_MALE)
                        {
                            lookface = (uint)(new Random().Next(109, 113));
                            hair     = 400;
                        }
                        else if (pMsg.Body == (ushort)BodyType.HEAVY_MALE)
                        {
                            lookface = (uint)(new Random().Next(129, 133));
                            hair     = 400;
                        }
                        else if (pMsg.Body == (ushort)BodyType.THIN_FEMALE)
                        {
                            lookface = (uint)(new Random().Next(300, 304));
                        }
                        else if (pMsg.Body == (ushort)BodyType.HEAVY_FEMALE)
                        {
                            lookface = (uint)(new Random().Next(325, 329));
                        }
                        break;
                    }
                    #endregion

                    DbPointAllot points =
                        ServerKernel.PointAllot.Values.FirstOrDefault(
                            x => x.Profession == ((pMsg.Profession - (pMsg.Profession % 10)) / 10) && x.Level == 1);
                    if (points == null)
                    {
                        pClient.Send(new MsgTalk("Could not fetch class attribute points.", ChatTone.CHARACTER_CREATION));
                        return;
                    }

                    int    idx    = new Random().Next(m_startX.Length - 1);
                    ushort startX = m_startX[idx];
                    ushort startY = m_startY[idx];

                    switch (profession)
                    {
                    case ProfessionType.INTERN_TROJAN:
                    case ProfessionType.INTERN_WARRIOR:
                    case ProfessionType.INTERN_ARCHER:
                    case ProfessionType.INTERN_NINJA:
                    case ProfessionType.INTERN_TAOIST:
                    case ProfessionType.INTERN_MONK:
                    {
                        break;
                    }

                    default:
                        DisconnectWithMsg(pClient, ServerMessages.CharacterCreation.AccessDenied);
                        return;
                    }

                    uint money = 10000, emoney = 270;
                    if (pClient.VipLevel == 6)
                    {
                        money  *= 10;
                        emoney *= 5;
                    }

                    ushort startLife = (ushort)(((points.Agility + points.Strength + points.Spirit) * 3) + points.Vitality * 24);

                    var newUser = new DbUser
                    {
                        AccountId           = pClient.AccountIdentity,
                        Name                = pMsg.Name,
                        Lookface            = pMsg.Body + (lookface * 10000),
                        Profession          = (byte)profession,
                        Mate                = "None",
                        AdditionalPoints    = 0,
                        Agility             = points.Agility,
                        Strength            = points.Strength,
                        Vitality            = points.Vitality,
                        Spirit              = points.Spirit,
                        AutoAllot           = 1,
                        AutoExercise        = 0,
                        BoundEmoney         = 4300,
                        Business            = 255,
                        CoinMoney           = 0,
                        CurrentLayout       = 0,
                        Donation            = 0,
                        Emoney              = emoney,
                        Experience          = 0,
                        Level               = 1,
                        FirstProfession     = 0,
                        Metempsychosis      = 0,
                        Flower              = 0,
                        HomeId              = 0,
                        LastLogin           = 0,
                        LastLogout          = 0,
                        LastProfession      = 0,
                        Life                = startLife,
                        LockKey             = 0,
                        Hair                = hair,
                        Mana                = 0,
                        MapId               = _START_MAP,
                        MapX                = startX,
                        MapY                = startY,
                        MeteLevel           = 0,
                        Money               = money,
                        MoneySaved          = 0,
                        Orchids             = 0,
                        PkPoints            = 0,
                        RedRoses            = 0,
                        StudentPoints       = 0,
                        Tulips              = 0,
                        Virtue              = 0,
                        WhiteRoses          = 0,
                        EnlightPoints       = 0,
                        HeavenBlessing      = (uint)(UnixTimestamp.Timestamp() + 60 * 60 * 24 * 30),
                        ExperienceExpires   = (uint)(UnixTimestamp.Timestamp() + 60 * 60 * 24),
                        ExperienceMultipler = 10
                    };

                    if (pRepository.CreateNewCharacter(newUser))
                    {
                        uint idUser = newUser.Identity;

                        try
                        {
                            GenerateInitialStatus(idUser, profession);
                        }
                        catch
                        {
                            ServerKernel.Log.SaveLog("Could not create initial status for character " + idUser, true, LogType.ERROR);
                        }
                        ServerKernel.Log.SaveLog(string.Format("User [({0}){1}] has created character {2}.",
                                                               pClient.AccountIdentity, idUser, newUser.Name), true);

                        pClient.Send(ServerMessages.CharacterCreation.AnswerOk);
                        return;
                    }
                }
                else
                {
                    //DisconnectWithMsg(pClient, ServerMessages.CharacterCreation.InvalidName);
                    pClient.Send(ServerMessages.CharacterCreation.InvalidName);
                    return;
                }
            }
            else
            {
                DisconnectWithMsg(pClient, ServerMessages.CharacterCreation.AccessDenied);
                return;
            }
        }
コード例 #15
0
        public void ProcessMsgAuth(Client pClient, byte[] pMsg)
        {
            if (pClient != null && pClient.Packet != null) // check if it's alright
            {
                byte[] pPacket = pClient.Packet;
                var    pType   = (PacketType)BitConverter.ToInt16(pPacket, 2);

                if (BitConverter.ToUInt16(pPacket, 0) == 276 &&
                    (pType == PacketType.MSG_ACCOUNT1))
                {
                    var pRequest = new MsgAccount(pPacket, pClient.IpAddress.GetHashCode());

                    // tells the console that the user x is trying to login on server y
                    ServerKernel.Log.SaveLog(string.Format("User [{0}] is trying to login on server [{1}].",
                                                           pClient.Account, pRequest.Server), false, "Login_Server");

                    // let's check if user is spamming login requests
                    LoginAttemptRecord pLogin = null;
                    if (!ServerKernel.LoginAttemptRecords.TryGetValue(pClient.IpAddress, out pLogin))
                    {
                        pLogin = new LoginAttemptRecord(pClient.IpAddress);
                        ServerKernel.LoginAttemptRecords.TryAdd(pLogin.IpAddress, pLogin);
                    }

                    if (!pLogin.Enabled) // user spamming login?
                    {
                        pClient.Send(new MsgConnectEx(RejectionType.MAXIMUM_LOGIN_ATTEMPTS));
                        ServerKernel.Log.SaveLog(
                            string.Format("User [{0}] has passport denied due to exceeding login limit on IP [{1}].",
                                          pRequest.Account, pClient.IpAddress), true, "Login_Server");
                        pClient.Disconnect();
                        return;
                    }

                    DbAccount pUser = new AccountRepository().SearchByName(pRequest.Account); // fetch user information
                    if (pUser != null)                                                        // user exists?
                    {
                        // yes
                        pClient.Account = pUser;

                        // check uncommon characters
                        var szPw = string.Empty;
                        foreach (var c in pRequest.Password)
                        {
                            switch (c)
                            {
                            case '-':
                                szPw += '0';
                                break;

                            case '#':
                                szPw += '1';
                                break;

                            case '(':
                                szPw += '2';
                                break;

                            case '"':
                                szPw += '3';
                                break;

                            case '%':
                                szPw += '4';
                                break;

                            case '\f':
                                szPw += '5';
                                break;

                            case '\'':
                                szPw += '6';
                                break;

                            case '$':
                                szPw += '7';
                                break;

                            case '&':
                                szPw += '8';
                                break;

                            case '!':
                                szPw += '9';
                                break;

                            default:
                                szPw += c;
                                break;
                            }
                        }

                        //bool bSuccess = true;
                        // check if user has input the right password
                        if (pUser.Password != WhirlpoolHash.Hash(szPw))
                        {
                            // invalid pw
                            pClient.Send(new MsgConnectEx(RejectionType.INVALID_PASSWORD));
                            ServerKernel.Log.SaveLog(
                                string.Format("User [{0}] entered an invalid password [{1}].", pUser.Username,
                                              pClient.IpAddress), true, "LoginServer");
                            pClient.Disconnect();
                            return;
                        }

                        if (pUser.Lock > 0) // user is banned?
                        {
                            if (pUser.Lock >= 3 || pUser.LockExpire == 0 || UnixTimestamp.Timestamp() < pUser.LockExpire)
                            {
                                // banned
                                pClient.Send(new MsgConnectEx(RejectionType.ACCOUNT_BANNED));
                                ServerKernel.Log.SaveLog(
                                    string.Format("User [{0}] has passport denied due to account lock status.",
                                                  pUser.Username), true, "LoginServer");
                                pClient.Disconnect();
                                return;
                            }
                        }

                        //if (pUser.Lock == 2) // user has activated account?
                        //{
                        //    pClient.Send(new MsgConnectEx(RejectionType.ACCOUNT_NOT_ACTIVATED));
                        //    ServerKernel.Log.SaveLog(
                        //        string.Format("User [{0}] has passport denied due to account inactive status.",
                        //            pUser.Username), true, "LoginServer");

                        //    pClient.Disconnect();
                        //    return;
                        //}

                        // temporary just to leave people join using any server
                        GameServer pServer = ServerKernel.OnlineServers.Values.FirstOrDefault();
                        if (pServer == null)//!ServerKernel.OnlineServers.TryGetValue(pRequest.Server, out pServer))
                        // server is not online
                        {
                            pClient.Send(new MsgConnectEx(RejectionType.SERVER_MAINTENANCE));
                            ServerKernel.Log.SaveLog(
                                string.Format("User [{0}] tried to login on a invalid server [{1}].", pUser.Username,
                                              pRequest.Server), true, "LoginServer");

                            pClient.Disconnect();
                            return;
                        }

                        uint dwHash = (uint)ThreadSafeRandom.RandGet(1000, int.MaxValue);

                        var pTransferCipher = new TransferCipher(ServerKernel.LoginTransferKey,
                                                                 ServerKernel.LoginTransferSalt, pClient.IpAddress);
                        var pCrypto = pTransferCipher.Encrypt(new[] { pUser.Identity, dwHash });

                        string szAddress = "135.12.15.139"; // random ip just to connect
                        if (!pServer.IpAddress.StartsWith("127") && pServer.IpAddress != "localhost")
                        {
                            szAddress = pServer.IpAddress;
                        }

                        pServer.Send(new MsgUsrLogin(pUser.Identity, dwHash)
                        {
                            IpAddress = pClient.IpAddress
                        });

                        pClient.Send(new MsgConnectEx(pCrypto[0], pCrypto[1], szAddress, 5816));
                        ServerKernel.Log.SaveLog(string.Format("User [{0}] has successfully logged into {1}({2}:{3}).",
                                                               pUser.Username, pRequest.Server, szAddress, pServer.GamePort), true, "Login_Server", LogType.MESSAGE);

                        pUser.LastLogin = UnixTimestamp.Timestamp();
                        new AccountRepository().SaveOrUpdate(pUser);
                        return;
                    }
                    else
                    {
                        // no
                        pClient.Send(new MsgConnectEx(RejectionType.INVALID_PASSWORD));
                        ServerKernel.Log.SaveLog(
                            string.Format("User [{0}] doesn't exist. Connection [{1}].", pRequest.Account,
                                          pClient.IpAddress), true, "Login_Server");
                    }
                }
                else
                {
                    pClient.Send(new MsgConnectEx(RejectionType.INVALID_AUTHENTICATION_PROTOCOL));
                    ServerKernel.Log.SaveLog(string.Format("User has tried to connect with an invalid protocol at {0}.", pClient.IpAddress));
                }

                pClient.Disconnect();
            }
        }
コード例 #16
0
        public void Parse(GameClient Session, ClientPacket Packet)
        {
            if (!Session.GetHabbo().InRoom)
            {
                return;
            }

            Room Room = Session.GetHabbo().CurrentRoom;

            if (Room == null)
            {
                return;
            }

            if (!Session.GetHabbo().GetPermissions().HasRight("mod_tool") && Room.CheckMute(Session))
            {
                Session.SendWhisper("Bem, atualmente voce esta  mutado.");
                return;
            }

            if (BiosEmuThiago.GetUnixTimestamp() < Session.GetHabbo().FloodTime&& Session.GetHabbo().FloodTime != 0)
            {
                return;
            }

            string Params  = Packet.PopString();
            string ToUser  = Params.Split(' ')[0];
            string Message = Params.Substring(ToUser.Length + 1);
            int    Colour  = Packet.PopInt();

            RoomUser User = Room.GetRoomUserManager().GetRoomUserByHabbo(Session.GetHabbo().Id);

            if (User == null)
            {
                return;
            }

            RoomUser User2 = Room.GetRoomUserManager().GetRoomUserByHabbo(ToUser);

            if (User2 == null)
            {
                return;
            }

            if (Session.GetHabbo().TimeMuted > 0)
            {
                Session.SendMessage(new MutedComposer(Session.GetHabbo().TimeMuted));
                return;
            }

            ChatStyle Style = null;

            if (!BiosEmuThiago.GetGame().GetChatManager().GetChatStyles().TryGetStyle(Colour, out Style) || (Style.RequiredRight.Length > 0 && !Session.GetHabbo().GetPermissions().HasRight(Style.RequiredRight)))
            {
                Colour = 0;
            }

            User.LastBubble = Session.GetHabbo().CustomBubbleId == 0 ? Colour : Session.GetHabbo().CustomBubbleId;

            if (!Session.GetHabbo().GetPermissions().HasRight("mod_tool"))
            {
                int MuteTime;
                if (User.IncrementAndCheckFlood(out MuteTime))
                {
                    Session.SendMessage(new FloodControlComposer(MuteTime));
                    return;
                }
            }

            if (!User2.GetClient().GetHabbo().ReceiveWhispers&& !Session.GetHabbo().GetPermissions().HasRight("room_whisper_override"))
            {
                Session.SendWhisper("Bem, este usuário desativou seus sussurros!");
                return;
            }

            BiosEmuThiago.GetGame().GetChatManager().GetLogs().StoreChatlog(new ChatlogEntry(Session.GetHabbo().Id, Room.Id, "<Susurra a " + ToUser + ">: " + Message, UnixTimestamp.GetNow(), Session.GetHabbo(), Room));

            string word;

            if (!Session.GetHabbo().GetPermissions().HasRight("word_filter_override") &&
                BiosEmuThiago.GetGame().GetChatManager().GetFilter().IsUnnaceptableWord(Message, out word))
            {
                Session.GetHabbo().BannedPhraseCount++;
                if (Session.GetHabbo().BannedPhraseCount >= 1)
                {
                    User.MoveTo(Room.GetGameMap().Model.DoorX, Room.GetGameMap().Model.DoorY);
                    Session.GetHabbo().TimeMuted = 25;
                    Session.SendNotification("Você foi silenciad@ um moderador vai ver seu caso, aparentemente, você nomeou um hotel! <b>Aviso: " + Session.GetHabbo().BannedPhraseCount + "/5</b>");
                    BiosEmuThiago.GetGame().GetClientManager().StaffAlert(new RoomNotificationComposer("Alerta de divulgação:",
                                                                                                       "Atenção mencionou a palavra <b>" + word.ToUpper() + "</b> na frase <i>" + Message +
                                                                                                       "</i> dentro de uma sala\r\n" + "- Este usuario: <b>" +
                                                                                                       Session.GetHabbo().Username + "</b>", NotificationSettings.NOTIFICATION_FILTER_IMG, "Ir a Sala", "event:navigator/goto/" +
                                                                                                       Session.GetHabbo().CurrentRoomId));
                }
                if (Session.GetHabbo().BannedPhraseCount >= 3)
                {
                    BiosEmuThiago.GetGame().GetModerationManager().BanUser("System", HabboHotel.Moderation.ModerationBanType.USERNAME, Session.GetHabbo().Username, "Banido por spam (" + Message + ")", (BiosEmuThiago.GetUnixTimestamp() + 78892200));
                    Session.Disconnect();
                    return;
                }

                Session.SendMessage(new WhisperComposer(User.VirtualId, "Palavra Inapropriada.", 0, User.LastBubble));
                return;
            }

            BiosEmuThiago.GetGame().GetQuestManager().ProgressUserQuest(Session, QuestType.SOCIAL_CHAT);

            User.UnIdle();
            User.GetClient().SendMessage(new WhisperComposer(User.VirtualId, Message, 0, User.LastBubble));

            if (User2 != null && !User2.IsBot && User2.UserId != User.UserId)
            {
                if (!User2.GetClient().GetHabbo().MutedUsers.Contains(Session.GetHabbo().Id))
                {
                    User2.GetClient().SendMessage(new WhisperComposer(User.VirtualId, Message, 0, User.LastBubble));
                }
            }

            List <RoomUser> ToNotify = Room.GetRoomUserManager().GetRoomUserByRank(2);

            if (ToNotify.Count > 0)
            {
                foreach (RoomUser user in ToNotify)
                {
                    if (user != null && user.HabboId != User2.HabboId && user.HabboId != User.HabboId)
                    {
                        if (user.GetClient() != null && user.GetClient().GetHabbo() != null && !user.GetClient().GetHabbo().IgnorePublicWhispers)
                        {
                            user.GetClient().SendMessage(new WhisperComposer(User.VirtualId, "[Susurra a " + ToUser + "] " + Message, 0, User.LastBubble));
                        }
                    }
                }
            }
        }
コード例 #17
0
ファイル: ProblemViewer.cs プロジェクト: maestrofx/UVA-Arena
        private void LoadSubmission()
        {
            if (current == null)
            {
                return;
            }

            string user = (string)usernameList1.Tag;
            string uid  = LocalDatabase.GetUserid(user);

            submissionStatus.ClearObjects();

            long   start, stop;
            string url = "", format;

            switch (_curSubType)
            {
            case SubViewType.LastSubmission:
                start  = UnixTimestamp.ToUnixTime(dateTimePicker1.Value);
                stop   = UnixTimestamp.ToUnixTime(DateTime.Now);
                format = "http://uhunt.felix-halim.net/api/p/subs/{0}/{1}/{2}";     //pid, unix time start, stop
                url    = string.Format(format, current.pid, start, stop);
                Interactivity.SetStatus("Downloading last submissions on current problem...");
                break;

            case SubViewType.Ranklist:
                start  = 1;
                stop   = (long)numericUpDown1.Value;
                format = "http://uhunt.felix-halim.net/api/p/rank/{0}/{1}/{2}";     //pid, rank start, rank count
                url    = string.Format(format, current.pid, start, stop);
                Interactivity.SetStatus("Downloading ranks on current problem...");
                break;

            case SubViewType.UsersRank:
                start = stop = 10;
                if (string.IsNullOrEmpty(uid) || uid == "-")
                {
                    return;
                }
                format = "http://uhunt.felix-halim.net/api/p/ranklist/{0}/{1}/{2}/{3}";     //pid, uid, before_count, after_count
                url    = string.Format(format, current.pid, uid, start, stop);
                Interactivity.SetStatus("Downloading " + user + "'s rank-data on current problem...");
                break;

            case SubViewType.UsersSub:
                if (string.IsNullOrEmpty(uid) || uid == "-")
                {
                    return;
                }
                format = "http://uhunt.felix-halim.net/api/subs-nums/{0}/{1}/{2}";     //uid, pnum, last sid
                url    = string.Format(format, uid, current.pnum, 0);
                Interactivity.SetStatus("Downloading " + user + "'s submission on current problem...");
                break;

            case SubViewType.Comapre:
                List <string> uidcol = new List <string>();
                foreach (var val in LocalDatabase.usernames.Values)
                {
                    uidcol.Add(val);
                }
                if (uidcol.Count == 0)
                {
                    return;
                }
                format = "http://uhunt.felix-halim.net/api/subs-nums/{0}/{1}/0";     //uids(sep = comma), pnum
                url    = string.Format(format, string.Join(",", uidcol.ToArray()), current.pnum);
                Interactivity.SetStatus("Comparing user's on current problem...");
                break;
            }

            Downloader.DownloadStringAsync(url, user, Priority.Normal, dt_progressChanged, dt_taskCompleted);
        }
コード例 #18
0
        /// <summary>
        /// authLevel 认证等级(0-被封禁 1-标准用户 2-组员 3-组长 4-出题组 5-管理员)
        /// onlyInGaming 是否为在比赛允许时间内才可调用的API(默认为false,设为true时只有比赛期间内可以调用)
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <param name="authLevel"></param>
        /// <param name="onlyInGaming"></param>
        /// <returns></returns>
        public static async Task <UserSession> Check(Request request, Response response, AuthLevel authLevel, bool onlyInGaming = false)
        {
            IDictionary <string, object> headers = request.Header;

            if (!headers.ContainsKey("user-token"))
            {
                await response.BadRequest("请求格式不完整:User-Token 不可为空。");

                return(null);
            }

            var token = headers["user-token"].ToString();

            if (!headers.ContainsKey("x-auth-token"))
            {
                await response.BadRequest("请求格式不完整:X-Auth-Token 不可为空。");

                return(null);
            }

            var xAuthToken = headers["x-auth-token"].ToString();
            var xAuth      = xAuthToken?.Split(" ").Select(it => it.Trim()).ToList();

            if (xAuth == null || xAuth.Count != 3)
            {
                await response.BadRequest("请求格式错误:X-Auth-Token 结构不正确。");

                return(null);
            }

            if (xAuth[0] != "Ccxc-Auth")
            {
                await response.BadRequest("请求格式错误:X-Auth-Token 认证失败。");

                return(null);
            }

            var ts   = xAuth[1];
            var sign = xAuth[2];

            //ts判断,客户端与前端钟差不能大于5min
            long.TryParse(ts, out var tsNum);
            var signedTime = UnixTimestamp.FromTimestamp(tsNum);
            var diff       = Math.Abs((DateTime.Now - signedTime).TotalMinutes);

            if (diff > 5)
            {
                await response.Unauthorized($"客户端时钟不准,无法完成加密认证。请调整至正确的时间。服务器时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss}");

                return(null);
            }


            //从缓存中取出Session
            var cache = DbFactory.GetCache();

            var sessionKey  = cache.GetUserSessionKey(token);
            var userSession = await cache.Get <UserSession>(sessionKey);

            if (userSession == null) //Session不存在
            {
                await response.Unauthorized("登录已经过期,请重新登录。");

                return(null);
            }

            if (userSession.is_active != 1) //Session无效
            {
                await response.Unauthorized(userSession.inactive_message);

                return(null);
            }

            //是否在比赛期间认证
            if (onlyInGaming)
            {
                var now       = DateTime.Now;
                var startTime = UnixTimestamp.FromTimestamp(Config.Config.Options.StartTime);
                var endTime   = UnixTimestamp.FromTimestamp(Config.Config.Options.EndTime);

                if (userSession.is_betaUser != 1)
                {
                    if (now < startTime)
                    {
                        await response.BadRequest("未到开赛时间");

                        return(null);
                    }

                    if (now >= endTime)
                    {
                        await response.BadRequest("比赛时间已过,感谢您的参与!");

                        return(null);
                    }
                }
            }


            //计算签名
            var sk             = userSession.sk;
            var unsingedString = $"token={token}&ts={ts}&bodyString={request.BodyString}";
            var calcedSign     = HashTools.HmacSha1Base64(unsingedString, sk);

            if (sign != calcedSign) //签名不匹配
            {
                await response.Unauthorized("认证失败");

                return(null);
            }

            //判断用户权限等级是否满足
            var authLevelNumber = (int)authLevel;

            if (userSession.roleid < authLevelNumber)
            {
                await response.Unauthorized("权限不足");

                return(null);
            }

            //认证通过,Session续期
            userSession.last_update = DateTime.Now;
            await cache.Put(sessionKey, userSession, Config.Config.Options.UserSessionTimeout * 1000);

            return(userSession);
        }
コード例 #19
0
        public void Parse(GameClient Session, ClientPacket Packet)
        {
            if (Session == null || Session.GetHabbo() == null || !Session.GetHabbo().InRoom)
            {
                return;
            }

            Room Room = Session.GetHabbo().CurrentRoom;

            if (Room == null)
            {
                return;
            }

            RoomUser User = Room.GetRoomUserManager().GetRoomUserByHabbo(Session.GetHabbo().Id);

            if (User == null)
            {
                return;
            }

            string Message = StringCharFilter.Escape(Packet.PopString());

            if (Message.Length > 100)
            {
                Message = Message.Substring(0, 100);
            }

            int Colour = Packet.PopInt();

            ChatStyle Style = null;

            if (!RocketEmulador.GetGame().GetChatManager().GetChatStyles().TryGetStyle(Colour, out Style) || (Style.RequiredRight.Length > 0 && !Session.GetHabbo().GetPermissions().HasRight(Style.RequiredRight)))
            {
                Colour = 0;
            }

            User.LastBubble = Session.GetHabbo().CustomBubbleId == 0 ? Colour : Session.GetHabbo().CustomBubbleId;

            if (RocketEmulador.GetUnixTimestamp() < Session.GetHabbo().FloodTime&& Session.GetHabbo().FloodTime != 0)
            {
                return;
            }

            if (Session.GetHabbo().TimeMuted > 0)
            {
                Session.SendMessage(new MutedComposer(Session.GetHabbo().TimeMuted));
                return;
            }

            if (!Session.GetHabbo().GetPermissions().HasRight("room_ignore_mute") && Room.CheckMute(Session))
            {
                Session.SendWhisper("Ops, você está no momento silenciado.", 34);
                return;
            }

            if (!Session.GetHabbo().GetPermissions().HasRight("mod_tool"))
            {
                int MuteTime;
                if (User.IncrementAndCheckFlood(out MuteTime))
                {
                    Session.SendMessage(new FloodControlComposer(MuteTime));
                    return;
                }
            }

            if (Message.StartsWith(":", StringComparison.CurrentCulture) && RocketEmulador.GetGame().GetChatManager().GetCommands().Parse(Session, Message))
            {
                return;
            }

            RocketEmulador.GetGame().GetChatManager().GetLogs().StoreChatlog(new Rocket.HabboHotel.Rooms.Chat.Logs.ChatlogEntry(Session.GetHabbo().Id, Room.Id, Message, UnixTimestamp.GetNow(), Session.GetHabbo(), Room));

            if (RocketEmulador.GetGame().GetChatManager().GetFilter().CheckBannedWords(Message))
            {
                Session.GetHabbo().BannedPhraseCount++;
                if (Session.GetHabbo().BannedPhraseCount >= RocketGame.BannedPhrasesAmount)
                {
                    RocketEmulador.GetGame().GetModerationManager().BanUser("RocketEmulador", HabboHotel.Moderation.ModerationBanType.USERNAME, Session.GetHabbo().Username, "Spamming banned phrases (" + Message + ")", (RocketEmulador.GetUnixTimestamp() + 78892200));
                    Session.Disconnect();
                    return;
                }
                Session.SendMessage(new ShoutComposer(User.VirtualId, Message, 0, Colour));
                return;
            }

            if (!Session.GetHabbo().GetPermissions().HasRight("word_filter_override"))
            {
                Message = RocketEmulador.GetGame().GetChatManager().GetFilter().CheckMessage(Message);
            }

            RocketEmulador.GetGame().GetQuestManager().ProgressUserQuest(Session, QuestType.SOCIAL_CHAT);

            User.UnIdle();
            User.OnChat(User.LastBubble, Message, true);
        }
コード例 #20
0
ファイル: FileUploader.cs プロジェクト: MaddysTeam/Thesis
        public static HttpResult UploadStream(Stream stream, SliceUpload uploader, string policy, string file)
        {
            Auth   auth   = EnvUtility.EnvAuth();
            Config config = EnvUtility.EnvConfig();

            // 上传到这个 bucket
            string bucket = "csj-zyk";
            string key    = file;

            // 上传前先删除
            BucketManager bm     = new BucketManager(auth, config);
            HttpResult    result = bm.Delete(bucket, key);

            long dataSize = GetDataSize(stream.Length);

            byte[] data = new byte[dataSize];
            stream.Read(data, 0, data.Length);

            // 最后合成文件时的 hash
            Console.WriteLine("ETag of uploading data: {0}", ETag.ComputeEtag(data));

            // 一个小时的超时,转为 UnixTime 毫秒数
            long   deadline    = UnixTimestamp.GetUnixTimestamp(3600) * 1000;
            string putPolicy   = "{\"scope\": \"" + bucket + ":" + key + "\",\"deadline\": \"" + deadline + "\"}";
            string uploadToken = auth.CreateUploadToken(putPolicy);

            // 第一个分片不宜太大,因为可能遇到错误,上传太大是白费流量和时间!
            const long blockSize      = 4 * 1024 * 1024;
            const int  firstChunkSize = 1024;

            SliceUpload su = uploader; // new SliceUpload(auth, config);

            result = su.MakeBlock(blockSize, 0, data, 0, firstChunkSize, uploadToken);

            if ((int)HttpStatusCode.OK == result.Code)
            {
                long     blockCount = (dataSize + blockSize - 1) / blockSize;
                string[] contexts   = new string[blockCount];


                JObject jo = JObject.Parse(result.Text);

                contexts[0] = jo["ctx"].ToString();

                // 上传第 1 个 block 剩下的数据
                result = su.Bput(contexts[0], firstChunkSize, data, firstChunkSize, (int)(blockSize - firstChunkSize), uploadToken);
                if ((int)HttpStatusCode.OK == result.Code)
                {
                    jo          = JObject.Parse(result.Text);
                    contexts[0] = jo["ctx"].ToString();

                    // 上传后续 block,每次都是一整块上传
                    for (int blockIndex = 1; blockIndex < blockCount; ++blockIndex)
                    {
                        long leftSize  = dataSize - blockSize * blockIndex;
                        int  chunkSize = (int)(leftSize > blockSize ? blockSize : leftSize);
                        result = su.MakeBlock(chunkSize, blockIndex, data, (int)(blockSize * blockIndex), chunkSize, uploadToken);
                        if ((int)HttpStatusCode.OK == result.Code)
                        {
                            jo = JObject.Parse(result.Text);
                            contexts[blockIndex] = jo["ctx"].ToString();
                        }
                        else
                        {
                            return(result);
                        }
                    }

                    // 合成文件,注意与前面打印的 ETag 对比

                    result = su.MakeFile(dataSize, key, contexts, uploadToken);
                }
            }

            return(result);
        }
コード例 #21
0
ファイル: UnixTimestamp.cs プロジェクト: AnotherAltr/Rc.Core
 public bool Equals(UnixTimestamp other) => other.secondsSinceEpoch == secondsSinceEpoch;
コード例 #22
0
 private void method_0()
 {
     this.double_0 = UnixTimestamp.GetCurrent();
 }
コード例 #23
0
        public void Parse(GameClient Session, ClientPacket Packet)
        {
            if (!Session.GetHabbo().InRoom)
            {
                return;
            }

            Room Room = Session.GetHabbo().CurrentRoom;

            if (Room == null)
            {
                return;
            }

            if (!Session.GetHabbo().GetPermissions().HasRight("mod_tool") && Room.CheckMute(Session))
            {
                Session.SendWhisper("Oops, you're currently muted.");
                return;
            }

            if (PlusEnvironment.GetUnixTimestamp() < Session.GetHabbo().FloodTime&& Session.GetHabbo().FloodTime != 0)
            {
                return;
            }

            string Params  = Packet.PopString();
            string ToUser  = Params.Split(' ')[0];
            string Message = Params.Substring(ToUser.Length + 1);
            int    Colour  = Packet.PopInt();

            RoomUser User = Room.GetRoomUserManager().GetRoomUserByHabbo(Session.GetHabbo().Id);

            if (User == null)
            {
                return;
            }

            RoomUser User2 = Room.GetRoomUserManager().GetRoomUserByHabbo(ToUser);

            if (User2 == null)
            {
                return;
            }

            if (Session.GetHabbo().TimeMuted > 0)
            {
                Session.SendPacket(new MutedComposer(Session.GetHabbo().TimeMuted));
                return;
            }

            if (!Session.GetHabbo().GetPermissions().HasRight("word_filter_override"))
            {
                Message = PlusEnvironment.GetGame().GetChatManager().GetFilter().CheckMessage(Message);
            }

            ChatStyle Style = null;

            if (!PlusEnvironment.GetGame().GetChatManager().GetChatStyles().TryGetStyle(Colour, out Style) || (Style.RequiredRight.Length > 0 && !Session.GetHabbo().GetPermissions().HasRight(Style.RequiredRight)))
            {
                Colour = 0;
            }

            User.LastBubble = Session.GetHabbo().CustomBubbleId == 0 ? Colour : Session.GetHabbo().CustomBubbleId;

            if (!Session.GetHabbo().GetPermissions().HasRight("mod_tool"))
            {
                int MuteTime;
                if (User.IncrementAndCheckFlood(out MuteTime))
                {
                    Session.SendPacket(new FloodControlComposer(MuteTime));
                    return;
                }
            }

            if (!User2.GetClient().GetHabbo().ReceiveWhispers&& !Session.GetHabbo().GetPermissions().HasRight("room_whisper_override"))
            {
                Session.SendWhisper("Oops, this user has their whispers disabled!");
                return;
            }

            PlusEnvironment.GetGame().GetChatManager().GetLogs().StoreChatlog(new ChatlogEntry(Session.GetHabbo().Id, Room.Id, "<Whisper to " + ToUser + ">: " + Message, UnixTimestamp.GetNow(), Session.GetHabbo(), Room));

            if (PlusEnvironment.GetGame().GetChatManager().GetFilter().CheckBannedWords(Message))
            {
                Session.GetHabbo().BannedPhraseCount++;
                if (Session.GetHabbo().BannedPhraseCount >= (Convert.ToInt32(PlusEnvironment.GetSettingsManager().TryGetValue("room.chat.filter.banned_phrases.chances"))))
                {
                    PlusEnvironment.GetGame().GetModerationManager().BanUser("System", HabboHotel.Moderation.ModerationBanType.USERNAME, Session.GetHabbo().Username, "Spamming banned phrases (" + Message + ")", (PlusEnvironment.GetUnixTimestamp() + 78892200));
                    Session.Disconnect();
                    return;
                }
                Session.SendPacket(new WhisperComposer(User.VirtualId, Message, 0, User.LastBubble));
                return;
            }


            PlusEnvironment.GetGame().GetQuestManager().ProgressUserQuest(Session, QuestType.SOCIAL_CHAT);

            User.UnIdle();
            User.GetClient().SendPacket(new WhisperComposer(User.VirtualId, Message, 0, User.LastBubble));

            if (User2 != null && !User2.IsBot && User2.UserId != User.UserId)
            {
                if (!User2.GetClient().GetHabbo().GetIgnores().IgnoredUserIds().Contains(Session.GetHabbo().Id))
                {
                    User2.GetClient().SendPacket(new WhisperComposer(User.VirtualId, Message, 0, User.LastBubble));
                }
            }

            List <RoomUser> ToNotify = Room.GetRoomUserManager().GetRoomUserByRank(2);

            if (ToNotify.Count > 0)
            {
                foreach (RoomUser user in ToNotify)
                {
                    if (user != null && user.HabboId != User2.HabboId && user.HabboId != User.HabboId)
                    {
                        if (user.GetClient() != null && user.GetClient().GetHabbo() != null && !user.GetClient().GetHabbo().IgnorePublicWhispers)
                        {
                            user.GetClient().SendPacket(new WhisperComposer(User.VirtualId, "[Whisper to " + ToUser + "] " + Message, 0, User.LastBubble));
                        }
                    }
                }
            }
        }
コード例 #24
0
 public void CanImplicitConvertToString(UnixTimestamp sut)
 {
     var expected = sut.SecondsSinceEpoch.ToString(CultureInfo.InvariantCulture);
     Assert.Equal(expected, sut);
 }
コード例 #25
0
        public ModeratorInitComposer(ICollection <string> userPresets, ICollection <string> roomPresets, ICollection <ModerationTicket> tickets)
            : base(ServerPacketHeader.ModeratorInitMessageComposer)
        {
            WriteInteger(tickets.Count);
            foreach (var ticket in tickets)
            {
                WriteInteger(ticket.Id);                                                                                             // Id
                WriteInteger(ticket.GetStatus(Id));                                                                                  // Tab ID
                WriteInteger(ticket.Type);                                                                                           // Type
                WriteInteger(ticket.Category);                                                                                       // Category
                WriteInteger(Convert.ToInt32((DateTime.Now - UnixTimestamp.FromUnixTimestamp(ticket.Timestamp)).TotalMilliseconds)); // This should fix the overflow?
                WriteInteger(ticket.Priority);                                                                                       // Priority
                WriteInteger(ticket.Sender?.Id ?? 0);                                                                                // Sender ID
                WriteInteger(1);
                WriteString(ticket.Sender == null ? string.Empty : ticket.Sender.Username);                                          // Sender Name
                WriteInteger(ticket.Reported?.Id ?? 0);                                                                              // Reported ID
                WriteString(ticket.Reported == null ? string.Empty : ticket.Reported.Username);                                      // Reported Name
                WriteInteger(ticket.Moderator?.Id ?? 0);                                                                             // Moderator ID
                WriteString(ticket.Moderator == null ? string.Empty : ticket.Moderator.Username);                                    // Mod Name
                WriteString(ticket.Issue);                                                                                           // Issue
                WriteInteger(ticket.Room?.Id ?? 0);                                                                                  // Room Id
                WriteInteger(0);                                                                                                     //LOOP
            }

            WriteInteger(userPresets.Count);
            foreach (var pre in userPresets)
            {
                WriteString(pre);
            }

            /*base.WriteInteger(UserActionPresets.Count);
             * foreach (KeyValuePair<string, List<ModerationPresetActionMessages>> Cat in UserActionPresets.ToList())
             * {
             *  base.WriteString(Cat.Key);
             *  base.WriteBoolean(true);
             *  base.WriteInteger(Cat.Value.Count);
             *  foreach (ModerationPresetActionMessages Preset in Cat.Value.ToList())
             *  {
             *      base.WriteString(Preset.Caption);
             *      base.WriteString(Preset.MessageText);
             *      base.WriteInteger(Preset.BanTime); // Account Ban Hours
             *      base.WriteInteger(Preset.IPBanTime); // IP Ban Hours
             *      base.WriteInteger(Preset.MuteTime); // Mute in Hours
             *      base.WriteInteger(0);//Trading lock duration
             *      base.WriteString(Preset.Notice + "\n\nPlease Note: Avatar ban is an IP ban!");
             *      base.WriteBoolean(false);//Show HabboWay
             *  }
             * }*/

            // TODO: Figure out
            WriteInteger(0);
            {
                //Loop a string.
            }

            WriteBoolean(true); // Ticket right
            WriteBoolean(true); // Chatlogs
            WriteBoolean(true); // User actions alert etc
            WriteBoolean(true); // Kick users
            WriteBoolean(true); // Ban users
            WriteBoolean(true); // Caution etc
            WriteBoolean(true); // Love you, Tom

            WriteInteger(roomPresets.Count);
            foreach (var pre in roomPresets)
            {
                WriteString(pre);
            }
        }
コード例 #26
0
ファイル: DatabaseClient.cs プロジェクト: Bankst/DragonFiesta
 private void UpdateLastActivity()
 {
     mLastActivity = UnixTimestamp.GetCurrent();
 }
コード例 #27
0
ファイル: ChatEvent.cs プロジェクト: xjoao97/HabboRP
        public void Parse(GameClient Session, ClientPacket Packet)
        {
            if (Session == null || Session.GetHabbo() == null || !Session.GetHabbo().InRoom)
            {
                return;
            }

            Room Room = Session.GetHabbo().CurrentRoom;

            if (Room == null)
            {
                return;
            }

            RoomUser User = Room.GetRoomUserManager().GetRoomUserByHabbo(Session.GetHabbo().Id);

            if (User == null)
            {
                return;
            }

            if (Session.LoggingOut)
            {
                return;
            }

            string Message = StringCharFilter.Escape(Packet.PopString(), false, Session);

            if (Message.Length > 150)
            {
                Message = Message.Substring(0, 150);
            }

            int Colour = Packet.PopInt();

            if (Colour != 0 && !User.GetClient().GetHabbo().GetPermissions().HasRight("use_any_bubble"))
            {
                Colour = 0;
            }

            ChatStyle Style = null;

            if (!PlusEnvironment.GetGame().GetChatManager().GetChatStyles().TryGetStyle(Colour, out Style) || (Style.RequiredRight.Length > 0 && !Session.GetHabbo().GetPermissions().HasRight(Style.RequiredRight)))
            {
                Colour = 0;
            }

            if (PlusEnvironment.GetUnixTimestamp() < Session.GetHabbo().FloodTime&& Session.GetHabbo().FloodTime != 0)
            {
                return;
            }

            if (Session.GetHabbo().TimeMuted > 0)
            {
                Session.SendMessage(new MutedComposer(Session.GetHabbo().TimeMuted));
                return;
            }

            if (!Session.GetHabbo().GetPermissions().HasRight("room_ignore_mute") && Room.CheckMute(Session))
            {
                Session.SendWhisper("Opa, você atualmente está mutado.", 1);
                return;
            }

            User.LastBubble = Session.GetHabbo().CustomBubbleId == 0 ? Colour : Session.GetHabbo().CustomBubbleId;

            if (Message.Equals("x"))
            {
                if (Session.GetRoleplay().LastCommand != "")
                {
                    Message = Session.GetRoleplay().LastCommand.ToString();
                }
            }

            if (!Session.GetHabbo().GetPermissions().HasRight("mod_tool"))
            {
                int MuteTime;
                if (Message.StartsWith(":", StringComparison.CurrentCulture) && PlusEnvironment.GetGame().GetChatManager().GetCommands().Parse(Session, Message))
                {
                    return;
                }
                else if (User.IncrementAndCheckFlood(out MuteTime))
                {
                    Session.SendMessage(new FloodControlComposer(MuteTime));
                    return;
                }
            }

            if (Message.StartsWith(":", StringComparison.CurrentCulture) && PlusEnvironment.GetGame().GetChatManager().GetCommands().Parse(Session, Message))
            {
                return;
            }

            PlusEnvironment.GetGame().GetChatManager().GetLogs().StoreChatlog(new ChatlogEntry(Session.GetHabbo().Id, Room.Id, Message, UnixTimestamp.GetNow(), Session.GetHabbo(), Room));

            if (!Session.GetHabbo().GetPermissions().HasRight("advertisement_filter_override"))
            {
                string Phrase = "";
                if (PlusEnvironment.GetGame().GetChatManager().GetFilter().CheckBannedWords(Message, out Phrase))
                {
                    Session.GetHabbo().AdvertisingStrikes++;

                    if (Session.GetHabbo().AdvertisingStrikes < 2)
                    {
                        Session.SendMessage(new RoomNotificationComposer("Atenção!", "Por favor, evite de anunciar outros sites que não são permitidos, afiliados ou oferecidos pelo HabboRPG. Você ficará mudo se você fizer isso de novo!<br><br>Frase da Lista Negra: '" + Phrase + "'", "frank10", "ok", "event:"));
                        return;
                    }

                    if (Session.GetHabbo().AdvertisingStrikes >= 2)
                    {
                        Session.GetHabbo().TimeMuted = 3600;

                        using (var dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
                        {
                            dbClient.RunQuery("UPDATE `users` SET `time_muted` = '3600' WHERE `id` = '" + Session.GetHabbo().Id + "' LIMIT 1");
                        }

                        Session.SendMessage(new RoomNotificationComposer("Você foi mutado!", "Desculpe, mas você foi automaticamente mutadod por divulgar '" + Phrase + "'.<br><br>A equipe de moderação foi notificada e ações serão tomadas dentro de sua conta!", "frank10", "ok", "event:"));

                        List <string> Messages = new List <string>();
                        Messages.Add(Message);
                        PlusEnvironment.GetGame().GetModerationTool().SendNewTicket(Session, 9, Session.GetHabbo().Id, "[Servidor] O civil já recebeu uma advertência " + Phrase + ".", Messages);
                        return;
                    }

                    return;
                }
            }

            if (!Session.GetHabbo().GetPermissions().HasRight("word_filter_override"))
            {
                Message = PlusEnvironment.GetGame().GetChatManager().GetFilter().CheckMessage(Message);
            }

            if (Message.ToLower().Equals("o/"))
            {
                Room.SendMessage(new ActionComposer(User.VirtualId, 1));
                return;
            }

            if (Message.ToLower().Equals("_b"))
            {
                Room.SendMessage(new ActionComposer(User.VirtualId, 7));
                return;
            }

            User.UnIdle();

            if (Session.GetRoleplay() != null)
            {
                if (Session.GetRoleplay().IsWorking&& HabboHotel.Groups.GroupManager.HasJobCommand(Session, "guide"))
                {
                    User.OnChat(37, Message, false);
                }
                else if (Session.GetRoleplay().StaffOnDuty&& Session.GetHabbo().GetPermissions().HasRight("mod_tool"))
                {
                    User.OnChat(23, Message, false);
                }
                else if (Session.GetRoleplay().AmbassadorOnDuty&& Session.GetHabbo().GetPermissions().HasRight("ambassador"))
                {
                    User.OnChat(37, Message, false);
                }

                // Roleplay
                else if (Session.GetRoleplay().CurHealth > 25 && Session.GetRoleplay().CurHealth <= 40 && !Session.GetRoleplay().IsDead)
                {
                    User.OnChat(5, Message, false);
                }
                else if (Session.GetRoleplay().CurHealth <= 25 && !Session.GetRoleplay().IsDead)
                {
                    User.OnChat(3, Message, false);
                }
                else if (Session.GetRoleplay().IsDead)
                {
                    User.OnChat(3, "[ " + Message + " ]", false);
                }
                else
                {
                    User.OnChat(User.LastBubble, Message, false);
                }
            }
            else
            {
                User.OnChat(User.LastBubble, Message, false);
            }
        }
コード例 #28
0
        public void Parse(GameClient session, ClientPacket packet)
        {
            List <RoomData> rooms = RoomFactory.GetRoomsDataByOwnerSortByName(session.Habbo.Id);

            rooms = rooms.Where(x => x.Promotion == null || x.Promotion.TimestampExpires < UnixTimestamp.GetNow()).ToList();

            session.SendPacket(new PromotableRoomsComposer(rooms));
        }
コード例 #29
0
ファイル: WhisperEvent.cs プロジェクト: SpreedBlood/PlusEMU
        public void Parse(GameClient session, ClientPacket packet)
        {
            if (!session.Habbo.InRoom)
            {
                return;
            }

            Room room = session.Habbo.CurrentRoom;

            if (room == null)
            {
                return;
            }

            if (!session.Habbo.GetPermissions().HasRight("mod_tool") && room.CheckMute(session))
            {
                session.SendWhisper("Oops, you're currently muted.");
                return;
            }

            if (PlusEnvironment.GetUnixTimestamp() < session.Habbo.FloodTime && session.Habbo.FloodTime != 0)
            {
                return;
            }

            string Params  = packet.PopString();
            string toUser  = Params.Split(' ')[0];
            string message = Params.Substring(toUser.Length + 1);
            int    colour  = packet.PopInt();

            RoomUser user = room.GetRoomUserManager().GetRoomUserByHabbo(session.Habbo.Id);

            if (user == null)
            {
                return;
            }

            RoomUser user2 = room.GetRoomUserManager().GetRoomUserByHabbo(toUser);

            if (user2 == null)
            {
                return;
            }

            if (session.Habbo.TimeMuted > 0)
            {
                session.SendPacket(new MutedComposer(session.Habbo.TimeMuted));
                return;
            }

            if (!session.Habbo.GetPermissions().HasRight("word_filter_override"))
            {
                message = PlusEnvironment.GetGame().GetChatManager().GetFilter().CheckMessage(message);
            }

            if (!PlusEnvironment.GetGame().GetChatManager().GetChatStyles().TryGetStyle(colour, out ChatStyle style) || style.RequiredRight.Length > 0 && !session.Habbo.GetPermissions().HasRight(style.RequiredRight))
            {
                colour = 0;
            }

            user.LastBubble = session.Habbo.CustomBubbleId == 0 ? colour : session.Habbo.CustomBubbleId;

            if (!session.Habbo.GetPermissions().HasRight("mod_tool"))
            {
                if (user.IncrementAndCheckFlood(out int muteTime))
                {
                    session.SendPacket(new FloodControlComposer(muteTime));
                    return;
                }
            }

            if (!user2.GetClient().Habbo.ReceiveWhispers&& !session.Habbo.GetPermissions().HasRight("room_whisper_override"))
            {
                session.SendWhisper("Oops, this user has their whispers disabled!");
                return;
            }

            PlusEnvironment.GetGame().GetChatManager().GetLogs().StoreChatlog(new ChatlogEntry(session.Habbo.Id, room.Id, "<Whisper to " + toUser + ">: " + message, UnixTimestamp.GetNow(), session.Habbo, room));

            if (PlusEnvironment.GetGame().GetChatManager().GetFilter().CheckBannedWords(message))
            {
                session.Habbo.BannedPhraseCount++;
                if (session.Habbo.BannedPhraseCount >= Convert.ToInt32(PlusEnvironment.GetSettingsManager().TryGetValue("room.chat.filter.banned_phrases.chances")))
                {
                    PlusEnvironment.GetGame().GetModerationManager().BanUser("System", HabboHotel.Moderation.ModerationBanType.Username, session.Habbo.Username, "Spamming banned phrases (" + message + ")", PlusEnvironment.GetUnixTimestamp() + 78892200);
                    session.Disconnect();
                    return;
                }
                session.SendPacket(new WhisperComposer(user.VirtualId, message, 0, user.LastBubble));
                return;
            }


            PlusEnvironment.GetGame().GetQuestManager().ProgressUserQuest(session, QuestType.SocialChat);

            user.UnIdle();
            user.GetClient().SendPacket(new WhisperComposer(user.VirtualId, message, 0, user.LastBubble));

            if (!user2.IsBot && user2.UserId != user.UserId)
            {
                if (!user2.GetClient().Habbo.GetIgnores().IgnoredUserIds().Contains(session.Habbo.Id))
                {
                    user2.GetClient().SendPacket(new WhisperComposer(user.VirtualId, message, 0, user.LastBubble));
                }
            }

            List <RoomUser> toNotify = room.GetRoomUserManager().GetRoomUserByRank(2);

            if (toNotify.Count > 0)
            {
                foreach (RoomUser notifiable in toNotify)
                {
                    if (notifiable != null && notifiable.HabboId != user2.HabboId && notifiable.HabboId != user.HabboId)
                    {
                        if (notifiable.GetClient() != null && notifiable.GetClient().Habbo != null && !notifiable.GetClient().Habbo.IgnorePublicWhispers)
                        {
                            notifiable.GetClient().SendPacket(new WhisperComposer(user.VirtualId, "[Whisper to " + toUser + "] " + message, 0, user.LastBubble));
                        }
                    }
                }
            }
        }
コード例 #30
0
        public static string InitializeDatabase()
        {
            string   exePath             = System.Reflection.Assembly.GetExecutingAssembly().Location;
            FileInfo exeInfo             = new FileInfo(exePath);
            string   filename            = Data.DataFolder.DatabaseFileName;
            string   defaultDatabasePath = Path.Combine(exeInfo.Directory.FullName, filename);

            string defaultDatabaseVersion = null;
            string currentDatabaseVersion = null;

            bool defaultDatabaseExists     = File.Exists(defaultDatabasePath);
            bool currentDatabaseExists     = File.Exists(Data.DataFolder.FullDatabasePath);
            bool databaseVersionsDifferent = false;

            if (!defaultDatabaseExists && !currentDatabaseExists)
            {
                Logger.Error("Database could not be initialized because the default database {0} is missing",
                             defaultDatabasePath);
                return(null);
            }

            if (defaultDatabaseExists)
            {
                DataStore ds      = new DataStore(defaultDatabasePath);
                Setting   setting = ds.GetSetting("Version");

                if (setting != null)
                {
                    UnixTimestamp ts       = setting.DateAdded;
                    long          unixTime = ts.UnixTime;
                    DateTime      utc      = ts.UtcTime;
                    DateTime      local    = utc.ToLocalTime();
                    defaultDatabaseVersion = setting.Value;
                    Logger.Info("Default database: {0} version: {1} ",
                                defaultDatabasePath, defaultDatabaseVersion);
                }
            }

            if (currentDatabaseExists)
            {
                DataStore ds      = Data.SQLite.DataStore.Instance;
                Setting   setting = ds.GetSetting("Version");

                if (setting != null)
                {
                    UnixTimestamp ts       = setting.DateAdded;
                    long          unixTime = ts.UnixTime;
                    DateTime      utc      = ts.UtcTime;
                    DateTime      local    = utc.ToLocalTime();
                    currentDatabaseVersion = setting.Value;
                    Logger.Info("Current database: {0} version: {1} ",
                                Data.DataFolder.FullDatabasePath, currentDatabaseVersion);
                }
            }
            else
            {
                Logger.Warn("Database is missing.");
            }

            if (defaultDatabaseExists && currentDatabaseExists)
            {
                databaseVersionsDifferent =
                    string.Compare(currentDatabaseVersion,
                                   defaultDatabaseVersion, true) != 0;
            }

            if (databaseVersionsDifferent)
            {
                Logger.Warn("Database version mismatch.");
            }

            if (!currentDatabaseExists || databaseVersionsDifferent)
            {
                string src = defaultDatabasePath;
                Logger.Warn("Trying to copy the default database from '{0}'", src);

                FileInfo source = new FileInfo(src);
                if (source.Exists == true)
                {
                    source.CopyTo(Data.DataFolder.FullDatabasePath, true);
                    Logger.Info("Default database copied to data directory");
                    return(Data.DataFolder.FullDatabasePath);
                }
                else
                {
                    Logger.Warn("Default database not found:  '{0}'", src);
                    return(null);
                }
            }
            else
            {
                return(Data.DataFolder.FullDatabasePath);
            }
        }
コード例 #31
0
ファイル: B_Parser.cs プロジェクト: danij/IRCService.NET
        public override void Parse(string[] spaceSplit, string[] colonSplit, 
            string fullRow)
        {
            if (spaceSplit.Count() < 5)
            {
                return;
            }

            string channelName = spaceSplit[2];
            Channel channel = null;
            UnixTimestamp creationTimestamp = 
                new UnixTimestamp(Convert.ToInt32(spaceSplit[3]));
            int userIndex = 4;
            int channelModes = 0;
            string key = "";
            int limit = 0;

            if (spaceSplit[4][0] == '+')
            {
                userIndex += 1;
                for (int i = 0; i < spaceSplit[4].Length; i++)
                {
                    switch (spaceSplit[4][i])
                    {
                        case 'n': channelModes |= (int)ChannelModes.n; break;
                        case 't': channelModes |= (int)ChannelModes.t; break;
                        case 'm': channelModes |= (int)ChannelModes.m; break;
                        case 'i': channelModes |= (int)ChannelModes.i; break;
                        case 's': channelModes |= (int)ChannelModes.s; break;
                        case 'p': channelModes |= (int)ChannelModes.p; break;
                        case 'r': channelModes |= (int)ChannelModes.r; break;
                        case 'O': channelModes |= (int)ChannelModes.O; break;
                        case 'c': channelModes |= (int)ChannelModes.c; break;
                        case 'C': channelModes |= (int)ChannelModes.C; break;
                        case 'k': channelModes |= (int)ChannelModes.k;
                            if (spaceSplit.Count() > (userIndex + 1))
                            {
                                key = spaceSplit[userIndex];
                                userIndex += 1;
                            }
                            break;
                        case 'l': channelModes |= (int)ChannelModes.l;
                            if (spaceSplit.Count() > (userIndex + 1))
                            {
                                limit = Convert.ToInt32(spaceSplit[userIndex]);
                                if (limit < 0)
                                {
                                    limit = 0;

                                }
                                userIndex += 1;
                            }
                            break;
                    }
                }
            }
            if (spaceSplit.Count() > userIndex)
            {
                bool Op = false;
                bool HalfOp = false;
                bool Voice = false;
                string channelUserNumeric;
                IUser channelUser;
                string[] ChannelUsers = spaceSplit[userIndex].Split(',');
                if (spaceSplit[userIndex][0] != ':')
                {
                    for (int i = 0; i < ChannelUsers.Length; i++)
                    {
                        if (ChannelUsers[i].Length == 5)
                        {
                            channelUserNumeric = ChannelUsers[i];
                        }
                        else
                        {
                            string[] modeSplit = ChannelUsers[i].Split(':');
                            if (modeSplit.Length > 1)
                            {
                                Op = false;
                                HalfOp = false;
                                Voice = false;
                                for (int ii = 0; ii < modeSplit[1].Length; ii++)
                                {
                                    switch (modeSplit[1][ii])
                                    {
                                        case 'o': Op = true; break;
                                        case 'h': HalfOp = true; break;
                                        case 'v': Voice = true; break;
                                    }
                                }
                            }
                            else
                            {
                                continue;
                            }
                            channelUserNumeric = modeSplit[0];
                        }
                        channelUser = Service.GetUser(channelUserNumeric);
                        if (channelUser == null)
                        {
                            Service.AddLog("Burst for unknown user " + 
                                channelUserNumeric + " on channel " + channelName);
                            return;
                        }

                        channel = Service.GetChannel(channelName) as Channel;
                        if (channel == null)
                        {
                            channel = Service.CreateChannel(channelName, 
                                creationTimestamp) as Channel;
                        }
                        else
                        {
                            channel.CreationTimeStamp = creationTimestamp;
                        }

                        if (channelUser.Server.GetChannel(channelName) == null)
                        {
                            (channelUser.Server as Server).AddChannel(channel);
                        }

                        channel.AddUser(channelUser, Op, Voice, HalfOp);
                    }
                }
            }

            List<Ban> bans = new List<Ban>();
            string[] banList = fullRow.Split(
                new string[] { ":%" }, 
                StringSplitOptions.None
            );
            if (banList.Length > 1)
            {
                string[] banStrings = banList[1].Split(' ');
                foreach (string currentBan in banStrings)
                {
                    bans.Add(new Ban(currentBan));
                }
            }

            if (channel == null)
            {
                channel = Service.GetChannel(channelName) as Channel;
                if (channel == null)
                {
                    return;
                }
            }

            if (channel.CreationTimeStamp.Timestamp > 
                creationTimestamp.Timestamp)
            {
                channel.CreationTimeStamp = creationTimestamp;
            }
            if (channelModes > 0)
            {
                channel.SetMode(channelModes);
                if (limit > 0)
                {
                    channel.SetMode(ChannelModes.l, limit);
                }
                if (key.Length > 0)
                {
                    channel.SetMode(ChannelModes.k, key);
                }
            }
            if (bans.Count > 0)
            {
                channel.AddBan(bans);
            }
        }
コード例 #32
0
        public void Parse(GameClient session, ClientPacket packet)
        {
            if (session?.GetHabbo() == null)
            {
                return;
            }

            if (!session.GetHabbo().GetPermissions().HasRight("mod_tool"))
            {
                return;
            }

            var data = PlusEnvironment.GetHabboById(packet.PopInt());

            if (data == null)
            {
                session.SendNotification("Unable to load info for user.");
                return;
            }

            PlusEnvironment.GetGame().GetChatManager().GetLogs().FlushAndSave();

            var chatlogs = new List <KeyValuePair <RoomData, List <ChatlogEntry> > >();

            using (var dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
            {
                dbClient.SetQuery("SELECT `room_id`,`entry_timestamp`,`exit_timestamp` FROM `user_roomvisits` WHERE `user_id` = '" + data.Id +
                                  "' ORDER BY `entry_timestamp` DESC LIMIT 7");
                var getLogs = dbClient.GetTable();

                if (getLogs != null)
                {
                    chatlogs.AddRange(from DataRow row in getLogs.Rows
                                      let roomData = PlusEnvironment.GetGame().GetRoomManager().GenerateRoomData(Convert.ToInt32(row["room_id"]))
                                                     where roomData != null
                                                     let timestampExit = Convert.ToDouble(row["exit_timestamp"]) <= 0 ? UnixTimestamp.GetNow() : Convert.ToDouble(row["exit_timestamp"])
                                                                         select new KeyValuePair <RoomData, List <ChatlogEntry> >(roomData, GetChatlogs(roomData, Convert.ToDouble(row["entry_timestamp"]), timestampExit)));
                }

                session.SendPacket(new ModeratorUserChatlogComposer(data, chatlogs));
            }
        }
コード例 #33
0
ファイル: IRCService.cs プロジェクト: danij/IRCService.NET
        /// <summary>
        /// Occurs when a new connection is established
        /// </summary>
        protected void OnConnect()
        {
            Status = ServiceStatus.Connected;
            connectionTimestamp = UnixTimestamp.CurrentTimestamp();

            OnConnectionEstablished();

            if (MainServer == null)
            {
                PrepareForPlugins();
            }

            var authCommand = CommandFactory.CreateServerAuthenticationCommand();
            authCommand.Password = password;
            SendCommand(authCommand, false);

            var introCommand = CommandFactory.CreateServerIntroductionCommand();
            introCommand.Server = MainServer;
            introCommand.StartTimeStamp = startTimestamp;
            SendCommand(introCommand, false);
        }
コード例 #34
0
        public void TestBlendingLCR()
        {
            var node            = new MockNode(500000);
            var incomingMessage = new MockMessage();

            incomingMessage.SetIncoming(node, string.Join(":",
                                                          "%%>message",
                                                          "234479208",
                                                          UnixTimestamp.ToString(),
                                                          "call.route",
                                                          "id=sip/852978",
                                                          "module=sip",
                                                          "error=",
                                                          "reason=",
                                                          "status=incoming",
                                                          "address=51.0.0.1%z5060",
                                                          "billid=1418778188-53",
                                                          "answered=false",
                                                          "direction=incoming",
                                                          "caller=00012521339915",
                                                          "called=1111101",
                                                          "callername=00012521339915",
                                                          "sip_Tracking-ID=",
                                                          "sip_Gateway-ID="
                                                          ));


            Dispatcher.Process(incomingMessage).Wait();

            var result      = node.RetrieveMessage();
            var routingTree = getRoutingTree(node, "1418778188-53", true);

            // Assert - split because MS are measured for 'clwaitingtime,clprocessingtime' and change between runs
            Assert.IsTrue(result.OutgoingMessage.StartsWith("%%<message:234479208:true:call.route::error=:"
                                                            + "reason=:location=fork:fork.calltype=:fork.autoring=:fork.automessage=:fork.ringer=:clnodeid=500000:"
                                                            + "clcustomerid=500000:clcustomeripid=500000:cltrackingid=1418778188-53:clprocessingtime="));

            Assert.IsTrue(result.OutgoingMessage.Contains(":clcustomerpriceid=500000:clcustomerpricepermin=30:clcustomercurrency=USD:cldialcodemasterid=3:clwaitingtime="));
            Assert.IsTrue(result.OutgoingMessage.EndsWith(CopyParams
                                                          + ":callto.1=sip/sip%[email protected]%z5057:callto.1.called=1111101:callto.1.caller=00012521339915:callto.1.callername=00012521339915:callto.1.format=g729:"
                                                          + "callto.1.formats=g729,alaw,mulaw:callto.1.line=:callto.1.maxcall=65000:callto.1.osip_P-Asserted-Identity=:callto.1.osip_Gateway-ID=:callto.1.osip_Tracking-ID=:"
                                                          + "callto.1.rtp_addr=50.0.0.103:callto.1.rtp_forward=true:callto.1.rtp_port=6057:callto.1.oconnection_id=general:callto.1.clgatewayid=500002:callto.1.clgatewayaccountid=:"
                                                          + "callto.1.clgatewayipid=500002:callto.1.cltechcalled=sip/sip%[email protected]%z5057:"
                                                          + "callto.1.clgatewaypriceid=500002:callto.1.clgatewaypricepermin=0,035:callto.1.clgatewaycurrency=USD:callto.1.cldecision=8:callto.1.timeout=1085:"
                                                          + "callto.2=|next=10000:"
                                                          + "callto.3=sip/sip%[email protected]%z5057:callto.3.called=1111101:callto.3.caller=00012521339915:callto.3.callername=00012521339915:callto.3.format=g729:"
                                                          + "callto.3.formats=g729,alaw,mulaw:callto.3.line=:callto.3.maxcall=65000:callto.3.osip_P-Asserted-Identity=:callto.3.osip_Gateway-ID=:callto.3.osip_Tracking-ID=:"
                                                          + "callto.3.rtp_addr=50.0.0.102:callto.3.rtp_forward=true:callto.3.rtp_port=6057:callto.3.oconnection_id=general:callto.3.clgatewayid=500001:callto.3.clgatewayaccountid=:"
                                                          + "callto.3.clgatewayipid=500001:callto.3.cltechcalled=sip/sip%[email protected]%z5057:"
                                                          + "callto.3.clgatewaypriceid=500001:callto.3.clgatewaypricepermin=0,03:callto.3.clgatewaycurrency=USD:callto.3.cldecision=8:callto.3.timeout=1085:"
                                                          + "callto.4=|next=10000:"
                                                          + "callto.5=sip/sip%[email protected]%z5057:callto.5.called=1111101:callto.5.caller=00012521339915:callto.5.callername=00012521339915:callto.5.format=g729:"
                                                          + "callto.5.formats=g729,alaw,mulaw:callto.5.line=:callto.5.maxcall=65000:callto.5.osip_P-Asserted-Identity=:callto.5.osip_Gateway-ID=:callto.5.osip_Tracking-ID=:"
                                                          + "callto.5.rtp_addr=50.0.0.101:callto.5.rtp_forward=true:callto.5.rtp_port=6057:callto.5.oconnection_id=general:callto.5.clgatewayid=500000:callto.5.clgatewayaccountid=:"
                                                          + "callto.5.clgatewayipid=500000:callto.5.cltechcalled=sip/sip%[email protected]%z5057:"
                                                          + "callto.5.clgatewaypriceid=500000:callto.5.clgatewaypricepermin=0,006:callto.5.clgatewaycurrency=USD:callto.5.cldecision=8:callto.5.timeout=1085\n"));

            Assert.IsNotNull(routingTree);
            Assert.AreEqual(routingTree.Context.Endpoint, Utilities.RoutingTree.TargetType.Context);
            Assert.AreEqual(routingTree.Context.Id, 500000);
            Assert.IsNull(routingTree.Context.InternalRoutedGateway);
            Assert.IsNotNull(routingTree.Context.BlendingContext);
            Assert.IsNull(routingTree.Context.BlendingContext.BlendingContext);
            Assert.AreEqual(routingTree.Context.BlendingContext.Endpoint, Utilities.RoutingTree.TargetType.Context);
            Assert.AreEqual(routingTree.Context.BlendingContext.Id, 500001);
            Assert.IsNull(routingTree.Context.BlendingContext.InternalRoutedGateway);
            Assert.IsNull(routingTree.Context.BlendingContext.Route);
            Assert.AreEqual(routingTree.Context.BlendingContext.LCRGateways.Count, 1);
            Assert.AreEqual(routingTree.Context.BlendingContext.LCRGateways[0].Endpoint, Utilities.RoutingTree.TargetType.Gateway);
            Assert.AreEqual(routingTree.Context.BlendingContext.LCRGateways[0].Id, 500002);
            Assert.AreEqual(routingTree.Context.BlendingContext.LCRGateways[0].TargetReason, Utilities.RoutingTree.Reason.Blending);
            Assert.IsNull(routingTree.Context.BlendingContext.LCRGateways[0].Via);
            Assert.AreEqual(routingTree.Context.LCRGateways.Count, 2);
            Assert.AreEqual(routingTree.Context.LCRGateways[0].Endpoint, Utilities.RoutingTree.TargetType.Gateway);
            Assert.AreEqual(routingTree.Context.LCRGateways[0].Id, 500001);
            Assert.AreEqual(routingTree.Context.LCRGateways[0].TargetReason, Utilities.RoutingTree.Reason.OK);
            Assert.IsNull((routingTree.Context.LCRGateways[0] as Utilities.RoutingTree.Gateway).Via);
            Assert.AreEqual(routingTree.Context.LCRGateways[1].Endpoint, Utilities.RoutingTree.TargetType.Gateway);
            Assert.AreEqual(routingTree.Context.LCRGateways[1].Id, 500000);
            Assert.AreEqual(routingTree.Context.LCRGateways[1].TargetReason, Utilities.RoutingTree.Reason.OK);
            Assert.IsNull((routingTree.Context.LCRGateways[1] as Utilities.RoutingTree.Gateway).Via);
            Assert.AreEqual(routingTree.GatewayOrder[0], 500002);
            Assert.AreEqual(routingTree.GatewayOrder[1], 500001);
            Assert.AreEqual(routingTree.GatewayOrder[2], 500000);
        }
コード例 #35
0
ファイル: UnixTimestamp.cs プロジェクト: DogWars/WechatHelper
 public static TimeSpan Now()
 {
     return(UnixTimestamp.FromDateTime(DateTime.Now));
 }
コード例 #36
0
ファイル: User.cs プロジェクト: danij/IRCService.NET
 /// <summary>
 /// Default constructor
 /// </summary>
 /// <param name="server"></param>
 /// <param name="numeric"></param>
 /// <param name="nick"></param>
 /// <param name="ident"></param>
 /// <param name="host"></param>
 /// <param name="name"></param>
 /// <param name="connectionTimestamp"></param>
 /// <param name="IPAddress"></param>
 public User(IServer server, string numeric, string nick, string ident, 
     string host, string name, UnixTimestamp connectionTimestamp, 
     IPAddress IPAddress, IRCServicePlugin plugin = null)
     : this(server, numeric, nick, ident, host, name, 
     connectionTimestamp, "", plugin)
 {            
     if (IPAddress.AddressFamily == 
         System.Net.Sockets.AddressFamily.InterNetworkV6)
     {
         throw new NotSupportedException("IPv6 is not yet supported");
     }
     this.IPAddress = IPAddress;
     var split = IPAddress.ToString().Split('.');
     Int64 integerIP = 0;
     integerIP |= (Convert.ToInt64(split[0]) << 24);
     integerIP |= (Convert.ToInt64(split[1]) << 16);
     integerIP |= (Convert.ToInt64(split[2]) << 8);
     integerIP |= (Convert.ToInt64(split[3]));
     Base64IP = Base64Converter.IntToNumeric(integerIP, 6);
 }
コード例 #37
0
 private bool IsValid(DbSyndicateAdvertising pSyn)
 {
     return(pSyn.Timestamp + 60 * 60 * 24 * 7 > UnixTimestamp.Timestamp());
 }
コード例 #38
0
 public MySqlFunctionManager(bool allowFuncDefChange)
 {
     this.allowFuncDefChange = allowFuncDefChange;
     parsingStrateg["CAST"] = FunctionParsingStrategy.Cast;
     parsingStrateg["POSITION"] = FunctionParsingStrategy.Position;
     parsingStrateg["SUBSTR"] = FunctionParsingStrategy.Substring;
     parsingStrateg["SUBSTRING"] = FunctionParsingStrategy.Substring;
     parsingStrateg["TRIM"] = FunctionParsingStrategy.Trim;
     parsingStrateg["AVG"] = FunctionParsingStrategy.Avg;
     parsingStrateg["COUNT"] = FunctionParsingStrategy.Count;
     parsingStrateg["GROUP_CONCAT"] = FunctionParsingStrategy.GroupConcat;
     parsingStrateg["MAX"] = FunctionParsingStrategy.Max;
     parsingStrateg["MIN"] = FunctionParsingStrategy.Min;
     parsingStrateg["SUM"] = FunctionParsingStrategy.Sum;
     parsingStrateg["ROW"] = FunctionParsingStrategy.Row;
     parsingStrateg["CHAR"] = FunctionParsingStrategy.Char;
     parsingStrateg["CONVERT"] = FunctionParsingStrategy.Convert;
     parsingStrateg["EXTRACT"] = FunctionParsingStrategy.Extract;
     parsingStrateg["TIMESTAMPADD"] = FunctionParsingStrategy.Timestampadd;
     parsingStrateg["TIMESTAMPDIFF"] = FunctionParsingStrategy.Timestampdiff;
     parsingStrateg["GET_FORMAT"] = FunctionParsingStrategy.GetFormat;
     functionPrototype["ABS"] = new Abs(null);
     functionPrototype["ACOS"] = new Acos(null);
     functionPrototype["ADDDATE"] = new Adddate(null);
     functionPrototype["ADDTIME"] = new Addtime(null);
     functionPrototype["AES_DECRYPT"] = new AesDecrypt(null);
     functionPrototype["AES_ENCRYPT"] = new AesEncrypt(null);
     functionPrototype["ANALYSE"] = new Analyse(null);
     functionPrototype["ASCII"] = new Ascii(null);
     functionPrototype["ASIN"] = new Asin(null);
     functionPrototype["ATAN2"] = new Atan2(null);
     functionPrototype["ATAN"] = new Atan(null);
     functionPrototype["BENCHMARK"] = new Benchmark(null);
     functionPrototype["BIN"] = new Bin(null);
     functionPrototype["BIT_AND"] = new BitAnd(null);
     functionPrototype["BIT_COUNT"] = new BitCount(null);
     functionPrototype["BIT_LENGTH"] = new BitLength(null);
     functionPrototype["BIT_OR"] = new BitOR(null);
     functionPrototype["BIT_XOR"] = new BitXor(null);
     functionPrototype["CEIL"] = new Ceiling(null);
     functionPrototype["CEILING"] = new Ceiling(null);
     functionPrototype["CHAR_LENGTH"] = new CharLength(null);
     functionPrototype["CHARACTER_LENGTH"] = new CharLength(null);
     functionPrototype["CHARSET"] = new Charset(null);
     functionPrototype["COALESCE"] = new Coalesce(null);
     functionPrototype["COERCIBILITY"] = new Coercibility(null);
     functionPrototype["COLLATION"] = new Collation(null);
     functionPrototype["COMPRESS"] = new Compress(null);
     functionPrototype["CONCAT_WS"] = new ConcatWs(null);
     functionPrototype["CONCAT"] = new Concat(null);
     functionPrototype["CONNECTION_ID"] = new ConnectionId(null);
     functionPrototype["CONV"] = new Conv(null);
     functionPrototype["CONVERT_TZ"] = new ConvertTz(null);
     functionPrototype["COS"] = new Cos(null);
     functionPrototype["COT"] = new Cot(null);
     functionPrototype["CRC32"] = new Crc32(null);
     functionPrototype["CURDATE"] = new Curdate();
     functionPrototype["CURRENT_DATE"] = new Curdate();
     functionPrototype["CURRENT_TIME"] = new Curtime();
     functionPrototype["CURTIME"] = new Curtime();
     functionPrototype["CURRENT_TIMESTAMP"] = new Now();
     functionPrototype["CURRENT_USER"] = new CurrentUser();
     functionPrototype["CURTIME"] = new Curtime();
     functionPrototype["DATABASE"] = new Database(null);
     functionPrototype["DATE_ADD"] = new DateAdd(null);
     functionPrototype["DATE_FORMAT"] = new DateFormat(null);
     functionPrototype["DATE_SUB"] = new DateSub(null);
     functionPrototype["DATE"] = new Date(null);
     functionPrototype["DATEDIFF"] = new Datediff(null);
     functionPrototype["DAY"] = new Dayofmonth(null);
     functionPrototype["DAYOFMONTH"] = new Dayofmonth(null);
     functionPrototype["DAYNAME"] = new Dayname(null);
     functionPrototype["DAYOFWEEK"] = new Dayofweek(null);
     functionPrototype["DAYOFYEAR"] = new Dayofyear(null);
     functionPrototype["DECODE"] = new Decode(null);
     functionPrototype["DEFAULT"] = new Default(null);
     functionPrototype["DEGREES"] = new Degrees(null);
     functionPrototype["DES_DECRYPT"] = new DesDecrypt(null);
     functionPrototype["DES_ENCRYPT"] = new DesEncrypt(null);
     functionPrototype["ELT"] = new Elt(null);
     functionPrototype["ENCODE"] = new Encode(null);
     functionPrototype["ENCRYPT"] = new Encrypt(null);
     functionPrototype["EXP"] = new Exp(null);
     functionPrototype["EXPORT_SET"] = new ExportSet(null);
     // functionPrototype.put("EXTRACT", new Extract(null));
     functionPrototype["EXTRACTVALUE"] = new ExtractValue(null);
     functionPrototype["FIELD"] = new Field(null);
     functionPrototype["FIND_IN_SET"] = new FindInSet(null);
     functionPrototype["FLOOR"] = new Floor(null);
     functionPrototype["FORMAT"] = new Format(null);
     functionPrototype["FOUND_ROWS"] = new FoundRows(null);
     functionPrototype["FROM_DAYS"] = new FromDays(null);
     functionPrototype["FROM_UNIXTIME"] = new FromUnixtime(null);
     // functionPrototype.put("GET_FORMAT", new GetFormat(null));
     functionPrototype["GET_LOCK"] = new GetLock(null);
     functionPrototype["GREATEST"] = new Greatest(null);
     functionPrototype["HEX"] = new Hex(null);
     functionPrototype["HOUR"] = new Hour(null);
     functionPrototype["IF"] = new IF(null);
     functionPrototype["IFNULL"] = new IFNull(null);
     functionPrototype["INET_ATON"] = new InetAton(null);
     functionPrototype["INET_NTOA"] = new InetNtoa(null);
     functionPrototype["INSERT"] = new Insert(null);
     functionPrototype["INSTR"] = new Instr(null);
     functionPrototype["INTERVAL"] = new Interval(null);
     functionPrototype["IS_FREE_LOCK"] = new IsFreeLock(null);
     functionPrototype["IS_USED_LOCK"] = new IsUsedLock(null);
     functionPrototype["ISNULL"] = new IsNull(null);
     functionPrototype["LAST_DAY"] = new LastDay(null);
     functionPrototype["LAST_INSERT_ID"] = new LastInsertId(null);
     functionPrototype["LCASE"] = new Lower(null);
     functionPrototype["LEAST"] = new Least(null);
     functionPrototype["LEFT"] = new Left(null);
     functionPrototype["LENGTH"] = new Length(null);
     functionPrototype["LN"] = new Log(null);
     // Ln(X) equals Log(X)
     functionPrototype["LOAD_FILE"] = new LoadFile(null);
     functionPrototype["LOCALTIME"] = new Now();
     functionPrototype["LOCALTIMESTAMP"] = new Now();
     functionPrototype["LOCATE"] = new Locate(null);
     functionPrototype["LOG10"] = new Log10(null);
     functionPrototype["LOG2"] = new Log2(null);
     functionPrototype["LOG"] = new Log(null);
     functionPrototype["LOWER"] = new Lower(null);
     functionPrototype["LPAD"] = new Lpad(null);
     functionPrototype["LTRIM"] = new Ltrim(null);
     functionPrototype["MAKE_SET"] = new MakeSet(null);
     functionPrototype["MAKEDATE"] = new Makedate(null);
     functionPrototype["MAKETIME"] = new Maketime(null);
     functionPrototype["MASTER_POS_WAIT"] = new MasterPosWait(null);
     functionPrototype["MD5"] = new Md5(null);
     functionPrototype["MICROSECOND"] = new Microsecond(null);
     functionPrototype["MID"] = new Substring(null);
     functionPrototype["MINUTE"] = new Minute(null);
     functionPrototype["MONTH"] = new Month(null);
     functionPrototype["MONTHNAME"] = new Monthname(null);
     functionPrototype["NAME_CONST"] = new NameConst(null);
     functionPrototype["NOW"] = new Now();
     functionPrototype["NULLIF"] = new NullIF(null);
     functionPrototype["OCT"] = new Oct(null);
     functionPrototype["OCTET_LENGTH"] = new Length(null);
     functionPrototype["OLD_PASSWORD"] = new OldPassword(null);
     functionPrototype["ORD"] = new Ord(null);
     functionPrototype["PASSWORD"] = new Password(null);
     functionPrototype["PERIOD_ADD"] = new PeriodAdd(null);
     functionPrototype["PERIOD_DIFF"] = new PeriodDiff(null);
     functionPrototype["PI"] = new PI(null);
     functionPrototype["POW"] = new Pow(null);
     functionPrototype["POWER"] = new Pow(null);
     functionPrototype["QUARTER"] = new Quarter(null);
     functionPrototype["QUOTE"] = new Quote(null);
     functionPrototype["RADIANS"] = new Radians(null);
     functionPrototype["RAND"] = new Rand(null);
     functionPrototype["RELEASE_LOCK"] = new ReleaseLock(null);
     functionPrototype["REPEAT"] = new Repeat(null);
     functionPrototype["REPLACE"] = new Replace(null);
     functionPrototype["REVERSE"] = new Reverse(null);
     functionPrototype["RIGHT"] = new Right(null);
     functionPrototype["ROUND"] = new Round(null);
     functionPrototype["ROW_COUNT"] = new RowCount(null);
     functionPrototype["RPAD"] = new Rpad(null);
     functionPrototype["RTRIM"] = new Rtrim(null);
     functionPrototype["SCHEMA"] = new Database(null);
     functionPrototype["SEC_TO_TIME"] = new SecToTime(null);
     functionPrototype["SECOND"] = new Second(null);
     functionPrototype["SESSION_USER"] = new User(null);
     functionPrototype["SHA1"] = new Sha1(null);
     functionPrototype["SHA"] = new Sha1(null);
     functionPrototype["SHA2"] = new Sha2(null);
     functionPrototype["SIGN"] = new Sign(null);
     functionPrototype["SIN"] = new Sin(null);
     functionPrototype["SLEEP"] = new Sleep(null);
     functionPrototype["SOUNDEX"] = new Soundex(null);
     functionPrototype["SPACE"] = new Space(null);
     functionPrototype["SQRT"] = new Sqrt(null);
     functionPrototype["STD"] = new Std(null);
     functionPrototype["STDDEV_POP"] = new StdDevPop(null);
     functionPrototype["STDDEV_SAMP"] = new StdDevSamp(null);
     functionPrototype["STDDEV"] = new StdDev(null);
     functionPrototype["STR_TO_DATE"] = new StrToDate(null);
     functionPrototype["STRCMP"] = new Strcmp(null);
     functionPrototype["SUBDATE"] = new Subdate(null);
     functionPrototype["SUBSTRING_INDEX"] = new SubstringIndex(null);
     functionPrototype["SUBTIME"] = new Subtime(null);
     functionPrototype["SYSDATE"] = new Sysdate(null);
     functionPrototype["SYSTEM_USER"] = new User(null);
     functionPrototype["TAN"] = new Tan(null);
     functionPrototype["TIME_FORMAT"] = new TimeFormat(null);
     functionPrototype["TIME_TO_SEC"] = new TimeToSec(null);
     functionPrototype["TIME"] = new Time(null);
     functionPrototype["TIMEDIFF"] = new Timediff(null);
     functionPrototype["TIMESTAMP"] = new Timestamp(null);
     // functionPrototype.put("TIMESTAMPADD", new Timestampadd(null));
     // functionPrototype.put("TIMESTAMPDIFF", new Timestampdiff(null));
     functionPrototype["TO_DAYS"] = new ToDays(null);
     functionPrototype["TO_SECONDS"] = new ToSeconds(null);
     functionPrototype["TRUNCATE"] = new Truncate(null);
     functionPrototype["UCASE"] = new Upper(null);
     functionPrototype["UNCOMPRESS"] = new Uncompress(null);
     functionPrototype["UNCOMPRESSED_LENGTH"] = new UncompressedLength(null);
     functionPrototype["UNHEX"] = new Unhex(null);
     functionPrototype["UNIX_TIMESTAMP"] = new UnixTimestamp(null);
     functionPrototype["UPDATEXML"] = new UpdateXml(null);
     functionPrototype["UPPER"] = new Upper(null);
     functionPrototype["USER"] = new User(null);
     functionPrototype["UTC_DATE"] = new UtcDate(null);
     functionPrototype["UTC_TIME"] = new UtcTime(null);
     functionPrototype["UTC_TIMESTAMP"] = new UtcTimestamp(null);
     functionPrototype["UUID_SHORT"] = new UuidShort(null);
     functionPrototype["UUID"] = new Uuid(null);
     functionPrototype["VALUES"] = new Values(null);
     functionPrototype["VAR_POP"] = new VarPop(null);
     functionPrototype["VAR_SAMP"] = new VarSamp(null);
     functionPrototype["VARIANCE"] = new Variance(null);
     functionPrototype["VERSION"] = new Version(null);
     functionPrototype["WEEK"] = new Week(null);
     functionPrototype["WEEKDAY"] = new Weekday(null);
     functionPrototype["WEEKOFYEAR"] = new Weekofyear(null);
     functionPrototype["YEAR"] = new Year(null);
     functionPrototype["YEARWEEK"] = new Yearweek(null);
 }
コード例 #39
0
        public void AddSyndicate(Character pSender, MsgSynRecuitAdvertising pMsg)
        {
            if (pSender == null || pSender.Syndicate == null)
            {
                return;
            }

            string szMessage = pMsg.Description;

            if (pSender.SyndicateRank != SyndicateRank.GUILD_LEADER)
            {
                return;
            }

            if (szMessage.Length > 255)
            {
                szMessage = szMessage.Substring(0, 255);
            }

            if (m_pSyndicateAdvertisings.Values.FirstOrDefault(x => x.SyndicateIdentity == pSender.SyndicateIdentity) != null)
            {
                EditSyndicate(pSender, pMsg);
                return;
            }

            if (pMsg.LevelRequirement <= 0)
            {
                pMsg.LevelRequirement = 1;
            }

            if (pSender.Syndicate.SilverDonation < pMsg.Amount)
            {
                pSender.Send(ServerString.STR_SYNRECRUIT_NOT_ENOUGH_MONEY);
                return;
            }

            if (pMsg.Amount < _MIN_MONEY_AMOUNT)
            {
                pSender.Send(ServerString.STR_SYNRECRUIT_NOT_ENOUGH_DONATION);
                return;
            }

            pSender.Syndicate.ChangeFunds((int)pMsg.Amount * -1);

            DbSyndicateAdvertising dbSyn = new DbSyndicateAdvertising
            {
                AutoRecruit            = (byte)(pMsg.IsAutoRecruit ? 1 : 0),
                Donation               = (uint)pMsg.Amount,
                Message                = szMessage,
                RequiredLevel          = pMsg.LevelRequirement,
                RequiredMetempsychosis = pMsg.RebornRequirement,
                RequiredProfession     = pMsg.ProfessionForbid,
                SyndicateIdentity      = pSender.SyndicateIdentity,
                SyndicateName          = pSender.SyndicateName,
                Timestamp              = (uint)UnixTimestamp.Timestamp()
            };

            if (m_pRepo.SaveOrUpdate(dbSyn))
            {
                m_pSyndicateAdvertisings.TryAdd(dbSyn.SyndicateIdentity, dbSyn);
            }
            else
            {
                pSender.Send("Oops! Something went wrong.");
            }
        }
コード例 #40
0
ファイル: IRCService.cs プロジェクト: danij/IRCService.NET
 /// <summary>
 /// Creates a new channel and sets this service as a reference
 /// </summary>
 /// <param name="name"></param>
 /// <param name="creationTimestamp"></param>
 /// <returns></returns>
 public IChannel CreateChannel(string name, 
     UnixTimestamp creationTimestamp = null)
 {
     return new Channel(this, name, creationTimestamp);
 }
コード例 #41
0
        public void Parse(GameClient Session, ClientPacket Packet)
        {
            if (Session == null || Session.GetHabbo() == null || !Session.GetHabbo().InRoom)
            {
                return;
            }

            Room Room = Session.GetHabbo().CurrentRoom;

            if (Room == null)
            {
                return;
            }

            RoomUser User = Room.GetRoomUserManager().GetRoomUserByHabbo(Session.GetHabbo().Id);

            if (User == null)
            {
                return;
            }

            string Message = StringCharFilter.Escape(Packet.PopString());

            if (Message.Length > 100)
            {
                Message = Message.Substring(0, 100);
            }

            int Colour = Packet.PopInt();

            ChatStyle Style = null;

            if (!RavenEnvironment.GetGame().GetChatManager().GetChatStyles().TryGetStyle(Colour, out Style) || (Style.RequiredRight.Length > 0 && !Session.GetHabbo().GetPermissions().HasRight(Style.RequiredRight)))
            {
                Colour = 0;
            }

            User.LastBubble = Session.GetHabbo().CustomBubbleId == 0 ? Colour : Session.GetHabbo().CustomBubbleId;

            if (RavenEnvironment.GetUnixTimestamp() < Session.GetHabbo().FloodTime&& Session.GetHabbo().FloodTime != 0)
            {
                return;
            }

            if (Session.GetHabbo().TimeMuted > 0)
            {
                Session.SendMessage(new MutedComposer(Session.GetHabbo().TimeMuted));
                return;
            }

            if (!Room.CheckRights(Session, false) && Room.muteSignalEnabled == true)
            {
                Session.SendWhisper("La sala está silenciada, no puedes hablar en ella hasta tanto el dueño o alguien con permisos en ella lo permita.");
                return;
            }

            if (!Session.GetHabbo().GetPermissions().HasRight("room_ignore_mute") && Room.CheckMute(Session))
            {
                Session.SendWhisper("Oops, usted se encuentra silenciad@.");
                return;
            }

            if (!Session.GetHabbo().GetPermissions().HasRight("mod_tool"))
            {
                int MuteTime;
                if (User.IncrementAndCheckFlood(out MuteTime))
                {
                    Session.SendMessage(new FloodControlComposer(MuteTime));
                    return;
                }
            }

            if (Session.GetHabbo().LastMessage == Message)
            {
                Session.GetHabbo().LastMessageCount++;
                if (Session.GetHabbo().LastMessageCount > 3)
                {
                    RavenEnvironment.GetGame().GetClientManager().RepeatAlert(new RoomInviteComposer(int.MinValue, "Repeat: " + Session.GetHabbo().Username + " / Frase: " + Message + " / Veces: " + Session.GetHabbo().LastMessageCount + "."));
                    Session.GetHabbo().LastMessageCount = 0;
                }
            }

            if (Message.Contains("&#1º;") || Message.Contains("&#1º") || Message.Contains("&#"))
            {
                Session.SendMessage(new MassEventComposer("habbopages/spammer.txt")); return;
            }

            Room.GetFilter().CheckMessage(Message);
            if (Room.GetWired().TriggerEvent(HabboHotel.Items.Wired.WiredBoxType.TriggerUserSays, Session.GetHabbo(), Message.ToLower()))
            {
                return;
            }

            if (Message.StartsWith(":", StringComparison.CurrentCulture) && RavenEnvironment.GetGame().GetChatManager().GetCommands().Parse(Session, Message))
            {
                return;
            }

            RavenEnvironment.GetGame().GetChatManager().GetLogs().StoreChatlog(new Raven.HabboHotel.Rooms.Chat.Logs.ChatlogEntry(Session.GetHabbo().Id, Room.Id, Message, UnixTimestamp.GetNow(), Session.GetHabbo(), Room));

            string word;

            if (!Session.GetHabbo().GetPermissions().HasRight("word_filter_override") &&
                RavenEnvironment.GetGame().GetChatManager().GetFilter().IsUnnaceptableWord(Message, out word))
            {
                Session.GetHabbo().BannedPhraseCount++;
                if (Session.GetHabbo().BannedPhraseCount >= 1)
                {
                    Session.SendWhisper("¡Has mencionado una palabra no apta para el código de " + RavenEnvironment.GetDBConfig().DBData["hotel.name"] + "! Aviso " + Session.GetHabbo().BannedPhraseCount + "/10");

                    RavenEnvironment.GetGame().GetClientManager().StaffAlert1(new RoomInviteComposer(int.MinValue, "Spammer: " + Session.GetHabbo().Username + " / Frase: " + Message + " / Palabra: " + word.ToUpper() + " / Fase: " + Session.GetHabbo().BannedPhraseCount + " / 10."));
                    RavenEnvironment.GetGame().GetClientManager().StaffAlert2(new RoomNotificationComposer("Alerta de publicista:",
                                                                                                           "<b><font color=\"#B40404\">Por favor, recuerda investigar bien antes de recurrir a una sanción.</font></b><br><br>Palabra: <b>" + word.ToUpper() + "</b>.<br><br><b>Frase:</b><br><i>" + Message +
                                                                                                           "</i>.<br><br><b>Tipo:</b><br>Chat de sala.\r\n" + "<b>Usuario: " + Session.GetHabbo().Username + "</b><br><b>Secuencia:</b> " + Session.GetHabbo().BannedPhraseCount + "/10.", "foto", "Investigar", "event:navigator/goto/" +
                                                                                                           Session.GetHabbo().CurrentRoomId));
                    return;
                }
                if (Session.GetHabbo().BannedPhraseCount >= 10)
                {
                    RavenEnvironment.GetGame().GetModerationManager().BanUser("System", HabboHotel.Moderation.ModerationBanType.USERNAME, Session.GetHabbo().Username, "Baneado por hacer spam con la frase (" + Message + ")", (RavenEnvironment.GetUnixTimestamp() + 78892200));
                    Session.Disconnect();
                    return;
                }
                Session.SendMessage(new ShoutComposer(User.VirtualId, "Mensaje Inapropiado", 0, Colour));
                return;
            }

            Session.GetHabbo().LastMessage = Message;
            RavenEnvironment.GetGame().GetQuestManager().ProgressUserQuest(Session, QuestType.SOCIAL_CHAT);

            User.UnIdle();
            User.OnChat(User.LastBubble, Message, true);
        }
コード例 #42
0
 public void GetHashCodeReturnsHashCodeOfLong(
     UnixTimestamp sut)
 {
     var expected = sut.SecondsSinceEpoch.GetHashCode();
     Assert.Equal(expected, sut.GetHashCode());
 }
コード例 #43
0
        public void Parse(HabboHotel.GameClients.GameClient Session, ClientPacket Packet)
        {
            if (Session == null || Session.GetHabbo() == null)
            {
                return;
            }

            // Run a quick check to see if we have any existing tickets.
            if (BiosEmuThiago.GetGame().GetModerationManager().UserHasTickets(Session.GetHabbo().Id))
            {
                ModerationTicket PendingTicket = BiosEmuThiago.GetGame().GetModerationManager().GetTicketBySenderId(Session.GetHabbo().Id);
                if (PendingTicket != null)
                {
                    Session.SendMessage(new CallForHelpPendingCallsComposer(PendingTicket));
                    return;
                }
            }

            List <string> Chats = new List <string>();

            string Message        = StringCharFilter.Escape(Packet.PopString().Trim());
            int    Category       = Packet.PopInt();
            int    ReportedUserId = Packet.PopInt();
            int    Type           = Packet.PopInt();// Unsure on what this actually is.

            Habbo ReportedUser = BiosEmuThiago.GetHabboById(ReportedUserId);

            if (ReportedUser == null)
            {
                // User doesn't exist.
                return;
            }

            int Messagecount = Packet.PopInt();

            for (int i = 0; i < Messagecount; i++)
            {
                Packet.PopInt();
                Chats.Add(Packet.PopString());
            }

            ModerationTicket Ticket = new ModerationTicket(1, Type, Category, UnixTimestamp.GetNow(), 1, Session.GetHabbo(), ReportedUser, Message, Session.GetHabbo().CurrentRoom, Chats);

            if (!BiosEmuThiago.GetGame().GetModerationManager().TryAddTicket(Ticket))
            {
                return;
            }

            using (IQueryAdapter dbClient = BiosEmuThiago.GetDatabaseManager().GetQueryReactor())
            {
                // TODO: Come back to this.

                /*dbClient.SetQuery("INSERT INTO `moderation_tickets` (`score`,`type`,`status`,`sender_id`,`reported_id`,`moderator_id`,`message`,`room_id`,`room_name`,`timestamp`) VALUES (1, '" + Category + "', 'open', '" + Session.GetHabbo().Id + "', '" + ReportedUserId + "', '0', @message, '0', '', '" + BiosEmuThiago.GetUnixTimestamp() + "')");
                 * dbClient.AddParameter("message", Message);
                 * dbClient.RunQuery();*/

                dbClient.runFastQuery("UPDATE `user_info` SET `cfhs` = `cfhs` + '1' WHERE `user_id` = '" + Session.GetHabbo().Id + "' LIMIT 1");
            }

            BiosEmuThiago.GetGame().GetClientManager().ModAlert("Um novo ticket de suporte foi enviado!");
            BiosEmuThiago.GetGame().GetClientManager().SendMessage(new ModeratorSupportTicketComposer(Session.GetHabbo().Id, Ticket), "mod_tool");
        }
コード例 #44
0
 public void SecondsSinceEpochIsExpected(long expected)
 {
     var actual = new UnixTimestamp(expected);
     Assert.Equal(expected, actual.SecondsSinceEpoch);
 }
コード例 #45
0
        public void Parse(GameClient Session, ClientPacket Packet)
        {
            if (Session == null || Session.GetHabbo() == null || !Session.GetHabbo().InRoom)
            {
                return;
            }

            Room Room = Session.GetHabbo().CurrentRoom;

            if (Room == null)
            {
                return;
            }

            RoomUser User = Room.GetRoomUserManager().GetRoomUserByHabbo(Session.GetHabbo().Id);

            if (User == null)
            {
                return;
            }

            string Message = StringCharFilter.Escape(Packet.PopString());

            if (Message.Length > 100)
            {
                Message = Message.Substring(0, 100);
            }

            int Colour = Packet.PopInt();

            ChatStyle Style = null;

            if (!RocketEmulador.GetGame().GetChatManager().GetChatStyles().TryGetStyle(Colour, out Style) || (Style.RequiredRight.Length > 0 && !Session.GetHabbo().GetPermissions().HasRight(Style.RequiredRight)))
            {
                Colour = 0;
            }

            User.UnIdle();

            if (RocketEmulador.GetUnixTimestamp() < Session.GetHabbo().FloodTime&& Session.GetHabbo().FloodTime != 0)
            {
                return;
            }

            if (Session.GetHabbo().TimeMuted > 0)
            {
                Session.SendMessage(new MutedComposer(Session.GetHabbo().TimeMuted));
                return;
            }
            if (RocketEmulador.GetGame().GetChatManager().GetFilter().IsFiltered(Message))
            {
                RocketEmulador.GetGame().GetClientManager().StaffAlert(new RoomNotificationComposer("Alerta de divulgação !",
                                                                                                    "O Usuário: <b>" + Session.GetHabbo().Username + "<br>" +

                                                                                                    "<br></b> Está divulgando uma palavra que foi bloqueada" + "<br>" +

                                                                                                    "<br><b>A palavra usada foi:</b><br>" +
                                                                                                    "<br>" + "<b>" + "<font color =\"#FF0000\">" + Message + "</font>" + "</b><br>" +
                                                                                                    "<br>Para ir a la sala, clique em \"Ir a Sala \"</b>",
                                                                                                    "filter", "Ir a Sala", "event:navigator/goto/" + Session.GetHabbo().CurrentRoomId));
                Session.GetHabbo().GetClient().SendMessage(new WhisperComposer(User.VirtualId, "A seguinte palavra foi bloqueada em nosso hotel:" + " " + Message, 0, 34));
                Message = null;
            }

            if (!Session.GetHabbo().GetPermissions().HasRight("room_ignore_mute") && Room.CheckMute(Session))
            {
                Session.SendWhisper("Opa, você atualmente está silenciado.", 34);
                return;
            }

            User.LastBubble = Session.GetHabbo().CustomBubbleId == 0 ? Colour : Session.GetHabbo().CustomBubbleId;

            if (!Session.GetHabbo().GetPermissions().HasRight("mod_tool"))
            {
                int MuteTime;
                if (User.IncrementAndCheckFlood(out MuteTime))
                {
                    Session.SendMessage(new FloodControlComposer(MuteTime));
                    return;
                }
            }

            if (Message.StartsWith(":", StringComparison.CurrentCulture) && RocketEmulador.GetGame().GetChatManager().GetCommands().Parse(Session, Message))
            {
                return;
            }

            RocketEmulador.GetGame().GetChatManager().GetLogs().StoreChatlog(new ChatlogEntry(Session.GetHabbo().Id, Room.Id, Message, UnixTimestamp.GetNow(), Session.GetHabbo(), Room));

            if (RocketEmulador.GetGame().GetChatManager().GetFilter().CheckBannedWords(Message))
            {
                Session.GetHabbo().BannedPhraseCount++;

                if (Session.GetHabbo().BannedPhraseCount >= RocketGame.BannedPhrasesAmount)
                {
                    RocketEmulador.GetGame().GetModerationManager().BanUser("RocketEmulador", HabboHotel.Moderation.ModerationBanType.USERNAME, Session.GetHabbo().Username, "Spamming banned phrases (" + Message + ")", (RocketEmulador.GetUnixTimestamp() + 78892200));
                    Session.Disconnect();
                    return;
                }

                Session.SendMessage(new ChatComposer(User.VirtualId, Message, 0, Colour));
                return;
            }

            if (!Session.GetHabbo().GetPermissions().HasRight("word_filter_override"))
            {
                Message = RocketEmulador.GetGame().GetChatManager().GetFilter().CheckMessage(Message);
            }


            RocketEmulador.GetGame().GetQuestManager().ProgressUserQuest(Session, QuestType.SOCIAL_CHAT);

            User.OnChat(User.LastBubble, Message, false);
        }
コード例 #46
0
        public void Parse(GameClient Session, ClientPacket Packet)
        {
            if (Session == null || Session.GetHabbo() == null || !Session.GetHabbo().InRoom)
            {
                return;
            }

            Room Room = Session.GetHabbo().CurrentRoom;

            if (Room == null)
            {
                return;
            }

            RoomUser User = Room.GetRoomUserManager().GetRoomUserByHabbo(Session.GetHabbo().Id);

            if (User == null)
            {
                return;
            }

            string Message = StringCharFilter.Escape(Packet.PopString());

            if (Message.Length > 100)
            {
                Message = Message.Substring(0, 100);
            }

            int Colour = Packet.PopInt();

            ChatStyle Style = null;

            if (!QuasarEnvironment.GetGame().GetChatManager().GetChatStyles().TryGetStyle(Colour, out Style) || (Style.RequiredRight.Length > 0 && !Session.GetHabbo().GetPermissions().HasRight(Style.RequiredRight)))
            {
                Colour = 0;
            }

            User.LastBubble = Session.GetHabbo().CustomBubbleId == 0 ? Colour : Session.GetHabbo().CustomBubbleId;

            if (QuasarEnvironment.GetUnixTimestamp() < Session.GetHabbo().FloodTime&& Session.GetHabbo().FloodTime != 0)
            {
                return;
            }

            if (Session.GetHabbo().TimeMuted > 0)
            {
                Session.SendMessage(new MutedComposer(Session.GetHabbo().TimeMuted));
                return;
            }

            if (!Session.GetHabbo().GetPermissions().HasRight("room_ignore_mute") && Room.CheckMute(Session))
            {
                Session.SendMessage(new RoomCustomizedAlertComposer("Deze kamer heeft een spraakverbod."));
                return;
            }

            if (!Session.GetHabbo().GetPermissions().HasRight("mod_tool"))
            {
                int MuteTime;
                if (User.IncrementAndCheckFlood(out MuteTime))
                {
                    Session.SendMessage(new FloodControlComposer(MuteTime));
                    return;
                }
            }

            if (Message.StartsWith(":", StringComparison.CurrentCulture) && QuasarEnvironment.GetGame().GetChatManager().GetCommands().Parse(Session, Message))
            {
                return;
            }

            QuasarEnvironment.GetGame().GetChatManager().GetLogs().StoreChatlog(new Quasar.HabboHotel.Rooms.Chat.Logs.ChatlogEntry(Session.GetHabbo().Id, Room.Id, Message, UnixTimestamp.GetNow(), Session.GetHabbo(), Room));


            string word;

            if (!Session.GetHabbo().GetPermissions().HasRight("word_filter_override") &&
                QuasarEnvironment.GetGame().GetChatManager().GetFilter().IsUnnaceptableWord(Message, out word))
            {
                Session.SendMessage(new RoomCustomizedAlertComposer("Het woord '" + word + "' is verboden."));
                QuasarEnvironment.GetGame().GetClientManager().StaffAlert(RoomNotificationComposer.SendBubble("bubble_filter", "Filter bericht\n\nHabbis: " + Session.GetHabbo().Username + "\nWoord: " + word + "\nType: Chat (kamer)", ""));
                return;
            }

            QuasarEnvironment.GetGame().GetQuestManager().ProgressUserQuest(Session, QuestType.SOCIAL_CHAT);

            User.UnIdle();
            User.OnChat(User.LastBubble, Message, true);
        }
コード例 #47
0
        public bool Add(Item item, bool isLogin = false)
        {
            ItemPosition pos = Calculations.GetItemPosition(item.Type);

            #region Sanity Checks

            if (!isLogin)
            {
                // Level check
                if (item.Itemtype.ReqLevel > m_pOwner.Level)
                {
                    return(false);
                }

                // Profession check
                if (m_pOwner.Metempsychosis > 0 &&
                    m_pOwner.Level >= 70 &&
                    item.Itemtype.ReqLevel <= 70)
                {
                }
                else
                {
                    if (item.Itemtype.ReqProfession > 0)
                    {
                        // item
                        int iProfession      = item.Itemtype.ReqProfession / 10;
                        int iProfessionLevel = item.Itemtype.ReqProfession % 10;

                        if (iProfession == 19)
                        {
                            iProfession = 10;
                        }

                        // user
                        int uProfession      = m_pOwner.Profession / 10;
                        int uProfessionLevel = m_pOwner.Profession % 10;

                        if (uProfession > 10 && iProfession == 10)
                        {
                            uProfession = 10;
                        }

                        if (iProfession == uProfession)
                        {
                            if (iProfessionLevel > uProfessionLevel)
                            {
                                return(false);
                            }
                        }
                        else
                        {
                            return(false);
                        }
                    }

                    // Attribute check
                    if (item.Itemtype.ReqForce != 0 &&
                        item.Itemtype.ReqForce > m_pOwner.Strength)
                    {
                        return(false);
                    }
                    if (item.Itemtype.ReqSpeed != 0 &&
                        item.Itemtype.ReqSpeed > m_pOwner.Agility)
                    {
                        return(false);
                    }
                    if (item.Itemtype.ReqHealth != 0 &&
                        item.Itemtype.ReqHealth > m_pOwner.Vitality)
                    {
                        return(false);
                    }
                    if (item.Itemtype.ReqSoul != 0 &&
                        item.Itemtype.ReqSoul > m_pOwner.Spirit)
                    {
                        return(false);
                    }

                    ushort type = (ushort)(item.Type / 1000);
                    if (pos == ItemPosition.RIGHT_HAND && !m_pOwner.WeaponSkill.Skills.ContainsKey(type) &&
                        item.Itemtype.ReqWeaponskill > 0)
                    {
                        return(false);
                    }

                    if (m_pOwner.WeaponSkill.Skills.ContainsKey(type))
                    {
                        if (pos == ItemPosition.RIGHT_HAND &&
                            m_pOwner.WeaponSkill.Skills[type].Level < item.Itemtype.ReqWeaponskill)
                        {
                            return(false);
                        }
                    }

                    if (type == 421 &&
                        item.Position < (ItemPosition)20 &&
                        Items.ContainsKey(ItemPosition.LEFT_HAND))
                    {
                        m_pOwner.Send("Please remove the equipment in your left hand first.");
                        return(false);
                    }

                    if (type == 900 &&
                        Items.ContainsKey(ItemPosition.RIGHT_HAND) &&
                        Items[ItemPosition.RIGHT_HAND].GetItemSubtype() == 421)
                    {
                        m_pOwner.Send("You cannot equip a shield while wearing a backsword.");
                        return(false);
                    }
                }

                // Gender check
                if (item.Itemtype.ReqSex != 0)
                {
                    if (item.Itemtype.ReqSex != m_pOwner.Gender)
                    {
                        return(false);
                    }
                }
            }

            ItemSort itemSort = item.GetSort();

            if ((itemSort == ItemSort.ITEMSORT_USABLE ||
                 itemSort == ItemSort.ITEMSORT_USABLE2 ||
                 itemSort == ItemSort.ITEMSORT_USABLE3) &&
                pos == ItemPosition.INVENTORY && item.Type / 1000 != 1050)
            {
                // Stores the item temporary data.
                m_pOwner.LastItemResource = 0;
                m_pOwner.LastUsedItem     = item.Identity;
                m_pOwner.LastUsedItemTime = (uint)UnixTimestamp.Timestamp();
                m_pOwner.LastUsedItemtype = item.Type;

                if ((item.Type >= 1000000 && item.Type < 1050000) || item.Type == 725065 || item.Type == 725066)
                // potion
                {
                    if (!m_pOwner.IsAlive)
                    {
                        m_pOwner.Send(ServerString.STR_NOT_ALIVE);
                        return(false);
                    }

                    if (item.Itemtype.Life > 0 && m_pOwner.QueryStatus(FlagInt.POISON_STAR) != null)
                    {
                        //m_pOwner.Send(ServerString.STR_CANT_HEAL_POISON_STAR);
                        return(false);
                    }

                    if (item.Itemtype.Life > 0 && m_pOwner.Life >= m_pOwner.MaxLife)
                    {
                        //m_pOwner.Send(ServerString.STR_YOUR_LIFE_FULL);
                        return(false); // return false so it wont spend processing recalculating the user stts
                    }

                    if (item.Itemtype.Mana > 0 && m_pOwner.Mana >= m_pOwner.MaxMana)
                    {
                        //m_pOwner.Send(ServerString.STR_YOUR_MANA_FULL);
                        return(false); // return false so it wont spend processing recalculating the user stts
                    }

                    if (m_pOwner.IsGm)
                    {
                        m_pOwner.FillLife();
                        m_pOwner.FillMana();
                        return(false);
                    }

                    if (m_pOwner.Inventory.Remove(item.Type, 1))
                    {
                        m_pOwner.AddAttribute(ClientUpdateType.HITPOINTS, item.Itemtype.Life, true);
                        m_pOwner.AddAttribute(ClientUpdateType.MANA, item.Itemtype.Mana, true);
                    }
                    return(false);
                }

                if (item.Type == SpecialItem.MEMORY_AGATE)
                {
                    item.SendCarry();
                    return(false);
                }

                if (item.Type == 723726)
                {
                    if (m_pOwner.Inventory.Remove(item.Type, 1))
                    {
                        m_pOwner.FillLife();
                        m_pOwner.FillMana();
                    }
                    return(false);
                }

                if (item.Type == 723790 && m_pOwner.Inventory.Remove(723790))
                {
                    m_pOwner.AddAttribute(ClientUpdateType.HITPOINTS, 500, true);
                    return(false);
                }

                if (item.Type == SpecialItem.TYPE_EXP_BALL || item.Type == 723834)
                {
                    if (m_pOwner.ExpBallAmount >= 10)
                    {
                        int nDayOfYear  = UnixTimestamp.ToDateTime(m_pOwner.LastUsedExpBall).DayOfYear;
                        int nDayOfYear2 = DateTime.Now.DayOfYear;
                        if (nDayOfYear == nDayOfYear2)
                        {
                            return(false);
                        }
                        m_pOwner.ExpBallAmount = 0;
                    }

                    if (m_pOwner.Inventory.Remove(item.Identity))
                    {
                        m_pOwner.ExpBallAmount   = (byte)(m_pOwner.ExpBallAmount + 1);
                        m_pOwner.LastUsedExpBall = (uint)UnixTimestamp.Timestamp();
                        m_pOwner.Save();
                        m_pOwner.AwardExperience(ServerKernel.GetExpBallExperience(m_pOwner.Level), true, true);
                    }
                    return(false);
                }

                if ((item.Type >= 1060020 && item.Type <= 1060039) || item.Type == 1060102)
                {
                    if (m_pOwner.Map.IsChgMapDisable())
                    {
                        return(false);
                    }
                    m_pOwner.Inventory.Remove(item.Identity);
                }
                else if (item.Type / 1000 == 1060)
                {
                    m_pOwner.Inventory.Remove(item.Identity);
                }

                m_pOwner.TaskItem = item;
                m_pOwner.GameAction.ProcessAction(item.Itemtype.IdAction, m_pOwner, null, item, null);
                return(false);
            }
            if (pos == ItemPosition.INVENTORY)
            {
                return(false);
            }

            if (pos == ItemPosition.LEFT_HAND &&
                itemSort == ItemSort.ITEMSORT_WEAPON_SHIELD)
            {
                if (Items.ContainsKey(ItemPosition.RIGHT_HAND) &&
                    Items[ItemPosition.RIGHT_HAND].GetSort() == ItemSort.ITEMSORT_WEAPON_DOUBLE_HAND)
                {
                    if (!m_pOwner.Magics.CheckType(10311))
                    {
                        return(false);
                    }
                }
                if (!Items.ContainsKey(ItemPosition.RIGHT_HAND))
                {
                    return(false);
                }
            }

            #endregion

            if (item.IsArrowSort())
            {
                item.Position = ItemPosition.LEFT_HAND;
            }

            switch (item.Position)
            {
            case ItemPosition.RIGHT_HAND:
                if (pos != ItemPosition.RIGHT_HAND ||
                    (itemSort != ItemSort.ITEMSORT_WEAPON_SINGLE_HAND &&
                     itemSort != ItemSort.ITEMSORT_WEAPON_DOUBLE_HAND &&
                     itemSort != ItemSort.ITEMSORT_WEAPON_SINGLE_HAND2))
                {
                    item.Position = 0;
                    return(false);
                }

                if ((itemSort == ItemSort.ITEMSORT_WEAPON_DOUBLE_HAND &&
                     Items.ContainsKey(ItemPosition.LEFT_HAND)))
                {
                    Remove(ItemPosition.LEFT_HAND);
                }

                if (Items.ContainsKey(ItemPosition.RIGHT_HAND) && item.Position == ItemPosition.RIGHT_HAND)
                {
                    Remove(ItemPosition.RIGHT_HAND, ItemRemoveMethod.REMOVE_TO_INVENTORY);
                }
                break;

            case ItemPosition.LEFT_HAND:
                if (itemSort != ItemSort.ITEMSORT_WEAPON_SINGLE_HAND &&
                    itemSort != ItemSort.ITEMSORT_WEAPON_SHIELD &&
                    itemSort != ItemSort.ITEMSORT_WEAPON_SINGLE_HAND2 &&
                    item.Type / 1000 != 1050)
                {
                    item.Position = 0;
                    return(false);
                }

                if (m_pOwner.Profession >= 100)
                {
                    if (Items.ContainsKey(ItemPosition.LEFT_HAND) && Items[ItemPosition.LEFT_HAND] == item)
                    {
                        Remove(ItemPosition.LEFT_HAND, ItemRemoveMethod.REMOVE_TO_INVENTORY);
                    }

                    item.Position = 0;
                    return(false);
                }

                if (item.IsArrowSort() &&
                    (!Items.ContainsKey(ItemPosition.RIGHT_HAND) ||
                     !Items[ItemPosition.RIGHT_HAND].IsBow()))
                {
                    item.Position = 0;
                    return(false);
                }

                if (Items.ContainsKey(ItemPosition.LEFT_HAND))
                {
                    Remove(ItemPosition.LEFT_HAND, ItemRemoveMethod.REMOVE_TO_INVENTORY);
                }
                break;

            case ItemPosition.ACCESSORY_R:
            {
                if ((itemSort != ItemSort.ITEMSORT_ACCESSORY) ||
                    item.Type / 10000 == 38)
                {
                    item.Position = 0;
                    return(false);
                }

                switch (item.Type / 10000)
                {
                case 38:
                    item.Position = 0;
                    return(false);
                }

                if (Items.ContainsKey(ItemPosition.ACCESSORY_R))
                {
                    Remove(ItemPosition.ACCESSORY_R);
                }
                break;
            }

            case ItemPosition.ACCESSORY_L:
            {
                if (itemSort != ItemSort.ITEMSORT_ACCESSORY || item.Type / 10000 == 37)
                {
                    item.Position = 0;
                    return(false);
                }

                switch (item.Type / 10000)
                {
                case 37:
                    item.Position = 0;
                    return(false);
                }

                if (Items.ContainsKey(ItemPosition.ACCESSORY_L))
                {
                    Remove(ItemPosition.ACCESSORY_L);
                }
                break;
            }

            default:
                if (pos == item.Position &&
                    Items.ContainsKey(item.Position))
                {
                    Remove(item.Position);
                }
                else if (pos != item.Position)
                {
                    if (item.Position < ItemPosition.ALT_HEAD && pos != item.Position)
                    {
                        item.Position = 0;
                        return(false);
                    }
                    if (item.Position >= ItemPosition.ALT_HEAD && item.Position <= ItemPosition.ALT_STEED)
                    {
                        switch (item.Position)
                        {
                        case ItemPosition.ALT_HEAD:
                        {
                            if (pos != ItemPosition.HEADWEAR)
                            {
                                return(false);
                            }
                            break;
                        }

                        case ItemPosition.ALT_NECKLACE:
                        {
                            if (pos != ItemPosition.NECKLACE)
                            {
                                return(false);
                            }
                            break;
                        }

                        case ItemPosition.ALT_RING:
                        {
                            if (pos != ItemPosition.RING)
                            {
                                return(false);
                            }
                            break;
                        }

                        case ItemPosition.ALT_WEAPON_R:
                        {
                            if (pos != ItemPosition.RIGHT_HAND)
                            {
                                return(false);
                            }
                            break;
                        }

                        case ItemPosition.ALT_WEAPON_L:
                        {
                            if (pos != ItemPosition.LEFT_HAND && pos != ItemPosition.RIGHT_HAND)
                            {
                                return(false);
                            }
                            break;
                        }

                        case ItemPosition.ALT_ARMOR:
                        {
                            if (pos != ItemPosition.ARMOR)
                            {
                                return(false);
                            }
                            break;
                        }

                        case ItemPosition.ALT_BOOTS:
                        {
                            if (pos != ItemPosition.BOOTS)
                            {
                                return(false);
                            }
                            break;
                        }

                        case ItemPosition.ALT_BOTTLE:
                        {
                            if (pos != ItemPosition.BOTTLE)
                            {
                                return(false);
                            }
                            break;
                        }

                        case ItemPosition.ALT_GARMENT:
                        {
                            if (pos != ItemPosition.GARMENT)
                            {
                                return(false);
                            }
                            break;
                        }

                        default:
                            item.Position = 0;
                            return(false);
                        }

                        if (Items.ContainsKey(item.Position) && Items.Count >= 40)
                        {
                            item.Position = 0;
                            return(false);
                        }
                        if (Items.ContainsKey(item.Position))
                        {
                            Remove(item.Position);
                        }
                    }
                    else
                    {
                        item.Position = 0;
                        return(false);
                    }
                }
                break;
            }

            var itemEquip = new MsgItem
            {
                Identity = item.Identity,
                Action   = ItemAction.EQUIP,
                Param1   = (uint)item.Position
            };

            // We build the item information packet
            MsgItemInformation itemInfo = item.InformationPacket(!isLogin);

            // If we are logging in, we set this as default, because the item hasnt been
            // created yet, otherwise, we send this as an update.
            if (isLogin)
            {
                itemInfo.ItemMode = ItemMode.DEFAULT;
                m_pOwner.Send(itemInfo);
            }
            else
            {
                //itemInfo.ItemMode = ItemMode.Update;
                if (!m_pOwner.Inventory.Contains(item.Identity))
                {
                    return(false);
                }
                Item trash;
                m_pOwner.Inventory.Items.TryRemove(item.Identity, out trash);
                item.Save();
                m_pOwner.RecalculateAttributes();
            }

            m_pOwner.Send(itemEquip);
            Items.TryAdd(item.Position, item);
            SendEquipedItems();
            item.SendPurification();
            item.TryUnlockItem();
            item.SendItemLockTime();

            switch (item.Position)
            {
            case ItemPosition.HEADWEAR:
                m_pOwner.Helmet      = item.Type;
                m_pOwner.HelmetColor = (ushort)item.Color;
                break;

            case ItemPosition.ARMOR:
                m_pOwner.Armor      = item.Type;
                m_pOwner.ArmorColor = (ushort)item.Color;
                break;

            case ItemPosition.LEFT_HAND:
                m_pOwner.LeftHand    = item.Type;
                m_pOwner.ShieldColor = (ushort)item.Color;
                break;

            case ItemPosition.RIGHT_HAND:
                m_pOwner.RightHand = item.Type;
                break;

            case ItemPosition.GARMENT:
                m_pOwner.Garment = item.Type;
                break;

            case ItemPosition.ACCESSORY_R:
                m_pOwner.RightAccessory = item.Type;
                break;

            case ItemPosition.ACCESSORY_L:
                m_pOwner.LeftAccessory = item.Type;
                break;

            case ItemPosition.STEED:
                m_pOwner.MountType  = item.Type;
                m_pOwner.MountColor = item.SocketProgress;
                m_pOwner.MountPlus  = item.Plus;
                break;

            case ItemPosition.STEED_ARMOR:
                m_pOwner.MountArmor = item.Type;
                break;
            }

            return(true);
        }
コード例 #48
0
 public void CanImplicitConvertToDateTime(UnixTimestamp sut)
 {
     var expected = UnixTimestamp.Epoch.AddSeconds(sut.SecondsSinceEpoch);
     Assert.Equal(expected, sut);
 }
コード例 #49
0
ファイル: ChatEvent.cs プロジェクト: pedruhb/RavenServer
        public void Parse(GameClient Session, ClientPacket Packet)
        {
            if (Session == null || Session.GetHabbo() == null || !Session.GetHabbo().InRoom)
            {
                return;
            }

            Room Room = Session.GetHabbo().CurrentRoom;

            if (Room == null)
            {
                return;
            }

            RoomUser User = Room.GetRoomUserManager().GetRoomUserByHabbo(Session.GetHabbo().Id);

            if (User == null)
            {
                return;
            }
            if (Session.GetHabbo().Rank > 3 && !Session.GetHabbo().StaffOk)
            {
                return;
            }

            string Message = StringCharFilter.Escape(Packet.PopString());

            if (Message.Length > 100)
            {
                Message = Message.Substring(0, 100);
            }

            int Colour = Packet.PopInt();

            if (Message.Contains("&#1º;") || Message.Contains("&#1º") || Message.Contains("&#"))
            {
                Session.SendMessage(new MassEventComposer("habbopages/spammer.txt")); return;
            }

            ChatStyle Style = null;

            if (!RavenEnvironment.GetGame().GetChatManager().GetChatStyles().TryGetStyle(Colour, out Style) || (Style.RequiredRight.Length > 0 && !Session.GetHabbo().GetPermissions().HasRight(Style.RequiredRight)))
            {
                Colour = 0;
            }

            User.UnIdle();

            if (RavenEnvironment.GetUnixTimestamp() < Session.GetHabbo().FloodTime&& Session.GetHabbo().FloodTime != 0)
            {
                return;
            }

            if (Session.GetHabbo().TimeMuted > 0)
            {
                Session.SendMessage(new MutedComposer(Session.GetHabbo().TimeMuted));
                return;
            }

            if (!Room.CheckRights(Session, false) && Room.muteSignalEnabled == true)
            {
                Session.SendWhisper("La sala está silenciada, no puedes hablar en ella hasta tanto el dueño o alguien con permisos en ella lo permita.");
                return;
            }

            if (!Session.GetHabbo().GetPermissions().HasRight("room_ignore_mute") && Room.CheckMute(Session))
            {
                Session.SendWhisper("Oops, usted se encuentra silenciad@");
                return;
            }

            User.LastBubble = Session.GetHabbo().CustomBubbleId == 0 ? Colour : Session.GetHabbo().CustomBubbleId;

            if (Room.GetWired().TriggerEvent(HabboHotel.Items.Wired.WiredBoxType.TriggerUserSays, Session.GetHabbo(), Message.ToLower()))
            {
                return;
            }
            else if (!Session.GetHabbo().GetPermissions().HasRight("mod_tool"))
            {
                int MuteTime;
                if (User.IncrementAndCheckFlood(out MuteTime))
                {
                    Session.SendMessage(new FloodControlComposer(MuteTime));
                    return;
                }
            }

            Room.GetFilter().CheckMessage(Message);

            if (Message.StartsWith(":", StringComparison.CurrentCulture) && RavenEnvironment.GetGame().GetChatManager().GetCommands().Parse(Session, Message))
            {
                return;
            }

            if (Session.GetHabbo().LastMessage == Message)
            {
                Session.GetHabbo().LastMessageCount++;
                if (Session.GetHabbo().LastMessageCount > 3)
                {
                    RavenEnvironment.GetGame().GetClientManager().RepeatAlert(new RoomInviteComposer(int.MinValue, "Repeat: " + Session.GetHabbo().Username + " / Frase: " + Message + " / Veces: " + Session.GetHabbo().LastMessageCount + "."));
                    Session.GetHabbo().LastMessageCount = 0;
                }
            }

            RavenEnvironment.GetGame().GetChatManager().GetLogs().StoreChatlog(new ChatlogEntry(Session.GetHabbo().Id, Room.Id, Message, UnixTimestamp.GetNow(), Session.GetHabbo(), Room));
            string word;

            if (!Session.GetHabbo().GetPermissions().HasRight("word_filter_override") &&
                RavenEnvironment.GetGame().GetChatManager().GetFilter().IsUnnaceptableWord(Message, out word))
            {
                Session.GetHabbo().BannedPhraseCount++;

                if (Session.GetHabbo().BannedPhraseCount >= 1)
                {
                    Session.SendWhisper("¡Has mencionado una palabra no apta para el hotel! Aviso " + Session.GetHabbo().BannedPhraseCount + "/10");

                    DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
                    dtDateTime = dtDateTime.AddSeconds(RavenEnvironment.GetUnixTimestamp()).ToLocalTime();

                    RavenEnvironment.GetGame().GetClientManager().StaffAlert1(new RoomInviteComposer(int.MinValue, "Spammer: " + Session.GetHabbo().Username + " / Frase: " + Message + " / Palabra: " + word.ToUpper() + " / Fase: " + Session.GetHabbo().BannedPhraseCount + " / 10."));
                    RavenEnvironment.GetGame().GetClientManager().StaffAlert2(new RoomNotificationComposer("Alerta de publicista:",
                                                                                                           "<b><font color=\"#B40404\">Por favor, recuerda investigar bien antes de recurrir a una sanción.</font></b><br><br>Palabra: <b>" + word.ToUpper() + "</b>.<br><br><b>Frase:</b><br><i>" + Message +
                                                                                                           "</i>.<br><br><b>Tipo:</b><br>Chat de sala.\r\n" + "<b>Usuario: " + Session.GetHabbo().Username + "</b><br><b>Secuencia:</b> " + Session.GetHabbo().BannedPhraseCount + "/10.", "foto", "Investigar", "event:navigator/goto/" +
                                                                                                           Session.GetHabbo().CurrentRoomId));

                    if (Session.GetHabbo().BannedPhraseCount >= 10)
                    {
                        RavenEnvironment.GetGame().GetClientManager().StaffAlert(RoomNotificationComposer.SendBubble("commandsupdated", "El usuario " + Session.GetHabbo().Username + " ha sido baneado de manera automática por el sistema.", ""));

                        RavenEnvironment.GetGame().GetModerationManager().BanUser("System", HabboHotel.Moderation.ModerationBanType.USERNAME, Session.GetHabbo().Username, "Baneado por hacer Spam con la Frase (" + word + ")", (RavenEnvironment.GetUnixTimestamp() + 78892200));
                        Session.Disconnect();
                        return;
                    }
                    return;
                }

                Session.SendMessage(new ChatComposer(User.VirtualId, "Mensaje inapropiado.", 0, Colour));
                return;
            }

            if (Session.GetHabbo().MultiWhisper)
            {
                Session.SendMessage(new WhisperComposer(User.VirtualId, "@blue@ [MULTI] " + Message, 0, User.LastBubble));
                List <RoomUser> MultiW = Session.GetHabbo().MultiWhispers;
                if (MultiW.Count > 0)
                {
                    foreach (RoomUser user in MultiW)
                    {
                        if (user != null)
                        {
                            if (user.GetClient() != null && user.GetClient().GetHabbo() != null && !user.GetClient().GetHabbo().IgnorePublicWhispers)
                            {
                                user.GetClient().SendMessage(new WhisperComposer(User.VirtualId, "@blue@ [MULTI] " + Message, 0, User.LastBubble));
                            }
                        }
                    }
                }
                return;
            }

            //if (Session.GetHabbo().IsBeingAsked == true && Message.ToLower().Contains("s"))
            //{
            //    Session.GetHabbo().SecureTradeEnabled = true;
            //    Session.GetHabbo().IsBeingAsked = false;
            //    Session.SendMessage(new WiredSmartAlertComposer("Acabas de activar el modo seguro de tradeo para dados."));
            //}
            //else if (Session.GetHabbo().IsBeingAsked == true && !Message.ToLower().Contains("s"))
            //{
            //    Session.GetHabbo().SecureTradeEnabled = false;
            //    Session.GetHabbo().IsBeingAsked = false;
            //    Session.SendMessage(new WiredSmartAlertComposer("Has dejado el tradeo en modo normal."));
            //}

            Session.GetHabbo().LastMessage = Message;

            RavenEnvironment.GetGame().GetQuestManager().ProgressUserQuest(Session, QuestType.SOCIAL_CHAT);
            User.OnChat(User.LastBubble, Message, false);
        }
コード例 #50
0
 public void DifferentUnixTimestampReturnsExpectedInequality(
     UnixTimestamp timestamp1,
     UnixTimestamp timestamp2)
 {
     Assert.True(timestamp1 != timestamp2);
 }
コード例 #51
0
        public bool isActive()
        {
            double Now = UnixTimestamp.GetNow();

            return(Now >= RewardStart && Now <= RewardEnd);
        }