Example #1
0
        public async Task ProcessIncomingMessage(ChatMessage message)
        {
            if (message == null)
            {
                throw new UnprocessableEntityException("Cannot process null message");
            }

            // check if message from same source with same SourceMessageId already in database
            if (await chatMessageService.MessageExists(message))
            {
                logger.LogInformation($"{message.Source} message id {message.SourceMessageId} already in database, skipping");
                return;
            }

            // - check for author
            if (message.Author == null)
            {
                if (message.AuthorId == 0)
                {
                    throw new UnprocessableEntityException("Author not defined");
                }

                message.Author = await authorService.GetAuthors().SingleOrDefaultAsync(x => x.Id == message.AuthorId);
            }

            if (message.Author == null)
            {
                logger.LogWarning($"Message without author... skipping");
                return;
            }

            if (!authorService.IsValid(message.Author))
            {
                logger.LogInformation($"invalid author, skipping: Source='{message.Author.Source}', SourceAuthorId='{message.Author.SourceAuthorId}', Name='{message.Author.Name}'");
                return;
            }

            var author = await authorService.EnsureAuthor(message.AuthorId, message.Author);

            // Housekeeping: syncs author's name changes
            if (author.Name != message.Author.Name)
            {
                author.Name = message.Author.Name;
            }

            // - check infractions
            if (chatRulesService.HasInfractions(message))
            {
                // apply infraction penalty
                author.Score -= 1;
            }
            else
            {
                author.Score += 1;
            }

            await authorService.Update(author);

            // save message
            if (message.AuthorId == 0)
            {
                message.AuthorId = author.Id;
            }
            await chatMessageService.CreateMessage(message);

            await SendToChannel("All", message);

            if (await botService.IsBotCommand(message))
            {
                await ProcessIncomingBotMessage(message);

                return;
            }

            // send message to view channels
            foreach (var channel in await chatRulesService.AllowedChannels(message))
            {
                await SendToChannel(channel, message);
            }

            //if (message.AuthorId > 0)
            //{
            //    message.Author = null;
            //}
        }