public void HandlesSavesDeliveredMessageWithProperData(string id, string topic, long timestamp, string text)
        {
            // Arrange
            var repoMock = new Mock <IAuditLogItemRepository>();
            var listener = new AuditEventLoggingListener(repoMock.Object, new NullLoggerFactory());

            AuditLogItem resultItem = null;

            repoMock.Setup(e => e.Save(It.IsAny <AuditLogItem>()))
            .Callback <AuditLogItem>(item => resultItem = item);

            var inputObject = new
            {
                Id        = id,
                TimeStamp = timestamp,
                Data      = text,
                Topic     = topic
            };

            string input = JsonConvert.SerializeObject(inputObject);

            // Act
            listener.Handle(input);

            // Assert
            Assert.AreEqual(input, resultItem.Data);
        }
Ejemplo n.º 2
0
        public void FetchedLogItemsArePublishedProperly(string data, string topic, string type, long timestamp)
        {
            // Arrange
            Mock <IAuditLogItemRepository> repositoryMock     = new Mock <IAuditLogItemRepository>(MockBehavior.Strict);
            Mock <IEventPublisher>         eventPublisherMock = new Mock <IEventPublisher>();

            AuditLogItem auditLogItem = new AuditLogItem
            {
                Id        = Guid.NewGuid().ToString(),
                TimeStamp = timestamp,
                Data      = data,
                Topic     = topic,
                Type      = type
            };

            repositoryMock.Setup(e => e.FindBy(It.IsAny <AuditLogItemCriteria>()))
            .Returns(new List <AuditLogItem> {
                auditLogItem
            });

            ReplayCommandListener commandListener = new ReplayCommandListener(repositoryMock.Object, eventPublisherMock.Object, new LoggerFactory());

            ReplayEventsCommand command = new ReplayEventsCommand(0);

            // Act
            commandListener.Handle(command);

            Thread.Sleep(WaitTime);

            // Assert
            eventPublisherMock.Verify(e => e.PublishAsync(timestamp, $"replay_{topic}", It.IsAny <Guid>(), type, data));
        }
Ejemplo n.º 3
0
        public async Task LogMessageDeletedAsync(Cacheable <IMessage, ulong> message, ISocketMessageChannel channel, SocketGuild guild)
        {
            var deletedMessage = message.HasValue ? message.Value : MessageCache.TryRemove(message.Id);

            var entity = new AuditLogItem()
            {
                Type             = AuditLogType.MessageDeleted,
                CreatedAt        = DateTime.Now,
                GuildIdSnowflake = guild.Id,
            };

            if (deletedMessage == null)
            {
                entity.SetData(MessageDeletedAuditData.Create(channel));
            }
            else
            {
                await ProcessMessageDeletedWithCacheAsync(entity, channel, deletedMessage, guild);
            }

            if (MessageCache.Exists(message.Id))
            {
                MessageCache.TryRemove(message.Id);
            }

            await MessageCache.AppendAroundAsync(channel, message.Id, 100);

            await GrillBotRepository.AddAsync(entity);

            await GrillBotRepository.CommitAsync();
        }
Ejemplo n.º 4
0
        public async Task LogMessageEditedAsync(Cacheable <IMessage, ulong> before, SocketMessage after, ISocketMessageChannel channel, SocketGuild guild)
        {
            var oldMessage = before.HasValue ? before.Value : MessageCache.Get(before.Id);

            if (!IsMessageEdited(oldMessage, after))
            {
                return;
            }

            var userId = await UserSearchService.GetUserIDFromDiscordUserAsync(guild, after.Author);

            var entity = new AuditLogItem()
            {
                Type             = AuditLogType.MessageEdited,
                CreatedAt        = DateTime.Now,
                GuildIdSnowflake = guild.Id,
                UserId           = userId
            };

            entity.SetData(MessageEditedAuditData.Create(channel, oldMessage, after));
            await GrillBotRepository.AddAsync(entity);

            await GrillBotRepository.CommitAsync();

            MessageCache.Update(after);
        }
Ejemplo n.º 5
0
        private async Task ProcessMessageDeletedWithCacheAsync(AuditLogItem entity, ISocketMessageChannel channel, IMessage message, SocketGuild guild)
        {
            entity.SetData(MessageDeletedAuditData.Create(channel, message));

            var auditLog = (await guild.GetAuditLogDataAsync(actionType: ActionType.MessageDeleted)).Find(o =>
            {
                var data = (MessageDeleteAuditLogData)o.Data;
                return(data.Target.Id == message.Author.Id && data.ChannelId == channel.Id);
            });

            entity.UserId = await UserSearchService.GetUserIDFromDiscordUserAsync(guild, auditLog?.User ?? message.Author);

            if (message.Attachments.Count > 0)
            {
                foreach (var attachment in message.Attachments.Where(o => o.Size < 10 * 1024 * 1024)) // Max 10MB
                {
                    var fileContent = await attachment.DownloadFileAsync();

                    if (fileContent == null)
                    {
                        continue;
                    }

                    entity.Files.Add(new Database.Entity.File()
                    {
                        Content  = fileContent,
                        Filename = $"{Path.GetFileNameWithoutExtension(attachment.Filename)}_{attachment.Id}{Path.GetExtension(attachment.Filename)}"
                    });
                }
            }
        }
 public static AuditLogItem Find(Type t)
 {
     lock (s_DomainTypesSyncObj)
     {
         AuditLogItem result;
         if (t != typeof(AuditLog))
         {
             if (!s_DomainTypes.TryGetValue(t, out result))
             {
                 result = new AuditLogItem();
                 PPWAuditLogAttribute auditLogAttribute = t.GetCustomAttributes(true).OfType<PPWAuditLogAttribute>().FirstOrDefault();
                 if (auditLogAttribute != null)
                 {
                     result.AuditLogAction = auditLogAttribute.AuditLogAction;
                     result.Properties = new Dictionary<string, PPWAuditLogActionEnum>();
                     foreach (PropertyInfo pi in t.GetProperties().Where(o => o.CanWrite))
                     {
                         PPWAuditLogPropertyIgnoreAttribute auditLogPropertyIgnore = pi.GetCustomAttributes(true).OfType<PPWAuditLogPropertyIgnoreAttribute>().FirstOrDefault();
                         result.Properties.Add(pi.Name, auditLogPropertyIgnore != null ? auditLogPropertyIgnore.AuditLogAction : PPWAuditLogActionEnum.NONE);
                     }
                 }
                 s_DomainTypes.Add(t, result);
             }
         }
         else
         {
             result = new AuditLogItem();
         }
         return result;
     }
 }
Ejemplo n.º 7
0
        public void SavingAnItemWorks(string data, string topic)
        {
            // Arrange
            using (var context = new AuditLogContext(_options))
            {
                var repository = new AuditLogItemRepository(context);

                var item = new AuditLogItem
                {
                    Data  = data,
                    Topic = topic,
                    Id    = Guid.NewGuid().ToString()
                };

                // Act
                repository.Save(item);
            }

            // Assert
            using var controlContext = new AuditLogContext(_options);

            var resultData = controlContext.AuditLogItems.ToArray();

            Assert.AreEqual(1, resultData.Length);

            var firstItem = resultData.First();

            Assert.AreEqual(data, firstItem.Data);
            Assert.AreEqual(topic, firstItem.Topic);
        }
Ejemplo n.º 8
0
        public void TestConstructionWithoutTime()
        {
            DateTime     now     = DateTime.Now;
            AuditLogItem logItem = new AuditLogItem(documentId, actor, action, info);

            Assert.True(logItem.LogTime >= now);
        }
Ejemplo n.º 9
0
        public virtual void OnPostUpdate(PostUpdateEvent @event)
        {
            AuditLogItem auditLogItem = AuditLogItem.Find(@event.Entity.GetType());

            if ((auditLogItem.AuditLogAction & AuditLogActionEnum.UPDATE) == AuditLogActionEnum.UPDATE)
            {
                string   identityName = IdentityProvider.IdentityName;
                DateTime now          = TimeProvider.Now.ToUniversalTime();
                string   entityName   = @event.Entity.GetType().Name;

                if (@event.OldState == null)
                {
                    throw new ProgrammingError(
                              string.Format(
                                  "No old state available for entity type '{1}'.{0}Make sure you're loading it into Session before modifying and saving it.",
                                  Environment.NewLine,
                                  entityName));
                }

                List <TAuditEntity> auditLogs = new List <TAuditEntity>();
                int[] fieldIndices            = @event.Persister.FindDirty(@event.State, @event.OldState, @event.Entity, @event.Session);
                foreach (int dirtyFieldIndex in fieldIndices)
                {
                    string oldValue = GetStringValueFromStateArray(@event.OldState, dirtyFieldIndex);
                    string newValue = GetStringValueFromStateArray(@event.State, dirtyFieldIndex);

                    if (oldValue != newValue)
                    {
                        string             propertyName = @event.Persister.PropertyNames[dirtyFieldIndex];
                        AuditLogActionEnum auditLogAction;
                        if (auditLogItem.Properties.TryGetValue(propertyName, out auditLogAction))
                        {
                            if ((auditLogAction & AuditLogActionEnum.UPDATE) == AuditLogActionEnum.NONE)
                            {
                                auditLogs.Add(
                                    new TAuditEntity
                                {
                                    EntryType    = "U",
                                    EntityName   = entityName,
                                    EntityId     = @event.Id.ToString(),
                                    PropertyName = propertyName,
                                    OldValue     = oldValue,
                                    NewValue     = newValue,
                                    CreatedBy    = identityName,
                                    CreatedAt    = now,
                                });
                            }
                        }
                    }
                }

                if (auditLogs.Count > 0)
                {
                    ISession session = @event.Session.GetSession(EntityMode.Poco);
                    auditLogs.ForEach(o => session.Save(o));
                }
            }
        }
Ejemplo n.º 10
0
        public void TestConstruction()
        {
            AuditLogItem logItem = new AuditLogItem(time, documentId, actor, action, info);

            Assert.Equal(time, logItem.LogTime);
            Assert.Equal(documentId, logItem.DocumentId);
            Assert.Equal(actor, logItem.Actor);
            Assert.Equal(action, logItem.Action);
            Assert.Equal(info, logItem.AdditionalInformation);
        }
Ejemplo n.º 11
0
        public void TestSerializedNames()
        {
            AuditLogItem logItem = new AuditLogItem(time, documentId, actor, action, info);
            string       json    = JsonConvert.SerializeObject(logItem);
            JObject      obj     = JObject.Parse(json);

            Assert.True(obj.ContainsKey("logTime"));
            Assert.True(obj.ContainsKey("documentId"));
            Assert.True(obj.ContainsKey("actor"));
            Assert.True(obj.ContainsKey("action"));
            Assert.True(obj.ContainsKey("additionalInformation"));
        }
        public Dictionary <Guid, QueryResponse> QueryDomains(IGlymaSession glymaSession)
        {
            using (IDbConnectionAbstraction mapDbConnection = glymaSession.ConnectionFactory.CreateMapDbConnection())
            {
                SqlCommand queryDomainMapCommand = new SqlCommand("SELECT [DomainUid], [NodeUid] FROM [Nodes] WHERE NodeTypeUid = '263754C2-2F31-4D21-B9C4-6509E00A5E94'", mapDbConnection.Connection);
                queryDomainMapCommand.CommandType = CommandType.Text;

                mapDbConnection.Open();

                SqlDataReader queryMapResults = queryDomainMapCommand.ExecuteReader();

                Dictionary <Guid, QueryResponse> domainResponses = new Dictionary <Guid, QueryResponse>();

                if (queryMapResults.HasRows)
                {
                    while (queryMapResults.Read())
                    {
                        Guid domainId = queryMapResults.GetGuid(0);
                        Guid nodeId   = queryMapResults.GetGuid(1);

                        QueryResponse response = QueryMap(glymaSession, domainId, nodeId, 0, false, null, null, 0, false);
                        domainResponses[domainId] = response;
                    }
                }
                mapDbConnection.Close();

                try
                {
                    mapDbConnection.Open();
                    AuditLogItem logItem = new AuditLogItem(mapDbConnection.Connection);
                    logItem.OperationName = "QueryDomains";
                    //logItem.CallingUrl = callingUrl;
                    logItem.DomainUid        = null;
                    logItem.NodeUid          = null;
                    logItem.RootMapUid       = null;
                    logItem.MaxDepth         = null;
                    logItem.ObjectIndex      = null;
                    logItem.EdgeConditions   = null;
                    logItem.FilterConditions = null;
                    logItem.SearchConditions = null;
                    logItem.PageNumber       = null;
                    logItem.PageSize         = null;
                    logItem.Commit();
                    mapDbConnection.Close();
                }
                catch
                {
                    /// Don't do anything. This is here because audit logging is a very low importance task and we don't want it potentially killing the more important tasks at hand.
                }

                return(domainResponses);
            }
        }
        public QueryResponse QueryMapByDomain(IGlymaSession glymaSession, Guid domainId, int maxDepth, EdgeConditions edgeConditions, FilterConditions filterConditions)
        {
            using (IDbConnectionAbstraction mapDbConnection = glymaSession.ConnectionFactory.CreateMapDbConnection())
            {
                SqlCommand queryDomainMapCommand = new SqlCommand("SELECT [NodeUid] FROM [Nodes] WHERE DomainUid = @DomainId AND NodeTypeUid = '263754C2-2F31-4D21-B9C4-6509E00A5E94'", mapDbConnection.Connection);
                queryDomainMapCommand.CommandType = CommandType.Text;
                queryDomainMapCommand.Parameters.Add(new SqlParameter("@DomainId", domainId));

                Guid domainNodeId = Guid.Empty;

                mapDbConnection.Open();

                SqlDataReader queryMapResults = queryDomainMapCommand.ExecuteReader();

                if (queryMapResults.HasRows)
                {
                    queryMapResults.Read();

                    domainNodeId = queryMapResults.GetGuid(0);
                }
                mapDbConnection.Close();

                try
                {
                    mapDbConnection.Open();
                    AuditLogItem logItem = new AuditLogItem(mapDbConnection.Connection);
                    logItem.OperationName = "QueryMapByDomain";
                    //logItem.CallingUrl = callingUrl;
                    logItem.DomainUid        = domainId;
                    logItem.NodeUid          = null;
                    logItem.RootMapUid       = null;
                    logItem.MaxDepth         = maxDepth;
                    logItem.ObjectIndex      = null;
                    logItem.EdgeConditions   = null;
                    logItem.FilterConditions = null;
                    logItem.SearchConditions = null;
                    logItem.PageNumber       = null;
                    logItem.PageSize         = null;
                    logItem.Commit();
                    mapDbConnection.Close();
                }
                catch
                {
                    /// Don't do anything. This is here because audit logging is a very low importance task and we don't want it potentially killing the more important tasks at hand.
                }

                return(QueryMap(glymaSession, domainId, domainNodeId, maxDepth, true, edgeConditions, filterConditions, 0));
            }
        }
Ejemplo n.º 14
0
        public virtual void OnPostInsert(PostInsertEvent @event)
        {
            AuditLogItem auditLogItem = AuditLogItem.Find(@event.Entity.GetType());

            if ((auditLogItem.AuditLogAction & AuditLogActionEnum.CREATE) == AuditLogActionEnum.CREATE)
            {
                string   identityName = IdentityProvider.IdentityName;
                DateTime now          = TimeProvider.Now.ToUniversalTime();
                string   entityName   = @event.Entity.GetType().Name;

                List <TAuditEntity> auditLogs = new List <TAuditEntity>();
                int length = @event.State.Count();
                for (int fieldIndex = 0; fieldIndex < length; fieldIndex++)
                {
                    string newValue = GetStringValueFromStateArray(@event.State, fieldIndex);

                    string             propertyName = @event.Persister.PropertyNames[fieldIndex];
                    AuditLogActionEnum auditLogAction;
                    if (auditLogItem.Properties.TryGetValue(propertyName, out auditLogAction))
                    {
                        if ((auditLogAction & AuditLogActionEnum.CREATE) == AuditLogActionEnum.NONE)
                        {
                            auditLogs.Add(
                                new TAuditEntity
                            {
                                EntryType    = "I",
                                EntityName   = entityName,
                                EntityId     = @event.Id.ToString(),
                                PropertyName = propertyName,
                                OldValue     = null,
                                NewValue     = newValue,
                                CreatedBy    = identityName,
                                CreatedAt    = now,
                            });
                        }
                    }
                }

                if (auditLogs.Count > 0)
                {
                    ISession session = @event.Session.GetSession(EntityMode.Poco);
                    auditLogs.ForEach(o => session.Save(o));
                }
            }
        }
Ejemplo n.º 15
0
        public async Task LogUserLeftAsync(SocketGuildUser user)
        {
            if (user == null)
            {
                return;
            }

            var ban = await user.Guild.FindBanAsync(user);

            RestAuditLogEntry dcAuditLogItem;

            if (ban != null)
            {
                dcAuditLogItem = (await user.Guild.GetAuditLogDataAsync(actionType: ActionType.Ban))?
                                 .FirstOrDefault(o => (o.Data as BanAuditLogData)?.Target.Id == user.Id);
            }
            else
            {
                dcAuditLogItem = (await user.Guild.GetAuditLogDataAsync(actionType: ActionType.Kick))?
                                 .FirstOrDefault(o => (o.Data as KickAuditLogData)?.Target.Id == user.Id);
            }

            long?executor = null;

            if (dcAuditLogItem != null)
            {
                executor = await UserSearchService.GetUserIDFromDiscordUserAsync(user.Guild, dcAuditLogItem.User);
            }

            var entity = new AuditLogItem()
            {
                Type             = AuditLogType.UserLeft,
                CreatedAt        = DateTime.Now,
                GuildIdSnowflake = user.Guild.Id,
                UserId           = executor
            };

            entity.SetData(UserLeftAuditData.Create(user.Guild, user, ban != null, ban?.Reason));
            await GrillBotRepository.AddAsync(entity);

            await GrillBotRepository.CommitAsync();
        }
        public void Handle(string evt)
        {
            _logger.LogDebug($"Deserializing event with data {evt}");

            try
            {
                AuditLogItem item = JsonConvert.DeserializeObject <AuditLogItem>(evt);
                item.TimeStamp = new DateTime(item.TimeStamp).ToFileTimeUtc();
                item.Data      = evt;

                _repository.Save(item);
            }
            catch (JsonReaderException exception)
            {
                _logger.LogCritical($"Json Exception occured while handling incoming event! {exception.Message}. " +
                                    $"This means that this item IS NOT saved! Item {evt}");

                throw;
            }
        }
Ejemplo n.º 17
0
        public virtual void OnPostDelete(PostDeleteEvent @event)
        {
            AuditLogItem auditLogItem = AuditLogItem.Find(@event.Entity.GetType());

            if ((auditLogItem.AuditLogAction & AuditLogActionEnum.DELETE) == AuditLogActionEnum.DELETE)
            {
                string   identityName = IdentityProvider.IdentityName;
                DateTime now          = TimeProvider.Now.ToUniversalTime();
                string   entityName   = @event.Entity.GetType().Name;

                ISession session = @event.Session.GetSession(EntityMode.Poco);
                session.Save(
                    new TAuditEntity
                {
                    EntryType  = "D",
                    EntityName = entityName,
                    EntityId   = @event.Id.ToString(),
                    CreatedBy  = identityName,
                    CreatedAt  = now,
                });
            }
        }
Ejemplo n.º 18
0
        public async Task LogCommandAsync(Optional <CommandInfo> command, ICommandContext context)
        {
            if (context.Guild == null || !command.IsSpecified)
            {
                return;
            }

            var userId = await UserSearchService.GetUserIDFromDiscordUserAsync(context.Guild, context.User);

            var entity = new AuditLogItem()
            {
                Type             = AuditLogType.Command,
                CreatedAt        = DateTime.Now,
                GuildIdSnowflake = context.Guild.Id,
                UserId           = userId
            };

            entity.SetData(CommandAuditData.CreateDbItem(context, command.Value));
            await GrillBotRepository.AddAsync(entity);

            await GrillBotRepository.CommitAsync();
        }
Ejemplo n.º 19
0
            public static AuditLogItem Find(Type t)
            {
                AuditLogItem result = s_DomainTypes
                                      .GetOrAdd(
                    t,
                    @type =>
                {
                    result = new AuditLogItem();
                    if (@type != typeof(TAuditEntity))
                    {
                        AuditLogAttribute auditLogAttribute =
                            @type
                            .GetCustomAttributes(true)
                            .OfType <AuditLogAttribute>()
                            .FirstOrDefault();
                        if (auditLogAttribute != null)
                        {
                            result.AuditLogAction = auditLogAttribute.AuditLogAction;
                            result.Properties     = new Dictionary <string, AuditLogActionEnum>();
                            foreach (PropertyInfo propertyInfo in t.GetProperties().Where(o => o.CanWrite))
                            {
                                AuditLogPropertyIgnoreAttribute auditLogPropertyIgnore =
                                    propertyInfo
                                    .GetCustomAttributes(true)
                                    .OfType <AuditLogPropertyIgnoreAttribute>()
                                    .FirstOrDefault();
                                result
                                .Properties
                                .Add(propertyInfo.Name, auditLogPropertyIgnore != null ? auditLogPropertyIgnore.AuditLogAction : AuditLogActionEnum.NONE);
                            }
                        }
                    }

                    return(result);
                });

                return(result);
            }
Ejemplo n.º 20
0
        /// <summary>
        /// Converts an IDataReader to a list of AuditLogItems.
        /// </summary>
        /// <typeparam name="U"></typeparam>
        /// <param name="reader"></param>
        /// <returns></returns>
        protected List <AuditLogItem> ConvertDataReaderToList(IDataReader reader)
        {
            List <AuditLogItem> list = new List <AuditLogItem>();

            while (reader.Read())
            {
                AuditLogItem item = new AuditLogItem();
                item.ID          = long.Parse(reader["audit_log_id"].ToString());
                item.ChangedTime = DateTime.Parse(reader["changed_time"].ToString());
                item.ChangedBy   = reader["changed_by"].ToString();
                item.ContractID  = long.Parse(reader["contract_id"].ToString());
                item.Contract    = reader["contract_descr"].ToString();
                item.Source1     = reader["source1"].ToString();
                item.Source2     = reader["source2"].ToString();
                item.PkValue     = reader["pk_value"].ToString();
                item.AuditAction = reader["audit_action"].ToString();
                item.Description = reader["descr"].ToString();
                item.OldValue    = reader["old_value"].ToString();
                item.NewValue    = reader["new_value"].ToString();
                list.Add(item);
            }
            reader.Dispose();
            return(list);
        }
Ejemplo n.º 21
0
        public async Task LogUserJoinAsync(SocketGuildUser user)
        {
            if (user == null || !user.IsUser())
            {
                return;
            }

            var userEntity = await GrillBotRepository.UsersRepository.GetOrCreateUserAsync(user.Guild.Id, user.Id, UsersIncludes.None);

            await GrillBotRepository.CommitAsync();

            var entity = new AuditLogItem()
            {
                Type             = AuditLogType.UserJoined,
                CreatedAt        = DateTime.Now,
                GuildIdSnowflake = user.Guild.Id,
                UserId           = userEntity.ID
            };

            entity.SetData(UserJoinedAuditData.Create(user.Guild));
            await GrillBotRepository.AddAsync(entity);

            await GrillBotRepository.CommitAsync();
        }
 /// <summary>
 /// Save a log item to the database
 /// </summary>
 public void Save(AuditLogItem item)
 {
     _auditLogContext.AuditLogItems.Add(item);
     _auditLogContext.SaveChanges();
 }
Ejemplo n.º 23
0
        public async Task TriggerBackgroundTaskAsync(object data)
        {
            if (data is not DownloadAuditLogBackgroundTask task)
            {
                return;
            }

            var guild = Client.GetGuild(task.GuildId);

            if (guild == null)
            {
                return;
            }

            if (!AuditServiceHelper.IsTypeDefined(task.ActionType))
            {
                return;
            }

            var logs = await guild.GetAuditLogDataAsync(100, task.ActionType);

            if (logs.Count == 0)
            {
                return;
            }

            var auditLogType = AuditServiceHelper.AuditLogTypeMap[task.ActionType];
            var logIds       = (await GrillBotRepository.AuditLogs.GetLastAuditLogIdsQuery(guild.Id, auditLogType).ToListAsync())
                               .ConvertAll(o => Convert.ToUInt64(o));

            foreach (var log in logs)
            {
                if (logIds.Contains(log.Id))
                {
                    continue;
                }

                var userId = await GetOrCreateUserId(guild, log.User);

                var item = new AuditLogItem()
                {
                    CreatedAt             = log.CreatedAt.LocalDateTime,
                    DcAuditLogIdSnowflake = log.Id,
                    UserId           = userId,
                    GuildIdSnowflake = guild.Id,
                    Type             = auditLogType
                };

                var logMappingMethod = AuditServiceHelper.AuditLogDataMap[task.ActionType];

                if (logMappingMethod != null)
                {
                    var mappedItem = logMappingMethod(log.Data);

                    if (mappedItem != null)
                    {
                        item.SetData(mappedItem);
                    }
                }

                await GrillBotRepository.AddAsync(item);
            }

            await GrillBotRepository.CommitAsync();
        }
Ejemplo n.º 24
0
        public static async Task <AuditItem> CreateAsync(SocketGuild guild, AuditLogItem dbItem, DiscordUser user, IMessageCache cache)
        {
            var item = new AuditItem()
            {
                CreatedAt       = dbItem.CreatedAt,
                Id              = dbItem.Id,
                Type            = dbItem.Type,
                User            = user,
                AttachmentNames = dbItem.Files.Select(o => o.Filename).ToList()
            };

            switch (dbItem.Type)
            {
            case AuditLogType.BotAdded:
                item.BotAdded = JsonConvert.DeserializeObject <AuditBotAdded>(dbItem.JsonData);
                break;

            case AuditLogType.ChannelCreated:
            case AuditLogType.ChannelDeleted:
                item.ChannelInfo = JsonConvert.DeserializeObject <AuditChannelInfo>(dbItem.JsonData);
                break;

            case AuditLogType.ChannelUpdated:
                item.ChannelUpdated = JsonConvert.DeserializeObject <AuditChannelUpdated>(dbItem.JsonData);
                break;

            case AuditLogType.Command:
                item.CommandAuditData = JsonConvert.DeserializeObject <CommandAuditData>(dbItem.JsonData).GetFilledModel(guild);
                break;

            case AuditLogType.EmojiCreated:
            case AuditLogType.EmojiDeleted:
                item.EmoteInfo = JsonConvert.DeserializeObject <AuditEmoteInfo>(dbItem.JsonData);
                break;

            case AuditLogType.EmojiUpdated:
                item.EmoteUpdated = JsonConvert.DeserializeObject <AuditEmoteUpdated>(dbItem.JsonData);
                break;

            case AuditLogType.GuildUpdated:
                item.GuildUpdated = JsonConvert.DeserializeObject <GuildUpdated>(dbItem.JsonData).GetFilledModel(guild);
                break;

            case AuditLogType.MemberRoleUpdated:
            case AuditLogType.MemberUpdated:
                item.MemberUpdated = await JsonConvert.DeserializeObject <AuditMemberUpdated>(dbItem.JsonData).GetFilledModelAsync(guild);

                break;

            case AuditLogType.MessageDeleted:
                item.MessageDeletedAuditData = JsonConvert.DeserializeObject <MessageDeletedAuditData>(dbItem.JsonData).GetFilledModel(guild);
                break;

            case AuditLogType.MessageEdited:
                item.MessageEditedAuditData = JsonConvert.DeserializeObject <MessageEditedAuditData>(dbItem.JsonData).GetFilledModel(guild);
                break;

            case AuditLogType.MessagePinned:
            case AuditLogType.MessageUnpinned:
                item.PinInfo = await JsonConvert.DeserializeObject <AuditMessagePinInfo>(dbItem.JsonData).GetFilledModelAsync(guild, cache);

                break;

            case AuditLogType.OverwriteCreated:
            case AuditLogType.OverwriteDeleted:
                item.OverwriteInfo = JsonConvert.DeserializeObject <AuditOverwriteInfo>(dbItem.JsonData).GetFilledModel(guild);
                break;

            case AuditLogType.OverwriteUpdated:
                item.OverwriteUpdated = JsonConvert.DeserializeObject <AuditOverwriteUpdated>(dbItem.JsonData).GetFilledModel(guild);
                break;

            case AuditLogType.Prune:
                item.PruneMembers = JsonConvert.DeserializeObject <AuditPruneMembers>(dbItem.JsonData);
                break;

            case AuditLogType.RoleCreated:
            case AuditLogType.RoleDeleted:
                item.Role = JsonConvert.DeserializeObject <Role>(dbItem.JsonData);
                break;

            case AuditLogType.RoleUpdated:
                item.RoleUpdated = JsonConvert.DeserializeObject <RoleUpdated>(dbItem.JsonData);
                break;

            case AuditLogType.Unban:
                item.Unban = JsonConvert.DeserializeObject <AuditUnban>(dbItem.JsonData);
                break;

            case AuditLogType.UserJoined:
                item.UserJoinedAuditData = JsonConvert.DeserializeObject <UserJoinedAuditData>(dbItem.JsonData).GetFilledModel(user);
                break;

            case AuditLogType.UserLeft:
                item.UserLeftAuditData = JsonConvert.DeserializeObject <UserLeftAuditData>(dbItem.JsonData);
                break;

            case AuditLogType.WebhookCreated:
            case AuditLogType.WebhookDeleted:
                item.Webhook = JsonConvert.DeserializeObject <Webhook>(dbItem.JsonData);
                break;

            case AuditLogType.WebhookUpdated:
                item.WebhookUpdated = JsonConvert.DeserializeObject <WebhookUpdated>(dbItem.JsonData).GetFilledModel(guild);
                break;
            }

            return(item);
        }
        public QueryResponse QueryMap(IGlymaSession glymaSession, Guid domainId, Guid nodeId, int maxDepth, bool isFullDomainSearch, EdgeConditions edgeConditions, FilterConditions filterConditions, int objectIndex, bool isCompressed)
        {
            if (!isCompressed)
            {
                TransactionalMappingToolServiceCommonBase.SoftObjectLimit = 3000;
                TransactionalMappingToolServiceCommonBase.HardObjectLimit = 4000;
            }
            else
            {
                TransactionalMappingToolServiceCommonBase.SoftObjectLimit = 5500;
                TransactionalMappingToolServiceCommonBase.HardObjectLimit = 6500;
            }

            using (IDbConnectionAbstraction mapDbConnection = glymaSession.ConnectionFactory.CreateMapDbConnection())
            {
                SqlCommand queryMapCommand = new SqlCommand("QueryMap", mapDbConnection.Connection);
                queryMapCommand.CommandType = CommandType.StoredProcedure;
                queryMapCommand.Parameters.Add(new SqlParameter("@DomainId", domainId));
                queryMapCommand.Parameters.Add(new SqlParameter("@NodeId", nodeId));
                queryMapCommand.Parameters.Add(new SqlParameter("@Depth", maxDepth));
                queryMapCommand.Parameters.Add(new SqlParameter("@FullDomain", isFullDomainSearch));

                mapDbConnection.Open();

                SqlDataReader queryMapResults = queryMapCommand.ExecuteReader();

                QueryResponse queryResponse = new QueryResponse();

                List <Node>[] orderedNodes = new List <Node> [maxDepth + 1];

                do
                {
                    while (queryMapResults.Read())
                    {
                        if (queryMapResults.GetSchemaTable().Select("ColumnName = 'Level'").Length > 0)
                        {
                            Node node = new Node();
                            node.LoadElement(queryMapResults);

                            List <Node> nodes;

                            if (orderedNodes[node.Depth] != null)
                            {
                                nodes = orderedNodes[node.Depth];
                            }
                            else
                            {
                                nodes = new List <Node>();
                                orderedNodes[node.Depth] = nodes;
                            }

                            nodes.Add(node);

                            queryResponse.AddNode(node);
                        }
                        else if (queryMapResults.GetSchemaTable().Select("ColumnName = 'MetadataId'").Length > 0)
                        {
                            Metadata metadata = new Metadata();
                            metadata.LoadElement(queryMapResults);

                            queryResponse.AddMetadata(metadata);
                        }
                        else if (queryMapResults.GetSchemaTable().Select("ColumnName = 'DescriptorUid'").Length > 0)
                        {
                            Descriptor descriptor = new Descriptor();
                            descriptor.LoadElement(queryMapResults);

                            queryResponse.AddDescriptor(descriptor);
                        }
                        else if (queryMapResults.GetSchemaTable().Select("ColumnName = 'RelationshipUid'").Length > 0)
                        {
                            Relationship relationship = new Relationship();
                            relationship.LoadElement(queryMapResults);

                            queryResponse.AddRelationship(relationship);
                        }
                    }
                }while (queryMapResults.NextResult());

                mapDbConnection.Close();

                try
                {
                    mapDbConnection.Open();
                    AuditLogItem logItem = new AuditLogItem(mapDbConnection.Connection);
                    logItem.OperationName = "QueryMap";
                    //logItem.CallingUrl = callingUrl;
                    logItem.DomainUid        = domainId;
                    logItem.NodeUid          = nodeId;
                    logItem.RootMapUid       = null;
                    logItem.MaxDepth         = maxDepth;
                    logItem.ObjectIndex      = objectIndex;
                    logItem.EdgeConditions   = null;
                    logItem.FilterConditions = null;
                    logItem.SearchConditions = null;
                    logItem.PageNumber       = null;
                    logItem.PageSize         = null;
                    logItem.Commit();
                    mapDbConnection.Close();
                }
                catch
                {
                    /// Don't do anything. This is here because audit logging is a very low importance task and we don't want it potentially killing the more important tasks at hand.
                }

                if (!queryResponse.Nodes.ContainsKey(nodeId))
                {
                    queryResponse.ErrorId      = 1;
                    queryResponse.ErrorMessage = "Provided node ID context doesn't exist";

                    return(queryResponse);
                }

                queryResponse.AttachElements();
                queryResponse.NodeContext = queryResponse.Nodes[nodeId];

                if (maxDepth > 0 && edgeConditions != null && edgeConditions.EdgeCondition != null)
                {
                    List <Guid> nodesToRemove         = new List <Guid>();
                    List <Guid> relationshipsToRemove = new List <Guid>();

                    List <Guid> boundaryNodes         = new List <Guid>();
                    List <Guid> boundaryRelationships = new List <Guid>();

                    for (int i = 1; i <= maxDepth; i++)
                    {
                        List <Node> nodes = orderedNodes[i];

                        foreach (Node node in nodes)
                        {
                            bool         isBoundaryNode         = false;
                            bool         isBoundaryRelationship = false;
                            bool         isNodeIncluded         = true;
                            bool         isRelationshipIncluded = true;
                            Relationship connectingRelationship = queryResponse.Relationships[node.ConnectingRelationship];

                            if (boundaryNodes.Contains(node.Origin))
                            {
                                isBoundaryNode         = true;
                                isBoundaryRelationship = true;
                                isNodeIncluded         = false;
                                isRelationshipIncluded = false;
                            }
                            else
                            {
                                EdgeResult relationshipEvalResult = edgeConditions.EdgeCondition.EvaluateCondition(connectingRelationship);

                                if (relationshipEvalResult.IsEdge.HasValue && relationshipEvalResult.IsEdge.Value)
                                {
                                    // THis means the relationship was evaluated to be a boundary edge.
                                    isBoundaryRelationship = true;
                                    isRelationshipIncluded = relationshipEvalResult.IsIncluded;
                                }

                                EdgeResult nodeEvalResult = edgeConditions.EdgeCondition.EvaluateCondition(node);

                                if (nodeEvalResult.IsEdge.HasValue && nodeEvalResult.IsEdge.Value)
                                {
                                    // This means the node was evaluated to be a boundary edge.
                                    isBoundaryNode = true;
                                    isNodeIncluded = nodeEvalResult.IsIncluded;
                                    // The inclusion value for the node trumps the relationship value as the relationship is dependent on the node existing anyway.
                                    isRelationshipIncluded = isNodeIncluded;
                                }
                                else if (isBoundaryRelationship)
                                {
                                    // If the relationship was discovered to be a boundary then this node will be a boundary edge too.
                                    isBoundaryNode = true;
                                    isNodeIncluded = isRelationshipIncluded;
                                }
                            }

                            if (isBoundaryNode)
                            {
                                boundaryNodes.Add(node.NodeUid);
                            }

                            if (isBoundaryRelationship)
                            {
                                boundaryRelationships.Add(connectingRelationship.RelationshipUid);
                            }

                            if (!isNodeIncluded)
                            {
                                nodesToRemove.Add(node.NodeUid);
                            }

                            if (!isRelationshipIncluded)
                            {
                                relationshipsToRemove.Add(connectingRelationship.RelationshipUid);
                            }
                        }
                    }

                    foreach (Guid nodeIdToRemove in nodesToRemove)
                    {
                        queryResponse.Nodes.Remove(nodeIdToRemove);
                    }

                    foreach (Guid relationshipIdToRemove in relationshipsToRemove)
                    {
                        queryResponse.Relationships.Remove(relationshipIdToRemove);
                    }
                }

                int totalObjects = queryResponse.CountObjects();

                queryResponse.Domain           = new Domain();
                queryResponse.Domain.DomainUid = domainId;

                if (totalObjects > TransactionalMappingToolServiceCommonBase.HardObjectLimit || objectIndex > 0)
                {
                    return(queryResponse.GetPage(objectIndex));
                }

                return(queryResponse);
            }
        }
        /// <summary>
        /// TODO: This method needs to be moved from here as it makes calls to schema specific methods.
        /// </summary>
        /// <param name="callingUrl"></param>
        /// <param name="domainId"></param>
        /// <param name="conditions"></param>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public SearchMapResult SearchMap(IGlymaSession glymaSession, Guid domainId, Guid rootMapUid, SearchConditions conditions, int pageNumber = 1, int pageSize = 5)
        {
            SearchMapResult result = new SearchMapResult();

            using (IDbConnectionAbstraction mapDbConnection = glymaSession.ConnectionFactory.CreateMapDbConnection())
            {
                mapDbConnection.Open();

                SqlCommand findMetadata = conditions.BuildSearchQuery(mapDbConnection.Connection, rootMapUid, pageNumber, pageSize);

                SqlDataReader matchingMetadata = findMetadata.ExecuteReader();

                matchingMetadata.Read();
                int totalMetadataCount = (int)matchingMetadata[0];
                matchingMetadata.NextResult();

                int currentMetadataPagePosition = pageNumber * pageSize;

                DataTable nodesList;

                result.Count = totalMetadataCount;

                if (currentMetadataPagePosition > totalMetadataCount && pageNumber > 1)
                {
                    int itemsToRemove = currentMetadataPagePosition - totalMetadataCount;

                    if (itemsToRemove >= pageSize)
                    {
                        result = new SearchMapResult();

                        return(result);
                    }
                    else
                    {
                        nodesList = new DataTable("NodesList");
                        nodesList.Load(matchingMetadata);

                        for (int i = 0; i < itemsToRemove; i++)
                        {
                            nodesList.Rows.RemoveAt(0);
                        }

                        nodesList.Columns.Remove("Modified");
                    }
                }
                else
                {
                    nodesList = new DataTable("NodesList");
                    nodesList.Load(matchingMetadata);
                    nodesList.Columns.Remove("Modified");
                }

                QueryNodes queryNodes = new QueryNodes(mapDbConnection);
                Dictionary <Guid, SearchedNode> nodes = queryNodes.GetNodes(nodesList);

                result.SearchedNodes = nodes;

                mapDbConnection.Close();

                try
                {
                    mapDbConnection.Open();
                    AuditLogItem logItem = new AuditLogItem(mapDbConnection.Connection);
                    logItem.OperationName = "SearchMap";
                    //logItem.CallingUrl = callingUrl;
                    logItem.DomainUid        = domainId;
                    logItem.NodeUid          = null;
                    logItem.RootMapUid       = rootMapUid;
                    logItem.MaxDepth         = null;
                    logItem.ObjectIndex      = null;
                    logItem.EdgeConditions   = null;
                    logItem.FilterConditions = null;
                    logItem.SearchConditions = null;
                    logItem.PageNumber       = pageNumber;
                    logItem.PageSize         = pageSize;
                    logItem.Commit();
                    mapDbConnection.Close();
                }
                catch
                {
                    /// Don't do anything. This is here because audit logging is a very low importance task and we don't want it potentially killing the more important tasks at hand.
                }

                return(result);
            }
        }