namespace Supercell.Laser.Server.Message { using Supercell.Laser.Logic.Avatar; using Supercell.Laser.Server.Utils; using Supercell.Laser.Logic.Avatar.Structures; using Supercell.Laser.Logic.Club; using Supercell.Laser.Logic.Command.Avatar; using Supercell.Laser.Logic.Data; using Supercell.Laser.Logic.Friends; using Supercell.Laser.Logic.Home; using Supercell.Laser.Logic.Home.Structures; using Supercell.Laser.Logic.Listener; using Supercell.Laser.Logic.Message.Account; using Supercell.Laser.Logic.Message.Club; using Supercell.Laser.Logic.Message.Friends; using Supercell.Laser.Logic.Message.Home; using Supercell.Laser.Logic.Message.Ranking; using Supercell.Laser.Logic.Message.Security; using Supercell.Laser.Logic.Message.Team; using Supercell.Laser.Logic.Message.Udp; using Supercell.Laser.Logic.Stream.Entry; using Supercell.Laser.Logic.Team; using Supercell.Laser.Server.Database; using Supercell.Laser.Server.Database.Models; using Supercell.Laser.Server.Logic.Game; using Supercell.Laser.Server.Networking; using Supercell.Laser.Server.Networking.Session; using Supercell.Laser.Server.Settings; using Supercell.Laser.Server.Logic; using System.Diagnostics; using Supercell.Laser.Server.Database.Cache; using Supercell.Laser.Logic.Util; using Supercell.Laser.Logic.Battle; using Supercell.Laser.Logic.Message.Battle; using Supercell.Laser.Server.Networking.UDP.Game; using Supercell.Laser.Server.Networking.Security; using Supercell.Laser.Logic.Home.Items; using Supercell.Laser.Logic.Team.Stream; using Supercell.Laser.Logic.Message.Team.Stream; using Supercell.Laser.Logic.Message; using Supercell.Laser.Logic.Message.Account.Auth; using Supercell.Laser.Logic.Message.Latency; using Supercell.Laser.Logic.Command; using Supercell.Laser.Logic.Battle.Structures; using Newtonsoft.Json.Linq; using Newtonsoft.Json; using System.Reflection; using System.Numerics; using Supercell.Laser.Logic.Home.Quest; using Supercell.Laser.Logic.Data.Helper; using System.Linq; using Supercell.Laser.Logic.Command.Home; using Supercell.Laser.Logic.Message.Api; using System.Xml.Linq; using Microsoft.VisualBasic; using Supercell.Laser.Logic.Message.Ranked; using Supercell.Laser.Logic.Ranked; using Supercell.Laser.Titan.Math; using Supercell.Laser.Server.PlayerMapUtils; public class MessageManager { public Connection Connection { get; } public HomeMode HomeMode; public CommandManager CommandManager; private DateTime LastKeepAlive; public MessageManager(Connection connection) { Connection = connection; LastKeepAlive = DateTime.UtcNow; } public bool IsAlive() { return (int)(DateTime.UtcNow - LastKeepAlive).TotalSeconds < 30; } public string GetPingIconByMs(int ms) { string str = "▂ "; if (ms <= 75) { str = "▂▄▆█"; } else if (ms <= 125) { str = "▂▄▆ "; } else if (ms <= 300) { str = "▂▄ "; } return str; } public void ShowLobbyInfo() { if (HomeMode?.Avatar != null && HomeMode.Avatar.LobbyInfoDisabled) { Connection.Send(new LobbyInfoMessage() { LobbyData = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", PlayersCount = 0 }); return; } string abd = $"Connection: {GetPingIconByMs(0)} (---ms)\n"; if (Connection.Ping != 0) { abd = $"Connection: {GetPingIconByMs(Connection.Ping)} ({Connection.Ping}ms)\n"; } var eventNow = DateTime.UtcNow; string eventLine = ""; if (eventNow >= Supercell.Laser.Logic.Battle.CommunityEvent.EventStart && eventNow <= Supercell.Laser.Logic.Battle.CommunityEvent.EventEnd) { int total = Supercell.Laser.Logic.Battle.CommunityEvent.TotalWins; int goal = Supercell.Laser.Logic.Battle.CommunityEvent.GoalWins; int gems = Supercell.Laser.Logic.Battle.CommunityEvent.GemsReward; eventLine = $"\nИВЕНТ: {total}/{goal} побед -> {gems} гемов всем!\n"; } LobbyInfoMessage b = new() { LobbyData = $"\nt.me/aimbrawl\n{abd}Players online: {Sessions.Count}{eventLine}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nhi'", PlayersCount = 0 }; Connection.Send(b); } public void ReceiveMessage(GameMessage message) { switch (message.GetMessageType()) { case 10099: Connection.Close(); break; case 10100: ClientHelloReceived((ClientHelloMessage)message); break; case 10101: LoginReceived((AuthenticationMessage)message); break; case 10107: ClientCapabilitesReceived((ClientCapabilitiesMessage)message); //Connection.Send(new StartLatencyTestRequestMessage()); break; case 10108: LastKeepAlive = DateTime.UtcNow; Connection.Send(new KeepAliveServerMessage()); ShowLobbyInfo(); if (!Sessions.IsSessionActive(HomeMode.Avatar.AccountId)) { Sessions.Create(HomeMode, Connection); } break; case 10110: ShowLobbyInfo(); break; case 10119: ReportAllianceStreamReceived((ReportAllianceStreamMessage)message); break; case 10212: ChangeName((ChangeAvatarNameMessage)message); break; case 10177: ClientInfoReceived((ClientInfoMessage)message); break; case 10501: AcceptFriendReceived((AcceptFriendMessage)message); break; case 10502: AddFriendReceived((AddFriendMessage)message); break; case 10504: AskForFriendListReceived((AskForFriendListMessage)message); break; case 10506: RemoveFriendReceived((RemoveFriendMessage)message); break; case 10576: SetBlockFriendRequestsReceived((SetBlockFriendRequestsMessage)message); break; case 10555: break; case 14101: GoHomeReceived((GoHomeMessage)message); break; case 14102: EndClientTurnReceived((EndClientTurnMessage)message); break; case 14103: MatchmakeRequestReceived((MatchmakeRequestMessage)message); break; case 14104: StartSpectateReceived((StartSpectateMessage)message); break; case 14106: CancelMatchMaking((CancelMatchmakingMessage)message); break; case 14107: StopSpectateReceived((StopSpectateMessage)message); break; case 14109: GoHomeFromOfflinePractiseReceived((GoHomeFromOfflinePractiseMessage)message); break; case 14110: AskForBattleEndReceived((AskForBattleEndMessage)message); break; case 14114: GetBattleLogReceived((GetBattleLogMessage)message); break; case 14113: GetPlayerProfile((GetPlayerProfileMessage)message); break; case 14117: RequestMatchCancelReceived((RequestMatchCancelMessage)message); break; case 14118: SinglePlayerMatchRequestReceived((SinglePlayerMatchRequestMessage)message); break; case 14166: break; case 14277: GetSeasonRewardsReceived((GetSeasonRewardsMessage)message); break; case 14301: CreateAllianceReceived((CreateAllianceMessage)message); break; case 14302: AskForAllianceDataReceived((AskForAllianceDataMessage)message); break; case 14303: AskForJoinableAllianceListReceived((AskForJoinableAllianceListMessage)message); break; case 14305: JoinAllianceReceived((JoinAllianceMessage)message); break; case 14306: ChangeAllianceMemberRoleReceived((ChangeAllianceMemberRoleMessage)message); break; case 14307: KickAllianceMemberReceived((KickAllianceMemberMessage)message); break; case 14308: LeaveAllianceReceived((LeaveAllianceMessage)message); break; case 14315: ChatToAllianceStreamReceived((ChatToAllianceStreamMessage)message); break; case 14316: ChangeAllianceSettingsReceived((ChangeAllianceSettingsMessage)message); break; case 14324: AllianceSearchReceived((AllianceSearchMessage)message); break; case 14350: TeamCreateReceived((TeamCreateMessage)message); break; case 14353: TeamLeaveReceived((TeamLeaveMessage)message); break; case 14354: TeamChangeMemberSettingsReceived((TeamChangeMemberSettingsMessage)message); break; case 14355: TeamSetMemberReadyReceived((TeamSetMemberReadyMessage)message); break; case 14358: TeamSpectateMessageReceived((TeamSpectateMessage)message); break; case 14359: TeamChatReceived((TeamChatMessage)message); break; case 14361: TeamMemberStatusReceived((TeamMemberStatusMessage)message); ShowLobbyInfo(); break; case 14362: TeamSetEventReceived((TeamSetEventMessage)message); break; case 14363: TeamSetLocationReceived((TeamSetLocationMessage)message); break; case 14365: TeamInviteReceived((TeamInviteMessage)message); break; case 14366: PlayerStatusReceived((PlayerStatusMessage)message); ShowLobbyInfo(); break; case 14367: TeamClearInviteMessageReceived((TeamClearInviteMessage)message); break; case 14369: TeamPremadeChatReceived((TeamPremadeChatMessage)message); break; case 14370: TeamInviteReceived((TeamInviteMessage)message); break; case 14403: GetLeaderboardReceived((GetLeaderboardMessage)message); break; case 14479: TeamInvitationResponseReceived((TeamInvitationResponseMessage)message); break; case 14600: AvatarNameCheckRequestReceived((AvatarNameCheckRequestMessage)message); break; case 14777: SetInvitesBlockedReceived((SetInvitesBlockedMessage)message); break; case 18686: SetSupportedCreatorReceived((SetSupportedCreatorMessage)message); break; case 19001: LatencyTestResultReceived((LatencyTestResultMessage)message); break; case 11000: RequestSyncSSIDReceived((RequestSyncSSID)message); break; case 19995: RequestSynsCodeSSIDReceived((RequestCodeSSID)message); break; case 19996: RequestMaintenanceReceived((RequestMaintenance)message); break; case 19997: RequestSaveAllReceived((RequestSaveAll)message); break; case 19998: RequestDBChangesReceived((RequestDBChanges)message); break; case 19999: RequestServerReceived((RequestServerStatus)message); break; case 12155: _= RankedMatchPickHeroReceived((RankedMatchPickHeroMessage)message); break; case 12152: _= RankedMatchBanHero((RankedMatchBanHeroMessage)message); break; case 12100: CreatePlayerMapReceived((CreatePlayerMapMessage)message); break; case 12101: DeletePlayerMapReceived((DeletePlayerMapMessage)message); break; case 12102: GetPlayerMapsReceived((GetPlayerMapsMessage)message); break; case 12103: UpdatePlayerMapReceived((UpdatePlayerMapMessage)message); break; case 12104: SubmitPlayerMapReceived((SubmitPlayerMapMessage)message); break; case 12105: PublishPlayerMapReceived((PublishPlayerMapMessage)message); break; case 12106: ChangePlayerMapNameReceived((ChangePlayerMapNameMessage)message); break; case 12107: EnterMapEditorReceived((EnterMapEditorMessage)message); break; case 12108: GoHomeFromMapEditorReceived((GoHomeFromMapEditorMessage)message); break; case 12110: TeamSetPlayerMapReceived((TeamSetPlayerMapMessage)message); break; case 12111: SignoffPlayerMapReceived((SignoffPlayerMapMessage)message); break; case 12125: ReportPlayerMapReceived((ReportPlayerMapMessage)message); break; case 14351: TeamJoinReceived((TeamJoinMessage)message); break; case 14371: TeamJoinOrCreateRoomReceived((TeamJoinOrCreateRoomMessage)message); break; default: Logger.Print($"MessageManager::ReceiveMessage - no case for {message.GetType().Name} ({message.GetMessageType()})"); break; } //Logger.Print($"[MessageManager::ReceiveMessage] Message received! PacketName: {message.GetType().Name}, PacketID: {message.GetMessageType()}"); } private async Task RankedMatchPickHeroReceived(RankedMatchPickHeroMessage message) { try { var match = RankedMatchRegulator.Get(HomeMode.Avatar.RankedId); if (match == null) return; var player = match.GetPlayer(HomeMode.Avatar.AccountId); if (player == null) return; Logger.WriteServerLog($"[PickHero] Select={message.Select}, BrawlerId={message.BrawlerId}, HasPicked={player.HasPickedCharacter}, IsLocked={player.IsPickingLocked}"); if (player.HasPickedCharacter || player.IsPickingLocked) { Logger.WriteServerLog("[PickHero] Already picked or locked, ignoring"); return; } if (message.Select) { match.PickHero(player, message.BrawlerId, false); } else { bool success = match.PickHero(player, message.BrawlerId, true); if (!success) { // Очищаем предпросмотр у игрока player.CharacterPreview = 0; player.HasPickedCharacter = false; player.BanState = 0; /*public int BannedCharacter; public int PlayerIndex; public long BannerAccountId; public bool Success; public int ErrorType; */ match.SendAsync(new RankedMatchBanHeroResponseMessage { BannedCharacter = message.BrawlerId, Success = false }); // Отправляем клиенту обновление, чтобы он сбросил UI // match.SendAsync(new RankedMatchHeroDataUpdatedMessage { Player = player }); // Отправляем сообщение об ошибке /* Connection.Send(new RankedMatchPickHeroFailedMessage { Success = false, ErrorType = 1, PickedCharacter = message.BrawlerId });*/ // match.SendAsync(new RankedMatchUpdateHeroDataMessage { }); } } } catch (Exception ex) { Logger.WriteServerLog($"[PickHero] EXCEPTION {ex}"); } } private async Task RankedMatchBanHero(RankedMatchBanHeroMessage message) { try { var match = RankedMatchRegulator.Get(HomeMode.Avatar.RankedId); if (match == null) return; var player = match.GetPlayer(HomeMode.Avatar.AccountId); if (player == null) return; if (message.PickType == 1) { match.BanHero(player, message.BrawlerId, false); } else if (message.PickType == 0) { match.BanHero(player, message.BrawlerId, true); } } catch (Exception ex) { Logger.WriteServerLog($"[RankedMatchBanHero] EXCEPTION: {ex}"); } } public void SetSupportedCreatorReceived(SetSupportedCreatorMessage message) { PromocodeData promo = Promocodes.GetPromocode(message.ContentCreator); if (promo == null) { return; } if (promo.promoActivations.Contains(HomeMode.Avatar.AccountId)) { return; } if (promo.promoActivations.Count >= promo.promoLimitActivation) { return; } Account promoAccount = Accounts.Load(HomeMode.Avatar.AccountId); if (promoAccount == null) { return; } if (Promocodes.ActivatePromocode(message.ContentCreator, HomeMode.Avatar.AccountId)) { switch (promo.promoProduct.ToLower()) { case "gems": Notification notifPromoGems = new Notification { Id = 89, DonationCount = int.Parse(promo.promoProductCount), TimePassed = DateTime.UtcNow, MessageEntry = $"Промокод активирован." }; promoAccount.Home.NotificationFactory.Add(notifPromoGems); LogicAddNotificationCommand LANCPromoGems = new() { Notification = notifPromoGems }; AvailableServerCommandMessage ASCMPromoGems = new AvailableServerCommandMessage(); ASCMPromoGems.Command = LANCPromoGems; if (Sessions.IsSessionActive(HomeMode.Avatar.AccountId)) { var session = Sessions.GetSession(HomeMode.Avatar.AccountId); session.GameListener.SendTCPMessage(ASCMPromoGems); } break; } LogicSetSupportedCreatorCommand LSSCC = new() { Name = "Промокод активирован" }; AvailableServerCommandMessage LSSCCASCM = new AvailableServerCommandMessage(); LSSCCASCM.Command = LSSCC; if (Sessions.IsSessionActive(HomeMode.Avatar.AccountId)) { var session = Sessions.GetSession(HomeMode.Avatar.AccountId); session.GameListener.SendTCPMessage(LSSCCASCM); } } return; } private void TeamSpectateMessageReceived(TeamSpectateMessage message) { TeamEntry team = Teams.Get(message.TeamId); if (team == null) { TeamErrorMessage errorMessage = new TeamErrorMessage(); errorMessage.Reason = 3; Connection.Send(errorMessage); return; } LocationData locationData = null; int maxPlayersInRoom = 6; if (team.LocationId > 0) { locationData = DataTables.Get(DataType.Location) .GetDataByGlobalId(team.LocationId); } if (locationData != null) { switch (locationData.GameMode) { case "Showdown": case "DuoShowdown": maxPlayersInRoom = 10; break; default: maxPlayersInRoom = 6; break; } } if (team.Type == 0 && team.Members.Count > 2 || team.Type == 0 && team.Members.Count >= 1 && locationData.GameMode == "DuoShowdown") { TeamErrorMessage errorMessage = new TeamErrorMessage(); errorMessage.Reason = 2; Connection.Send(errorMessage); return; } if (team.Type == 1 && team.Members.Count >= maxPlayersInRoom) { TeamErrorMessage errorMessage = new TeamErrorMessage(); errorMessage.Reason = 2; Connection.Send(errorMessage); return; } HomeMode.Avatar.TeamId = team.Id; TeamMember member = new TeamMember { AccountId = HomeMode.Avatar.AccountId, CharacterId = HomeMode.Home.CharacterId, DisplayData = new PlayerDisplayData( HomeMode.Home.HasPremiumPass, HomeMode.Home.ThumbnailId, HomeMode.Home.NameColorId, HomeMode.Avatar.Name) }; Hero hero = HomeMode.Avatar.GetHero(HomeMode.Home.CharacterId); member.HeroLevel = hero.PowerLevel + 1; member.Starpower = 0; member.Gadget = 0; if (hero.SelectedStarPowerId > 0) { CardData starPower = DataTables.Get(DataType.Card) .GetDataByGlobalId( GlobalId.CreateGlobalId(23, hero.SelectedStarPowerId)); if (starPower != null) { member.Starpower = starPower.GetGlobalId(); } } if (hero.SelectedGadgetId > 0) { CardData gadget = DataTables.Get(DataType.Card) .GetDataByGlobalId( GlobalId.CreateGlobalId(23, hero.SelectedGadgetId)); if (gadget != null) { member.Gadget = gadget.GetGlobalId(); } } member.SkinId = GlobalId.CreateGlobalId(29, hero.SelectedSkinId); member.HeroTrophies = hero.Trophies; member.HeroHighestTrophies = hero.HighestTrophies; member.IsOwner = false; member.State = 2; team.Members.Add(member); team.TeamUpdated(); } private void SetBlockFriendRequestsReceived(SetBlockFriendRequestsMessage message) { //HomeMode.Home.BlockFriendRequests = message.State; } private void ReportAllianceStreamReceived(ReportAllianceStreamMessage message) { if (HomeMode.Avatar.AllianceId < 0) return; Alliance myAlliance = Alliances.Load(HomeMode.Avatar.AllianceId); if (myAlliance == null) return; if (HomeMode.Home.ReportsIds.Count > 5) { Connection.Send(new ReportUserStatusMessage() { Status = 2 }); return; } long index = 0; foreach (AllianceStreamEntry e in myAlliance.Stream.GetEntries()) { index++; if (e.Id == message.MessageIndex) { if (HomeMode.Home.ReportsIds.Contains(e.AuthorId)) { Connection.Send(new ReportUserStatusMessage() { Status = 3 }); return; } string reporterTag = LogicLongCodeGenerator.ToCode(HomeMode.Avatar.AccountId); string reporterName = HomeMode.Avatar.Name; string susTag = LogicLongCodeGenerator.ToCode(e.AuthorId); string susName = e.AuthorName; HomeMode.Home.ReportsIds.Add(e.AuthorId); string text = ""; try { text += myAlliance.Stream.GetEntries()[index - 5].SendTime + " " + LogicLongCodeGenerator.ToCode(myAlliance.Stream.GetEntries()[index - 5].AuthorId) + " " + myAlliance.Stream.GetEntries()[index - 5].AuthorName + ">>> " + myAlliance.Stream.GetEntries()[index - 5].Message + "\n"; } catch { } try { text += myAlliance.Stream.GetEntries()[index - 4].SendTime + " " + LogicLongCodeGenerator.ToCode(myAlliance.Stream.GetEntries()[index - 4].AuthorId) + " " + myAlliance.Stream.GetEntries()[index - 4].AuthorName + ">>> " + myAlliance.Stream.GetEntries()[index - 4].Message + "\n"; } catch { } try { text += myAlliance.Stream.GetEntries()[index - 3].SendTime + " " + LogicLongCodeGenerator.ToCode(myAlliance.Stream.GetEntries()[index - 3].AuthorId) + " " + myAlliance.Stream.GetEntries()[index - 3].AuthorName + ">>> " + myAlliance.Stream.GetEntries()[index - 3].Message + "\n"; } catch { } try { text += myAlliance.Stream.GetEntries()[index - 2].SendTime + " " + LogicLongCodeGenerator.ToCode(myAlliance.Stream.GetEntries()[index - 2].AuthorId) + " " + myAlliance.Stream.GetEntries()[index - 2].AuthorName + ">>> " + myAlliance.Stream.GetEntries()[index - 2].Message + "\n"; } catch { } try { text += myAlliance.Stream.GetEntries()[index - 1].SendTime + " " + LogicLongCodeGenerator.ToCode(myAlliance.Stream.GetEntries()[index - 1].AuthorId) + " " + myAlliance.Stream.GetEntries()[index - 1].AuthorName + ">>> " + myAlliance.Stream.GetEntries()[index - 1].Message + "\n"; } catch { } try { text += myAlliance.Stream.GetEntries()[index - 0].SendTime + " " + LogicLongCodeGenerator.ToCode(myAlliance.Stream.GetEntries()[index - 0].AuthorId) + " " + myAlliance.Stream.GetEntries()[index - 0].AuthorName + ">>> " + myAlliance.Stream.GetEntries()[index - 0].Message + "\n"; } catch { } try { text += myAlliance.Stream.GetEntries()[index + 1].SendTime + " " + LogicLongCodeGenerator.ToCode(myAlliance.Stream.GetEntries()[index + 1].AuthorId) + " " + myAlliance.Stream.GetEntries()[index + 1].AuthorName + ">>> " + myAlliance.Stream.GetEntries()[index + 1].Message + "\n"; } catch { } try { text += myAlliance.Stream.GetEntries()[index + 2].SendTime + " " + LogicLongCodeGenerator.ToCode(myAlliance.Stream.GetEntries()[index + 2].AuthorId) + " " + myAlliance.Stream.GetEntries()[index + 2].AuthorName + ">>> " + myAlliance.Stream.GetEntries()[index + 2].Message + "\n"; } catch { } try { text += myAlliance.Stream.GetEntries()[index + 3].SendTime + " " + LogicLongCodeGenerator.ToCode(myAlliance.Stream.GetEntries()[index + 3].AuthorId) + " " + myAlliance.Stream.GetEntries()[index + 3].AuthorName + ">>> " + myAlliance.Stream.GetEntries()[index + 3].Message + "\n"; } catch { } try { text += myAlliance.Stream.GetEntries()[index + 4].SendTime + " " + LogicLongCodeGenerator.ToCode(myAlliance.Stream.GetEntries()[index + 4].AuthorId) + " " + myAlliance.Stream.GetEntries()[index + 4].AuthorName + ">>> " + myAlliance.Stream.GetEntries()[index + 4].Message + "\n"; } catch { } try { text += myAlliance.Stream.GetEntries()[index + 5].SendTime + " " + LogicLongCodeGenerator.ToCode(myAlliance.Stream.GetEntries()[index + 5].AuthorId) + " " + myAlliance.Stream.GetEntries()[index + 5].AuthorName + ">>> " + myAlliance.Stream.GetEntries()[index + 5].Message + "\n"; } catch { } Logger.HandleReport($"Player {reporterName}, {reporterTag} reported player {susName}, {susTag}, in this msgs:\n`\n{text}`"); Connection.Send(new ReportUserStatusMessage() { Status = 1 }); break; } } } private void GetSeasonRewardsReceived(GetSeasonRewardsMessage message) { Connection.Send(new SeasonRewardsMessage()); } private void SetInvitesBlockedReceived(SetInvitesBlockedMessage message) { HomeMode.Avatar.DoNotDisturb = message.State; LogicInviteBlockingChangedCommand command = new LogicInviteBlockingChangedCommand(); command.State = message.State; AvailableServerCommandMessage serverCommandMessage = new AvailableServerCommandMessage(); serverCommandMessage.Command = command; Connection.Send(serverCommandMessage); if (HomeMode.Avatar.AllianceId > 0) { Alliance a = Alliances.Load(HomeMode.Avatar.AllianceId); AllianceMember m = a.GetMemberById(HomeMode.Avatar.AccountId); m.DoNotDisturb = message.State; AllianceDataMessage dataMessage = new AllianceDataMessage() { Alliance = a, IsMyAlliance = true, }; a.SendToAlliance(dataMessage); } } private void LatencyTestResultReceived(LatencyTestResultMessage message) { LatencyTestStatusMessage l = new() { Ping = Connection.Ping }; Connection.Send(l); } private void TeamPremadeChatReceived(TeamPremadeChatMessage message) { if (HomeMode.Avatar.TeamId <= 0) return; TeamEntry team = GetTeam(); if (team == null) return; QuickChatStreamEntry entry = new QuickChatStreamEntry(); entry.AccountId = HomeMode.Avatar.AccountId; entry.TargetId = message.TargetId; entry.Name = HomeMode.Avatar.Name; if (message.TargetId > 0) { TeamMember member = team.GetMember(message.TargetId); if (member != null) { entry.TargetPlayerName = member.DisplayData.Name; } } entry.MessageDataId = message.MessageDataId; entry.Unknown1 = message.Unknown1; entry.Unknown2 = message.Unknown2; team.AddStreamEntry(entry); } private void TeamChatReceived(TeamChatMessage message) { if (HomeMode.Avatar.TeamId <= 0) return; if (HomeMode.Avatar.IsCommunityBanned) return; TeamEntry team = GetTeam(); if (team == null) return; ChatStreamEntry entry = new ChatStreamEntry(); entry.AccountId = HomeMode.Avatar.AccountId; entry.Name = HomeMode.Avatar.Name; entry.Message = message.Message; team.AddStreamEntry(entry); } private void AvatarNameCheckRequestReceived(AvatarNameCheckRequestMessage message) { LogicChangeAvatarNameCommand command = new LogicChangeAvatarNameCommand(); command.Name = message.Name; command.ChangeNameCost = 0; command.Execute(HomeMode); if (HomeMode.Avatar.AllianceId >= 0) { Alliance a = Alliances.Load(HomeMode.Avatar.AllianceId); if (a == null) return; AllianceMember m = a.GetMemberById(HomeMode.Avatar.AccountId); m.DisplayData.Name = message.Name; } AvailableServerCommandMessage serverCommandMessage = new AvailableServerCommandMessage(); serverCommandMessage.Command = command; Connection.Send(serverCommandMessage); } private void TeamSetEventReceived(TeamSetEventMessage message) { if (HomeMode.Avatar.TeamId <= 0) return; TeamEntry team = GetTeam(); if (team == null) return; if (message.EventSlot == 2) return; EventData data = Events.GetEvent(message.EventSlot); if (data == null) return; team.EventSlot = message.EventSlot; team.LocationId = data.LocationId; team.TeamUpdated(); } private BattleMode SpectatedBattle; private void StopSpectateReceived(StopSpectateMessage message) { if (SpectatedBattle != null) { SpectatedBattle.RemoveSpectator(Connection.UdpSessionId); SpectatedBattle = null; } if (Connection.Home != null && Connection.Avatar != null) { OwnHomeDataMessage ohd = new OwnHomeDataMessage(); ohd.Home = Connection.Home; ohd.Avatar = Connection.Avatar; Connection.Send(ohd); } } private void StartSpectateReceived(StartSpectateMessage message) { Account data = Accounts.Load(message.AccountId); if (data == null) return; ClientAvatar avatar = data.Avatar; long battleId = avatar.BattleId; BattleMode battle = Battles.Get(battleId); if (battle == null) return; SpectatedBattle = battle; UDPSocket socket = UDPGateway.CreateSocket(); socket.Battle = battle; socket.IsSpectator = true; socket.TCPConnection = Connection; Connection.UdpSessionId = socket.SessionId; battle.AddSpectator(socket.SessionId, new UDPGameListener(socket, Connection)); StartLoadingMessage startLoading = new StartLoadingMessage(); startLoading.LocationId = battle.Location.GetGlobalId(); startLoading.TeamIndex = 0; startLoading.OwnIndex = 0; startLoading.GameMode = battle.GetGameModeVariation(); startLoading.Players.AddRange(battle.GetPlayers()); startLoading.SpectateMode = 1; Connection.Send(startLoading); UdpConnectionInfoMessage info = new UdpConnectionInfoMessage(); info.SessionId = Connection.UdpSessionId; info.ServerAddress = Configuration.Instance.UdpHost; info.ServerPort = Configuration.Instance.UdpPort; Connection.Send(info); } private void GoHomeFromOfflinePractiseReceived(GoHomeFromOfflinePractiseMessage message) { if (Connection.Home != null && Connection.Avatar != null) { if (Connection.Avatar.IsTutorialState()) { Connection.Avatar.SkipTutorial(); } if (false)//(HomeMode.Avatar.BattleStartTime != new DateTime()) { Hero h = HomeMode.Avatar.GetHero(HomeMode.Home.CharacterId); int lose = 0; int brawlerTrophies = h.Trophies; if (brawlerTrophies <= 49) { lose = 0; } else if (50 <= brawlerTrophies && brawlerTrophies <= 99) { lose = -1; } else if (100 <= brawlerTrophies && brawlerTrophies <= 199) { lose = -2; } else if (200 <= brawlerTrophies && brawlerTrophies <= 299) { lose = -3; } else if (300 <= brawlerTrophies && brawlerTrophies <= 399) { lose = -4; } else if (400 <= brawlerTrophies && brawlerTrophies <= 499) { lose = -5; } else if (500 <= brawlerTrophies && brawlerTrophies <= 599) { lose = -6; } else if (600 <= brawlerTrophies && brawlerTrophies <= 699) { lose = -7; } else if (700 <= brawlerTrophies && brawlerTrophies <= 799) { lose = -8; } else if (800 <= brawlerTrophies && brawlerTrophies <= 899) { lose = -9; } else if (900 <= brawlerTrophies && brawlerTrophies <= 999) { lose = -10; } else if (1000 <= brawlerTrophies && brawlerTrophies <= 1099) { lose = -11; } else if (1100 <= brawlerTrophies && brawlerTrophies <= 1199) { lose = -12; } else if (brawlerTrophies >= 1200) { lose = -12; } h.AddTrophies(lose); HomeMode.Home.PowerPlayGamesPlayed = Math.Max(0, HomeMode.Home.PowerPlayGamesPlayed - 1); HomeMode.Avatar.BattleStartTime = new DateTime(); Logger.BLog($"Player {LogicLongCodeGenerator.ToCode(HomeMode.Avatar.AccountId)} left battle!"); } Connection.Home.Events = Events.GetEventsById(HomeMode.Home.PowerPlayGamesPlayed, Connection.Avatar.AccountId); Connection.Avatar.Refresh(); OwnHomeDataMessage ohd = new OwnHomeDataMessage(); ohd.Home = Connection.Home; ohd.Avatar = Connection.Avatar; ShowLobbyInfo(); Connection.Send(ohd); } } /*private void TeamSetLocationReceived(TeamSetLocationMessage message) { if (HomeMode.Avatar.TeamId <= 0) return; TeamEntry team = GetTeam(); if (team == null) return; LocationData locationData = DataTables.Get(DataType.Location).GetDataByGlobalId(message.LocationId); int maxPlayersInRoom = 3; switch (locationData.GameMode) { case "Showdown": maxPlayersInRoom = 1; break; case "DuoShowdown": maxPlayersInRoom = 1; break; } if (team.Type == 1 && team.Members.Count >= maxPlayersInRoom) { TeamErrorMessage errorMessage = new TeamErrorMessage(); errorMessage.Reason = 22; Connection.Send(errorMessage); return; } team.LocationId = message.LocationId; team.Type = 1; team.TeamUpdated(); } */ private void TeamSetLocationReceived(TeamSetLocationMessage message) { if (HomeMode.Avatar.TeamId <= 0) return; TeamEntry team = GetTeam(); if (team == null) return; team.LocationId = message.LocationId; //team.CustomModifiers = message.CustomModifiers.ToList(); team.Type = 1; team.TeamUpdated(); FriendOnlineStatusEntryMessage entryMessage = new FriendOnlineStatusEntryMessage(); entryMessage.AvatarId = HomeMode.Avatar.AccountId; entryMessage.PlayerStatus = HomeMode.Avatar.PlayerStatus; entryMessage.AllianceTeamEntry = team; foreach (Friend friend in HomeMode.Avatar.Friends.ToArray()) { if (LogicServerListener.Instance.IsPlayerOnline(friend.AccountId)) { // LogicServerListener.Instance.GetGameListener(friend.AccountId).SendTCPMessage(entryMessage); } } //HomeMode.Home.EventId = message.locid; } private void ChangeAllianceSettingsReceived(ChangeAllianceSettingsMessage message) { if (HomeMode.Avatar.AllianceId <= 0) return; if (HomeMode.Avatar.AllianceRole != AllianceRole.Leader && HomeMode.Avatar.AllianceRole != AllianceRole.CoLeader) return; Alliance alliance = Alliances.Load(HomeMode.Avatar.AllianceId); if (alliance == null) return; if (message.BadgeId >= 8000000 && message.BadgeId < 8000000 + DataTables.Get(DataType.AllianceBadge).Count) { alliance.AllianceBadgeId = message.BadgeId; } else { alliance.AllianceBadgeId = 8000000; } alliance.Type = message.Type == 1 ? 1 : 3; alliance.Description = message.Description; alliance.RequiredTrophies = message.RequiredTrophies; Connection.Send(new AllianceResponseMessage() { ResponseType = 10 }); MyAllianceMessage myAlliance = new MyAllianceMessage(); myAlliance.Role = HomeMode.Avatar.AllianceRole; myAlliance.OnlineMembers = alliance.OnlinePlayers; myAlliance.AllianceHeader = alliance.Header; Connection.Send(myAlliance); } private void AllianceSearchReceived(AllianceSearchMessage message) { var list = new AllianceListMessage { query = message.SearchValue }; bool isHashtagSearch = message.SearchValue.StartsWith("#"); List alliances = Alliances.GetRankingList(message.SearchValue, isHashtagSearch); list.clubs.AddRange(alliances); Connection.Send(list); } private void KickAllianceMemberReceived(KickAllianceMemberMessage message) { if (HomeMode.Avatar.AllianceId <= 0) return; if (HomeMode.Avatar.AllianceRole == AllianceRole.Member || HomeMode.Avatar.AllianceRole == AllianceRole.None) return; Alliance alliance = Alliances.Load(HomeMode.Avatar.AllianceId); if (alliance == null) return; AllianceMember member = alliance.GetMemberById(message.AccountId); if (member == null) return; ClientAvatar avatar = Accounts.Load(message.AccountId).Avatar; if (alliance.getRoleVector(avatar.AllianceRole, (AllianceRole)HomeMode.Avatar.AllianceRole)) return; alliance.Members.Remove(member); avatar.AllianceId = -1; AllianceStreamEntry entry = new AllianceStreamEntry(); entry.AuthorId = HomeMode.Avatar.AccountId; entry.AuthorName = HomeMode.Avatar.Name; entry.Id = ++alliance.Stream.EntryIdCounter; entry.PlayerId = avatar.AccountId; entry.PlayerName = avatar.Name; entry.Type = 4; entry.Event = 1; // kicked entry.AuthorRole = HomeMode.Avatar.AllianceRole; alliance.AddStreamEntry(entry); AllianceResponseMessage response = new AllianceResponseMessage(); response.ResponseType = 70; Connection.Send(response); if (LogicServerListener.Instance.IsPlayerOnline(avatar.AccountId)) { LogicServerListener.Instance.GetGameListener(avatar.AccountId).SendTCPMessage(new AllianceResponseMessage() { ResponseType = 100 }); LogicServerListener.Instance.GetGameListener(avatar.AccountId).SendTCPMessage(new MyAllianceMessage()); } } private void TeamSetMemberReadyReceived(TeamSetMemberReadyMessage message) { TeamEntry team = Teams.Get(HomeMode.Avatar.TeamId); if (team == null) return; TeamMember member = team.GetMember(HomeMode.Avatar.AccountId); if (member == null) return; if (team.Type == 0 && team.CheckBrawlers(HomeMode.Avatar.AccountId)) return; if (HomeMode.Home.Character.Disabled) { Connection.Send(new OutOfSyncMessage()); return; } member.IsReady = message.IsReady; team.TeamUpdated(); if (!team.IsEveryoneReady()) return; Teams.StartGame(team); if (true) return; /*BattleMode battle = new BattleMode(15000032); battle.Id = Battles.Add(battle); BattlePlayer player = BattlePlayer.Create(Connection.Home, Connection.Avatar, 0, 0); player.CharacterId = Connection.Home.CharacterId; Hero hero = Connection.Avatar.GetHero(Connection.Home.CharacterId); if (hero != null) { player.Trophies = hero.Trophies; player.HighestTrophies = hero.HighestTrophies; } else { player.Trophies = 0; player.HighestTrophies = 0; } UDPSocket socket = UDPGateway.CreateSocket(); socket.TCPConnection = Connection; socket.Battle = battle; Connection.UdpSessionId = socket.SessionId; battle.AddPlayer(player, Connection.UdpSessionId); battle.AddGameObjects(); StartLoadingMessage startLoading = new StartLoadingMessage(); startLoading.LocationId = battle.Location.GetGlobalId(); startLoading.TeamIndex = player.TeamIndex; startLoading.OwnIndex = player.PlayerIndex; startLoading.GameMode = battle.GetGameModeVariation(); Connection.Avatar.UdpSessionId = Connection.UdpSessionId; startLoading.Players.AddRange(battle.GetPlayers()); Connection.Send(startLoading); battle.Start();*/ } private void TeamChangeMemberSettingsReceived(TeamChangeMemberSettingsMessage message) { ; } private void TeamMemberStatusReceived(TeamMemberStatusMessage message) { if (HomeMode == null) return; if (message.Status < 0) return; TeamEntry team = Teams.Get(HomeMode.Avatar.TeamId); if (team == null) return; TeamMember member = team.GetMember(HomeMode.Avatar.AccountId); if (member == null) return; member.State = message.Status; team.TeamUpdated(); } private void TeamInvitationResponseReceived(TeamInvitationResponseMessage message) { bool isAccept = message.Response == 1; TeamEntry team = Teams.Get(message.TeamId); if (team == null) return; TeamInviteEntry invite = team.GetInviteById(HomeMode.Avatar.AccountId); if (invite == null) return; team.Invites.Remove(invite); if (isAccept) { TeamMember member = new TeamMember(); member.AccountId = HomeMode.Avatar.AccountId; member.CharacterId = HomeMode.Home.CharacterId; member.DisplayData = new PlayerDisplayData(HomeMode.Home.HasPremiumPass, HomeMode.Home.ThumbnailId, HomeMode.Home.NameColorId, HomeMode.Avatar.Name); Hero hero = HomeMode.Avatar.GetHero(HomeMode.Home.CharacterId); member.HeroTrophies = hero.Trophies; member.HeroHighestTrophies = hero.HighestTrophies; member.HeroLevel = hero.PowerLevel + 1; member.IsOwner = false; member.State = 0; team.Members.Add(member); HomeMode.Avatar.TeamId = team.Id; } team.TeamUpdated(); } private TeamEntry GetTeam() { return Teams.Get(HomeMode.Avatar.TeamId); } private void TeamInviteReceived(TeamInviteMessage message) { TeamEntry team = GetTeam(); if (team == null) return; Account data = Accounts.Load(message.AvatarId); if (data == null) return; TeamInviteEntry entry = new TeamInviteEntry(); entry.Slot = message.Team; entry.Name = data.Avatar.Name; entry.Id = message.AvatarId; entry.InviterId = HomeMode.Avatar.AccountId; team.Invites.Add(entry); team.TeamUpdated(); LogicGameListener gameListener = LogicServerListener.Instance.GetGameListener(message.AvatarId); if (gameListener != null) { TeamInvitationMessage teamInvitationMessage = new TeamInvitationMessage(); teamInvitationMessage.TeamId = team.Id; Friend friendEntry = new Friend(); friendEntry.AccountId = HomeMode.Avatar.AccountId; friendEntry.DisplayData = new PlayerDisplayData(HomeMode.Home.HasPremiumPass, HomeMode.Home.ThumbnailId, HomeMode.Home.NameColorId, HomeMode.Avatar.Name); friendEntry.Trophies = HomeMode.Avatar.Trophies; teamInvitationMessage.Unknown = 1; teamInvitationMessage.FriendEntry = friendEntry; gameListener.SendTCPMessage(teamInvitationMessage); } } private void TeamClearInviteMessageReceived(TeamClearInviteMessage message) { TeamEntry team = GetTeam(); if (team == null) return; TeamInviteEntry inviteToRemove = team.Invites.FirstOrDefault(invite => invite.Slot == message.Slot); if (inviteToRemove != null) { team.Invites.Remove(inviteToRemove); team.TeamUpdated(); } } private void TeamLeaveReceived(TeamLeaveMessage message) { if (HomeMode.Avatar.TeamId <= 0) return; TeamEntry team = Teams.Get(HomeMode.Avatar.TeamId); if (team == null) { Logger.Print("TeamLeave - Team is NULL!"); HomeMode.Avatar.TeamId = -1; Connection.Send(new TeamLeftMessage()); return; } TeamMember entry = team.GetMember(HomeMode.Avatar.AccountId); if (entry == null) return; HomeMode.Avatar.TeamId = -1; team.Members.Remove(entry); Connection.Send(new TeamLeftMessage()); team.TeamUpdated(); foreach (TeamMember member in team.Members) { member.IsReady = false; } if (team.Members.Count == 0) { Teams.Remove(team.Id); } } private void TeamCreateReceived(TeamCreateMessage message) { TeamEntry teamEntry = Teams.Create(); teamEntry.Type = message.TeamType; EventData firstEvent = Events.GetEvent(1); teamEntry.LocationId = firstEvent != null ? firstEvent.LocationId : 0; teamEntry.EventSlot = 1; TeamMember teamMember = new TeamMember(); teamMember.AccountId = HomeMode.Avatar.AccountId; teamMember.CharacterId = HomeMode.Home.CharacterId; teamMember.DisplayData = new PlayerDisplayData(HomeMode.Home.HasPremiumPass, HomeMode.Home.ThumbnailId, HomeMode.Home.NameColorId, HomeMode.Avatar.Name); // teamMember.homeMode = HomeMode; Hero hero = HomeMode.Avatar.GetHero(HomeMode.Home.CharacterId); teamMember.HeroTrophies = hero.Trophies; teamMember.HeroHighestTrophies = hero.HighestTrophies; teamMember.HeroLevel = hero.PowerLevel + 1; teamMember.Starpower = 0; teamMember.Gadget = 0; if (hero.SelectedStarPowerId > 0) { CardData starPower = DataTables.Get(DataType.Card).GetDataByGlobalId(GlobalId.CreateGlobalId(23, hero.SelectedStarPowerId)); if (starPower != null) teamMember.Starpower = starPower.GetGlobalId(); } if (hero.SelectedGadgetId > 0) { CardData gadget = DataTables.Get(DataType.Card).GetDataByGlobalId(GlobalId.CreateGlobalId(23, hero.SelectedGadgetId)); if (gadget != null) teamMember.Gadget = gadget.GetGlobalId(); } teamMember.SkinId = GlobalId.CreateGlobalId(29, hero.SelectedSkinId); teamMember.IsOwner = true; teamMember.State = 0; teamEntry.Members.Add(teamMember); TeamMessage teamMessage = new TeamMessage(); teamMessage.Team = teamEntry; HomeMode.Avatar.TeamId = teamEntry.Id; Connection.Send(teamMessage); FriendOnlineStatusEntryMessage friendOnlineStatusEntryMessage = new FriendOnlineStatusEntryMessage(); friendOnlineStatusEntryMessage.AvatarId = HomeMode.Avatar.AccountId; friendOnlineStatusEntryMessage.PlayerStatus = HomeMode.Avatar.PlayerStatus; friendOnlineStatusEntryMessage.AllianceTeamEntry = teamEntry; Friend[] array = HomeMode.Avatar.Friends.ToArray(); foreach (Friend friend in array) { if (LogicServerListener.Instance.IsPlayerOnline(friend.AccountId)) { // LogicServerListener.Instance.GetGameListener(friend.AccountId).SendTCPMessage(friendOnlineStatusEntryMessage); } } } /* private void TeamCreateReceived(TeamCreateMessage message) { //return; TeamEntry team = Teams.Create(); team.Type = message.TeamType; team.LocationId = Events.GetEvents()[0].LocationId; team.EventSlot = 1; TeamMember member = new TeamMember(); member.AccountId = HomeMode.Avatar.AccountId; member.CharacterId = HomeMode.Home.CharacterId; member.DisplayData = new PlayerDisplayData(HomeMode.Home.HasPremiumPass, HomeMode.Home.ThumbnailId, HomeMode.Home.NameColorId, HomeMode.Avatar.Name); // member.homeMode = homeMode; Hero hero = HomeMode.Avatar.GetHero(HomeMode.Home.CharacterId); member.HeroTrophies = hero.Trophies; member.HeroHighestTrophies = hero.HighestTrophies; member.HeroLevel = hero.PowerLevel + 1; member.IsOwner = true; member.State = 0; team.Members.Add(member); TeamMessage teamMessage = new TeamMessage(); teamMessage.Team = team; HomeMode.Avatar.TeamId = team.Id; Connection.Send(teamMessage); FriendOnlineStatusEntryMessage entryMessage = new FriendOnlineStatusEntryMessage(); entryMessage.AvatarId = HomeMode.Avatar.AccountId; entryMessage.PlayerStatus = HomeMode.Avatar.PlayerStatus; entryMessage.AllianceTeamEntry = team; foreach (Friend friend in HomeMode.Avatar.Friends.ToArray()) { if (LogicServerListener.Instance.IsPlayerOnline(friend.AccountId)) { LogicServerListener.Instance.GetGameListener(friend.AccountId).SendTCPMessage(entryMessage); } } } */ private void AcceptFriendReceived(AcceptFriendMessage message) { Account data = Accounts.Load(message.AvatarId); if (data == null) return; { Friend entry = HomeMode.Avatar.GetRequestFriendById(message.AvatarId); if (entry == null) return; Friend oldFriend = HomeMode.Avatar.GetAcceptedFriendById(message.AvatarId); if (oldFriend != null) { HomeMode.Avatar.Friends.Remove(entry); Connection.Send(new OutOfSyncMessage()); return; } entry.FriendReason = 0; entry.FriendState = 4; FriendListUpdateMessage update = new FriendListUpdateMessage(); update.Entry = entry; Connection.Send(update); } { ClientAvatar avatar = data.Avatar; Friend entry = avatar.GetFriendById(HomeMode.Avatar.AccountId); if (entry == null) return; entry.FriendState = 4; entry.FriendReason = 0; if (LogicServerListener.Instance.IsPlayerOnline(avatar.AccountId)) { FriendListUpdateMessage update = new FriendListUpdateMessage(); update.Entry = entry; LogicServerListener.Instance.GetGameListener(avatar.AccountId).SendTCPMessage(update); } } } private void RemoveFriendReceived(RemoveFriendMessage message) { Account data = Accounts.Load(message.AvatarId); if (data == null) return; ClientAvatar avatar = data.Avatar; Friend MyEntry = HomeMode.Avatar.GetFriendById(message.AvatarId); if (MyEntry == null) return; MyEntry.FriendState = 0; HomeMode.Avatar.Friends.Remove(MyEntry); FriendListUpdateMessage update = new FriendListUpdateMessage(); update.Entry = MyEntry; Connection.Send(update); Friend OtherEntry = avatar.GetFriendById(HomeMode.Avatar.AccountId); if (OtherEntry == null) return; OtherEntry.FriendState = 0; avatar.Friends.Remove(OtherEntry); if (LogicServerListener.Instance.IsPlayerOnline(avatar.AccountId)) { FriendListUpdateMessage update2 = new FriendListUpdateMessage(); update2.Entry = OtherEntry; LogicServerListener.Instance.GetGameListener(avatar.AccountId).SendTCPMessage(update2); } } private void CreatePlayerMapReceived(CreatePlayerMapMessage message) { if (HomeMode.Avatar.PlayerMaps == null) { HomeMode.Avatar.PlayerMaps = new List(); } LogicPlayerMap map = new LogicPlayerMap { MapId = System.Security.Cryptography.RandomNumberGenerator.GetInt32(1, int.MaxValue), AccountId = HomeMode.Avatar.AccountId, MapName = message.MapName, AvatarName = HomeMode.Avatar.Name, GameModeVariation = message.GameModeVariation, MapEnvironmentData = message.MapEnvironmentData, CompressedMapData = new LogicCompressedString(string.Empty), State = 1 }; HomeMode.Avatar.PlayerMaps.Add(map); Logger.WriteServerLog($"[PlayerMap] Created MapId={map.MapId}, GameModeVariation={map.GameModeVariation}, MapEnvironmentData={map.MapEnvironmentData} (classId={Supercell.Laser.Logic.Data.Helper.GlobalId.GetClassId(map.MapEnvironmentData)}, instanceId={Supercell.Laser.Logic.Data.Helper.GlobalId.GetInstanceId(map.MapEnvironmentData)})"); CreatePlayerMapResponseMessage response = new CreatePlayerMapResponseMessage { ErrorCode = 0, PlayerMap = map }; Connection.Send(response); PlayerMapManager.SyncPlayerMap(map); Account account = Accounts.Load(HomeMode.Avatar.AccountId); if (account != null) { account.Avatar = HomeMode.Avatar; Accounts.Save(account); } } private void DeletePlayerMapReceived(DeletePlayerMapMessage message) { int errorCode = 1; if (HomeMode.Avatar.PlayerMaps != null) { LogicPlayerMap map = HomeMode.Avatar.PlayerMaps.Find(m => m.MapId == message.MapId); if (map != null) { HomeMode.Avatar.PlayerMaps.Remove(map); errorCode = 0; } } Connection.Send(new DeletePlayerMapResponseMessage { ErrorCode = errorCode, MapId = message.MapId }); if (errorCode == 0) PlayerMapManager.DeletePlayerMap(message.MapId); if (errorCode == 0) { Account account = Accounts.Load(HomeMode.Avatar.AccountId); if (account != null) { account.Avatar = HomeMode.Avatar; Accounts.Save(account); } } } private void GetPlayerMapsReceived(GetPlayerMapsMessage message) { PlayerMapsMessage response = new PlayerMapsMessage(); if (HomeMode.Avatar.PlayerMaps != null) { response.PlayerMaps = HomeMode.Avatar.PlayerMaps; } Connection.Send(response); } private void UpdatePlayerMapReceived(UpdatePlayerMapMessage message) { int errorCode = 1; LogicPlayerMap map = null; if (HomeMode.Avatar.PlayerMaps != null) { map = HomeMode.Avatar.PlayerMaps.Find(m => m.MapId == message.MapId); if (map != null) { map.CompressedMapData = message.CompressedMapData; errorCode = 0; } } Connection.Send(new UpdatePlayerMapResponseMessage { ErrorCode = errorCode, MapId = message.MapId }); if(map != null) PlayerMapManager.SyncPlayerMap(map); if (errorCode == 0) { Account account = Accounts.Load(HomeMode.Avatar.AccountId); if (account != null) { account.Avatar = HomeMode.Avatar; Accounts.Save(account); } } } private void SubmitPlayerMapReceived(SubmitPlayerMapMessage message) { int errorCode = 1; int mapState = 0; LogicPlayerMap map = null; if (HomeMode.Avatar.PlayerMaps != null) { map = HomeMode.Avatar.PlayerMaps.Find(m => m.MapId == message.MapId); if (map != null) { map.State = 2; mapState = map.State; errorCode = 0; } } Connection.Send(new SubmitPlayerMapResponseMessage { ErrorCode = errorCode, MapId = message.MapId, MapState = mapState }); if(map != null) PlayerMapManager.SyncPlayerMap(map); if (errorCode == 0) { Account account = Accounts.Load(HomeMode.Avatar.AccountId); if (account != null) { account.Avatar = HomeMode.Avatar; Accounts.Save(account); } } } private void PublishPlayerMapReceived(PublishPlayerMapMessage message) { int errorCode = 1; int mapState = 0; LogicPlayerMap map = null; if (HomeMode.Avatar.PlayerMaps != null) { map = HomeMode.Avatar.PlayerMaps.Find(m => m.MapId == message.MapId); if (map != null) { map.State = 3; mapState = map.State; errorCode = 0; } } Connection.Send(new PublishPlayerMapResponseMessage { ErrorCode = errorCode, MapId = message.MapId, MapState = mapState }); if(map != null) PlayerMapManager.SyncPlayerMap(map); if (errorCode == 0) { Account account = Accounts.Load(HomeMode.Avatar.AccountId); if (account != null) { account.Avatar = HomeMode.Avatar; Accounts.Save(account); } } } private void ChangePlayerMapNameReceived(ChangePlayerMapNameMessage message) { int errorCode = 1; LogicPlayerMap map = null; if (HomeMode.Avatar.PlayerMaps != null) { map = HomeMode.Avatar.PlayerMaps.Find(m => m.MapId == message.MapId); if (map != null) { map.MapName = message.MapName; errorCode = 0; } } Connection.Send(new ChangePlayerMapNameResponseMessage { ErrorCode = errorCode, MapId = message.MapId, MapName = message.MapName }); if(map != null) PlayerMapManager.SyncPlayerMap(map); if (errorCode == 0) { Account account = Accounts.Load(HomeMode.Avatar.AccountId); if (account != null) { account.Avatar = HomeMode.Avatar; Accounts.Save(account); } } } private void EnterMapEditorReceived(EnterMapEditorMessage message) { } private void GoHomeFromMapEditorReceived(GoHomeFromMapEditorMessage message) { if (Connection.Home != null && Connection.Avatar != null) { OwnHomeDataMessage ohd = new OwnHomeDataMessage(); ohd.Home = Connection.Home; ohd.Avatar = Connection.Avatar; Connection.Send(ohd); } } private void TeamSetPlayerMapReceived(TeamSetPlayerMapMessage message) { TeamEntry team = Teams.Get(HomeMode.Avatar.TeamId); if (team == null) return; LogicPlayerMap map = HomeMode.Avatar.PlayerMaps?.Find(m => m.MapId == message.MapId); if (map == null) return; Logger.WriteServerLog($"[PlayerMap] TeamSetPlayerMapReceived: MapId={map.MapId}, GameModeVariation={map.GameModeVariation}, MapEnvironmentData={map.MapEnvironmentData} (classId={Supercell.Laser.Logic.Data.Helper.GlobalId.GetClassId(map.MapEnvironmentData)}, instanceId={Supercell.Laser.Logic.Data.Helper.GlobalId.GetInstanceId(map.MapEnvironmentData)}), HasMapData={map.CompressedMapData?.HasString()}, MapDataLength={map.CompressedMapData?.Length}"); if (map.CompressedMapData != null && map.CompressedMapData.HasString()) { try { Supercell.Laser.Titan.Util.ZLibHelper.DecompressInMySQLFormat(map.CompressedMapData.Data, out byte[] decompressed); string decoded = System.Text.Encoding.UTF8.GetString(decompressed); Logger.WriteServerLog($"[PlayerMap] Decompressed map data ({decompressed.Length} bytes): {decoded.Replace("\n", "\\n")}"); } catch (Exception ex) { Logger.WriteServerLog($"[PlayerMap] Failed to decompress map data: {ex.Message}"); } } team.PlayerMap = new BattlePlayerMap { MapId = map.MapId, MapName = map.MapName, GMV = map.GameModeVariation, MapEnvironmentData = map.MapEnvironmentData, MapData = map.CompressedMapData, AccountId = map.AccountId, AvatarName = HomeMode.Avatar.Name, State = map.State }; team.CustomModifiers = message.Modifiers; TeamMessage teamMessage = new TeamMessage(); teamMessage.Team = team; foreach (TeamMember teamMember in team.Members) { Session memberSession = Sessions.GetSession(teamMember.AccountId); if (memberSession != null) { memberSession.Connection.Send(teamMessage); } } } private void SignoffPlayerMapReceived(SignoffPlayerMapMessage message) { LogicPlayerMap map = HomeMode.Avatar.PlayerMaps?.Find(m => m.MapId == message.MapId); if (map != null) { map.FriendlySignoffCount++; } Account ownerData = Accounts.Load(message.MapOwnerAccountId); if (ownerData == null) return; LogicPlayerMap ownerMap = ownerData.Avatar.PlayerMaps?.Find(m => m.MapId == message.MapId); if (ownerMap != null) { ownerMap.FriendlySignoffCount++; } } private void ReportPlayerMapReceived(ReportPlayerMapMessage message) { int resultCode = 0; string mapName = string.Empty; if (HomeMode.Avatar.PlayerMaps != null) { LogicPlayerMap map = HomeMode.Avatar.PlayerMaps.Find(m => m.MapId == message.MapId); if (map != null) { mapName = map.MapName; } } Connection.Send(new ReportPlayerMapResponseMessage { ResultCode = resultCode, MapId = message.MapId, MapName = mapName }); } private void AddFriendReceived(AddFriendMessage message) { Account data = Accounts.Load(message.AvatarId); if (data == null) { Connection.Send(new AddFriendFailedMessage { Reason = 5 }); return; } if (data.Avatar.AccountId == HomeMode.Avatar.AccountId) { // 2 - too many invites // 4 - invite urself // 5 doesnt exist // 7 - u have too many friends, rm // 8 - u have too many friends Connection.Send(new AddFriendFailedMessage { Reason = 4 }); return; } if (data.Home.BlockFriendRequests) { Connection.Send(new AddFriendFailedMessage { Reason = 0 }); return; } ClientAvatar avatar = data.Avatar; Friend requestEntry = HomeMode.Avatar.GetFriendById(message.AvatarId); if (requestEntry != null) { return; } else { Friend friendEntry = new Friend(); friendEntry.AccountId = HomeMode.Avatar.AccountId; friendEntry.DisplayData = new PlayerDisplayData(HomeMode.Home.HasPremiumPass, HomeMode.Home.ThumbnailId, HomeMode.Home.NameColorId, HomeMode.Avatar.Name); friendEntry.FriendReason = message.Reason; friendEntry.FriendState = 3; avatar.Friends.Add(friendEntry); Friend request = new Friend(); request.AccountId = avatar.AccountId; request.DisplayData = new PlayerDisplayData(data.Home.HasPremiumPass, data.Home.ThumbnailId, data.Home.NameColorId, data.Avatar.Name); request.FriendReason = 0; request.FriendState = 2; HomeMode.Avatar.Friends.Add(request); if (LogicServerListener.Instance.IsPlayerOnline(message.AvatarId)) { var gameListener = LogicServerListener.Instance.GetGameListener(message.AvatarId); FriendListUpdateMessage update = new FriendListUpdateMessage(); update.Entry = friendEntry; gameListener.SendTCPMessage(update); } FriendListUpdateMessage update2 = new FriendListUpdateMessage(); update2.Entry = request; Connection.Send(update2); } } private void AskForFriendListReceived(AskForFriendListMessage message) { FriendListMessage friendList = new FriendListMessage(); friendList.Friends = HomeMode.Avatar.Friends.ToArray(); Connection.Send(friendList); } private void RequestSyncSSIDReceived(RequestSyncSSID message) { if (message.AuthPass != "Gf9kTq3LmZx1Aa4JvR6pYbXsQc5WnVtE") { return; } foreach (KeyValuePair pair in message.Requests) { if (!Sessions.RegistratedSSID.ContainsKey(pair.Key)) { Sessions.RegistratedSSID.Add(pair.Key, pair.Value); Logger.WriteServerLog("VexApi.RequestSynsSSID data: " + Sessions.RegistratedSSID[pair.Key]); } else { Sessions.RegistratedSSID[pair.Key] = pair.Value; Logger.WriteServerLog("VexApi.RequestSynsSSID data: " + Sessions.RegistratedSSID[pair.Key]); } } foreach (string k in message.DisposeRequests) { Sessions.RegistratedSSID.Remove(k); } Connection.Send(new SyncSSIDResponce() { Requests = Sessions.RequestedSSID, RecAccs = Sessions.LeaveJoin }); Sessions.RequestedSSID = new(); Sessions.LeaveJoin = new(); } private void RequestSynsCodeSSIDReceived(RequestCodeSSID message) { if (message.AuthPass != "Gf9kTq3LmZx1Aa4JvR6pYbXsQc5WnVtE") { return; } if (!Sessions.RequestedSSID.ContainsKey(message.AccountTag)) { SynsCodeSSIDResponce response = new SynsCodeSSIDResponce(); response.code = 111999; Connection.Send(response); } else { SynsCodeSSIDResponce response = new SynsCodeSSIDResponce(); response.code = int.Parse(Sessions.RequestedSSID[message.AccountTag]); Connection.Send(response); } } private void RequestMaintenanceReceived(RequestMaintenance message) { if (message.AuthPass != "Gf9kTq3LmZx1Aa4JvR6pYbXsQc5WnVtE") { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"dsadas")); return; } Sessions.StartShutdown(); AccountCache.SaveAll(); AllianceCache.SaveAll(); AccountCache.Started = false; AllianceCache.Started = false; Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes("Done!")); } private void RequestSaveAllReceived(RequestSaveAll message) { if (message.AuthPass != "Gf9kTq3LmZx1Aa4JvR6pYbXsQc5WnVtE") { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"dsadas")); return; } AccountCache.SaveAll(); AllianceCache.SaveAll(); Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes("Done!")); } private void RequestDBChangesReceived(RequestDBChanges message) { if (message.AuthPass != "Gf9kTq3LmZx1Aa4JvR6pYbXsQc5WnVtE") { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"dsadas")); return; } string[] cmd = message.Message.Substring(1).Split(' '); if (cmd[0] == "reloadEvents") { Logger.WriteServerLog("Events reload"); Events.Init(); } if (cmd[0] == "addDonateOfferSkin") { if (cmd.Length != 3) { Logger.WriteServerLog("Error: Invalid usage"); return; } long accountsLastId = Accounts.GetMaxAvatarId(); for (int accid = 1; accid <= accountsLastId; accid++) { Account donateOfferAccount = Accounts.LoadNoChache(accid); if (donateOfferAccount == null) continue; try { if (donateOfferAccount.Home.UnlockedSkins.Contains(int.Parse(cmd[1]))) continue; SkinData skin = DataTables.Get(DataType.Skin).GetDataByGlobalId(int.Parse(cmd[1])); SkinConfData skinConf = DataTables.Get(DataType.SkinConf).GetData(skin.Conf); CharacterData character = DataTables.Get(DataType.Character).GetData(skinConf.Character); if (donateOfferAccount.Avatar.HasHero(character.GetGlobalId()) == false) { return; } // Fix 12: Не добавляем дубликат — если бандл с этим скином уже есть // в списке офферов, пропускаем. Без этой проверки повторный вызов // addDonateOfferSkin плодит копии бандла в каждом аккаунте, // бесконечно раздувая Home.OfferBundles. int skinInstanceId = GlobalId.GetInstanceId(int.Parse(cmd[1]) - 29000000); bool skinAlreadyOffered = donateOfferAccount.Home.OfferBundles.Any(b => b.Items.Any(o => o.Type == ShopItem.Skin && o.SkinDataId == skinInstanceId)); if (skinAlreadyOffered) continue; OfferBundle bundle = new OfferBundle(); bundle.Title = "Новый скин" + "|" + cmd[2] + "₽"; bundle.IsDailyDeals = false; bundle.EndTime = DateTime.UtcNow.AddDays(7); // tomorrow at 8:00 utc (11:00 MSK) bundle.Cost = 99999; bundle.Currency = 999; Offer offer = new Offer(ShopItem.Skin, 1); offer.SkinDataId = skinInstanceId; bundle.Items.Add(offer); donateOfferAccount.Home.OfferBundles.Add(bundle); Accounts.Save(donateOfferAccount); } catch { } } } if (cmd[0] == "removeAllOffers") { long accountsLastId = Accounts.GetMaxAvatarId(); for (int accid = 1; accid <= accountsLastId; accid++) { Account donateOfferAccount = Accounts.LoadNoChache(accid); if (donateOfferAccount == null) continue; try { donateOfferAccount.Home.LastRotateDate = new DateTime(2025, 12, 1, 8, 0, 0); // Fix 12: Раскомментирован сброс списка офферов — без этого // removeAllOffers только сбрасывала дату ротации, но не удаляла // накопившиеся бандлы из Home.OfferBundles каждого аккаунта. donateOfferAccount.Home.OfferBundles = new List(); Accounts.Save(donateOfferAccount); } catch { } } } if (cmd[0] == "addDonateOfferBrawler") { if (cmd.Length != 3) { Logger.WriteServerLog("Error: Invalid usage"); return; } long accountsLastId = Accounts.GetMaxAvatarId(); for (int accid = 1; accid <= accountsLastId; accid++) { Account donateOfferAccount = Accounts.LoadNoChache(accid); if (donateOfferAccount == null) continue; try { if (donateOfferAccount.Avatar.HasHero(int.Parse(cmd[1]))) continue; CharacterData character = DataTables.Get(DataType.Character).GetDataByGlobalId(int.Parse(cmd[1])); // Fix 12: Проверка дубликата перед добавлением бандла. // Повторный вызов addDonateOfferBrawler не должен плодить // одинаковые бандлы в списке офферов одного аккаунта. int brawlerInstanceId = GlobalId.GetInstanceId(int.Parse(cmd[1])); bool brawlerAlreadyOffered = donateOfferAccount.Home.OfferBundles.Any(b => b.Items.Any(o => o.Type == ShopItem.GuaranteedHero && o.ItemDataId == brawlerInstanceId)); if (brawlerAlreadyOffered) continue; OfferBundle bundle = new OfferBundle(); bundle.Title = "Ранний Доступ" + "|" + cmd[2] + "₽"; bundle.IsDailyDeals = false; bundle.EndTime = DateTime.UtcNow.AddDays(7); // tomorrow at 8:00 utc (11:00 MSK) bundle.Cost = 99999; bundle.Currency = 999; Offer offer = new Offer(ShopItem.GuaranteedHero, 1); offer.ItemDataId = brawlerInstanceId; bundle.Items.Add(offer); donateOfferAccount.Home.OfferBundles.Add(bundle); Accounts.Save(donateOfferAccount); } catch { } } } if (cmd[0] == "giveprem") { if (cmd.Length != 2) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid usage")); Logger.WriteServerLog("]"); return; } bool sc = false; long id = 0; if (cmd[1].StartsWith('#')) { id = LogicLongCodeGenerator.ToId(cmd[1]); } else { sc = true; id = long.Parse(cmd[1]); } Account account = Accounts.Load(id); if (account == null) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid tag: {id}")); return; } if (account.Home.PremiumEndTime < DateTime.UtcNow) { account.Home.PremiumEndTime = DateTime.UtcNow.AddMonths(1); } else { account.Home.PremiumEndTime = account.Home.PremiumEndTime.AddMonths(1); } account.Avatar.PremiumLevel = 1; Notification n = new Notification { Id = 89, DonationCount = 80, TimePassed = DateTime.UtcNow, MessageEntry = $"VIP-статус активирован/продлён до {account.Home.PremiumEndTime} UTC, спасибо за поддержку сервера!" }; account.Home.NotificationFactory.Add(n); LogicAddNotificationCommand acm = new() { Notification = n }; AvailableServerCommandMessage asm = new AvailableServerCommandMessage(); asm.Command = acm; if (Sessions.IsSessionActive(id)) { var session = Sessions.GetSession(id); session.GameListener.SendTCPMessage(asm); } string d = sc ? LogicLongCodeGenerator.ToCode(long.Parse(cmd[1])) : cmd[1]; Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Done: set vip status for {d} activated/extended to {account.Home.PremiumEndTime} UTC!")); } else if (cmd[0] == "chat_unmute") { if (cmd.Length != 3) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid usage")); Logger.WriteServerLog("]"); return; } bool sc = false; long id = 0; if (cmd[1].StartsWith('#')) { id = LogicLongCodeGenerator.ToId(cmd[1]); } else { sc = true; id = long.Parse(cmd[1]); } Account account = Accounts.Load(id); if (account == null) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid tag: {id}")); return; } account.Home.ChatBanEndTime = DateTime.MinValue; Notification wn = new Notification { Id = 81, TimePassed = DateTime.UtcNow, MessageEntry = $"Блокировка чата твоего аккаунта была успешно снята.\nТеперь ты можешь снова общаться без ограничений." }; account.Home.NotificationFactory.Add(wn); if (LogicServerListener.Instance.IsPlayerOnline(account.Avatar.AccountId)) { LogicServerListener.Instance.GetGameListener(account.Avatar.AccountId).SendTCPMessage(new AvailableServerCommandMessage { Command = new LogicAddNotificationCommand() { Notification = wn } }); } string d = sc ? LogicLongCodeGenerator.ToCode(long.Parse(cmd[1])) : cmd[1]; Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Done: unmuted {d}")); } else if (cmd[0] == "chat_mute") { if (cmd.Length != 3) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid usage")); Logger.WriteServerLog("]"); return; } bool sc = false; long id = 0; if (cmd[1].StartsWith('#')) { id = LogicLongCodeGenerator.ToId(cmd[1]); } else { sc = true; id = long.Parse(cmd[1]); } Account account = Accounts.Load(id); if (account == null) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid tag: {id}")); return; } account.Home.ChatBanEndTime = DateTime.UtcNow.AddDays(int.Parse(cmd[2])); Notification wwn = new Notification { Id = 81, TimePassed = DateTime.UtcNow, MessageEntry = $"Ваш аккаунт был временно отключён в чате за нарушение правил.\nБлокировка действует до {account.Home.ChatBanEndTime} UTC.\nОбратите внимание, что повторные нарушения могут привести к постоянной блокировке чата." }; account.Home.NotificationFactory.Add(wwn); if (LogicServerListener.Instance.IsPlayerOnline(account.Avatar.AccountId)) { LogicServerListener.Instance.GetGameListener(account.Avatar.AccountId).SendTCPMessage(new AvailableServerCommandMessage { Command = new LogicAddNotificationCommand() { Notification = wwn } }); } string d = sc ? LogicLongCodeGenerator.ToCode(long.Parse(cmd[1])) : cmd[1]; Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Done: muted {d} for {int.Parse(cmd[2])}d")); } else if (cmd[0] == "resetBrawlPass") { long lastAccId1 = Accounts.GetMaxAvatarId(); for (int accid = 1; accid <= lastAccId1; accid++) { Account thisAcc = Accounts.LoadNoChache(accid); if (thisAcc == null) continue; thisAcc.Home.HasPremiumPass = false; thisAcc.Home.BrawlPassProgress = 0; thisAcc.Home.BrawlPassTokens = 0; thisAcc.Home.PremiumPassProgress = 0; Accounts.Save(thisAcc); Logger.WriteServerLog($"[resetBrawlPass] accid={accid}"); } } else if (cmd[0] == "resetseason") { long lastAccId = Accounts.GetMaxAvatarId(); for (int accid = 1; accid <= lastAccId; accid++) { Account thisAcc = Accounts.LoadNoChache(accid); if (thisAcc == null) continue; if (thisAcc.Avatar.Trophies >= 550) { List hhh = new(); List ht = new(); List htr = new(); List sa = new(); int[] StarPointsTrophiesStart = { 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000, 1050, 1100, 1150, 1200, 1250, 1300, 1350, 1400 }; int[] StarPointsTrophiesEnd = { 599, 649, 699, 749, 799, 849, 899, 949, 999, 1049, 1099, 1149, 1199, 1249, 1299, 1349, 1399, 1000000 }; int[] StarPointsSeasonRewardAmount = { 70, 120, 160, 200, 220, 240, 260, 280, 300, 320, 340, 360, 380, 400, 420, 440, 460, 480 }; int[] StarPointsTrophiesInReset = { 549, 599, 649, 699, 749, 799, 849, 899, 924, 949, 974, 1024, 1049, 1074, 1099, 1124, 1149, 1174 }; foreach (Hero h in thisAcc.Avatar.Heroes) { if (h.Trophies >= StarPointsTrophiesStart[0] * 10) { hhh.Add(h.CharacterId); ht.Add(h.Trophies); int i = 0; while (true) { if (h.Trophies >= StarPointsTrophiesStart[i] * 10 && h.Trophies <= StarPointsTrophiesEnd[i] * 10) { if (StarPointsTrophiesStart[i] * 10 != 14000) { htr.Add(h.Trophies - StarPointsTrophiesInReset[i] * 10); h.Trophies = StarPointsTrophiesInReset[i] * 10; sa.Add(StarPointsSeasonRewardAmount[i]); } else { int b = h.Trophies - 14400; b /= 2; htr.Add(h.Trophies - StarPointsTrophiesInReset[i] * 10 - b); h.Trophies = (StarPointsTrophiesInReset[i] * 10 + b); sa.Add(StarPointsSeasonRewardAmount[i] + b / 2); } break; } else { i++; } } } } if (hhh.Count > 0) { thisAcc.Home.NotificationFactory.Add(new Notification { Id = 79, //Time = DateTime.UtcNow, HeroesIds = hhh, HeroesTrophies = ht, HeroesTrophiesReseted = htr, StarpointsAwarded = sa, }); } } Accounts.Save(thisAcc); Logger.WriteServerLog($"[resetseason] accid={accid}"); } } else if (cmd[0] == "addgems") { if (cmd.Length != 3) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid usage")); Logger.WriteServerLog("]"); return; } bool sc = false; long id = 0; if (cmd[1].StartsWith('#')) { id = LogicLongCodeGenerator.ToId(cmd[1]); } else { sc = true; id = long.Parse(cmd[1]); } Account account = Accounts.Load(id); if (account == null) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid tag: {id}")); return; } //account.Avatar.Diamonds += int.Parse(cmd[2]); Notification n = new Notification { Id = 89, DonationCount = int.Parse(cmd[2]), TimePassed = DateTime.UtcNow, MessageEntry = $"Thanks for donation!" }; account.Home.NotificationFactory.Add(n); LogicAddNotificationCommand acm = new() { Notification = n }; AvailableServerCommandMessage asm = new AvailableServerCommandMessage(); asm.Command = acm; if (Sessions.IsSessionActive(id)) { var session = Sessions.GetSession(id); session.GameListener.SendTCPMessage(asm); } string d = sc ? LogicLongCodeGenerator.ToCode(long.Parse(cmd[1])) : cmd[1]; Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Done: added {int.Parse(cmd[2])} gems for {d}!")); } else if (cmd[0] == "settrophy") { if (cmd.Length != 4) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid usage")); Logger.WriteServerLog("]"); return; } bool sc = false; long id = 0; if (cmd[1].StartsWith('#')) { id = LogicLongCodeGenerator.ToId(cmd[1]); } else { sc = true; id = long.Parse(cmd[1]); } Account account = Accounts.Load(id); if (account == null) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid tag: {id}")); return; } Hero h = account.Avatar.GetHero(int.Parse(cmd[2])); h.Trophies = int.Parse(cmd[3]); if (h.Trophies > h.HighestTrophies) { h.HighestTrophies = h.Trophies; } if (account.Avatar.Trophies > account.Avatar.HighestTrophies) { account.Avatar.HighestTrophies = account.Avatar.Trophies; } //account.Avatar.Diamonds += int.Parse(cmd[2]); if (Sessions.IsSessionActive(id)) { var session = Sessions.GetSession(id); session.GameListener.SendTCPMessage(new AuthenticationFailedMessage() { Message = "Some data changed, please re-enter game!" }); Sessions.Remove(id); } string d = sc ? LogicLongCodeGenerator.ToCode(long.Parse(cmd[1])) : cmd[1]; Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Done: set {int.Parse(cmd[3])} trophies for brawler {int.Parse(cmd[2])} for {d}!")); } else if (cmd[0] == "addgold") { if (cmd.Length != 3) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid usage")); Logger.WriteServerLog("]"); return; } bool sc = false; long id = 0; if (cmd[1].StartsWith('#')) { id = LogicLongCodeGenerator.ToId(cmd[1]); } else { sc = true; id = long.Parse(cmd[1]); } Account account = Accounts.Load(id); if (account == null) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid tag: {id}")); return; } //account.Avatar.Diamonds += int.Parse(cmd[2]); Notification n = new Notification { Id = 90, TimePassed = DateTime.UtcNow, DonationCount = int.Parse(cmd[2]), //DonationGlobalId = GlobalId.CreateGlobalId(5, 8), MessageEntry = $"Thanks for donation!" }; account.Home.NotificationFactory.Add(n); LogicAddNotificationCommand acm = new() { Notification = n }; AvailableServerCommandMessage asm = new AvailableServerCommandMessage(); asm.Command = acm; if (Sessions.IsSessionActive(id)) { var session = Sessions.GetSession(id); session.GameListener.SendTCPMessage(asm); } string d = sc ? LogicLongCodeGenerator.ToCode(long.Parse(cmd[1])) : cmd[1]; Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Done: added {int.Parse(cmd[2])} gold for {d}!")); } else if (cmd[0] == "addspints") { if (cmd.Length != 3) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid usage")); Logger.WriteServerLog("]"); return; } bool sc = false; long id = 0; if (cmd[1].StartsWith('#')) { id = LogicLongCodeGenerator.ToId(cmd[1]); } else { sc = true; id = long.Parse(cmd[1]); } Account account = Accounts.Load(id); if (account == null) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid tag: {id}")); return; } //account.Avatar.Diamonds += int.Parse(cmd[2]); Notification n = new Notification { Id = 90, DonationCount = int.Parse(cmd[2]), //DonationGlobalId = GlobalId.CreateGlobalId(5, 10), TimePassed = DateTime.UtcNow, MessageEntry = $"Thanks for donation!" }; account.Home.NotificationFactory.Add(n); LogicAddNotificationCommand acm = new() { Notification = n }; AvailableServerCommandMessage asm = new AvailableServerCommandMessage(); asm.Command = acm; if (Sessions.IsSessionActive(id)) { var session = Sessions.GetSession(id); session.GameListener.SendTCPMessage(asm); } string d = sc ? LogicLongCodeGenerator.ToCode(long.Parse(cmd[1])) : cmd[1]; Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Done: added {int.Parse(cmd[2])} starpoints for {d}!")); } else if (cmd[0] == "addbrawler" || cmd[0] == "addskin") { if (cmd.Length != 3) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid usage")); Logger.WriteServerLog("]"); return; } bool sc = false; long id = 0; if (cmd[1].StartsWith('#')) { id = LogicLongCodeGenerator.ToId(cmd[1]); } else { sc = true; id = long.Parse(cmd[1]); } Account account = Accounts.Load(id); if (account == null) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid tag: {id}")); return; } //account.Avatar.Diamonds += int.Parse(cmd[2]); string MessageEntry1 = ""; if (int.Parse(cmd[2]) == 29000059) { MessageEntry1 = ""; } else { MessageEntry1 = $"Thanks for donation!"; } Notification n = new Notification { Id = cmd[0] == "addbrawler" ? 93 : 94, DonationCount = 0, TimePassed = DateTime.UtcNow, DonationGlobalId = int.Parse(cmd[2]), MessageEntry = MessageEntry1 }; account.Home.NotificationFactory.Add(n); LogicAddNotificationCommand acm = new() { Notification = n }; AvailableServerCommandMessage asm = new AvailableServerCommandMessage(); asm.Command = acm; if (Sessions.IsSessionActive(id)) { var session = Sessions.GetSession(id); session.GameListener.SendTCPMessage(asm); } string d = sc ? LogicLongCodeGenerator.ToCode(long.Parse(cmd[1])) : cmd[1]; Connection.Socket.Send(System.Text.Encoding.UTF8.GetBytes($"Done: added ксвкакое-то {int.Parse(cmd[2])} for {d}!")); } else if (cmd[0] == "addstartokens") { if (cmd.Length != 3) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid usage")); Logger.WriteServerLog("]"); return; } bool sc = false; long id = 0; if (cmd[1].StartsWith('#')) { id = LogicLongCodeGenerator.ToId(cmd[1]); } else { sc = true; id = long.Parse(cmd[1]); } Account account = Accounts.Load(id); if (account == null) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid tag: {id}")); return; } //account.Avatar.Diamonds += int.Parse(cmd[2]); Notification n = new Notification { Id = 90, DonationCount = int.Parse(cmd[2]), //DonationGlobalId = GlobalId.CreateGlobalId(5, 9), TimePassed = DateTime.UtcNow, MessageEntry = $"Thanks for donation!" }; account.Home.NotificationFactory.Add(n); LogicAddNotificationCommand acm = new() { Notification = n }; AvailableServerCommandMessage asm = new AvailableServerCommandMessage(); asm.Command = acm; if (Sessions.IsSessionActive(id)) { var session = Sessions.GetSession(id); session.GameListener.SendTCPMessage(asm); } string d = sc ? LogicLongCodeGenerator.ToCode(long.Parse(cmd[1])) : cmd[1]; Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Done: added {int.Parse(cmd[2])} startokens for {d}!")); } else if (cmd[0] == "getusrinfo") { if (cmd.Length != 2) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid usage")); Logger.WriteServerLog("]"); return; } bool sc = false; long id = 0; if (cmd[1].StartsWith('#')) { id = LogicLongCodeGenerator.ToId(cmd[1]); } else { sc = true; id = long.Parse(cmd[1]); } Account account = Accounts.Load(id); if (account == null) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid tag: {id}")); return; } string d = sc ? LogicLongCodeGenerator.ToCode(long.Parse(cmd[1])) : cmd[1]; /*Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Done: Information of {d}!\n" + $"IpAddress: {ConvertInfoToData(account.Home.IpAddress)}\n" + $"Last Login Time: {account.Home.LastVisitHomeTime} UTC\n" + $"Device: {ConvertInfoToData(account.Home.Device)}\n" + $"Device(?) Identificator: {ConvertInfoToData(account.Home.DeviceIdenteficdactor)}\n" + $"Language: {ConvertInfoToData(account.Home.Lang)}\n" + $"Os Version: {ConvertInfoToData(account.Home.OsVersion)}"));*/ } else if (cmd[0] == "resettoken") { if (cmd.Length < 2) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid usage")); Logger.WriteServerLog("]"); return; } bool sc = false; long id = 0; if (cmd[1].StartsWith('#')) { id = LogicLongCodeGenerator.ToId(cmd[1]); } else { sc = true; id = long.Parse(cmd[1]); } Account account = Accounts.Load(id); if (account == null) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid tag: {id}")); return; } account.PassToken = Helpers.RandomString(40); if (Sessions.IsSessionActive(id)) { var session = Sessions.GetSession(id); session.GameListener.SendTCPMessage(new AuthenticationFailedMessage() { Message = "Some data changed, please re-enter game!" }); Sessions.Remove(id); } string d = sc ? LogicLongCodeGenerator.ToCode(long.Parse(cmd[1])) : cmd[1]; Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Done: reseted pass token for {d}!")); } else if (cmd[0] == "chname") { if (cmd.Length < 3) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid usage")); Logger.WriteServerLog("]"); return; } bool sc = false; long id = 0; if (cmd[1].StartsWith('#')) { id = LogicLongCodeGenerator.ToId(cmd[1]); } else { sc = true; id = long.Parse(cmd[1]); } Account account = Accounts.Load(id); if (account == null) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid tag: {id}")); return; } string name = message.Message.Substring(1).Split("##!")[1]; account.Avatar.Name = name; if (account.Avatar.AllianceId >= 0) { Alliance a = Alliances.Load(account.Avatar.AllianceId); if (a == null) return; AllianceMember m = a.GetMemberById(account.Avatar.AccountId); m.DisplayData.Name = name; } foreach (Friend friend in account.Avatar.Friends) { Friend entry = friend.Avatar.GetFriendById(account.Avatar.AccountId); entry.DisplayData.Name = account.Avatar.Name; if (LogicServerListener.Instance.IsPlayerOnline(friend.Avatar.AccountId)) { FriendListUpdateMessage update = new() { Entry = entry }; LogicServerListener.Instance.GetGameListener(friend.AccountId).SendTCPMessage(update); } } if (Sessions.IsSessionActive(id)) { var session = Sessions.GetSession(id); session.GameListener.SendTCPMessage(new AuthenticationFailedMessage() { Message = "Some data changed, please re-enter game!" }); Sessions.Remove(id); } string d = sc ? LogicLongCodeGenerator.ToCode(long.Parse(cmd[1])) : cmd[1]; Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Done: set vip status for {d} activated/extended to {account.Home.PremiumEndTime} UTC!")); } else { if (cmd.Length != 4) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid usage")); Logger.WriteServerLog("]"); return; } bool sc = false; long id = 0; if (cmd[1].StartsWith('#')) { id = LogicLongCodeGenerator.ToId(cmd[1]); } else { sc = true; id = long.Parse(cmd[1]); } Account account = Accounts.Load(id); if (account == null) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid tag: {id}")); return; } string[] req = cmd[2].Split('.'); Type type = null; bool IsAvatar = false; if (req[0] == "Avatar") { IsAvatar = true; type = typeof(ClientAvatar); } else { type = typeof(ClientHome); } FieldInfo field = type.GetField(req[1]); if (field == null) { Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Error: Invalid tag: {cmd[2]} - is unknwon field")); return; } if (cmd[3] == "true") { field.SetValue(IsAvatar ? account.Avatar : account.Home, true); } else if (cmd[3] == "false") { field.SetValue(IsAvatar ? account.Avatar : account.Home, false); } else { try { field.SetValue(IsAvatar ? account.Avatar : account.Home, int.Parse(cmd[3])); } catch { field.SetValue(IsAvatar ? account.Avatar : account.Home, cmd[3]); } } if (Sessions.IsSessionActive(id)) { var session = Sessions.GetSession(id); session.GameListener.SendTCPMessage(new AuthenticationFailedMessage() { Message = "Some data changed, please re-enter game!" }); Sessions.Remove(id); } string d = sc ? LogicLongCodeGenerator.ToCode(long.Parse(cmd[1])) : cmd[1]; Connection.Socket.Send(System.Text.Encoding.ASCII.GetBytes($"Done: set {cmd[2]} to {cmd[3]} for {d}")); } } private void RequestServerReceived(RequestServerStatus message) { long megabytesUsed = Process.GetCurrentProcess().PrivateMemorySize64 / (1024 * 1024); DateTime now = Process.GetCurrentProcess().StartTime; DateTime futureDate = DateTime.Now; TimeSpan timeDifference = futureDate - now; string formattedTime = string.Format("{0}{1}{2}{3}", timeDifference.Days > 0 ? $"{timeDifference.Days} Days, " : string.Empty, timeDifference.Hours > 0 || timeDifference.Days > 0 ? $"{timeDifference.Hours} Hours, " : string.Empty, timeDifference.Minutes > 0 || timeDifference.Hours > 0 ? $"{timeDifference.Minutes} Minutes, " : string.Empty, timeDifference.Seconds > 0 ? $"{timeDifference.Seconds} Seconds" : string.Empty); string msg = $"Server Status:\n" + $"Server Build: {Program.SERVER_VERSION} ({Fingerprint.Version})\n" + $"Environment: Prod\n" + $"Server Time: {DateTime.Now} UTC\n" + $"Players Online: {Sessions.Count}\n" + $"Battles: {Battles.GetBattlesCount()}\n" + $"Battles Played: {Program.BattlesCompleted}\n" + $"Memory Used: {megabytesUsed} MB\n" + $"Uptime: {formattedTime}\n" + $"Accounts Cached: {AccountCache.Count}\n" + $"Alliances Cached: {AllianceCache.Count}\n" + $"Teams Cached: {Teams.Count}\n"; ApiResponceMessage serverStatus = new ApiResponceMessage(); serverStatus.Message = msg; Connection.Send(serverStatus); } private void PlayerStatusReceived(PlayerStatusMessage message) { if (HomeMode == null) return; if (message.Status < 0) return; int oldstatus = HomeMode.Avatar.PlayerStatus; int newstatus = message.Status; /* * practice: * 10 * -1 * 8 * * battle: * 3 * -1 * 8 */ HomeMode.Avatar.PlayerStatus = message.Status; Logger.WriteServerLog($"MESSAGE.STATUS: {message.Status}"); if (oldstatus == 3 && newstatus == 8) { HomeMode.Avatar.BattleStartTime = DateTime.UtcNow; } if (oldstatus == 8 && newstatus == 3) { Hero h = HomeMode.Avatar.GetHero(HomeMode.Home.CharacterId); int lose = 0; int brawlerTrophies = h.Trophies; if (brawlerTrophies <= 49) { lose = 0; } else if (50 <= brawlerTrophies && brawlerTrophies <= 99) { lose = -1; } else if (100 <= brawlerTrophies && brawlerTrophies <= 199) { lose = -2; } else if (200 <= brawlerTrophies && brawlerTrophies <= 299) { lose = -3; } else if (300 <= brawlerTrophies && brawlerTrophies <= 399) { lose = -4; } else if (400 <= brawlerTrophies && brawlerTrophies <= 499) { lose = -5; } else if (500 <= brawlerTrophies && brawlerTrophies <= 599) { lose = -6; } else if (600 <= brawlerTrophies && brawlerTrophies <= 699) { lose = -7; } else if (700 <= brawlerTrophies && brawlerTrophies <= 799) { lose = -8; } else if (800 <= brawlerTrophies && brawlerTrophies <= 899) { lose = -9; } else if (900 <= brawlerTrophies && brawlerTrophies <= 999) { lose = -10; } else if (1000 <= brawlerTrophies && brawlerTrophies <= 1099) { lose = -11; } else if (1100 <= brawlerTrophies && brawlerTrophies <= 1199) { lose = -12; } else if (brawlerTrophies >= 1200) { lose = -12; } h.AddTrophies(lose); HomeMode.Home.PowerPlayGamesPlayed = Math.Max(0, HomeMode.Home.PowerPlayGamesPlayed - 1); HomeMode.Avatar.BattleStartTime = new DateTime(); HomeMode.Home.TrophiesReward = 0; Logger.BLog($"Player {LogicLongCodeGenerator.ToCode(HomeMode.Avatar.AccountId)} left battle!"); HomeMode.Avatar.BattleStartTime = DateTime.MinValue; } FriendOnlineStatusEntryMessage entryMessage = new FriendOnlineStatusEntryMessage(); entryMessage.AvatarId = HomeMode.Avatar.AccountId; entryMessage.PlayerStatus = HomeMode.Avatar.PlayerStatus; foreach (Friend friend in HomeMode.Avatar.Friends.ToArray()) { if (LogicServerListener.Instance.IsPlayerOnline(friend.AccountId)) { // LogicServerListener.Instance.GetGameListener(friend.AccountId).SendTCPMessage(entryMessage); } } } private void SendMyAllianceData(Alliance alliance) { MyAllianceMessage myAlliance = new MyAllianceMessage(); myAlliance.Role = HomeMode.Avatar.AllianceRole; myAlliance.OnlineMembers = alliance.OnlinePlayers; myAlliance.AllianceHeader = alliance.Header; Connection.Send(myAlliance); AllianceStreamMessage stream = new AllianceStreamMessage(); stream.Entries = alliance.Stream.GetEntries(); Connection.Send(stream); } private int BotIdCounter; private void RequestMatchCancelReceived(RequestMatchCancelMessage message) { if (Connection.Home != null && Connection.Avatar != null) { OwnHomeDataMessage ohd = new OwnHomeDataMessage(); ohd.Home = Connection.Home; ohd.Avatar = Connection.Avatar; Connection.Send(ohd); } } private void SinglePlayerMatchRequestReceived(SinglePlayerMatchRequestMessage message) { BattleMode battle = new BattleMode(15000121); battle.Id = Battles.Add(battle); CharacterData characterData = DataTables.Get(DataType.Character).GetDataWithId(message.CharacterId); if (characterData == null) { Logger.WriteServerLog($"[TRAINING] Invalid characterId: {message.CharacterId}"); return; } BattlePlayer player = BattlePlayer.Create(Connection.Home, Connection.Avatar, 0, 0, null, message.CharacterId); player.CharacterIds[0] = message.CharacterId; player.CharacterDatas[0] = characterData; player.SkinIds[0] = message.SkinId; Hero hero = Connection.Avatar.GetHero(message.CharacterId); /*if (hero != null) { player.Trophies = hero.Trophies; player.HighestTrophies = hero.HighestTrophies; player.HeroPowerLevel = hero.PowerLevel; if (hero != null && hero.SelectedGadgetId > 0) { Logger.WriteServerLog($"Hero found, SelectedGadgetId: {hero.SelectedGadgetId}"); CardData gadgetCard = DataTables.Get(23).GetData(hero.SelectedGadgetId); if (gadgetCard != null && Connection.Avatar.UnlockedMeta.Contains(gadgetCard.GetGlobalId())) { Logger.WriteServerLog($"Gadget card is valid and unlocked. Gadget name: {gadgetCard.Name}, GlobalId: {gadgetCard.GetGlobalId()}"); player.AccessoryCardDatas[0] = gadgetCard; player.AccessoryDatas[0] = DataTables.Get(DataType.Accessory).GetData(gadgetCard.Name); player.Accessory = new Accessory(player.AccessoryDatas[0]); Logger.WriteServerLog($"Successfully applied gadget: {gadgetCard.Name} to player"); } else { if (gadgetCard == null) { Logger.WriteServerLog($"Warning: Gadget card is null for ID: {hero.SelectedGadgetId}"); } else if (!Connection.Avatar.UnlockedMeta.Contains(gadgetCard.GetGlobalId())) { Logger.WriteServerLog($"Warning: Gadget {gadgetCard.Name} (GlobalId: {gadgetCard.GetGlobalId()}) is not unlocked"); } } } else { if (hero == null) { Logger.WriteServerLog("Warning: Hero is null, skipping gadget assignment"); } else if (hero.SelectedGadgetId <= 0) { Logger.WriteServerLog($"Hero has no gadget selected (SelectedGadgetId: {hero.SelectedGadgetId})"); } player.AccessoryCardDatas[0] = null; player.AccessoryDatas[0] = null; player.Accessory = null; Logger.WriteServerLog("Cleared player accessory data"); } if (hero.SelectedStarPowerId > 0) { CardData starPower = DataTables.Get(23).GetData(hero.SelectedStarPowerId); if (starPower != null && Connection.Avatar.UnlockedMeta.Contains(starPower.GetGlobalId())) { player.StarPowerDatas[0] = starPower; } } if (hero.Emotes != null && hero.Emotes.Count > 0) { if (hero.Emotes.TryGetValue(1, out int emote1)) player.Emotes[1] = emote1; if (hero.Emotes.TryGetValue(2, out int emote2)) player.Emotes[2] = emote2; if (hero.Emotes.TryGetValue(3, out int emote3)) player.Emotes[3] = emote3; } } else { player.Trophies = 0; player.HighestTrophies = 0; player.HeroPowerLevel = 11; } */ if (Connection.Home.PlayerSelectedEmotes != null && Connection.Home.PlayerSelectedEmotes.Count > 0) { if (Connection.Home.PlayerSelectedEmotes.TryGetValue(4, out int emote4)) player.Emotes[4] = emote4; if (Connection.Home.PlayerSelectedEmotes.TryGetValue(5, out int emote5)) player.Emotes[5] = emote5; } UDPSocket socket = UDPGateway.CreateSocket(); socket.TCPConnection = Connection; socket.Battle = battle; Connection.UdpSessionId = socket.SessionId; battle.AddPlayer(player, Connection.UdpSessionId); battle.AddGameObjects(); StartLoadingMessage startLoading = new StartLoadingMessage(); startLoading.LocationId = battle.Location.GetGlobalId(); startLoading.TeamIndex = player.TeamIndex; startLoading.OwnIndex = player.PlayerIndex; startLoading.GameMode = battle.GetGameModeVariation(); startLoading.GameType = 8; Connection.Avatar.UdpSessionId = Connection.UdpSessionId; startLoading.Players.AddRange(battle.GetPlayers()); Logger.Print($"[Battle] Sending StartLoading to AccountId={HomeMode.Avatar.AccountId} BattleId={battle.Id}"); Connection.Send(startLoading); battle.Dummy = startLoading; battle.Start(); } private void ChatToAllianceStreamReceived(ChatToAllianceStreamMessage message) { Alliance alliance = Alliances.Load(HomeMode.Avatar.AllianceId); if (alliance == null) return; if (message.Message.StartsWith("/")) { string[] cmd = message.Message.Substring(1).Split(' '); if (cmd.Length == 0) return; DebugOpenMessage debugopen = new() { }; AllianceStreamEntryMessage response = new() { Entry = new AllianceStreamEntry { AuthorName = "Alliance Bot", AuthorId = HomeMode.Avatar.AccountId + 1, Id = alliance.Stream.EntryIdCounter + 1, AuthorRole = AllianceRole.Member, Type = 2 } }; long accountId = HomeMode.Avatar.AccountId; switch (cmd[0]) { case "help": response.Entry.Message = $"Доступные команды:\n/help - показать список команд сервера\n/status - показать статус сервера\n/lobbyinfo on/off - включить/выключить показ информации в лобби"; Connection.Send(response); break; case "status": long megabytesUsed = Process.GetCurrentProcess().PrivateMemorySize64 / (1024 * 1024); DateTime now = Process.GetCurrentProcess().StartTime; DateTime futureDate = DateTime.Now; TimeSpan timeDifference = futureDate - now; string formattedTime = string.Format("{0}{1}{2}{3}", timeDifference.Days > 0 ? $"{timeDifference.Days} Days, " : string.Empty, timeDifference.Hours > 0 || timeDifference.Days > 0 ? $"{timeDifference.Hours} Hours, " : string.Empty, timeDifference.Minutes > 0 || timeDifference.Hours > 0 ? $"{timeDifference.Minutes} Minutes, " : string.Empty, timeDifference.Seconds > 0 ? $"{timeDifference.Seconds} Seconds" : string.Empty); response.Entry.Message = $"Server Status:\n" + $"Server Build: {Program.SERVER_VERSION} ({Fingerprint.Version})\n" + $"Battles: {Battles.GetBattlesCount()}\n" + $"Battles Played: {Program.BattlesCompleted}\n" + $"Resources Sha: {Fingerprint.Sha}\n" + $"Environment: Prod\n" + $"Server Time: {DateTime.Now} EEST\n" + $"Memory Used: {megabytesUsed} MB\n" + $"Uptime: {formattedTime}\n"; Connection.Send(response); break; case "lobbyinfo": if (cmd.Length != 2 || (cmd[1].ToLower() != "on" && cmd[1].ToLower() != "off")) { response.Entry.Message = $"Использование: /lobbyinfo on/off (on - включить, off - выключить)"; Connection.Send(response); return; } if (cmd[1].ToLower() == "on") { if (!HomeMode.Avatar.LobbyInfoDisabled) { response.Entry.Message = $"Ваша информация уже включена, чтобы отключить напишите /lobbyinfo off"; } else { HomeMode.Avatar.LobbyInfoDisabled = false; response.Entry.Message = $"Вы успешно включили информацию в лобби!"; } } else { if (HomeMode.Avatar.LobbyInfoDisabled) { response.Entry.Message = $"Ваша информация уже отключена, чтобы включить напишите /lobbyinfo on"; } else { HomeMode.Avatar.LobbyInfoDisabled = true; response.Entry.Message = $"Вы успешно отключили информацию в лобби!"; } } Connection.Send(response); break; case "load": if (cmd.Length != 3) { response.Entry.Message = $"Usage: /load [Account tag in #XXX format] [Account code]"; // /usecode [code] - use bonus code Connection.Send(response); return; } if (cmd[2].Length != 6) { response.Entry.Message = $"Code must be in XXXXXX format, where X - num from 0-9"; // /usecode [code] - use bonus code Connection.Send(response); return; } if (!Sessions.RegistratedSSID.ContainsKey(cmd[1])) { response.Entry.Message = $"Invalid tag or code"; // /usecode [code] - use bonus code Connection.Send(response); return; } if (Sessions.RegistratedSSID[cmd[1]] != cmd[2]) { response.Entry.Message = $"Invalid tag or code"; // /usecode [code] - use bonus code Connection.Send(response); return; } List list = new List { HomeMode.Home.IpAddress, HomeMode.Home.Device }; Sessions.LeaveJoin.Add(cmd[1], list); Account t = Accounts.Load(LogicLongCodeGenerator.ToId(cmd[1])); t.Avatar.ShouldRedirect = false; if (t == null) { response.Entry.Message = $"Invalid tag or code"; // /usecode [code] - use bonus code Connection.Send(response); return; } Connection.Send(new CreateAccountOkMessage { AccountId = t.AccountId, PassToken = t.PassToken }); Connection.Send(new AuthenticationFailedMessage { ErrorCode = 1, Message = "Done!" }); Sessions.RegistratedSSID.Remove(LogicLongCodeGenerator.ToCode(t.Avatar.AccountId)); //Sessions.RegistratedSSID.Remove(LogicLongCodeGenerator.ToCode(t.Avatar.AccountId)); //HomeMode.Avatar.RedirectId = t.AccountId; break; case "link": Random r = new Random(); string code = ""; for (int i = 0; i < 6; i++) { int v = r.Next(1, 9); code += v.ToString(); } if (!Sessions.RequestedSSID.ContainsKey(LogicLongCodeGenerator.ToCode(HomeMode.Avatar.AccountId))) { Sessions.RequestedSSID.Add(LogicLongCodeGenerator.ToCode(HomeMode.Avatar.AccountId), code); response.Entry.Message = $"Done! your code is {code}\nTo link your account, open in telegram bot @SavDonatebot, and pm him:\n/link {LogicLongCodeGenerator.ToCode(HomeMode.Avatar.AccountId)} {code}"; Connection.Send(response); } else { code = Sessions.RequestedSSID[LogicLongCodeGenerator.ToCode(HomeMode.Avatar.AccountId)]; response.Entry.Message = $"Code was already generated, your code is: {code}\nTo link your account, open in telegram bot @SavDonatebot, and pm him:\n/link {LogicLongCodeGenerator.ToCode(HomeMode.Avatar.AccountId)} {code}"; Connection.Send(response); } break; case "resetBrawlPass": if (HomeMode.Avatar.AccountId != 1) { response.Entry.Message = $"You don\'t have right to use this command"; // /usecode [code] - use bonus code Connection.Send(response); return; } long lastAccId1 = Accounts.GetMaxAvatarId(); for (int accid = 1; accid <= lastAccId1; accid++) { Account thisAcc = Accounts.LoadNoChache(accid); if (thisAcc == null) continue; thisAcc.Home.HasPremiumPass = false; thisAcc.Home.BrawlPassProgress = 0; thisAcc.Home.BrawlPassTokens = 0; thisAcc.Home.PremiumPassProgress = 0; Accounts.Save(thisAcc); Logger.WriteServerLog($"[resetBrawlPass] accid={accid}"); } break; case "resetBpDev": Account thisAcc1 = Accounts.LoadNoChache(1); thisAcc1.Home.HasPremiumPass = false; thisAcc1.Home.BrawlPassProgress = 0; thisAcc1.Home.BrawlPassTokens = 0; thisAcc1.Home.PremiumPassProgress = 0; Accounts.Save(thisAcc1); break; case "resetseason": if (HomeMode.Avatar.AccountId != 1) { response.Entry.Message = $"You don\'t have right to use this command"; // /usecode [code] - use bonus code Connection.Send(response); return; } long lastAccId2 = Accounts.GetMaxAvatarId(); for (int accid = 1; accid <= lastAccId2; accid++) { Account thisAcc = Accounts.LoadNoChache(accid); if (thisAcc == null) continue; //thisAcc.Home.HasPremiumPass = false; //thisAcc.Home.BrawlPassProgress = 0; //thisAcc.Home.BrawlPassTokens = 0; //thisAcc.Home.PremiumPassProgress = 0; //thisAcc.Home.LastRotateDate = new(); /*if (thisAcc.Avatar.AllianceId > 0) { Alliance a = Alliances.Load(thisAcc.Avatar.AllianceId); if (a == null) { thisAcc.Avatar.AllianceId = 0; } else { AllianceMember rr = a.GetMemberById(thisAcc.Avatar.AccountId); if (rr == null) { thisAcc.Avatar.AllianceId = 0; } else { thisAcc.Avatar.AllianceRole = rr.Role; rr.DisplayData.NameColorId = thisAcc.Home.NameColorId; } } }*/ if (thisAcc.Avatar.Trophies >= 550) { List hhh = new(); List ht = new(); List htr = new(); List sa = new(); int[] StarPointsTrophiesStart = { 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000, 1050, 1100, 1150, 1200, 1250, 1300, 1350, 1400 }; int[] StarPointsTrophiesEnd = { 599, 649, 699, 749, 799, 849, 899, 949, 999, 1049, 1099, 1149, 1199, 1249, 1299, 1349, 1399, 1000000 }; int[] StarPointsSeasonRewardAmount = { 70, 120, 160, 200, 220, 240, 260, 280, 300, 320, 340, 360, 380, 400, 420, 440, 460, 480 }; int[] StarPointsTrophiesInReset = { 525, 550, 600, 650, 700, 725, 750, 775, 800, 825, 850, 875, 900, 925, 950, 975, 1000, 1025 }; foreach (Hero h in thisAcc.Avatar.Heroes) { if (h.Trophies >= StarPointsTrophiesStart[0]) { hhh.Add(h.CharacterId); ht.Add(h.Trophies); int i = 0; while (true) { if (h.Trophies >= StarPointsTrophiesStart[i] && h.Trophies <= StarPointsTrophiesEnd[i]) { if (StarPointsTrophiesStart[i] != 1400) { htr.Add(h.Trophies - StarPointsTrophiesInReset[i]); h.Trophies = StarPointsTrophiesInReset[i]; sa.Add(StarPointsSeasonRewardAmount[i]); } else { int b = h.Trophies - 1440; b /= 2; htr.Add(h.Trophies - StarPointsTrophiesInReset[i] - b); h.Trophies = (StarPointsTrophiesInReset[i] + b); sa.Add(StarPointsSeasonRewardAmount[i] + b / 2); } break; } else { i++; } } } } if (hhh.Count > 0) { thisAcc.Home.NotificationFactory.Add(new Notification { Id = 79, HeroesIds = hhh, HeroesTrophies = ht, HeroesTrophiesReseted = htr, StarpointsAwarded = sa, }); } } Accounts.Save(thisAcc); Logger.WriteServerLog($"[resetseason] accid={accid}"); } break; default: response.Entry.Message = $"Unknown command /{cmd[0]}!"; Connection.Send(response); break; } return; } if (!HomeMode.Avatar.IsCommunityBanned && message.Message.Length < 100) { alliance.SendChatMessage(HomeMode.Avatar.AccountId, message.Message); } else if (HomeMode.Avatar.IsCommunityBanned) { AllianceStreamEntryMessage response = new() { Entry = new AllianceStreamEntry { AuthorName = "Console", AuthorId = 0, Id = alliance.Stream.EntryIdCounter + 1, AuthorRole = AllianceRole.Member, Message = "Это сообщение не видят другие учасники, для общения в чате дождись конца блокривки!", Type = 2 } }; Connection.Send(response); } else { AllianceStreamEntryMessage response = new() { Entry = new AllianceStreamEntry { AuthorName = "Console", AuthorId = 0, Id = alliance.Stream.EntryIdCounter + 1, AuthorRole = AllianceRole.Member, Message = "Unknown error occured. We are working on this...", Type = 2 } }; Connection.Send(response); } } private void JoinAllianceReceived(JoinAllianceMessage message) { Alliance alliance = Alliances.Load(message.AllianceId); if (HomeMode.Avatar.AllianceId > 0) return; if (alliance == null) return; if (HomeMode.Avatar.Trophies < alliance.RequiredTrophies) return; if (alliance.Members.Count >= 100) return; if (alliance.Type == 3) return; AllianceStreamEntry entry = new AllianceStreamEntry(); entry.AuthorId = HomeMode.Avatar.AccountId; entry.AuthorName = HomeMode.Avatar.Name; entry.Id = ++alliance.Stream.EntryIdCounter; entry.PlayerId = HomeMode.Avatar.AccountId; entry.PlayerName = HomeMode.Avatar.Name; entry.Type = 4; entry.Event = 3; entry.AuthorRole = HomeMode.Avatar.AllianceRole; alliance.AddStreamEntry(entry); HomeMode.Avatar.AllianceRole = AllianceRole.Member; HomeMode.Avatar.AllianceId = alliance.Id; alliance.Members.Add(new AllianceMember(HomeMode.Avatar)); AllianceResponseMessage response = new AllianceResponseMessage(); response.ResponseType = 40; Connection.Send(response); SendMyAllianceData(alliance); } private void LeaveAllianceReceived(LeaveAllianceMessage message) { if (HomeMode.Avatar.AllianceId < 0 || HomeMode.Avatar.AllianceRole == AllianceRole.None) return; Alliance alliance = Alliances.Load(HomeMode.Avatar.AllianceId); if (alliance == null) return; if (HomeMode.Avatar.AllianceRole == AllianceRole.Leader) { AllianceMember nextLeader = alliance.GetNextRoleMember(); if (nextLeader == null) { alliance.RemoveMemberById(HomeMode.Avatar.AccountId); if (alliance.Members.Count < 1) { Alliances.Delete(HomeMode.Avatar.AllianceId); } HomeMode.Avatar.AllianceId = -1; HomeMode.Avatar.AllianceRole = AllianceRole.None; Connection.Send(new AllianceResponseMessage { ResponseType = 80 }); Connection.Send(new MyAllianceMessage()); return; }; Account target = Accounts.Load(nextLeader.AccountId); if (target == null) return; target.Avatar.AllianceRole = AllianceRole.Leader; nextLeader.Role = AllianceRole.Leader; if (LogicServerListener.Instance.IsPlayerOnline(target.AccountId)) { LogicServerListener.Instance.GetGameListener(target.AccountId).SendTCPMessage(new AllianceResponseMessage() { ResponseType = 101 }); MyAllianceMessage targetAlliance = new() { AllianceHeader = alliance.Header, Role = HomeMode.Avatar.AllianceRole }; LogicServerListener.Instance.GetGameListener(target.AccountId).SendTCPMessage(targetAlliance); } } alliance.RemoveMemberById(HomeMode.Avatar.AccountId); if (alliance.Members.Count < 1) { Alliances.Delete(HomeMode.Avatar.AllianceId); } else { AllianceStreamEntry entry = new() { AuthorId = HomeMode.Avatar.AccountId, AuthorName = HomeMode.Avatar.Name, Id = ++alliance.Stream.EntryIdCounter, PlayerId = HomeMode.Avatar.AccountId, PlayerName = HomeMode.Avatar.Name, Type = 4, Event = 4, AuthorRole = HomeMode.Avatar.AllianceRole }; alliance.AddStreamEntry(entry); } HomeMode.Avatar.AllianceId = -1; HomeMode.Avatar.AllianceRole = AllianceRole.None; AllianceResponseMessage response = new() { ResponseType = 80 }; Connection.Send(response); MyAllianceMessage myAlliance = new(); Connection.Send(myAlliance); } private void CreateAllianceReceived(CreateAllianceMessage message) { if (HomeMode.Avatar.AllianceId >= 0) return; /* if (HomeMode.Home.Experience < 219) { Connection.Send(new AllianceResponseMessage() { ResponseType = 21 }); return; }*/ if (message.Name.Contains(" 20) { Connection.Send(new AllianceResponseMessage() { ResponseType = 21 }); return; } if (message.Description.Length > 250) { Connection.Send(new AllianceResponseMessage() { ResponseType = 21 }); return; } Alliance alliance = new Alliance(); alliance.Name = message.Name; alliance.Description = message.Description; alliance.RequiredTrophies = message.RequiredTrophies; alliance.Type = message.Type == 1 ? 1 : 3; if (message.BadgeId >= 8000000 && message.BadgeId < 8000000 + DataTables.Get(DataType.AllianceBadge).Count) { alliance.AllianceBadgeId = message.BadgeId; } else { alliance.AllianceBadgeId = 8000000; } HomeMode.Avatar.AllianceRole = AllianceRole.Leader; alliance.Members.Add(new AllianceMember(HomeMode.Avatar)); Alliances.Create(alliance); HomeMode.Avatar.AllianceId = alliance.Id; AllianceResponseMessage response = new AllianceResponseMessage(); response.ResponseType = 20; Connection.Send(response); SendMyAllianceData(alliance); } private void AskForAllianceDataReceived(AskForAllianceDataMessage message) { Alliance alliance = Alliances.Load(message.AllianceId); if (alliance == null) return; AllianceDataMessage data = new AllianceDataMessage(); data.Alliance = alliance; data.IsMyAlliance = message.AllianceId == HomeMode.Avatar.AllianceId; Connection.Send(data); } private void ChangeAllianceMemberRoleReceived(ChangeAllianceMemberRoleMessage message) { if (HomeMode.Avatar.AllianceId <= 0) return; if (HomeMode.Avatar.AllianceRole == AllianceRole.Member || HomeMode.Avatar.AllianceRole == AllianceRole.None) return; Alliance alliance = Alliances.Load(HomeMode.Avatar.AllianceId); if (alliance == null) return; AllianceMember member = alliance.GetMemberById(message.AccountId); if (member == null) return; ClientAvatar avatar = Accounts.Load(message.AccountId).Avatar; AllianceRole None = 0, Member = (AllianceRole)1, Leader = (AllianceRole)2, Elder = (AllianceRole)3, CoLeader = (AllianceRole)4; if (HomeMode.Avatar.AllianceRole == (AllianceRole)Member) return; //if (member.Role == Leader) return; if (alliance.getRoleVector(member.Role, (AllianceRole)message.Role)) { if (avatar.AllianceRole == (AllianceRole)Member) { avatar.AllianceRole = (AllianceRole)Elder; } else if (avatar.AllianceRole == (AllianceRole)Elder) { avatar.AllianceRole = (AllianceRole)CoLeader; } else if (avatar.AllianceRole == (AllianceRole)CoLeader) { HomeMode.Avatar.AllianceRole = (AllianceRole)CoLeader; avatar.AllianceRole = (AllianceRole)Leader; AllianceStreamEntry entry2 = new() { AuthorId = HomeMode.Avatar.AccountId, AuthorName = HomeMode.Avatar.Name, Id = ++alliance.Stream.EntryIdCounter, PlayerId = HomeMode.Avatar.AccountId, PlayerName = HomeMode.Avatar.Name, Type = 4, Event = 6, AuthorRole = HomeMode.Avatar.AllianceRole }; alliance.AddStreamEntry(entry2); AllianceMember me = alliance.GetMemberById(HomeMode.Avatar.AccountId); me.Role = HomeMode.Avatar.AllianceRole; } member.Role = avatar.AllianceRole; AllianceStreamEntry entry = new() { AuthorId = HomeMode.Avatar.AccountId, AuthorName = HomeMode.Avatar.Name, Id = ++alliance.Stream.EntryIdCounter, PlayerId = avatar.AccountId, PlayerName = avatar.Name, Type = 4, Event = 5, AuthorRole = HomeMode.Avatar.AllianceRole }; alliance.AddStreamEntry(entry); AllianceResponseMessage response = new() { ResponseType = 81 }; Connection.Send(response); MyAllianceMessage myAlliance = new() { AllianceHeader = alliance.Header, Role = HomeMode.Avatar.AllianceRole }; Connection.Send(myAlliance); if (LogicServerListener.Instance.IsPlayerOnline(avatar.AccountId)) { LogicServerListener.Instance.GetGameListener(avatar.AccountId).SendTCPMessage(new AllianceResponseMessage() { ResponseType = 101 }); MyAllianceMessage targetAlliance = new() { AllianceHeader = alliance.Header, Role = avatar.AllianceRole }; LogicServerListener.Instance.GetGameListener(avatar.AccountId).SendTCPMessage(targetAlliance); } } else { if (avatar.AllianceRole == (AllianceRole)Elder) { avatar.AllianceRole = (AllianceRole)Member; } else if (avatar.AllianceRole == (AllianceRole)CoLeader) { avatar.AllianceRole = (AllianceRole)Elder; } member.Role = avatar.AllianceRole; AllianceStreamEntry entry = new() { AuthorId = HomeMode.Avatar.AccountId, AuthorName = HomeMode.Avatar.Name, Id = ++alliance.Stream.EntryIdCounter, PlayerId = avatar.AccountId, PlayerName = avatar.Name, Type = 4, Event = 6, AuthorRole = HomeMode.Avatar.AllianceRole }; alliance.AddStreamEntry(entry); AllianceResponseMessage response = new() { ResponseType = 82 }; Connection.Send(response); MyAllianceMessage myAlliance = new() { AllianceHeader = alliance.Header, Role = HomeMode.Avatar.AllianceRole }; Connection.Send(myAlliance); if (LogicServerListener.Instance.IsPlayerOnline(avatar.AccountId)) { LogicServerListener.Instance.GetGameListener(avatar.AccountId).SendTCPMessage(new AllianceResponseMessage() { ResponseType = 102 }); MyAllianceMessage targetAlliance = new() { AllianceHeader = alliance.Header, Role = avatar.AllianceRole }; LogicServerListener.Instance.GetGameListener(avatar.AccountId).SendTCPMessage(targetAlliance); } } } private void AskForJoinableAllianceListReceived(AskForJoinableAllianceListMessage message) { JoinableAllianceListMessage list = new JoinableAllianceListMessage(); List alliances = Alliances.GetRandomAlliances(HomeMode.Avatar, 20); foreach (Alliance alliance in alliances) { list.JoinableAlliances.Add(alliance.Header); } Connection.Send(list); } private void ClientCapabilitesReceived(ClientCapabilitiesMessage message) { Connection.PingUpdated(message.Ping); ShowLobbyInfo(); } private void GetBattleLogReceived(GetBattleLogMessage message) { BattleLogMessage battleLogs = new BattleLogMessage(); battleLogs.BattleLog = HomeMode.Home.BattleLogs; Connection.Send(battleLogs); } private void AskForBattleEndReceived(AskForBattleEndMessage message) { } private void GoHomeReceived(GoHomeMessage message) { if (Connection.Home != null && Connection.Avatar != null) { Connection.Home.Events = Events.GetEventsById(HomeMode.Home.PowerPlayGamesPlayed, Connection.Avatar.AccountId); OwnHomeDataMessage ohd = new OwnHomeDataMessage(); ohd.Home = Connection.Home; ohd.Avatar = Connection.Avatar; Connection.Send(ohd); ShowLobbyInfo(); } } private void GetLeaderboardReceived(GetLeaderboardMessage message) { Logger.WriteServerLog($"[LB DEBUG] Incoming LeaderboardType={message.LeaderboardType}, IsRegional={message.IsRegional}, CharachterId={message.CharachterId}, SeasonId={message.SeasonId}, AccountId={Connection.Avatar?.AccountId}"); if (message.LeaderboardType == 1) { Account[] rankingList = Leaderboards.GetAvatarRankingList(); LeaderboardMessage leaderboard = new() { LeaderboardType = 1, Region = message.IsRegional ? "RU" : null, SeasonId = message.SeasonId }; foreach (Account data in rankingList) { leaderboard.Avatars.Add(new KeyValuePair(data.Home, data.Avatar)); } leaderboard.OwnAvatarId = Connection.Avatar.AccountId; Connection.Send(leaderboard); } else if (message.LeaderboardType == 2) { Alliance[] rankingList = Leaderboards.GetAllianceRankingList(); LeaderboardMessage leaderboard = new() { LeaderboardType = 2, Region = message.IsRegional ? "RU" : null, SeasonId = message.SeasonId }; leaderboard.AllianceList.AddRange(rankingList); Connection.Send(leaderboard); } else if (message.LeaderboardType == 0) { Dictionary> rankingList = Leaderboards.GetBrawlersRankingList(); LeaderboardMessage leaderboard = new() { LeaderboardType = 0, Region = message.IsRegional ? "RU" : null, SeasonId = message.SeasonId, }; Dictionary aaaa = new(); foreach (KeyValuePair> data in rankingList) { if (data.Key == message.CharachterId) { foreach (Account account in data.Value) { aaaa.Add(account.Home, account.Avatar); } } } leaderboard.CharachterId = message.CharachterId; aaaa = aaaa.OrderBy(x => x.Value.GetHero(message.CharachterId).Trophies).Reverse().ToDictionary(x => x.Key, x => x.Value); aaaa = aaaa.Take(Math.Min(aaaa.Count, 200)).ToDictionary(kvp => kvp.Key, kvp => kvp.Value); leaderboard.Brawlers = aaaa; leaderboard.OwnAvatarId = Connection.Avatar.AccountId; Connection.Send(leaderboard); } else if (message.LeaderboardType == 4 || message.LeaderboardType == 5) { // NOTE: LeaderboardType 5 is the client's second ranked-mode tab // (RankedLeaderboardsScreen::getListType returns 5 when its mode flag != 0, // corresponding to config slot 15 vs 14 in getActiveEventForSlot). // This server only tracks a single RankedRank per account, so both tabs // currently show the same ranking. If the two modes need separate // standings, Account/ClientAvatar needs a second rank field (e.g. // RankedRankSecondary) populated by whatever awards rank for that mode, // and a matching GetRankedRankingList overload to query it. Account[] rankingList = Leaderboards.GetRankedRankingList(); LeaderboardMessage leaderboard = new() { LeaderboardType = message.LeaderboardType, Region = message.IsRegional ? "RU" : null, SeasonId = message.SeasonId }; foreach (Account data in rankingList) { leaderboard.Avatars.Add(new KeyValuePair(data.Home, data.Avatar)); } leaderboard.OwnAvatarId = Connection.Avatar.AccountId; Connection.Send(leaderboard); } else { // Defensive fallback: never leave a GetLeaderboardMessage unanswered. // The client blocks its leaderboard UI waiting for a matching response // (see RankedLeaderboardsScreen::onData, which checks the reply's type // against getListType()); silence here is what causes the hang/disconnect // seen in the logs for any future/unknown LeaderboardType. Connection.Send(new LeaderboardMessage { LeaderboardType = message.LeaderboardType, Region = message.IsRegional ? "RU" : null, SeasonId = message.SeasonId, OwnAvatarId = Connection.Avatar.AccountId }); } } private void TeamJoinReceived(TeamJoinMessage message) { long teamId = ((long)message.UnkVInt1 << 32) | (uint)message.UnkVInt2; TeamEntry team = Teams.Get(teamId); if (team == null) { TeamErrorMessage errorMessage = new TeamErrorMessage(); errorMessage.Reason = 3; Connection.Send(errorMessage); return; } int maxPlayersInRoom = 6; if (team.LocationId > 0) { LocationData locationData = DataTables.Get(DataType.Location) .GetDataByGlobalId(team.LocationId); if (locationData != null) { switch (locationData.GameMode) { case "Showdown": case "DuoShowdown": maxPlayersInRoom = 10; break; default: maxPlayersInRoom = 6; break; } if (team.Type == 0 && team.Members.Count > 2 || team.Type == 0 && team.Members.Count >= 1 && locationData.GameMode == "DuoShowdown") { TeamErrorMessage errorMessage = new TeamErrorMessage(); errorMessage.Reason = 2; Connection.Send(errorMessage); return; } } } if (team.Type == 1 && team.Members.Count >= maxPlayersInRoom) { TeamErrorMessage errorMessage = new TeamErrorMessage(); errorMessage.Reason = 2; Connection.Send(errorMessage); return; } HomeMode.Avatar.TeamId = team.Id; TeamMember member = new TeamMember { AccountId = HomeMode.Avatar.AccountId, CharacterId = HomeMode.Home.CharacterId, DisplayData = new PlayerDisplayData( HomeMode.Home.HasPremiumPass, HomeMode.Home.ThumbnailId, HomeMode.Home.NameColorId, HomeMode.Avatar.Name) }; Hero hero = HomeMode.Avatar.GetHero(HomeMode.Home.CharacterId); member.HeroLevel = hero.PowerLevel + 1; member.Starpower = 0; member.Gadget = 0; if (hero.SelectedStarPowerId > 0) { CardData starPower = DataTables.Get(DataType.Card) .GetDataByGlobalId( GlobalId.CreateGlobalId(23, hero.SelectedStarPowerId)); if (starPower != null) { member.Starpower = starPower.GetGlobalId(); } } if (hero.SelectedGadgetId > 0) { CardData gadget = DataTables.Get(DataType.Card) .GetDataByGlobalId( GlobalId.CreateGlobalId(23, hero.SelectedGadgetId)); if (gadget != null) member.Gadget = gadget.GetGlobalId(); } member.SkinId = GlobalId.CreateGlobalId(29, hero.SelectedSkinId); member.HeroTrophies = hero.Trophies; member.HeroHighestTrophies = hero.HighestTrophies; member.IsOwner = false; member.State = 2; team.Members.Add(member); team.TeamUpdated(); } private void TeamJoinOrCreateRoomReceived(TeamJoinOrCreateRoomMessage message) { } private void ClientInfoReceived(ClientInfoMessage message) { UdpConnectionInfoMessage info = new UdpConnectionInfoMessage(); info.SessionId = Connection.UdpSessionId; info.ServerAddress = Configuration.Instance.UdpHost; info.ServerPort = Configuration.Instance.UdpPort; Connection.Send(info); } private void CancelMatchMaking(CancelMatchmakingMessage message) { Matchmaking.CancelMatchmake(Connection); Connection.Send(new MatchMakingCancelledMessage()); } private void MatchmakeRequestReceived(MatchmakeRequestMessage message) { int slot = message.EventSlot; if (HomeMode.Home.Character.Disabled) { Connection.Send(new OutOfSyncMessage()); return; } if (!Events.HasSlot(slot)) { slot = 1; } Matchmaking.RequestMatchmake(Connection, slot); } private void EndClientTurnReceived(EndClientTurnMessage message) { foreach (Command command in message.Commands) { if (!CommandManager.ReceiveCommand(command)) { OutOfSyncMessage outOfSync = new(); Connection.Send(outOfSync); } } HomeMode.ClientTurnReceived(message.Tick, message.Checksum, message.Commands); } private void GetPlayerProfile(GetPlayerProfileMessage message) { if (message.AccountId == 0) { Profile p = Profile.CreateConsole(); PlayerProfileMessage a = new PlayerProfileMessage(); a.Profile = p; Connection.Send(a); return; } Account data = Accounts.Load(message.AccountId); if (data == null) return; Profile profile = Profile.Create(data.Home, data.Avatar); PlayerProfileMessage profileMessage = new PlayerProfileMessage(); profileMessage.Profile = profile; if (data.Avatar.AllianceId >= 0) { Alliance alliance = Alliances.Load(data.Avatar.AllianceId); if (alliance != null) { profileMessage.AllianceHeader = alliance.Header; profileMessage.AllianceRole = data.Avatar.AllianceRole; } } Connection.Send(profileMessage); } private void ChangeName(ChangeAvatarNameMessage message) { LogicChangeAvatarNameCommand command = new() { Name = message.Name, ChangeNameCost = 0 }; if (HomeMode.Avatar.AllianceId >= 0) { Alliance a = Alliances.Load(HomeMode.Avatar.AllianceId); if (a == null) return; AllianceMember m = a.GetMemberById(HomeMode.Avatar.AccountId); m.DisplayData.Name = message.Name; } command.Execute(HomeMode); AvailableServerCommandMessage serverCommandMessage = new() { Command = command }; Connection.Send(serverCommandMessage); } private void OnChangeCharacter(int characterId) { TeamEntry team = Teams.Get(HomeMode.Avatar.TeamId); if (team == null) return; TeamMember member = team.GetMember(HomeMode.Avatar.AccountId); if (member == null) return; Hero hero = HomeMode.Avatar.GetHero(characterId); if (hero == null) return; member.CharacterId = characterId; member.HeroTrophies = hero.Trophies; member.HeroHighestTrophies = hero.HighestTrophies; member.HeroLevel = hero.PowerLevel + 1; member.Starpower = 0; member.Gadget = 0; if (hero.SelectedStarPowerId > 0) { CardData starPower = DataTables.Get(DataType.Card) .GetDataByGlobalId(GlobalId.CreateGlobalId(23, hero.SelectedStarPowerId)); if (starPower != null) { member.Starpower = starPower.GetGlobalId(); } } if (hero.SelectedGadgetId > 0) { CardData gadget = DataTables.Get(DataType.Card) .GetDataByGlobalId(GlobalId.CreateGlobalId(23, hero.SelectedGadgetId)); if (gadget != null) member.Gadget = gadget.GetGlobalId(); } member.SkinId = GlobalId.CreateGlobalId(29, hero.SelectedSkinId); team.TeamUpdated(); } private void LoginReceived(AuthenticationMessage message) { Account account = null; if (message.Major != 36) { AuthenticationFailedMessage loginFailed = new AuthenticationFailedMessage(); loginFailed.ErrorCode = 8; loginFailed.Message = "Update!"; loginFailed.UpdateUrl = "https://t.me/aimbrawl"; Connection.Send(loginFailed); return; } if (message.AccountId == 0) { account = Accounts.Create(); } else { account = Accounts.Load(message.AccountId); if (account == null) { AuthenticationFailedMessage loginFailed = new AuthenticationFailedMessage(); loginFailed.ErrorCode = 1; loginFailed.Message = "Clear data game!"; loginFailed.UpdateUrl = "https://t.me/aimbrawl"; Connection.Send(loginFailed); Connection.Send(new CreateAccountOkMessage { AccountId = 0, PassToken = "" }); return; } if (account.PassToken != message.PassToken) { account = null; } } if (message.RndKey == 1456) { // return; } if (account == null) { AuthenticationFailedMessage loginFailed = new AuthenticationFailedMessage(); loginFailed.ErrorCode = 1; loginFailed.Message = "Clear data game!"; loginFailed.UpdateUrl = "https://t.me/aimbrawl"; Connection.Send(loginFailed); Connection.Send(new CreateAccountOkMessage { AccountId = 0, PassToken = "" }); return; } if (account.Avatar.Banned) { AuthenticationFailedMessage loginFailed = new AuthenticationFailedMessage(); loginFailed.ErrorCode = 11; Connection.Send(loginFailed); return; } AuthenticationOkMessage loginOk = new AuthenticationOkMessage(); if (!account.Avatar.ShouldRedirect) { loginOk.AccountId = account.AccountId; loginOk.PassToken = account.PassToken; loginOk.Major = message.Major; loginOk.Minor = message.Minor; loginOk.Build = message.Build; loginOk.ServerEnvironment = "prod"; } else { //account.Avatar.ShouldRedirect = false; Account t = Accounts.Load(account.Avatar.RedirectId); account = t; loginOk.AccountId = t.AccountId; loginOk.PassToken = t.PassToken; loginOk.Major = message.Major; loginOk.Minor = message.Minor; loginOk.Build = message.Build; loginOk.ServerEnvironment = "prod"; } Connection.Send(loginOk); /*AuthenticationFailedMessage loginFailedPath = new AuthenticationFailedMessage(); loginFailedPath.ErrorCode = 7; loginFailedPath.Message = "Update assets"; loginFailedPath.UpdateUrl = "https://t.me/aimbrawl"; loginFailedPath.ContentUrl = "http://144.31.14.115:9090/"; loginFailedPath.FingerprintSha = Fingerprint.Sha; Connection.Send(loginFailedPath);*/ HomeMode = HomeMode.LoadHomeState(new HomeGameListener(Connection), account.Home, account.Avatar, Events.GetEventsById(account.Home.PowerPlayGamesPlayed, account.Avatar.AccountId)); HomeMode.CharacterChanged += OnChangeCharacter; HomeMode.Home.IpAddress = Connection.Socket.RemoteEndPoint.ToString().Split(" ")[0]; HomeMode.Home.Device = message.DeviceId; if (HomeMode.Avatar.HighestTrophies == 0 && HomeMode.Avatar.Trophies != 0) { HomeMode.Avatar.HighestTrophies = HomeMode.Avatar.Trophies; } if (HomeMode.Avatar.HighestTrophies < HomeMode.Avatar.Trophies) { HomeMode.Avatar.HighestTrophies = HomeMode.Avatar.Trophies; } CommandManager = new(HomeMode, Connection); if (HomeMode.Avatar.BattleStartTime != new DateTime()) { Hero h = HomeMode.Avatar.GetHero(HomeMode.Home.CharacterId); int lose = 0; int brawlerTrophies = h.Trophies; if (brawlerTrophies <= 49) { lose = 0; } else if (50 <= brawlerTrophies && brawlerTrophies <= 99) { lose = -1; } else if (100 <= brawlerTrophies && brawlerTrophies <= 199) { lose = -2; } else if (200 <= brawlerTrophies && brawlerTrophies <= 299) { lose = -3; } else if (300 <= brawlerTrophies && brawlerTrophies <= 399) { lose = -4; } else if (400 <= brawlerTrophies && brawlerTrophies <= 499) { lose = -5; } else if (500 <= brawlerTrophies && brawlerTrophies <= 599) { lose = -6; } else if (600 <= brawlerTrophies && brawlerTrophies <= 699) { lose = -7; } else if (700 <= brawlerTrophies && brawlerTrophies <= 799) { lose = -8; } else if (800 <= brawlerTrophies && brawlerTrophies <= 899) { lose = -9; } else if (900 <= brawlerTrophies && brawlerTrophies <= 999) { lose = -10; } else if (1000 <= brawlerTrophies && brawlerTrophies <= 1099) { lose = -11; } else if (1100 <= brawlerTrophies && brawlerTrophies <= 1199) { lose = -12; } else if (brawlerTrophies >= 1200) { lose = -12; } h.AddTrophies(lose); HomeMode.Home.PowerPlayGamesPlayed = Math.Max(0, HomeMode.Home.PowerPlayGamesPlayed - 1); Connection.Home.Events = Events.GetEventsById(HomeMode.Home.PowerPlayGamesPlayed, Connection.Avatar.AccountId); HomeMode.Avatar.BattleStartTime = new DateTime(); } BattleMode battle = null; if (HomeMode.Avatar.BattleId > 0) { battle = Battles.Get(HomeMode.Avatar.BattleId); } if (battle == null) { OwnHomeDataMessage ohd = new OwnHomeDataMessage(); ohd.Home = HomeMode.Home; ohd.Avatar = HomeMode.Avatar; Connection.Send(ohd); } else { StartLoadingMessage startLoading = new StartLoadingMessage(); startLoading.LocationId = battle.Location.GetGlobalId(); startLoading.TeamIndex = HomeMode.Avatar.TeamIndex; startLoading.OwnIndex = HomeMode.Avatar.OwnIndex; startLoading.GameMode = battle.GetGameModeVariation(); if (battle.BattlePlayerMap != null && battle.BattlePlayerMap.MapData != null) { startLoading.SetPlayerMap(battle.BattlePlayerMap); } startLoading.Players.AddRange(battle.GetPlayers()); UDPSocket socket = UDPGateway.CreateSocket(); socket.TCPConnection = Connection; socket.Battle = battle; if (!battle.BattleWithTrophies) startLoading.isFriendlyMatch = true; if (battle.GetGameModeVariation() == 13) startLoading.GameType = 8; Connection.UdpSessionId = socket.SessionId; battle.ChangePlayerSessionId(HomeMode.Avatar.UdpSessionId, socket.SessionId); HomeMode.Avatar.UdpSessionId = socket.SessionId; Connection.Send(startLoading); } Connection.Avatar.LastOnline = DateTime.UtcNow; Sessions.Create(HomeMode, Connection); if (true) { HomeMode.Avatar.PlayerStatus = 3; FriendListMessage friendList = new FriendListMessage(); friendList.Friends = HomeMode.Avatar.Friends.ToArray(); Connection.Send(friendList); if (HomeMode.Avatar.AllianceRole != AllianceRole.None && HomeMode.Avatar.AllianceId > 0) { Alliance alliance = Alliances.Load(HomeMode.Avatar.AllianceId); if (alliance != null) { SendMyAllianceData(alliance); AllianceDataMessage data = new AllianceDataMessage(); data.Alliance = alliance; data.IsMyAlliance = true; Connection.Send(data); } } foreach (Friend entry in HomeMode.Avatar.Friends.ToArray()) { if (LogicServerListener.Instance.IsPlayerOnline(entry.AccountId)) { FriendOnlineStatusEntryMessage statusMessage = new FriendOnlineStatusEntryMessage(); statusMessage.AvatarId = entry.AccountId; statusMessage.PlayerStatus = entry.Avatar?.PlayerStatus ?? 0; Connection.Send(statusMessage); } } foreach (Friend entry in HomeMode.Avatar.Friends.ToArray()) { Session friendSession = Sessions.GetSession(entry.AccountId); if (friendSession != null) { FriendOnlineStatusEntryMessage statusMessage = new FriendOnlineStatusEntryMessage(); statusMessage.AvatarId = HomeMode.Avatar.AccountId; statusMessage.PlayerStatus = HomeMode.Avatar.PlayerStatus; friendSession.Connection.Send(statusMessage); } } if (HomeMode.Avatar.TeamId > 0) { TeamMessage teamMessage = new TeamMessage(); teamMessage.Team = Teams.Get(HomeMode.Avatar.TeamId); if (teamMessage.Team != null) { Connection.Send(teamMessage); TeamMember member = teamMessage.Team.GetMember(HomeMode.Avatar.AccountId); if (member != null) { member.State = 0; teamMessage.Team.TeamUpdated(); } } else { HomeMode.Avatar.TeamId = -1; } } } } private void ClientHelloReceived(ClientHelloMessage message) { if (message.KeyVersion != PepperKey.VERSION) { //return; } if (message.Major != 36) { AuthenticationFailedMessage loginFailed = new AuthenticationFailedMessage(); loginFailed.ErrorCode = 8; loginFailed.Message = "Сервер обновился.\nt.me/aimbrawl"; loginFailed.UpdateUrl = "https://t.me/aimbrawl"; Connection.Send(loginFailed); return; } if (Sessions.Maintenance) { Connection.Send(new AuthenticationFailedMessage() { ErrorCode = 10 }); return; } Connection.Messaging.Seed = message.ClientSeed; Random r = new(); ServerHelloMessage hello = new ServerHelloMessage(); hello.SetServerHelloToken(Connection.Messaging.SessionToken); Connection.Send(hello); } } }