public async Task <ActionResult> SubverseSettings([Bind(Include = "Name, Description, Sidebar, Stylesheet")] Subverse subverseToEdit) { try { if (ModelState.IsValid) { var existingSubverse = db.Subverses.Find(subverseToEdit.name); //check if subverse exists before attempting to edit it if (existingSubverse != null) { existingSubverse.description = subverseToEdit.description; existingSubverse.sidebar = subverseToEdit.sidebar; existingSubverse.stylesheet = subverseToEdit.stylesheet; await db.SaveChangesAsync(); //go back to this subverse return(RedirectToAction("Index", "Subverses", new { subversetoshow = subverseToEdit.name })); } else { ModelState.AddModelError(string.Empty, "Sorry, The subverse you are trying to edit does not exist."); return(View()); } } else { return(View()); } } catch (Exception) { ModelState.AddModelError(string.Empty, "Something bad happened."); return(View()); } }
public static bool ContentContainsBannedDomain(string subverse, string contentToEvaluate) { if (!String.IsNullOrEmpty(contentToEvaluate)) { Subverse s = null; if (!String.IsNullOrEmpty(subverse)) { s = DataCache.Subverse.Retrieve(subverse); } if (s == null || (s != null && !s.ExcludeSitewideBans)) { List <string> domains = new List <string>(); ProcessMatches(Regex.Matches(contentToEvaluate, CONSTANTS.PROTOCOL_LESS_LINK_REGEX, RegexOptions.IgnoreCase), domains); if (domains.Count > 0) { bool hasBannedDomainLinks = BanningUtility.IsDomainBanned(domains.ToArray()); if (hasBannedDomainLinks) { return(true); } } } } return(false); }
public static bool ContentContainsBannedDomain(string subverse, string contentToEvaluate) { if (!String.IsNullOrEmpty(contentToEvaluate)) { Subverse s = null; if (!String.IsNullOrEmpty(subverse)) { s = DataCache.Subverse.Retrieve(subverse); } if (s == null || (s != null && !s.ExcludeSitewideBans)) { MatchCollection matches = Regex.Matches(contentToEvaluate, CONSTANTS.HTTP_LINK_REGEX, RegexOptions.IgnoreCase); List <string> domains = new List <string>(); foreach (Match match in matches) { string domain = match.Groups["domain"].Value.ToLower(); if (!String.IsNullOrWhiteSpace(domain) && !domains.Contains(domain)) { domains.Add(domain); } } if (domains.Count > 0) { bool hasBannedDomainLinks = BanningUtility.IsDomainBanned(domains.ToArray()); if (hasBannedDomainLinks) { return(true); } } } } return(false); }
public ActionResult @New(int?page, string subversetoshow, string sortingmode) { //sortingmode: new, contraversial, hot, etc ViewBag.SortingMode = sortingmode; ViewBag.SelectedSubverse = subversetoshow; int pageSize = 25; int pageNumber = (page ?? 1); ViewBag.Title = subversetoshow; if (subversetoshow != "all") { //check if subverse exists, if not, send to a page not found error Subverse subverse = db.Subverses.Find(subversetoshow); if (subverse != null) { var submissions = db.Messages.Where(x => x.Subverse == subversetoshow && x.Name != "deleted").OrderByDescending(s => s.Date).ToList(); return(View("Index", submissions.ToPagedList(pageNumber, pageSize))); } else { return(View("~/Views/Errors/Subversenotfound.cshtml")); } } else { //if selected subverse is ALL, show submissions from all subverses, sorted by date var submissions = db.Messages .Where(x => x.Name != "deleted") .OrderByDescending(s => s.Date).ToList(); return(View("Index", submissions.ToPagedList(pageNumber, pageSize))); } }
// subscribe to a subverse public static void SubscribeToSubverse(string userName, string subverse) { if (IsUserSubverseSubscriber(userName, subverse)) { return; } using (var db = new voatEntities()) { // add a new subscription var newSubscription = new SubverseSubscription { UserName = userName, Subverse = subverse }; db.SubverseSubscriptions.Add(newSubscription); // record new subscription in subverse table subscribers field Subverse tmpSubverse = db.Subverses.Find(subverse); if (tmpSubverse != null) { tmpSubverse.SubscriberCount++; } db.SaveChanges(); } }
// unsubscribe from a subverse public static void UnSubscribeFromSubverse(string userName, string subverse) { if (IsUserSubverseSubscriber(userName, subverse)) { using (var db = new voatEntities()) { var subscription = db.SubverseSubscriptions.FirstOrDefault(b => b.UserName == userName && b.Subverse == subverse); if (subverse == null) { return; } // remove subscription record db.SubverseSubscriptions.Remove(subscription); // record new unsubscription in subverse table subscribers field Subverse tmpSubverse = db.Subverses.Find(subverse); if (tmpSubverse != null) { tmpSubverse.SubscriberCount--; } db.SaveChanges(); } } }
// unsubscribe from a subverse public static void UnSubscribeFromSubverse(string userName, string subverse) { if (IsUserSubverseSubscriber(userName, subverse)) { using (whoaverseEntities db = new whoaverseEntities()) { var subscription = db.Subscriptions .Where(b => b.Username == userName && b.SubverseName == subverse) .FirstOrDefault(); if (subverse != null) { // remove subscription record db.Subscriptions.Remove(subscription); // record new unsubscription in subverse table subscribers field Subverse tmpSubverse = db.Subverses.Find(subverse); if (tmpSubverse != null) { tmpSubverse.subscribers--; } db.SaveChanges(); } } } }
public static Models.SubverseInformation Map(this Subverse subverse) { SubverseInformation result = null; if (subverse != null) { result = new Models.SubverseInformation() { Name = subverse.Name, Title = subverse.Title, Description = subverse.Description, CreationDate = subverse.CreationDate, SubscriberCount = (subverse.SubscriberCount == null ? 0 : subverse.SubscriberCount.Value), Sidebar = subverse.SideBar, //Type = subverse.Type, IsAnonymized = subverse.IsAnonymized, IsAdult = subverse.IsAdult, //IsAdminDisabled = (subverse.IsAdminDisabled.HasValue ? subverse.IsAdminDisabled.Value : false), CreatedBy = subverse.CreatedBy }; result.FormattedSidebar = Formatting.FormatMessage(subverse.SideBar, true); } return(result); }
public async Task <IViewComponentResult> InvokeAsync(DomainReference domainReference, ContentReference contentReference = null) { IViewComponentResult result = View("Default", domainReference); if (domainReference != null) { switch (domainReference.Type) { case DomainType.Subverse: Subverse subverse = null; if (!String.IsNullOrEmpty(domainReference.Name)) { var q = new QuerySubverse(domainReference.Name); subverse = await q.ExecuteAsync(); } if (subverse != null) { var qa = new QueryActiveSessionCount(domainReference); ViewBag.OnlineUsers = await qa.ExecuteAsync(); var view = "Subverse"; // contentReference != null && contentReference.Type == ContentType.Submission ? "Submission" : "Subverse"; if (contentReference != null) { switch (contentReference.Type) { case ContentType.Vote: view = "VoteSubmission"; break; } } result = View(view, subverse); } else { result = View("Default"); } break; case DomainType.User: result = View("User", domainReference); break; case DomainType.Set: var qSet = new QuerySet(domainReference.Name, domainReference.OwnerName); var set = await qSet.ExecuteAsync(); result = View("Set", set); break; } } return(result); return(View("Chat", domainReference)); }
// GET: /set/setId/page // fetch x more items from a set public ActionResult SingleSetPage(int setId, int page) { if (Settings.SetsDisabled) { return(RedirectToAction("UnAuthorized", "Error")); } const int pageSize = 2; try { // get list of subverses for the set // for each subverse, get top ranked submissions var set = _db.UserSets.FirstOrDefault(ds => ds.ID == setId); if (set == null) { return(new HttpStatusCodeResult(HttpStatusCode.NotFound)); } ViewBag.SelectedSubverse = set.Name; var singleSetResultModel = new SingleSetViewModel(); var submissions = new List <SetSubmission>(); foreach (var subverse in set.UserSetLists) { // get 5 top ranked submissions for current subverse Subverse currentSubverse = subverse.Subverse1; if (currentSubverse != null) { // skip parameter could be passed here submissions.AddRange(SetsUtility.TopRankedSubmissionsFromASub(currentSubverse.Name, _db.Submissions, set.Name, pageSize, page * pageSize)); } singleSetResultModel.Name = set.Name; singleSetResultModel.Description = set.Description; singleSetResultModel.Id = set.ID; } singleSetResultModel.SubmissionsList = new List <SetSubmission>(submissions.OrderByDescending(s => s.Rank).ThenByDescending(s => s.CreationDate)); if (submissions.Any()) { ViewBag.Page = page; return(PartialView("~/Views/Sets/_SingleSetPage.cshtml", singleSetResultModel)); } // no more entries found return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } catch (Exception) { throw; } }
// GET: /set/setid // show single set frontpage public ActionResult SingleSet(int setId, int?page) { const int pageSize = 25; int recordsToSkip = (page ?? 0); try { // get list of subverses for the set // for each subverse, get top ranked submissions var set = _db.Usersets.FirstOrDefault(ds => ds.Set_id == setId); if (set == null) { return(RedirectToAction("NotFound", "Error")); } ViewBag.SelectedSubverse = set.Name; var singleSetResultModel = new SingleSetViewModel(); var submissions = new List <SetSubmission>(); // if subs in set count is < 1, don't display the page, instead, check if the user owns this set and give them a chance to add subs to the set if (set.Usersetdefinitions.Count < 1) { // check if the user owns this sub if (User.Identity.IsAuthenticated && User.Identity.Name == set.Created_by) { return(RedirectToAction("EditSet", "Sets", new { setId = set.Set_id })); } } foreach (var subverse in set.Usersetdefinitions) { // get 5 top ranked submissions for current subverse Subverse currentSubverse = subverse.Subvers; if (currentSubverse != null) { // skip parameter could be passed here submissions.AddRange(SetsUtility.TopRankedSubmissionsFromASub(currentSubverse.name, _db.Messages, set.Name, 5, recordsToSkip * pageSize)); } singleSetResultModel.Name = set.Name; singleSetResultModel.Id = set.Set_id; } singleSetResultModel.SubmissionsList = new List <SetSubmission>(submissions.OrderByDescending(s => s.Rank)); return(View("~/Views/Sets/Index.cshtml", singleSetResultModel)); } catch (Exception) { return(RedirectToAction("HeavyLoad", "Error")); } }
public ActionResult Random() { var qry = from row in db.Subverses select row; int count = qry.Count(); // 1st round-trip int index = new Random().Next(count); // example subverse to show: pics Subverse randomSubverse = qry.OrderBy(s => s.name).Skip(index).FirstOrDefault(); // 2nd round-trip return(RedirectToAction("Index", "Subverses", new { subversetoshow = randomSubverse.name })); }
public async Task <ActionResult> CreateSubverse([Bind(Include = "Name, Title, Description, Type, Sidebar, Creation_date, Owner")] AddSubverse subverseTmpModel) { try { if (ModelState.IsValid) { Subverse subverse = new Subverse(); subverse.name = subverseTmpModel.Name; subverse.title = "/v/" + subverseTmpModel.Name; subverse.description = subverseTmpModel.Description; subverse.type = subverseTmpModel.Type; subverse.sidebar = subverseTmpModel.Sidebar; subverse.creation_date = subverseTmpModel.Creation_date; //check if subverse exists before attempting to create it if (db.Subverses.Find(subverse.name) == null) { db.Subverses.Add(subverse); await db.SaveChangesAsync(); //register user as the owner of the newly created subverse SubverseAdmin tmpSubverseAdmin = new SubverseAdmin(); tmpSubverseAdmin.SubverseName = subverse.name; tmpSubverseAdmin.Username = subverseTmpModel.Owner; tmpSubverseAdmin.Power = 1; db.SubverseAdmins.Add(tmpSubverseAdmin); await db.SaveChangesAsync(); //go to newly created Subverse return(RedirectToAction("Index", "Subverses", new { subversetoshow = subverse.name })); } else { ModelState.AddModelError(string.Empty, "Sorry, The subverse you are trying to create already exists."); return(View()); } } else { return(View()); } } catch (Exception) { ModelState.AddModelError(string.Empty, "Something bad happened."); return(View()); } }
public static Subverse Retrieve(string subverse) { if (!String.IsNullOrEmpty(subverse)) { string cacheKey = CacheHandler.Keys.SubverseInfo(subverse); Subverse sub = (Subverse)CacheHandler.Retrieve(cacheKey); if (sub == null) { sub = (Subverse)CacheHandler.Register(cacheKey, new Func <object>(() => { using (voatEntities db = new voatEntities()) { return(db.Subverses.Where(x => x.name == subverse).FirstOrDefault()); } }), TimeSpan.FromMinutes(5), 50); } return(sub); } return(null); }
protected override RuleOutcome EvaluateRule(VoatRuleContext context) { DemandContext(context); Subverse subverse = context.PropertyBag.Subverse; if (((int)base.Scope & (int)RuleAction.Create) > 0) { if (subverse.IsAdminDisabled.HasValue && subverse.IsAdminDisabled.Value) { return(CreateOutcome(RuleResult.Denied, "Subverse is disabled")); } } if (UserHelper.IsUserBannedFromSubverse(context.UserName, subverse.Name)) { return(CreateOutcome(RuleResult.Denied, "User is banned from v/{0}", subverse.Name)); } return(base.EvaluateRule(context)); }
// GET: sidebar for selected subverse public ActionResult DetailsForSelectedSubverse(string selectedSubverse) { Subverse subverse = db.Subverses.Find(selectedSubverse); if (subverse != null) { // get subscriber count for selected subverse int subscriberCount = db.Subscriptions.AsEnumerable() .Where(r => r.SubverseName.Equals(selectedSubverse, StringComparison.OrdinalIgnoreCase)) .Count(); ViewBag.SubscriberCount = subscriberCount; ViewBag.SelectedSubverse = selectedSubverse; return(PartialView("_SubverseDetails", subverse)); } else { //don't return a sidebar since subverse doesn't exist or is a system subverse return(new EmptyResult()); } }
public ActionResult SubverseSettings(string subversetoshow) { Subverse subverse = db.Subverses.Find(subversetoshow); if (subverse == null) { ViewBag.SelectedSubverse = "404"; return(View("~/Views/Errors/Subversenotfound.cshtml")); } SubverseAdmin subAdmin = db.SubverseAdmins .Where(x => x.SubverseName == subversetoshow && x.Username == User.Identity.Name && x.Power == 1).FirstOrDefault(); if (subAdmin != null) { return(View(subverse)); } else { return(new EmptyResult()); } }
//show a subverse index public ActionResult Index(int?page, string subversetoshow) { int pageSize = 25; int pageNumber = (page ?? 1); if (subversetoshow == null) { return(View("~/Views/Errors/Subversenotfound.cshtml")); } ViewBag.SelectedSubverse = subversetoshow; if (subversetoshow != "all") { //check if subverse exists, if not, send to a page not found error Subverse subverse = db.Subverses.Find(subversetoshow); if (subverse != null) { var submissions = db.Messages.Where(x => x.Subverse == subversetoshow && x.Name != "deleted").OrderByDescending(s => s.Rank).ToList(); ViewBag.Title = subverse.description; return(View(submissions.ToPagedList(pageNumber, pageSize))); } else { ViewBag.SelectedSubverse = "404"; return(View("~/Views/Errors/Subversenotfound.cshtml")); } } else { //if selected subverse is ALL, show submissions from all subverses, sorted by rank var submissions = db.Messages .Where(x => x.Name != "deleted") .OrderByDescending(s => s.Rank).ToList(); ViewBag.Title = "all subverses"; return(View(submissions.ToPagedList(pageNumber, pageSize))); } }
// subscribe to a subverse public static void SubscribeToSubverse(string userName, string subverse) { if (!IsUserSubverseSubscriber(userName, subverse)) { using (whoaverseEntities db = new whoaverseEntities()) { // add a new subscription Subscription newSubscription = new Subscription(); newSubscription.Username = userName; newSubscription.SubverseName = subverse; db.Subscriptions.Add(newSubscription); // record new subscription in subverse table subscribers field Subverse tmpSubverse = db.Subverses.Find(subverse); if (tmpSubverse != null) { tmpSubverse.subscribers++; } db.SaveChanges(); } } }
// add new submission public static async Task <string> AddNewSubmission(Submission 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.Content)) { // ABORT return("The URI you are trying to submit is invalid."); } // check if target subvere allows submissions from globally banned hostnames if (!targetSubverse.ExcludeSitewideBans) { // check if hostname is banned before accepting submission var domain = UrlUtility.GetDomainFromUri(submissionModel.Content); if (BanningUtility.IsDomainBanned(domain)) { // ABORT return("The domain you are trying to submit is banned."); } } // check if user has reached daily crossposting quota if (UserHelper.DailyCrossPostingQuotaUsed(userName, submissionModel.Content)) { // 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.IsThumbnailEnabled) { // 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 submissionModel.IsAnonymized = targetSubverse.IsAnonymized; submissionModel.UserName = userName; submissionModel.Subverse = targetSubverse.Name; submissionModel.UpCount = 1; db.Submissions.Add(submissionModel); 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."); } // grab server timestamp and modify submission timestamp to have posting time instead of "started writing submission" time submissionModel.IsAnonymized = targetSubverse.IsAnonymized; submissionModel.UserName = userName; submissionModel.Subverse = targetSubverse.Name; submissionModel.CreationDate = DateTime.Now; submissionModel.UpCount = 1; db.Submissions.Add(submissionModel); if (ContentProcessor.Instance.HasStage(ProcessingStage.InboundPreSave)) { submissionModel.Content = ContentProcessor.Instance.Process(submissionModel.Content, ProcessingStage.InboundPreSave, submissionModel); } await db.SaveChangesAsync(); if (ContentProcessor.Instance.HasStage(ProcessingStage.InboundPostSave)) { ContentProcessor.Instance.Process(submissionModel.Content, ProcessingStage.InboundPostSave, submissionModel); } } } // null is returned if no errors were raised return(null); }
public async Task<ActionResult> SubverseSettings(Subverse updatedModel) { try { if (!ModelState.IsValid) return View("~/Views/Subverses/Admin/SubverseSettings.cshtml"); var existingSubverse = _db.Subverses.Find(updatedModel.name); // check if subverse exists before attempting to edit it if (existingSubverse != null) { // check if user requesting edit is authorized to do so for current subverse // check that the user requesting to edit subverse settings is subverse owner! var subAdmin = _db.SubverseAdmins.FirstOrDefault( x => x.SubverseName == updatedModel.name && x.Username == User.Identity.Name && x.Power <= 2); if (subAdmin == null) return new EmptyResult(); // TODO investigate if EntityState is applicable here and use that instead // db.Entry(updatedModel).State = EntityState.Modified; existingSubverse.description = updatedModel.description; existingSubverse.sidebar = updatedModel.sidebar; if (updatedModel.stylesheet != null) { if (updatedModel.stylesheet.Length < 50001) { existingSubverse.stylesheet = updatedModel.stylesheet; } else { ModelState.AddModelError(string.Empty, "Sorry, custom CSS limit is set to 50000 characters."); return View("~/Views/Subverses/Admin/SubverseSettings.cshtml"); } } else { existingSubverse.stylesheet = updatedModel.stylesheet; } existingSubverse.rated_adult = updatedModel.rated_adult; existingSubverse.private_subverse = updatedModel.private_subverse; existingSubverse.enable_thumbnails = updatedModel.enable_thumbnails; existingSubverse.authorized_submitters_only = updatedModel.authorized_submitters_only; existingSubverse.exclude_sitewide_bans = updatedModel.exclude_sitewide_bans; existingSubverse.minimumdownvoteccp = updatedModel.minimumdownvoteccp; // these properties are currently not implemented but they can be saved and edited for future use existingSubverse.type = updatedModel.type; existingSubverse.label_submit_new_link = updatedModel.label_submit_new_link; existingSubverse.label_sumit_new_selfpost = updatedModel.label_sumit_new_selfpost; existingSubverse.submission_text = updatedModel.submission_text; existingSubverse.allow_default = updatedModel.allow_default; if (existingSubverse.anonymized_mode && updatedModel.anonymized_mode == false) { ModelState.AddModelError(string.Empty, "Sorry, this subverse is permanently locked to anonymized mode."); return View("~/Views/Subverses/Admin/SubverseSettings.cshtml"); } existingSubverse.anonymized_mode = updatedModel.anonymized_mode; await _db.SaveChangesAsync(); SubverseCache.Remove(existingSubverse.name); // go back to this subverse return RedirectToAction("SubverseIndex", "Subverses", new { subversetoshow = updatedModel.name }); // user was not authorized to commit the changes, drop attempt } ModelState.AddModelError(string.Empty, "Sorry, The subverse you are trying to edit does not exist."); return View("~/Views/Subverses/Admin/SubverseSettings.cshtml"); } catch (Exception) { ModelState.AddModelError(string.Empty, "Something bad happened."); return View("~/Views/Subverses/Admin/SubverseSettings.cshtml"); } }
public async Task<ActionResult> CreateSubverse([Bind(Include = "Name, Title, Description, Type, Sidebar, Creation_date, Owner")] AddSubverse subverseTmpModel) { // abort if model state is invalid if (!ModelState.IsValid) return View(); int minimumCcp = MvcApplication.MinimumCcp; int maximumOwnedSubs = MvcApplication.MaximumOwnedSubs; // verify recaptcha if user has less than minimum required CCP if (Karma.CommentKarma(User.Identity.Name) < minimumCcp) { // begin recaptcha check bool isCaptchaCodeValid = await ReCaptchaUtility.Validate(Request); if (!isCaptchaCodeValid) { ModelState.AddModelError("", "Incorrect recaptcha answer."); // TODO // SET PREVENT SPAM DELAY TO 0 return View(); } } // only allow users with less than maximum allowed subverses to create a subverse var amountOfOwnedSubverses = _db.SubverseAdmins .Where(s => s.Username == User.Identity.Name && s.Power == 1) .ToList(); if (amountOfOwnedSubverses.Count >= maximumOwnedSubs) { ModelState.AddModelError(string.Empty, "Sorry, you can not own more than " + maximumOwnedSubs + " subverses."); return View(); } // check if subverse already exists if (SubverseCache.Retrieve(subverseTmpModel.Name) != null) { ModelState.AddModelError(string.Empty, "Sorry, The subverse you are trying to create already exists, but you can try to claim it by submitting a takeover request to /v/subverserequest."); return View(); } try { // setup default values and create the subverse var subverse = new Subverse { name = subverseTmpModel.Name, title = "/v/" + subverseTmpModel.Name, description = subverseTmpModel.Description, sidebar = subverseTmpModel.Sidebar, creation_date = DateTime.Now, type = "link", enable_thumbnails = true, rated_adult = false, private_subverse = false, minimumdownvoteccp = 0, admin_disabled = false }; _db.Subverses.Add(subverse); await _db.SaveChangesAsync(); // subscribe user to the newly created subverse Utils.User.SubscribeToSubverse(subverseTmpModel.Owner, subverse.name); // register user as the owner of the newly created subverse var tmpSubverseAdmin = new SubverseAdmin { SubverseName = subverseTmpModel.Name, Username = User.Identity.Name, Power = 1 }; _db.SubverseAdmins.Add(tmpSubverseAdmin); await _db.SaveChangesAsync(); // go to newly created Subverse return RedirectToAction("SubverseIndex", "Subverses", new { subversetoshow = subverseTmpModel.Name }); } catch (Exception) { ModelState.AddModelError(string.Empty, "Something bad happened, please report this to /v/voatdev. Thank you."); return View(); } }
public async Task <ActionResult> AddModerator([Bind("ID,Subverse,UserName,Power")] SubverseModerator subverseAdmin) { if (!ModelState.IsValid) { return(View(subverseAdmin)); } // check if caller can add mods, if not, deny posting if (!ModeratorPermission.HasPermission(User, subverseAdmin.Subverse, Domain.Models.ModeratorAction.InviteMods)) { return(RedirectToAction("Index", "Home")); } subverseAdmin.UserName = subverseAdmin.UserName.TrimSafe(); Subverse subverseModel = null; //lots of premature retuns so wrap the common code var sendFailureResult = new Func <string, ActionResult>(errorMessage => { ViewBag.SubverseModel = subverseModel; ViewBag.SubverseName = subverseAdmin.Subverse; ViewBag.SelectedSubverse = string.Empty; ModelState.AddModelError(string.Empty, errorMessage); SetNavigationViewModel(subverseAdmin.Subverse); return(View("~/Views/Subverses/Admin/AddModerator.cshtml", new SubverseModeratorViewModel { UserName = subverseAdmin.UserName, Power = subverseAdmin.Power } )); }); // prevent invites to the current moderator if (User.Identity.Name.IsEqual(subverseAdmin.UserName)) { return(sendFailureResult("Can not add yourself as a moderator")); } string originalRecipientUserName = UserHelper.OriginalUsername(subverseAdmin.UserName); // prevent invites to the current moderator if (String.IsNullOrEmpty(originalRecipientUserName)) { return(sendFailureResult("User can not be found")); } // get model for selected subverse subverseModel = DataCache.Subverse.Retrieve(subverseAdmin.Subverse); if (subverseModel == null) { return(ErrorView(ErrorViewModel.GetErrorViewModel(ErrorType.SubverseNotFound))); } if ((subverseAdmin.Power < 1 || subverseAdmin.Power > 4) && subverseAdmin.Power != 99) { return(sendFailureResult("Only powers levels 1 - 4 and 99 are supported currently")); } //check current mod level and invite level and ensure they are a lower level var currentModLevel = ModeratorPermission.Level(User, subverseModel.Name); if (subverseAdmin.Power <= (int)currentModLevel && currentModLevel != Domain.Models.ModeratorLevel.Owner) { return(sendFailureResult("Sorry, but you can only add moderators that are a lower level than yourself")); } int maximumOwnedSubs = VoatSettings.Instance.MaximumOwnedSubs; // check if the user being added is not already a moderator of 10 subverses var currentlyModerating = _db.SubverseModerator.Where(a => a.UserName == originalRecipientUserName).ToList(); SubverseModeratorViewModel tmpModel; if (currentlyModerating.Count <= maximumOwnedSubs) { // check that user is not already moderating given subverse var isAlreadyModerator = _db.SubverseModerator.FirstOrDefault(a => a.UserName == originalRecipientUserName && a.Subverse == subverseAdmin.Subverse); if (isAlreadyModerator == null) { // check if this user is already invited var userModeratorInvitations = _db.ModeratorInvitation.Where(i => i.Recipient.ToLower() == originalRecipientUserName.ToLower() && i.Subverse.ToLower() == subverseModel.Name.ToLower()); if (userModeratorInvitations.Any()) { return(sendFailureResult("Sorry, the user is already invited to moderate this subverse")); } // send a new moderator invitation ModeratorInvitation modInv = new ModeratorInvitation { CreatedBy = User.Identity.Name, CreationDate = Repository.CurrentDate, Recipient = originalRecipientUserName, Subverse = subverseAdmin.Subverse, Power = subverseAdmin.Power }; _db.ModeratorInvitation.Add(modInv); _db.SaveChanges(); int invitationId = modInv.ID; var invitationBody = new StringBuilder(); //v/{subverse}/about/moderatorinvitations/accept/{invitationId} string acceptInviteUrl = VoatUrlFormatter.BuildUrlPath(this.HttpContext, new PathOptions(true, true), $"/v/{subverseModel.Name}/about/moderatorinvitations/accept/{invitationId}"); invitationBody.Append("Hello,"); invitationBody.Append(Environment.NewLine); invitationBody.Append($"@{User.Identity.Name} invited you to moderate v/" + subverseAdmin.Subverse + "."); invitationBody.Append(Environment.NewLine); invitationBody.Append(Environment.NewLine); invitationBody.Append($"Please visit the following link if you want to accept this invitation: {acceptInviteUrl}"); invitationBody.Append(Environment.NewLine); invitationBody.Append(Environment.NewLine); invitationBody.Append("Thank you."); var cmd = new SendMessageCommand(new Domain.Models.SendMessage() { Sender = $"v/{subverseAdmin.Subverse}", Recipient = originalRecipientUserName, Subject = $"v/{subverseAdmin.Subverse} moderator invitation", Message = invitationBody.ToString() }, true).SetUserContext(User); await cmd.Execute(); return(RedirectToAction("SubverseModerators")); } else { return(sendFailureResult("Sorry, the user is already moderating this subverse")); } } else { return(sendFailureResult("Sorry, the user is already moderating a maximum of " + maximumOwnedSubs + " subverses")); } }
private async Task <CommandResponse <bool?> > SetSubverseListChange(SubverseSet set, Subverse subverse, SubscriptionAction action) { using (var db = new VoatDataContext()) { CommandResponse <bool?> response = new CommandResponse <bool?>(true, Status.Success, ""); var actionTaken = SubscriptionAction.Toggle; var setSubverseRecord = db.SubverseSetList.FirstOrDefault(n => n.SubverseSetID == set.ID && n.SubverseID == subverse.ID); if (setSubverseRecord == null && ((action == SubscriptionAction.Subscribe) || action == SubscriptionAction.Toggle)) { db.SubverseSetList.Add(new SubverseSetList { SubverseSetID = set.ID, SubverseID = subverse.ID, CreationDate = CurrentDate }); actionTaken = SubscriptionAction.Subscribe; } else if (setSubverseRecord != null && ((action == SubscriptionAction.Unsubscribe) || action == SubscriptionAction.Toggle)) { db.SubverseSetList.Remove(setSubverseRecord); actionTaken = SubscriptionAction.Unsubscribe; } await db.SaveChangesAsync().ConfigureAwait(CONSTANTS.AWAIT_CAPTURE_CONTEXT); //If Subscribe is to a front page, update subscriber count if (set.Type == (int)SetType.Front && !String.IsNullOrEmpty(set.UserName)) { await UpdateSubverseSubscriberCount(new DomainReference(DomainType.Subverse, subverse.Name), actionTaken); } response.Response = actionTaken == SubscriptionAction.Toggle ? (bool?)null : actionTaken == SubscriptionAction.Subscribe; return(response); } }
// 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); } // abort if title is < than 10 characters if (submissionModel.Linkdescription.Length < 10) { // ABORT return ("The title may not be less than 10 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 (User.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); } // abort if title less than 10 characters if (submissionModel.Title.Length < 10) { return ("Sorry, the the submission title may not be less than 10 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; }
// various spam checks, to be replaced with new rule engine public static async Task<string> PreAddSubmissionCheck(Message submissionModel, HttpRequestBase request, string userName, Subverse targetSubverse) { // check if user has reached hourly posting quota for target subverse if (User.UserHourlyPostingQuotaForSubUsed(userName, submissionModel.Subverse)) { return ("You have reached your hourly submission quota for this subverse."); } // check if user has reached daily posting quota for target subverse if (User.UserDailyPostingQuotaForSubUsed(userName, submissionModel.Subverse)) { return ("You have reached your daily submission quota for this subverse."); } // verify recaptcha if user has less than 25 CCP var userCcp = Karma.CommentKarma(userName); if (userCcp < 25) { bool isCaptchaCodeValid = await ReCaptchaUtility.Validate(request); if (!isCaptchaCodeValid) { // TODO: SET PREVENT SPAM DELAY TO 0 return ("Incorrect recaptcha answer."); } } // if user CCP or SCP is less than -50, allow only X submissions per 24 hours var userScp = Karma.LinkKarma(userName); if (userCcp <= -50 || userScp <= -50) { var quotaUsed = User.UserDailyPostingQuotaForNegativeScoreUsed(userName); if (quotaUsed) { return ("You have reached your daily submission quota. Your current quota is " + MvcApplication.DailyPostingQuotaForNegativeScore + " submission(s) per 24 hours."); } } // check if subverse has "authorized_submitters_only" set and dissalow submission if user is not allowed submitter if (targetSubverse.authorized_submitters_only) { if (!User.IsUserSubverseModerator(userName, targetSubverse.name)) { // user is not a moderator, check if user is an administrator if (!User.IsUserSubverseAdmin(userName, targetSubverse.name)) { return ("You are not authorized to submit links or start discussions in this subverse. Please contact subverse moderators for authorization."); } } } // null is returned if all checks have passed return null; }
// various spam checks, to be replaced with new rule engine public static async Task <string> PreAddSubmissionCheck(Submission submissionModel, HttpRequestBase request, string userName, Subverse targetSubverse, Func <HttpRequestBase, Task <bool> > captchaValidator) { // TODO: reject if a submission with this title was posted in the last 60 minutes // check posting quotas if user is posting to subs they do not moderate if (!UserHelper.IsUserSubverseModerator(userName, submissionModel.Subverse)) { // reject if user has reached global daily submission quota if (UserHelper.UserDailyGlobalPostingQuotaUsed(userName)) { return("You have reached your daily global submission quota."); } // reject if user has reached global hourly submission quota if (UserHelper.UserHourlyGlobalPostingQuotaUsed(userName)) { return("You have reached your hourly global submission quota."); } // check if user has reached hourly posting quota for target subverse if (UserHelper.UserHourlyPostingQuotaForSubUsed(userName, submissionModel.Subverse)) { return("You have reached your hourly submission quota for this subverse."); } // check if user has reached daily posting quota for target subverse if (UserHelper.UserDailyPostingQuotaForSubUsed(userName, submissionModel.Subverse)) { return("You have reached your daily submission quota for this subverse."); } } // verify recaptcha if user has less than 25 CCP var userCcp = Karma.CommentKarma(userName); if (userCcp < 25) { bool isCaptchaCodeValid = await captchaValidator(request); if (!isCaptchaCodeValid) { // TODO: SET PREVENT SPAM DELAY TO 0 return("Incorrect recaptcha answer."); } } // if user CCP or SCP is less than -10, allow only X submissions per 24 hours var userScp = Karma.LinkKarma(userName); if (userCcp <= -10 || userScp <= -10) { var quotaUsed = UserHelper.UserDailyPostingQuotaForNegativeScoreUsed(userName); if (quotaUsed) { return("You have reached your daily submission quota. Your current quota is " + Settings.DailyPostingQuotaForNegativeScore + " submission(s) per 24 hours."); } } // check if subverse has "authorized_submitters_only" set and dissalow submission if user is not allowed submitter if (targetSubverse.IsAuthorizedOnly) { if (!UserHelper.IsUserSubverseModerator(userName, targetSubverse.Name)) { return("You are not authorized to submit links or start discussions in this subverse. Please contact subverse moderators for authorization."); } } // null is returned if all checks have passed return(null); }
// GET: /set/setid // show single set frontpage public ActionResult SingleSet(int setId, int?page) { const int pageSize = 25; int recordsToSkip = (page ?? 0); try { // get list of subverses for the set // for each subverse, get top ranked submissions var set = _db.UserSets.FirstOrDefault(ds => ds.ID == setId); if (set == null) { return(RedirectToAction("NotFound", "Error")); } ViewBag.SelectedSubverse = set.Name; var singleSetResultModel = new SingleSetViewModel(); var submissions = new List <SetSubmission>(); // if subs in set count is < 1, don't display the page, instead, check if the user owns this set and give them a chance to add subs to the set if (set.UserSetLists.Count < 1) { // check if the user owns this sub if (User.Identity.IsAuthenticated && User.Identity.Name == set.CreatedBy) { return(RedirectToAction("EditSet", "Sets", new { setId = set.ID })); } } int subsInSet = set.UserSetLists.Count(); int submissionsToGet = 5; // there is at least 1 sub in the set if (subsInSet == 1) { submissionsToGet = 25; } // get only one submission from each sub if set contains 25 or more subverses else if (subsInSet >= 25) { submissionsToGet = 1; } // try to aim for 25 submissions else { submissionsToGet = (int)Math.Ceiling((double)25 / subsInSet); } foreach (var subverse in set.UserSetLists) { // get top ranked submissions for current subverse Subverse currentSubverse = subverse.Subverse1; if (currentSubverse != null) { // skip parameter could be passed here submissions.AddRange(SetsUtility.TopRankedSubmissionsFromASub(currentSubverse.Name, _db.Submissions, set.Name, submissionsToGet, recordsToSkip * pageSize)); } singleSetResultModel.Name = set.Name; singleSetResultModel.Description = set.Description; singleSetResultModel.Id = set.ID; } singleSetResultModel.SubmissionsList = new List <SetSubmission>(submissions.OrderByDescending(s => s.Rank)); return(View("~/Views/Sets/Index.cshtml", singleSetResultModel)); } catch (Exception) { return(RedirectToAction("HeavyLoad", "Error")); } }