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.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(); } if (onSuccess != null) { onSuccess(recipient); } } catch (Exception ex) { throw ex; } } }
// 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; } } }
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); }
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"); }
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"); }
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.CommentContent != 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.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(); 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.MessageId); if (submission != null) { // check if recipient exists if (UserHelper.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(); if (onSuccess != null) { onSuccess(postReplyNotification.Recipient); } } } } } } } catch (Exception ex) { throw ex; } }
// 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); } // 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.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 (UserHelper.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); } // 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."); } // 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; }
public static async Task SendUserMentionNotification(string user, Submission 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.IsAnonymized || subverse.IsAnonymized) { commentReplyNotification.Sender = (new Random()).Next(10000, 20000).ToString(CultureInfo.InvariantCulture); } else { commentReplyNotification.Sender = submission.UserName; } commentReplyNotification.Body = submission.Content; commentReplyNotification.Subverse = subverse.Name; commentReplyNotification.IsUnread = true; commentReplyNotification.CreationDate = DateTime.Now; commentReplyNotification.Subject = String.Format("@{0} mentioned you in post '{1}'", submission.UserName, submission.Title); _db.CommentReplyNotifications.Add(commentReplyNotification); await _db.SaveChangesAsync(); } if (onSuccess != null) { onSuccess(recipient); } } catch (Exception ex) { throw ex; } } }