Beispiel #1
0
        public async Task <ViewModels.Quotes.EditQuotes> Index()
        {
            var returnObject = new ViewModels.Quotes.EditQuotes {
                Quotes = new List <ViewModels.Quotes.EditQuote>()
            };

            foreach (var record in await Records())
            {
                var originalMessage = DbContext.Messages.FirstOrDefault(r => r.Id == record.MessageId);
                var postedBy        = (await AccountRepository.Records()).FirstOrDefault(r => r.Id == record.PostedById);
                var submittedBy     = (await AccountRepository.Records()).FirstOrDefault(r => r.Id == record.SubmittedById);

                returnObject.Quotes.Add(new ViewModels.Quotes.EditQuote {
                    Id            = record.Id,
                    MessageId     = record.MessageId,
                    OriginalBody  = record.OriginalBody,
                    DisplayBody   = record.DisplayBody,
                    PostedBy      = postedBy?.DecoratedName ?? "Missing User",
                    PostedTime    = originalMessage.TimePosted,
                    SubmittedBy   = submittedBy?.DecoratedName ?? "Missing User",
                    SubmittedTime = record.SubmittedTime,
                    Approved      = record.Approved
                });
            }

            return(returnObject);
        }
		/// <summary>
		/// Searches a post for references to other users
		/// </summary>
		public async Task FindMentionedUsers(InputModels.ProcessedMessageInput processedMessageInput) {
			var regexUsers = new Regex(@"@(\S+)");

			var matches = 0;

			foreach (Match regexMatch in regexUsers.Matches(processedMessageInput.DisplayBody)) {
				matches++;

				// DoS prevention
				if (matches > 10) {
					break;
				}

				var matchedTag = regexMatch.Groups[1].Value;

				var users = await AccountRepository.Records();

				var user = users.FirstOrDefault(u => u.DisplayName.ToLower() == matchedTag.ToLower());

				// try to guess what they meant
				if (user is null) {
					user = users.FirstOrDefault(u => u.UserName.ToLower().Contains(matchedTag.ToLower()));
				}

				if (user != null) {
					if (user.Id != UserContext.ApplicationUser.Id) {
						processedMessageInput.MentionedUsers.Add(user.Id);
					}

					// Eventually link to user profiles
					// returnObject.ProcessedBody = Regex.Replace(returnObject.ProcessedBody, @"@" + regexMatch.Groups[1].Value, "<a href='/Profile/Details/" + user.UserId + "' class='user'>" + user.DisplayName + "</span>");
				}
			}
		}
Beispiel #3
0
        public async Task <ItemViewModels.IndexBoard> GetIndexBoard(DataModels.Board boardRecord, bool includeReplies = false)
        {
            var indexBoard = new ItemViewModels.IndexBoard {
                Id           = boardRecord.Id.ToString(),
                Name         = boardRecord.Name,
                Description  = boardRecord.Description,
                DisplayOrder = boardRecord.DisplayOrder,
                Unread       = false
            };

            if (includeReplies)
            {
                var messages = from messageBoard in DbContext.MessageBoards
                               join message in DbContext.Messages on messageBoard.MessageId equals message.Id
                               where messageBoard.BoardId == boardRecord.Id
                               orderby message.LastReplyPosted descending
                               select new {
                    messageBoard.MessageId,
                    LastReplyId  = message.LastReplyId > 0 ? message.LastReplyId : message.Id,
                    TopicPreview = message.ShortPreview
                };

                var users = await AccountRepository.Records();

                // Only checks the most recent 10 topics. If all 10 are forbidden, then LastMessage stays null.
                foreach (var item in messages.Take(10))
                {
                    var messageBoardQuery = from messageBoard in DbContext.MessageBoards
                                            where messageBoard.MessageId == item.MessageId
                                            select messageBoard.BoardId;

                    var messageBoards = messageBoardQuery.ToList();

                    var messageRoleIds = from role in await RoleRepository.BoardRoles()
                                             where messageBoards.Contains(role.BoardId)
                                         select role.RoleId;

                    if (UserContext.IsAdmin || !messageRoleIds.Any() || messageRoleIds.Intersect(UserContext.Roles).Any())
                    {
                        var lastReplyQuery = from message in DbContext.Messages
                                             where message.Id == item.LastReplyId
                                             select new Models.ViewModels.Topics.Items.MessagePreview {
                            Id              = message.Id,
                            ShortPreview    = item.TopicPreview,
                            LastReplyId     = message.LastReplyId,
                            LastReplyById   = message.LastReplyById,
                            LastReplyPosted = message.LastReplyPosted,
                        };

                        indexBoard.LastMessage = lastReplyQuery.FirstOrDefault();
                        indexBoard.LastMessage.LastReplyByName = users.FirstOrDefault(r => r.Id == indexBoard.LastMessage.LastReplyById)?.DecoratedName ?? "User";
                        break;
                    }
                }
            }

            return(indexBoard);
        }
Beispiel #4
0
        public async Task <ViewModels.Quotes.DisplayQuote> Get()
        {
            var approvedRecords = (await Records()).Where(r => r.Approved).ToList();

            if (!approvedRecords.Any())
            {
                return(null);
            }

            var randomQuoteIndex = new Random().Next(0, approvedRecords.Count);
            var randomQuote      = approvedRecords[randomQuoteIndex];

            var postedBy = (await AccountRepository.Records()).FirstOrDefault(r => r.Id == randomQuote.PostedById);

            return(new ViewModels.Quotes.DisplayQuote {
                Id = randomQuote.MessageId,
                DisplayBody = randomQuote.DisplayBody,
                PostedBy = postedBy.DecoratedName
            });
        }
        /// <summary>
        /// Searches a post for references to other users
        /// </summary>
        public async Task FindMentionedUsers(InputModels.ProcessedMessageInput processedMessageInput)
        {
            var regexUsers = new Regex(@"@(\S+)");

            var matches = 0;

            foreach (Match regexMatch in regexUsers.Matches(processedMessageInput.DisplayBody))
            {
                matches++;

                // DoS prevention
                if (matches > 10)
                {
                    break;
                }

                var matchedTag = regexMatch.Groups[1].Value;

                var users = await AccountRepository.Records();

                var user = users.FirstOrDefault(u => u.DisplayName.ToLower() == matchedTag.ToLower());

                // try to guess what they meant
                if (user is null)
                {
                    user = users.FirstOrDefault(u => u.UserName.ToLower().Contains(matchedTag.ToLower()));
                }

                if (user != null)
                {
                    if (user.Id != CurrentUser.Id)
                    {
                        processedMessageInput.MentionedUsers.Add(user.Id);
                    }

                    // UNTESTED
                    //processedMessageInput.DisplayBody = processedMessageInput.DisplayBody.Replace($"{regexMatch.Groups[1].Value}", $"<a href='/Messages/History/{user.Id}'>{user.DisplayName}</span>");
                }
            }
        }
        public async Task <List <ViewModels.Items.IndexItem> > Index(bool showRead = false)
        {
            if (UserContext.ApplicationUser is null)
            {
                return(new List <ViewModels.Items.IndexItem>());
            }

            var hiddenTimeLimit = DateTime.Now.AddDays(-7);
            var recentTimeLimit = DateTime.Now.AddMinutes(-30);

            var notificationQuery = from n in DbContext.Notifications
                                    where n.UserId == UserContext.ApplicationUser.Id
                                    where n.Time > hiddenTimeLimit
                                    where showRead || n.Unread
                                    orderby n.Time descending
                                    select new ViewModels.Items.IndexItem {
                Id           = n.Id,
                Type         = n.Type,
                Recent       = n.Time > recentTimeLimit,
                Time         = n.Time,
                TargetUserId = n.TargetUserId
            };

            var notifications = notificationQuery.ToList();
            var users         = await AccountRepository.Records();

            foreach (var notification in notifications)
            {
                if (!string.IsNullOrEmpty(notification.TargetUserId))
                {
                    notification.TargetUser = users.FirstOrDefault(r => r.Id == notification.TargetUserId)?.DecoratedName ?? "User";
                }

                notification.Text = NotificationText(notification);
            }

            return(notifications);
        }
Beispiel #7
0
        public async Task <List <ViewModels.TopicPreview> > GetPreviews(List <int> topicIds)
        {
            var topicsQuery = from topic in DbContext.Topics
                              where topicIds.Contains(topic.Id)
                              where !topic.Deleted
                              select topic;

            var topics = await topicsQuery.ToListAsync();

            var topicBoardsQuery = from topicBoard in DbContext.TopicBoards
                                   where topicIds.Contains(topicBoard.TopicId)
                                   select new {
                topicBoard.BoardId,
                topicBoard.TopicId
            };

            var topicBoards = await topicBoardsQuery.ToListAsync();

            var users = await AccountRepository.Records();

            var topicPreviews = new List <ViewModels.TopicPreview>();
            var today         = DateTime.Now.Date;

            var boards = await BoardRepository.Records();

            foreach (var topicId in topicIds)
            {
                var topic = topics.First(item => item.Id == topicId);
                var firstMessagePostedBy = users.First(r => r.Id == topic.FirstMessagePostedById);
                var lastMessagePostedBy  = users.FirstOrDefault(r => r.Id == topic.LastMessagePostedById);

                var topicPreview = new ViewModels.TopicPreview {
                    Id                           = topic.Id,
                    Pinned                       = topic.Pinned,
                    ViewCount                    = topic.ViewCount,
                    ReplyCount                   = topic.ReplyCount,
                    Popular                      = topic.ReplyCount > UserContext.ApplicationUser.PopularityLimit,
                    Pages                        = Convert.ToInt32(Math.Ceiling(1.0 * topic.ReplyCount / UserContext.ApplicationUser.MessagesPerPage)),
                    FirstMessageId               = topic.FirstMessageId,
                    FirstMessageTimePosted       = topic.FirstMessageTimePosted,
                    FirstMessagePostedById       = topic.FirstMessagePostedById,
                    FirstMessagePostedByName     = firstMessagePostedBy?.DecoratedName ?? "User",
                    FirstMessagePostedByBirthday = today == new DateTime(today.Year, firstMessagePostedBy.Birthday.Month, firstMessagePostedBy.Birthday.Day).Date,
                    FirstMessageShortPreview     = string.IsNullOrEmpty(topic.FirstMessageShortPreview.Trim()) ? "No subject" : topic.FirstMessageShortPreview,
                    LastMessageId                = topic.Id,
                    LastMessageTimePosted        = topic.LastMessageTimePosted,
                    LastMessagePostedById        = topic.LastMessagePostedById,
                    LastMessagePostedByName      = lastMessagePostedBy?.DecoratedName ?? "User",
                    LastMessagePostedByBirthday  = today == new DateTime(today.Year, firstMessagePostedBy.Birthday.Month, firstMessagePostedBy.Birthday.Day).Date,
                };

                topicPreviews.Add(topicPreview);

                var historyTimeLimit = DateTime.Now.AddDays(-14);

                if (topic.LastMessageTimePosted > historyTimeLimit)
                {
                    topicPreview.Unread = GetUnreadLevel(topic.Id, topic.LastMessageTimePosted);
                }

                var topicPreviewBoardsQuery = from topicBoard in topicBoards
                                              where topicBoard.TopicId == topic.Id
                                              join board in boards on topicBoard.BoardId equals board.Id
                                              orderby board.DisplayOrder
                                              select new Models.ViewModels.Boards.IndexBoard {
                    Id           = board.Id.ToString(),
                    Name         = board.Name,
                    Description  = board.Description,
                    DisplayOrder = board.DisplayOrder,
                };

                topicPreview.Boards = topicPreviewBoardsQuery.ToList();
            }

            return(topicPreviews);
        }
Beispiel #8
0
        public async Task <ViewModels.Boards.IndexBoard> GetIndexBoard(DataModels.Board boardRecord, bool includeReplies = false)
        {
            var indexBoard = new ViewModels.Boards.IndexBoard {
                Id           = boardRecord.Id.ToString(),
                Name         = boardRecord.Name,
                Description  = boardRecord.Description,
                DisplayOrder = boardRecord.DisplayOrder,
                Unread       = false
            };

            if (includeReplies)
            {
                var topicsInThisBoard = from topicBoard in DbContext.TopicBoards
                                        join topic in DbContext.Topics on topicBoard.TopicId equals topic.Id
                                        where topicBoard.BoardId == boardRecord.Id
                                        where !topic.Deleted
                                        orderby topic.LastMessageTimePosted descending
                                        select new {
                    topic.Id,
                    topic.LastMessageId,
                    topic.FirstMessageShortPreview
                };

                var users = await AccountRepository.Records();

                // Only checks the most recent 10 topics. If all 10 are forbidden, then LastMessage stays null.
                foreach (var topic in topicsInThisBoard.Take(10))
                {
                    var topicBoardIdsQuery = from topicBoard in DbContext.TopicBoards
                                             where topicBoard.TopicId == topic.Id
                                             select topicBoard.BoardId;

                    var topicBoardIds = topicBoardIdsQuery.ToList();

                    var relevantRoleIds = from role in await RoleRepository.BoardRoles()
                                              where topicBoardIds.Contains(role.BoardId)
                                          select role.RoleId;

                    if (UserContext.IsAdmin || !relevantRoleIds.Any() || relevantRoleIds.Intersect(UserContext.Roles).Any())
                    {
                        var lastMessage = await DbContext.Messages.FindAsync(topic.LastMessageId);

                        var lastMessageUser = users.FirstOrDefault(r => r.Id == lastMessage.PostedById);

                        indexBoard.RecentTopic = new ViewModels.Topics.TopicPreview {
                            Id = topic.Id,
                            FirstMessageShortPreview    = topic.FirstMessageShortPreview,
                            LastMessageId               = lastMessage.Id,
                            LastMessagePostedById       = lastMessage.PostedById,
                            LastMessageTimePosted       = lastMessage.TimePosted,
                            LastMessagePostedByName     = lastMessageUser?.DecoratedName ?? "User",
                            LastMessagePostedByBirthday = lastMessageUser.IsBirthday,
                        };

                        break;
                    }
                }
            }

            return(indexBoard);
        }
        /// <summary>
        /// Builds a collection of Message objects. The message ids should already have been filtered by permissions.
        /// </summary>
        public async Task <List <ViewModels.Messages.DisplayMessage> > GetMessages(List <int> messageIds)
        {
            var thoughtQuery = from mt in DbContext.MessageThoughts
                               where messageIds.Contains(mt.MessageId)
                               select new ViewModels.Messages.MessageThought {
                MessageId = mt.MessageId.ToString(),
                UserId    = mt.UserId,
                SmileyId  = mt.SmileyId,
            };

            var thoughts = thoughtQuery.ToList();
            var smileys  = await SmileyRepository.Records();

            var users = await AccountRepository.Records();

            foreach (var item in thoughts)
            {
                var smiley = smileys.FirstOrDefault(r => r.Id == item.SmileyId);
                var user   = users.FirstOrDefault(r => r.Id == item.UserId);

                item.Path    = smiley.Path;
                item.Thought = smiley.Thought.Replace("{user}", user.DecoratedName);
            }

            var messageQuery = from message in DbContext.Messages
                               where messageIds.Contains(message.Id)
                               select new ViewModels.Messages.DisplayMessage {
                Id           = message.Id.ToString(),
                TopicId      = message.TopicId,
                ReplyId      = message.ReplyId,
                Body         = message.DisplayBody,
                Cards        = message.Cards,
                OriginalBody = message.OriginalBody,
                PostedById   = message.PostedById,
                TimePosted   = message.TimePosted,
                TimeEdited   = message.TimeEdited,
                RecordTime   = message.TimeEdited
            };

            var messages = await messageQuery.ToListAsync();

            foreach (var message in messages)
            {
                message.ShowControls = true;

                if (message.ReplyId > 0)
                {
                    var reply = DbContext.Messages.FirstOrDefault(item => item.Id == message.ReplyId && !item.Deleted);

                    if (!(reply is null))
                    {
                        if (string.IsNullOrEmpty(reply.ShortPreview))
                        {
                            reply.ShortPreview = "No preview";
                        }

                        message.ReplyBody    = reply.DisplayBody;
                        message.ReplyPreview = reply.ShortPreview;

                        var replyPostedBy = users.FirstOrDefault(item => item.Id == reply.PostedById);
                        message.ReplyPostedBy = replyPostedBy?.DecoratedName ?? "A user";
                    }
                }

                var topic = DbContext.Topics.Find(message.TopicId);

                message.IsFirstMessage = topic.FirstMessageId.ToString() == message.Id;
                message.CanEdit        = CurrentUser.IsAdmin || CurrentUser.Id == message.PostedById;
                message.CanDelete      = CurrentUser.IsAdmin || CurrentUser.Id == message.PostedById;
                message.CanReply       = CurrentUser.IsAuthenticated;
                message.CanThought     = CurrentUser.IsAuthenticated;
                message.CanQuote       = CurrentUser.IsAuthenticated;
                message.Thoughts       = thoughts.Where(item => item.MessageId == message.Id).ToList();

                var postedBy = users.FirstOrDefault(item => item.Id == message.PostedById);

                if (!(postedBy is null))
                {
                    message.PostedByAvatarPath = postedBy.AvatarPath;
                    message.PostedByName       = postedBy.DecoratedName;
                    message.Poseys             = postedBy.Poseys;

                    if (DateTime.Now.Date == new DateTime(DateTime.Now.Year, postedBy.Birthday.Month, postedBy.Birthday.Day).Date)
                    {
                        message.Birthday = true;
                    }
                }
            }

            return(messages);
        }
Beispiel #10
0
        public async Task <List <ItemModels.MessagePreview> > GetPreviews(List <int> messageIds)
        {
            var messageQuery = from message in DbContext.Messages
                               where messageIds.Contains(message.Id)
                               select new {
                message.Id,
                message.ShortPreview,
                message.ViewCount,
                message.ReplyCount,
                message.TimePosted,
                message.PostedById,
                message.LastReplyId,
                message.LastReplyById,
                message.LastReplyPosted,
                message.Pinned
            };

            var messages = await messageQuery.ToListAsync();

            var users = await AccountRepository.Records();

            var messagePreviews = new List <ItemModels.MessagePreview>();
            var today           = DateTime.Now.Date;

            var boards = await BoardRepository.Records();

            foreach (var messageId in messageIds)
            {
                var message  = messages.First(item => item.Id == messageId);
                var postedBy = users.First(r => r.Id == message.PostedById);

                var messagePreview = new ItemModels.MessagePreview {
                    Id               = message.Id,
                    ShortPreview     = string.IsNullOrEmpty(message.ShortPreview.Trim()) ? "No subject" : message.ShortPreview,
                    Views            = message.ViewCount,
                    Replies          = message.ReplyCount,
                    Pages            = Convert.ToInt32(Math.Ceiling(1.0 * message.ReplyCount / UserContext.ApplicationUser.MessagesPerPage)),
                    LastReplyId      = message.Id,
                    Popular          = message.ReplyCount > UserContext.ApplicationUser.PopularityLimit,
                    Pinned           = message.Pinned,
                    TimePosted       = message.TimePosted,
                    PostedById       = message.PostedById,
                    PostedByName     = postedBy.DecoratedName,
                    PostedByBirthday = today == new DateTime(today.Year, postedBy.Birthday.Month, postedBy.Birthday.Day).Date
                };

                messagePreviews.Add(messagePreview);

                var lastMessageTime = message.TimePosted;

                if (message.LastReplyId != 0)
                {
                    var lastReply = (from item in DbContext.Messages
                                     where item.Id == message.LastReplyId
                                     select new {
                        item.ShortPreview
                    }).FirstOrDefault();

                    if (lastReply != null)
                    {
                        var lastReplyBy = users.FirstOrDefault(r => r.Id == message.LastReplyById);

                        messagePreview.LastReplyId      = message.LastReplyId;
                        messagePreview.LastReplyPreview = lastReply.ShortPreview;
                        messagePreview.LastReplyById    = message.LastReplyById;
                        messagePreview.LastReplyPosted  = message.LastReplyPosted;
                        lastMessageTime = message.LastReplyPosted;
                        messagePreview.LastReplyByName = lastReplyBy?.DecoratedName ?? "User";

                        if (!(lastReplyBy is null))
                        {
                            messagePreview.LastReplyByBirthday = today.Date == new DateTime(today.Year, lastReplyBy.Birthday.Month, lastReplyBy.Birthday.Day).Date;
                        }
                    }
                }

                var historyTimeLimit = DateTime.Now.AddDays(-14);

                if (lastMessageTime > historyTimeLimit)
                {
                    messagePreview.Unread = GetUnreadLevel(message.Id, lastMessageTime);
                }

                var boardIdQuery = from messageBoard in DbContext.MessageBoards
                                   where messageBoard.MessageId == message.Id
                                   select messageBoard.BoardId;

                var messageBoards = new List <Models.ViewModels.Boards.Items.IndexBoard>();

                foreach (var boardId in boardIdQuery)
                {
                    var boardRecord = boards.Single(r => r.Id == boardId);

                    messageBoards.Add(new Models.ViewModels.Boards.Items.IndexBoard {
                        Id           = boardRecord.Id.ToString(),
                        Name         = boardRecord.Name,
                        Description  = boardRecord.Description,
                        DisplayOrder = boardRecord.DisplayOrder,
                    });
                }

                messagePreview.Boards = messageBoards.OrderBy(r => r.DisplayOrder).ToList();
            }

            return(messagePreviews);
        }