private UserPreference GetUserPreference(VoatOutOfRepositoryDataContextAccessor context) { var userPreferences = context.UserPreference.Find(User.Identity.Name); if (userPreferences == null) { userPreferences = new UserPreference(); userPreferences.UserName = User.Identity.Name; Repository.SetDefaultUserPreferences(userPreferences); context.UserPreference.Add(userPreferences); } return(userPreferences); }
public async Task <IViewComponentResult> InvokeAsync(DomainReference domainReference) { var cacheData = CacheHandler.Instance.Register("legacy:TopViewedSubmissions24Hours", new Func <object>(() => { using (var db = new VoatOutOfRepositoryDataContextAccessor(CONSTANTS.CONNECTION_READONLY)) { var startDate = Repository.CurrentDate.Add(new TimeSpan(0, -24, 0, 0, 0)); IQueryable <Data.Models.Submission> submissions = (from message in db.Submission join subverse in db.Subverse on message.Subverse equals subverse.Name where message.ArchiveDate == null && !message.IsDeleted && subverse.IsPrivate != true && subverse.IsAdminPrivate != true && subverse.IsAdult == false && message.CreationDate >= startDate && message.CreationDate <= Repository.CurrentDate where !(from bu in db.BannedUser select bu.UserName).Contains(message.UserName) where !subverse.IsAdminDisabled.Value //where !(from ubs in _db.UserBlockedSubverses where ubs.Subverse.Equals(subverse.Name) select ubs.UserName).Contains(User.Identity.Name) select message).OrderByDescending(s => s.Views).Take(5).AsQueryable(); //select message).OrderByDescending(s => s.Views).DistinctBy(m => m.Subverse).Take(5).AsQueryable().AsNoTracking(); return(submissions.ToList()); } }), TimeSpan.FromMinutes(60), 5); return(View(cacheData)); }
// return user statistics for user profile overview public static UserStatsModel UserStatsModel(string userName) { var loadFunc = new Func <UserStatsModel>(() => { var userStatsModel = new UserStatsModel(); using (var db = new VoatOutOfRepositoryDataContextAccessor()) { // 5 subverses user submitted to most var subverses = db.Submission.Where(a => a.UserName == userName && !a.IsAnonymized && !a.IsDeleted) .GroupBy(a => new { a.UserName, a.Subverse }) .Select(g => new SubverseStats { SubverseName = g.Key.Subverse, Count = g.Count() }) .OrderByDescending(s => s.Count) .Take(5) .ToList(); // total comment count var comments = db.Comment.Count(a => a.UserName == userName && !a.IsDeleted); // voting habits var userData = new Domain.UserData(userName); var commentUpvotes = userData.Information.CommentVoting.UpCount; var commentDownvotes = userData.Information.CommentVoting.DownCount; var submissionUpvotes = userData.Information.SubmissionVoting.UpCount; var submissionDownvotes = userData.Information.SubmissionVoting.DownCount; //var commentUpvotes = db.CommentVoteTrackers.Count(a => a.UserName == userName && a.VoteStatus == 1); //var commentDownvotes = db.CommentVoteTrackers.Count(a => a.UserName == userName && a.VoteStatus == -1); //var submissionUpvotes = db.SubmissionVoteTrackers.Count(a => a.UserName == userName && a.VoteStatus == 1); //var submissionDownvotes = db.SubmissionVoteTrackers.Count(a => a.UserName == userName && a.VoteStatus == -1); // get 3 highest rated comments var highestRatedComments = db.Comment .Include(x => x.Submission) .Where(a => a.UserName == userName && !a.IsAnonymized && !a.IsDeleted) .OrderByDescending(s => s.UpCount - s.DownCount) .Take(3) .ToList(); // get 3 lowest rated comments var lowestRatedComments = db.Comment .Include(x => x.Submission) .Where(a => a.UserName == userName && !a.IsAnonymized && !a.IsDeleted) .OrderBy(s => s.UpCount - s.DownCount) .Take(3) .ToList(); var linkSubmissionsCount = db.Submission.Count(a => a.UserName == userName && a.Type == 2 && !a.IsDeleted && !a.IsAnonymized); var messageSubmissionsCount = db.Submission.Count(a => a.UserName == userName && a.Type == 1 && !a.IsDeleted && !a.IsAnonymized); // get 5 highest rated submissions var highestRatedSubmissions = db.Submission.Where(a => a.UserName == userName && !a.IsAnonymized && !a.IsDeleted) .OrderByDescending(s => s.UpCount - s.DownCount) .Take(5) .ToList(); // get 5 lowest rated submissions var lowestRatedSubmissions = db.Submission.Where(a => a.UserName == userName && !a.IsAnonymized && !a.IsDeleted) .OrderBy(s => s.UpCount - s.DownCount) .Take(5) .ToList(); userStatsModel.TopSubversesUserContributedTo = subverses; userStatsModel.LinkSubmissionsSubmitted = linkSubmissionsCount; userStatsModel.MessageSubmissionsSubmitted = messageSubmissionsCount; userStatsModel.LowestRatedSubmissions = lowestRatedSubmissions; userStatsModel.HighestRatedSubmissions = highestRatedSubmissions; userStatsModel.TotalCommentsSubmitted = comments; userStatsModel.HighestRatedComments = highestRatedComments; userStatsModel.LowestRatedComments = lowestRatedComments; userStatsModel.TotalCommentsUpvoted = commentUpvotes; userStatsModel.TotalCommentsDownvoted = commentDownvotes; userStatsModel.TotalSubmissionsUpvoted = submissionUpvotes; userStatsModel.TotalSubmissionsDownvoted = submissionDownvotes; ////HACK: EF causes JSON to StackOverflow on the highest/lowest comments because of the nested loading EF does with the include option, therefore null the refs here. //highestRatedComments.ForEach(x => x.Submission.Comments = null); //lowestRatedComments.ForEach(x => x.Submission.Comments = null); } return(userStatsModel); }); var cachedData = CacheHandler.Instance.Register(CachingKey.UserOverview(userName), loadFunc, TimeSpan.FromMinutes(30)); return(cachedData); }
private AdViewModel GetAdModel(string subverse, bool useExisting = false) { var linkToAdPurchase = String.Format("[Want to advertize on {1}?]({0})", Url.Action("Advertize", "Home"), VoatSettings.Instance.SiteName); //Default add var adToDisplay = new AdViewModel { Name = $"Advertize on {VoatSettings.Instance.SiteName}", DestinationUrl = Url.Action("Advertize", "Home"), Description = linkToAdPurchase, GraphicUrl = Url.Content("~/images/voat-ad-placeholder.png") }; try { using (var db = new VoatOutOfRepositoryDataContextAccessor()) { var ad = (from x in db.Ad where ((subverse != null && subverse.ToLower() == subverse.ToLower() || (x.Subverse == null))) && (x.EndDate >= Repository.CurrentDate && x.StartDate <= Repository.CurrentDate) && x.IsActive orderby x.Subverse descending select x).FirstOrDefault(); if (ad != null) { adToDisplay = new AdViewModel { Name = ad.Name, DestinationUrl = ad.DestinationUrl, Description = String.Format("{0}\n\n\n\n{1}", ad.Description, linkToAdPurchase), GraphicUrl = ad.GraphicUrl }; } else if (useExisting) { { var ads = CacheHandler.Instance.Register(CachingKey.AdCache(), new Func <IList <Ad> >(() => { using (var dbcontext = new VoatOutOfRepositoryDataContextAccessor()) { var adCache = (from x in dbcontext.Ad where x.Subverse == null && x.IsActive select x).ToList(); return(adCache); } }), TimeSpan.FromMinutes(60)); if (ads != null && ads.Count > 0) { //pick random index Random m = new Random(); var index = m.Next(0, ads.Count - 1); ad = ads[index]; adToDisplay = new AdViewModel { Name = ad.Name, DestinationUrl = ad.DestinationUrl, Description = String.Format("{0}\n\n\n\n{1}", ad.Description, linkToAdPurchase), GraphicUrl = ad.GraphicUrl }; } } } } } catch (Exception ex) { /*no-op - ensure that ads don't throw exceptions */ } return(adToDisplay); }
public async Task <ActionResult> UserPreferencesAbout([Bind("Bio, Avatarfile")] UserAboutViewModel model) { if (!ModelState.IsValid) { return(View("Manage", model)); } ViewBag.UserName = User.Identity.Name; string avatarKey = null; //ThumbGenerator.GenerateThumbnail if (model.Avatarfile != null) { try { var stream = model.Avatarfile.OpenReadStream(); var result = await ThumbGenerator.GenerateAvatar(stream, model.Avatarfile.FileName, model.Avatarfile.ContentType); if (result.Success) { avatarKey = result.Response; } else { ModelState.AddModelError("Avatarfile", result.Message); return(View("Manage", model)); } } catch (Exception ex) { ModelState.AddModelError("Avatarfile", "Uploaded file is not recognized as a valid image."); return(RedirectToAction("Manage", new { Message = ManageMessageId.InvalidFileFormat })); } } var bio = model.Bio.TrimSafe(); //This is a hack var context = new VoatOutOfRepositoryDataContextAccessor(); using (var repo = new Repository(User, context)) { var p = await repo.GetUserPreferences(User.Identity.Name); if (bio != p.Bio) { if (String.IsNullOrEmpty(bio)) { p.Bio = "I tried to delete my bio but they gave me this instead"; } else if (bio == STRINGS.DEFAULT_BIO) { p.Bio = null; } else { p.Bio = bio; } } if (!String.IsNullOrEmpty(avatarKey)) { p.Avatar = avatarKey; } await context.SaveChangesAsync(); } /* * using (var db = new VoatUIDataContextAccessor()) * { * var userPreferences = GetUserPreference(db); * * 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) * { * 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 }); * } * } * * var bio = model.Bio.TrimSafe(); * * if (String.IsNullOrEmpty(bio)) * { * userPreferences.Bio = "I tried to delete my bio but they gave me this instead"; * } * else if (bio == STRINGS.DEFAULT_BIO) * { * userPreferences.Bio = null; * } * else * { * userPreferences.Bio = bio; * } * await db.SaveChangesAsync(); * } */ ClearUserCache(); return(RedirectToAction("Manage")); }
internal static async Task SendCommentReplyNotification(IPrincipal user, Data.Models.Submission submission, Data.Models.Comment comment) { try { using (var _db = new VoatOutOfRepositoryDataContextAccessor()) { Random _rnd = new Random(); if (comment.ParentID != null && comment.Content != null) { // find the parent comment and its author var parentComment = _db.Comment.Find(comment.ParentID); if (parentComment != null) { // check if recipient exists if (UserHelper.UserExists(parentComment.UserName)) { // do not send notification if author is the same as comment author if (parentComment.UserName != comment.UserName) { // send the message //BlockedUser Implementation - Comment Reply if (!MesssagingUtility.IsSenderBlocked(comment.UserName, parentComment.UserName)) { //var submission = DataCache.Submission.Retrieve(comment.SubmissionID); //var q = new QuerySubmission(comment.SubmissionID.Value); //var submission = await q.ExecuteAsync().ConfigureAwait(CONSTANTS.AWAIT_CAPTURE_CONTEXT); if (submission != null) { //var subverse = DataCache.Subverse.Retrieve(submission.Subverse); var message = new Domain.Models.Message(); message.IsAnonymized = submission.IsAnonymized; message.Recipient = parentComment.UserName; message.RecipientType = Domain.Models.IdentityType.User; message.Sender = comment.UserName; message.SenderType = Domain.Models.IdentityType.User; message.Subverse = submission.Subverse; message.SubmissionID = submission.ID; message.CommentID = comment.ID; message.Type = Domain.Models.MessageType.CommentReply; message.CreationDate = Repository.CurrentDate; using (var repo = new Repository(user)) { var response = await repo.SendMessage(message); if (response.Success) { EventNotification.Instance.SendMessageNotice(message.Recipient, message.Sender, Domain.Models.MessageTypeFlag.CommentReply, Domain.Models.ContentType.Comment, comment.ID); } } } } } } } } } } catch (Exception ex) { throw ex; } }