protected void UpdateResources( IGameData gameData, DataModels.GameSession session, Character character, DataModels.Resources resources) { if (resources == null) { resources = new DataModels.Resources { Id = Guid.NewGuid(), }; gameData.Add(resources); character.ResourcesId = resources.Id; } var user = gameData.GetUser(character.UserId); var gameEvent = gameData.CreateSessionEvent(GameEventType.ResourceUpdate, session, new ResourceUpdate { UserId = user.UserId, FishAmount = resources.Fish, OreAmount = resources.Ore, WheatAmount = resources.Wheat, WoodAmount = resources.Wood, CoinsAmount = resources.Coins }); gameData.Add(gameEvent); }
public bool KickPlayer(string userId) { var character = gameData.GetCharacterByUserId(userId); var userToRemove = gameData.GetUser(character.UserId); if (userToRemove == null) { return(false); } var currentSession = gameData.GetSessionByUserId(userId); //var currentSession = gameData.GetUserSession(character.UserIdLock.GetValueOrDefault()); if (currentSession == null) { return(false); } var characterUser = gameData.GetUser(character.UserId); var gameEvent = gameData.CreateSessionEvent( GameEventType.PlayerRemove, currentSession, new PlayerRemove() { Reason = $"{character.Name} was kicked remotely.", UserId = characterUser.UserId }); gameData.Add(gameEvent); return(true); }
public ItemSellResult SellItem( SessionToken token, string userId, Guid itemId, long amount, decimal pricePerItem) { if (amount <= 0 || pricePerItem <= 0) { return(new ItemSellResult(ItemTradeState.RequestToLow)); } var character = GetCharacterAsync(token, userId); if (character == null) { return(new ItemSellResult(ItemTradeState.Failed)); } if (!playerManager.AcquiredUserLock(token, character)) { return(new ItemSellResult(ItemTradeState.Failed)); } var itemsToSell = gameData.GetInventoryItems(character.Id, itemId); var totalItemCount = itemsToSell.Count > 0 ? itemsToSell.Sum(x => x.Amount.GetValueOrDefault()) : 0; var newItemAmount = totalItemCount - amount; if (itemsToSell.Count == 0 || newItemAmount < 0) { return(new ItemSellResult(ItemTradeState.DoesNotOwn)); } gameData.RemoveRange(itemsToSell); if (newItemAmount > 0) { var mergedInventoryItem = new InventoryItem { Id = Guid.NewGuid(), Amount = newItemAmount, CharacterId = character.Id, Equipped = false, ItemId = itemId, }; gameData.Add(mergedInventoryItem); } var marketItem = new DataModels.MarketItem { Id = Guid.NewGuid(), Amount = amount, Created = DateTime.UtcNow, ItemId = itemId, PricePerItem = pricePerItem, SellerCharacterId = character.Id, }; gameData.Add(marketItem); return(new ItemSellResult(ItemTradeState.Success)); }
public void BroadcastMessageAsync(string message, int time) { var sessions = gameData.GetActiveSessions(); foreach (var session in sessions) { var gameEvent = gameData.CreateSessionEvent(GameEventType.ServerMessage, session, new ServerMessage() { Message = message, Time = time }); gameData.Add(gameEvent); } }
public Task <Agreements> UpdateCodeOfConduct(UpdateCodeOfConduct data) { return(Task.Run(() => { var agreements = gameData.GetAllAgreements(); var coc = agreements.FirstOrDefault(x => x.Type.ToLower() == "coc"); if (coc != null) { if (coc.Message != data.Message || coc.Title != data.Title || coc.VisibleInClient != data.VisibleInClient) { coc.Message = data.Message; coc.Title = data.Title; coc.Revision = coc.Revision + 1; coc.LastModified = DateTime.UtcNow; coc.VisibleInClient = data.VisibleInClient; } } else { coc = new Agreements { Id = Guid.NewGuid(), Type = "coc", Message = data.Message, Title = data.Title, Revision = 1, ValidFrom = DateTime.UtcNow, LastModified = DateTime.UtcNow, VisibleInClient = data.VisibleInClient }; gameData.Add(coc); } return coc; })); }
private void AddItem(Item item) { var entity = ModelMapper.Map(item); gameData.Add(entity); InvalidateCache(); }
private UserPatreon GetOrCreateUserPatreon(IPatreonData data) { var patreon = gameData.GetPatreonUser(data.PatreonId); if (patreon != null) { return(patreon); } var now = DateTime.UtcNow; var firstName = data.FullName?.Split(' ')?.FirstOrDefault(); var pledgeAmount = GetPledgeAmount(data); var title = GetTierTitle(data); patreon = new UserPatreon() { Id = Guid.NewGuid(), Email = data.Email, FullName = data.FullName, PatreonId = data.PatreonId, PledgeAmount = pledgeAmount, PledgeTitle = title, Tier = data.Tier, TwitchUserId = data.TwitchUserId, FirstName = firstName, //TwitchUserId = data.TwitchUserId ?? user?.UserId, //UserId = user?.Id, Updated = now, Created = now, }; gameData.Add(patreon); return(patreon); }
public IActionResult OnPost() { if (ModelState.IsValid) { var g = _gameData.Add(_gameConverter.ToEntity(Game)); return(RedirectToAction("Details", "Games", new { id = g.Id })); } return(Page()); }
private void UpdateClanExperience(IGameData gameData, GameSession session, Clan clan) { var now = DateTime.UtcNow; var elapsed = TimeSpan.Zero; if (clanExpUpdate.TryGetValue(clan.Id, out var lastUpdate)) { elapsed = now - lastUpdate; } if (clan.Level == 0) { clan.Level = 1; } var exp = elapsed.TotalSeconds; //var multi = gameData.GetActiveExpMultiplierEvent(); //if (multi != null) //{ // exp *= multi.Multiplier; //} clan.Experience += exp; var nextLevel = GameMath.ExperienceForLevel(clan.Level + 1); var oldLevel = clan.Level; while (clan.Experience >= nextLevel) { clan.Experience -= nextLevel; ++clan.Level; nextLevel = GameMath.ExperienceForLevel(clan.Level + 1); } clanExpUpdate[clan.Id] = now; var announcementKey = session.Id + "_" + clan.Id; // Use session ID and not clan ID as we need to send to all open clients and not just once per clan. if (!clanExpAnnouncement.TryGetValue(announcementKey, out var lastAnnouncement)) { clanExpAnnouncement[announcementKey] = now; } if (now - lastAnnouncement > UpdateInterval) { gameData.Add(gameData.CreateSessionEvent(GameEventType.ClanLevelChanged, session, new ClanLevelChanged { ClanId = clan.Id, Experience = (long)clan.Experience, Level = clan.Level, LevelDelta = clan.Level - oldLevel, })); clanExpAnnouncement[announcementKey] = now; } }
public ActionResult Create(Game game) { //if (ModelState.IsValid) //{ // db.Add(game); // return RedirectToAction("Details", new { id= game.Id}); //} db.Add(game); return(RedirectToAction("Index")); }
//public bool FixCharacterExpGain(Guid characterId) //{ // var character = gameData.GetCharacter(characterId); // if (character == null) return false; // var playerSkills = gameData.GetSkills(character.SkillsId); // if (playerSkills == null) return false; // var skills = playerSkills.GetSkills(); // foreach (var skill in skills) // { // var level = skill.Level; // var cappedLevel = level > 170 ? 170 : level; // var expBase = GameMath.OLD_ExperienceToLevel(cappedLevel); // var newLevelDiff = level - cappedLevel; // var totalGainedExp = 0m; // for (var i = 1; i <= newLevelDiff; ++i) // { // totalGainedExp += GameMath.ExperienceForLevel(level + i); // } // skill.Experience // } //} public bool AddCoins(string query, string identifier) { var character = itemResolver.ResolveCharacter(query, identifier); if (character == null) { return(false); } var amount = query.Split(' ').LastOrDefault(); if (long.TryParse(amount, out var amountValue)) { var resx = gameData.GetResourcesByCharacterId(character.Id); if (resx == null) { resx = new DataModels.Resources { Id = Guid.NewGuid(), Coins = amountValue }; character.ResourcesId = resx.Id; gameData.Add(resx); return(true); } resx.Coins += amountValue; return(true); } return(false); }
public bool AddItem(Item item) { var dataItem = gameData.GetItem(item.Id); if (dataItem == null) { var entity = ModelMapper.Map(item); gameData.Add(entity); return(true); } return(false); }
protected void IncrementItemStack( IGameData gameData, DataModels.GameSession session, Character character, Guid itemId) { var items = gameData.GetInventoryItems(character.Id, itemId); if (items == null || items.Count == 0) { gameData.Add(CreateInventoryItem(character, itemId)); } else { ++items.First().Amount; } var user = gameData.GetUser(character.UserId); gameData.Add(gameData.CreateSessionEvent(GameEventType.ItemAdd, session, new ItemAdd { UserId = user.UserId, Amount = 1, ItemId = itemId })); }
private void UpdateResources(IGameData gameData, DataModels.GameSession session, Character character, DataModels.Resources resources) { var user = gameData.GetUser(character.UserId); var gameEvent = gameData.CreateSessionEvent(GameEventType.ResourceUpdate, session, new ResourceUpdate { UserId = user.UserId, FishAmount = resources.Fish, OreAmount = resources.Ore, WheatAmount = resources.Wheat, WoodAmount = resources.Wood, CoinsAmount = resources.Coins }); gameData.Add(gameEvent); }
protected void IncrementItemStack( IGameData gameData, IPlayerInventoryProvider inventoryProvider, DataModels.GameSession session, Character character, Guid itemId) { var inventory = inventoryProvider.Get(character.Id); var items = inventory.AddItem(itemId); gameData.Add(gameData.CreateSessionEvent(GameEventType.ItemAdd, session, new ItemAdd { UserId = gameData.GetUser(character.UserId).UserId, Amount = 1, ItemId = itemId, InventoryItemId = items.FirstOrDefault().Id, })); }
public bool SendPlayerInvite(Guid clanId, Guid characterId, Guid?senderUserId = null) { // character does not exist var character = gameData.GetCharacter(characterId); if (character == null) { return(false); } // clan does not exist var clan = gameData.GetClan(clanId); if (clan == null) { return(false); } // existing invite to same clan. var invite = gameData.GetClanInvitesByCharacter(characterId).FirstOrDefault(x => x.ClanId == clanId); if (invite != null) { return(false); } invite = new DataModels.CharacterClanInvite { Id = Guid.NewGuid(), CharacterId = characterId, ClanId = clanId, Created = DateTime.UtcNow, InviterUserId = senderUserId }; invite.NotificationId = notificationManager.ClanInviteReceived(clanId, characterId, senderUserId)?.Id; gameData.Add(invite); return(true); }
private static void EnsureClanSkills(IGameData gameData, Clan clan, IReadOnlyList <ClanSkill> clanSkills) { foreach (var s in gameData .GetSkills() .Where(x => x.RequiredClanLevel <= clan.Level && !clanSkills.Any(y => y.SkillId == x.Id))) { var newSkill = new ClanSkill { Id = Guid.NewGuid(), ClanId = clan.Id, Experience = 0, Level = 1, SkillId = s.Id }; gameData.Add(newSkill); } }
public override void Process( IIntegrityChecker integrityChecker, IGameData gameData, IPlayerInventoryProvider inventoryProvider, DataModels.GameSession session, Character character, CharacterState characterState) { var now = DateTime.UtcNow; var resources = gameData.GetResources(character.ResourcesId); if (resources == null) { resources = new DataModels.Resources { Id = Guid.NewGuid(), }; gameData.Add(resources); character.ResourcesId = resources.Id; } var state = gameData.GetCharacterSessionState(session.Id, character.Id); if (now - state.LastTaskUpdate >= TimeSpan.FromSeconds(ItemDropRateSettings.ResourceGatherInterval)) { session.Updated = DateTime.UtcNow; state.LastTaskUpdate = DateTime.UtcNow; if (resources.Ore >= OrePerIngot) { resources.Ore -= OrePerIngot; IncrementItemStack(gameData, inventoryProvider, session, character, IngotId); } if (resources.Wood >= WoodPerPlank) { resources.Wood -= WoodPerPlank; IncrementItemStack(gameData, inventoryProvider, session, character, PlankId); } UpdateResources(gameData, session, character, resources); } }
public override void Process( IIntegrityChecker integrityChecker, IGameData gameData, IPlayerInventoryProvider inventoryProvider, DataModels.GameSession session, Character character, CharacterState state) { if (DateTime.UtcNow - lastUpdate < updateInterval) { return; } var village = gameData.GetOrCreateVillageBySession(session); var players = gameData.GetSessionCharacters(session); village.Experience += players.Count * 20; var newLevel = GameMath.OLD_ExperienceToLevel(village.Experience); var levelDelta = newLevel - village.Level; village.Level = newLevel; var villageHouses = gameData.GetOrCreateVillageHouses(village); if (levelDelta > 0 || DateTime.UtcNow - lastExpSend > updateExpInterval) { var data = new VillageLevelUp { Experience = village.Experience, Level = village.Level, LevelDelta = levelDelta, HouseSlots = villageHouses.Count }; gameData.Add(gameData.CreateSessionEvent(GameEventType.VillageLevelUp, session, data)); lastExpSend = DateTime.UtcNow; } lastUpdate = DateTime.UtcNow; }
private UserLoyalty CreateUserLoyalty( IGameData gameData, GameSession session, User user) { var loyalty = new UserLoyalty { Id = Guid.NewGuid(), Playtime = "00:00:00", Points = 0, Experience = 0, StreamerUserId = session.UserId, UserId = user.Id, Level = 1, CheeredBits = 0, GiftedSubs = 0 }; gameData.Add(loyalty); return(loyalty); }
public Task BroadcastMessageAsync(string message) { // 1. get all active sessions var sessions = gameData.GetActiveSessions(); //var sessions = await db.GameSession // .Include(x => x.GameEvents) // .Where(x => x.Stopped != null) // .ToListAsync(); // 2. push a new event for each session foreach (var session in sessions) { //var revision = session.GameEvents.Count > 0 // ? session.GameEvents.Max(x => x.Revision) + 1 : 1; var gameEvent = gameData.CreateSessionEvent(GameEventType.ServerMessage, session, new ServerMessage() { Message = message, }); gameData.Add(gameEvent); //await db.GameEvent.AddAsync(new DataModels.GameEvent() //{ // Id = Guid.NewGuid(), // GameSessionId = session.Id, // GameSession = session, // Data = JSON.Stringify(new ServerMessage() // { // Message = message, // }), // Type = (int)GameEventType.ServerMessage, // Revision = revision //}); } return(Task.CompletedTask); }
private void UpdateSessionTasks(DateTime utcNow) { var session = gameData.GetSession(sessionToken.SessionId); if (session == null) { return; } // force keep a session alive if we are connected here session.Stopped = null; session.Status = (int)SessionStatus.Active; session.Updated = utcNow; var village = GetTaskProcessor(VillageProcessorName); if (village != null) { village.Process(integrityChecker, gameData, inventoryProvider, session, null, null); } var characters = gameData.GetSessionCharacters(session); if (characters.Count > 0) { var loyalty = GetTaskProcessor(LoyaltyProcessorName); var clan = GetTaskProcessor(ClanProcessorName); var rested = GetTaskProcessor(RestedProcessorName); foreach (var character in characters) { //if (character.CharacterIndex == 0) //{ // var inventory = inventoryProvider.Get(character.Id); // inventory.AddPatreonTierRewards(); //} var state = gameData.GetCharacterState(character.StateId); if (state == null) { state = new DataModels.CharacterState { Id = Guid.NewGuid() }; gameData.Add(state); character.StateId = state.Id; } rested.Process(integrityChecker, gameData, inventoryProvider, session, character, state); clan.Process(integrityChecker, gameData, inventoryProvider, session, character, state); loyalty.Process(integrityChecker, gameData, inventoryProvider, session, character, state); if (string.IsNullOrEmpty(state.Task) || (state.InOnsen ?? false) || (state.InDungeon ?? false) || state.InArena || state.InRaid || string.IsNullOrEmpty(state.Island) || state.Island == "War" || !string.IsNullOrEmpty(state.DuelOpponent)) { continue; } var task = GetTaskProcessor(state.Task); if (task != null) { task.Process(integrityChecker, gameData, inventoryProvider, session, character, state); } } } }
public async Task <ExtensionPlayerJoinResult> PlayerJoin(string broadcasterId) { var result = new ExtensionPlayerJoinResult(); if (string.IsNullOrEmpty(broadcasterId)) { result.ErrorMessage = "Invalid broadcaster or bad character id"; return(result); } var activeSession = gameData.GetOwnedSessionByUserId(broadcasterId); if (activeSession == null) { result.ErrorMessage = "Broadcaster does not have an active game session"; return(result); } if (TryGetSession(out var sessionInfo)) { var user = gameData.GetUser(sessionInfo.AccountId); if (user == null) { result.ErrorMessage = "No such user."; return(result); } var existingCharacters = gameData.GetCharactersByUserId(user.Id); if (existingCharacters.Count >= 3) { result.ErrorMessage = "You already have 3 characters."; return(result); } var index = existingCharacters.Count + 1; var player = await playerManager.CreatePlayer(user.UserId, user.UserName, index.ToString()); if (player == null) { result.ErrorMessage = "Failed to create a new character."; return(result); } var c = gameData.GetCharacter(player.Id); if (c == null) { result.ErrorMessage = "Okay. We don't know what went wrong here. Very sorry!"; return(result); } // We are just going to assume that it was successeful // since, if it "fails" as the character is already in game. well. Then what harm done? result.Success = true; result.Player = c.MapForWebsite(gameData, user); sessionInfoProvider.SetActiveCharacter(sessionInfo, c.Id); var gameEvent = gameData.CreateSessionEvent( GameEventType.PlayerAdd, activeSession, new PlayerAdd() { CharacterId = c.Id, Identifier = c.Identifier, UserId = sessionInfo.UserId, UserName = sessionInfo.UserName }); gameData.Add(gameEvent); } else { result.ErrorMessage = "You don't seem to be authenticated."; return(result); } return(result); }
public bool WalkTo(string userId, int x, int y, int z) { var targetSession = gameData.GetSessionByUserId(userId); if (targetSession == null) { return(false); } var character = gameData.GetCharacterByUserId(userId); if (character == null) { return(false); } gameData.Add(gameData.CreateSessionEvent( GameEventType.PlayerMove, targetSession, new PlayerMove() { UserId = userId, X = x, Y = y, Z = z } )); return(true); }
public override void Process( IIntegrityChecker integrityChecker, IGameData gameData, IPlayerInventoryProvider inventoryProvider, GameSession session, Character character, CharacterState state) { if (state == null) { return; } var isResting = state.InOnsen.GetValueOrDefault() && !state.InDungeon.GetValueOrDefault() && !state.InArena && !state.InRaid && !string.IsNullOrEmpty(state.Island) && string.IsNullOrEmpty(state.DuelOpponent); var now = DateTime.UtcNow; if (!lastUpdate.TryGetValue(character.Id, out var lastUpdateTime)) { lastUpdateTime = now; } var elapsed = now - lastUpdateTime; var requireUpdate = isResting ? AddRestTime(state, elapsed) : RemoveRestTime(state, elapsed); if (!lastEvent.TryGetValue(character.Id, out var lastEventUpdate)) { lastEventUpdate = DateTime.MinValue; } if (requireUpdate) { var sinceLastEvent = now - lastEventUpdate; if (sinceLastEvent >= RestedEventUpdateInterval) { var restedTime = (double)(state.RestedTime ?? 0); var restedPercent = restedTime / MaxRestTime.TotalSeconds; var isRested = restedTime > 0; var data = new Models.PlayerRestedUpdate { CharacterId = character.Id, ExpBoost = isRested ? ExpBoost : 0, StatsBoost = isRested ? CombatStatsBoost : 0, RestedTime = restedTime, RestedPercent = restedPercent, }; var gameEvent = gameData.CreateSessionEvent(GameEventType.PlayerRestedUpdate, session, data); gameData.Add(gameEvent); lastEvent[character.Id] = now; if (restedTime > 0) { TrySendToExtensionAsync(character, data); } } } lastUpdate[character.Id] = now; }
public ItemSellResult SellItem( SessionToken token, string userId, Guid itemId, long amount, double pricePerItem) { //if (i != null && i.Category == (int)DataModels.ItemCategory.StreamerToken) //{ // return new ItemSellResult(ItemTradeState.Failed); //} if (amount <= 0 || pricePerItem <= 0) { return(new ItemSellResult(ItemTradeState.RequestToLow)); } if (pricePerItem >= 1_000_000_000) { return(new ItemSellResult(ItemTradeState.Failed)); } var character = GetCharacterAsync(token, userId); if (character == null) { return(new ItemSellResult(ItemTradeState.Failed)); } if (!playerManager.AcquiredUserLock(token, character)) { return(new ItemSellResult(ItemTradeState.Failed)); } var inventory = inventoryProvider.Get(character.Id); var session = gameData.GetSession(token.SessionId); var sessionOwner = gameData.GetUser(session.UserId); var item = gameData.GetItem(itemId); string itemTag = null; if (item.Soulbound.GetValueOrDefault()) { return(new ItemSellResult(ItemTradeState.Untradable)); } if (item.Category == (int)DataModels.ItemCategory.StreamerToken) { itemTag = sessionOwner.UserId; } var itemToSell = inventory.GetUnequippedItem(itemId, tag: itemTag); if (itemToSell.IsNull()) { return(new ItemSellResult(ItemTradeState.DoesNotOwn)); } var totalItemCount = itemToSell.Amount;//itemsToSell.Count > 0 ? itemsToSell.Sum(x => x.Amount.GetValueOrDefault()) : 0; var newItemAmount = totalItemCount - amount; if (newItemAmount < 0) { return(new ItemSellResult(ItemTradeState.DoesNotOwn)); } inventory.RemoveItem(itemToSell, amount); var marketItem = new DataModels.MarketItem { Id = Guid.NewGuid(), Amount = amount, Created = DateTime.UtcNow, ItemId = itemId, PricePerItem = pricePerItem, SellerCharacterId = character.Id, Tag = itemToSell.Tag, Flags = itemToSell.Flags, Enchantment = itemToSell.Enchantment, Name = itemToSell.Name, TransmogrificationId = itemToSell.TransmogrificationId, Expires = DateTime.UtcNow.AddDays(14), }; gameData.Add(marketItem); return(new ItemSellResult(ItemTradeState.Success)); }
private void TryRemovePlayerFromPreviousSession(Character character, DataModels.GameSession joiningSession) { var userToRemove = gameData.GetUser(character.UserId); if (userToRemove == null) { return; } var currentSession = gameData.GetUserSession(character.UserIdLock.GetValueOrDefault()); if (currentSession == null || currentSession.Id == joiningSession.Id || currentSession.UserId == joiningSession.UserId) { return; } var targetSessionUser = gameData.GetUser(joiningSession.UserId); var characterUser = gameData.GetUser(character.UserId); var gameEvent = gameData.CreateSessionEvent( GameEventType.PlayerRemove, currentSession, new PlayerRemove() { Reason = targetSessionUser != null ? $"{character.Name} joined {targetSessionUser.UserName}'s stream" : $"{character.Name} joined another session.", UserId = characterUser.UserId }); gameData.Add(gameEvent); }
public async Task <SessionToken> BeginSessionAsync( AuthToken token, string clientVersion, string accessKey, bool isLocal, float syncTime) { var game = gameData.Client; var user = gameData.GetUser(token.UserId); if (game == null) { return(null); } if (game.AccessKey != accessKey) { return(null); } var userId = token.UserId; var activeSession = gameData.GetUserSession(userId); // x => x.UserId == userId && x.Status == (int)SessionStatus.Active if (activeSession != null) { EndSession(activeSession); } var newGameSession = gameData.CreateSession(userId); gameData.Add(newGameSession); var sessionState = gameData.GetSessionState(newGameSession.Id); sessionState.SyncTime = syncTime; var isAdmin = user.IsAdmin.GetValueOrDefault(); var isModerator = user.IsModerator.GetValueOrDefault(); var subInfo = await twitchClient.GetSubscriberAsync(user.UserId); var subscriptionTier = 0; var expMultiplierLimit = 0; if (subInfo != null && int.TryParse(subInfo.Tier, out subscriptionTier)) { subscriptionTier /= 1000; expMultiplierLimit = subscriptionTier == 1 ? 10 : (subscriptionTier - 1) * 25; } if (isModerator) { subscriptionTier = 3; expMultiplierLimit = 50; } if (isAdmin) { subscriptionTier = 3; expMultiplierLimit = 5000; } if (isAdmin || isModerator || subInfo != null) { var permissionEvent = gameData.CreateSessionEvent( GameEventType.PermissionChange, newGameSession, new Permissions { IsAdministrator = user.IsAdmin ?? false, IsModerator = user.IsModerator ?? false, SubscriberTier = subscriptionTier, ExpMultiplierLimit = expMultiplierLimit, }); gameData.Add(permissionEvent); } var village = gameData.GetOrCreateVillageBySession(newGameSession); var villageHouses = gameData.GetOrCreateVillageHouses(village); var villageInfoEvent = gameData.CreateSessionEvent( GameEventType.VillageInfo, newGameSession, new VillageInfo { Name = village.Name, Level = village.Level, Experience = village.Experience, Houses = villageHouses.Select(x => new VillageHouseInfo { Owner = x.UserId != null ? gameData.GetUser(x.UserId.Value).UserId : null, Slot = x.Slot, Type = x.Type } ).ToList() } ); gameData.Add(villageInfoEvent); return(GenerateSessionToken(token, newGameSession)); }
public async Task <SessionToken> BeginSessionAsync( AuthToken token, string clientVersion, string accessKey, bool isLocal, float syncTime) { var game = gameData.Client; var user = gameData.GetUser(token.UserId); if (game == null) { return(null); } if (game.AccessKey != accessKey) { //logger.LogError("Unable to start session for user: "******", client version: {clientVersion}, accessKey: {accessKey}"); return(null); } if (clientVersion.ToLower() != game.ClientVersion.ToLower()) { var expectedVersionStr = game.ClientVersion.Replace("a", ""); var clientVersionStr = clientVersion.Replace("a", ""); if (!Version.TryParse(clientVersionStr, out var version) || !Version.TryParse(expectedVersionStr, out var expectedVersion) || version < expectedVersion) { //logger.LogError("Unable to start session for user: "******", client version: {clientVersion}, accessKey: {accessKey}"); return(null); // new SessionToken(); } } var userId = token.UserId; gameData.ClearAllCharacterSessionStates(userId); var activeSession = gameData.GetSessionByUserId(userId); // x => x.UserId == userId && x.Status == (int)SessionStatus.Active var oldSessionExpired = false; var oldSession = activeSession; if (activeSession != null) { oldSessionExpired = DateTime.UtcNow - activeSession.Updated.GetValueOrDefault() >= TimeSpan.FromMinutes(30); if (oldSessionExpired) { activeSession.Status = (int)SessionStatus.Inactive; activeSession.Stopped = DateTime.UtcNow; activeSession = null; } } var newGameSession = activeSession ?? gameData.CreateSession(userId); if (activeSession == null) { gameData.Add(newGameSession); } if (oldSession != null && !oldSessionExpired) { logger.LogError("BeginSessionAsync was called while an existing session is active. User: "******". Previous players will not be cleared."); } else { var activeChars = gameData.GetSessionCharacters(newGameSession); if (activeChars != null) { foreach (var c in activeChars) { c.UserIdLock = null; } } //#if DEBUG // logger.LogDebug(user.UserName + " game session started. " + activeChars.Count + " characters cleared."); //#endif } newGameSession.Revision = 0; var sessionState = gameData.GetSessionState(newGameSession.Id); sessionState.SyncTime = syncTime; sessionState.ClientVersion = clientVersion; SendPermissionData(newGameSession, user); SendVillageInfo(newGameSession); return(GenerateSessionToken(token, user, newGameSession, clientVersion)); }
public static Player Map( this User user, IGameData gameData, Character character, bool rejoin = false, bool inGame = false) { var playItems = gameData.GetAllPlayerItems(character.Id); if (inGame && character.UserIdLock != null) { var targetStreamUser = gameData.GetUser(character.UserIdLock.Value); // if we got streamer tokens, only send the ones for the appropriate streamer playItems = playItems.Where(x => x.Tag == null || x.Tag == targetStreamUser.UserId).ToList(); } var invItems = Map(playItems); if (user == null) { return(null); } var clanMembership = gameData.GetClanMembership(character.Id); var clan = clanMembership != null?Map(gameData, gameData.GetClan(clanMembership.ClanId)) : null; var clanRole = clanMembership != null?Map(gameData.GetClanRole(clanMembership.ClanRoleId), clanMembership) : null; var characterState = gameData.GetCharacterState(character.StateId); if (character.StateId == null || characterState == null) { characterState = new DataModels.CharacterState() { Id = Guid.NewGuid() }; character.StateId = characterState.Id; gameData.Add(characterState); } return(new Player { Id = character.Id, UserName = user.UserName, UserId = user.UserId, Name = character.Name, IsRejoin = rejoin, IsAdmin = user.IsAdmin.GetValueOrDefault(), IsModerator = user.IsModerator.GetValueOrDefault(), Appearance = Map(gameData.GetAppearance(character.SyntyAppearanceId)), Resources = Map(gameData.GetResources(character.ResourcesId)), Skills = Map(gameData.GetCharacterSkills(character.SkillsId)), State = Map(characterState), InventoryItems = invItems, Statistics = Map(gameData.GetStatistics(character.StatisticsId)), Clan = clan, ClanRole = clanRole, OriginUserId = character.OriginUserId, Revision = character.Revision.GetValueOrDefault(), Identifier = character.Identifier, CharacterIndex = character.CharacterIndex, PatreonTier = user.PatreonTier.GetValueOrDefault(), IsHiddenInHighscore = user.IsHiddenInHighscore.GetValueOrDefault() }); }