Esempio n. 1
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 voatEntities())
            {
                if (result == true)
                {
                    // Already saved, unsave
                    UnSaveComment(userWhichSaved, commentId);
                }
                else
                {
                    // register save
                    var tmpSavingTracker = new Commentsavingtracker
                    {
                        CommentId = commentId,
                        UserName = userWhichSaved,
                        Timestamp = DateTime.Now
                    };
                    db.Commentsavingtrackers.Add(tmpSavingTracker);
                    db.SaveChanges();
                }
            }
        }
Esempio n. 2
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 voatEntities())
            {
                if (result == true)
                {
                    // Already saved, unsave
                    UnSaveSubmission(userWhichSaved, submissionId);
                }
                else
                {
                    // register save
                    var tmpSavingTracker = new Savingtracker
                    {
                        MessageId = submissionId,
                        UserName = userWhichSaved,
                        Timestamp = DateTime.Now
                    };
                    db.Savingtrackers.Add(tmpSavingTracker);
                    db.SaveChanges();
                }
            }
        }
Esempio n. 3
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 voatEntities())
            {
                try
                {
                    var privateMessage = new Privatemessage
                    {
                        Sender = sender,
                        Recipient = recipient,
                        Timestamp = DateTime.Now,
                        Subject = subject,
                        Body = body,
                        Status = true,
                        Markedasunread = true
                    };

                    db.Privatemessages.Add(privateMessage);
                    db.SaveChanges();

                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }
        }
Esempio n. 4
0
        // returns true if saved, false otherwise
        public static bool? CheckIfSaved(string userToCheck, int messageId)
        {
            using (voatEntities db = new voatEntities())
            {

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

                var param = cmd.CreateParameter();
                param.ParameterName = "UserName";
                param.DbType = System.Data.DbType.String;
                param.Value = userToCheck;
                cmd.Parameters.Add(param);

                param = cmd.CreateParameter();
                param.ParameterName = "MessageId";
                param.DbType = System.Data.DbType.String;
                param.Value = messageId;
                cmd.Parameters.Add(param);

                if (cmd.Connection.State != System.Data.ConnectionState.Open)
                {
                    cmd.Connection.Open();
                }

                int count = (int)cmd.ExecuteScalar();

                return count > 0;
            }

            //using (var db = new voatEntities())
            //{
            //    return db.Savingtrackers.Where(u => u.UserName == userToCheck && u.MessageId == messageId).AsNoTracking().Any();
            //}
        }
Esempio n. 5
0
        // get comment contribution points for a user
        public static int CommentKarma(string userName)
        {
            string cacheKey = CacheKey(userName, KarmaCacheType.Comment);

            object cacheData = Cache[cacheKey];
            if (cacheData != null)
            {
                return (int)cacheData;
            }

            int count = 0;
            using (voatEntities db = new voatEntities())
            {
                // try to get CCP from storage
                var storedUserCcp = db.Userscores.FirstOrDefault(x => x.Username.Equals(userName, StringComparison.OrdinalIgnoreCase));
                if (storedUserCcp != null)
                {
                    // add CCP value to cache
                    Cache.Insert(cacheKey, storedUserCcp.CCP, null, DateTime.Now.AddSeconds(cacheTimeInSeconds), Cache.NoSlidingExpiration);
                    return storedUserCcp.CCP;
                }

                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;
                // add CCP value to cache
                Cache.Insert(cacheKey, count, null, DateTime.Now.AddSeconds(cacheTimeInSeconds), System.Web.Caching.Cache.NoSlidingExpiration);
            }

            return count;

            //using (var db = new voatEntities())
            //{
            //    try
            //    {
            //        return db.Comments.Where(c => c.Name.Trim().Equals(userName, StringComparison.OrdinalIgnoreCase))
            //            .Select(c => c.Likes - c.Dislikes)
            //            .Sum();
            //    }
            //    catch (Exception)
            //    {
            //        return 0;
            //    }
            //}
        }
Esempio n. 6
0
        //// returns -1:downvoted, 1:upvoted, 0:not voted
        //public static SubmissionVoteTracker GetVote(voatEntities db, string userToCheck, int submissionID)
        //{
        //        var checkResult = db.SubmissionVoteTrackers.Where(u => u.UserName == userToCheck && u.SubmissionID == submissionID)
        //                .AsNoTracking()
        //                .FirstOrDefault();
        //}
        // a user has either upvoted or downvoted this submission earlier and wishes to reset the vote, delete the record
        public static void ResetMessageVote(string userWhichVoted, int submissionID)
        {
            using (var db = new voatEntities())
            {
                var votingTracker = db.SubmissionVoteTrackers.FirstOrDefault(b => b.SubmissionID == submissionID && b.UserName == userWhichVoted);

                if (votingTracker == null) return;
                //delete vote history
                db.SubmissionVoteTrackers.Remove(votingTracker);
                db.SaveChanges();
            }
        }
Esempio n. 7
0
File: Voting.cs Progetto: rnand/voat
        // returns -1:downvoted, 1:upvoted, 0:not voted
        public static int CheckIfVoted(string userToCheck, int submissionID)
        {
            using (var db = new voatEntities())
            {
                var checkResult = db.SubmissionVoteTrackers.Where(u => u.UserName == userToCheck && u.SubmissionID == submissionID)
                        .AsNoTracking()
                        .FirstOrDefault();

                int intCheckResult = checkResult != null ? checkResult.VoteStatus.Value : 0;
                return intCheckResult;
            }
        }
Esempio n. 8
0
        // returns -1:downvoted, 1:upvoted, 0:not voted
        public static int CheckIfVoted(string userToCheck, int messageId)
        {
            using (var db = new voatEntities())
            {
                var checkResult = db.Votingtrackers.Where(u => u.UserName == userToCheck && u.MessageId == messageId)
                        .AsNoTracking()
                        .FirstOrDefault();

                int intCheckResult = checkResult != null ? checkResult.VoteStatus.Value : 0;
                return intCheckResult;
            }
        }
Esempio n. 9
0
        // get link contribution points for a user
        public static int LinkKarma(string userName)
        {

            string cacheKey = CacheKey(userName, KarmaCacheType.Link);

            object cacheData = Cache[cacheKey];
            if (cacheData != null)
            {
                return (int)cacheData;
            }


            int count = 0;
            using (voatEntities db = new voatEntities())
            {

                var cmd = db.Database.Connection.CreateCommand();
                cmd.CommandText = "SELECT ISNULL(SUM(UpCount - DownCount), 0) FROM Submission WITH (NOLOCK) WHERE UserName = @UserName";
                var param = cmd.CreateParameter();
                param.ParameterName = "UserName";
                param.DbType = System.Data.DbType.String;
                param.Value = userName;
                cmd.Parameters.Add(param);

                if (cmd.Connection.State != System.Data.ConnectionState.Open)
                {
                    cmd.Connection.Open();
                }
                long l = (long)cmd.ExecuteScalar();
                count = (int)l;
                Cache.Insert(cacheKey, count, null, DateTime.Now.AddSeconds(cacheTimeInSeconds), System.Web.Caching.Cache.NoSlidingExpiration);

            }


            return count;


            //using (var db = new voatEntities())
            //{
            //    try
            //    {
            //        return db.Messages.Where(c => c.Name.Trim().Equals(userName, StringComparison.OrdinalIgnoreCase))
            //            .Select(c => c.Likes - c.Dislikes)
            //            .Sum();
            //    }
            //    catch (Exception)
            //    {
            //        return 0;
            //    }
            //}
        }
Esempio n. 10
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 voatEntities())
            {
                var checkResult = db.Commentvotingtrackers.FirstOrDefault(b => b.CommentId == commentId && b.UserName == userToCheck);

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

                return intCheckResult;
            }
        }
Esempio n. 11
0
        public static async Task SendUserMentionNotification(string user, Comment comment, Action<string> onSuccess)
        {
            if (comment != null)
            {
                if (!UserHelper.UserExists(user))
                {
                    return;
                }
                try
                {
                    string recipient = UserHelper.OriginalUsername(user);

                    var commentReplyNotification = new Commentreplynotification();
                    using (var _db = new voatEntities())
                    {
                        var submission = DataCache.Submission.Retrieve(comment.MessageId);
                        var subverse = DataCache.Subverse.Retrieve(submission.Subverse);

                        commentReplyNotification.CommentId = comment.Id;
                        commentReplyNotification.SubmissionId = comment.MessageId.Value;
                        commentReplyNotification.Recipient = recipient;
                        if (submission.Anonymized || subverse.anonymized_mode)
                        {
                            commentReplyNotification.Sender = (new Random()).Next(10000, 20000).ToString(CultureInfo.InvariantCulture);
                        }
                        else
                        {
                            commentReplyNotification.Sender = comment.Name;
                        }
                        commentReplyNotification.Body = comment.CommentContent;
                        commentReplyNotification.Subverse = subverse.name;
                        commentReplyNotification.Status = true;
                        commentReplyNotification.Timestamp = DateTime.Now;

                        commentReplyNotification.Subject = String.Format("@{0} mentioned you in a comment", comment.Name, submission.Title);

                        _db.Commentreplynotifications.Add(commentReplyNotification);
                       
                        await _db.SaveChangesAsync();
                    }

                    if (onSuccess != null)
                    {
                        onSuccess(recipient);
                    }
                }
                catch (Exception ex) {
                    throw ex;
                }
            }
        }
Esempio n. 12
0
        public static bool IsHostnameBanned(string hostnameToCheck)
        {
            // manual ban for blogspot
            if (hostnameToCheck.Contains("blogspot"))
            {
                return true;
            }

            using (var db = new voatEntities())
            {
                var bannedHostname = db.Banneddomains.FirstOrDefault(r => r.Hostname.Equals(hostnameToCheck, StringComparison.OrdinalIgnoreCase));

                // look for exact match
                return bannedHostname != null;
            }
        }
Esempio n. 13
0
        public static double? GetSubverseHighestRanking(string subverse)
        {
            var highestRank =  CacheHandler.Register(GetHighestRankingCacheKey(subverse), new Func<double?>(() => {
                using (var db = new voatEntities())
                {
                    var submission = db.Submissions.OrderByDescending(x => x.Rank).Where(x => x.Subverse == subverse).FirstOrDefault();
                    if (submission != null)
                    {
                        return submission.Rank;
                    }
                    return null;
                }
            }), TimeSpan.FromMinutes(30));

            return highestRank;
        }
Esempio n. 14
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 voatEntities())
            {
                try
                {
                    // mark all items as read
                    if (markAll != null && (bool) markAll)
                    {
                        IQueryable<Privatemessage> unreadPrivateMessages = db.Privatemessages
                                                                            .Where(s => s.Recipient.Equals(userName, StringComparison.OrdinalIgnoreCase) && s.Status)
                                                                            .OrderByDescending(s => s.Timestamp)
                                                                            .ThenBy(s => s.Sender);

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

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

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

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

        }
Esempio n. 15
0
        // returns true if saved, false otherwise
        public static bool? CheckIfSavedComment(string userToCheck, int commentID)
        {

            using (voatEntities db = new voatEntities())
            {

                var cmd = db.Database.Connection.CreateCommand();
                cmd.CommandText = "SELECT COUNT(*) FROM CommentSaveTracker 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 voatEntities())
            //{
            //    return db.Commentsavingtrackers.Where(b => b.CommentId == commentId && b.UserName == userToCheck).AsNoTracking().Any();
            //}

        }
Esempio n. 16
0
 public static bool IsDomainBanned(params string[] domains)
 {
     foreach (string domain in domains)
     {
         using (var db = new voatEntities())
         {
             if (domain != null)
             {
                 // manual ban for blogspot
                 if (domain.ToLower().Contains("blogspot"))
                 {
                     return true;
                 }
                 var result = db.BannedDomains.Any(r => r.Domain.Equals(domain, StringComparison.OrdinalIgnoreCase));
                 if (result)
                 {
                     return result;
                 }
             }
         }
     }
     return false;
 }
Esempio n. 17
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 (voatEntities db = new voatEntities())
                    {
                        var cmd = db.Database.Connection.CreateCommand();
                        cmd.CommandText = "SELECT COUNT(*) FROM Comment WITH (NOLOCK) WHERE SubmissionID = @SubmissionID AND IsDeleted != 1";
                        var param = cmd.CreateParameter();
                        param.ParameterName = "SubmissionID";
                        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;
        }
Esempio n. 18
0
        // add new link submission
        public static async Task<string> AddNewSubmission(Message submissionModel, Subverse targetSubverse, string userName)
        {
            using (var db = new voatEntities())
            {
                // LINK TYPE SUBMISSION
                if (submissionModel.Type == 2)
                {
                    // strip unicode if title contains unicode
                    if (ContainsUnicode(submissionModel.Linkdescription))
                    {
                        submissionModel.Linkdescription = StripUnicode(submissionModel.Linkdescription);
                    }

                    // reject if title is whitespace or < than 5 characters
                    if (submissionModel.Linkdescription.Length < 5 || String.IsNullOrWhiteSpace(submissionModel.Linkdescription))
                    {
                        return ("The title may not be less than 5 characters.");
                    }

                    // make sure the input URI is valid
                    if (!UrlUtility.IsUriValid(submissionModel.MessageContent))
                    {
                        // ABORT
                        return ("The URI you are trying to submit is invalid.");
                    }

                    // check if target subvere allows submissions from globally banned hostnames
                    if (!targetSubverse.exclude_sitewide_bans)
                    {
                        // check if hostname is banned before accepting submission
                        var domain = UrlUtility.GetDomainFromUri(submissionModel.MessageContent);
                        if (BanningUtility.IsHostnameBanned(domain))
                        {
                            // ABORT
                            return ("The hostname you are trying to submit is banned.");
                        }
                    }

                    // check if user has reached daily crossposting quota
                    if (UserHelper.DailyCrossPostingQuotaUsed(userName, submissionModel.MessageContent))
                    {
                        // ABORT
                        return ("You have reached your daily crossposting quota for this URL.");
                    }

                    // check if target subverse has thumbnails setting enabled before generating a thumbnail
                    if (targetSubverse.enable_thumbnails)
                    {
                        // try to generate and assign a thumbnail to submission model
                        submissionModel.Thumbnail = await ThumbGenerator.ThumbnailFromSubmissionModel(submissionModel);
                    }

                    // flag the submission as anonymized if it was submitted to a subverse with active anonymized_mode
                    if (targetSubverse.anonymized_mode)
                    {
                        submissionModel.Anonymized = true;
                    }
                    else
                    {
                        submissionModel.Name = userName;
                    }

                    // accept submission and save it to the database
                    submissionModel.Subverse = targetSubverse.name;
                    submissionModel.Likes = 1;
                    db.Messages.Add(submissionModel);

                    // update last submission received date for target subverse
                    targetSubverse.last_submission_received = DateTime.Now;
                    await db.SaveChangesAsync();
                }
                else
                // MESSAGE TYPE SUBMISSION
                {
                    // strip unicode if submission contains unicode
                    if (ContainsUnicode(submissionModel.Title))
                    {
                        submissionModel.Title = StripUnicode(submissionModel.Title);
                    }

                    // reject if title is whitespace or less than 5 characters
                    if (submissionModel.Title.Length < 5 || String.IsNullOrWhiteSpace(submissionModel.Title))
                    {
                        return ("Sorry, submission title may not be less than 5 characters.");
                    }

                    // flag the submission as anonymized if it was submitted to a subverse with active anonymized_mode
                    if (targetSubverse.anonymized_mode)
                    {
                        submissionModel.Anonymized = true;
                    }
                    else
                    {
                        submissionModel.Name = userName;
                    }

                    // grab server timestamp and modify submission timestamp to have posting time instead of "started writing submission" time
                    submissionModel.Subverse = targetSubverse.name;
                    submissionModel.Date = DateTime.Now;
                    submissionModel.Likes = 1;
                    db.Messages.Add(submissionModel);

                    // update last submission received date for target subverse
                    targetSubverse.last_submission_received = DateTime.Now;

                    if (ContentProcessor.Instance.HasStage(ProcessingStage.InboundPreSave))
                    {
                        submissionModel.MessageContent = ContentProcessor.Instance.Process(submissionModel.MessageContent, ProcessingStage.InboundPreSave, submissionModel);
                    }

                    await db.SaveChangesAsync();

                    if (ContentProcessor.Instance.HasStage(ProcessingStage.InboundPostSave))
                    {
                        ContentProcessor.Instance.Process(submissionModel.MessageContent, ProcessingStage.InboundPostSave, submissionModel);
                    }
                }
            }
            
            // null is returned if no errors were raised
            return null;
        }
Esempio n. 19
0
        public async Task<ActionResult> ToggleNightMode()
        {
            string newTheme = "light";
            // save changes
            using (var db = new voatEntities())
            {
                var userPreferences = db.Userpreferences.Find(User.Identity.Name);

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

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

            UserHelper.SetUserStylePreferenceCookie(newTheme);
            Response.StatusCode = 200;
            return Json("Toggled Night Mode", JsonRequestBehavior.AllowGet);
        }
Esempio n. 20
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)
        {
            if (!ModelState.IsValid) return View("Manage", model);
            
            // save changes
            string newTheme;
            using (var db = new voatEntities())
            {
                var userPreferences = db.Userpreferences.Find(User.Identity.Name);

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

                    await db.SaveChangesAsync();
                    newTheme = userPreferences.Night_mode ? "dark" : "light";
                }
                else
                {
                    // create a new record for this user in userpreferences table
                    var tmpModel = new Userpreference
                    {
                        Disable_custom_css = model.Disable_custom_css ? true : false,
                        Night_mode = model.Night_mode ? true : false,
                        Language = "en",
                        Clicking_mode = model.OpenLinksInNewTab ? true : false,
                        Enable_adult_content = model.Enable_adult_content ? true : false,
                        Public_votes = false,
                        Public_subscriptions = model.Public_subscriptions ? true : false,
                        Topmenu_from_subscriptions = model.Topmenu_from_subscriptions,
                        Username = User.Identity.Name
                    };
                    db.Userpreferences.Add(tmpModel);

                    await db.SaveChangesAsync();
                    newTheme = tmpModel.Night_mode ? "dark" : "light";
                }
            }

            UserHelper.SetUserStylePreferenceCookie(newTheme);
            return RedirectToAction("Manage");
        }
Esempio n. 21
0
        public ActionResult UserPreferences()
        {
            try
            {
                using (var db = new voatEntities())
                {
                    var userPreferences = db.Userpreferences.Find(User.Identity.Name);

                    if (userPreferences != null)
                    {
                        // load existing preferences and return to view engine
                        var tmpModel = new UserPreferencesViewModel
                        {
                            Disable_custom_css = userPreferences.Disable_custom_css,
                            Night_mode = userPreferences.Night_mode,
                            OpenLinksInNewTab = userPreferences.Clicking_mode,
                            Enable_adult_content = userPreferences.Enable_adult_content,
                            Public_subscriptions = userPreferences.Public_subscriptions,
                            Topmenu_from_subscriptions = userPreferences.Topmenu_from_subscriptions
                        };

                        return PartialView("_UserPreferences", tmpModel);
                    }
                    else
                    {
                        var tmpModel = new UserPreferencesViewModel();
                        return PartialView("_UserPreferences", tmpModel);
                    }
                }
            }
            catch (Exception)
            {
                return new EmptyResult();
            }
        }
Esempio n. 22
0
        public async Task<ActionResult> UserPreferencesAbout([Bind(Include = "Shortbio, Avatarfile")] UserAboutViewModel model)
        {
            // save changes
            using (var db = new voatEntities())
            {
                var userPreferences = db.Userpreferences.Find(User.Identity.Name);
                var tmpModel = new Userpreference();

                if (userPreferences == null)
                {
                    // create a new record for this user in userpreferences table
                    tmpModel.Shortbio = model.Shortbio;
                    tmpModel.Username = User.Identity.Name;
                }

                if (model.Avatarfile != null && model.Avatarfile.ContentLength > 0)
                {
                    // check uploaded file size is < 300000 bytes (300 kilobytes)
                    if (model.Avatarfile.ContentLength < 300000)
                    {
                        try
                        {
                            using (var img = Image.FromStream(model.Avatarfile.InputStream))
                            {
                                if (img.RawFormat.Equals(ImageFormat.Jpeg) || img.RawFormat.Equals(ImageFormat.Png))
                                {
                                    // resize uploaded file
                                    var thumbnailResult = await ThumbGenerator.GenerateAvatar(img, User.Identity.Name, model.Avatarfile.ContentType);
                                    if (thumbnailResult)
                                    {
                                        if (userPreferences == null)
                                        {
                                            tmpModel.Avatar = User.Identity.Name + ".jpg";
                                        }
                                        else
                                        {
                                            userPreferences.Avatar = User.Identity.Name + ".jpg";
                                        }
                                    }
                                    else
                                    {
                                        // unable to generate thumbnail
                                        ModelState.AddModelError("", "Uploaded file is not recognized as a valid image.");
                                        return RedirectToAction("Manage", new { Message = ManageMessageId.InvalidFileFormat });
                                    }
                                }
                                else
                                {
                                    // uploaded file was invalid
                                    ModelState.AddModelError("", "Uploaded file is not recognized as an image.");
                                    return RedirectToAction("Manage", new { Message = ManageMessageId.InvalidFileFormat });
                                }
                            }
                        }
                        catch (Exception)
                        {
                            // uploaded file was invalid
                            ModelState.AddModelError("", "Uploaded file is not recognized as an image.");
                            return RedirectToAction("Manage", new { Message = ManageMessageId.InvalidFileFormat });
                        }
                    }
                    else
                    {
                        // refuse to save the file and explain why
                        ModelState.AddModelError("", "Uploaded image may not exceed 300 kb, please upload a smaller image.");
                        return RedirectToAction("Manage", new { Message = ManageMessageId.UploadedFileToolarge });
                    }
                }

                if (userPreferences == null)
                {
                    db.Userpreferences.Add(tmpModel);
                    await db.SaveChangesAsync();
                }
                else
                {
                    userPreferences.Shortbio = model.Shortbio;
                    userPreferences.Username = User.Identity.Name;
                    await db.SaveChangesAsync();
                }

            }

            return RedirectToAction("Manage");
        }
Esempio n. 23
0
        public ActionResult UserPreferencesAbout()
        {
            try
            {
                using (var db = new voatEntities())
                {
                    var userPreferences = db.Userpreferences.Find(User.Identity.Name);

                    if (userPreferences != null)
                    {
                        // load existing preferences and return to view engine
                        var tmpModel = new UserAboutViewModel()
                        {
                            Shortbio = userPreferences.Shortbio,
                            Avatar = userPreferences.Avatar
                        };

                        return PartialView("_UserPreferencesAbout", tmpModel);
                    }
                    else
                    {
                        var tmpModel = new UserAboutViewModel();
                        return PartialView("_UserPreferencesAbout", tmpModel);
                    }
                }
            }
            catch (Exception)
            {
                return new EmptyResult();
            }
        }
Esempio n. 24
0
        // a method to send a private message to a user, invoked by other methods
        public static bool SendPrivateMessage(string sender, string recipientList, string subject, string body)
        {
            if (Voat.Utilities.UserHelper.IsUserGloballyBanned(System.Web.HttpContext.Current.User.Identity.Name))
            {
                return false;
            }

            List<PrivateMessage> messages = new List<PrivateMessage>();
            MatchCollection col = Regex.Matches(recipientList, @"((?'prefix'@|u/|/u/|v/|/v/)?(?'recipient'[\w-.]+))", RegexOptions.IgnoreCase);

            foreach (Match m in col)
            {
                var recipient = m.Groups["recipient"].Value;
                var prefix = m.Groups["prefix"].Value;

                if (!String.IsNullOrEmpty(prefix) && prefix.ToLower().Contains("v"))
                {
                    //don't allow banned users to send to subverses
                    if (!UserHelper.IsUserBannedFromSubverse(System.Web.HttpContext.Current.User.Identity.Name, recipient))
                    {
                        //send to subverse mods
                        using (var db = new voatEntities())
                        {
                            //designed to limit abuse by taking the level 1 mod and the next four oldest
                            var mods = (from mod in db.SubverseModerators
                                        where mod.Subverse.Equals(recipient, StringComparison.OrdinalIgnoreCase) && mod.UserName != "system" && mod.UserName != "youcanclaimthissub"
                                        orderby mod.Power ascending, mod.CreationDate descending
                                        select mod).Take(5);

                            foreach (var moderator in mods)
                            {
                                messages.Add(new PrivateMessage
                                {
                                    Sender = sender,
                                    Recipient = moderator.UserName,
                                    CreationDate = DateTime.Now,
                                    Subject = String.Format("[v/{0}] {1}", recipient, subject),
                                    Body = body,
                                    IsUnread = true,
                                    MarkedAsUnread = true
                                });
                            }
                        }
                    }
                }
                else
                {
                    //ensure proper cased
                    recipient = UserHelper.OriginalUsername(recipient);

                    if (Voat.Utilities.UserHelper.UserExists(recipient))
                    {
                        messages.Add(new PrivateMessage
                        {
                            Sender = sender,
                            Recipient = recipient,
                            CreationDate = DateTime.Now,
                            Subject = subject,
                            Body = body,
                            IsUnread = true,
                            MarkedAsUnread = true
                        });
                    }
                }
            }

            if (messages.Count > 0)
            {
                using (var db = new voatEntities())
                {
                    try
                    {
                        db.PrivateMessages.AddRange(messages);
                        db.SaveChanges();
                    }
                    catch (Exception)
                    {
                        return false;
                    }
                }
            }
            return true;
        }
Esempio n. 25
0
File: Voting.cs Progetto: rnand/voat
        // submit submission downvote
        public static void DownvoteSubmission(int submissionID, string userName, string clientIp)
        {
            //int result = CheckIfVoted(userWhichDownvoted, submissionId);

            using (var db = new voatEntities())
            {
                Submission submission = db.Submissions.Find(submissionID);

                SubmissionVoteTracker previousVote = db.SubmissionVoteTrackers.Where(u => u.UserName == userName && u.SubmissionID == submissionID).FirstOrDefault();

                // do not execute downvoting if subverse is in anonymized mode
                if (submission.IsAnonymized)
                {
                    return;
                }

                // do not execute downvoting if user has insufficient CCP for target subverse
                if (Karma.CommentKarmaForSubverse(userName, submission.Subverse) < submission.Subverse1.MinCCPForDownvote)
                {
                    return;
                }

                int result = (previousVote == null ? 0 : previousVote.VoteStatus.Value);

                switch (result)
                {
                    // never voted before
                    case 0:
                        {
                            // this user is downvoting more than upvoting, don't register the downvote
                            if (UserHelper.IsUserCommentVotingMeanie(userName))
                            {
                                return;
                            }

                            // check if this IP already voted on the same submission, abort voting if true
                            var ipVotedAlready = db.SubmissionVoteTrackers.Where(x => x.SubmissionID == submissionID && x.IPAddress == clientIp);
                            if (ipVotedAlready.Any()) return;

                            submission.DownCount++;

                            double currentScore = submission.UpCount - submission.DownCount;
                            double submissionAge = Submissions.CalcSubmissionAgeDouble(submission.CreationDate);
                            double newRank = Ranking.CalculateNewRank(submission.Rank, submissionAge, currentScore);

                            submission.Rank = newRank;

                            // register downvote
                            var tmpVotingTracker = new SubmissionVoteTracker
                            {
                                SubmissionID = submissionID,
                                UserName = userName,
                                VoteStatus = -1,
                                CreationDate = DateTime.Now,
                                IPAddress = clientIp
                            };
                            db.SubmissionVoteTrackers.Add(tmpVotingTracker);
                            db.SaveChanges();

                            SendVoteNotification(submission.UserName, "downvote");
                        }

                        break;

                    // upvoted before, turn upvote to downvote
                    case 1:
                        {
                            submission.UpCount--;
                            submission.DownCount++;

                            double currentScore = submission.UpCount - submission.DownCount;
                            double submissionAge = Submissions.CalcSubmissionAgeDouble(submission.CreationDate);
                            double newRank = Ranking.CalculateNewRank(submission.Rank, submissionAge, currentScore);

                            submission.Rank = newRank;

                            // register Turn DownVote To UpVote
                            var votingTracker = db.SubmissionVoteTrackers.FirstOrDefault(b => b.SubmissionID == submissionID && b.UserName == userName);

                            previousVote.VoteStatus = -1;
                            previousVote.CreationDate = DateTime.Now;

                            db.SaveChanges();

                            SendVoteNotification(submission.UserName, "uptodownvote");
                        }

                        break;

                    // downvoted before, reset
                    case -1:
                        {
                            //ResetMessageVote(userName, submissionID);
                            submission.DownCount--;

                            double currentScore = submission.UpCount - submission.DownCount;
                            double submissionAge = Submissions.CalcSubmissionAgeDouble(submission.CreationDate);
                            double newRank = Ranking.CalculateNewRank(submission.Rank, submissionAge, currentScore);

                            submission.Rank = newRank;
                            db.SubmissionVoteTrackers.Remove(previousVote);
                            db.SaveChanges();

                            SendVoteNotification(submission.UserName, "upvote");
                        }

                        break;
                }
            }
        }
Esempio n. 26
0
File: Voting.cs Progetto: rnand/voat
        // submit submission upvote
        public static void UpvoteSubmission(int submissionID, string userName, string clientIp)
        {
            //// user account voting check
            //int result = CheckIfVoted(userName, submissionID);

            using (var db = new voatEntities())
            {

                SubmissionVoteTracker previousVote = db.SubmissionVoteTrackers.Where(u => u.UserName == userName && u.SubmissionID == submissionID).FirstOrDefault();

                Submission submission = db.Submissions.Find(submissionID);

                if (submission.IsAnonymized)
                {
                    // do not execute voting, subverse is in anonymized mode
                    return;
                }

                int result = (previousVote == null ? 0 : previousVote.VoteStatus.Value);

                switch (result)
                {
                    // never voted before
                    case 0:

                        if (submission.UserName != userName)
                        {
                            // check if this IP already voted on the same submission, abort voting if true
                            var ipVotedAlready = db.SubmissionVoteTrackers.Where(x => x.SubmissionID == submissionID && x.IPAddress == clientIp);
                            if (ipVotedAlready.Any()) return;

                            submission.UpCount++;
                            double currentScore = submission.UpCount - submission.DownCount;
                            double submissionAge = Submissions.CalcSubmissionAgeDouble(submission.CreationDate);
                            double newRank = Ranking.CalculateNewRank(submission.Rank, submissionAge, currentScore);
                            submission.Rank = newRank;

                            // register upvote
                            var tmpVotingTracker = new SubmissionVoteTracker
                            {
                                SubmissionID = submissionID,
                                UserName = userName,
                                VoteStatus = 1,
                                CreationDate = DateTime.Now,
                                IPAddress = clientIp
                            };

                            db.SubmissionVoteTrackers.Add(tmpVotingTracker);
                            db.SaveChanges();

                            SendVoteNotification(submission.UserName, "upvote");
                        }

                        break;

                    // downvoted before, turn downvote to upvote
                    case -1:

                        if (submission.UserName != userName)
                        {
                            submission.UpCount++;
                            submission.DownCount--;

                            double currentScore = submission.UpCount - submission.DownCount;
                            double submissionAge = Submissions.CalcSubmissionAgeDouble(submission.CreationDate);
                            double newRank = Ranking.CalculateNewRank(submission.Rank, submissionAge, currentScore);
                            submission.Rank = newRank;

                            previousVote.VoteStatus = 1;
                            previousVote.CreationDate = DateTime.Now;

                            db.SaveChanges();

                            SendVoteNotification(submission.UserName, "downtoupvote");
                        }

                        break;

                    // upvoted before, reset
                    case 1:
                        {
                            submission.UpCount--;

                            double currentScore = submission.UpCount - submission.DownCount;
                            double submissionAge = Submissions.CalcSubmissionAgeDouble(submission.CreationDate);
                            double newRank = Ranking.CalculateNewRank(submission.Rank, submissionAge, currentScore);

                            submission.Rank = newRank;
                            db.SubmissionVoteTrackers.Remove(previousVote);
                            db.SaveChanges();

                            //ResetMessageVote(userName, submissionID);

                            SendVoteNotification(submission.UserName, "downvote");
                        }

                        break;
                }
            }
        }
Esempio n. 27
0
        // a user has either upvoted or downvoted this submission earlier and wishes to reset the vote, delete the record
        public static void ResetCommentVote(string userWhichVoted, int commentId)
        {
            using (var db = new voatEntities())
            {
                var votingTracker = db.CommentVoteTrackers.FirstOrDefault(b => b.CommentID == commentId && b.UserName == userWhichVoted);

                if (votingTracker == null) return;
                // delete vote history
                db.CommentVoteTrackers.Remove(votingTracker);
                db.SaveChanges();
            }
        }
Esempio n. 28
0
        // submit comment upvote
        public static void UpvoteComment(int commentId, string userWhichUpvoted, string clientIpHash)
        {
            int result = CheckIfVotedComment(userWhichUpvoted, commentId);

            using (voatEntities db = new voatEntities())
            {
                Comment comment = db.Comments.Find(commentId);

                if (comment.Submission.IsAnonymized)
                {
                    // do not execute voting, subverse is in anonymized mode
                    return;
                }                

                switch (result)
                {
                    // never voted before
                    case 0:

                        if (comment.UserName != userWhichUpvoted)
                        {
                            // check if this IP already voted on the same comment, abort voting if true
                            var ipVotedAlready = db.CommentVoteTrackers.Where(x => x.CommentID == commentId && x.IPAddress == clientIpHash);
                            if (ipVotedAlready.Any()) return;

                            comment.UpCount++;

                            // register upvote
                            var tmpVotingTracker = new CommentVoteTracker
                            {
                                CommentID = commentId,
                                UserName = userWhichUpvoted,
                                VoteStatus = 1,
                                CreationDate = DateTime.Now,
                                IPAddress = clientIpHash
                            };
                            db.CommentVoteTrackers.Add(tmpVotingTracker);
                            db.SaveChanges();

                            Voting.SendVoteNotification(comment.UserName, "upvote");
                        }

                        break;

                    // downvoted before, turn downvote to upvote
                    case -1:

                        if (comment.UserName != userWhichUpvoted)
                        {
                            comment.UpCount++;
                            comment.DownCount--;

                            // register Turn DownVote To UpVote
                            var votingTracker = db.CommentVoteTrackers.FirstOrDefault(b => b.CommentID == commentId && b.UserName == userWhichUpvoted);

                            if (votingTracker != null)
                            {
                                votingTracker.VoteStatus = 1;
                                votingTracker.CreationDate = DateTime.Now;
                            }
                            db.SaveChanges();

                            Voting.SendVoteNotification(comment.UserName, "downtoupvote");
                        }

                        break;

                    // upvoted before, reset
                    case 1:

                        comment.UpCount--;
                        db.SaveChanges();

                        Voting.SendVoteNotification(comment.UserName, "downvote");

                        ResetCommentVote(userWhichUpvoted, commentId);

                        break;
                }
            }

        }
Esempio n. 29
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 voatEntities())
            {
                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();
            }
        }
Esempio n. 30
0
        public static async Task SendCommentNotification(Comment comment, Action<string> onSuccess)
        {
            try 
            { 
                using (var _db = new voatEntities())
                {
                    Random _rnd = new Random();

                    if (comment.ParentId != null && comment.CommentContent != null)
                    {
                        // find the parent comment and its author
                        var parentComment = _db.Comments.Find(comment.ParentId);
                        if (parentComment != null)
                        {
                            // check if recipient exists
                            if (UserHelper.UserExists(parentComment.Name))
                            {
                                // do not send notification if author is the same as comment author
                                if (parentComment.Name != HttpContext.Current.User.Identity.Name)
                                {
                                    // send the message

                                    var submission = DataCache.Submission.Retrieve(comment.MessageId);
                                    if (submission != null)
                                    {
                                        var subverse = DataCache.Subverse.Retrieve(submission.Subverse);

                                        var commentReplyNotification = new Commentreplynotification();
                                        commentReplyNotification.CommentId = comment.Id;
                                        commentReplyNotification.SubmissionId = submission.Id;
                                        commentReplyNotification.Recipient = parentComment.Name;
                                        if (submission.Anonymized || subverse.anonymized_mode)
                                        {
                                            commentReplyNotification.Sender = _rnd.Next(10000, 20000).ToString(CultureInfo.InvariantCulture);
                                        }
                                        else
                                        {
                                            commentReplyNotification.Sender = HttpContext.Current.User.Identity.Name;
                                        }
                                        commentReplyNotification.Body = comment.CommentContent;
                                        commentReplyNotification.Subverse = subverse.name;
                                        commentReplyNotification.Status = true;
                                        commentReplyNotification.Timestamp = DateTime.Now;

                                        // self = type 1, url = type 2
                                        commentReplyNotification.Subject = submission.Type == 1 ? submission.Title : submission.Linkdescription;

                                        _db.Commentreplynotifications.Add(commentReplyNotification);

                                        await _db.SaveChangesAsync();

                                        if (onSuccess != null)
                                        {
                                            onSuccess(commentReplyNotification.Recipient);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        // comment reply is sent to a root comment which has no parent id, trigger post reply notification
                        var submission = DataCache.Submission.Retrieve(comment.MessageId);
                        if (submission != null)
                        {
                            // check if recipient exists
                            if (UserHelper.UserExists(submission.Name))
                            {
                                // do not send notification if author is the same as comment author
                                if (submission.Name != HttpContext.Current.User.Identity.Name)
                                {
                                    // send the message
                                    var postReplyNotification = new Postreplynotification();

                                    postReplyNotification.CommentId = comment.Id;
                                    postReplyNotification.SubmissionId = submission.Id;
                                    postReplyNotification.Recipient = submission.Name;
                                    var subverse = DataCache.Subverse.Retrieve(submission.Subverse);
                                    if (submission.Anonymized || subverse.anonymized_mode)
                                    {
                                        postReplyNotification.Sender = _rnd.Next(10000, 20000).ToString(CultureInfo.InvariantCulture);
                                    }
                                    else
                                    {
                                        postReplyNotification.Sender = HttpContext.Current.User.Identity.Name;
                                    }

                                    postReplyNotification.Body = comment.CommentContent;
                                    postReplyNotification.Subverse = submission.Subverse;
                                    postReplyNotification.Status = true;
                                    postReplyNotification.Timestamp = DateTime.Now;

                                    // self = type 1, url = type 2
                                    postReplyNotification.Subject = submission.Type == 1 ? submission.Title : submission.Linkdescription;

                                    _db.Postreplynotifications.Add(postReplyNotification);

                                    await _db.SaveChangesAsync();

                                    if (onSuccess != null)
                                    {
                                        onSuccess(postReplyNotification.Recipient);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }