예제 #1
0
        public async Task <ActionResult> CreateSet([Bind(Include = "Name, Description")] AddSet setTmpModel)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            int maximumOwnedSets = Settings.MaximumOwnedSets;

            // TODO
            // ###############################################################################################
            try
            {
                // abort if model is in invalid state
                if (!ModelState.IsValid)
                {
                    return(View());
                }

                // setup default values
                var set = new UserSet
                {
                    Name            = setTmpModel.Name,
                    Description     = setTmpModel.Description,
                    CreationDate    = DateTime.Now,
                    CreatedBy       = User.Identity.Name,
                    IsDefault       = false,
                    IsPublic        = true,
                    SubscriberCount = 0
                };

                // only allow users with less than maximum allowed sets to create a set
                var amountOfOwnedSets = _db.UserSets
                                        .Where(s => s.CreatedBy == User.Identity.Name)
                                        .ToList();

                if (amountOfOwnedSets.Count <= maximumOwnedSets)
                {
                    _db.UserSets.Add(set);
                    await _db.SaveChangesAsync();

                    // subscribe user to the newly created set
                    UserHelper.SubscribeToSet(User.Identity.Name, set.ID);

                    // go to newly created Set
                    return(RedirectToAction("EditSet", "Sets", new { setId = set.ID }));
                }

                ModelState.AddModelError(string.Empty, "Sorry, you can not own more than " + maximumOwnedSets + " sets.");
                return(View());
            }
            catch (Exception)
            {
                ModelState.AddModelError(string.Empty, "Something bad happened.");
                return(View());
            }
            // ###############################################################################################
        }
예제 #2
0
        public async Task <ActionResult> Compose([Bind(Include = "Id,Recipient,Subject,Body")] Privatemessage privateMessage)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }
            if (privateMessage.Recipient == null || privateMessage.Subject == null || privateMessage.Body == null)
            {
                return(RedirectToAction("Sent", "Messaging"));
            }

            if (Karma.CommentKarma(User.Identity.Name) < 100)
            {
                bool isCaptchaValid = await ReCaptchaUtility.Validate(Request);

                if (!isCaptchaValid)
                {
                    ModelState.AddModelError(string.Empty, "Incorrect recaptcha answer.");
                    return(View());
                }
            }

            // check if recipient exists
            if (Voat.Utilities.UserHelper.UserExists(privateMessage.Recipient) && !Voat.Utilities.UserHelper.IsUserGloballyBanned(User.Identity.Name))
            {
                // send the submission
                privateMessage.Timestamp = DateTime.Now;
                privateMessage.Sender    = User.Identity.Name;
                privateMessage.Status    = true;
                if (Voat.Utilities.UserHelper.IsUserGloballyBanned(User.Identity.Name))
                {
                    return(RedirectToAction("Sent", "Messaging"));
                }
                _db.Privatemessages.Add(privateMessage);
                try
                {
                    await _db.SaveChangesAsync();

                    // get count of unread notifications
                    int unreadNotifications = Voat.Utilities.UserHelper.UnreadTotalNotificationsCount(privateMessage.Recipient);

                    // send SignalR realtime notification to recipient
                    var hubContext = GlobalHost.ConnectionManager.GetHubContext <MessagingHub>();
                    hubContext.Clients.User(privateMessage.Recipient).setNotificationsPending(unreadNotifications);
                }
                catch (Exception)
                {
                    return(View("~/Views/Errors/DbNotResponding.cshtml"));
                }
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Sorry, there is no recipient with that username.");
                return(View());
            }
            return(RedirectToAction("Sent", "Messaging"));
        }
예제 #3
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)
        {
            if (!ModelState.IsValid)
            {
                return(View("Manage", model));
            }

            // save changes
            string newTheme;

            using (var db = new voatEntities())
            {
                var userPreferences = db.UserPreferences.Find(User.Identity.Name);

                if (userPreferences != null)
                {
                    // modify existing preferences
                    userPreferences.DisableCSS           = model.Disable_custom_css;
                    userPreferences.NightMode            = model.Night_mode;
                    userPreferences.OpenInNewWindow      = model.OpenLinksInNewTab;
                    userPreferences.EnableAdultContent   = model.Enable_adult_content;
                    userPreferences.DisplaySubscriptions = model.Public_subscriptions;
                    userPreferences.UseSubscriptionsMenu = model.Topmenu_from_subscriptions;

                    await db.SaveChangesAsync();

                    newTheme = userPreferences.NightMode ? "dark" : "light";
                }
                else
                {
                    // create a new record for this user in userpreferences table
                    var tmpModel = new UserPreference
                    {
                        DisableCSS           = model.Disable_custom_css ? true : false,
                        NightMode            = model.Night_mode ? true : false,
                        Language             = "en",
                        OpenInNewWindow      = model.OpenLinksInNewTab ? true : false,
                        EnableAdultContent   = model.Enable_adult_content ? true : false,
                        DisplayVotes         = false,
                        DisplaySubscriptions = model.Public_subscriptions ? true : false,
                        UseSubscriptionsMenu = model.Topmenu_from_subscriptions,
                        UserName             = User.Identity.Name
                    };
                    db.UserPreferences.Add(tmpModel);

                    await db.SaveChangesAsync();

                    newTheme = tmpModel.NightMode ? "dark" : "light";
                }
            }

            UserHelper.SetUserStylePreferenceCookie(newTheme);
            return(RedirectToAction("Manage"));
        }
예제 #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"));
        }
예제 #5
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.IsUnread)
                                                                            .OrderByDescending(s => s.CreationDate)
                                                                            .ThenBy(s => s.Sender);

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

                        foreach (var singleMessage in unreadPrivateMessages.ToList())
                        {
                            singleMessage.IsUnread = 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.IsUnread && s.ID == itemId);
                        if (privateMessageToMarkAsread == null)
                        {
                            return(false);
                        }

                        var item = db.PrivateMessages.Find(itemId);
                        item.IsUnread = false;
                        await db.SaveChangesAsync();

                        return(true);
                    }
                    return(false);
                }
                catch (Exception)
                {
                    return(false);
                }
            }
        }
예제 #6
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)
        {
            ViewBag.UserName = User.Identity.Name;

            if (!ModelState.IsValid)
            {
                return(View("Manage", model));
            }

            // save changes
            string newTheme;

            using (var db = new voatEntities())
            {
                var userPreferences = GetUserPreference(db);

                // modify existing preferences
                userPreferences.DisableCSS           = model.Disable_custom_css;
                userPreferences.NightMode            = model.Night_mode;
                userPreferences.OpenInNewWindow      = model.OpenLinksInNewTab;
                userPreferences.EnableAdultContent   = model.Enable_adult_content;
                userPreferences.DisplaySubscriptions = model.Public_subscriptions;
                userPreferences.UseSubscriptionsMenu = model.Topmenu_from_subscriptions;

                await db.SaveChangesAsync();

                newTheme = userPreferences.NightMode ? "dark" : "light";
            }

            ClearUserCache();
            UserHelper.SetUserStylePreferenceCookie(newTheme);
            return(RedirectToAction("Manage"));
        }
예제 #7
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));
        }
예제 #8
0
        public async Task <ActionResult> SendPrivateMessage([Bind(Include = "ID,Recipient,Subject,Body")] PrivateMessage privateMessage)
        {
            if (!ModelState.IsValid)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.Forbidden));
            }
            if (privateMessage.Recipient == null || privateMessage.Subject == null || privateMessage.Body == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.OK));
            }
            // check if recipient exists
            if (UserHelper.UserExists(privateMessage.Recipient))
            {
                // send the submission
                privateMessage.CreationDate = DateTime.Now;
                privateMessage.Sender       = User.Identity.Name;
                privateMessage.IsUnread     = true;
                if (Voat.Utilities.UserHelper.IsUserGloballyBanned(User.Identity.Name))
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.OK));
                }
                _db.PrivateMessages.Add(privateMessage);

                try
                {
                    await _db.SaveChangesAsync();

                    // get count of unread notifications
                    int unreadNotifications = Voat.Utilities.UserHelper.UnreadTotalNotificationsCount(privateMessage.Recipient);

                    // send SignalR realtime notification to recipient
                    var hubContext = GlobalHost.ConnectionManager.GetHubContext <MessagingHub>();
                    hubContext.Clients.User(privateMessage.Recipient).setNotificationsPending(unreadNotifications);
                }
                catch (Exception)
                {
                    return(View("~/Views/Errors/DbNotResponding.cshtml"));
                }
            }
            else
            {
                return(new HttpStatusCodeResult(HttpStatusCode.Forbidden));
            }

            return(new HttpStatusCodeResult(HttpStatusCode.OK));
        }
예제 #9
0
        public static async Task SendUserMentionNotification(string user, Comment comment, Action <string> onSuccess)
        {
            if (comment != null)
            {
                if (!UserHelper.UserExists(user))
                {
                    return;
                }
                try
                {
                    string recipient = UserHelper.OriginalUsername(user);

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

                        commentReplyNotification.CommentID    = comment.ID;
                        commentReplyNotification.SubmissionID = comment.SubmissionID.Value;
                        commentReplyNotification.Recipient    = recipient;
                        if (submission.IsAnonymized || subverse.IsAnonymized)
                        {
                            commentReplyNotification.Sender = (new Random()).Next(10000, 20000).ToString(CultureInfo.InvariantCulture);
                        }
                        else
                        {
                            commentReplyNotification.Sender = comment.UserName;
                        }
                        commentReplyNotification.Body         = comment.Content;
                        commentReplyNotification.Subverse     = subverse.Name;
                        commentReplyNotification.IsUnread     = true;
                        commentReplyNotification.CreationDate = DateTime.Now;

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

                        _db.CommentReplyNotifications.Add(commentReplyNotification);

                        await _db.SaveChangesAsync();
                    }

                    if (onSuccess != null)
                    {
                        onSuccess(recipient);
                    }
                }
                catch (Exception ex) {
                    throw ex;
                }
            }
        }
예제 #10
0
        public static async Task SendUserMentionNotification(string user, Message submission, Action <string> onSuccess)
        {
            if (submission != null)
            {
                if (!UserHelper.UserExists(user))
                {
                    return;
                }
                try {
                    string recipient = UserHelper.OriginalUsername(user);

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

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

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

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

                    if (onSuccess != null)
                    {
                        onSuccess(recipient);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
예제 #11
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);
            }
        }
예제 #12
0
        public async Task <ActionResult> ToggleNightMode()
        {
            string newTheme = "light";

            // save changes
            using (var db = new voatEntities())
            {
                var userPreferences = GetUserPreference(db);

                userPreferences.NightMode = !userPreferences.NightMode;
                await db.SaveChangesAsync();

                newTheme = userPreferences.NightMode ? "dark" : "light";
            }

            UserHelper.SetUserStylePreferenceCookie(newTheme);
            Response.StatusCode = 200;
            return(Json("Toggled Night Mode", JsonRequestBehavior.AllowGet));
        }
예제 #13
0
파일: Submissions.cs 프로젝트: zlzw/voat
        // add new submission
        public static async Task <string> AddNewSubmission(Submission 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);
                    }

                    // reject if title is whitespace or < than 5 characters
                    if (submissionModel.LinkDescription.Length < 5 || String.IsNullOrWhiteSpace(submissionModel.LinkDescription))
                    {
                        return("The title may not be less than 5 characters.");
                    }

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

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

                    // check if user has reached daily crossposting quota
                    if (UserHelper.DailyCrossPostingQuotaUsed(userName, submissionModel.Content))
                    {
                        // 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.IsThumbnailEnabled)
                    {
                        // 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
                    submissionModel.IsAnonymized = targetSubverse.IsAnonymized;
                    submissionModel.UserName     = userName;
                    submissionModel.Subverse     = targetSubverse.Name;
                    submissionModel.UpCount      = 1;
                    db.Submissions.Add(submissionModel);

                    await db.SaveChangesAsync();
                }
                else
                // MESSAGE TYPE SUBMISSION
                {
                    // strip unicode if submission contains unicode
                    if (ContainsUnicode(submissionModel.Title))
                    {
                        submissionModel.Title = StripUnicode(submissionModel.Title);
                    }

                    // reject if title is whitespace or less than 5 characters
                    if (submissionModel.Title.Length < 5 || String.IsNullOrWhiteSpace(submissionModel.Title))
                    {
                        return("Sorry, submission title may not be less than 5 characters.");
                    }

                    // grab server timestamp and modify submission timestamp to have posting time instead of "started writing submission" time
                    submissionModel.IsAnonymized = targetSubverse.IsAnonymized;
                    submissionModel.UserName     = userName;
                    submissionModel.Subverse     = targetSubverse.Name;
                    submissionModel.CreationDate = DateTime.Now;
                    submissionModel.UpCount      = 1;
                    db.Submissions.Add(submissionModel);

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

                    await db.SaveChangesAsync();

                    if (ContentProcessor.Instance.HasStage(ProcessingStage.InboundPostSave))
                    {
                        ContentProcessor.Instance.Process(submissionModel.Content, ProcessingStage.InboundPostSave, submissionModel);
                    }
                }
            }

            // null is returned if no errors were raised
            return(null);
        }
예제 #14
0
        public async Task <ActionResult> DeleteSubmission(int submissionId)
        {
            var submissionToDelete = _db.Submissions.Find(submissionId);

            if (submissionToDelete != null)
            {
                // delete submission if delete request is issued by submission author
                if (submissionToDelete.UserName == User.Identity.Name)
                {
                    submissionToDelete.IsDeleted = true;

                    if (submissionToDelete.Type == 1)
                    {
                        submissionToDelete.Content = "deleted by author at " + DateTime.Now;
                    }
                    else
                    {
                        submissionToDelete.Content = "http://voat.co";
                    }

                    // remove sticky if submission was stickied
                    var existingSticky = _db.StickiedSubmissions.FirstOrDefault(s => s.SubmissionID == submissionId);
                    if (existingSticky != null)
                    {
                        _db.StickiedSubmissions.Remove(existingSticky);
                    }

                    await _db.SaveChangesAsync();

                    DataCache.Submission.Remove(submissionId);
                }

                // delete submission if delete request is issued by subverse moderator
                else if (UserHelper.IsUserSubverseModerator(User.Identity.Name, submissionToDelete.Subverse))
                {
                    // mark submission as deleted
                    submissionToDelete.IsDeleted = true;

                    // move the submission to removal log
                    var removalLog = new SubmissionRemovalLog
                    {
                        SubmissionID = submissionToDelete.ID,
                        Moderator    = User.Identity.Name,
                        Reason       = "This feature is not yet implemented",
                        CreationDate = DateTime.Now
                    };

                    _db.SubmissionRemovalLogs.Add(removalLog);

                    if (submissionToDelete.Type == 1)
                    {
                        // notify submission author that his submission has been deleted by a moderator
                        MesssagingUtility.SendPrivateMessage(
                            "Voat",
                            submissionToDelete.UserName,
                            "Your submission has been deleted by a moderator",
                            "Your [submission](/v/" + submissionToDelete.Subverse + "/comments/" + submissionToDelete.ID + ") has been deleted by: " +
                            "/u/" + User.Identity.Name + " at " + DateTime.Now + "  " + Environment.NewLine +
                            "Original submission content was: " + Environment.NewLine +
                            "---" + Environment.NewLine +
                            "Submission title: " + submissionToDelete.Title + ", " + Environment.NewLine +
                            "Submission content: " + submissionToDelete.Content
                            );
                    }
                    else
                    {
                        // notify submission author that his submission has been deleted by a moderator
                        MesssagingUtility.SendPrivateMessage(
                            "Voat",
                            submissionToDelete.UserName,
                            "Your submission has been deleted by a moderator",
                            "Your [submission](/v/" + submissionToDelete.Subverse + "/comments/" + submissionToDelete.ID + ") has been deleted by: " +
                            "/u/" + User.Identity.Name + " at " + DateTime.Now + "  " + Environment.NewLine +
                            "Original submission content was: " + Environment.NewLine +
                            "---" + Environment.NewLine +
                            "Link description: " + submissionToDelete.LinkDescription + ", " + Environment.NewLine +
                            "Link URL: " + submissionToDelete.Content
                            );
                    }

                    // remove sticky if submission was stickied
                    var existingSticky = _db.StickiedSubmissions.FirstOrDefault(s => s.SubmissionID == submissionId);
                    if (existingSticky != null)
                    {
                        _db.StickiedSubmissions.Remove(existingSticky);
                    }

                    await _db.SaveChangesAsync();

                    DataCache.Submission.Remove(submissionId);
                }
            }

            string url = Request.UrlReferrer.AbsolutePath;

            return(Redirect(url));
        }
예제 #15
0
        public async Task <ActionResult> SubmitComment([Bind(Include = "ID, Content, SubmissionID, ParentID")] Comment commentModel)
        {
            commentModel.CreationDate = DateTime.Now;
            commentModel.UserName     = User.Identity.Name;
            commentModel.Votes        = 0;
            commentModel.UpCount      = 0;

            if (ModelState.IsValid)
            {
                // flag the comment as anonymized if it was submitted to a sub which has active anonymized_mode
                var submission = DataCache.Submission.Retrieve(commentModel.SubmissionID.Value);
                var subverse   = DataCache.Subverse.Retrieve(submission.Subverse);
                commentModel.IsAnonymized = submission.IsAnonymized || subverse.IsAnonymized;

                // if user CCP is < 50, allow only X comment submissions per 24 hours
                var userCcp = Karma.CommentKarma(User.Identity.Name);
                if (userCcp <= -50)
                {
                    var quotaUsed = UserHelper.UserDailyCommentPostingQuotaForNegativeScoreUsed(User.Identity.Name);
                    if (quotaUsed)
                    {
                        return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "You have reached your daily comment quota. Your current quota is " + Settings.DailyCommentPostingQuotaForNegativeScore.ToString() + " comment(s) per 24 hours."));
                        //ModelState.AddModelError("", "You have reached your daily comment quota. Your current quota is " + Settings.DailyCommentPostingQuotaForNegativeScore + " comment(s) per 24 hours.");
                        //return View();
                    }
                }

                // check if author is banned, don't save the comment or send notifications if true
                if (!UserHelper.IsUserGloballyBanned(User.Identity.Name) && !UserHelper.IsUserBannedFromSubverse(User.Identity.Name, submission.Subverse))
                {
                    bool containsBannedDomain = BanningUtility.ContentContainsBannedDomain(subverse.Name, commentModel.Content);
                    if (containsBannedDomain)
                    {
                        return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Comment contains links to banned domain(s)."));
                    }


                    if (ContentProcessor.Instance.HasStage(ProcessingStage.InboundPreSave))
                    {
                        commentModel.Content = ContentProcessor.Instance.Process(commentModel.Content, ProcessingStage.InboundPreSave, commentModel);
                    }

                    //save fully formatted content
                    var formattedComment = Formatting.FormatMessage(commentModel.Content);
                    commentModel.FormattedContent = formattedComment;

                    _db.Comments.Add(commentModel);

                    await _db.SaveChangesAsync();

                    DataCache.CommentTree.AddCommentToTree(commentModel);

                    if (ContentProcessor.Instance.HasStage(ProcessingStage.InboundPostSave))
                    {
                        ContentProcessor.Instance.Process(commentModel.Content, ProcessingStage.InboundPostSave, commentModel);
                    }

                    // send comment reply notification to parent comment author if the comment is not a new root comment
                    await NotificationManager.SendCommentNotification(commentModel,
                                                                      new Action <string>(recipient => {
                        //get count of unread notifications
                        int unreadNotifications = UserHelper.UnreadTotalNotificationsCount(recipient);
                        // send SignalR realtime notification to recipient
                        var hubContext = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext <MessagingHub>();
                        hubContext.Clients.User(recipient).setNotificationsPending(unreadNotifications);
                    })
                                                                      );
                }
                if (Request.IsAjaxRequest())
                {
                    var comment = commentModel;

                    ViewBag.CommentId   = comment.ID;               //why?
                    ViewBag.rootComment = comment.ParentID == null; //why?

                    if (submission.IsAnonymized || subverse.IsAnonymized)
                    {
                        comment.UserName = comment.ID.ToString(CultureInfo.InvariantCulture);
                    }

                    var model = new CommentBucketViewModel(comment);

                    return(PartialView("~/Views/Shared/Submissions/_SubmissionComment.cshtml", model));
                    //return new HttpStatusCodeResult(HttpStatusCode.OK);
                }
                if (Request.UrlReferrer != null)
                {
                    var url = Request.UrlReferrer.AbsolutePath;
                    return(Redirect(url));
                }
            }
            if (Request.IsAjaxRequest())
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            ModelState.AddModelError(String.Empty, "Sorry, you are either banned from this sub or doing that too fast. Please try again in 2 minutes.");
            return(View("~/Views/Help/SpeedyGonzales.cshtml"));
        }
예제 #16
0
        public async Task <ActionResult> UserPreferencesAbout([Bind(Include = "Bio, Avatarfile")] UserAboutViewModel model)
        {
            ViewBag.UserName = User.Identity.Name;
            // save changes
            using (var db = new voatEntities())
            {
                var userPreferences = GetUserPreference(db);

                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 = await ThumbGenerator.GenerateAvatar(img, User.Identity.Name, model.Avatarfile.ContentType);

                                    if (thumbnailResult)
                                    {
                                        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 }));
                    }
                }

                var bio = model.Bio.TrimSafe();

                if (String.IsNullOrEmpty(bio))
                {
                    userPreferences.Bio = "I tried to delete my bio but they gave me this instead";
                }
                else if (bio == STRINGS.DEFAULT_BIO)
                {
                    userPreferences.Bio = null;
                }
                else
                {
                    userPreferences.Bio = bio;
                }
                await db.SaveChangesAsync();
            }

            ClearUserCache();

            return(RedirectToAction("Manage"));
        }
예제 #17
0
        public static async Task SendCommentNotification(Comment comment, Action <string> onSuccess)
        {
            try
            {
                using (var _db = new voatEntities())
                {
                    Random _rnd = new Random();

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

                                    var submission = DataCache.Submission.Retrieve(comment.SubmissionID);
                                    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.UserName;
                                        if (submission.IsAnonymized || subverse.IsAnonymized)
                                        {
                                            commentReplyNotification.Sender = _rnd.Next(10000, 20000).ToString(CultureInfo.InvariantCulture);
                                        }
                                        else
                                        {
                                            commentReplyNotification.Sender = HttpContext.Current.User.Identity.Name;
                                        }
                                        commentReplyNotification.Body         = comment.Content;
                                        commentReplyNotification.Subverse     = subverse.Name;
                                        commentReplyNotification.IsUnread     = true;
                                        commentReplyNotification.CreationDate = DateTime.Now;

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

                                        _db.CommentReplyNotifications.Add(commentReplyNotification);

                                        await _db.SaveChangesAsync();

                                        if (onSuccess != null)
                                        {
                                            onSuccess(commentReplyNotification.Recipient);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        // comment reply is sent to a root comment which has no parent id, trigger post reply notification
                        var submission = DataCache.Submission.Retrieve(comment.SubmissionID);
                        if (submission != null)
                        {
                            // check if recipient exists
                            if (UserHelper.UserExists(submission.UserName))
                            {
                                // do not send notification if author is the same as comment author
                                if (submission.UserName != HttpContext.Current.User.Identity.Name)
                                {
                                    // send the message
                                    var postReplyNotification = new SubmissionReplyNotification();

                                    postReplyNotification.CommentID    = comment.ID;
                                    postReplyNotification.SubmissionID = submission.ID;
                                    postReplyNotification.Recipient    = submission.UserName;
                                    var subverse = DataCache.Subverse.Retrieve(submission.Subverse);
                                    if (submission.IsAnonymized || subverse.IsAnonymized)
                                    {
                                        postReplyNotification.Sender = _rnd.Next(10000, 20000).ToString(CultureInfo.InvariantCulture);
                                    }
                                    else
                                    {
                                        postReplyNotification.Sender = HttpContext.Current.User.Identity.Name;
                                    }

                                    postReplyNotification.Body         = comment.Content;
                                    postReplyNotification.Subverse     = submission.Subverse;
                                    postReplyNotification.IsUnread     = true;
                                    postReplyNotification.CreationDate = DateTime.Now;

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

                                    _db.SubmissionReplyNotifications.Add(postReplyNotification);

                                    await _db.SaveChangesAsync();

                                    if (onSuccess != null)
                                    {
                                        onSuccess(postReplyNotification.Recipient);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #18
0
        public async Task <ActionResult> Submit([Bind(Include = "Id,Votes,Name,Date,Type,Linkdescription,Title,Rank,MessageContent,Subverse")] Message submission)
        {
            // abort if model state is invalid
            if (!ModelState.IsValid)
            {
                return(View());
            }

            // save temp values for the view in case submission fails
            ViewBag.selectedSubverse = submission.Subverse;
            ViewBag.message          = submission.MessageContent;
            ViewBag.title            = submission.Title;
            ViewBag.linkDescription  = submission.Linkdescription;

            // grab server timestamp and modify submission timestamp to have posting time instead of "started writing submission" time
            submission.Date = DateTime.Now;

            // check if user is banned
            if (UserHelper.IsUserGloballyBanned(User.Identity.Name) || UserHelper.IsUserBannedFromSubverse(User.Identity.Name, submission.Subverse))
            {
                ViewBag.SelectedSubverse = submission.Subverse;
                return(View("~/Views/Home/Comments.cshtml", submission));
            }

            // check if subverse exists
            var targetSubverse = _db.Subverses.Find(submission.Subverse.Trim());

            if (targetSubverse == null || submission.Subverse.Equals("all", StringComparison.OrdinalIgnoreCase))
            {
                ModelState.AddModelError(string.Empty, "Sorry, The subverse you are trying to post to does not exist.");
                return(View("Submit"));
            }

            //wrap captcha check in anon method as following method is in non UI dll
            var captchaCheck = new Func <HttpRequestBase, Task <bool> >(request => {
                return(ReCaptchaUtility.Validate(request));
            });

            // check if this submission is valid and good to go
            var preProcessCheckResult = await Submissions.PreAddSubmissionCheck(submission, Request, User.Identity.Name, targetSubverse, captchaCheck);

            if (preProcessCheckResult != null)
            {
                ModelState.AddModelError(string.Empty, preProcessCheckResult);
                return(View("Submit"));
            }

            // submission is a link post
            if (submission.Type == 2 && submission.MessageContent != null && submission.Linkdescription != null)
            {
                // check if same link was submitted before and deny submission
                var existingSubmission = _db.Messages.FirstOrDefault(s => s.MessageContent.Equals(submission.MessageContent, StringComparison.OrdinalIgnoreCase) && s.Subverse.Equals(submission.Subverse, StringComparison.OrdinalIgnoreCase));

                // submission is a repost, discard it and inform the user
                if (existingSubmission != null)
                {
                    ModelState.AddModelError(string.Empty, "Sorry, this link has already been submitted by someone else.");

                    // todo: offer the option to repost after informing the user about it
                    return(RedirectToRoute(
                               "SubverseComments",
                               new
                    {
                        controller = "Comment",
                        action = "Comments",
                        id = existingSubmission.Id,
                        subversetoshow = existingSubmission.Subverse
                    }
                               ));
                }

                // process new link submission
                var addLinkSubmissionResult = await Submissions.AddNewSubmission(submission, targetSubverse, User.Identity.Name);

                if (addLinkSubmissionResult != null)
                {
                    ModelState.AddModelError(string.Empty, addLinkSubmissionResult);
                    return(View("Submit"));
                }
                // update last submission received date for target subverse
                targetSubverse.last_submission_received = DateTime.Now;
                await _db.SaveChangesAsync();
            }
            // submission is a message type submission
            else if (submission.Type == 1 && submission.Title != null)
            {
                // process new message type submission
                var addMessageSubmissionResult = await Submissions.AddNewSubmission(submission, targetSubverse, User.Identity.Name);

                if (addMessageSubmissionResult != null)
                {
                    ModelState.AddModelError(string.Empty, addMessageSubmissionResult);
                    return(View("Submit"));
                }
                // update last submission received date for target subverse
                targetSubverse.last_submission_received = DateTime.Now;
                await _db.SaveChangesAsync();
            }

            // redirect to comments section of newly posted submission
            return(RedirectToRoute(
                       "SubverseComments",
                       new
            {
                controller = "Comment",
                action = "Comments",
                id = submission.Id,
                subversetoshow = submission.Subverse
            }
                       ));
        }
예제 #19
0
        public async Task <ActionResult> SubmitComment([Bind(Include = "Id, CommentContent, MessageId, ParentId")] Comment commentModel)
        {
            commentModel.Date  = DateTime.Now;
            commentModel.Name  = User.Identity.Name;
            commentModel.Votes = 0;
            commentModel.Likes = 0;

            if (ModelState.IsValid)
            {
                // flag the comment as anonymized if it was submitted to a sub which has active anonymized_mode
                var message = _db.Messages.Find(commentModel.MessageId);
                if (message != null && (message.Anonymized || message.Subverses.anonymized_mode))
                {
                    commentModel.Anonymized = true;
                }

                // if user CCP is < 50, allow only X comment submissions per 24 hours
                var userCcp = Karma.CommentKarma(User.Identity.Name);
                if (userCcp <= -50)
                {
                    var quotaUsed = Utils.User.UserDailyCommentPostingQuotaForNegativeScoreUsed(User.Identity.Name);
                    if (quotaUsed)
                    {
                        ModelState.AddModelError("", "You have reached your daily comment quota. Your current quota is " + MvcApplication.DailyCommentPostingQuotaForNegativeScore + " comment(s) per 24 hours.");
                        return(View());
                    }
                }

                // check if author is banned, don't save the comment or send notifications if true
                if (!Utils.User.IsUserGloballyBanned(User.Identity.Name) && !Utils.User.IsUserBannedFromSubverse(User.Identity.Name, message.Subverse))
                {
                    if (ContentProcessor.Instance.HasStage(ProcessingStage.InboundPreSave))
                    {
                        commentModel.CommentContent = ContentProcessor.Instance.Process(commentModel.CommentContent, ProcessingStage.InboundPreSave, commentModel);
                    }

                    //save fully formatted content
                    var formattedComment = Formatting.FormatMessage(commentModel.CommentContent);
                    commentModel.FormattedContent = formattedComment;

                    _db.Comments.Add(commentModel);

                    await _db.SaveChangesAsync();

                    if (ContentProcessor.Instance.HasStage(ProcessingStage.InboundPostSave))
                    {
                        ContentProcessor.Instance.Process(commentModel.CommentContent, ProcessingStage.InboundPostSave, commentModel);
                    }

                    // send comment reply notification to parent comment author if the comment is not a new root comment
                    await NotificationManager.SendCommentNotification(commentModel);
                }

                if (Request.UrlReferrer != null)
                {
                    var url = Request.UrlReferrer.AbsolutePath;
                    return(Redirect(url));
                }
            }
            if (Request.IsAjaxRequest())
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            ModelState.AddModelError(String.Empty, "Sorry, you are either banned from this sub or doing that too fast. Please try again in 2 minutes.");
            return(View("~/Views/Help/SpeedyGonzales.cshtml"));
        }
예제 #20
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)
        {
            if (!ModelState.IsValid) return View("Manage", model);
            
            // save changes
            string newTheme;
            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();
                    newTheme = userPreferences.Night_mode ? "dark" : "light";
                }
                else
                {
                    // create a new record for this user in userpreferences table
                    var tmpModel = new Userpreference
                    {
                        Disable_custom_css = model.Disable_custom_css ? true : false,
                        Night_mode = model.Night_mode ? true : false,
                        Language = "en",
                        Clicking_mode = model.OpenLinksInNewTab ? true : false,
                        Enable_adult_content = model.Enable_adult_content ? true : false,
                        Public_votes = false,
                        Public_subscriptions = model.Public_subscriptions ? true : false,
                        Topmenu_from_subscriptions = model.Topmenu_from_subscriptions,
                        Username = User.Identity.Name
                    };
                    db.Userpreferences.Add(tmpModel);

                    await db.SaveChangesAsync();
                    newTheme = tmpModel.Night_mode ? "dark" : "light";
                }
            }

            UserHelper.SetUserStylePreferenceCookie(newTheme);
            return RedirectToAction("Manage");
        }
예제 #21
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 = await 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");
        }
예제 #22
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"));
        }
예제 #23
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"] = UserHelper.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"] = UserHelper.UserStylePreference(User.Identity.Name);
                }
            }

            //return RedirectToAction("Manage", new { Message = "Your user preferences have been saved." });
            UserHelper.SetUserStylePreferenceCookie(newTheme);
            return RedirectToAction("Manage");
        }
예제 #24
0
        public static async Task SendCommentNotification(Comment comment)
        {
            voatEntities _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 commentMessage = _db.Messages.Find(comment.MessageId);
                            if (commentMessage != null)
                            {
                                var commentReplyNotification = new Commentreplynotification();
                                commentReplyNotification.CommentId    = comment.Id;
                                commentReplyNotification.SubmissionId = commentMessage.Id;
                                commentReplyNotification.Recipient    = parentComment.Name;
                                if (parentComment.Message.Anonymized || parentComment.Message.Subverses.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  = commentMessage.Subverse;
                                commentReplyNotification.Status    = true;
                                commentReplyNotification.Timestamp = DateTime.Now;

                                // self = type 1, url = type 2
                                commentReplyNotification.Subject = parentComment.Message.Type == 1 ? parentComment.Message.Title : parentComment.Message.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 commentMessage = _db.Messages.Find(comment.MessageId);
                if (commentMessage != null)
                {
                    // check if recipient exists
                    if (User.UserExists(commentMessage.Name))
                    {
                        // do not send notification if author is the same as comment author
                        if (commentMessage.Name != HttpContext.Current.User.Identity.Name)
                        {
                            // send the message
                            var postReplyNotification = new Postreplynotification();

                            postReplyNotification.CommentId    = comment.Id;
                            postReplyNotification.SubmissionId = commentMessage.Id;
                            postReplyNotification.Recipient    = commentMessage.Name;

                            if (commentMessage.Anonymized || commentMessage.Subverses.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  = commentMessage.Subverse;
                            postReplyNotification.Status    = true;
                            postReplyNotification.Timestamp = DateTime.Now;

                            // self = type 1, url = type 2
                            postReplyNotification.Subject = commentMessage.Type == 1 ? commentMessage.Title : commentMessage.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);
                        }
                    }
                }
            }
        }
예제 #25
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"] = UserHelper.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"] = UserHelper.UserStylePreference(User.Identity.Name);
                }
            }

            UserHelper.SetUserStylePreferenceCookie(newTheme);
            Response.StatusCode = 200;
            return Json("Toggled Night Mode", JsonRequestBehavior.AllowGet);
        }
예제 #26
0
        // GET: Renders Primary Submission Comments Page
        public async Task <ActionResult> Comments(int?submissionID, string subverseName, int?commentID, string sort, int?context)
        {
            #region Validation

            if (submissionID == null)
            {
                return(GenericErrorView(new ErrorViewModel()
                {
                    Description = "Can not find what was requested because input is not valid"
                }));
            }

            var submission = _db.Submissions.Find(submissionID.Value);

            if (submission == null)
            {
                return(NotFoundErrorView());
            }

            // make sure that the combination of selected subverse and submission subverse are linked
            if (!submission.Subverse.Equals(subverseName, StringComparison.OrdinalIgnoreCase))
            {
                return(NotFoundErrorView());
            }

            var subverse = DataCache.Subverse.Retrieve(subverseName);
            //var subverse = _db.Subverse.Find(subversetoshow);

            if (subverse == null)
            {
                return(NotFoundErrorView());
            }

            if (subverse.IsAdminDisabled.HasValue && subverse.IsAdminDisabled.Value)
            {
                ViewBag.Subverse = subverse.Name;
                return(SubverseDisabledErrorView());
            }

            #endregion

            if (commentID != null)
            {
                ViewBag.StartingCommentId  = commentID;
                ViewBag.CommentToHighLight = commentID;
            }

            #region Set ViewBag
            ViewBag.Subverse   = subverse;
            ViewBag.Submission = submission;
            //This is a required view bag property in _Layout.cshtml
            ViewBag.SelectedSubverse = subverse.Name;

            var SortingMode = (sort == null ? "top" : sort).ToLower();
            ViewBag.SortingMode = SortingMode;

            #endregion

            #region Track Views

            // experimental: register a new session for this subverse
            string clientIpAddress = UserHelper.UserIpAddress(Request);
            if (clientIpAddress != String.Empty)
            {
                // generate salted hash of client IP address
                string ipHash = IpHash.CreateHash(clientIpAddress);

                // register a new session for this subverse
                SessionHelper.Add(subverse.Name, ipHash);

                //TODO: This needs to be executed in seperate task
                #region TODO

                // register a new view for this thread
                // check if this hash is present for this submission id in viewstatistics table
                var existingView = _db.ViewStatistics.Find(submission.ID, ipHash);

                // this IP has already viwed this thread, skip registering a new view
                if (existingView == null)
                {
                    // this is a new view, register it for this submission
                    var view = new ViewStatistic {
                        SubmissionID = submission.ID, ViewerID = ipHash
                    };
                    _db.ViewStatistics.Add(view);
                    submission.Views++;
                    await _db.SaveChangesAsync();
                }

                #endregion
            }

            #endregion
            CommentSegment model = null;
            if (commentID != null)
            {
                ViewBag.CommentToHighLight = commentID.Value;
                model = await GetCommentContext(submission.ID, commentID.Value, context, sort);
            }
            else
            {
                model = await GetCommentSegment(submission.ID, null, 0, sort);
            }

            var q = new QuerySubverseModerators(subverseName);
            ViewBag.ModeratorList = await q.ExecuteAsync();

            return(View("~/Views/Home/Comments.cshtml", model));
        }