private static void ConvertEvents(IEnumerable <Event> events, Raids raids)
 {
     foreach (var even in events)
     {
         Objects.GameObjects.Raid raid = ConvertEvent(even);
         raids.Raid.Add(raid);
     }
 }
 public RaidModel(Raids pRaid)
 {
     this.IdRaid    = pRaid.IdRaid;
     this.Pool      = new PoolModel(pRaid.IdPoolNavigation);
     this.Name      = pRaid.Name;
     this.Timestamp = pRaid.Timestamp;
     this.Ticks     = new List <TickModel>();
 }
        public async void CreateNewRaid()
        {
            RaidDate = RaidDate.ToLocalTime();
            Console.WriteLine($"NewRaidForm::CreateNewRaid ({RaidDate})");
            Raid raid = await RaidService.AddRaid(new Raid { Date = RaidDate });

            Raids.AddRaid(raid);
            RaidDate = DateTime.Now;
        }
Exemple #4
0
        public bool AddRaid(Raid raid, ulong senderId, ulong channelSenderId)
        {
            var roles = viewDiscordChannel.GetUserRoles(senderId, viewDiscordChannel.GetGuildIdByChannel(channelSenderId));

            if (!roles.Contains(captainRoleName))
            {
                return(false);
            }

            var captain = database.Users.GetAll().FirstOrDefault(p => p.IdDiscord == senderId);

            if (captain == default)
            {
                return(false);
            }

            raid.CaptainName = captain.Name.Trim();

            if (!captain.IsCaptain)
            {
                captain.IsCaptain = true;
                database.Users.Update(captain);
                database.Captains.Add(new Captains()
                {
                    DroveRaids = 0, LastDrivenRaid = null, User = captain
                });
                database.Save();
            }

            raid.Id            = GenerateId();
            raid.CaptainUserId = captain.Id;

            string mes = BuildString(raid);

            raid.ChannelAssemblyId = viewDiscordChannel.CreateChannel(
                raid.ChannelAssemblyId, (raid.TimeStart.ToShortTimeString() + " " + raid.CaptainName));

            raid.MessageId      = viewDiscordChannel.SendMessage(mes, raid.ChannelAssemblyId);
            raid.TableMessageId = default;

            raid.timerAssembly       = new TimerCallback(raid.TimeStartAssembly, raid.SetIsAssemblingTrue);
            raid.timerStart          = new TimerCallback(raid.TimeStart, raid.Start);
            raid.timerHourAfterStart = new TimerCallback(raid.TimeStart + new TimeSpan(1, 0, 0), raid.HourAfterStart);

            currentRaids.Add(raid);
            if (viewDiscordChannel.DoesMessageExist(raid.MessageId, raid.ChannelAssemblyId))
            {
                viewDiscordChannel.AddReactionToMes(raid.MessageId, raid.ChannelAssemblyId, Reactions.HEART);
            }

            Raids raids = mapperRaidToRaids.Map <Raid, Raids>(raid);

            files.Add <Raids>(raids, FileTypes.CurrentRaids);

            return(true);
        }
Exemple #5
0
        protected override async Task Send(Raid raid)
        {
            if (raid == null || !Raids.Contains(raid))
            {
                return;
            }

            var link = $"<a href =\"https://raidikalu.herokuapp.com/#raidi-{raid.Id}\">{raid.Name}</a>";

            var message = raid.ComposeMessage(link);

            bool useDelay = false;

            if (raid.Messages.Any())
            {
                try
                {
                    useDelay = raid.Messages.Count > 25;
                    foreach (var raidMessage in raid.Messages)
                    {
                        var editResult = await Bot.EditMessageTextAsync(raidMessage.ChatId, raidMessage.MessageId, message,
                                                                        ParseMode.Html, true);

                        if (useDelay)
                        {
                            Task.Delay(200).Wait();
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Error modifying message: {e.Message}");
                }
            }
            else
            {
                try
                {
                    var sendChannels = Channels.Where(ch => ch.Gyms.Contains(raid.Name)).ToList();
                    useDelay = sendChannels.Count() > 25;
                    foreach (var serviceChannel in sendChannels)
                    {
                        raid.Messages.Add(new TGMessage(await Bot.SendTextMessageAsync(serviceChannel.Id, message, ParseMode.Html, true,
                                                                                       DateTime.Now.Hour < 9 || DateTime.Now.Hour > 22)));
                        if (useDelay)
                        {
                            Task.Delay(200).Wait();
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Error writing message: {e.Message}");
                }
            }
        }
        public static Raids Convert(IEnumerable <Event> events)
        {
            var raids = new Raids();

            raids.Raid = new List <Objects.GameObjects.Raid>();

            ConvertEvents(events, raids);

            return(raids);
        }
        public async Task DeleteRaid()
        {
            bool confirmed = await JSRuntime.InvokeAsync <bool>("confirm", $"Are you sure you want to raid {Raid.Date.ToString("yyyy-MM-dd")}?");

            if (confirmed)
            {
                await RaidService.DeleteRaid(Raid);

                Raids.DeleteRaid(Raid);
            }
        }
 public async Task <List <DateTime> > GetObservedRaidDatesAsync(long teamId, int observedAttendances)
 {
     return(await Raids
            .AsNoTracking()
            .Where(r => r.RaidTeamId == teamId)
            .Select(r => r.StartedAt.Date)
            .Distinct()
            .OrderByDescending(date => date)
            .Take(observedAttendances)
            .ToListAsync());
 }
Exemple #9
0
 /// <summary>
 /// This method removes and existing Raids from the DbContext and saves it
 /// </summary>
 /// <param name="Raids"></param>
 /// <returns></returns>
 public async Task DeleteRaidsAsync(Raids Raids)
 {
     try
     {
         dbContext.Raids.Remove(Raids);
         await dbContext.SaveChangesAsync();
     }
     catch (Exception)
     {
         throw;
     }
 }
Exemple #10
0
 /// <summary>
 /// This method add a new Raids to the DbContext and saves it
 /// </summary>
 /// <param name="Raids"></param>
 /// <returns></returns>
 public async Task <Raids> AddRaidsAsync(Raids Raids)
 {
     try
     {
         dbContext.Raids.Add(Raids);
         await dbContext.SaveChangesAsync();
     }
     catch (Exception)
     {
         throw;
     }
     return(Raids);
 }
Exemple #11
0
        public void SetAssemblingTrue(Raid raid)
        {
            if (raid.IsAssembling == true)
            {
                return;
            }

            raid.IsAssembling = true;

            Raids raids = mapperRaidToRaids.Map <Raid, Raids>(raid);

            files.Update <Raids>(raids, FileTypes.CurrentRaids);

            SendRaidTable(raid);
        }
Exemple #12
0
        public async Task <IActionResult> Post()
        {
            IFormCollection nvc  = Request.Form;
            var             name = nvc["name"];
            DateTime        date = DateTime.Parse(nvc["date"]);
            Raids           raid = new Raids(
                );

            raid.RaidName = name;
            raid.RaidDate = date;
            _context.Raids.Add(raid);
            await _context.SaveChangesAsync();

            return(Ok());
        }
Exemple #13
0
        /// <summary>
        /// Lambda to insert character to character table
        /// </summary>
        /// <param name="pRequest">Incoming API Gateway request object, should be a PUT or POST with a BODY</param>
        /// <param name="pContext">Incoming Lambda Context object, not used currently</param>
        /// <returns></returns>
        public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest pRequest, ILambdaContext pContext)
        {
            if (pRequest.Headers.Keys.Contains("warmup"))
            {
                return(HttpHelper.WarmupResponse());
            }
            var vResponse = HttpHelper.HandleError("[DeleteRaid] Unknown Backend error", 500);

            try
            {
                if (pRequest != null && pRequest.PathParameters != null && pRequest.PathParameters.Count > 0)
                {
                    int vId = int.Parse(pRequest.PathParameters["id"]);
                    using (opendkpContext vDatabase = new opendkpContext())
                    {
                        //Authorized Users only for Deleting Raids
                        if (!CognitoHelper.IsDkpAdmin(pRequest) ||
                            !CognitoHelper.IsAuthorizedAdmin(vDatabase, pRequest))
                        {
                            return(HttpHelper.HandleError("You do not have permission to perform this action", 401));
                        }
                        var vCognitoUser = CognitoHelper.GetCognitoUser(pRequest.Headers["cognitoinfo"]);

                        //We need to retrieve the ClientId for multitenancy purposes
                        var vClientId = pRequest.Headers["clientid"];

                        Raids vResult = RaidHelper.DeleteRaid(vDatabase, vId, vClientId);
                        vDatabase.SaveChanges();
                        vResponse = HttpHelper.HandleResponse(vResult, 200);

                        //Audit
                        AuditHelper.InsertAudit(vDatabase, vClientId, vResult, string.Empty, vCognitoUser.Username, Audit.ACTION_RAID_DELETE);

                        //Update Caches
                        int vStatus = CacheManager.UpdateSummaryCacheAsync(vClientId).GetAwaiter().GetResult();
                        Console.WriteLine("SummaryCacheResponse=" + vStatus);
                        vStatus = CacheManager.UpdateItemCacheAsync(vClientId).GetAwaiter().GetResult();
                        Console.WriteLine("ItemCacheResponse=" + vStatus);
                    }
                }
            }
            catch
            {
                vResponse = HttpHelper.HandleError("[DeleteRaid] Issue with DB or Query", 500);
            }

            return(vResponse);
        }
Exemple #14
0
        public async Task <IActionResult> Delete(int id)
        {
            IFormCollection nvc      = Request.Form;
            var             password = nvc["password"];

            if (password != _password)
            {
                return(Unauthorized());
            }
            var raid = new Raids();

            raid.RaidId = id;
            _context.Remove(raid);
            _context.SaveChanges();
            return(Ok());
        }
Exemple #15
0
        private dynamic GetAuditModel(Raids vRaid)
        {
            dynamic vOldModel = new
            {
                vRaid.Name,
                vRaid.Timestamp,
                vRaid.UpdatedTimestamp,
                vRaid.UpdatedBy,
                vRaid.IdPool,
                Ticks = new List <object>(),
                Items = new List <object>(),
                Pool  = new
                {
                    vRaid.IdPoolNavigation.IdPool,
                    vRaid.IdPoolNavigation.Name,
                    vRaid.IdPoolNavigation.Description,
                    vRaid.IdPoolNavigation.Order
                }
            };

            foreach (Ticks vTick in vRaid.Ticks)
            {
                var vAttendees = new List <string>();
                foreach (var vName in vTick.TicksXCharacters)
                {
                    vAttendees.Add(vName.IdCharacterNavigation.Name);
                }
                vOldModel.Ticks.Add(new
                {
                    vTick.Description,
                    vTick.Value,
                    Attendees = vAttendees
                });
            }

            foreach (var vItem in vRaid.ItemsXCharacters)
            {
                vOldModel.Items.Add(new
                {
                    ItemName      = vItem.Item.Name,
                    DkpValue      = vItem.Dkp,
                    CharacterName = vItem.Character.Name,
                    ItemID        = vItem.ItemId
                });
            }
            return(vOldModel);
        }
Exemple #16
0
 /// <summary>
 /// This method update and existing Raids and saves the changes
 /// </summary>
 /// <param name="Raids"></param>
 /// <returns></returns>
 public async Task <Raids> UpdateRaidsAsync(Raids Raids)
 {
     try
     {
         var RaidsExist = dbContext.Raids.FirstOrDefault(p => p.ID == Raids.ID);
         if (RaidsExist != null)
         {
             dbContext.Update(Raids);
             await dbContext.SaveChangesAsync();
         }
     }
     catch (Exception)
     {
         throw;
     }
     return(Raids);
 }
Exemple #17
0
        /// <summary>
        /// Creates a raid Id, probably isn't needed anymore but early on in development I needed to get the RaidID first. 99.99% sure this isn't needed anymore but no time to refactor
        /// </summary>
        /// <param name="pDBContext">The database context to create the raid id in</param>
        /// <param name="pModel">The model containing the raid information to generate the id</param>
        /// <returns></returns>
        public static int CreateRaidId(opendkpContext pDBContext, string pClientId, dynamic pModel)
        {
            //Insert the raid first to get the RaidId
            Raids vRaid = new Raids()
            {
                Name             = pModel.Name,
                Timestamp        = pModel.Timestamp,
                IdPool           = pModel.Pool.IdPool,
                UpdatedBy        = pModel.UpdatedBy,
                UpdatedTimestamp = pModel.UpdatedTimestamp,
                ClientId         = pClientId
            };

            pDBContext.Add(vRaid);
            pDBContext.SaveChanges();
            //Set Raid Id to the Model we return to client for future updates
            return(vRaid.IdRaid);
        }
        public void UpdateRaid(long charId)
        {
            try
            {
                if (Raids != null)
                {
                    Raid myRaid = Raids.FirstOrDefault(s => s.IsMemberOfRaid(charId));
                    if (myRaid == null)
                    {
                        return;
                    }

                    string                str         = $"rdlst {myRaid.MinLvl} {myRaid.AverageLvl} 0 ";
                    Character             leader      = myRaid.Leader.Character;
                    IList <ClientSession> raidMembers = Raids.FirstOrDefault(s => s.IsMemberOfRaid(charId))?.Characters;

                    str += $"{leader.Level}."
                           + $"{(leader.UseSp || leader.IsVehicled ? leader.Morph : 0)}."
                           + $"{(short)leader.Class}.0.{leader.Name}.0."
                           + $"{myRaid.Leader.SessionId}.{leader.HeroLevel} ";

                    if (raidMembers != null)
                    {
                        foreach (ClientSession session in raidMembers)
                        {
                            str += $"{session.Character.Level}."
                                   + $"{(session.Character.UseSp || session.Character.IsVehicled ? session.Character.Morph : 0)}."
                                   + $"{(short)session.Character.Class}.0.{session.Character.Name}.0."
                                   + $"{session.SessionId}.{session.Character.HeroLevel} ";
                        }
                    }

                    foreach (ClientSession session in myRaid.Characters)
                    {
                        session.SendPacket(str);
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Error(e);
            }
        }
Exemple #19
0
        protected async override Task Send(Raid raid)
        {
            if (raid == null || !Raids.Contains(raid))
            {
                return;
            }

            var link = $"{raid.Name}"; // (https://raidikalu.herokuapp.com/#raidi-{raid.Id})";

            var message = raid.ComposeMessage(link);
            var url     = $"https://raidikalu.herokuapp.com/#raidi-{raid.Id}";

            var embed = new EmbedBuilder
            {
                Title = "Raidikalu",
                Url   = url
            };

            bool useDelay = false;

            if (raid.Messages.Any())
            {
                try
                {
                    useDelay = raid.Messages.Count > 25;
                    foreach (var raidMessage in raid.Messages)
                    {
                        var discordMessage = raidMessage.Content as Discord.Rest.RestUserMessage;
                        if (discordMessage != null)
                        {
                            await discordMessage.ModifyAsync(m => { m.Content = message; m.Embed = embed.Build(); });
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Error modifying message: {e.Message}");
                }
            }
            else
            {
                try
                {
                    var sendChannels = Channels.Where(ch => ch.Gyms.Contains(raid.Name)).ToList();
                    useDelay = sendChannels.Count() > 25;
                    foreach (var serviceChannel in sendChannels)
                    {
                        var channel = client.GetChannel((ulong)serviceChannel.Id);
                        if (channel == null)
                        {
                            var splitName = serviceChannel.Name.Split('#');
                            if (splitName.Length != 2)
                            {
                                continue;
                            }
                            var user = client.GetUser(splitName[0].Substring(1), splitName[1]);
                            if (user != null)
                            {
                                var dmchannel = user.GetOrCreateDMChannelAsync().Result;
                                raid.Messages.Add(new DiscordMessage(await dmchannel.SendMessageAsync(message, false, embed.Build())));
                            }
                        }
                        else if (channel is SocketTextChannel textChannel)
                        {
                            raid.Messages.Add(new DiscordMessage(await textChannel.SendMessageAsync(message, false, embed.Build())));
                        }
                        if (useDelay)
                        {
                            Task.Delay(200).Wait();
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Error writing message: {e.Message}");
                }
            }

            //throw new NotImplementedException();
        }
 public bool IsCharacterMemberOfRaid(long characterId)
 {
     return(Raids != null && Raids.Any(g => g.IsMemberOfRaid(characterId)));
 }
 public Raid GetRaidByCharacterId(long characterId)
 {
     return(Raids?.SingleOrDefault(g => g.IsMemberOfRaid(characterId)));
 }
Exemple #22
0
        private APIGatewayProxyResponse HandleUpdate(APIGatewayProxyRequest pRequest, ILambdaContext pContext, CognitoUser pCognitoUser, opendkpContext pDatabase)
        {
            var vResponse = HttpHelper.HandleError("[InsertOrUpdateAdjustment] Unknown error backend...", 500);

            try
            {
                //Populate Model
                dynamic vModel  = JsonConvert.DeserializeObject(pRequest.Body);
                int     vIdRaid = vModel.IdRaid;
                //We need to retrieve the ClientId for multitenancy purposes
                var vClientId = pRequest.Headers["clientid"];


                Dictionary <string, Characters> vCharacterModels = RaidHelper.GetCharacterModels(pDatabase, vClientId, vModel);

                using (var dbContextTransaction = pDatabase.Database.BeginTransaction())
                {
                    Raids vRaid = pDatabase.Raids.
                                  Include("Ticks.TicksXCharacters").
                                  Include("ItemsXCharacters.Item").
                                  Include("ItemsXCharacters.Character").
                                  Include("IdPoolNavigation").
                                  FirstOrDefault(x => x.ClientId.Equals(vClientId) && x.IdRaid == vIdRaid);

                    dynamic vOldModel = GetAuditModel(vRaid);

                    //Update some attributes of the raid
                    vRaid.Name             = vModel.Name;
                    vRaid.Timestamp        = vModel.Timestamp;
                    vRaid.UpdatedTimestamp = DateTime.Now;
                    vRaid.UpdatedBy        = vModel.UpdatedBy;
                    vRaid.IdPool           = vModel.Pool.IdPool;
                    vRaid.ClientId         = vClientId;

                    //Three Cases to handle: Raid Tick Added, Raid Tick Removed, Raid Tick Updated
                    #region Handle Raid Tick Removed here
                    SimpleTick[] vSimpleTicks = vModel.Ticks.ToObject <SimpleTick[]>();
                    List <Ticks> vRemoveTicks = new List <Ticks>();
                    foreach (Ticks vIndex in vRaid.Ticks)
                    {
                        var vFound = vSimpleTicks.FirstOrDefault(x => x.TickId == vIndex.TickId);
                        if (vFound == null)
                        {
                            vRemoveTicks.Add(vIndex);
                        }
                    }
                    foreach (Ticks vTick in vRemoveTicks)
                    {
                        vRaid.Ticks.Remove(vTick);
                    }
                    #endregion
                    #region Handle Raid Tick Added & Raid Tick Updated Here
                    foreach (var vTick in vModel.Ticks)
                    {
                        int?vTickId = vTick.TickId;
                        //If tickId is null, we have to create an insert a new one
                        if (vTickId == null)
                        {
                            RaidHelper.CreateTick(pDatabase, vClientId, vRaid.IdRaid, vTick, vCharacterModels);
                        }
                        else
                        {
                            Ticks vFoundTick = vRaid.Ticks.FirstOrDefault(x => x.TickId == vTickId);
                            if (vFoundTick != null)
                            {
                                vFoundTick.Description = vTick.Description;
                                vFoundTick.Value       = vTick.Value;
                                vFoundTick.ClientId    = vClientId;

                                //Now that I've found the tick
                                vFoundTick.TicksXCharacters = new List <TicksXCharacters>();
                                foreach (string vAttendee in vTick.Attendees)
                                {
                                    vFoundTick.TicksXCharacters.Add(new TicksXCharacters
                                    {
                                        IdCharacterNavigation = vCharacterModels[vAttendee.ToLower()],
                                        IdTickNavigation      = vFoundTick,
                                        ClientId = vClientId
                                    });
                                }
                            }
                            else
                            {
                                throw new Exception(string.Format("The tick id {0} does not exist, will not save raid", vTickId));
                            }
                        }
                    }
                    #endregion

                    //Handle Items
                    vRaid.ItemsXCharacters = new List <ItemsXCharacters>();
                    RaidHelper.InsertRaidItems(pDatabase, vClientId, vModel, vCharacterModels);

                    //Save
                    pDatabase.SaveChanges();
                    dbContextTransaction.Commit();

                    //Respond
                    vResponse = HttpHelper.HandleResponse(vModel, 200);

                    //Audit
                    AuditHelper.InsertAudit(pDatabase, vClientId, vOldModel, vModel, pCognitoUser.Username, Audit.ACTION_RAID_UPDATE);

                    //Update Caches
                    int vStatus = CacheManager.UpdateSummaryCacheAsync(vClientId).GetAwaiter().GetResult();
                    Console.WriteLine("SummaryCacheResponse=" + vStatus);
                    vStatus = CacheManager.UpdateItemCacheAsync(vClientId).GetAwaiter().GetResult();
                    Console.WriteLine("ItemCacheResponse=" + vStatus);
                }
            }
            catch (Exception vException)
            {
                vResponse = HttpHelper.HandleError(vException.Message, 500);
            }

            return(vResponse);
        }