public static LogicDeliverable GetLogicDeliverable(LogicJSONObject jsonObject)
        {
            LogicDeliverable deliverable = LogicDeliverableFactory.CreateByType(LogicStringUtil.ConvertToInt(LogicJSONHelper.GetString(jsonObject, "type")));

            deliverable.ReadFromJSON(jsonObject);
            return(deliverable);
        }
        private static void LoadFingerprint()
        {
            ResourceManager.FINGERPRINT_JSON = ResourceManager.LoadAssetString("fingerprint.json");

            if (ResourceManager.FINGERPRINT_JSON != null)
            {
                LogicJSONObject jsonObject = (LogicJSONObject)LogicJSONParser.Parse(ResourceManager.FINGERPRINT_JSON);

                ResourceManager.FINGERPRINT_SHA     = LogicJSONHelper.GetString(jsonObject, "sha");
                ResourceManager.FINGERPRINT_VERSION = LogicJSONHelper.GetString(jsonObject, "version");

                string[] version = ResourceManager.FINGERPRINT_VERSION.Split('.');

                if (version.Length == 3)
                {
                    ResourceManager.m_version = new int[3];

                    for (int i = 0; i < 3; i++)
                    {
                        ResourceManager.m_version[i] = int.Parse(version[i]);
                    }
                }
                else
                {
                    Logging.Error("ResourceManager.loadFingerprint: invalid fingerprint version: " + ResourceManager.FINGERPRINT_VERSION);
                }

                ZLibHelper.CompressInZLibFormat(LogicStringUtil.GetBytes(ResourceManager.FINGERPRINT_JSON), out ResourceManager.COMPRESSED_FINGERPRINT_DATA);
            }
            else
            {
                Logging.Error("ResourceManager.loadFingerprint: fingerprint.json not exist");
            }
        }
        public override void WriteString(string value)
        {
            base.WriteString(value);

            if (value == null)
            {
                this.WriteIntToByteArray(-1);
            }
            else
            {
                byte[] bytes  = LogicStringUtil.GetBytes(value);
                int    length = bytes.Length;

                if (length <= 900000)
                {
                    this.EnsureCapacity(length + 4);
                    this.WriteIntToByteArray(length);

                    Buffer.BlockCopy(bytes, 0, this.m_buffer, this.m_offset, length);

                    this.m_offset += length;
                }
                else
                {
                    Debugger.Warning("ByteStream::writeString invalid string length " + length);
                    this.WriteIntToByteArray(-1);
                }
            }
        }
Пример #4
0
        private void SaveState()
        {
            if (this.m_logicGameMode.GetState() == 1)
            {
                LogicJSONObject jsonObject = new LogicJSONObject(64);

                this.m_logicGameMode.SaveToJSON(jsonObject);

                ZLibHelper.CompressInZLibFormat(LogicStringUtil.GetBytes(LogicJSONParser.CreateJSONString(jsonObject, 1536)), out byte[] homeJSON);
                ServerMessageManager.SendMessage(new GameStateCallbackMessage
                {
                    AccountId              = this.m_logicGameMode.GetLevel().GetPlayerAvatar().GetId(),
                    SessionId              = this.m_session.Id,
                    LogicClientAvatar      = this.m_logicGameMode.GetLevel().GetPlayerAvatar(),
                    AvatarChanges          = this.m_avatarChangeListener.RemoveAvatarChanges(),
                    ExecutedServerCommands = new LogicArrayList <LogicServerCommand>(),
                    HomeJSON              = homeJSON,
                    RemainingShieldTime   = this.m_logicGameMode.GetShieldRemainingSeconds(),
                    RemainingGuardTime    = this.m_logicGameMode.GetGuardRemainingSeconds(),
                    NextPersonalBreakTime = this.m_logicGameMode.GetPersonalBreakCooldownSeconds(),
                    SaveTime              = TimeUtil.GetTimestamp()
                }, 9);
            }
            else
            {
                ServerMessageManager.SendMessage(new GameStateCallbackMessage
                {
                    AccountId         = this.m_logicGameMode.GetLevel().GetPlayerAvatar().GetId(),
                    SessionId         = this.m_session.Id,
                    LogicClientAvatar = this.m_logicGameMode.GetLevel().GetPlayerAvatar(),
                    AvatarChanges     = this.m_avatarChangeListener.RemoveAvatarChanges()
                }, 9);
            }
        }
        public LogicData GetDataParameter(int idx, LogicDataType tableIdx)
        {
            if (this.IsValidParameter(idx))
            {
                int value = LogicStringUtil.ConvertToInt(this.m_parameters[idx]);

                if (value != 0)
                {
                    LogicData data = LogicDataTables.GetDataById(value, tableIdx);

                    if (data != null)
                    {
                        return(data);
                    }

                    this.m_errorHandler.WarningFunction(this.m_calendarEvent, this, this.m_functionData.GetParameterName(idx),
                                                        string.Format("Unable to find data by id {0} from tableId {1}.", value, tableIdx));
                }
                else
                {
                    this.m_errorHandler.WarningFunction(this.m_calendarEvent, this, this.m_functionData.GetParameterName(idx),
                                                        string.Format("Expected globalId got {0}.", value));
                }
            }

            return(null);
        }
Пример #6
0
        /// <summary>
        ///     Loads the fingerprint file.
        /// </summary>
        private static void LoadFingeprint()
        {
            ResourceManager.FingerprintJson = ResourceManager.LoadAssetFile("fingerprint.json");

            if (ResourceManager.FingerprintJson != null)
            {
                LogicJSONObject jsonObject = (LogicJSONObject)LogicJSONParser.Parse(ResourceManager.FingerprintJson);

                ResourceManager.FingerprintSha     = LogicJSONHelper.GetJSONString(jsonObject, "sha");
                ResourceManager.FingerprintVersion = LogicJSONHelper.GetJSONString(jsonObject, "version");

                string[] version = ResourceManager.FingerprintVersion.Split('.');

                if (version.Length == 3)
                {
                    ResourceManager._version = new int[3];

                    for (int i = 0; i < 3; i++)
                    {
                        ResourceManager._version[i] = int.Parse(version[i]);
                    }
                }
                else
                {
                    Debugger.Error("ResourceManager::loadFingeprint invalid fingerprint version: " + ResourceManager.FingerprintVersion);
                }

                ZLibHelper.CompressInZLibFormat(LogicStringUtil.GetBytes(ResourceManager.FingerprintJson), out ResourceManager.CompressedFingeprintJson);
            }
            else
            {
                Debugger.Error("ResourceManager::loadFingeprint fingerprint.json not exist");
            }
        }
Пример #7
0
 private static void OnCreateReplayStreamRequestMessageReceived(CreateReplayStreamRequestMessage message)
 {
     ZLibHelper.CompressInZLibFormat(LogicStringUtil.GetBytes(message.JSON), out byte[] entry);
     StreamManager.Create(entry, out LogicLong id);
     ServerRequestManager.SendResponse(new CreateReplayStreamResponseMessage
     {
         Success = true,
         Id      = id
     }, message);
 }
        public static GameMode LoadMatchedAttackState(HomeSession session, GameMatchedAttackState state)
        {
            LogicClientHome   home                      = state.Home;
            LogicClientAvatar homeOwnerAvatar           = state.HomeOwnerAvatar;
            LogicClientAvatar attackerLogicClientAvatar = state.PlayerAvatar;

            int currentTimestamp            = TimeUtil.GetTimestamp();
            int secondsSinceLastSave        = state.SaveTime != -1 ? currentTimestamp - state.SaveTime : 0;
            int secondsSinceLastMaintenance = state.MaintenanceTime != -1 ? currentTimestamp - state.MaintenanceTime : 0;

            EnemyHomeDataMessage enemyHomeDataMessage = new EnemyHomeDataMessage();

            enemyHomeDataMessage.SetCurrentTimestamp(currentTimestamp);
            enemyHomeDataMessage.SetSecondsSinceLastSave(secondsSinceLastSave);
            enemyHomeDataMessage.SetSecondsSinceLastMaintenance(secondsSinceLastMaintenance);
            enemyHomeDataMessage.SetLogicClientHome(home);
            enemyHomeDataMessage.SetLogicClientAvatar(homeOwnerAvatar);
            enemyHomeDataMessage.SetAttackerLogicClientAvatar(attackerLogicClientAvatar);
            enemyHomeDataMessage.SetAttackSource(3);
            enemyHomeDataMessage.Encode();

            CompressibleStringHelper.Uncompress(home.GetCompressibleHomeJSON());
            CompressibleStringHelper.Uncompress(home.GetCompressibleCalendarJSON());
            CompressibleStringHelper.Uncompress(home.GetCompressibleGlobalJSON());

            try
            {
                GameMode gameMode = new GameMode(session);

                gameMode.m_avatarChangeListener = new AvatarChangeListener(gameMode, attackerLogicClientAvatar);
                attackerLogicClientAvatar.SetChangeListener(gameMode.m_avatarChangeListener);

                gameMode.m_logicGameMode.LoadMatchedAttackState(home, homeOwnerAvatar, attackerLogicClientAvatar, currentTimestamp, secondsSinceLastSave, secondsSinceLastMaintenance);
                gameMode.m_gameDefenderLocked = state.GameDefenderLocked;
                gameMode.m_liveReplayId       = state.LiveReplayId;

                ZLibHelper.CompressInZLibFormat(LogicStringUtil.GetBytes(LogicJSONParser.CreateJSONString(gameMode.m_logicGameMode.GetReplay().GetJson())), out byte[] streamJSON);
                ServerMessageManager.SendMessage(new InitializeLiveReplayMessage
                {
                    AccountId  = gameMode.m_liveReplayId,
                    StreamData = streamJSON
                }, 9);

                session.SendPiranhaMessage(enemyHomeDataMessage, 1);

                return(gameMode);
            }
            catch (Exception exception)
            {
                Logging.Error("GameMode.loadMatchedAttackState: exception while the loading of attack state: " + exception);
            }

            return(null);
        }
        public static LogicData GetLogicData(LogicJSONObject jsonObject, string key)
        {
            LogicData data = LogicDataTables.GetDataById(LogicStringUtil.ConvertToInt(LogicJSONHelper.GetString(jsonObject, key, string.Empty, true)));

            if (data == null)
            {
                Debugger.Error("Unable to load data. key:" + key);
            }

            return(data);
        }
Пример #10
0
        /// <summary>
        /// Initializes the <see cref="Alliances"/> class.
        /// </summary>
        internal static void Init()
        {
            if (Alliances.Initialized)
            {
                return;
            }

            Alliances.Pool = new ConcurrentDictionary <long, Alliance>();

            switch (Settings.Database)
            {
            case DBMS.Mongo:
            {
                foreach (AllianceDb dbEntry in Mongo.Alliances.Find(db => true).ToList())
                {
                    if (dbEntry != null)
                    {
                        Alliance alliance = new Alliance(dbEntry.HighID, dbEntry.LowID);

                        JsonConvert.PopulateObject(dbEntry.Profile.ToJson(), alliance, AllianceDb.JsonSettings);

                        Alliances.Add(alliance);
                    }
                }

                Alliances.Seed = Mongo.AllianceSeed;

                break;
            }

            case DBMS.File:
            {
                DirectoryInfo directory = new DirectoryInfo($"{System.IO.Directory.GetCurrentDirectory()}/Saves/Alliances/");

                directory.CreateIfNotExists();
                directory.DeleteIfExists(".json");

                Parallel.ForEach(directory.GetFiles("*.json"), file =>
                    {
                        string[] id = Path.GetFileNameWithoutExtension(file.Name).Split('-');
                        Alliances.Add(Alliances.Get(LogicStringUtil.ConvertToInt(id[0]), LogicStringUtil.ConvertToInt(id[1])));
                    });

                Alliances.Seed = directory.GetFiles("*.json").Length;
                break;
            }
            }

            Console.WriteLine($"Loaded {Avatars.Count} {((Avatars.Count != 1) ? "avatars" : "avatar")} and {Alliances.Count} {((Alliances.Count != 1) ? "alliances" : "alliance")} into memory." + Environment.NewLine);

            Alliances.Initialized = true;
        }
        /// <summary>
        ///     Uncompresses the <see cref="LogicCompressibleString" /> instance.
        /// </summary>
        public static void Uncompress(LogicCompressibleString str)
        {
            if (str.IsCompressed())
            {
                int    compressedLength   = str.GetCompressedLength();
                byte[] compressedData     = str.RemoveCompressed();
                int    uncompressedLength = ZLibHelper.DecompressInMySQLFormat(compressedData, compressedLength, out byte[] uncompressedData);

                if (uncompressedLength > 0)
                {
                    str.Set(LogicStringUtil.CreateString(uncompressedData, 0, uncompressedLength));
                }
            }
        }
Пример #12
0
        /// <summary>
        /// Initializes the <see cref="Avatars"/> class.
        /// </summary>
        internal static void Init()
        {
            if (Avatars.Initialized)
            {
                return;
            }

            Avatars.Pool = new ConcurrentDictionary <long, LogicClientAvatar>();

            switch (Settings.Database)
            {
            case DBMS.Mongo:
            {
                foreach (AvatarDb dbEntry in Mongo.Avatars.Find(db => true).ToList())
                {
                    if (dbEntry != null)
                    {
                        LogicClientAvatar avatar = new LogicClientAvatar(null, new LogicLong(dbEntry.HighID, dbEntry.LowID));

                        JsonConvert.PopulateObject(dbEntry.Profile.ToJson(), avatar, AvatarDb.JsonSettings);

                        Avatars.Add(avatar);
                    }
                }

                Avatars.Seed = Mongo.AvatarSeed;

                break;
            }

            case DBMS.File:
            {
                DirectoryInfo directory = new DirectoryInfo($"{System.IO.Directory.GetCurrentDirectory()}/Saves/Players/");

                directory.CreateIfNotExists();
                directory.DeleteIfExists(".json");

                Parallel.ForEach(directory.GetFiles("*.json"), file =>
                    {
                        string[] id = Path.GetFileNameWithoutExtension(file.Name).Split('-');
                        Avatars.Add(Avatars.Get(new LogicLong(LogicStringUtil.ConvertToInt(id[0]), LogicStringUtil.ConvertToInt(id[1]))));
                    });

                Avatars.Seed = directory.GetFiles("*.json").Length;
                break;
            }
            }

            Avatars.Initialized = true;
        }
Пример #13
0
        private static int ConvertStringToTimestamp(string time, bool round)
        {
            int spliter = time.IndexOf("T");

            Debugger.DoAssert(spliter == 8, "Unable to convert time. ISO8601 expected.");
            LogicGregDate date = new LogicGregDate(LogicStringUtil.ConvertToInt(time, 0, 4),
                                                   LogicStringUtil.ConvertToInt(time, 4, 6),
                                                   LogicStringUtil.ConvertToInt(time, 6, 8));

            date.Validate();

            int    totalSecs = date.GetIndex() * 86400;
            string dayTime   = time.Substring(spliter + 1);

            if (dayTime.Length < 2)
            {
                if (round)
                {
                    return(totalSecs + 82800);
                }

                return(totalSecs);
            }

            totalSecs += 3600 * LogicStringUtil.ConvertToInt(dayTime, 0, 2);

            if (dayTime.Length < 4)
            {
                if (round)
                {
                    return(totalSecs + 3540);
                }

                return(totalSecs);
            }

            totalSecs += 60 * LogicStringUtil.ConvertToInt(dayTime, 2, 4);

            if (dayTime.Length < 6)
            {
                if (round)
                {
                    return(totalSecs + 59);
                }

                return(totalSecs);
            }

            return(totalSecs + LogicStringUtil.ConvertToInt(dayTime, 4, 6));
        }
Пример #14
0
        /// <summary>
        ///     Saves the account info to json.
        /// </summary>
        internal void SaveAccount(ServerType serverType, string passToken, int accHighId, int accLowId)
        {
            LogicJSONObject jsonRoot = new LogicJSONObject();

            jsonRoot.Put("High", new LogicJSONNumber(accHighId));
            jsonRoot.Put("Low", new LogicJSONNumber(accLowId));
            jsonRoot.Put("Pass", new LogicJSONString(passToken));

            byte[] fileContent = LogicStringUtil.GetBytes(LogicJSONParser.CreateJSONString(jsonRoot));

            using (FileStream stream = new FileStream("Files/save.json", FileMode.OpenOrCreate))
            {
                stream.Write(fileContent, 0, fileContent.Length);
            }
        }
        /// <summary>
        ///     Compresses the <see cref="LogicCompressibleString" /> instance.
        /// </summary>
        public static void Compress(LogicCompressibleString str)
        {
            string strInstance = str.Get();

            if (strInstance != null)
            {
                byte[] uncompressedData = LogicStringUtil.GetBytes(strInstance);
                int    compressedLength = ZLibHelper.CompressInZLibFormat(uncompressedData, out byte[] compressedData);

                if (compressedLength > 0)
                {
                    str.Set(compressedData, compressedLength);
                }
            }
        }
Пример #16
0
        public static LogicClientAvatar LoadHomeOwnerAvatarFromHome(LogicClientHome home)
        {
            string json = home.GetCompressibleHomeJSON().Get();

            if (json == null)
            {
                ZLibHelper.DecompressInMySQLFormat(home.GetCompressibleHomeJSON().GetCompressed(), out byte[] output);
                json = LogicStringUtil.CreateString(output, 0, output.Length);
            }

            LogicClientAvatar logicClientAvatar = new LogicClientAvatar();

            logicClientAvatar.LoadForReplay(LogicJSONParser.ParseObject(json), true);
            return(logicClientAvatar);
        }
Пример #17
0
        private void OnLoginFailedMessageReceived(LoginFailedMessage message)
        {
            this.m_serverConnection.SetState(ServerConnectionState.LOGIN_FAILED);

            switch (message.GetErrorCode())
            {
            case LoginFailedMessage.ErrorCode.DATA_VERSION:
                ZLibHelper.DecompressInMySQLFormat(message.GetCompressedFingerprint(), out byte[] output);
                ResourceManager.DownloadDataUpdate(LogicStringUtil.CreateString(output, 0, output.Length), message.GetContentUrl());
                break;

            default:
                Debugger.Warning("MessageManager.onLoginFailedMessageReceived: error code: " + message.GetErrorCode());
                break;
            }
        }
Пример #18
0
        public byte[] CreateChallengeSnapshot()
        {
            if (this.m_logicGameMode.GetState() != 1)
            {
                throw new Exception("GameMode.createChallengeSnapshot called in invalid logic state.");
            }

            LogicLevel      logicLevel = this.m_logicGameMode.GetLevel();
            LogicJSONObject jsonObject = new LogicJSONObject(64);

            jsonObject.Put("exp_ver", new LogicJSONNumber(logicLevel.GetExperienceVersion()));
            logicLevel.GetGameObjectManagerAt(0).SaveToSnapshot(jsonObject, 6);

            this.m_logicGameMode.GetLevel().GetHomeOwnerAvatar().SaveToDirect(jsonObject);

            ZLibHelper.CompressInZLibFormat(LogicStringUtil.GetBytes(LogicJSONParser.CreateJSONString(jsonObject, 1536)), out byte[] homeJSON);

            return(homeJSON);
        }
        public int GetIntParameter(int idx)
        {
            if (this.IsValidParameter(idx))
            {
                int value    = LogicStringUtil.ConvertToInt(this.m_parameters[idx]);
                int minValue = this.m_functionData.GetMinValue(idx);
                int maxValue = this.m_functionData.GetMaxValue(idx);

                if (value < minValue || value > maxValue)
                {
                    this.m_errorHandler.WarningFunction(this.m_calendarEvent, this, this.m_functionData.GetParameterName(idx),
                                                        string.Format("Value {0} is not between {1} and {2}.", value, minValue, maxValue));
                    return(minValue);
                }

                return(value);
            }

            return(0);
        }
Пример #20
0
        /// <summary>
        /// Writes the string.
        /// </summary>
        public void WriteString(string value)
        {
            if (value != null)
            {
                int length = value.Length;

                if (length > 0)
                {
                    this.WriteInt(length);
                    this.Write(LogicStringUtil.GetBytes(value), length);
                }
                else
                {
                    this.WriteInt(0);
                }
            }
            else
            {
                this.WriteInt(-1);
            }
        }
        private static void LoadResources()
        {
            ZLibHelper.CompressInZLibFormat(LogicStringUtil.GetBytes(ServerHttpClient.DownloadString("/data/calendar.json")), out ResourceManager.SERVER_SAVE_FILE_CALENDAR);
            ZLibHelper.CompressInZLibFormat(LogicStringUtil.GetBytes(ResourceManager.LoadAssetString("globals.json")), out ResourceManager.SERVER_SAVE_FILE_GLOBAL);

            LogicDataTables.Init();
            LogicArrayList <LogicDataTableResource> resources = LogicResources.CreateDataTableResourcesArray();

            for (int i = 0; i < resources.Size(); i++)
            {
                string fileName = resources[i].GetFileName();
                string content  = ResourceManager.LoadAssetString(fileName);

                if (content != null)
                {
                    LogicResources.Load(resources, i, new CSVNode(content.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None), fileName));
                }
                else
                {
                    Logging.Error(string.Format("ResourceManager.loadResources: file {0} not exist.", fileName));
                }
            }
        }
Пример #22
0
        /// <summary>
        /// Handles the request.
        /// </summary>
        private static void EndProcess(this HttpListenerContext context)
        {
            LogicLong player   = LogicTagUtil.ToLogicLong(context.Request.QueryString["player"]);
            int       debugCmd = LogicStringUtil.ConvertToInt(context.Request.QueryString["command"]);

            Connection connection = Avatars.Get(player).Connection;

            if (connection != null)
            {
                if (connection.IsConnected && LogicVersion.IsIntegration)
                {
                    new AvailableServerCommandMessage(connection, new LogicDebugCommand(connection, debugCmd)).Send();
                    context.Response.Close(LogicStringUtil.GetBytes("OK"), true);
                }
                else
                {
                    context.Response.Close(LogicStringUtil.GetBytes("Error: Connection.IsConnected == false or the server is not in integration mode"), true);
                }
            }
            else
            {
                context.Response.Close(LogicStringUtil.GetBytes("Error: Connection == null"), true);
            }
        }
        internal override void Execute()
        {
            if (this.Connection.Avatar.ExpLevel >= this.Item.RequiredXp)
            {
                string[] cost = this.Item.Cost[this.Connection.Avatar.ItemLevels.GetCount(this.Item.GlobalID)].Split(',');

                if (cost.Length >= 7)
                {
                    int diamonds = LogicStringUtil.ConvertToInt(cost[0]);
                    int gold     = LogicStringUtil.ConvertToInt(cost[1]);
                    int energy   = LogicStringUtil.ConvertToInt(cost[2]);
                    int orb1     = LogicStringUtil.ConvertToInt(cost[3]);
                    int orb2     = LogicStringUtil.ConvertToInt(cost[4]);
                    int orb3     = LogicStringUtil.ConvertToInt(cost[5]);
                    int orb4     = LogicStringUtil.ConvertToInt(cost[6]);

                    if (diamonds != 0)
                    {
                        if (this.Connection.Avatar.Diamonds < diamonds)
                        {
                            Debugger.Error($"Unable to upgrade the item. {this.Connection.Avatar.Name} ({this.Connection.Avatar}) does not have enough diamonds. (Diamonds : {this.Connection.Avatar.Diamonds}, Require : {diamonds})");
                            return;
                        }
                    }

                    if (gold != 0)
                    {
                        if (this.Connection.Avatar.Gold < gold)
                        {
                            Debugger.Error($"Unable to upgrade the item. {this.Connection.Avatar.Name} ({this.Connection.Avatar}) does not have enough gold. (Gold : {this.Connection.Avatar.Gold}, Require : {gold})");
                            return;
                        }
                    }

                    if (energy != 0)
                    {
                        if (this.Connection.Avatar.Energy < energy)
                        {
                            Debugger.Error($"Unable to upgrade the item. {this.Connection.Avatar.Name} ({this.Connection.Avatar}) does not have enough energy. (Energy : {this.Connection.Avatar.Energy}, Require : {energy}.");
                            return;
                        }
                    }

                    if (orb1 != 0)
                    {
                        if (this.Connection.Avatar.Orb1 < orb1)
                        {
                            Debugger.Error($"Unable to upgrade the item. {this.Connection.Avatar.Name} ({this.Connection.Avatar}) does not have enough of orb1. (Orb1 : {this.Connection.Avatar.Orb1}, Require : {orb1})");
                            return;
                        }
                    }

                    if (orb2 != 0)
                    {
                        if (this.Connection.Avatar.Orb2 < orb2)
                        {
                            Debugger.Error($"Unable to upgrade the item. {this.Connection.Avatar.Name} ({this.Connection.Avatar}) does not have enough of orb2. (Orb2 : {this.Connection.Avatar.Orb2}, Require : {orb2})");
                            return;
                        }
                    }

                    if (orb3 != 0)
                    {
                        if (this.Connection.Avatar.Orb3 < orb3)
                        {
                            Debugger.Error($"Unable to upgrade the item. {this.Connection.Avatar.Name} ({this.Connection.Avatar}) does not have enough of orb3. (Orb3 : {this.Connection.Avatar.Orb3}, Require : {orb3})");
                            return;
                        }
                    }

                    if (orb4 != 0)
                    {
                        if (this.Connection.Avatar.Orb4 < orb4)
                        {
                            Debugger.Error($"Unable to upgrade the item. {this.Connection.Avatar.Name} ({this.Connection.Avatar}) does not have enough of orb4. (Orb4 : {this.Connection.Avatar.Orb4}, Require : {orb4})");
                            return;
                        }
                    }

                    this.Connection.Avatar.Diamonds -= diamonds;
                    this.Connection.Avatar.Gold     -= gold;
                    this.Connection.Avatar.Energy   -= energy;
                    this.Connection.Avatar.Orb1     -= orb1;
                    this.Connection.Avatar.Orb2     -= orb2;
                    this.Connection.Avatar.Orb3     -= orb3;
                    this.Connection.Avatar.Orb4     -= orb4;
                }

                this.Connection.Avatar.ItemInventories.AddItem(this.Item.GlobalID, 0);
                this.Connection.Avatar.ItemLevels.AddItem(this.Item.GlobalID, 0);
            }

            this.Connection.Avatar.Save();
        }
        public static void DownloadDataUpdate(string fingerprintJSON, string contentUrl)
        {
            LogicJSONObject     oldFingerprintJSON = LogicJSONParser.ParseObject(ResourceManager.FINGERPRINT_JSON);
            LogicJSONObject     newFingerprintJSON = LogicJSONParser.ParseObject(fingerprintJSON);
            LogicJSONArray      oldfileArray       = oldFingerprintJSON.GetJSONArray("files");
            LogicJSONArray      newfileArray       = newFingerprintJSON.GetJSONArray("files");
            List <DownloadTask> results            = new List <DownloadTask>();

            string fingerprintSha = newFingerprintJSON.GetJSONString("sha").GetStringValue();

            for (int i = 0; i < newfileArray.Size(); i++)
            {
                LogicJSONObject newFileObject = newfileArray.GetJSONObject(i);
                string          newFileName   = newFileObject.GetJSONString("file").GetStringValue();
                string          newFileSha    = newFileObject.GetJSONString("sha").GetStringValue();
                bool            needUpdate    = true;

                for (int j = 0; j < oldfileArray.Size(); j++)
                {
                    LogicJSONObject oldFileObject = oldfileArray.GetJSONObject(j);
                    string          oldFileName   = oldFileObject.GetJSONString("file").GetStringValue();

                    if (oldFileName == newFileName)
                    {
                        string oldFileSha = oldFileObject.GetJSONString("sha").GetStringValue();

                        if (oldFileSha == newFileSha)
                        {
                            needUpdate = false;
                        }

                        break;
                    }
                }

                if (needUpdate)
                {
                    results.Add(new DownloadTask(contentUrl, fingerprintSha, newFileName));
                }
            }

            bool success = true;

            for (int i = 0; i < results.Count; i++)
            {
                DownloadTask task = results[i];
                byte[]       data = task.Result;

                if (data != null)
                {
                    File.WriteAllBytes("assets/" + task.FileName, data);
                }
                else
                {
                    Debugger.Warning("ResourceManager.downloadDataUpdate: download file failed: " + task.FileName);
                    success = false;
                }
            }

            if (success)
            {
                File.WriteAllBytes("assets/fingerprint.json", LogicStringUtil.GetBytes(fingerprintJSON));
                ResourceManager.Init();
            }
        }
Пример #25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RC4"/> class.
 /// </summary>
 internal RC4(string Key)
 {
     this.Key = RC4.KSA(LogicStringUtil.GetBytes(Key));
 }
        internal override void Process()
        {
            if (this.Connection.Avatar.Rank >= this.RequiredRank)
            {
                if (this.Parameters.Length >= 2)
                {
                    if (this.Parameters[0] == "set")
                    {
                        switch (this.Parameters[1])
                        {
                        case "gold":
                        {
                            this.Connection.Avatar.Gold = LogicStringUtil.ConvertToInt(this.Parameters[2]);
                            break;
                        }

                        case "diamonds":
                        {
                            this.Connection.Avatar.Diamonds = LogicStringUtil.ConvertToInt(this.Parameters[2]);
                            break;
                        }

                        case "xp":
                        {
                            this.Connection.Avatar.ExpPoints = LogicStringUtil.ConvertToInt(this.Parameters[2]);
                            break;
                        }

                        case "score":
                        {
                            this.Connection.Avatar.Score = LogicStringUtil.ConvertToInt(this.Parameters[2]);
                            break;
                        }

                        default:
                        {
                            this.Connection.SendChatMessage(this.Help.ToString());
                            break;
                        }
                        }
                    }
                    if (this.Parameters[0] == "add")
                    {
                        switch (this.Parameters[1])
                        {
                        case "gold":
                        {
                            this.Connection.Avatar.AddGold(LogicStringUtil.ConvertToInt(this.Parameters[2]));
                            break;
                        }

                        case "diamonds":
                        {
                            this.Connection.Avatar.AddDiamonds(LogicStringUtil.ConvertToInt(this.Parameters[2]));
                            break;
                        }

                        case "xp":
                        {
                            this.Connection.Avatar.AddXP(LogicStringUtil.ConvertToInt(this.Parameters[2]));
                            break;
                        }

                        case "score":
                        {
                            this.Connection.Avatar.AddTrophies(LogicStringUtil.ConvertToInt(this.Parameters[2]));
                            break;
                        }

                        default:
                        {
                            this.Connection.SendChatMessage(this.Help.ToString());
                            break;
                        }
                        }
                    }

                    this.Connection.SendChatMessage($"Added {this.Parameters[1]} to your {this.Parameters[0]}");
                    this.Connection.Avatar.Save();

                    new OwnAvatarDataMessage(this.Connection).Send();
                }
                else
                {
                    this.Connection.SendChatMessage(this.Help.ToString());
                }
            }
            else
            {
                this.Connection.SendChatMessage("Insufficient privileges.");
            }
        }
Пример #27
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Parser"/> class.
        /// </summary>
        internal static void Init()
        {
            if (Parser.Initialized)
            {
                return;
            }

            new Thread(() =>
            {
                while (true)
                {
                    int cursorTop2 = Console.CursorTop = Console.WindowTop + Console.WindowHeight - 1;
                    Console.Write($"root@{Constants.LocalIP.ToString().Split(":")[0]} > ");

                    string[] command = Console.ReadLine()?.Split(' ');

                    Console.SetCursorPosition(0, cursorTop2 - 1);
                    Console.WriteLine(new string(' ', Console.BufferWidth));
                    Console.SetCursorPosition(0, cursorTop2 - 2);

                    switch (command?[0].Replace("/", string.Empty))
                    {
                    case "stats":
                        {
                            if (Loader.Initialized)
                            {
                                Console.WriteLine();
                                Console.WriteLine($"#  {DateTime.Now.ToString("d")} ---- STATS ---- {DateTime.Now.ToString("t")} #");
                                Console.WriteLine("# ----------------------------------- #");
                                Console.WriteLine($"# Connected Sockets # {LogicStringUtil.IntToString(Connections.Count).Pad(15)} #");
                                Console.WriteLine($"# In-Memory Avatars # {LogicStringUtil.IntToString(Avatars.Count).Pad(15)} #");
                                Console.WriteLine($"#  In-Memory Clans  # {LogicStringUtil.IntToString(Alliances.Count).Pad(15)} #");
                                Console.WriteLine("# ----------------------------------- #");
                            }

                            break;
                        }

                    case "setrank":
                        {
                            if (Loader.Initialized)
                            {
                                var tag  = command[1];
                                var rank = (Rank)Enum.GetValues(typeof(Rank)).GetValue(LogicStringUtil.ConvertToInt(command[2]));

                                LogicTagUtil.ToHighLow(tag, out int highId, out int lowId);

                                var player = Avatars.Get(new LogicLong(highId, lowId));
                                player.SetRank(rank);
                            }

                            break;
                        }

                    case "sendDebugCmd":
                        {
                            if (Loader.Initialized && LogicVersion.IsIntegration)
                            {
                                var commandId = LogicStringUtil.ConvertToInt(command[1]);

                                var playerId = command[2].Split('-');
                                var player   = Avatars.Get(new LogicLong(LogicStringUtil.ConvertToInt(playerId[0]), LogicStringUtil.ConvertToInt(playerId[1])));

                                new AvailableServerCommandMessage(player.Connection, new LogicDebugCommand(player.Connection, commandId)).Send(); // <- saving is false for the purpose of testing - this does not work yet
                                new OwnAvatarDataMessage(player.Connection).Send();

                                Console.WriteLine($"Sent Debug Command with ID {commandId} to player {player}");
                            }

                            break;
                        }

                    case "clear":
                        {
                            Console.Clear();
                            break;
                        }

                    case "exit":
                    case "shutdown":
                    case "stop":
                        {
                            EventsHandler.Exit();
                            break;
                        }

                    default:
                        {
                            Console.WriteLine();
                            break;
                        }
                    }
                }
            }).Start();

            Parser.Initialized = true;
        }
        internal override void Execute()
        {
            if (this.Hero != null)
            {
                if (this.Connection.Avatar.HeroUpgrade.CanUpgrade(this.Hero))
                {
                    if (this.Connection.Avatar.ExpLevel < this.Hero.RequiredXpLevel)
                    {
                        Debugger.Error($"Unable to upgrade the hero. {this.Connection.Avatar.Name} ({this.Connection.Avatar}) is not at the required level. (Level : {this.Connection.Avatar.ExpLevel}, Require : {this.Hero.RequiredXpLevel})");
                        return;
                    }

                    if (!string.IsNullOrEmpty(this.Hero.RequiredQuest))
                    {
                        if (!this.Connection.Avatar.NpcProgress.ContainsKey(this.Hero.RequiredQuestData.GlobalID))
                        {
                            Debugger.Error($"Unable to upgrade the hero. {this.Connection.Avatar.Name} ({this.Connection.Avatar}) has not unlocked the required quest.");
                            return;
                        }
                    }

                    string[] cost = this.Hero.Cost[this.Connection.Avatar.HeroLevels.GetCount(this.Hero.GlobalID)].Split(',');

                    if (cost.Length >= 7)
                    {
                        int diamonds = LogicStringUtil.ConvertToInt(cost[0]);
                        int gold     = LogicStringUtil.ConvertToInt(cost[1]);
                        int energy   = LogicStringUtil.ConvertToInt(cost[2]);
                        int orb1     = LogicStringUtil.ConvertToInt(cost[3]);
                        int orb2     = LogicStringUtil.ConvertToInt(cost[4]);
                        int orb3     = LogicStringUtil.ConvertToInt(cost[5]);
                        int orb4     = LogicStringUtil.ConvertToInt(cost[6]);

                        if (diamonds != 0)
                        {
                            if (this.Connection.Avatar.Diamonds < diamonds)
                            {
                                Debugger.Error($"Unable to upgrade the hero. {this.Connection.Avatar.Name} ({this.Connection.Avatar}) does not have enough diamonds. (Diamonds : {this.Connection.Avatar.Diamonds}, Require : {diamonds})");
                                return;
                            }
                        }

                        if (gold != 0)
                        {
                            if (this.Connection.Avatar.Gold < gold)
                            {
                                Debugger.Error($"Unable to upgrade the hero. {this.Connection.Avatar.Name} ({this.Connection.Avatar}) does not have enough gold. (Gold : {this.Connection.Avatar.Gold}, Require : {gold})");
                                return;
                            }
                        }

                        if (energy != 0)
                        {
                            if (this.Connection.Avatar.Energy < energy)
                            {
                                Debugger.Error($"Unable to upgrade the hero. {this.Connection.Avatar.Name} ({this.Connection.Avatar}) does not have enough energy. (Energy : {this.Connection.Avatar.Energy}, Require : {energy}.");
                                return;
                            }
                        }

                        if (orb1 != 0)
                        {
                            if (this.Connection.Avatar.Orb1 < orb1)
                            {
                                Debugger.Error($"Unable to upgrade the hero. {this.Connection.Avatar.Name} ({this.Connection.Avatar}) does not have enough of orb1. (Orb1 : {this.Connection.Avatar.Orb1}, Require : {orb1})");
                                return;
                            }
                        }

                        if (orb2 != 0)
                        {
                            if (this.Connection.Avatar.Orb2 < orb2)
                            {
                                Debugger.Error($"Unable to upgrade the hero. {this.Connection.Avatar.Name} ({this.Connection.Avatar}) does not have enough of orb2. (Orb2 : {this.Connection.Avatar.Orb2}, Require : {orb2})");
                                return;
                            }
                        }

                        if (orb3 != 0)
                        {
                            if (this.Connection.Avatar.Orb3 < orb3)
                            {
                                Debugger.Error($"Unable to upgrade the hero. {this.Connection.Avatar.Name} ({this.Connection.Avatar}) does not have enough of orb3. (Orb3 : {this.Connection.Avatar.Orb3}, Require : {orb3})");
                                return;
                            }
                        }

                        if (orb4 != 0)
                        {
                            if (this.Connection.Avatar.Orb4 < orb4)
                            {
                                Debugger.Error($"Unable to upgrade the hero. {this.Connection.Avatar.Name} ({this.Connection.Avatar}) does not have enough of orb4. (Orb4 : {this.Connection.Avatar.Orb4}, Require : {orb4})");
                                return;
                            }
                        }

                        this.Connection.Avatar.Diamonds -= diamonds;
                        this.Connection.Avatar.Gold     -= gold;
                        this.Connection.Avatar.Energy   -= energy;
                        this.Connection.Avatar.Orb1     -= orb1;
                        this.Connection.Avatar.Orb2     -= orb2;
                        this.Connection.Avatar.Orb3     -= orb3;
                        this.Connection.Avatar.Orb4     -= orb4;
                    }

                    this.Connection.Avatar.HeroUpgrade.Start(this.Hero);

                    this.Connection.Avatar.Save();
                }
            }
        }