コード例 #1
0
ファイル: WebApiController.cs プロジェクト: nishithleo/voat
        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;
        }
コード例 #2
0
 public void TestLogDurationWithMinimum()
 {
     if (log == null)
     {
         Assert.Inconclusive("Log4Net Logger disabled");
     }
     else
     {
         var activityID = Guid.NewGuid();
         using (var durationLog = new DurationLogger(log,
                                                     new LogInformation()
         {
             ActivityID = activityID,
             Type = LogType.Debug,
             Category = "Duration",
             UserName = "",
             Message = $"{this.GetType().Name}"
         },
                                                     TimeSpan.FromSeconds(10)))
         {
             System.Threading.Thread.Sleep(1000);
         }
         using (var db = new voatEntities())
         {
             var entry = db.EventLogs.FirstOrDefault(x => x.ActivityID == activityID.ToString().ToUpper());
             Assert.IsNull(entry, "Should not have log entry with specified minimum");
         }
     }
 }
コード例 #3
0
ファイル: SavingComments.cs プロジェクト: nevergofull/A
        // 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 CommentSaveTracker
                    {
                        CommentID    = commentId,
                        UserName     = userWhichSaved,
                        CreationDate = Repository.CurrentDate
                    };
                    db.CommentSaveTrackers.Add(tmpSavingTracker);
                    db.SaveChanges();
                }
            }
        }
コード例 #4
0
        public static IList <Submission> GetGuestFrontPage(int pageSize, int pageNumber)
        {
            //IAmAGate: Perf mods for caching
            string             cacheKey  = String.Format("front.guest.page.{0}.sort.rank", pageNumber);
            IList <Submission> cacheData = CacheHandler.Retrieve <IList <Submission> >(cacheKey);

            if (cacheData == null)
            {
                var getDataFunc = new Func <IList <Submission> >(() =>
                {
                    using (voatEntities db = new voatEntities(CONSTANTS.CONNECTION_READONLY))
                    {
                        // get only submissions from default subverses not older than 24 hours, order by relative rank
                        var startDate = DateTime.Now.Add(new TimeSpan(0, -24, 0, 0, 0));

                        IQueryable <Submission> submissions = (from message in db.Submissions.AsNoTracking()
                                                               where !message.IsArchived && !message.IsDeleted && message.UpCount >= 3 && message.CreationDate >= startDate && message.CreationDate <= DateTime.Now
                                                               where !(from bu in db.BannedUsers select bu.UserName).Contains(message.UserName)
                                                               join defaultsubverse in db.DefaultSubverses on message.Subverse equals defaultsubverse.Subverse
                                                               select message).OrderByDescending(s => s.RelativeRank);

                        return(submissions.Where(s => s.StickiedSubmission.SubmissionID != s.ID).Skip(pageNumber * pageSize).Take(pageSize).ToList());
                    }
                });
                //Now with it's own locking!
                cacheData = CacheHandler.Register(cacheKey, getDataFunc, TimeSpan.FromMinutes(CONSTANTS.DEFAULT_GUEST_PAGE_CACHE_MINUTES), (pageNumber < 3 ? 0 : 3));
            }

            return(cacheData);
        }
コード例 #5
0
 public void TestLogException()
 {
     if (log == null)
     {
         Assert.Inconclusive("Log4Net Logger disabled");
     }
     else
     {
         try
         {
             //Open the worm hole to narnia
             int wormhole             = 42;
             int idontcarewhathappens = 0;
             int narnia = wormhole / idontcarewhathappens;
         }
         catch (Exception ex)
         {
             var activityID = Guid.NewGuid();
             log.Log(ex, (Guid?)activityID);
             using (var db = new voatEntities())
             {
                 var entry = db.EventLogs.FirstOrDefault(x => x.ActivityID == activityID.ToString().ToUpper());
                 Assert.IsNotNull(entry, "If this isn't here, perhaps the narnia wormhole is open?");
             }
         }
     }
 }
コード例 #6
0
        public void TestLogEntry()
        {
            if (log == null)
            {
                Assert.Inconclusive("Log4Net Logger disabled");
            }
            else
            {
                LogInformation info = new LogInformation();
                info.Type       = LogType.Information;
                info.Origin     = "UnitTests";
                info.Category   = "Unit Test";
                info.Message    = "Test Message";
                info.Data       = new { url = "http://www.com" };
                info.ActivityID = Guid.NewGuid();

                log.Log(info);

                using (var db = new voatEntities())
                {
                    var entry = db.EventLogs.FirstOrDefault(x => x.ActivityID == info.ActivityID.ToString());
                    Assert.IsNotNull(entry, "Crickie! Where is the log data at!?");
                    Assert.AreEqual(info.Type.ToString(), entry.Type);
                    Assert.AreEqual(info.Origin, entry.Origin);
                    Assert.AreEqual(info.Category, entry.Category);
                    Assert.AreEqual(info.Message, entry.Message);
                    Assert.AreEqual(JsonConvert.SerializeObject(new { url = "http://www.com" }), entry.Data);
                    Assert.AreEqual(info.ActivityID.ToString().ToUpper(), entry.ActivityID);
                }
            }
        }
コード例 #7
0
ファイル: UserHelper.cs プロジェクト: rnand/voat
 // 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.DisableCSS;
     }
 }
コード例 #8
0
ファイル: UserHelper.cs プロジェクト: rnand/voat
 // 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.EnableAdultContent;
     }
 }
コード例 #9
0
ファイル: UserHelper.cs プロジェクト: rnand/voat
 // 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;
     }
 }
コード例 #10
0
ファイル: SessionTracker.cs プロジェクト: CuteThalia/voat
        // check if session exists
        public static bool SessionExists(string sessionId, string subverseName)
        {
            using (var db = new voatEntities())
            {
                var result = from sessions in db.SessionTrackers
                             where sessions.Subverse.Equals(subverseName) && sessions.SessionID.Equals(sessionId)
                             select sessions;

                return result.Any();
            }
        }
コード例 #11
0
ファイル: WebApiController.cs プロジェクト: nishithleo/voat
 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;
 }
コード例 #12
0
ファイル: SessionTracker.cs プロジェクト: Rumel/voat
        // 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;
            }
        }
コード例 #13
0
ファイル: SessionTracker.cs プロジェクト: CuteThalia/voat
 // clear all sessions
 public static void RemoveAllSessions()
 {
     try
     {
         using (var db = new voatEntities())
         {
             db.Database.ExecuteSqlCommand("TRUNCATE TABLE SESSIONTRACKER");
             db.SaveChanges();
         }
     }
     catch (Exception)
     {
         //
     }
 }
コード例 #14
0
ファイル: WebApiController.cs プロジェクト: CuteThalia/voat
        public IEnumerable<string> DefaultSubverses()
        {

            IEnumerable<string> defaultSubs = CacheHandler.Register<IEnumerable<string>>("LegacyApi.DefaultSubverses",
               new Func<IList<string>>(() =>
               {
                   using (voatEntities db = new voatEntities(CONSTANTS.CONNECTION_READONLY))
                   {
                       var listOfDefaultSubverses = db.DefaultSubverses.OrderBy(s => s.Order).ToList();
                       return listOfDefaultSubverses.Select(item => item.Subverse).ToList();
                   }
               }), TimeSpan.FromHours(12));
            return defaultSubs;

        }
コード例 #15
0
ファイル: SessionTracker.cs プロジェクト: CuteThalia/voat
 // remove a session
 public static void Remove(string sessionIdToRemove)
 {
     try
     {
         using (var db = new voatEntities())
         {
             // remove all records for given session id
             db.SessionTrackers.RemoveRange(db.SessionTrackers.Where(s => s.SessionID == sessionIdToRemove));
             db.SaveChanges();
         }
     }
     catch (Exception)
     {
         //
     }
 }
コード例 #16
0
ファイル: SessionTracker.cs プロジェクト: CuteThalia/voat
        // add a new session
        public static void Add(string subverseName, string sessionId)
        {
            try
            {
                if (SessionExists(sessionId, subverseName)) return;
                using (var db = new voatEntities())
                {
                    var newSession = new SessionTracker { SessionID = sessionId, Subverse = subverseName, CreationDate = DateTime.Now };

                    db.SessionTrackers.Add(newSession);
                    db.SaveChanges();

                }
            }
            catch (Exception)
            {
                //
            }
        }
コード例 #17
0
ファイル: UserHelper.cs プロジェクト: rnand/voat
        // 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.Subverse.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, Subverse = subverse };
                db.UserBlockedSubverses.Add(blockedSubverse);
                db.SaveChanges();
            }
        }
コード例 #18
0
        private ActionResult HandleSortedSubverse(int? page, string subversetoshow, string sortingmode, string daterange)
        {
            ViewBag.SortingMode = sortingmode;
            ViewBag.SelectedSubverse = subversetoshow;
            const string cookieName = "NSFWEnabled";
            DateTime startDate = DateTimeUtility.DateRangeToDateTime(daterange);

            if (!sortingmode.Equals("new") && !sortingmode.Equals("top")) return RedirectToAction("Index", "Home");

            const int pageSize = 25;
            int pageNumber = (page ?? 0);
            if (pageNumber < 0)
            {
                return View("~/Views/Errors/Error_404.cshtml");
            }

            // check if subverse exists, if not, send to a page not found error
            var subverse = DataCache.Subverse.Retrieve(subversetoshow);
            if (subverse == null) return View("~/Views/Errors/Subversenotfound.cshtml");

            ViewBag.Title = subverse.description;

            //HACK: Disable subverse
            if (subverse.admin_disabled.HasValue && subverse.admin_disabled.Value)
            {
                ViewBag.Subverse = subverse.name;
                return View("~/Views/Errors/SubverseDisabled.cshtml");
            }

            // subverse is adult rated, check if user wants to see NSFW content
            PaginatedList<Message> paginatedSubmissionsByRank;

            if (subverse.rated_adult)
            {
                if (User.Identity.IsAuthenticated)
                {
                    // check if user wants to see NSFW content by reading user preference
                    if (Voat.Utilities.UserHelper.AdultContentEnabled(User.Identity.Name))
                    {
                        if (sortingmode.Equals("new"))
                        {

                            var paginatedSubmissionsByDate = new PaginatedList<Message>(SubmissionsFromASubverseByDate(subversetoshow), page ?? 0, pageSize);
                            return View("SubverseIndex", paginatedSubmissionsByDate);
                        }

                        if (sortingmode.Equals("top"))
                        {
                            var paginatedSubmissionsByDate = new PaginatedList<Message>(SubmissionsFromASubverseByTop(subversetoshow, startDate), page ?? 0, pageSize);
                            return View("SubverseIndex", paginatedSubmissionsByDate);
                        }

                        // default sorting mode by rank
                        paginatedSubmissionsByRank = new PaginatedList<Message>(SubmissionsFromASubverseByRank(subversetoshow, _db), page ?? 0, pageSize);
                        return View("SubverseIndex", paginatedSubmissionsByRank);
                    }
                    return RedirectToAction("AdultContentFiltered", "Subverses", new { destination = subverse.name });
                }

                // check if user wants to see NSFW content by reading NSFW cookie
                if (!HttpContext.Request.Cookies.AllKeys.Contains(cookieName))
                {
                    return RedirectToAction("AdultContentWarning", "Subverses",
                        new { destination = subverse.name, nsfwok = false });
                }

                if (sortingmode.Equals("new"))
                {

                    var paginatedSubmissionsByDate = new PaginatedList<Message>(SubmissionsFromASubverseByDate(subversetoshow), page ?? 0, pageSize);
                    return View("SubverseIndex", paginatedSubmissionsByDate);
                }

                if (sortingmode.Equals("top"))
                {
                    var paginatedSubmissionsByDate = new PaginatedList<Message>(SubmissionsFromASubverseByTop(subversetoshow, startDate), page ?? 0, pageSize);
                    return View("SubverseIndex", paginatedSubmissionsByDate);
                }

                // default sorting mode by rank
                paginatedSubmissionsByRank = new PaginatedList<Message>(SubmissionsFromASubverseByRank(subversetoshow), page ?? 0, pageSize);
                return View("SubverseIndex", paginatedSubmissionsByRank);
            }

            // subverse is safe for work
            if (sortingmode.Equals("new"))
            {


                //IAmAGate: Perf mods for caching
                string cacheKey = String.Format("subverse.{0}.page.{1}.sort.{2}", subversetoshow, pageNumber, sortingmode).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 = SubmissionsFromASubverseByDate(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, sortingmode).ToLower();
                //Tuple<IList<Message>, int> cacheData = (Tuple<IList<Message>, int>)System.Web.HttpContext.Current.Cache[cacheKey];

                //if (cacheData == null)
                //{
                //    var x = SubmissionsFromASubverseByDate(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> paginatedSubmissionsByDate = new PaginatedList<Message>(cacheData.Item1, pageNumber, pageSize, cacheData.Item2);

                return View("SubverseIndex", paginatedSubmissionsByDate);

                //var paginatedSubmissionsByDate = new PaginatedList<Message>(SubmissionsFromASubverseByDate(subversetoshow), page ?? 0, pageSize);
                //return View("SubverseIndex", paginatedSubmissionsByDate);
            }

            if (sortingmode.Equals("top"))
            {

                var paginatedSubmissionsByDate = new PaginatedList<Message>(SubmissionsFromASubverseByTop(subversetoshow, startDate), page ?? 0, pageSize);
                return View("SubverseIndex", paginatedSubmissionsByDate);
            }

            // default sorting mode by rank
            paginatedSubmissionsByRank = new PaginatedList<Message>(SubmissionsFromASubverseByRank(subversetoshow), page ?? 0, pageSize);
            return View("SubverseIndex", paginatedSubmissionsByRank);
        }
コード例 #19
0
ファイル: HomeController.cs プロジェクト: Tsalsb/voat
        // GET: /new
        public ActionResult @New(int? page, string sortingmode)
        {
            // sortingmode: new, contraversial, hot, etc
            ViewBag.SortingMode = sortingmode;

            if (!sortingmode.Equals("new")) return RedirectToAction("Index", "Home");

            const int pageSize = 25;
            int pageNumber = (page ?? 0);

            if (pageNumber < 0)
            {
                return View("~/Views/Errors/Error_404.cshtml");
            }

            // setup a cookie to find first time visitors and display welcome banner
            const string cookieName = "NotFirstTime";
            if (ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains(cookieName))
            {
                // not a first time visitor
                ViewBag.FirstTimeVisitor = false;
            }
            else
            {
                // add a cookie for first time visitors
                HttpCookie hc = new HttpCookie("NotFirstTime", "1");
                hc.Expires = DateTime.Now.AddYears(1);
                System.Web.HttpContext.Current.Response.Cookies.Add(hc);

                ViewBag.FirstTimeVisitor = true;
            }

            try
            {
                // show only submissions from subverses that user is subscribed to if user is logged in
                // also do a check so that user actually has subscriptions
                if (User.Identity.IsAuthenticated && UserHelper.SubscriptionCount(User.Identity.Name) > 0)
                {

                    //IAmAGate: Perf mods for caching
                    int pagesToTake = 2;
                    int subset = pageNumber / pagesToTake;
                    string cacheKey = String.Format("front.{0}.block.{1}.sort.new", User.Identity.Name, subset);
                    object cacheData = CacheHandler.Retrieve(cacheKey);

                    if (cacheData == null)
                    {
                        int recordsToTake = 25 * pagesToTake; //pages worth

                        var getDataFunc = new Func<object>(() =>
                        {
                            using (voatEntities db = new voatEntities(CONSTANTS.CONNECTION_LIVE))
                            {
                                var blockedSubverses = db.UserBlockedSubverses.Where(x => x.UserName.Equals(User.Identity.Name)).Select(x => x.Subverse);
                                IQueryable<Submission> submissions = (from m in db.Submissions
                                                                   join s in db.SubverseSubscriptions on m.Subverse equals s.Subverse
                                                                   where !m.IsArchived && !m.IsDeleted && s.UserName == User.Identity.Name
                                                                   where !(from bu in db.BannedUsers select bu.UserName).Contains(m.UserName)
                                                                   select m).OrderByDescending(s => s.CreationDate);
                                return submissions.Where(x => !blockedSubverses.Contains(x.Subverse)).Skip(subset * recordsToTake).Take(recordsToTake).ToList();
                            }
                        });
                        //now with new and improved locking
                        cacheData = CacheHandler.Register(cacheKey, getDataFunc, TimeSpan.FromMinutes(5), 1);
                    }
                    var set = ((IList<Submission>)cacheData).Skip((pageNumber - (subset * pagesToTake)) * pageSize).Take(pageSize).ToList();

                    PaginatedList<Submission> paginatedSubmissions = new PaginatedList<Submission>(set, pageNumber, pageSize, 50000);
                    return View("Index", paginatedSubmissions);
                }
                else
                {

                    //IAmAGate: Perf mods for caching
                    string cacheKey = String.Format("front.guest.page.{0}.sort.new", pageNumber);
                    object cacheData = CacheHandler.Retrieve(cacheKey);

                    if (cacheData == null)
                    {
                        var getDataFunc = new Func<object>(() =>
                        {
                            using (voatEntities db = new voatEntities(CONSTANTS.CONNECTION_READONLY))
                            {
                                // get only submissions from default subverses, order by rank
                                IQueryable<Submission> submissions = (from message in db.Submissions
                                                                      where !message.IsArchived && !message.IsDeleted
                                                                   where !(from bu in db.BannedUsers select bu.UserName).Contains(message.UserName)
                                                                   join defaultsubverse in db.DefaultSubverses on message.Subverse equals defaultsubverse.Subverse
                                                                   select message).OrderByDescending(s => s.CreationDate);
                                return submissions.Where(s => s.StickiedSubmission.SubmissionID != s.ID).Skip(pageNumber * pageSize).Take(pageSize).ToList();
                            }
                        });

                        //now with new and improved locking
                        cacheData = CacheHandler.Register(cacheKey, getDataFunc, TimeSpan.FromMinutes(CONSTANTS.DEFAULT_GUEST_PAGE_CACHE_MINUTES), (pageNumber < 3 ? 0 : 3));
                    }
                    PaginatedList<Submission> paginatedSubmissions = new PaginatedList<Submission>((IList<Submission>)cacheData, pageNumber, pageSize, 50000);

                    //// get only submissions from default subverses, sort by date
                    //IQueryable<Message> submissions = (from submission in _db.Messages
                    //                              where submission.Name != "deleted"
                    //                              where !(from bu in _db.Bannedusers select bu.Username).Contains(submission.Name)
                    //                              join defaultsubverse in _db.Defaultsubverses on submission.Subverse equals defaultsubverse.name
                    //                              select submission).OrderByDescending(s => s.Date);

                    //PaginatedList<Message> paginatedSubmissions = new PaginatedList<Message>(submissions, page ?? 0, pageSize);

                    return View("Index", paginatedSubmissions);
                }
            }
            catch (Exception)
            {
                return View("~/Views/Errors/DbNotResponding.cshtml");
            }
        }
コード例 #20
0
ファイル: HomeController.cs プロジェクト: Tsalsb/voat
        // GET: /
        public ActionResult Index(int? page)
        {
            ViewBag.SelectedSubverse = "frontpage";

            const int pageSize = 25;
            int pageNumber = (page ?? 0);

            if (pageNumber < 0)
            {
                return View("~/Views/Errors/Error_404.cshtml");
            }

            try
            {
                // show only submissions from subverses that user is subscribed to if user is logged in
                // also do a check so that user actually has subscriptions
                if (User.Identity.IsAuthenticated && UserHelper.SubscriptionCount(User.Identity.Name) > 0)
                {
                    //IAmAGate: Perf mods for caching
                    int pagesToTake = 2;
                    int subset = pageNumber / pagesToTake;
                    string cacheKey = String.Format("front.{0}.block.{1}.sort.rank", User.Identity.Name, subset);
                    object cacheData = CacheHandler.Retrieve(cacheKey);

                    if (cacheData == null)
                    {
                        int recordsToTake = pageSize * pagesToTake; //4 pages worth

                        var getDataFunc = new Func<object>(() =>
                        {
                            using (voatEntities db = new voatEntities(CONSTANTS.CONNECTION_LIVE))
                            {

                                var blockedSubverses = db.UserBlockedSubverses.Where(x => x.UserName.Equals(User.Identity.Name)).Select(x => x.Subverse);

                                IQueryable<Submission> submissions = (from m in db.Submissions.Include("Subverse").AsNoTracking()
                                                                   join s in db.SubverseSubscriptions on m.Subverse equals s.Subverse
                                                                   where !m.IsArchived && !m.IsDeleted && s.UserName == User.Identity.Name
                                                                   where !(from bu in db.BannedUsers select bu.UserName).Contains(m.UserName)
                                                                   select m).OrderByDescending(s => s.Rank);

                                var submissionsWithoutStickies = submissions.Where(s => s.StickiedSubmission.SubmissionID != s.ID);

                                return submissionsWithoutStickies.Where(x => !blockedSubverses.Contains(x.Subverse)).Skip(subset * recordsToTake).Take(recordsToTake).ToList();

                            }

                        });
                        //now with new and improved locking
                        cacheData = CacheHandler.Register(cacheKey, getDataFunc, TimeSpan.FromMinutes(5));
                    }
                    var set = ((IList<Submission>)cacheData).Skip((pageNumber - (subset * pagesToTake)) * pageSize).Take(pageSize).ToList();
                    PaginatedList<Submission> paginatedSubmissions = new PaginatedList<Submission>(set, pageNumber, pageSize, 50000);

                    return View(paginatedSubmissions);
                }
                else
                {
                    //IAmAGate: Perf mods for caching
                    string cacheKey = String.Format("front.guest.page.{0}.sort.rank", pageNumber);
                    object cacheData = CacheHandler.Retrieve(cacheKey);
                    if (cacheData == null)
                    {

                        var getDataFunc = new Func<object>(() =>
                        {
                            using (voatEntities db = new voatEntities(CONSTANTS.CONNECTION_READONLY))
                            {

                                // get only submissions from default subverses, order by rank
                                IQueryable<Submission> submissions = (from message in db.Submissions.AsNoTracking()
                                                                   where !message.IsArchived && !message.IsDeleted
                                                                   where !(from bu in db.BannedUsers select bu.UserName).Contains(message.UserName)
                                                                   join defaultsubverse in db.DefaultSubverses on message.Subverse equals defaultsubverse.Subverse
                                                                   select message).OrderByDescending(s => s.Rank);

                                return submissions.Where(s => s.StickiedSubmission.SubmissionID != s.ID).Skip(pageNumber * pageSize).Take(pageSize).ToList();

                            }
                        });
                        //Now with it's own locking!
                        cacheData = CacheHandler.Register(cacheKey, getDataFunc, TimeSpan.FromMinutes(CONSTANTS.DEFAULT_GUEST_PAGE_CACHE_MINUTES), (pageNumber < 3 ? 0 : 3));
                    }

                    PaginatedList<Submission> paginatedSubmissions = new PaginatedList<Submission>((IList<Submission>)cacheData, pageNumber, pageSize, 50000);

                    return View(paginatedSubmissions);
                }
            }
            catch (Exception)
            {
                return View("~/Views/Errors/DbNotResponding.cshtml");
            }
        }
コード例 #21
0
ファイル: UserHelper.cs プロジェクト: rnand/voat
        // return a list of subverses user is subscribed to
        public static List<string> UserSubscriptions(string userName)
        {
            // get a list of subcribed subverses with details and order by subverse names, ascending
            using (var db = new voatEntities())
            {
                var subscribedSubverses = from c in db.Subverses
                                          join a in db.SubverseSubscriptions
                                          on c.Name equals a.Subverse
                                          where a.UserName.Equals(userName)
                                          orderby a.Subverse ascending
                                          select c.Name;

                return subscribedSubverses.ToList();
            }
        }
コード例 #22
0
ファイル: UserHelper.cs プロジェクト: rnand/voat
        // check which theme style user selected
        public static string UserStylePreference(string userName)
        {
            string theme = "light";

            var tc = System.Web.HttpContext.Current.Request.Cookies["theme"];
            if (tc != null && !String.IsNullOrEmpty(tc.Value))
            {
                theme = tc.Value;
            }
            else
            {
                if (!String.IsNullOrEmpty(userName)) {
                    using (var db = new voatEntities())
                    {
                        var result = db.UserPreferences.Find(userName);
                        if (result != null)
                        {
                            theme = result.NightMode ? "dark" : "light";
                        }
                    }
                }
            }
            return theme;
        }
コード例 #23
0
ファイル: UserHelper.cs プロジェクト: rnand/voat
        // check if given user has submitted the same url before
        public static bool DailyCrossPostingQuotaUsed(string userName, string url)
        {
            // read daily crosspost quota from web.config
            int dailyCrossPostQuota = Settings.DailyCrossPostingQuota;

            // set starting date to 24 hours ago from now
            var fromDate = DateTime.Now.Add(new TimeSpan(0, -24, 0, 0, 0));
            var toDate = DateTime.Now;

            using (var db = new voatEntities())
            {
                var numberOfTimesSubmitted = db.Submissions
                    .Where(m => m.Content.Equals(url, StringComparison.OrdinalIgnoreCase)
                    && m.UserName.Equals(userName, StringComparison.OrdinalIgnoreCase)
                    && m.CreationDate >= fromDate && m.CreationDate <= toDate);

                int nrtimessubmitted = numberOfTimesSubmitted.Count();

                if (dailyCrossPostQuota <= nrtimessubmitted)
                {
                    return true;
                }
                return false;
            }
        }
コード例 #24
0
        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;
        }
コード例 #25
0
ファイル: UserHelper.cs プロジェクト: rnand/voat
        // 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 voatEntities())
            {
                var result = db.UserPreferences.Find(userName);
                if (result == null) return placeHolderMessage;

                return result.Bio ?? placeHolderMessage;
            }
        }
コード例 #26
0
ファイル: UserHelper.cs プロジェクト: rnand/voat
        // check if a given user has used his hourly posting quota for a given subverse
        public static bool UserHourlyPostingQuotaForSubUsed(string userName, string subverse)
        {
            // set starting date to 1 hours ago from now
            var fromDate = DateTime.Now.Add(new TimeSpan(0, -1, 0, 0, 0));
            var toDate = DateTime.Now;

            // read daily posting quota per sub configuration parameter from web.config
            int dpqps = Settings.HourlyPostingQuotaPerSub;

            using (var db = new voatEntities())
            {
                // check how many submission user made in the last hour
                var userSubmissionsToTargetSub = db.Submissions.Count(
                    m => m.Subverse.Equals(subverse, StringComparison.OrdinalIgnoreCase)
                        && m.UserName.Equals(userName, StringComparison.OrdinalIgnoreCase)
                        && m.CreationDate >= fromDate && m.CreationDate <= toDate);

                if (dpqps <= userSubmissionsToTargetSub)
                {
                    return true;
                }
                return false;
            }
        }
コード例 #27
0
ファイル: UserHelper.cs プロジェクト: rnand/voat
        // check if a given user has used his global hourly posting quota
        public static bool UserHourlyGlobalPostingQuotaUsed(string userName)
        {
            // only execute this check if user account is less than a month old and user SCP is less than 50 and user is not posting to a sub they own/moderate
            DateTime userRegistrationDateTime = GetUserRegistrationDateTime(userName);
            int memberInDays = (DateTime.Now - userRegistrationDateTime).Days;
            int userScp = Karma.LinkKarma(userName);
            if (memberInDays > 30 && userScp >= 50)
            {
                return false;
            }

            // set starting date to 1 hours ago from now
            var fromDate = DateTime.Now.Add(new TimeSpan(0, -1, 0, 0, 0));
            var toDate = DateTime.Now;

            // read daily posting quota per sub configuration parameter from web.config
            int dpqps = Settings.HourlyGlobalPostingQuota;

            using (var db = new voatEntities())
            {
                // check how many submission user made in the last hour
                var totalUserSubmissionsForTimeSpam = db.Submissions.Count(m => m.UserName.Equals(userName, StringComparison.OrdinalIgnoreCase) && m.CreationDate >= fromDate && m.CreationDate <= toDate);

                if (dpqps <= totalUserSubmissionsForTimeSpam)
                {
                    return true;
                }
                return false;
            }
        }
コード例 #28
0
        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;
        }
コード例 #29
0
        private ActionResult HandleSortedSubverseAll(int? page, string sortingmode, string daterange)
        {
            const string cookieName = "NSFWEnabled";
            const int pageSize = 25;
            DateTime startDate = DateTimeUtility.DateRangeToDateTime(daterange);
            PaginatedList<Message> paginatedSubmissions;

            ViewBag.SelectedSubverse = "all";
            
            if (User.Identity.IsAuthenticated)
            {
                var blockedSubverses = _db.UserBlockedSubverses.Where(x => x.Username.Equals(User.Identity.Name)).Select(x => x.SubverseName);
                IQueryable<Message> submissionsExcludingBlockedSubverses;

                // check if user wants to see NSFW content by reading user preference and exclude submissions from blocked subverses
                if (Voat.Utilities.UserHelper.AdultContentEnabled(User.Identity.Name))
                {
                    if (sortingmode.Equals("new"))
                    {
                        submissionsExcludingBlockedSubverses = SubmissionsFromAllSubversesByDate().Where(x => !blockedSubverses.Contains(x.Subverse));
                        paginatedSubmissions = new PaginatedList<Message>(submissionsExcludingBlockedSubverses, page ?? 0, pageSize);
                        return View("SubverseIndex", paginatedSubmissions);
                    }

                    if (sortingmode.Equals("top"))
                    {
                        submissionsExcludingBlockedSubverses = SubmissionsFromAllSubversesByTop(startDate).Where(x => !blockedSubverses.Contains(x.Subverse));
                        paginatedSubmissions = new PaginatedList<Message>(submissionsExcludingBlockedSubverses, page ?? 0, pageSize);
                        return View("SubverseIndex", paginatedSubmissions);
                    }

                    // default sorting mode by rank
                    submissionsExcludingBlockedSubverses = SubmissionsFromAllSubversesByRank().Where(x => !blockedSubverses.Contains(x.Subverse));
                    paginatedSubmissions = new PaginatedList<Message>(submissionsExcludingBlockedSubverses, page ?? 0, pageSize);
                    return View("SubverseIndex", paginatedSubmissions);
                }

                // user does not want to see NSFW content
                if (sortingmode.Equals("new"))
                {
                    submissionsExcludingBlockedSubverses = SfwSubmissionsFromAllSubversesByDate().Where(x => !blockedSubverses.Contains(x.Subverse));
                    paginatedSubmissions = new PaginatedList<Message>(submissionsExcludingBlockedSubverses, page ?? 0, pageSize);
                    return View("SubverseIndex", paginatedSubmissions);
                }
                if (sortingmode.Equals("top"))
                {
                    submissionsExcludingBlockedSubverses = SfwSubmissionsFromAllSubversesByTop(startDate).Where(x => !blockedSubverses.Contains(x.Subverse));
                    paginatedSubmissions = new PaginatedList<Message>(submissionsExcludingBlockedSubverses, page ?? 0, pageSize);
                    return View("SubverseIndex", paginatedSubmissions);
                }

                // default sorting mode by rank
                submissionsExcludingBlockedSubverses = SfwSubmissionsFromAllSubversesByRank(_db).Where(x => !blockedSubverses.Contains(x.Subverse));
                paginatedSubmissions = new PaginatedList<Message>(submissionsExcludingBlockedSubverses, page ?? 0, pageSize);
                return View("SubverseIndex", paginatedSubmissions);
            }

            // guest users: check if user wants to see NSFW content by reading NSFW cookie
            if (!HttpContext.Request.Cookies.AllKeys.Contains(cookieName))
            {
                if (sortingmode.Equals("new"))
                {
                    //IAmAGate: Perf mods for caching
                    int pageNumber = page.HasValue ? page.Value : 0;
                    int size = pageSize;
                    string cacheKeyAll = String.Format("subverse.{0}.page.{1}.sort.{2}.sfw", "all", pageNumber, "new").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 = SfwSubmissionsFromAllSubversesByDate(db);
                                int count = 50000;
                                List<Message> content = x.Skip(pageNumber * size).Take(size).ToList();
                                return new Tuple<IList<Message>, int>(content, count);
                            }
                        });

                        cacheDataAll = (Tuple<IList<Message>, int>)CacheHandler.Register(cacheKeyAll, getDataFunc, TimeSpan.FromSeconds(subverseCacheTimeInSeconds), (pageNumber < 3 ? 10 : 1));
                    }
                    paginatedSubmissions = new PaginatedList<Message>(cacheDataAll.Item1, pageNumber, pageSize, cacheDataAll.Item2);

                    //paginatedSubmissions = new PaginatedList<Message>(SfwSubmissionsFromAllSubversesByDate(), page ?? 0, pageSize);
                    return View("SubverseIndex", paginatedSubmissions);
                }
                if (sortingmode.Equals("top"))
                {
                    paginatedSubmissions = new PaginatedList<Message>(SfwSubmissionsFromAllSubversesByTop(startDate), page ?? 0, pageSize);
                    return View("SubverseIndex", paginatedSubmissions);
                }

                //QUE: I don't think this code is reachable
                // default sorting mode by rank
                paginatedSubmissions = new PaginatedList<Message>(SfwSubmissionsFromAllSubversesByRank(_db), page ?? 0, pageSize);
                return View("SubverseIndex", paginatedSubmissions);
            }

            if (sortingmode.Equals("new"))
            {

                //IAmAGate: Perf mods for caching
                int pageNumber = page.HasValue ? page.Value : 0;
                string cacheKeyAll = String.Format("subverse.{0}.page.{1}.sort.{2}.nsfw", "all", pageNumber, "new").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 = SubmissionsFromAllSubversesByDate(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 < 3 ? 10 : 1));
                }
                paginatedSubmissions = new PaginatedList<Message>(cacheDataAll.Item1, pageNumber, pageSize, cacheDataAll.Item2);

                //paginatedSubmissions = new PaginatedList<Message>(SubmissionsFromAllSubversesByDate(), page ?? 0, pageSize);
                return View("SubverseIndex", paginatedSubmissions);
            }
            if (sortingmode.Equals("top"))
            {
                paginatedSubmissions = new PaginatedList<Message>(SubmissionsFromAllSubversesByTop(startDate), page ?? 0, pageSize);
                return View("SubverseIndex", paginatedSubmissions);
            }

            // default sorting mode by rank
            paginatedSubmissions = new PaginatedList<Message>(SubmissionsFromAllSubversesByRank(), page ?? 0, pageSize);
            return View("SubverseIndex", paginatedSubmissions);
        }
コード例 #30
0
        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);
        }
コード例 #31
0
ファイル: UserHelper.cs プロジェクト: rnand/voat
        // return user statistics for user profile overview
        public static UserStatsModel UserStatsModel(string userName)
        {
            var userStatsModel = new UserStatsModel();

            using (var db = new voatEntities())
            {
                // 5 subverses user submitted to most
                var subverses = db.Submissions.Where(a => a.UserName == userName && !a.IsAnonymized && !a.IsDeleted)
                         .GroupBy(a => new { a.UserName, a.Subverse })
                         .Select(g => new SubverseStats { SubverseName = g.Key.Subverse, Count = g.Count() })
                         .OrderByDescending(s => s.Count)
                         .Take(5)
                         .ToList();

                // total comment count
                var comments = db.Comments.Count(a => a.UserName == userName);

                // voting habits
                var commentUpvotes = db.CommentVoteTrackers.Count(a => a.UserName == userName && a.VoteStatus == 1);
                var commentDownvotes = db.CommentVoteTrackers.Count(a => a.UserName == userName && a.VoteStatus == -1);
                var submissionUpvotes = db.SubmissionVoteTrackers.Count(a => a.UserName == userName && a.VoteStatus == 1);
                var submissionDownvotes = db.SubmissionVoteTrackers.Count(a => a.UserName == userName && a.VoteStatus == -1);

                // get 3 highest rated comments
                var highestRatedComments = db.Comments
                    .Include("Submission")
                    .Where(a => a.UserName == userName && !a.IsAnonymized && !a.IsDeleted)
                    .OrderByDescending(s => s.UpCount - s.DownCount)
                    .Take(3)
                    .ToList();

                // get 3 lowest rated comments
                var lowestRatedComments = db.Comments
                    .Include("Submission")
                    .Where(a => a.UserName == userName && !a.IsAnonymized && !a.IsDeleted)
                    .OrderBy(s => s.UpCount - s.DownCount)
                    .Take(3)
                    .ToList();

                var linkSubmissionsCount = db.Submissions.Count(a => a.UserName == userName && a.Type == 2 && !a.IsDeleted);
                var messageSubmissionsCount = db.Submissions.Count(a => a.UserName == userName && a.Type == 1 && !a.IsDeleted);

                // get 5 highest rated submissions
                var highestRatedSubmissions = db.Submissions.Where(a => a.UserName == userName && !a.IsAnonymized && !a.IsDeleted)
                    .OrderByDescending(s => s.UpCount - s.DownCount)
                    .Take(5)
                    .ToList();

                // get 5 lowest rated submissions
                var lowestRatedSubmissions = db.Submissions.Where(a => a.UserName == userName && !a.IsAnonymized && !a.IsDeleted)
                    .OrderBy(s => s.UpCount - s.DownCount)
                    .Take(5)
                    .ToList();

                userStatsModel.TopSubversesUserContributedTo = subverses;
                userStatsModel.LinkSubmissionsSubmitted = linkSubmissionsCount;
                userStatsModel.MessageSubmissionsSubmitted = messageSubmissionsCount;
                userStatsModel.LowestRatedSubmissions = lowestRatedSubmissions;
                userStatsModel.HighestRatedSubmissions = highestRatedSubmissions;
                userStatsModel.TotalCommentsSubmitted = comments;
                userStatsModel.HighestRatedComments = highestRatedComments;
                userStatsModel.LowestRatedComments = lowestRatedComments;
                userStatsModel.TotalCommentsUpvoted = commentUpvotes;
                userStatsModel.TotalCommentsDownvoted = commentDownvotes;
                userStatsModel.TotalSubmissionsUpvoted = submissionUpvotes;
                userStatsModel.TotalSubmissionsDownvoted = submissionDownvotes;
            }

            return userStatsModel;
        }
コード例 #32
0
        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;
        }
コード例 #33
0
ファイル: UserHelper.cs プロジェクト: rnand/voat
        // check if a given user has used his daily posting quota
        public static bool UserDailyPostingQuotaForNegativeScoreUsed(string userName)
        {
            // set starting date to 24 hours ago from now
            var fromDate = DateTime.Now.Add(new TimeSpan(0, -24, 0, 0, 0));
            var toDate = DateTime.Now;

            // read daily posting quota per sub configuration parameter from web.config
            int dpqps = Settings.DailyPostingQuotaForNegativeScore;

            using (var db = new voatEntities())
            {
                // check how many submission user made today
                var userSubmissionsInPast24Hours = db.Submissions.Count(
                    m => m.UserName.Equals(userName, StringComparison.OrdinalIgnoreCase)
                        && m.CreationDate >= fromDate && m.CreationDate <= toDate);

                if (dpqps <= userSubmissionsInPast24Hours)
                {
                    return true;
                }
                return false;
            }
        }
コード例 #34
0
        // GET: show a subverse index
        public ActionResult SubverseIndex(int? page, string subversetoshow, bool? previewMode)
        {
            ViewBag.previewMode = previewMode ?? false;

            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 (Voat.Utilities.UserHelper.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 (Voat.Utilities.UserHelper.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");
            }
        }
コード例 #35
0
ファイル: UserHelper.cs プロジェクト: rnand/voat
        // check if given user has unread private messages, not including messages manually marked as unread
        public static bool UserHasNewMessages(string userName)
        {
            using (var db = new voatEntities())
            {
                var unreadPrivateMessagesCount = db.PrivateMessages.Count(s => s.Recipient.Equals(userName, StringComparison.OrdinalIgnoreCase) && s.IsUnread && s.MarkedAsUnread == false);
                var unreadCommentRepliesCount = db.CommentReplyNotifications.Count(s => s.Recipient.Equals(userName, StringComparison.OrdinalIgnoreCase) && s.IsUnread && s.MarkedAsUnread == false);
                var unreadPostRepliesCount = db.SubmissionReplyNotifications.Count(s => s.Recipient.Equals(userName, StringComparison.OrdinalIgnoreCase) && s.IsUnread && s.MarkedAsUnread == false);

                return unreadPrivateMessagesCount > 0 || unreadCommentRepliesCount > 0 || unreadPostRepliesCount > 0;
            }
        }