/// <summary> /// Get an alliance from cache or database /// </summary> /// <param name="allianceId"></param> /// <param name="onlineOnly"></param> /// <returns></returns> public async Task <Alliance> GetAllianceAsync(long allianceId, bool onlineOnly = false) { lock (_syncObject) { if (ContainsKey(allianceId)) { return(this[allianceId]); } } if (onlineOnly) { return(null); } if (!Redis.IsConnected) { return(await AllianceDb.GetAsync(allianceId)); } var alliance = await Redis.GetAllianceAsync(allianceId); if (alliance != null) { return(alliance); } alliance = await AllianceDb.GetAsync(allianceId); await Redis.CacheAsync(alliance); return(alliance); }
public async void Tick(object state, ElapsedEventArgs args) { await Task.Run(async() => { try { var currentGlobalPlayerRanking = await PlayerDb.GetGlobalPlayerRankingAsync(); for (var i = 0; i < currentGlobalPlayerRanking.Count; i++) { GlobalPlayerRanking.UpdateOrInsert(i, currentGlobalPlayerRanking[i]); } foreach (var(key, value) in LocalPlayerRanking) { var currentLocalPlayerRanking = await PlayerDb.GetLocalPlayerRankingAsync(key); for (var i = 0; i < currentLocalPlayerRanking.Count; i++) { value.UpdateOrInsert(i, currentLocalPlayerRanking[i]); } } var currentGlobalAllianceRanking = await AllianceDb.GetGlobalAlliancesAsync(); for (var i = 0; i < currentGlobalAllianceRanking.Count; i++) { GlobalAllianceRanking.UpdateOrInsert(i, currentGlobalAllianceRanking[i]); } } catch (Exception exception) { Logger.Log($"Error while updating leaderboads {exception}", GetType(), ErrorLevel.Error); } }); }
public static async void Initialize() { Logger = new Logger(); Logger.Log( $"Starting [{DateTime.Now.ToLongTimeString()} - {ServerUtils.GetOSName()}]...", null); Configuration = new Configuration(); Configuration.Initialize(); Fingerprint = new Fingerprint(); Sentry = new SentryReport(); Csv = new Csv(); UpdateManager = new UpdateManager(); PlayerDb = new PlayerDb(); AllianceDb = new AllianceDb(); Logger.Log( $"Successfully loaded MySql with {await PlayerDb.CountAsync()} player(s) & {await AllianceDb.CountAsync()} clan(s)", null); Redis = new Redis(); Battles = new Battles(); Players = new Players(); Alliances = new Alliances(); Leaderboard = new Leaderboard(); Netty = new NettyService(); await Task.Run(Netty.RunServerAsync); }
public async Task <Alliance> GetAllianceAsync(long allianceId, bool onlineOnly = false) { lock (_syncObject) { if (ContainsKey(allianceId)) { return(this[allianceId]); } } if (onlineOnly) { return(null); } var alliance = Resources.ObjectCache.GetCachedAlliance(allianceId); if (alliance != null) { return(alliance); } alliance = await AllianceDb.GetAsync(allianceId); Resources.ObjectCache.CacheAlliance(alliance); return(alliance); }
public static void Construct() { Configuration = new Configuration(); Configuration.Initialize(); _logger = new Logger(); Logger.Log($"ENV: {(Utils.IsLinux ? "Linux" : "Windows")}"); Csv = new Csv(); Fingerprint = new Fingerprint(); _playerDb = new PlayerDb(); _replayDb = new ReplayDb(); _allianceDb = new AllianceDb(); _redis = new Redis(); Levels = new Levels(); PlayerCache = new Players(); AllianceCache = new Alliances(); LeaderboardCache = new Leaderboards(); ChatManager = new LogicGlobalChatManager(); Gateway = new Gateway(); StartDateTime = DateTime.UtcNow; Gateway.StartAsync().Wait(); }
/// <summary> /// Creates a alliance with the specified identifier in the specified database. /// </summary> internal static Alliance Create(int high = 0, int low = 0, DBMS database = Settings.Database, bool store = true) { if (low == 0) { Alliance alliance = new Alliance(high, Interlocked.Increment(ref Alliances.Seed)); switch (database) { case DBMS.Mongo: { AllianceDb.Create(alliance).GetAwaiter().GetResult(); break; } case DBMS.File: { FileInfo file = new FileInfo($"{Directory.GetCurrentDirectory()}/Saves/Alliances/{alliance}.json"); if (!file.Exists) { file.WriteAllText(JsonConvert.SerializeObject(alliance, AllianceDb.JsonSettings)); } break; } } return(alliance); } return(null); }
public async Task <bool> RemoveAlliance(long id) { try { if (!ContainsKey(id)) { return(true); } var alliance = this[id]; alliance.Timer.Stop(); if (Redis.IsConnected) { await Redis.CacheAlliance(alliance); } await AllianceDb.Save(alliance); return(TryRemove(id, out var value)); } catch (Exception exception) { Logger.Log(exception, Enums.LogType.Error); return(false); } }
public async void SaveCallback(object state, ElapsedEventArgs args) { if (Redis.IsConnected) { await Redis.CacheAlliance(this); } await AllianceDb.Save(this); }
public override async void Process() { var player = Device.Player; if (!player.Home.UseGold(1000)) { return; } var alliance = await AllianceDb.CreateAsync(); if (alliance != null) { alliance.Name = Name; alliance.Description = Description; alliance.Badge = Badge; alliance.Type = Type; alliance.RequiredScore = RequiredScore; alliance.Region = Region; alliance.Members.Add( new AllianceMember(player, Logic.Clan.Alliance.Role.Leader)); player.Home.AllianceInfo = alliance.GetAllianceInfo(player.Home.Id); alliance.Save(); player.Save(); await new AvailableServerCommand(Device) { Command = new LogicJoinAllianceCommand(Device) { AllianceId = alliance.Id, AllianceName = Name, AllianceBadge = Badge } }.SendAsync(); await new AvailableServerCommand(Device) { Command = new LogicChangeAllianceRoleCommand(Device) { AllianceId = alliance.Id, NewRole = 2 } }.SendAsync(); alliance.UpdateOnlineCount(); } else { Device.Disconnect(); } }
/// <summary> /// Gets the alliance using the specified identifier in the specified database. /// </summary> internal static Alliance Get(int highId, int lowId, DBMS database = Settings.Database, bool store = true) { long id = (long)highId << 32 | (uint)lowId; if (!Alliances.Pool.TryGetValue(id, out Alliance alliance)) { switch (database) { case DBMS.Mongo: { AllianceDb save = Mongo.Alliances.Find(db => db.HighID == highId && db.LowID == lowId).SingleOrDefault(); if (save != null) { alliance = Alliances.Load(save.Profile.ToJson()); if (alliance == null) { Debugger.Error($"Unable to load alliance with the ID {highId}-{lowId}."); } } break; } case DBMS.File: { FileInfo file = new FileInfo($"{Directory.GetCurrentDirectory()}/Saves/Alliances/{highId}-{lowId}.json"); if (file.Exists) { string json = file.ReadAllText(); if (!json.IsNullOrEmptyOrWhitespace()) { alliance = JsonConvert.DeserializeObject <Alliance>(json, AllianceDb.JsonSettings); } else { Debugger.Error($"The data returned wasn't null but empty, at Get({highId}, {lowId}, File, {store})."); } } break; } } } return(alliance); }
public void Dispose() { Csv = null; Gateway = null; PlayerCache = null; Configuration = null; Levels = null; Fingerprint = null; _messagefactory = null; _commandfactory = null; _debugcommandfactory = null; _playerDb = null; _replayDb = null; _allianceDb = null; _logger = null; }
public override async void Process() { var home = Device.Player.Home; var alliance = await Resources.Alliances.GetAllianceAsync(home.AllianceInfo.Id); if (alliance == null) { return; } alliance.Remove(home.Id); home.AllianceInfo.Reset(); Device.Player.Save(); await new AvailableServerCommand(Device) { Command = new LogicLeaveAllianceCommand(Device) { AllianceId = alliance.Id } }.SendAsync(); if (alliance.Members.Count != 0) { var entry = new AllianceEventStreamEntry { EventType = AllianceEventStreamEntry.Type.Leave }; entry.SetTarget(Device.Player); entry.SetSender(Device.Player); alliance.AddEntry(entry); alliance.Save(); alliance.UpdateOnlineCount(); } else { await AllianceDb.DeleteAsync(alliance.Id); await Redis.UncacheAllianceAsync(alliance.Id); } }
/// <summary> /// Saves the specified alliance in the specified database. /// </summary> internal static void Save(Alliance alliance, DBMS database = Settings.Database) { if (alliance != null) { switch (database) { case DBMS.Mongo: { AllianceDb.Save(alliance).GetAwaiter().GetResult(); break; } case DBMS.File: { new FileInfo($"{Directory.GetCurrentDirectory()}/Saves/Alliances/{alliance}.json").WriteAllText(JsonConvert.SerializeObject(alliance, AllianceDb.JsonSettings)); break; } } } }
internal static void Delete(Alliance alliance, DBMS database = Settings.Database) { Alliances.Remove(alliance); switch (database) { case DBMS.Mongo: { AllianceDb.Delete(alliance.HighID, alliance.LowID).GetAwaiter().GetResult(); break; } case DBMS.File: { new FileInfo($"{Directory.GetCurrentDirectory()}/Saves/Alliances/{alliance.HighID}-{alliance.LowID}.json").DeleteIfExists(); break; } } Alliances.Save(); }
public async void TimerCallback(object state, ElapsedEventArgs args) { try { var currentGlobalPlayerRanking = await PlayerDb.GetGlobalPlayerRanking(); for (var i = 0; i < currentGlobalPlayerRanking.Count; i++) { GlobalPlayers.UpdateOrInsert(i, currentGlobalPlayerRanking[i]); } foreach (var players in LocalPlayers) { var currentLocalPlayerRanking = await PlayerDb.GetLocalPlayerRanking(players.Key); for (var i = 0; i < currentLocalPlayerRanking.Count; i++) { players.Value.UpdateOrInsert(i, currentLocalPlayerRanking[i]); } } var currentGlobalAllianceRanking = await AllianceDb.GetGlobalAllianceRanking(); for (var i = 0; i < currentGlobalAllianceRanking.Count; i++) { GlobalAlliances.UpdateOrInsert(i, currentGlobalAllianceRanking[i]); } var currentJoinableClans = await AllianceDb.GetJoinableAlliances(40); for (var i = 0; i < currentJoinableClans.Count; i++) { JoinableClans.UpdateOrInsert(i, JoinableClans[i]); } } catch (Exception exception) { Logger.Log(exception, Enums.LogType.Error); } }
public Resources() { Configuration = new Configuration(); Configuration.Initialize(); _logger = new Logger(); Logger.Log($"ENV: {(Utils.IsLinux ? "Linux" : "Windows")}"); Csv = new Csv(); Fingerprint = new Fingerprint(); _playerDb = new PlayerDb(); _replayDb = new ReplayDb(); _allianceDb = new AllianceDb(); if (!string.IsNullOrEmpty(Configuration.RedisPassword) && !string.IsNullOrEmpty(Configuration.RedisServer)) { _redis = new Redis(); } _messagefactory = new LogicMagicMessageFactory(); _commandfactory = new LogicCommandManager(); _debugcommandfactory = new DebugCommandFactory(); Levels = new Levels(); PlayerCache = new PlayerCache(); AllianceCache = new AllianceCache(); LeaderboardCache = new LeaderboardCache(); ChatManager = new LogicGlobalChatManager(); Gateway = new Gateway(); StartDateTime = DateTime.UtcNow; Gateway.StartAsync().Wait(); }
public async Task <Alliance> GetAlliance(long id) { if (ContainsKey(id)) { TryGetValue(id, out var value); return(value); } Alliance alliance; if (Redis.IsConnected) { alliance = await Redis.GetCachedAlliance(id); } else { alliance = await AllianceDb.Get(id); } AddAlliance(alliance); return(alliance); }
public override async void Process() { var info = Device.Player.Home.AllianceInfo; if (!info.HasAlliance) { return; } var alliance = await Resources.Alliances.GetAllianceAsync(info.Id); if (alliance == null) { return; } if (Message.StartsWith('/')) { var cmd = Message.Split(' '); var cmdType = cmd[0]; var cmdValue = 0; if (cmd.Length > 1) { if (Message.Split(' ')[1].Any(char.IsDigit)) { int.TryParse(Message.Split(' ')[1], out cmdValue); } } switch (cmdType) { case "/max": { var deck = Device.Player.Home.Deck; foreach (var card in Cards.GetAllCards()) { deck.Add(card); for (var i = 0; i < 12; i++) { deck.UpgradeCard(card.ClassId, card.InstanceId, true); } } await new ServerErrorMessage(Device) { Message = "Added all cards with max level" }.SendAsync(); break; } case "/unlock": { var deck = Device.Player.Home.Deck; foreach (var card in Cards.GetAllCards()) { deck.Add(card); } await new ServerErrorMessage(Device) { Message = "Added all cards" }.SendAsync(); break; } case "/gold": { Device.Player.Home.Gold += cmdValue; Device.Disconnect(); break; } case "/status": { await new ServerErrorMessage(Device) { Message = $"Online Players: {Resources.Players.Count}\nTotal Players: {await PlayerDb.CountAsync()}\n1v1 Battles: {Resources.Battles.Count}\n2v2 Battles: {Resources.DuoBattles.Count}\nTotal Clans: {await AllianceDb.CountAsync()}\nUptime: {DateTime.UtcNow.Subtract(Resources.StartTime).ToReadableString()}" }.SendAsync(); break; } /*case "/free": * { * Device.Player.Home.FreeChestTime = Device.Player.Home.FreeChestTime.Subtract(TimeSpan.FromMinutes(245)); * Device.Disconnect(); * break; * }*/ /*case "/replay": * { * await new HomeBattleReplayDataMessage(Device).SendAsync(); * break; * }*/ /*case "/trophies": * { * if (cmdValue >= 0) * Device.Player.Home.Arena.AddTrophies(cmdValue); * else if (cmdValue < 0) * Device.Player.Home.Arena.RemoveTrophies(cmdValue); * * Device.Disconnect(); * break; * }*/ } } else { var entry = new ChatStreamEntry { Message = Message }; entry.SetSender(Device.Player); alliance.AddEntry(entry); } }
public override async void Process() { var info = Device.Player.Home.AllianceInfo; if (!info.HasAlliance) { return; } var alliance = await Resources.Alliances.GetAllianceAsync(info.Id); if (alliance == null) { return; } if (Message.StartsWith('/')) { var cmd = Message.Split(' '); var cmdType = cmd[0]; var cmdValue = 0; if (cmd.Length > 1) { if (Message.Split(' ')[1].Any(char.IsDigit)) { int.TryParse(Message.Split(' ')[1], out cmdValue); } } switch (cmdType) { case "/max": { var deck = Device.Player.Home.Deck; foreach (var card in Cards.GetAllCards()) { deck.Add(card); for (var i = 0; i < 12; i++) { deck.UpgradeCard(card.ClassId, card.InstanceId, true); } } await new ServerErrorMessage(Device) { Message = "Added all cards with max level" }.SendAsync(); break; } case "/unlock": { var deck = Device.Player.Home.Deck; foreach (var card in Cards.GetAllCards()) { deck.Add(card); } await new ServerErrorMessage(Device) { Message = "Added all cards" }.SendAsync(); break; } case "/gold": { Device.Player.Home.Gold += cmdValue; Device.Disconnect(); break; } case "/gems": { Device.Player.Home.Diamonds += cmdValue; Device.Disconnect(); break; } case "/status": { var entry = new ChatStreamEntry { Message = $"Server status:\nBuild version: 1.5 (for 1.9.2)\nFingerprint SHA:\n{Resources.Fingerprint.Sha}\nOnline Players: {Resources.Players.Count}\nTotal Players: {await PlayerDb.CountAsync()}\n1v1 Battles: {Resources.Battles.Count}\n2v2 Battles: {Resources.DuoBattles.Count}\nTotal Clans: {await AllianceDb.CountAsync()}\nUptime: {DateTime.UtcNow.Subtract(Resources.StartTime).ToReadableString()}\nUsed RAM: {System.Diagnostics.Process.GetCurrentProcess().WorkingSet64 / (1024 * 1024) + " MB"}" }; entry.SetSender(Device.Player); alliance.AddEntry(entry); break; } case "/free": { Device.Player.Home.FreeChestTime = Device.Player.Home.FreeChestTime.Subtract(TimeSpan.FromMinutes(245)); Device.Disconnect(); break; } /*case "/replay": * { * await new HomeBattleReplayDataMessage(Device).SendAsync(); * break; * }*/ case "/trophies": { if (cmdValue >= 0) { Device.Player.Home.Arena.AddTrophies(cmdValue); } else if (cmdValue < 0) { Device.Player.Home.Arena.RemoveTrophies(cmdValue); } Device.Disconnect(); break; } case "/set": { Device.Player.Home.Arena.SetTrophies(cmdValue); Device.Disconnect(); break; } case "/help": { var help = new ChatStreamEntry { Message = $"List of commands:\n/max - open all cards max. level\n/unlock - open all cards\n/gold x - give out gold, where x - amount of gold\n/ gems x - give out gems, where x - amount of gems\n/ status - a command that shows the server status (needed for admins)\n / free - resets the timer of the free chest\n/trophies x - adds trophies, where x - the number of trophies (can be negative)\n/ set x - the specified number of trophies is available, where x - the number of trophies" }; help.SetSender(Device.Player); alliance.AddEntry(help); break; } default: var error = new ChatStreamEntry { Message = $"Command not found. Use /help for the list of commands." }; error.SetSender(Device.Player); alliance.AddEntry(error); break; } } else { var entry = new ChatStreamEntry { Message = Message }; entry.SetSender(Device.Player); alliance.AddEntry(entry); } }