public MemoryBase() { size = Size.average; speed = Speed.average; colour = Colour.muted; karma = Karma.aquainted; }
public JsonResult Vote(int messageId, int typeOfVote) { var loggedInUser = User.Identity.Name; switch (typeOfVote) { case 1: if (Karma.CommentKarma(loggedInUser) > 20) { // perform upvoting or resetting Voting.UpvoteSubmission(messageId, loggedInUser); } else if (Utils.User.TotalVotesUsedInPast24Hours(User.Identity.Name) < 11) { // perform upvoting or resetting even if user has no CCP but only allow 10 votes per 24 hours Voting.UpvoteSubmission(messageId, loggedInUser); } break; case -1: if (Karma.CommentKarma(loggedInUser) > 100) { // perform downvoting or resetting Voting.DownvoteSubmission(messageId, loggedInUser); } break; } return(Json("Voting ok", JsonRequestBehavior.AllowGet)); }
public static Karma UpdateKarma(this IMongoDatabase db, string nick, string channel, string server, int incr) { var karma = db.GetCollection <BsonDocument>("Karma"); var builder = Builders <BsonDocument> .Filter; var filter = builder.Eq("nick", nick) & builder.Eq("channel", channel.ToLower()) & builder.Eq("network", server); var document = karma.Find(filter).FirstOrDefault(); if (document == null) { karma.InsertOne(new BsonDocument { { "nick", nick }, { "channel", channel.ToLower() }, { "network", server }, { "score", 0 } }); document = karma.Find(filter).FirstOrDefault(); } var update = Builders <BsonDocument> .Update.Inc("score", incr); karma.UpdateOne(filter, update); var toReturn = Karma.FromJson(document.ToJson(new JsonWriterSettings { OutputMode = JsonOutputMode.Strict })); toReturn.Score += incr; return(toReturn); }
protected override void WriteDataXML(XElement ele, ElderScrollsPlugin master) { XElement subEle; ele.TryPathTo("Flags", true, out subEle); subEle.Value = Flags.ToString(); ele.TryPathTo("Fatigue", true, out subEle); subEle.Value = Fatigue.ToString(); ele.TryPathTo("BarterGold", true, out subEle); subEle.Value = BarterGold.ToString(); ele.TryPathTo("Level", true, out subEle); subEle.Value = Level.ToString(); ele.TryPathTo("CalcMin", true, out subEle); subEle.Value = CalcMin.ToString(); ele.TryPathTo("CalcMax", true, out subEle); subEle.Value = CalcMax.ToString(); ele.TryPathTo("SpeedMultiplier", true, out subEle); subEle.Value = SpeedMultiplier.ToString(); ele.TryPathTo("Karma", true, out subEle); subEle.Value = Karma.ToString("G15"); ele.TryPathTo("DispositionBase", true, out subEle); subEle.Value = DispositionBase.ToString(); ele.TryPathTo("TemplateFlags", true, out subEle); subEle.Value = TemplateFlags.ToString(); }
/// <summary> /// Print the object's XML to the XmlWriter. /// </summary> /// <param name="objWriter">XmlTextWriter to write with.</param> /// <param name="strLanguageToPrint">Language in which to print</param> public void Print(XmlTextWriter objWriter, string strLanguageToPrint) { if (objWriter == null) { return; } objWriter.WriteStartElement("critterpower"); objWriter.WriteElementString("guid", InternalId); objWriter.WriteElementString("sourceid", SourceIDString); objWriter.WriteElementString("name", DisplayNameShort(strLanguageToPrint)); objWriter.WriteElementString("fullname", DisplayName(strLanguageToPrint)); objWriter.WriteElementString("name_english", Name); objWriter.WriteElementString("extra", _objCharacter.TranslateExtra(_strExtra, strLanguageToPrint)); objWriter.WriteElementString("category", DisplayCategory(strLanguageToPrint)); objWriter.WriteElementString("category_english", Category); objWriter.WriteElementString("type", DisplayType(strLanguageToPrint)); objWriter.WriteElementString("action", DisplayAction(strLanguageToPrint)); objWriter.WriteElementString("range", DisplayRange(strLanguageToPrint)); objWriter.WriteElementString("duration", DisplayDuration(strLanguageToPrint)); objWriter.WriteElementString("karma", Karma.ToString(GlobalSettings.InvariantCultureInfo)); objWriter.WriteElementString("source", _objCharacter.LanguageBookShort(Source, strLanguageToPrint)); objWriter.WriteElementString("page", DisplayPage(strLanguageToPrint)); if (GlobalSettings.PrintNotes) { objWriter.WriteElementString("notes", Notes); } objWriter.WriteEndElement(); }
public void handle(RegistrationInfoFactory infoFactory, IrcDotNet.IrcClient client, FehBot bot, IMongoDatabase db, IrcDotNet.IrcUser from, IrcDotNet.IrcChannel channel, string message) { if (channel == null) { return; } if (isKarmaRequest(message)) { var request = parseKarmaRequest(message); request.Keys.ForEach(nick => { Karma document = db.UpdateKarma(nick, channel.Name, infoFactory.Server, request[nick]); string template = request[nick] > 0 ? "{0} gained a level! (Karma: {1})":"{0} lost a level! (Karma: {1})"; client.LocalUser.SendMessage(channel, String.Format(template, nick, document.Score)); JObject body = new JObject(); body.Add("nick", document.Nick); body.Add("from", from.NickName); body.Add("score", document.Score); body.Add("channel", document.Channel); body.Add("direction", request[nick]); callWebHook(db, body); }); } }
public async Task <ActionResult> Compose([Bind(Include = "ID,Recipient,Subject,Body")] PrivateMessage privateMessage) { if (!ModelState.IsValid) { return(View()); } if (privateMessage.Recipient == null || privateMessage.Subject == null || privateMessage.Body == null) { return(RedirectToAction("Sent", "Messaging")); } if (Karma.CommentKarma(User.Identity.Name) < 100) { bool isCaptchaValid = await ReCaptchaUtility.Validate(Request); if (!isCaptchaValid) { ModelState.AddModelError(string.Empty, "Incorrect recaptcha answer."); return(View()); } } var response = MesssagingUtility.SendPrivateMessage(User.Identity.Name, privateMessage.Recipient, privateMessage.Subject, privateMessage.Body); return(RedirectToAction("Sent", "Messaging")); }
public ApiUserInfo UserInfo(string userName) { if (userName != "deleted" && !Utils.User.UserExists(userName)) { throw new HttpResponseException(HttpStatusCode.NotFound); } if (userName == "deleted") { throw new HttpResponseException(HttpStatusCode.NotFound); } var resultModel = new ApiUserInfo(); var userBadgesList = Utils.User.UserBadges(userName); var resultBadgesList = userBadgesList.Select(item => new ApiUserBadge { Awarded = item.Awarded, BadgeName = item.Badge.BadgeName }).ToList(); resultModel.Name = userName; resultModel.CCP = Karma.CommentKarma(userName); resultModel.LCP = Karma.LinkKarma(userName); resultModel.RegistrationDate = Utils.User.GetUserRegistrationDateTime(userName); resultModel.Badges = resultBadgesList; return(resultModel); }
public async Task <ActionResult> Compose([Bind(Include = "Id,Recipient,Subject,Body")] Privatemessage privateMessage) { if (!ModelState.IsValid) { return(View()); } if (privateMessage.Recipient == null || privateMessage.Subject == null || privateMessage.Body == null) { return(RedirectToAction("Sent", "Messaging")); } if (Karma.CommentKarma(User.Identity.Name) < 100) { bool isCaptchaValid = await ReCaptchaUtility.Validate(Request); if (!isCaptchaValid) { ModelState.AddModelError(string.Empty, "Incorrect recaptcha answer."); return(View()); } } // check if recipient exists if (Voat.Utilities.UserHelper.UserExists(privateMessage.Recipient) && !Voat.Utilities.UserHelper.IsUserGloballyBanned(User.Identity.Name)) { // send the submission privateMessage.Timestamp = DateTime.Now; privateMessage.Sender = User.Identity.Name; privateMessage.Status = true; if (Voat.Utilities.UserHelper.IsUserGloballyBanned(User.Identity.Name)) { return(RedirectToAction("Sent", "Messaging")); } _db.Privatemessages.Add(privateMessage); try { await _db.SaveChangesAsync(); // get count of unread notifications int unreadNotifications = Voat.Utilities.UserHelper.UnreadTotalNotificationsCount(privateMessage.Recipient); // send SignalR realtime notification to recipient var hubContext = GlobalHost.ConnectionManager.GetHubContext <MessagingHub>(); hubContext.Clients.User(privateMessage.Recipient).setNotificationsPending(unreadNotifications); } catch (Exception) { return(View("~/Views/Errors/DbNotResponding.cshtml")); } } else { ModelState.AddModelError(string.Empty, "Sorry, there is no recipient with that username."); return(View()); } return(RedirectToAction("Sent", "Messaging")); }
public void Print(XmlTextWriter objWriter) { objWriter.WriteStartElement("skill"); int rating = PoolOtherAttribute(AttributeObject.TotalValue); int specRating = Specializations.Count == 0 ? rating : (!IsKnowledgeSkill && Name == "Artisan" && CharacterObject.Qualities.Any(objQuality => objQuality.Name == "Inspired") ? rating + 3 : rating + 2); int ratingModifiers = 0, dicePoolModifiers = 0; objWriter.WriteElementString("name", DisplayName); objWriter.WriteElementString("skillgroup", SkillGroupObject?.DisplayName ?? LanguageManager.Instance.GetString("String_None")); objWriter.WriteElementString("skillgroup_english", SkillGroupObject?.Name ?? LanguageManager.Instance.GetString("String_None")); objWriter.WriteElementString("skillcategory", SkillCategory); objWriter.WriteElementString("skillcategory_english", SkillCategory); //Might exist legacy but not existing atm, will see if stuff breaks objWriter.WriteElementString("grouped", (SkillGroupObject?.CareerIncrease).ToString()); objWriter.WriteElementString("default", Default.ToString()); objWriter.WriteElementString("rating", Rating.ToString()); objWriter.WriteElementString("ratingmax", RatingMaximum.ToString()); objWriter.WriteElementString("specializedrating", specRating.ToString()); objWriter.WriteElementString("total", PoolOtherAttribute(AttributeObject.TotalValue).ToString()); objWriter.WriteElementString("knowledge", IsKnowledgeSkill.ToString()); objWriter.WriteElementString("exotic", IsExoticSkill.ToString()); objWriter.WriteElementString("buywithkarma", BuyWithKarma.ToString()); objWriter.WriteElementString("base", Base.ToString()); objWriter.WriteElementString("karma", Karma.ToString()); objWriter.WriteElementString("spec", Specialization); objWriter.WriteElementString("attribute", Attribute); objWriter.WriteElementString("displayattribute", DisplayAttribute); objWriter.WriteElementString("notes", _strNotes); objWriter.WriteElementString("source", CharacterObject.Options.LanguageBookShort(Source)); objWriter.WriteElementString("page", Page); if (Attribute == "MAG" && CharacterObject.AdeptEnabled && CharacterObject.MagicianEnabled) { objWriter.WriteElementString("attributemod", CharacterObject.MAGMagician.ToString()); } else { objWriter.WriteElementString("attributemod", CharacterObject.GetAttribute(Attribute).TotalValue.ToString()); } objWriter.WriteElementString("ratingmod", (ratingModifiers + dicePoolModifiers).ToString()); objWriter.WriteElementString("poolmod", dicePoolModifiers.ToString()); objWriter.WriteElementString("islanguage", (SkillCategory == "Language").ToString()); objWriter.WriteElementString("bp", CurrentKarmaCost().ToString()); objWriter.WriteStartElement("skillspecializations"); foreach (SkillSpecialization objSpec in Specializations) { objSpec.Print(objWriter); } objWriter.WriteEndElement(); objWriter.WriteEndElement(); }
void Karistir() { for (int x = 0; x < Orjinal.Width; x++) { for (int y = 0; y < Orjinal.Height; y++) { Karma.SetPixel(x, y, GetColorK(x, y)); } } }
/// <summary> /// Responsible for initializing the necessary variables on start of /// running time. /// </summary> public void Start() { _controller = GetComponent <CharacterController>(); _plyrInteraction = GetComponent <PlayerInteraction>(); _cameraTransform = GetComponentInChildren <Camera>().transform; acceleration = Vector3.zero; velocity = Vector3.zero; velocityFactor = WALK_VELOCITY_FACTOR; _playerKarma = new Karma(this); _playerFaction = Faction.None; }
/// <summary> /// Print the object's XML to the XmlWriter. /// </summary> /// <param name="objWriter">XmlTextWriter to write with.</param> /// <param name="strLanguageToPrint">Language in which to print</param> public async ValueTask Print(XmlWriter objWriter, string strLanguageToPrint) { if (objWriter == null) { return; } // <critterpower> XmlElementWriteHelper objBaseElement = await objWriter.StartElementAsync("critterpower"); try { await objWriter.WriteElementStringAsync("guid", InternalId); await objWriter.WriteElementStringAsync("sourceid", SourceIDString); await objWriter.WriteElementStringAsync("name", await DisplayNameShortAsync(strLanguageToPrint)); await objWriter.WriteElementStringAsync("fullname", await DisplayNameAsync(strLanguageToPrint)); await objWriter.WriteElementStringAsync("name_english", Name); await objWriter.WriteElementStringAsync("extra", await _objCharacter.TranslateExtraAsync(_strExtra, strLanguageToPrint)); await objWriter.WriteElementStringAsync("category", await DisplayCategoryAsync(strLanguageToPrint)); await objWriter.WriteElementStringAsync("category_english", Category); await objWriter.WriteElementStringAsync("type", await DisplayTypeAsync(strLanguageToPrint)); await objWriter.WriteElementStringAsync("action", await DisplayActionAsync(strLanguageToPrint)); await objWriter.WriteElementStringAsync("range", await DisplayRangeAsync(strLanguageToPrint)); await objWriter.WriteElementStringAsync("duration", await DisplayDurationAsync(strLanguageToPrint)); await objWriter.WriteElementStringAsync("karma", Karma.ToString(GlobalSettings.InvariantCultureInfo)); await objWriter.WriteElementStringAsync("source", await _objCharacter.LanguageBookShortAsync(Source, strLanguageToPrint)); await objWriter.WriteElementStringAsync("page", await DisplayPageAsync(strLanguageToPrint)); if (GlobalSettings.PrintNotes) { await objWriter.WriteElementStringAsync("notes", Notes); } } finally { // </critterpower> await objBaseElement.DisposeAsync(); } }
internal void Print(XmlWriter objWriter) { objWriter.WriteStartElement("skillgroup"); objWriter.WriteElementString("name", DisplayName); objWriter.WriteElementString("name_english", Name); objWriter.WriteElementString("rating", Rating.ToString()); objWriter.WriteElementString("ratingmax", RatingMaximum.ToString()); objWriter.WriteElementString("base", Base.ToString()); objWriter.WriteElementString("karma", Karma.ToString()); objWriter.WriteEndElement(); }
internal void Print(XmlWriter objWriter, CultureInfo objCulture, string strLanguageToPrint) { objWriter.WriteStartElement("skillgroup"); objWriter.WriteElementString("name", DisplayNameMethod(strLanguageToPrint)); objWriter.WriteElementString("name_english", Name); objWriter.WriteElementString("rating", Rating.ToString(objCulture)); objWriter.WriteElementString("ratingmax", RatingMaximum.ToString(objCulture)); objWriter.WriteElementString("base", Base.ToString(objCulture)); objWriter.WriteElementString("karma", Karma.ToString(objCulture)); objWriter.WriteEndElement(); }
public void SaveKarma(string thing, int karmaPoints, ulong from) { var karma = new Karma { Server = _context.Guild.Id, Points = karmaPoints, Thing = thing, FromUserId = from, GivenOn = DateTime.Now }; _db.Karma.Add(karma); _db.SaveChanges(); }
protected virtual Karma RunInternal(string outputDirectory) { var outputFile = Settings.GetOutputFile(outputDirectory); try { var processOptions = GetProcessOptions(); processOptions.Add("-o", outputFile); Logger.Info(processOptions.CommandLine); _process = new Process(processOptions); try { _process.StandardOutputRead += (o, e) => { Logger.Info(e.Line); }; _process.StandardErrorRead += (o, e) => { Logger.Info(e.Line); }; _process.Run(); } finally { _process = null; } var karma = Karma.Load(outputFile); return(karma); } catch (Exception ex) { Logger.Error(ex.Message); return(null); } finally { if (!Settings.LogToFile) { IO.File.Delete(outputFile); } } }
public ActionResult UserBasicInfo(string userName) { var userRegistrationDateTime = UserHelper.GetUserRegistrationDateTime(userName); var memberFor = Submissions.CalcSubmissionAge(userRegistrationDateTime); var scp = Karma.LinkKarma(userName); var ccp = Karma.CommentKarma(userName); var userInfoModel = new BasicUserInfo() { MemberSince = memberFor, Ccp = ccp, Scp = scp }; return(PartialView("~/Views/AjaxViews/_BasicUserInfo.cshtml", userInfoModel)); }
Color GetColorO(int x, int y) { string r = IkiligeCevir(Karma.GetPixel(x, y).R).Substring(0, 4); r += "0000"; string b = IkiligeCevir(Karma.GetPixel(x, y).B).Substring(0, 4); b += "0000"; string g = IkiligeCevir(Karma.GetPixel(x, y).G).Substring(0, 4); g += "0000"; Color c = Color.FromArgb(OnlugaCevir(r), OnlugaCevir(g), OnlugaCevir(b)); return(c); }
public JsonResult VoteComment(int commentId, int typeOfVote) { lock (_locker) { int dailyVotingQuota = Settings.DailyVotingQuota; var loggedInUser = User.Identity.Name; var userCcp = Karma.CommentKarma(loggedInUser); var scaledDailyVotingQuota = Math.Max(dailyVotingQuota, userCcp / 2); var totalVotesUsedInPast24Hours = UserHelper.TotalVotesUsedInPast24Hours(User.Identity.Name); switch (typeOfVote) { case 1: if (userCcp >= 20) { if (totalVotesUsedInPast24Hours < scaledDailyVotingQuota) { // perform upvoting or resetting VotingComments.UpvoteComment(commentId, loggedInUser, IpHash.CreateHash(UserHelper.UserIpAddress(Request))); } } else if (totalVotesUsedInPast24Hours < 11) { // perform upvoting or resetting even if user has no CCP but only allow 10 votes per 24 hours VotingComments.UpvoteComment(commentId, loggedInUser, IpHash.CreateHash(UserHelper.UserIpAddress(Request))); } break; case -1: if (userCcp >= 100) { if (totalVotesUsedInPast24Hours < scaledDailyVotingQuota) { // perform downvoting or resetting VotingComments.DownvoteComment(commentId, loggedInUser, IpHash.CreateHash(UserHelper.UserIpAddress(Request))); } } break; } Response.StatusCode = 200; return(Json("Voting ok", JsonRequestBehavior.AllowGet)); } }
public async Task <ActionResult> Add(Karma karma) { if (ModelState.IsValid) { var user = await usermanager.GetUserAsync(User); if (user == null) { return(RedirectToAction("Logout", "Account")); } karma.UserId = user.Id; await db.AddKarmaAsync(karma); ViewBag.Message = "Задача успешно добавлена."; return(PartialView("_Success")); } return(PartialView(karma)); }
public JsonResult Vote(int messageId, int typeOfVote) { string loggedInUser = User.Identity.Name; if (typeOfVote == 1) { // perform upvoting or resetting Voting.UpvoteSubmission(messageId, loggedInUser); } else if (typeOfVote == -1) { // ignore downvote if user link karma is below certain treshold if (Karma.CommentKarma(loggedInUser) > 100) { // perform downvoting or resetting Voting.DownvoteSubmission(messageId, loggedInUser); } } return(Json("Voting ok", JsonRequestBehavior.AllowGet)); }
public JsonResult VoteComment(int commentId, int typeOfVote) { int dailyVotingQuota = Convert.ToInt32(ConfigurationManager.AppSettings["dailyVotingQuota"]); var loggedInUser = User.Identity.Name; var userCcp = Karma.CommentKarma(loggedInUser); var scaledDailyVotingQuota = Math.Max(dailyVotingQuota, userCcp / 2); var totalVotesUsedInPast24Hours = Utils.User.TotalVotesUsedInPast24Hours(User.Identity.Name); switch (typeOfVote) { case 1: if (userCcp >= 20) { if (totalVotesUsedInPast24Hours < scaledDailyVotingQuota) { // perform upvoting or resetting VotingComments.UpvoteComment(commentId, loggedInUser); } } else if (totalVotesUsedInPast24Hours < 11) { // perform upvoting or resetting even if user has no CCP but only allow 10 votes per 24 hours VotingComments.UpvoteComment(commentId, loggedInUser); } break; case -1: if (userCcp >= 100) { if (totalVotesUsedInPast24Hours < scaledDailyVotingQuota) { // perform downvoting or resetting VotingComments.DownvoteComment(commentId, loggedInUser); } } break; } Response.StatusCode = 200; return(Json("Voting ok", JsonRequestBehavior.AllowGet)); }
private static async Task <Embed> GetKarmaEmbed(Karma karma, string username, int topCount, GuildHandler messageSource) { if (karma.Upvotes == 0 && karma.Downvotes == 0) { return(new EmbedBuilder().WithTitle(":(").WithDescription($"{username} has yet to recieve any karma.").Build()); } EmbedBuilder builder = new EmbedBuilder(). WithTitle($"Karma for {username}"). WithDescription($"```{karma.Upvotes} upvotes.\n{karma.Downvotes} downvotes.\n{karma.Total} total.```"); builder.AddField(await GetTopMessage($"Top [count] message", (x, y) => y.Total - x.Total, karma.GetMessages(), topCount, messageSource)); builder.AddField(await GetTopMessage($"Buttom [count] message", (x, y) => x.Total - y.Total, karma.GetMessages(), topCount, messageSource)); builder.AddField(GetTopVoters((x, y) => y - x, karma.GetUpvotes(), $"{username} is most loved by..", "upvotes", "```No one :(```", topCount, messageSource)); builder.AddField(GetTopVoters((x, y) => y - x, karma.GetDownvotes(), $"{username} is most hated by..", "downvotes", "```No one! :)```", topCount, messageSource)); return(builder.Build()); }
public JsonResult VoteComment(int commentId, int typeOfVote) { string loggedInUser = User.Identity.Name; if (typeOfVote == 1) { // perform upvoting or resetting VotingComments.UpvoteComment(commentId, loggedInUser); } else if (typeOfVote == -1) { // ignore downvote if user comment karma is below certain treshold if (Karma.CommentKarma(loggedInUser) > 100) { // perform downvoting or resetting VotingComments.DownvoteComment(commentId, loggedInUser); } } Response.StatusCode = 200; return(Json("Voting ok", JsonRequestBehavior.AllowGet)); }
public JsonResult Vote(int messageId, int typeOfVote) { int dailyVotingQuota = MvcApplication.DailyVotingQuota; var loggedInUser = User.Identity.Name; var userCcp = Karma.CommentKarma(loggedInUser); var scaledDailyVotingQuota = Math.Max(dailyVotingQuota, userCcp / 2); var totalVotesUsedInPast24Hours = Utils.User.TotalVotesUsedInPast24Hours(User.Identity.Name); switch (typeOfVote) { case 1: if (userCcp >= 20) { if (totalVotesUsedInPast24Hours < scaledDailyVotingQuota) { // perform upvoting or resetting Voting.UpvoteSubmission(messageId, loggedInUser, IpHash.CreateHash(Utils.User.UserIpAddress(Request))); } } else if (totalVotesUsedInPast24Hours < 11) { // perform upvoting or resetting even if user has no CCP but only allow 10 votes per 24 hours Voting.UpvoteSubmission(messageId, loggedInUser, IpHash.CreateHash(Utils.User.UserIpAddress(Request))); } break; case -1: if (userCcp >= 100) { if (totalVotesUsedInPast24Hours < scaledDailyVotingQuota) { // perform downvoting or resetting Voting.DownvoteSubmission(messageId, loggedInUser, IpHash.CreateHash(Utils.User.UserIpAddress(Request))); } } break; } return(Json("Voting ok", JsonRequestBehavior.AllowGet)); }
public ActionResult <int> Post([FromBody] KarmaRequest value) { using (var db = new DatabaseContext()) { var karma = db.Karmas.Where(k => k.Name == value.Karma.Name).FirstOrDefault(); if (karma != null) { if (value.Action == KarmaAction.Increment) { karma.Score = karma.Score + 1; } else { karma.Score = karma.Score - 1; } db.SaveChanges(); return(Ok(karma)); } else { var newKarma = new Karma { Name = value.Karma.Name }; if (value.Action == KarmaAction.Increment) { newKarma.Score = 1; } else { newKarma.Score = -1; } db.Karmas.Add(newKarma); db.SaveChanges(); return(Ok(newKarma)); } } }
public override void TryExecute() { PawnKindDef pawnKind = PawnKindDef.Named("LotRD_DwarfColonist"); Faction ofPlayer = Faction.OfPlayer; bool pawnMustBeCapableOfViolence = true; PawnGenerationRequest request = new PawnGenerationRequest(pawnKind, ofPlayer, PawnGenerationContext.NonPlayer, -1, true, false, false, false, true, pawnMustBeCapableOfViolence, 20f, false, true, true, false, false, false, false, null, null, null, null, null, null, null, null); Pawn pawn = PawnGenerator.GeneratePawn(request); NameTriple old = pawn.Name as NameTriple; pawn.Name = new NameTriple(old.First, viewer.username, old.Last); GenSpawn.Spawn(pawn, loc, map, WipeMode.Vanish); string label = "Viewer Joins"; string text = $"A new pawn has been purchased by {viewer.username}, let's welcome them to the colony."; PawnRelationUtility.TryAppendRelationsWithColonistsInfo(ref text, ref label, pawn); Find.LetterStack.ReceiveLetter(label, text, LetterDefOf.PositiveEvent, pawn, null, null); Current.Game.GetComponent <GameComponentPawns>().AssignUserToPawn(viewer.username, pawn); viewer.TakeViewerCoins(this.storeIncident.cost); viewer.SetViewerKarma(Karma.CalculateNewKarma(viewer.GetViewerKarma(), this.storeIncident.karmaType, this.storeIncident.cost)); StorePurchaseLogger.LogPurchase(new Purchase(viewer.username, "", this.storeIncident.karmaType, this.storeIncident.cost, "", DateTime.Now)); Toolkit.client.SendMessage($"@{viewer.username} has purchased a pawn and is joining the colony.", separateChannel); }
public ApiUserInfo UserInfo(string userName) { if (userName != "deleted" && !UserHelper.UserExists(userName)) { throw new HttpResponseException(HttpStatusCode.NotFound); } if (userName == "deleted") { throw new HttpResponseException(HttpStatusCode.NotFound); } ApiUserInfo userInfo = CacheHandler.Register <ApiUserInfo>(String.Format("LegacyApi.UserInfo.{0}", userName), new Func <ApiUserInfo>(() => { using (voatEntities db = new voatEntities(CONSTANTS.CONNECTION_READONLY)) { var resultModel = new ApiUserInfo(); var userBadgesList = UserHelper.UserBadges(userName); var resultBadgesList = userBadgesList.Select(item => new ApiUserBadge { Awarded = item.CreationDate, BadgeName = item.Badge.Name }).ToList(); resultModel.Name = userName; resultModel.CCP = Karma.CommentKarma(userName); resultModel.LCP = Karma.LinkKarma(userName); resultModel.RegistrationDate = UserHelper.GetUserRegistrationDateTime(userName); resultModel.Badges = resultBadgesList; return(resultModel); } }), TimeSpan.FromMinutes(90)); return(userInfo); }
public ActionResult Submit([Bind(Include = "Id,Votes,Name,Date,Type,Linkdescription,Title,Rank,MessageContent,Subverse")] Message message) { // abort if model state is invalid if (!ModelState.IsValid) { return(View()); } // save temp values for the view in case submission fails ViewBag.selectedSubverse = message.Subverse; ViewBag.message = message.MessageContent; ViewBag.title = message.Title; ViewBag.linkDescription = message.Linkdescription; // check if user is banned if (Utils.User.IsUserGloballyBanned(message.Name) || Utils.User.IsUserBannedFromSubverse(User.Identity.Name, message.Subverse)) { ViewBag.SelectedSubverse = message.Subverse; return(View("~/Views/Home/Comments.cshtml", message)); } // check if user has reached hourly posting quota for target subverse if (Utils.User.UserHourlyPostingQuotaForSubUsed(User.Identity.Name, message.Subverse)) { ModelState.AddModelError("", "You have reached your hourly submission quota for this subverse."); return(View()); } // check if user has reached daily posting quota for target subverse if (Utils.User.UserDailyPostingQuotaForSubUsed(User.Identity.Name, message.Subverse)) { ModelState.AddModelError("", "You have reached your daily submission quota for this subverse."); return(View()); } // verify recaptcha if user has less than 25 CCP var userCcp = Karma.CommentKarma(User.Identity.Name); if (userCcp < 25) { string encodedResponse = Request.Form["g-Recaptcha-Response"]; bool isCaptchaCodeValid = (ReCaptchaUtility.Validate(encodedResponse) == "True" ? true : false); if (!isCaptchaCodeValid) { ModelState.AddModelError("", "Incorrect recaptcha answer."); // TODO // SET PREVENT SPAM DELAY TO 0 return(View()); } } // if user CCP or SCP is less than -50, allow only X submissions per 24 hours var userScp = Karma.LinkKarma(User.Identity.Name); if (userCcp <= -50 || userScp <= -50) { var quotaUsed = Utils.User.UserDailyPostingQuotaForNegativeScoreUsed(User.Identity.Name); if (quotaUsed) { ModelState.AddModelError("", "You have reached your daily submission quota. Your current quota is " + Convert.ToInt32(ConfigurationManager.AppSettings["dailyPostingQuotaForNegativeScore"]) + " submission(s) per 24 hours."); return(View()); } } // abort if model state is invalid if (!ModelState.IsValid) { return(View("Submit")); } // check if subverse exists var targetSubverse = _db.Subverses.Find(message.Subverse.Trim()); if (targetSubverse == null || message.Subverse.Equals("all", StringComparison.OrdinalIgnoreCase)) { ModelState.AddModelError(string.Empty, "Sorry, The subverse you are trying to post to does not exist."); return(View("Submit")); } // check if subverse has "authorized_submitters_only" set and dissalow submission if user is not allowed submitter if (targetSubverse.authorized_submitters_only) { if (!Utils.User.IsUserSubverseModerator(User.Identity.Name, targetSubverse.name)) { // user is not a moderator, check if user is an administrator if (!Utils.User.IsUserSubverseAdmin(User.Identity.Name, targetSubverse.name)) { ModelState.AddModelError("", "You are not authorized to submit links or start discussions in this subverse. Please contact subverse moderators for authorization."); return(View("Submit")); } } } // everything was okay, process incoming submission // submission is a link post // generate a thumbnail if submission is a direct link to image or video if (message.Type == 2 && message.MessageContent != null && message.Linkdescription != null) { // strip unicode if title contains unicode if (Submissions.ContainsUnicode(message.Linkdescription)) { message.Linkdescription = Submissions.StripUnicode(message.Linkdescription); } // abort if title less than 10 characters if (message.Linkdescription.Length < 10) { ModelState.AddModelError(string.Empty, "Sorry, the title may not be less than 10 characters."); return(View("Submit")); } var domain = UrlUtility.GetDomainFromUri(message.MessageContent); // check if target subvere allows submissions from globally banned hostnames if (!targetSubverse.exclude_sitewide_bans) { // check if hostname is banned before accepting submission if (BanningUtility.IsHostnameBanned(domain)) { ModelState.AddModelError(string.Empty, "Sorry, the hostname you are trying to submit is banned."); return(View("Submit")); } } // check if same link was submitted before and deny submission var existingSubmission = _db.Messages.FirstOrDefault(s => s.MessageContent.Equals(message.MessageContent, StringComparison.OrdinalIgnoreCase) && s.Subverse.Equals(message.Subverse, StringComparison.OrdinalIgnoreCase)); // submission is a repost, discard it and inform the user if (existingSubmission != null) { ModelState.AddModelError(string.Empty, "Sorry, this link has already been submitted by someone else."); // todo: offer the option to repost after informing the user about it return(RedirectToRoute( "SubverseComments", new { controller = "Comment", action = "Comments", id = existingSubmission.Id, subversetoshow = existingSubmission.Subverse } )); } // check if user has reached daily crossposting quota if (Utils.User.DailyCrossPostingQuotaUsed(User.Identity.Name, message.MessageContent)) { ModelState.AddModelError("", "You have reached your daily crossposting quota for this URL."); return(View()); } // 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 message.Thumbnail = ThumbGenerator.ThumbnailFromSubmissionModel(message); } // flag the submission as anonymized if it was submitted to a subverse with active anonymized_mode if (targetSubverse.anonymized_mode) { message.Anonymized = true; } else { message.Name = User.Identity.Name; } // accept submission and save it to the database message.Subverse = targetSubverse.name; // grab server timestamp and modify submission timestamp to have posting time instead of "started writing submission" time message.Date = DateTime.Now; message.Likes = 1; _db.Messages.Add(message); // update last submission received date for target subverse targetSubverse.last_submission_received = DateTime.Now; _db.SaveChanges(); } else if (message.Type == 1 && message.Title != null) { // submission is a self post // strip unicode if message contains unicode if (Submissions.ContainsUnicode(message.Title)) { message.Title = Submissions.StripUnicode(message.Title); } // abort if title less than 10 characters if (message.Title.Length < 10) { ModelState.AddModelError(string.Empty, "Sorry, the the message title may not be less than 10 characters."); return(View("Submit")); } // accept submission and save it to the database // trim trailing blanks from subverse name if a user mistakenly types them message.Subverse = targetSubverse.name; // flag the submission as anonymized if it was submitted to a subverse with active anonymized_mode if (targetSubverse.anonymized_mode) { message.Anonymized = true; } else { message.Name = User.Identity.Name; } // grab server timestamp and modify submission timestamp to have posting time instead of "started writing submission" time message.Date = DateTime.Now; message.Likes = 1; _db.Messages.Add(message); // update last submission received date for target subverse targetSubverse.last_submission_received = DateTime.Now; if (ContentProcessor.Instance.HasStage(ProcessingStage.InboundPreSave)) { message.MessageContent = ContentProcessor.Instance.Process(message.MessageContent, ProcessingStage.InboundPreSave, message); } _db.SaveChanges(); if (ContentProcessor.Instance.HasStage(ProcessingStage.InboundPostSave)) { ContentProcessor.Instance.Process(message.MessageContent, ProcessingStage.InboundPostSave, message); } } return(RedirectToRoute( "SubverseComments", new { controller = "Comment", action = "Comments", id = message.Id, subversetoshow = message.Subverse } )); }
static Karma GetUserKarma(string username) { try { WebClient wc = new WebClient(); StreamReader sr = new StreamReader(wc.OpenRead("http://reddit.com/user/" + username + "/about.json")); string data = sr.ReadToEnd(); sr.Close(); JObject json = JObject.Parse(data); Karma karma = new Karma(); karma.CommentKarma = json["data"]["comment_karma"].Value<int>(); karma.LinkKarma = json["data"]["link_karma"].Value<int>(); karma.Created = TimeSpanExtensions.UnixTimeStampToDateTime(json["data"]["created_utc"].Value<double>()); return karma; } catch (Exception e) { if (Debugger.IsAttached) Console.WriteLine(e.ToString()); } return null; }