// get total unread notifications count for a given user public static int UnreadTotalNotificationsCount(string userName) { using (var db = new whoaverseEntities()) { int totalCount = 0; int unreadPrivateMessagesCount = db.Privatemessages.Count(s => s.Recipient.Equals(userName, StringComparison.OrdinalIgnoreCase) && s.Status && s.Markedasunread == false); int unreadPostRepliesCount = db.Postreplynotifications.Count(s => s.Recipient.Equals(userName, StringComparison.OrdinalIgnoreCase) && s.Status && s.Markedasunread == false); int unreadCommentRepliesCount = db.Commentreplynotifications.Count(s => s.Recipient.Equals(userName, StringComparison.OrdinalIgnoreCase) && s.Status && s.Markedasunread == false); totalCount = totalCount + unreadPrivateMessagesCount + unreadPostRepliesCount + unreadCommentRepliesCount; return(totalCount); } }
// returns -1:downvoted, 1:upvoted, or 0:not voted public static int CheckIfVotedComment(string userToCheck, int commentId) { int intCheckResult = 0; using (var db = new whoaverseEntities()) { var checkResult = db.Commentvotingtrackers.FirstOrDefault(b => b.CommentId == commentId && b.UserName == userToCheck); intCheckResult = checkResult != null ? checkResult.VoteStatus.Value : 0; return(intCheckResult); } }
// returns -1:downvoted, 1:upvoted, 0:not voted public static int CheckIfVoted(string userToCheck, int messageId) { using (var db = new whoaverseEntities()) { var checkResult = db.Votingtrackers.Where(u => u.UserName == userToCheck && u.MessageId == messageId) .AsNoTracking() .FirstOrDefault(); int intCheckResult = checkResult != null ? checkResult.VoteStatus.Value : 0; return(intCheckResult); } }
// get session count for given subverse //HACK: This query is expensive. Cache results. public static int ActiveSessionsForSubverse(string subverseName) { try { string cacheKey = String.Format("activeSubSessions_{0}", subverseName); object cacheData = System.Web.HttpContext.Current.Cache[cacheKey]; if (cacheData != null) { return((int)cacheData); } int count = 0; using (whoaverseEntities db = new whoaverseEntities()) { var cmd = db.Database.Connection.CreateCommand(); cmd.CommandText = "SELECT ISNULL(COUNT(*),0) FROM [dbo].[Sessiontracker] WITH (NOLOCK) WHERE [Subverse] = @Subverse"; var param = cmd.CreateParameter(); param.ParameterName = "Subverse"; param.DbType = System.Data.DbType.String; param.Value = subverseName; cmd.Parameters.Add(param); if (cmd.Connection.State != System.Data.ConnectionState.Open) { cmd.Connection.Open(); } count = (int)cmd.ExecuteScalar(); System.Web.HttpContext.Current.Cache.Insert(cacheKey, count, null, DateTime.Now.AddSeconds(120), System.Web.Caching.Cache.NoSlidingExpiration); } return(count); //using (var db = new whoaverseEntities()) //{ // var result = from sessions in db.Sessiontrackers // where sessions.Subverse.Equals(subverseName) // select sessions; // return result.Count(); //} } catch (Exception) { return(-1); } }
// 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 whoaverseEntities()) { 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); } } }
// get link contribution points for a user public static int LinkKarma(string userName) { string cacheKey = CacheKey(userName, KarmaCacheType.Link); object cacheData = Cache[cacheKey]; if (cacheData != null) { return((int)cacheData); } int count = 0; using (whoaverseEntities db = new whoaverseEntities()) { var cmd = db.Database.Connection.CreateCommand(); cmd.CommandText = "SELECT ISNULL(SUM(Likes - Dislikes), 0) FROM Messages WITH (NOLOCK) WHERE Name = @Name"; var param = cmd.CreateParameter(); param.ParameterName = "Name"; param.DbType = System.Data.DbType.String; param.Value = userName; cmd.Parameters.Add(param); if (cmd.Connection.State != System.Data.ConnectionState.Open) { cmd.Connection.Open(); } long l = (long)cmd.ExecuteScalar(); count = (int)l; Cache.Insert(cacheKey, count, null, DateTime.Now.AddSeconds(cacheTimeInSeconds), System.Web.Caching.Cache.NoSlidingExpiration); } return(count); //using (var db = new whoaverseEntities()) //{ // try // { // return db.Messages.Where(c => c.Name.Trim().Equals(userName, StringComparison.OrdinalIgnoreCase)) // .Select(c => c.Likes - c.Dislikes) // .Sum(); // } // catch (Exception) // { // return 0; // } //} }
// delete a user account and all history: comments, posts and votes public static bool DeleteUser(string userName) { using (var db = new whoaverseEntities()) { using (var tmpUserManager = new UserManager <WhoaVerseUser>(new UserStore <WhoaVerseUser>(new ApplicationDbContext()))) { var tmpuser = tmpUserManager.FindByName(userName); if (tmpuser != null) { //remove voting history for submisions db.Votingtrackers.RemoveRange(db.Votingtrackers.Where(x => x.UserName == userName)); //remove voting history for comments db.Commentvotingtrackers.RemoveRange(db.Commentvotingtrackers.Where(x => x.UserName == userName)); //remove all comments var comments = db.Comments.Where(c => c.Name == userName); foreach (Comment c in comments) { c.Name = "deleted"; c.CommentContent = "deleted by user"; db.SaveChangesAsync(); } //remove all submissions var submissions = db.Messages.Where(c => c.Name == userName); foreach (Message s in submissions) { if (s.Type == 1) { s.Name = "deleted"; s.MessageContent = "deleted by user"; s.Title = "deleted by user"; } else { s.Name = "deleted"; s.Linkdescription = "deleted by user"; s.MessageContent = "http://voat.co"; } } db.SaveChangesAsync(); tmpUserManager.DeleteAsync(tmpuser); return(true); } return(false); } } }
public async Task <ActionResult> UserPreferences([Bind(Include = "Disable_custom_css, Night_mode, OpenLinksInNewTab, Enable_adult_content, Enable_only_adult_content, Public_subscriptions, Topmenu_from_subscriptions, Shortbio, Avatar")] UserPreferencesViewModel model) { // save changes using (var db = new whoaverseEntities()) { 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.Enable_only_adult_content = model.Enable_only_adult_content; userPreferences.Public_subscriptions = model.Public_subscriptions; userPreferences.Topmenu_from_subscriptions = model.Topmenu_from_subscriptions; await db.SaveChangesAsync(); // 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 = model.Disable_custom_css, Night_mode = model.Night_mode, Clicking_mode = model.OpenLinksInNewTab, Enable_adult_content = model.Enable_adult_content, Enable_only_adult_content = model.Enable_only_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(); // apply theme change Session["UserTheme"] = Utils.User.UserStylePreference(User.Identity.Name); } } //return RedirectToAction("Manage", new { Message = "Your user preferences have been saved." }); return(RedirectToAction("Manage")); }
// check if given user is subscribed to a given subverse public static bool IsUserSubverseSubscriber(string userName, string subverse) { using (whoaverseEntities db = new whoaverseEntities()) { var subverseSubscriber = db.Subscriptions.Where(n => n.SubverseName.ToLower() == subverse.ToLower() && n.Username == userName).FirstOrDefault(); if (subverseSubscriber != null) { return(true); } else { return(false); }; } }
// check if given user is moderator for a given subverse public static bool IsUserSubverseModerator(string userName, string subverse) { using (whoaverseEntities db = new whoaverseEntities()) { var subverseModerator = db.SubverseAdmins.Where(n => n.SubverseName.ToLower() == subverse.ToLower() && n.Username.ToLower() == userName && n.Power == 2).FirstOrDefault(); if (subverseModerator != null && subverseModerator.Username.ToLower() == userName.ToLower()) { return(true); } else { return(false); }; } }
// a user has saved this comment earlier and wishes to unsave it, delete the record private static void UnSaveComment(string userWhichSaved, int commentId) { using (var db = new whoaverseEntities()) { var votingTracker = db.Commentsavingtrackers.FirstOrDefault(b => b.CommentId == commentId && b.UserName == userWhichSaved); if (votingTracker == null) { return; } // delete vote history db.Commentsavingtrackers.Remove(votingTracker); db.SaveChanges(); } }
public static int CommentKarma(string userName) { using (whoaverseEntities db = new whoaverseEntities()) { int sumOfLikes = db.Comments.AsEnumerable() .Where(r => r.Name.Trim().Equals(userName, StringComparison.OrdinalIgnoreCase)) .Sum(r => (int)r.Likes); int sumOfdislikes = db.Comments.AsEnumerable() .Where(r => r.Name.Trim().Equals(userName, StringComparison.OrdinalIgnoreCase)) .Sum(r => (int)r.Dislikes); return(sumOfLikes - sumOfdislikes); } }
public static int LinkKarma(string userName) { using (whoaverseEntities db = new whoaverseEntities()) { int likes = db.Messages.AsEnumerable() .Where(r => r.Name.Equals(userName, StringComparison.OrdinalIgnoreCase) && r.Type == 2) .Sum(r => (int)r.Likes); int dislikes = db.Messages.AsEnumerable() .Where(r => r.Name.Equals(userName, StringComparison.OrdinalIgnoreCase) && r.Type == 2) .Sum(r => (int)r.Dislikes); return(likes - dislikes); } }
// check if given user has unread private messages and return the count public static int UnreadPrivateMessagesCount(string userName) { using (var db = new whoaverseEntities()) { var privateMessages = db.Privatemessages .Where(s => s.Recipient.Equals(userName, StringComparison.OrdinalIgnoreCase)) .OrderBy(s => s.Timestamp) .ThenBy(s => s.Sender); if (!privateMessages.Any()) return 0; var unreadPrivateMessages = privateMessages.Where(s => s.Status && s.Markedasunread == false); return unreadPrivateMessages.Any() ? unreadPrivateMessages.Count() : 0; } }
// check if given user has unread comment replies and return the count public static int UnreadCommentRepliesCount(string userName) { using (var db = new whoaverseEntities()) { var commentReplies = db.Commentreplynotifications .Where(s => s.Recipient.Equals(userName, StringComparison.OrdinalIgnoreCase)) .OrderBy(s => s.Timestamp) .ThenBy(s => s.Sender); if (!commentReplies.Any()) return 0; var unreadCommentReplies = commentReplies.Where(s => s.Status && s.Markedasunread == false); return unreadCommentReplies.Any() ? unreadCommentReplies.Count() : 0; } }
// a user has either upvoted or downvoted this submission earlier and wishes to reset the vote, delete the record public static void ResetMessageVote(string userWhichVoted, int messageId) { using (var db = new whoaverseEntities()) { var votingTracker = db.Votingtrackers.FirstOrDefault(b => b.MessageId == messageId && b.UserName == userWhichVoted); if (votingTracker == null) { return; } //delete vote history db.Votingtrackers.Remove(votingTracker); db.SaveChanges(); } }
// get short bio for a given user public static string UserShortbio(string userName) { const string placeHolderMessage = "Aww snap, this user did not yet write their bio. If they did, it would show up here, you know."; using (var db = new whoaverseEntities()) { var result = db.Userpreferences.Find(userName); if (result == null) { return(placeHolderMessage); } return(result.Shortbio ?? placeHolderMessage); } }
// a user has saved this submission earlier and wishes to unsave it, delete the record private static void UnSaveSubmission(string userWhichSaved, int messageId) { using (var db = new whoaverseEntities()) { var saveTracker = db.Savingtrackers.FirstOrDefault(b => b.MessageId == messageId && b.UserName == userWhichSaved); if (saveTracker == null) { return; } //delete vote history db.Savingtrackers.Remove(saveTracker); db.SaveChanges(); } }
// clear all sessions public static void RemoveAllSessions() { try { using (var db = new whoaverseEntities()) { db.Database.ExecuteSqlCommand("TRUNCATE TABLE SESSIONTRACKER"); db.SaveChanges(); } } catch (Exception) { // } }
// remove a session public static void Remove(string sessionIdToRemove) { try { using (var db = new whoaverseEntities()) { // remove all records for given session id db.Sessiontrackers.RemoveRange(db.Sessiontrackers.Where(s => s.SessionId == sessionIdToRemove)); db.SaveChanges(); } } catch (Exception) { // } }
//a user has either upvoted or downvoted this submission earlier and wishes to reset the vote, delete the record public static void ResetCommentVote(string userWhichVoted, int commentId) { using (whoaverseEntities db = new whoaverseEntities()) { var votingTracker = db.Commentvotingtrackers .Where(b => b.CommentId == commentId && b.UserName == userWhichVoted) .FirstOrDefault(); if (votingTracker != null) { //delete vote history db.Commentvotingtrackers.Remove(votingTracker); db.SaveChanges(); } } }
public static bool IsHostnameBanned(string hostnameToCheck) { using (var db = new whoaverseEntities()) { var bannedHostname = db.Banneddomains.FirstOrDefault(r => r.Hostname.Equals(hostnameToCheck, StringComparison.OrdinalIgnoreCase)); // manual ban for blogspot if (hostnameToCheck.Contains("blogspot")) { return(true); } // look for exact match return(bannedHostname != null); } }
// get total upvotes given by a user public static int UpvotesGiven(string userName) { using (var db = new whoaverseEntities()) { try { var submissionUpvotes = db.Votingtrackers.Count(a => a.UserName == userName && a.VoteStatus == 1); var commentUpvotes = db.Commentvotingtrackers.Count(a => a.UserName == userName && a.VoteStatus == 1); return(submissionUpvotes + commentUpvotes); } catch (Exception) { return(0); } } }
// get session count for given subverse public static int ActiveSessionsForSubverse(string subverseName) { try { using (var db = new whoaverseEntities()) { var result = from sessions in db.Sessiontrackers where sessions.Subverse.Equals(subverseName) select sessions; return(result.Count()); } } catch (Exception) { return(-1); } }
// return a list of subverses user is subscribed to public static List <SubverseDetailsViewModel> UserSubscriptions(string userName) { // get a list of subcribed subverses with details and order by subverse names, ascending using (var db = new whoaverseEntities()) { var subscribedSubverses = from c in db.Subverses join a in db.Subscriptions on c.name equals a.SubverseName where a.Username.Equals(userName) orderby a.SubverseName ascending select new SubverseDetailsViewModel { Name = c.name }; return(subscribedSubverses.ToList()); } }
public async Task <ActionResult> ToggleNightMode() { // save changes using (var db = new whoaverseEntities()) { var userPreferences = db.Userpreferences.Find(User.Identity.Name); if (userPreferences != null) { // modify existing preferences userPreferences.Night_mode = !userPreferences.Night_mode; await db.SaveChangesAsync(); // 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, Enable_only_adult_content = false, Public_subscriptions = false, Topmenu_from_subscriptions = false, Username = User.Identity.Name }; db.Userpreferences.Add(tmpModel); await db.SaveChangesAsync(); // apply theme change Session["UserTheme"] = Utils.User.UserStylePreference(User.Identity.Name); } } Response.StatusCode = 200; return(Json("Toggled Night Mode", JsonRequestBehavior.AllowGet)); }
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 whoaverseEntities()) { //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); } }
// check if a given user has downvoted more submissions than upvoted public static bool IsUserSubmissionVotingMeanie(string userName) { using (var db = new whoaverseEntities()) { // get voting habits var submissionUpvotes = db.Votingtrackers.Count(a => a.UserName == userName && a.VoteStatus == 1); var submissionDownvotes = db.Votingtrackers.Count(a => a.UserName == userName && a.VoteStatus == -1); var totalSubmissionVotes = submissionUpvotes + submissionDownvotes; // downvote ratio var downvotePercentage = (double)submissionDownvotes / totalSubmissionVotes * 100; // upvote ratio var upvotePercentage = (double)submissionUpvotes / totalSubmissionVotes * 100; return(downvotePercentage > upvotePercentage); } }
// check if a given user has downvoted more comments than upvoted public static bool IsUserCommentVotingMeanie(string userName) { using (var db = new whoaverseEntities()) { // get voting habits var commentUpvotes = db.Commentvotingtrackers.Count(a => a.UserName == userName && a.VoteStatus == 1); var commentDownvotes = db.Commentvotingtrackers.Count(a => a.UserName == userName && a.VoteStatus == -1); var totalCommentVotes = commentUpvotes + commentDownvotes; // downvote ratio var downvotePercentage = (double)commentDownvotes / totalCommentVotes * 100; // upvote ratio var upvotePercentage = (double)commentUpvotes / totalCommentVotes * 100; return downvotePercentage > upvotePercentage; } }
// block a subverse public static void BlockSubverse(string userName, string subverse) { using (var db = new whoaverseEntities()) { // unblock if subverse is already blocked if (IsUserBlockingSubverse(userName, subverse)) { var subverseBlock = db.UserBlockedSubverses.FirstOrDefault(n => n.SubverseName.ToLower() == subverse.ToLower() && n.Username == userName); if (subverseBlock != null) db.UserBlockedSubverses.Remove(subverseBlock); db.SaveChanges(); return; } // add a new block var blockedSubverse = new UserBlockedSubverse { Username = userName, SubverseName = subverse }; db.UserBlockedSubverses.Add(blockedSubverse); db.SaveChanges(); } }