Exemplo n.º 1
0
        public static async Task SendUserMentionNotification(string user, Comment comment)
        {
            if (comment != null)
            {
                if (!User.UserExists(user))
                {
                    return;
                }
                try
                {
                    string recipient = User.OriginalUsername(user);

                    var commentReplyNotification = new Commentreplynotification();
                    using (var _db = new voatEntities())
                    {
                        var submission = DataCache.Submission.Retrieve(comment.MessageId);
                        var subverse = DataCache.Subverse.Retrieve(submission.Subverse);

                        commentReplyNotification.CommentId = comment.Id;
                        commentReplyNotification.SubmissionId = comment.MessageId.Value;
                        commentReplyNotification.Recipient = recipient;
                        if (submission.Anonymized || subverse.anonymized_mode)
                        {
                            commentReplyNotification.Sender = (new Random()).Next(10000, 20000).ToString(CultureInfo.InvariantCulture);
                        }
                        else
                        {
                            commentReplyNotification.Sender = comment.Name;
                        }
                        commentReplyNotification.Body = comment.CommentContent;
                        commentReplyNotification.Subverse = subverse.name;
                        commentReplyNotification.Status = true;
                        commentReplyNotification.Timestamp = DateTime.Now;

                        commentReplyNotification.Subject = String.Format("@{0} mentioned you in a comment", comment.Name, submission.Title);

                        _db.Commentreplynotifications.Add(commentReplyNotification);
                       
                        await _db.SaveChangesAsync();
                    }

                    // get count of unread notifications
                    int unreadNotifications = User.UnreadTotalNotificationsCount(commentReplyNotification.Recipient);

                    // send SignalR realtime notification to recipient
                    var hubContext = GlobalHost.ConnectionManager.GetHubContext<MessagingHub>();
                    hubContext.Clients.User(commentReplyNotification.Recipient).setNotificationsPending(unreadNotifications);
                }
                catch (Exception ex) {
                    throw ex;
                }
            }
        }
Exemplo n.º 2
0
        // a method to mark single or all private messages as read for a given user
        public static async Task<bool> MarkPrivateMessagesAsRead(bool? markAll, string userName, int? itemId)
        {
            using (var db = new voatEntities())
            {
                try
                {
                    // mark all items as read
                    if (markAll != null && (bool) markAll)
                    {
                        IQueryable<Privatemessage> unreadPrivateMessages = db.Privatemessages
                                                                            .Where(s => s.Recipient.Equals(userName, StringComparison.OrdinalIgnoreCase) && s.Status)
                                                                            .OrderByDescending(s => s.Timestamp)
                                                                            .ThenBy(s => s.Sender);

                        if (!unreadPrivateMessages.Any()) return false;

                        foreach (var singleMessage in unreadPrivateMessages.ToList())
                        {
                            singleMessage.Status = false;
                        }
                        await db.SaveChangesAsync();
                        return true;
                    }

                    // mark single item as read
                    if (itemId != null)
                    {
                        var privateMessageToMarkAsread = db.Privatemessages.FirstOrDefault(s => s.Recipient.Equals(userName, StringComparison.OrdinalIgnoreCase) && s.Status && s.Id == itemId);
                        if (privateMessageToMarkAsread == null) return false;

                        var item = db.Privatemessages.Find(itemId);
                        item.Status = false;
                        await db.SaveChangesAsync();
                        return true;
                    }
                    return false;
                }
                catch (Exception)
                {
                    return false;
                }
            }

        }
Exemplo n.º 3
0
        public async Task<ActionResult> ToggleNightMode()
        {
            string newTheme = "light";
            // save changes
            using (var db = new voatEntities())
            {
                var userPreferences = db.Userpreferences.Find(User.Identity.Name);

                if (userPreferences != null)
                {
                    // modify existing preferences
                    userPreferences.Night_mode = !userPreferences.Night_mode;
                    await db.SaveChangesAsync();
                    newTheme = userPreferences.Night_mode ? "dark" : "light";
                    // apply theme change
                    //Session["UserTheme"] = Utils.User.UserStylePreference(User.Identity.Name);
                }
                else
                {
                    // create a new record for this user in userpreferences table
                    var tmpModel = new Userpreference
                    {
                        Disable_custom_css = false,
                        //Since if user has no pref, they must have been on the light theme
                        Night_mode = true,
                        Clicking_mode = false,
                        Enable_adult_content = false,
                        Public_subscriptions = false,
                        Topmenu_from_subscriptions = false,
                        Username = User.Identity.Name
                    };
                    db.Userpreferences.Add(tmpModel);

                    await db.SaveChangesAsync();
                    // apply theme change
                    newTheme = "dark";
                    //Session["UserTheme"] = Utils.User.UserStylePreference(User.Identity.Name);
                }
            }

            Utils.User.SetUserStylePreferenceCookie(newTheme);
            Response.StatusCode = 200;
            return Json("Toggled Night Mode", JsonRequestBehavior.AllowGet);
        }
Exemplo n.º 4
0
        public async Task<ActionResult> UserPreferences([Bind(Include = "Disable_custom_css, Night_mode, OpenLinksInNewTab, Enable_adult_content, Public_subscriptions, Topmenu_from_subscriptions, Shortbio, Avatar")] UserPreferencesViewModel model)
        {
            var newTheme = "light";
            // save changes
            using (var db = new voatEntities())
            {
                var userPreferences = db.Userpreferences.Find(User.Identity.Name);

                if (userPreferences != null)
                {
                    // modify existing preferences
                    userPreferences.Disable_custom_css = model.Disable_custom_css;
                    userPreferences.Night_mode = model.Night_mode;
                    userPreferences.Clicking_mode = model.OpenLinksInNewTab;
                    userPreferences.Enable_adult_content = model.Enable_adult_content;
                    userPreferences.Public_subscriptions = model.Public_subscriptions;
                    userPreferences.Topmenu_from_subscriptions = model.Topmenu_from_subscriptions;

                    await db.SaveChangesAsync();
                    // apply theme change
                    newTheme = userPreferences.Night_mode ? "dark" : "light";
                    //Session["UserTheme"] = Utils.User.UserStylePreference(User.Identity.Name);
                }
                else
                {
                    // create a new record for this user in userpreferences table
                    var tmpModel = new Userpreference
                    {
                        Disable_custom_css = model.Disable_custom_css,
                        Night_mode = model.Night_mode,
                        Clicking_mode = model.OpenLinksInNewTab,
                        Enable_adult_content = model.Enable_adult_content,
                        Public_subscriptions = model.Public_subscriptions,
                        Topmenu_from_subscriptions = model.Topmenu_from_subscriptions,
                        Username = User.Identity.Name
                    };
                    db.Userpreferences.Add(tmpModel);

                    await db.SaveChangesAsync();
                    newTheme = userPreferences.Night_mode ? "dark" : "light";
                    // apply theme change
                    //Session["UserTheme"] = Utils.User.UserStylePreference(User.Identity.Name);
                }
            }

            //return RedirectToAction("Manage", new { Message = "Your user preferences have been saved." });
            Utils.User.SetUserStylePreferenceCookie(newTheme);
            return RedirectToAction("Manage");
        }
Exemplo n.º 5
0
        public async Task<ActionResult> UserPreferencesAbout([Bind(Include = "Shortbio, Avatarfile")] UserAboutViewModel model)
        {
            // save changes
            using (var db = new voatEntities())
            {
                var userPreferences = db.Userpreferences.Find(User.Identity.Name);
                var tmpModel = new Userpreference();

                if (userPreferences == null)
                {
                    // create a new record for this user in userpreferences table
                    tmpModel.Shortbio = model.Shortbio;
                    tmpModel.Username = User.Identity.Name;
                }

                if (model.Avatarfile != null && model.Avatarfile.ContentLength > 0)
                {
                    // check uploaded file size is < 300000 bytes (300 kilobytes)
                    if (model.Avatarfile.ContentLength < 300000)
                    {
                        try
                        {
                            using (var img = Image.FromStream(model.Avatarfile.InputStream))
                            {
                                if (img.RawFormat.Equals(ImageFormat.Jpeg) || img.RawFormat.Equals(ImageFormat.Png))
                                {
                                    // resize uploaded file
                                    var thumbnailResult = ThumbGenerator.GenerateAvatar(img, User.Identity.Name, model.Avatarfile.ContentType);
                                    if (thumbnailResult)
                                    {
                                        if (userPreferences == null)
                                        {
                                            tmpModel.Avatar = User.Identity.Name + ".jpg";
                                        }
                                        else
                                        {
                                            userPreferences.Avatar = User.Identity.Name + ".jpg";
                                        }
                                    }
                                    else
                                    {
                                        // unable to generate thumbnail
                                        ModelState.AddModelError("", "Uploaded file is not recognized as a valid image.");
                                        return RedirectToAction("Manage", new { Message = ManageMessageId.InvalidFileFormat });
                                    }
                                }
                                else
                                {
                                    // uploaded file was invalid
                                    ModelState.AddModelError("", "Uploaded file is not recognized as an image.");
                                    return RedirectToAction("Manage", new { Message = ManageMessageId.InvalidFileFormat });
                                }
                            }
                        }
                        catch (Exception)
                        {
                            // uploaded file was invalid
                            ModelState.AddModelError("", "Uploaded file is not recognized as an image.");
                            return RedirectToAction("Manage", new { Message = ManageMessageId.InvalidFileFormat });
                        }
                    }
                    else
                    {
                        // refuse to save the file and explain why
                        ModelState.AddModelError("", "Uploaded image may not exceed 300 kb, please upload a smaller image.");
                        return RedirectToAction("Manage", new { Message = ManageMessageId.UploadedFileToolarge });
                    }
                }

                if (userPreferences == null)
                {
                    db.Userpreferences.Add(tmpModel);
                    await db.SaveChangesAsync();
                }
                else
                {
                    userPreferences.Shortbio = model.Shortbio;
                    userPreferences.Username = User.Identity.Name;
                    await db.SaveChangesAsync();
                }

            }

            return RedirectToAction("Manage");
        }
Exemplo n.º 6
0
        public static async Task SendCommentNotification(Comment comment)
        {
            try 
            { 
                using (var _db = new voatEntities())
                {
                    Random _rnd = new Random();

                    if (comment.ParentId != null && comment.CommentContent != null)
                    {
                        // find the parent comment and its author
                        var parentComment = _db.Comments.Find(comment.ParentId);
                        if (parentComment != null)
                        {
                            // check if recipient exists
                            if (User.UserExists(parentComment.Name))
                            {
                                // do not send notification if author is the same as comment author
                                if (parentComment.Name != HttpContext.Current.User.Identity.Name)
                                {
                                    // send the message

                                    var submission = DataCache.Submission.Retrieve(comment.MessageId);
                                    if (submission != null)
                                    {
                                        var subverse = DataCache.Subverse.Retrieve(submission.Subverse);

                                        var commentReplyNotification = new Commentreplynotification();
                                        commentReplyNotification.CommentId = comment.Id;
                                        commentReplyNotification.SubmissionId = submission.Id;
                                        commentReplyNotification.Recipient = parentComment.Name;
                                        if (submission.Anonymized || subverse.anonymized_mode)
                                        {
                                            commentReplyNotification.Sender = _rnd.Next(10000, 20000).ToString(CultureInfo.InvariantCulture);
                                        }
                                        else
                                        {
                                            commentReplyNotification.Sender = HttpContext.Current.User.Identity.Name;
                                        }
                                        commentReplyNotification.Body = comment.CommentContent;
                                        commentReplyNotification.Subverse = subverse.name;
                                        commentReplyNotification.Status = true;
                                        commentReplyNotification.Timestamp = DateTime.Now;

                                        // self = type 1, url = type 2
                                        commentReplyNotification.Subject = submission.Type == 1 ? submission.Title : submission.Linkdescription;

                                        _db.Commentreplynotifications.Add(commentReplyNotification);

                                        await _db.SaveChangesAsync();

                                        // get count of unread notifications
                                        int unreadNotifications = User.UnreadTotalNotificationsCount(commentReplyNotification.Recipient);

                                        // send SignalR realtime notification to recipient
                                        var hubContext = GlobalHost.ConnectionManager.GetHubContext<MessagingHub>();
                                        hubContext.Clients.User(commentReplyNotification.Recipient).setNotificationsPending(unreadNotifications);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        // comment reply is sent to a root comment which has no parent id, trigger post reply notification
                        var submission = DataCache.Submission.Retrieve(comment.MessageId);
                        if (submission != null)
                        {
                            // check if recipient exists
                            if (User.UserExists(submission.Name))
                            {
                                // do not send notification if author is the same as comment author
                                if (submission.Name != HttpContext.Current.User.Identity.Name)
                                {
                                    // send the message
                                    var postReplyNotification = new Postreplynotification();

                                    postReplyNotification.CommentId = comment.Id;
                                    postReplyNotification.SubmissionId = submission.Id;
                                    postReplyNotification.Recipient = submission.Name;
                                    var subverse = DataCache.Subverse.Retrieve(submission.Subverse);
                                    if (submission.Anonymized || subverse.anonymized_mode)
                                    {
                                        postReplyNotification.Sender = _rnd.Next(10000, 20000).ToString(CultureInfo.InvariantCulture);
                                    }
                                    else
                                    {
                                        postReplyNotification.Sender = HttpContext.Current.User.Identity.Name;
                                    }

                                    postReplyNotification.Body = comment.CommentContent;
                                    postReplyNotification.Subverse = submission.Subverse;
                                    postReplyNotification.Status = true;
                                    postReplyNotification.Timestamp = DateTime.Now;

                                    // self = type 1, url = type 2
                                    postReplyNotification.Subject = submission.Type == 1 ? submission.Title : submission.Linkdescription;

                                    _db.Postreplynotifications.Add(postReplyNotification);

                                    await _db.SaveChangesAsync();

                                    // get count of unread notifications
                                    int unreadNotifications = User.UnreadTotalNotificationsCount(postReplyNotification.Recipient);

                                    // send SignalR realtime notification to recipient
                                    var hubContext = GlobalHost.ConnectionManager.GetHubContext<MessagingHub>();
                                    hubContext.Clients.User(postReplyNotification.Recipient).setNotificationsPending(unreadNotifications);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 7
0
        public static async Task SendUserMentionNotification(string user, Message message)
        {
            if (message != null)
            {
                if (!User.UserExists(user))
                {
                    return;
                }

                string recipient = User.OriginalUsername(user);

                var commentReplyNotification = new Commentreplynotification();
                using (var _db = new voatEntities())
                {
                    //commentReplyNotification.CommentId = comment.Id;
                    commentReplyNotification.SubmissionId = message.Id;
                    commentReplyNotification.Recipient = recipient;
                    if (message.Anonymized || message.Subverses.anonymized_mode)
                    {
                        commentReplyNotification.Sender = (new Random()).Next(10000, 20000).ToString(CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        commentReplyNotification.Sender = message.Name;
                    }
                    commentReplyNotification.Body = message.MessageContent;
                    commentReplyNotification.Subverse = message.Subverse;
                    commentReplyNotification.Status = true;
                    commentReplyNotification.Timestamp = DateTime.Now;

                    commentReplyNotification.Subject = String.Format("@{0} mentioned you in post '{1}'", message.Name, message.Title);

                    _db.Commentreplynotifications.Add(commentReplyNotification);
                    await _db.SaveChangesAsync();
                }

                // get count of unread notifications
                int unreadNotifications = User.UnreadTotalNotificationsCount(commentReplyNotification.Recipient);

                // send SignalR realtime notification to recipient
                var hubContext = GlobalHost.ConnectionManager.GetHubContext<MessagingHub>();
                hubContext.Clients.User(commentReplyNotification.Recipient).setNotificationsPending(unreadNotifications);
            }
        }
Exemplo n.º 8
0
        // add new link submission
        public static async Task<string> AddNewSubmission(Message submissionModel, Subverse targetSubverse, string userName)
        {
            using (var db = new voatEntities())
            {
                // LINK TYPE SUBMISSION
                if (submissionModel.Type == 2)
                {
                    // strip unicode if title contains unicode
                    if (ContainsUnicode(submissionModel.Linkdescription))
                    {
                        submissionModel.Linkdescription = StripUnicode(submissionModel.Linkdescription);
                    }

                    // abort if title is < than 10 characters
                    if (submissionModel.Linkdescription.Length < 10)
                    {
                        // ABORT
                        return ("The title may not be less than 10 characters.");
                    }

                    // make sure the input URI is valid
                    if (!UrlUtility.IsUriValid(submissionModel.MessageContent))
                    {
                        // ABORT
                        return ("The URI you are trying to submit is invalid.");
                    }

                    // check if target subvere allows submissions from globally banned hostnames
                    if (!targetSubverse.exclude_sitewide_bans)
                    {
                        // check if hostname is banned before accepting submission
                        var domain = UrlUtility.GetDomainFromUri(submissionModel.MessageContent);
                        if (BanningUtility.IsHostnameBanned(domain))
                        {
                            // ABORT
                            return ("The hostname you are trying to submit is banned.");
                        }
                    }

                    // check if user has reached daily crossposting quota
                    if (User.DailyCrossPostingQuotaUsed(userName, submissionModel.MessageContent))
                    {
                        // ABORT
                        return ("You have reached your daily crossposting quota for this URL.");
                    }

                    // check if target subverse has thumbnails setting enabled before generating a thumbnail
                    if (targetSubverse.enable_thumbnails)
                    {
                        // try to generate and assign a thumbnail to submission model
                        submissionModel.Thumbnail = await ThumbGenerator.ThumbnailFromSubmissionModel(submissionModel);
                    }

                    // flag the submission as anonymized if it was submitted to a subverse with active anonymized_mode
                    if (targetSubverse.anonymized_mode)
                    {
                        submissionModel.Anonymized = true;
                    }
                    else
                    {
                        submissionModel.Name = userName;
                    }

                    // accept submission and save it to the database
                    submissionModel.Subverse = targetSubverse.name;
                    submissionModel.Likes = 1;
                    db.Messages.Add(submissionModel);

                    // update last submission received date for target subverse
                    targetSubverse.last_submission_received = DateTime.Now;
                    await db.SaveChangesAsync();
                }
                else
                // MESSAGE TYPE SUBMISSION
                {
                    // strip unicode if submission contains unicode
                    if (ContainsUnicode(submissionModel.Title))
                    {
                        submissionModel.Title = StripUnicode(submissionModel.Title);
                    }

                    // abort if title less than 10 characters
                    if (submissionModel.Title.Length < 10)
                    {
                        return ("Sorry, the the submission title may not be less than 10 characters.");
                    }

                    // flag the submission as anonymized if it was submitted to a subverse with active anonymized_mode
                    if (targetSubverse.anonymized_mode)
                    {
                        submissionModel.Anonymized = true;
                    }
                    else
                    {
                        submissionModel.Name = userName;
                    }

                    // grab server timestamp and modify submission timestamp to have posting time instead of "started writing submission" time
                    submissionModel.Subverse = targetSubverse.name;
                    submissionModel.Date = DateTime.Now;
                    submissionModel.Likes = 1;
                    db.Messages.Add(submissionModel);

                    // update last submission received date for target subverse
                    targetSubverse.last_submission_received = DateTime.Now;

                    if (ContentProcessor.Instance.HasStage(ProcessingStage.InboundPreSave))
                    {
                        submissionModel.MessageContent = ContentProcessor.Instance.Process(submissionModel.MessageContent, ProcessingStage.InboundPreSave, submissionModel);
                    }

                    await db.SaveChangesAsync();

                    if (ContentProcessor.Instance.HasStage(ProcessingStage.InboundPostSave))
                    {
                        ContentProcessor.Instance.Process(submissionModel.MessageContent, ProcessingStage.InboundPostSave, submissionModel);
                    }
                }
            }
            
            // null is returned if no errors were raised
            return null;
        }