Ejemplo n.º 1
0
        // 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 whoaverseEntities())
            {
                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;
                }
            }
        }
Ejemplo n.º 2
0
            public void PullsDefaultFrontpage(whoaverseEntities db, Defaultsubverse defaultsubverse, List<Message> messages)
            {
                // Arrange
                // TODO: See if we can coax Autofixture into handling this for us
                if (defaultsubverse.name.Length > 20)
                    defaultsubverse.name = defaultsubverse.name.Substring(0, 19);
                db.Defaultsubverses.Add(defaultsubverse);
                db.Subverses.Add(new Subverse {name = defaultsubverse.name, title = new Guid().ToString()});
                db.SaveChanges();

                foreach (var message in messages)
                {
                    // TODO: See if we can coax Autofixture into handling this for us
                    if (message.Thumbnail.Length > 40)
                        message.Thumbnail = message.Thumbnail.Substring(0, 39);
                    message.Subverse = defaultsubverse.name;
                }
                db.Messages.AddRange(messages);
                db.SaveChanges();

                var homeController = new HomeController(db);
                homeController.ControllerContext = GetControllerContext(false);

                // Act
                var actionResult = (ViewResult) homeController.Index(null);
                var model = (PaginatedList<Message>) actionResult.Model;

                // Assert
                Assert.True(model.Count == messages.Count);
            }
Ejemplo n.º 3
0
 // returns true if saved, false otherwise
 public static bool? CheckIfSavedComment(string userToCheck, int commentId)
 {
     using (var db = new whoaverseEntities())
     {
         return db.Commentsavingtrackers.Where(b => b.CommentId == commentId && b.UserName == userToCheck).AsNoTracking().Any();
     }
 }
Ejemplo n.º 4
0
        public ApiBadge BadgeInfo(string badgeId)
        {
            ApiBadge badgeInfo = CacheHandler.Register<ApiBadge>(String.Format("LegacyApi.ApiBadge.{0}", badgeId),
             new Func<ApiBadge>(() =>
             {
                 using (whoaverseEntities db = new whoaverseEntities(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;
        }
Ejemplo n.º 5
0
        // 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 whoaverseEntities())
            {
                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();
                }
            }
        }
Ejemplo n.º 6
0
 // returns true if saved, false otherwise
 public static bool? CheckIfSaved(string userToCheck, int messageId)
 {
     using (var db = new whoaverseEntities())
     {
         return db.Savingtrackers.Where(u => u.UserName == userToCheck && u.MessageId == messageId).AsNoTracking().Any();
     }
 }
Ejemplo n.º 7
0
        // returns true if saved, false otherwise
        public static bool? CheckIfSavedComment(string userToCheck, int commentId)
        {
            using (whoaverseEntities db = new whoaverseEntities())
            {

                var cmd = db.Database.Connection.CreateCommand();
                cmd.CommandText = "SELECT COUNT(*) FROM Commentsavingtracker WITH (NOLOCK) WHERE UserName = @UserName AND CommentId = @CommentId";

                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 = "CommentId";
                param.DbType = System.Data.DbType.String;
                param.Value = commentId;
                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 whoaverseEntities())
            //{
            //    return db.Commentsavingtrackers.Where(b => b.CommentId == commentId && b.UserName == userToCheck).AsNoTracking().Any();
            //}
        }
Ejemplo n.º 8
0
        // 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 whoaverseEntities())
            {
                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();
                }
            }
        }
Ejemplo n.º 9
0
 // check if a given user does not want to see custom CSS styles
 public static bool CustomCssDisabledForUser(string userName)
 {
     using (var db = new whoaverseEntities())
     {
         var result = db.Userpreferences.Find(userName);
         return result != null && result.Disable_custom_css;
     }
 }
Ejemplo n.º 10
0
 // check if a given user wants to see NSFW (adult) content
 public static bool AdultContentEnabled(string userName)
 {
     using (var db = new whoaverseEntities())
     {
         var result = db.Userpreferences.Find(userName);
         return result != null && result.Enable_adult_content;
     }
 }
Ejemplo n.º 11
0
 // get total number of comment replies for a given user
 public static int CommentRepliesCount(string userName)
 {
     using (var db = new whoaverseEntities())
     {
         var commentReplies = db.Commentreplynotifications.Where(s => s.Recipient.Equals(userName, StringComparison.OrdinalIgnoreCase));
         if (!commentReplies.Any()) return 0;
         return commentReplies.Any() ? commentReplies.Count() : 0;
     }
 }
Ejemplo n.º 12
0
        // a user has saved this comment earlier and wishes to unsave it, delete the record
        private static void UnSaveComment(string userWhichSaved, int commentId)
        {
            using (var db = new whoaverseEntities())
            {
                var votingTracker = db.Commentsavingtrackers.FirstOrDefault(b => b.CommentId == commentId && b.UserName == userWhichSaved);

                if (votingTracker == null) return;
                // delete vote history
                db.Commentsavingtrackers.Remove(votingTracker);
                db.SaveChanges();
            }
        }
Ejemplo n.º 13
0
        // a user has saved this submission earlier and wishes to unsave it, delete the record
        private static void UnSaveSubmission(string userWhichSaved, int messageId)
        {
            using (var db = new whoaverseEntities())
            {
                var saveTracker = db.Savingtrackers.FirstOrDefault(b => b.MessageId == messageId && b.UserName == userWhichSaved);

                if (saveTracker == null) return;
                //delete vote history
                db.Savingtrackers.Remove(saveTracker);
                db.SaveChanges();
            }
        }
Ejemplo n.º 14
0
        // returns -1:downvoted, 1:upvoted, 0:not voted
        public static int CheckIfVoted(string userToCheck, int messageId)
        {
            using (var db = new whoaverseEntities())
            {
                var checkResult = db.Votingtrackers.Where(u => u.UserName == userToCheck && u.MessageId == messageId)
                        .AsNoTracking()
                        .FirstOrDefault();

                int intCheckResult = checkResult != null ? checkResult.VoteStatus.Value : 0;
                return intCheckResult;
            }
        }
Ejemplo n.º 15
0
        // returns -1:downvoted, 1:upvoted, or 0:not voted
        public static int CheckIfVotedComment(string userToCheck, int commentId)
        {
            int intCheckResult = 0;

            using (var db = new whoaverseEntities())
            {
                var checkResult = db.Commentvotingtrackers.FirstOrDefault(b => b.CommentId == commentId && b.UserName == userToCheck);

                intCheckResult = checkResult != null ? checkResult.VoteStatus.Value : 0;

                return intCheckResult;
            }
        }
Ejemplo n.º 16
0
 public IEnumerable<string> BannedHostnames()
 {
     IEnumerable<string> bannedSubs = CacheHandler.Register<IEnumerable<string>>("LegacyApi.BannedHostnames",
       new Func<IList<string>>(() =>
       {
           using (whoaverseEntities db = new whoaverseEntities(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;
 }
Ejemplo n.º 17
0
Archivo: Karma.cs Proyecto: blakar/voat
        // 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 (whoaverseEntities db = new whoaverseEntities())
            {

                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 whoaverseEntities())
            //{
            //    try
            //    {
            //        return db.Comments.Where(c => c.Name.Trim().Equals(userName, StringComparison.OrdinalIgnoreCase))
            //            .Select(c => c.Likes - c.Dislikes)
            //            .Sum();
            //    }
            //    catch (Exception)
            //    {
            //        return 0;
            //    }
            //}
        }
Ejemplo n.º 18
0
        public static bool IsHostnameBanned(string hostnameToCheck)
        {
            using (var db = new whoaverseEntities())
            {
                var bannedHostname = db.Banneddomains.FirstOrDefault(r => r.Hostname.Equals(hostnameToCheck, StringComparison.OrdinalIgnoreCase));

                // manual ban for blogspot
                if (hostnameToCheck.Contains("blogspot"))
                {
                    return true;
                }

                // look for exact match
                return bannedHostname != null;
            }
        }
Ejemplo n.º 19
0
        // a method to mark single or all private messages as read for a given user
        public static async Task<bool> MarkPrivateMessagesAsRead(bool? markAll, string userName, int? itemId)
        {
            using (var db = new whoaverseEntities())
            {
                try
                {
                    // mark all items as read
                    if (markAll != null && (bool) markAll)
                    {
                        IQueryable<Privatemessage> unreadPrivateMessages = db.Privatemessages
                                                                            .Where(s => s.Recipient.Equals(userName, StringComparison.OrdinalIgnoreCase) && s.Status)
                                                                            .OrderByDescending(s => s.Timestamp)
                                                                            .ThenBy(s => s.Sender);

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

                        foreach (var singleMessage in unreadPrivateMessages.ToList())
                        {
                            singleMessage.Status = false;
                        }
                        await db.SaveChangesAsync();
                        return true;
                    }

                    // mark single item as read
                    if (itemId != null)
                    {
                        var privateMessageToMarkAsread = db.Privatemessages.FirstOrDefault(s => s.Recipient.Equals(userName, StringComparison.OrdinalIgnoreCase) && s.Status && s.Id == itemId);
                        if (privateMessageToMarkAsread == null) return false;

                        var item = db.Privatemessages.Find(itemId);
                        item.Status = false;
                        await db.SaveChangesAsync();
                        return true;
                    }
                    return false;
                }
                catch (Exception)
                {
                    return false;
                }
            }

        }
Ejemplo n.º 20
0
        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 (whoaverseEntities db = new whoaverseEntities()) {
                            return db.Subverses.Where(x => x.name == subverse).FirstOrDefault();
                        }

                    }), TimeSpan.FromMinutes(5), 50);
                }
                return sub;
            }
            return null;
        }
Ejemplo n.º 21
0
        // block a subverse
        public static void BlockSubverse(string userName, string subverse)
        {
            using (var db = new whoaverseEntities())
            {
                // unblock if subverse is already blocked
                if (IsUserBlockingSubverse(userName, subverse))
                {
                    var subverseBlock = db.UserBlockedSubverses.FirstOrDefault(n => n.SubverseName.ToLower() == subverse.ToLower() && n.Username == userName);
                    if (subverseBlock != null) db.UserBlockedSubverses.Remove(subverseBlock);
                    db.SaveChanges();
                    return;
                }

                // add a new block
                var blockedSubverse = new UserBlockedSubverse { Username = userName, SubverseName = subverse };
                db.UserBlockedSubverses.Add(blockedSubverse);
                db.SaveChanges();
            }
        }
Ejemplo n.º 22
0
        public static int CommentCount(int submissionID)
        {
            int count = 0;

            using (whoaverseEntities db = new whoaverseEntities())
            {

                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();
                }
                count = (int)cmd.ExecuteScalar();
            }
            return count;
        }
Ejemplo n.º 23
0
        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 (whoaverseEntities db = new whoaverseEntities())
                    {
                        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;
        }
Ejemplo n.º 24
0
        public ActionResult UserPreferencesAbout()
        {
            try
            {
                using (var db = new whoaverseEntities())
                {
                    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();
            }
        }
Ejemplo n.º 25
0
        // 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 && Utils.User.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 (whoaverseEntities db = new whoaverseEntities(CONSTANTS.CONNECTION_LIVE))
                            {
                                var blockedSubverses = db.UserBlockedSubverses.Where(x => x.Username.Equals(User.Identity.Name)).Select(x => x.SubverseName);
                                IQueryable<Message> submissions = (from m in db.Messages
                                                                   join s in db.Subscriptions on m.Subverse equals s.SubverseName
                                                                   where !m.IsArchived && m.Name != "deleted" && s.Username == User.Identity.Name
                                                                   where !(from bu in db.Bannedusers select bu.Username).Contains(m.Name)
                                                                   select m).OrderByDescending(s => s.Date);
                                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<Message>)cacheData).Skip((pageNumber - (subset * pagesToTake)) * pageSize).Take(pageSize).ToList();

                    PaginatedList<Message> paginatedSubmissions = new PaginatedList<Message>(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 (whoaverseEntities db = new whoaverseEntities(CONSTANTS.CONNECTION_READONLY))
                            {
                                // get only submissions from default subverses, order by rank
                                IQueryable<Message> submissions = (from message in db.Messages
                                                                   where !message.IsArchived && message.Name != "deleted"
                                                                   where !(from bu in db.Bannedusers select bu.Username).Contains(message.Name)
                                                                   join defaultsubverse in db.Defaultsubverses on message.Subverse equals defaultsubverse.name
                                                                   select message).OrderByDescending(s => s.Date);
                                return submissions.Where(s => s.Stickiedsubmission.Submission_id != 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<Message> paginatedSubmissions = new PaginatedList<Message>((IList<Message>)cacheData, pageNumber, pageSize, 50000);

                    //// get only submissions from default subverses, sort by date
                    //IQueryable<Message> submissions = (from message in _db.Messages
                    //                              where message.Name != "deleted"
                    //                              where !(from bu in _db.Bannedusers select bu.Username).Contains(message.Name)
                    //                              join defaultsubverse in _db.Defaultsubverses on message.Subverse equals defaultsubverse.name
                    //                              select message).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");
            }
        }
Ejemplo n.º 26
0
        // 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 && Utils.User.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 (whoaverseEntities db = new whoaverseEntities(CONSTANTS.CONNECTION_LIVE))
                            {
                                
                                var blockedSubverses = db.UserBlockedSubverses.Where(x => x.Username.Equals(User.Identity.Name)).Select(x => x.SubverseName);

                                IQueryable<Message> submissions = (from m in db.Messages.Include("Subverses").AsNoTracking()
                                                                   join s in db.Subscriptions on m.Subverse equals s.SubverseName
                                                                   where !m.IsArchived && m.Name != "deleted" && s.Username == User.Identity.Name
                                                                   where !(from bu in db.Bannedusers select bu.Username).Contains(m.Name)
                                                                   select m).OrderByDescending(s => s.Rank);

                                var submissionsWithoutStickies = submissions.Where(s => s.Stickiedsubmission.Submission_id != 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<Message>)cacheData).Skip((pageNumber - (subset * pagesToTake)) * pageSize).Take(pageSize).ToList();
                    PaginatedList<Message> paginatedSubmissions = new PaginatedList<Message>(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 (whoaverseEntities db = new whoaverseEntities(CONSTANTS.CONNECTION_READONLY))
                            {
                                
                                // get only submissions from default subverses, order by rank
                                IQueryable<Message> submissions = (from message in db.Messages.AsNoTracking()
                                                                   where !message.IsArchived &&  message.Name != "deleted"
                                                                   where !(from bu in db.Bannedusers select bu.Username).Contains(message.Name)
                                                                   join defaultsubverse in db.Defaultsubverses on message.Subverse equals defaultsubverse.name
                                                                   select message).OrderByDescending(s => s.Rank);

                                return submissions.Where(s => s.Stickiedsubmission.Submission_id != 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<Message> paginatedSubmissions = new PaginatedList<Message>((IList<Message>)cacheData, pageNumber, pageSize, 50000);

                    return View(paginatedSubmissions);
                }
            }
            catch (Exception)
            {
                return View("~/Views/Errors/DbNotResponding.cshtml");
            }
        }
Ejemplo n.º 27
0
        public async Task<ActionResult> UserPreferencesAbout([Bind(Include = "Shortbio, Avatarfile")] UserAboutViewModel model)
        {
            // save changes
            using (var db = new whoaverseEntities())
            {
                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");
        }
Ejemplo n.º 28
0
        public ActionResult UserPreferences()
        {
            try
            {
                using (var db = new whoaverseEntities())
                {
                    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();
            }
        }
Ejemplo n.º 29
0
        public async Task<ActionResult> ToggleNightMode()
        {
            // save changes
            using (var db = new whoaverseEntities())
            {
                var userPreferences = db.Userpreferences.Find(User.Identity.Name);

                if (userPreferences != null)
                {
                    // modify existing preferences
                    userPreferences.Night_mode = !userPreferences.Night_mode;

                    await db.SaveChangesAsync();
                    // apply theme change
                    Session["UserTheme"] = Utils.User.UserStylePreference(User.Identity.Name);
                }
                else
                {
                    // create a new record for this user in userpreferences table
                    var tmpModel = new Userpreference
                    {
                        Disable_custom_css = false,
                        //Since if user has no pref, they must have been on the light theme
                        Night_mode = true,
                        Clicking_mode = false,
                        Enable_adult_content = false,
                        Public_subscriptions = false,
                        Topmenu_from_subscriptions = false,
                        Username = User.Identity.Name
                    };
                    db.Userpreferences.Add(tmpModel);

                    await db.SaveChangesAsync();
                    // apply theme change
                    Session["UserTheme"] = Utils.User.UserStylePreference(User.Identity.Name);
                }
            }

            Response.StatusCode = 200;
            return Json("Toggled Night Mode", JsonRequestBehavior.AllowGet);
        }
Ejemplo n.º 30
0
        public async Task<ActionResult> UserPreferences([Bind(Include = "Disable_custom_css, Night_mode, OpenLinksInNewTab, Enable_adult_content, Public_subscriptions, Topmenu_from_subscriptions, Shortbio, Avatar")] UserPreferencesViewModel model)
        {
            // save changes
            using (var db = new whoaverseEntities())
            {
                var userPreferences = db.Userpreferences.Find(User.Identity.Name);

                if (userPreferences != null)
                {
                    // modify existing preferences
                    userPreferences.Disable_custom_css = model.Disable_custom_css;
                    userPreferences.Night_mode = model.Night_mode;
                    userPreferences.Clicking_mode = model.OpenLinksInNewTab;
                    userPreferences.Enable_adult_content = model.Enable_adult_content;
                    userPreferences.Public_subscriptions = model.Public_subscriptions;
                    userPreferences.Topmenu_from_subscriptions = model.Topmenu_from_subscriptions;

                    await db.SaveChangesAsync();
                    // apply theme change
                    Session["UserTheme"] = Utils.User.UserStylePreference(User.Identity.Name);
                }
                else
                {
                    // create a new record for this user in userpreferences table
                    var tmpModel = new Userpreference
                    {
                        Disable_custom_css = model.Disable_custom_css,
                        Night_mode = model.Night_mode,
                        Clicking_mode = model.OpenLinksInNewTab,
                        Enable_adult_content = model.Enable_adult_content,
                        Public_subscriptions = model.Public_subscriptions,
                        Topmenu_from_subscriptions = model.Topmenu_from_subscriptions,
                        Username = User.Identity.Name
                    };
                    db.Userpreferences.Add(tmpModel);

                    await db.SaveChangesAsync();
                    // apply theme change
                    Session["UserTheme"] = Utils.User.UserStylePreference(User.Identity.Name);
                }
            }

            //return RedirectToAction("Manage", new { Message = "Your user preferences have been saved." });
            return RedirectToAction("Manage");
        }