// a method to send a private message to a user, invoked by other methods public static bool SendPrivateMessage(string sender, string recipient, string subject, string body) { using (var db = new voatEntities()) { try { var privateMessage = new Privatemessage { Sender = sender, Recipient = recipient, Timestamp = DateTime.Now, Subject = subject, Body = body, Status = true, Markedasunread = true }; db.Privatemessages.Add(privateMessage); db.SaveChanges(); return true; } catch (Exception) { return false; } } }
// returns true if saved, false otherwise public static bool? CheckIfSaved(string userToCheck, int messageId) { using (voatEntities db = new voatEntities()) { var cmd = db.Database.Connection.CreateCommand(); cmd.CommandText = "SELECT COUNT(*) FROM Savingtracker WITH (NOLOCK) WHERE UserName = @UserName AND MessageId = @MessageId"; var param = cmd.CreateParameter(); param.ParameterName = "UserName"; param.DbType = System.Data.DbType.String; param.Value = userToCheck; cmd.Parameters.Add(param); param = cmd.CreateParameter(); param.ParameterName = "MessageId"; param.DbType = System.Data.DbType.String; param.Value = messageId; cmd.Parameters.Add(param); if (cmd.Connection.State != System.Data.ConnectionState.Open) { cmd.Connection.Open(); } int count = (int)cmd.ExecuteScalar(); return count > 0; } //using (var db = new voatEntities()) //{ // return db.Savingtrackers.Where(u => u.UserName == userToCheck && u.MessageId == messageId).AsNoTracking().Any(); //} }
public ApiBadge BadgeInfo(string badgeId) { ApiBadge badgeInfo = CacheHandler.Register<ApiBadge>(String.Format("LegacyApi.ApiBadge.{0}", badgeId), new Func<ApiBadge>(() => { using (voatEntities db = new voatEntities(CONSTANTS.CONNECTION_READONLY)) { var badge = _db.Badges.Find(badgeId); if (badge == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } var resultModel = new ApiBadge { BadgeId = badge.BadgeId, BadgeGraphics = badge.BadgeGraphics, Name = badge.BadgeName, Title = badge.BadgeTitle }; return resultModel; } }), TimeSpan.FromHours(5)); return badgeInfo; }
// a user wishes to save a submission, save it public static void SaveSubmission(int submissionId, string userWhichSaved) { var result = CheckIfSaved(userWhichSaved, submissionId); using (var db = new voatEntities()) { if (result == true) { // Already saved, unsave UnSaveSubmission(userWhichSaved, submissionId); } else { // register save var tmpSavingTracker = new Savingtracker { MessageId = submissionId, UserName = userWhichSaved, Timestamp = DateTime.Now }; db.Savingtrackers.Add(tmpSavingTracker); db.SaveChanges(); } } }
// a user wishes to save a comment, save it public static void SaveComment(int commentId, string userWhichSaved) { var result = CheckIfSavedComment(userWhichSaved, commentId); using (var db = new voatEntities()) { if (result == true) { // Already saved, unsave UnSaveComment(userWhichSaved, commentId); } else { // register save var tmpSavingTracker = new Commentsavingtracker { CommentId = commentId, UserName = userWhichSaved, Timestamp = DateTime.Now }; db.Commentsavingtrackers.Add(tmpSavingTracker); db.SaveChanges(); } } }
// check if a given user does not want to see custom CSS styles public static bool CustomCssDisabledForUser(string userName) { using (var db = new voatEntities()) { var result = db.Userpreferences.Find(userName); return result != null && result.Disable_custom_css; } }
// check if a given user wants to see NSFW (adult) content public static bool AdultContentEnabled(string userName) { using (var db = new voatEntities()) { var result = db.Userpreferences.Find(userName); return result != null && result.Enable_adult_content; } }
// get total number of comment replies for a given user public static int CommentRepliesCount(string userName) { using (var db = new voatEntities()) { var commentReplies = db.Commentreplynotifications.Where(s => s.Recipient.Equals(userName, StringComparison.OrdinalIgnoreCase)); if (!commentReplies.Any()) return 0; return commentReplies.Any() ? commentReplies.Count() : 0; } }
// returns -1:downvoted, 1:upvoted, 0:not voted public static int CheckIfVoted(string userToCheck, int messageId) { using (var db = new voatEntities()) { var checkResult = db.Votingtrackers.Where(u => u.UserName == userToCheck && u.MessageId == messageId) .AsNoTracking() .FirstOrDefault(); int intCheckResult = checkResult != null ? checkResult.VoteStatus.Value : 0; return intCheckResult; } }
public static async Task SendUserMentionNotification(string user, Comment comment) { if (comment != null) { if (!User.UserExists(user)) { return; } try { string recipient = User.OriginalUsername(user); var commentReplyNotification = new Commentreplynotification(); using (var _db = new voatEntities()) { var submission = DataCache.Submission.Retrieve(comment.MessageId); var subverse = DataCache.Subverse.Retrieve(submission.Subverse); commentReplyNotification.CommentId = comment.Id; commentReplyNotification.SubmissionId = comment.MessageId.Value; commentReplyNotification.Recipient = recipient; if (submission.Anonymized || subverse.anonymized_mode) { commentReplyNotification.Sender = (new Random()).Next(10000, 20000).ToString(CultureInfo.InvariantCulture); } else { commentReplyNotification.Sender = comment.Name; } commentReplyNotification.Body = comment.CommentContent; commentReplyNotification.Subverse = subverse.name; commentReplyNotification.Status = true; commentReplyNotification.Timestamp = DateTime.Now; commentReplyNotification.Subject = String.Format("@{0} mentioned you in a comment", comment.Name, submission.Title); _db.Commentreplynotifications.Add(commentReplyNotification); await _db.SaveChangesAsync(); } // get count of unread notifications int unreadNotifications = User.UnreadTotalNotificationsCount(commentReplyNotification.Recipient); // send SignalR realtime notification to recipient var hubContext = GlobalHost.ConnectionManager.GetHubContext<MessagingHub>(); hubContext.Clients.User(commentReplyNotification.Recipient).setNotificationsPending(unreadNotifications); } catch (Exception ex) { throw ex; } } }
public IEnumerable<string> BannedHostnames() { IEnumerable<string> bannedSubs = CacheHandler.Register<IEnumerable<string>>("LegacyApi.BannedHostnames", new Func<IList<string>>(() => { using (voatEntities db = new voatEntities(CONSTANTS.CONNECTION_READONLY)) { var bannedHostnames = db.Banneddomains.OrderBy(s => s.Added_on).ToList(); return bannedHostnames.Select(item => "Hostname: " + item.Hostname + ", reason: " + item.Reason + ", added on: " + item.Added_on + ", added by: " + item.Added_by).ToList(); } }), TimeSpan.FromHours(12)); return bannedSubs; }
// returns -1:downvoted, 1:upvoted, or 0:not voted public static int CheckIfVotedComment(string userToCheck, int commentId) { int intCheckResult = 0; using (var db = new voatEntities()) { var checkResult = db.Commentvotingtrackers.FirstOrDefault(b => b.CommentId == commentId && b.UserName == userToCheck); intCheckResult = checkResult != null ? checkResult.VoteStatus.Value : 0; return intCheckResult; } }
// get comment contribution points for a user public static int CommentKarma(string userName) { string cacheKey = CacheKey(userName, KarmaCacheType.Comment); object cacheData = Cache[cacheKey]; if (cacheData != null) { return (int)cacheData; } int count = 0; using (voatEntities db = new voatEntities()) { var cmd = db.Database.Connection.CreateCommand(); cmd.CommandText = "SELECT ISNULL(SUM(Likes - Dislikes), 0) FROM Comments 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 voatEntities()) //{ // try // { // return db.Comments.Where(c => c.Name.Trim().Equals(userName, StringComparison.OrdinalIgnoreCase)) // .Select(c => c.Likes - c.Dislikes) // .Sum(); // } // catch (Exception) // { // return 0; // } //} }
// 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 (voatEntities db = new voatEntities()) { 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 voatEntities()) //{ // var result = from sessions in db.Sessiontrackers // where sessions.Subverse.Equals(subverseName) // select sessions; // return result.Count(); //} } catch (Exception) { return -1; } }
public static bool IsHostnameBanned(string hostnameToCheck) { using (var db = new voatEntities()) { 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; } }
// 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 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); } }
public static Subverse Retrieve(string subverse) { if (!String.IsNullOrEmpty(subverse)) { string cacheKey = CacheHandler.Keys.SubverseInfo(subverse); Subverse sub = (Subverse)CacheHandler.Retrieve(cacheKey); if (sub == null) { sub = (Subverse)CacheHandler.Register(cacheKey, new Func<object>(() => { using (voatEntities db = new voatEntities()) { return db.Subverses.Where(x => x.name == subverse).FirstOrDefault(); } }), TimeSpan.FromMinutes(5), 50); } return sub; } return null; }
// block a subverse public static void BlockSubverse(string userName, string subverse) { using (var db = new voatEntities()) { // 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(); } }
public static int CommentCount(int submissionID) { int count = 0; string cacheKey = String.Format("comment.count.{0}", submissionID).ToString(); object data = CacheHandler.Retrieve(cacheKey); if (data == null) { data = CacheHandler.Register(cacheKey, new Func<object>(() => { using (voatEntities db = new voatEntities()) { var cmd = db.Database.Connection.CreateCommand(); cmd.CommandText = "SELECT COUNT(*) FROM Comments WITH (NOLOCK) WHERE MessageID = @MessageID AND Name != 'deleted'"; var param = cmd.CreateParameter(); param.ParameterName = "MessageID"; param.DbType = System.Data.DbType.Int32; param.Value = submissionID; cmd.Parameters.Add(param); if (cmd.Connection.State != System.Data.ConnectionState.Open) { cmd.Connection.Open(); } return (int)cmd.ExecuteScalar(); } }), TimeSpan.FromMinutes(2), 1); count = (int)data; } else { count = (int)data; } return count; }
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); }
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"); }
public ActionResult UserPreferences() { try { using (var db = new voatEntities()) { var userPreferences = db.Userpreferences.Find(User.Identity.Name); if (userPreferences != null) { // load existing preferences and return to view engine var tmpModel = new UserPreferencesViewModel { Disable_custom_css = userPreferences.Disable_custom_css, Night_mode = userPreferences.Night_mode, OpenLinksInNewTab = userPreferences.Clicking_mode, Enable_adult_content = userPreferences.Enable_adult_content, Public_subscriptions = userPreferences.Public_subscriptions, Topmenu_from_subscriptions = userPreferences.Topmenu_from_subscriptions }; return PartialView("_UserPreferences", tmpModel); } else { var tmpModel = new UserPreferencesViewModel(); return PartialView("_UserPreferences", tmpModel); } } } catch (Exception) { return new EmptyResult(); } }
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"); }
public ActionResult UserPreferencesAbout() { try { using (var db = new voatEntities()) { var userPreferences = db.Userpreferences.Find(User.Identity.Name); if (userPreferences != null) { // load existing preferences and return to view engine var tmpModel = new UserAboutViewModel() { Shortbio = userPreferences.Shortbio, Avatar = userPreferences.Avatar }; return PartialView("_UserPreferencesAbout", tmpModel); } else { var tmpModel = new UserAboutViewModel(); return PartialView("_UserPreferencesAbout", tmpModel); } } } catch (Exception) { return new EmptyResult(); } }
// GET: show a subverse index public ActionResult SubverseIndex(int? page, string subversetoshow) { const string cookieName = "NSFWEnabled"; int pageSize = 25; int pageNumber = (page ?? 0); if (pageNumber < 0) { return View("~/Views/Errors/Error_404.cshtml"); } if (subversetoshow == null) { return View("~/Views/Errors/Subversenotfound.cshtml"); } // register a new session for this subverse try { var currentSubverse = (string)RouteData.Values["subversetoshow"]; // register a new session for this subverse string clientIpAddress = String.Empty; if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null) { clientIpAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; } else if (Request.UserHostAddress.Length != 0) { clientIpAddress = Request.UserHostAddress; } string ipHash = IpHash.CreateHash(clientIpAddress); SessionTracker.Add(currentSubverse, ipHash); ViewBag.OnlineUsers = SessionTracker.ActiveSessionsForSubverse(currentSubverse); } catch (Exception) { ViewBag.OnlineUsers = -1; } try { if (!subversetoshow.Equals("all", StringComparison.OrdinalIgnoreCase)) { // check if subverse exists, if not, send to a page not found error //Can't use cached, view using to query db var subverse = _db.Subverses.Find(subversetoshow); if (subverse == null) { ViewBag.SelectedSubverse = "404"; return View("~/Views/Errors/Subversenotfound.cshtml"); } //HACK: Disable subverse if (subverse.admin_disabled.HasValue && subverse.admin_disabled.Value) { ViewBag.Subverse = subverse.name; return View("~/Views/Errors/SubverseDisabled.cshtml"); } ViewBag.SelectedSubverse = subverse.name; ViewBag.Title = subverse.description; //IAmAGate: Perf mods for caching string cacheKey = String.Format("subverse.{0}.page.{1}.sort.{2}", subversetoshow, pageNumber, "rank").ToLower(); Tuple<IList<Message>, int> cacheData = (Tuple<IList<Message>, int>)CacheHandler.Retrieve(cacheKey); if (cacheData == null) { var getDataFunc = new Func<object>(() => { using (voatEntities db = new voatEntities(CONSTANTS.CONNECTION_LIVE)) { var x = SubmissionsFromASubverseByRank(subversetoshow, db); int count = x.Count(); List<Message> content = x.Skip(pageNumber * pageSize).Take(pageSize).ToList(); return new Tuple<IList<Message>, int>(content, count); } }); cacheData = (Tuple<IList<Message>, int>)CacheHandler.Register(cacheKey, getDataFunc, TimeSpan.FromSeconds(subverseCacheTimeInSeconds), (pageNumber < 3 ? 10 : 1)); } ////IAmAGate: Perf mods for caching //string cacheKey = String.Format("subverse.{0}.page.{1}.sort.{2}", subversetoshow, pageNumber, "rank").ToLower(); //Tuple<IList<Message>, int> cacheData = (Tuple<IList<Message>, int>)System.Web.HttpContext.Current.Cache[cacheKey]; //if (cacheData == null) //{ // var x = SubmissionsFromASubverseByRank(subversetoshow); // int count = x.Count(); // List<Message> content = x.Skip(pageNumber * pageSize).Take(pageSize).ToList(); // cacheData = new Tuple<IList<Message>, int>(content, count); // System.Web.HttpContext.Current.Cache.Insert(cacheKey, cacheData, null, DateTime.Now.AddSeconds(subverseCacheTimeInSeconds), System.Web.Caching.Cache.NoSlidingExpiration); //} PaginatedList<Message> paginatedSubmissions = new PaginatedList<Message>(cacheData.Item1, pageNumber, pageSize, cacheData.Item2); //var paginatedSubmissions = new PaginatedList<Message>(SubmissionsFromASubverseByRank(subversetoshow), page ?? 0, pageSize); // check if subverse is rated adult, show a NSFW warning page before entering if (!subverse.rated_adult) return View(paginatedSubmissions); // check if user wants to see NSFW content by reading user preference if (User.Identity.IsAuthenticated) { if (Utils.User.AdultContentEnabled(User.Identity.Name)) { return View(paginatedSubmissions); } // display a view explaining that account preference is set to NO NSFW and why this subverse can not be shown return RedirectToAction("AdultContentFiltered", "Subverses", new { destination = subverse.name }); } // check if user wants to see NSFW content by reading NSFW cookie if (!ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains(cookieName)) { return RedirectToAction("AdultContentWarning", "Subverses", new { destination = subverse.name, nsfwok = false }); } return View(paginatedSubmissions); } // selected subverse is ALL, show submissions from all subverses, sorted by rank ViewBag.SelectedSubverse = "all"; ViewBag.Title = "all subverses"; PaginatedList<Message> paginatedSfwSubmissions; // check if user wants to see NSFW content by reading user preference if (User.Identity.IsAuthenticated) { if (Utils.User.AdultContentEnabled(User.Identity.Name)) { var paginatedSubmissionsFromAllSubverses = new PaginatedList<Message>(SubmissionsFromAllSubversesByRank(), page ?? 0, pageSize); return View(paginatedSubmissionsFromAllSubverses); } // return only sfw submissions paginatedSfwSubmissions = new PaginatedList<Message>(SfwSubmissionsFromAllSubversesByRank(_db), page ?? 0, pageSize); return View(paginatedSfwSubmissions); } // check if user wants to see NSFW content by reading NSFW cookie if (ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains(cookieName)) { var paginatedSubmissionsFromAllSubverses = new PaginatedList<Message>(SubmissionsFromAllSubversesByRank(), page ?? 0, pageSize); return View(paginatedSubmissionsFromAllSubverses); } //NEW LOGIC //IAmAGate: Perf mods for caching string cacheKeyAll = String.Format("subverse.{0}.page.{1}.sort.{2}.sfw", "all", pageNumber, "rank").ToLower(); Tuple<IList<Message>, int> cacheDataAll = (Tuple<IList<Message>, int>)CacheHandler.Retrieve(cacheKeyAll); if (cacheDataAll == null) { var getDataFunc = new Func<object>(() => { using (voatEntities db = new voatEntities(CONSTANTS.CONNECTION_LIVE)) { var x = SfwSubmissionsFromAllSubversesByRank(db); int count = 50000; List<Message> content = x.Skip(pageNumber * pageSize).Take(pageSize).ToList(); return new Tuple<IList<Message>, int>(content, count); } }); cacheDataAll = (Tuple<IList<Message>, int>)CacheHandler.Register(cacheKeyAll, getDataFunc, TimeSpan.FromSeconds(subverseCacheTimeInSeconds), (pageNumber > 2) ? 5 : 0); } paginatedSfwSubmissions = new PaginatedList<Message>(cacheDataAll.Item1, pageNumber, pageSize, cacheDataAll.Item2); return View(paginatedSfwSubmissions); //OLD LOGIC // return only sfw submissions //paginatedSfwSubmissions = new PaginatedList<Message>(SfwSubmissionsFromAllSubversesByRank(), page ?? 0, pageSize); //return View(paginatedSfwSubmissions); } catch (Exception) { return View("~/Views/Errors/DbNotResponding.cshtml"); } }
private IQueryable<Message> SubmissionsFromASubverseByRank(string subverseName, voatEntities _db = null) { if (_db == null) { _db = this._db; } var subverseStickie = _db.Stickiedsubmissions.FirstOrDefault(ss => ss.Subverse.name.Equals(subverseName, StringComparison.OrdinalIgnoreCase)); IQueryable<Message> submissionsFromASubverseByRank = (from message in _db.Messages join subverse in _db.Subverses on message.Subverse equals subverse.name where message.Name != "deleted" && message.Subverse == subverseName where !(from bu in _db.Bannedusers select bu.Username).Contains(message.Name) select message).OrderByDescending(s => s.Rank).ThenByDescending(s => s.Date).AsNoTracking(); if (subverseStickie != null) { return submissionsFromASubverseByRank.Where(s => s.Id != subverseStickie.Submission_id); } return submissionsFromASubverseByRank; }
private IQueryable<Message> SubmissionsFromAllSubversesByDate(voatEntities _db = null) { if (_db == null) { _db = this._db; } string userName = ""; if (User != null) { userName = User.Identity.Name; } IQueryable<Message> submissionsFromAllSubversesByDate = (from message in _db.Messages join subverse in _db.Subverses on message.Subverse equals subverse.name where !message.IsArchived && message.Name != "deleted" && subverse.private_subverse != true && subverse.forced_private != true && subverse.minimumdownvoteccp == 0 where !(from bu in _db.Bannedusers select bu.Username).Contains(message.Name) where !subverse.admin_disabled.Value where !(from ubs in _db.UserBlockedSubverses where ubs.SubverseName.Equals(subverse.name) select ubs.Username).Contains(userName) select message).OrderByDescending(s => s.Date).AsNoTracking(); return submissionsFromAllSubversesByDate; }
private IQueryable<Message> SfwSubmissionsFromAllSubversesByViews24Hours(voatEntities _db) { if (_db == null) { _db = this._db; } var startDate = DateTime.Now.Add(new TimeSpan(0, -24, 0, 0, 0)); IQueryable<Message> sfwSubmissionsFromAllSubversesByViews24Hours = (from message in _db.Messages join subverse in _db.Subverses on message.Subverse equals subverse.name where !message.IsArchived && message.Name != "deleted" && subverse.private_subverse != true && subverse.forced_private != true && subverse.rated_adult == false && message.Date >= startDate && message.Date <= DateTime.Now where !(from bu in _db.Bannedusers select bu.Username).Contains(message.Name) where !subverse.admin_disabled.Value where !(from ubs in _db.UserBlockedSubverses where ubs.SubverseName.Equals(subverse.name) select ubs.Username).Contains(User.Identity.Name) select message).OrderByDescending(s => s.Views).DistinctBy(m => m.Subverse).Take(5).AsQueryable().AsNoTracking(); return sfwSubmissionsFromAllSubversesByViews24Hours; }
public ActionResult TopViewedSubmissions24Hours() { //var submissions = var cacheData = CacheHandler.Register("TopViewedSubmissions24Hours", new Func<object>(() => { using (voatEntities db = new voatEntities(CONSTANTS.CONNECTION_READONLY)){ return SfwSubmissionsFromAllSubversesByViews24Hours(db).ToList(); } }), TimeSpan.FromMinutes(60), 5); return PartialView("_MostViewedSubmissions", cacheData); }