private WebhookCreateAuditLogData(IWebhook webhook, WebhookType type, string name, ulong channelId) { Webhook = webhook; Name = name; Type = type; ChannelId = channelId; }
public async Task SavesExpectedValues(WebhookType webhookType) { var guid = Guid.NewGuid().ToString(); var json = @"{""A"": ""B""}"; await Connection.ExecuteAsync($@" INSERT INTO ""user"" (twitchuserid, guid) VALUES (1, '{guid}'); "); var userId = await Connection.QueryFirstAsync <int>(@" SELECT id FROM ""user"" LIMIT 1; "); var handler = new SaveWebhookJson.Handler(Connection); await handler.Handle(new SaveWebhookJson.Request(webhookType, guid, json), CancellationToken.None); var result = await Connection.QuerySingleAsync(@" SELECT * FROM webhookdumps; "); ((WebhookType)result.webhooktypeid).Should().Be(webhookType); ((int)result.userid).Should().Be(userId); ((DateTime)result.datecreated).Should().BeCloseTo(DateTime.UtcNow, precision: 1000); ((string)result.jsondata).Should().Be(json); }
private WebhookDeleteAuditLogData(ulong id, ulong channel, WebhookType type, string name, string avatar) { WebhookId = id; ChannelId = channel; Name = name; Type = type; Avatar = avatar; }
private object[] BuildFields(WebhookType webhookType, string adminName, string reason, string playerId, uint duration) { var fields = Array.Empty <object>(); switch (webhookType) { case WebhookType.BanEvading: fields = new[] { Discord.BuildDiscordField(m_StringLocalizer["webhooks:global:steam64id"], playerId, true), Discord.BuildDiscordField(m_StringLocalizer["webhooks:global:time"], DateTime.Now.ToString(CultureInfo.InvariantCulture), true), Discord.BuildDiscordField(m_StringLocalizer["webhooks:global:reason"], reason, false), Discord.BuildDiscordField(m_StringLocalizer["webhooks:global:duration"], duration.ToString(), true) }; break; case WebhookType.Ban: fields = new[] { Discord.BuildDiscordField(m_StringLocalizer["webhooks:global:steam64id"], playerId, true), Discord.BuildDiscordField(m_StringLocalizer["webhooks:ban:banned_by"], adminName, true), Discord.BuildDiscordField(m_StringLocalizer["webhooks:global:time"], DateTime.Now.ToString(CultureInfo.InvariantCulture), false), Discord.BuildDiscordField(m_StringLocalizer["webhooks:global:reason"], reason, true), Discord.BuildDiscordField(m_StringLocalizer["webhooks:global:duration"], duration.ToString(), true) }; break; case WebhookType.Kick: fields = new[] { Discord.BuildDiscordField(m_StringLocalizer["webhooks:global:steam64id"], playerId, true), Discord.BuildDiscordField(m_StringLocalizer["webhooks:kick:kicked_by"], adminName, true), Discord.BuildDiscordField(m_StringLocalizer["webhooks:global:time"], DateTime.Now.ToString(CultureInfo.InvariantCulture), false), Discord.BuildDiscordField(m_StringLocalizer["webhooks:global:reason"], reason, true) }; break; case WebhookType.Unban: fields = new[] { Discord.BuildDiscordField(m_StringLocalizer["webhooks:global:steam64id"], playerId, true), Discord.BuildDiscordField(m_StringLocalizer["webhooks:unban:unbanned_by"], adminName, true), Discord.BuildDiscordField(m_StringLocalizer["webhooks:global:time"], DateTime.Now.ToString(CultureInfo.InvariantCulture), false) }; break; } return(fields); }
public void SendWebhook(WebhookType webhookType, string playerName, string adminName, string reason, string playerId, uint duration) { Discord.SendWebhookPost(m_Configuration[$"webhooks:{webhookType.ToString().ToLower()}:url"], Discord.BuildDiscordEmbed(m_StringLocalizer[$"webhooks:{webhookType.ToString().ToLower()}:title"], m_StringLocalizer[$"webhooks:{webhookType.ToString().ToLower()}:description", new { Player = playerName, Reason = reason }], m_StringLocalizer["webhooks:global:displayname"], m_Configuration["webhooks:image_url"], m_Configuration.GetSection($"webhooks:{webhookType.ToString().ToLower()}:color").Get <int>(), BuildFields(webhookType, adminName, reason, playerId, duration))); }
public IWebhookBuilder Create(WebhookType type) { switch (type) { case WebhookType.Discord: return(new DiscordWebhookBuilder()); default: throw new ArgumentException("Invalid webhook type"); } }
public static string WebhookTypeToString(WebhookType type) { return(type switch { WebhookType.Pokemon => "pokemon", WebhookType.Pokestops => "pokestops", WebhookType.Raids => "raids", WebhookType.Eggs => "eggs", WebhookType.Quests => "quests", WebhookType.Lures => "lures", WebhookType.Invasions => "invasions", WebhookType.Gyms => "gyms", WebhookType.Weather => "weather", _ => "pokemon", });
public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "delete")] HttpRequestMessage req, [Table("webhookRegistration")] IQueryable <WebhookRegistrationEntity> existingWebhooks, [Table("webhookRegistration")] CloudTable webhookRegistrationTable, TraceWriter log) { dynamic data = await req.Content.ReadAsAsync <object>(); int type = data?.type; string webhook = data?.webhook; WebhookType webhookTypeValue = data?.webhookType; var lastBundleType = BundleTypes.SPECIAL; if (type < 0 || type > (int)lastBundleType) { return(req.CreateResponse(HttpStatusCode.BadRequest, "Please pass in a valid Bundle Type int (0 - " + (int)lastBundleType + ")")); } var bundleType = (BundleTypes)type; if (webhook == null) { return(req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a webhook in the request body")); } if (webhookTypeValue == WebhookType.Discord) { if (!webhook.Contains("discordapp.com/api/webhooks/")) { return(req.CreateResponse(HttpStatusCode.BadRequest, "Please pass in a valid Discord Webhook URL in the request body")); } } var entity = existingWebhooks.ToList().FirstOrDefault(x => x.BundleType == type && x.GetDecryptedWebhook() == webhook); if (entity == null) { return(req.CreateResponse(HttpStatusCode.NotFound, "Could not find a registered Webhook for the given Bundle Type")); } var deleteOperation = TableOperation.Delete(entity); webhookRegistrationTable.Execute(deleteOperation); return(req.CreateResponse(HttpStatusCode.OK)); }
internal static WebhookDeleteAuditLogData Create(BaseDiscordClient discord, Model log, EntryModel entry) { API.AuditLogChangeJson[] changes = entry.Changes; API.AuditLogChangeJson channelIdModel = changes.FirstOrDefault(x => x.ChangedProperty == "channel_id"); API.AuditLogChangeJson typeModel = changes.FirstOrDefault(x => x.ChangedProperty == "type"); API.AuditLogChangeJson nameModel = changes.FirstOrDefault(x => x.ChangedProperty == "name"); API.AuditLogChangeJson avatarHashModel = changes.FirstOrDefault(x => x.ChangedProperty == "avatar_hash"); ulong channelId = channelIdModel.OldValue.ToObject <ulong>(discord.ApiClient.Serializer); WebhookType type = typeModel.OldValue.ToObject <WebhookType>(discord.ApiClient.Serializer); string name = nameModel.OldValue.ToObject <string>(discord.ApiClient.Serializer); string avatarHash = avatarHashModel?.OldValue?.ToObject <string>(discord.ApiClient.Serializer); return(new WebhookDeleteAuditLogData(entry.TargetId.Value, channelId, type, name, avatarHash)); }
internal static WebhookCreateAuditLogData Create(BaseDiscordClient discord, Model log, EntryModel entry) { API.AuditLogChangeJson[] changes = entry.Changes; API.AuditLogChangeJson channelIdModel = changes.FirstOrDefault(x => x.ChangedProperty == "channel_id"); API.AuditLogChangeJson typeModel = changes.FirstOrDefault(x => x.ChangedProperty == "type"); API.AuditLogChangeJson nameModel = changes.FirstOrDefault(x => x.ChangedProperty == "name"); ulong channelId = channelIdModel.NewValue.ToObject <ulong>(discord.ApiClient.Serializer); WebhookType type = typeModel.NewValue.ToObject <WebhookType>(discord.ApiClient.Serializer); string name = nameModel.NewValue.ToObject <string>(discord.ApiClient.Serializer); API.WebhookJson webhookInfo = log.Webhooks?.FirstOrDefault(x => x.Id == entry.TargetId); RestWebhook webhook = webhookInfo == null ? null : RestWebhook.Create(discord, (IGuild)null, webhookInfo); return(new WebhookCreateAuditLogData(webhook, entry.TargetId.Value, type, name, channelId)); }
/// <summary> /// Converts a WebhookType value to a corresponding string value /// </summary> /// <param name="enumValue">The WebhookType value to convert</param> /// <returns>The representative string value</returns> public static string ToValue(WebhookType enumValue) { switch (enumValue) { //only valid enum elements can be used //this is necessary to avoid errors case WebhookType.INTEREST_CHARGE: case WebhookType.SCHEDULED_PAYMENT_CANCELLED: case WebhookType.SCHEDULED_PAYMENT_INSUFFICIENT_FUNDS: case WebhookType.TRANSACTION_CARD: case WebhookType.TRANSACTION_CASH_WITHDRAWAL: case WebhookType.TRANSACTION_MOBILE_WALLET: case WebhookType.TRANSACTION_DIRECT_CREDIT: case WebhookType.TRANSACTION_DIRECT_DEBIT: case WebhookType.TRANSACTION_DIRECT_DEBIT_INSUFFICIENT_FUNDS: case WebhookType.TRANSACTION_DIRECT_DEBIT_DISPUTE: case WebhookType.TRANSACTION_FASTER_PAYMENT_IN: case WebhookType.TRANSACTION_FASTER_PAYMENT_OUT: case WebhookType.TRANSACTION_FASTER_PAYMENT_REVERSAL: case WebhookType.TRANSACTION_INTEREST_PAYMENT: case WebhookType.TRANSACTION_INTERNAL_TRANSFER: case WebhookType.TRANSACTION_NOSTRO_DEPOSIT: case WebhookType.TRANSACTION_ON_US_PAYMENT_IN: case WebhookType.TRANSACTION_ON_US_PAYMENT_OUT: case WebhookType.TRANSACTION_INTEREST_WAIVED_DEPOSIT: case WebhookType.TRANSACTION_STRIPE_FUNDING: case WebhookType.TRANSACTION_DECLINED_INSUFFICIENT_FUNDS: case WebhookType.TRANSACTION_AUTH_DECLINED: case WebhookType.TRANSACTION_AUTH_PARTIAL_REVERSAL: case WebhookType.TRANSACTION_AUTH_FULL_REVERSAL: return(StringValues[(int)enumValue]); //an invalid enum value was requested default: return(null); } }
public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, [Table("humbleBundles")] IQueryable <HumbleBundleEntity> currentTableBundles, [Table("webhookRegistration")] IQueryable <WebhookRegistrationEntity> existingWebhooks, [Queue("jsonmessagequeue")] ICollector <JsonMessage> jsonMessageQueue, [Queue("discordmessagequeue")] ICollector <DiscordMessage> discordMessageQueue, TraceWriter log) { req.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); dynamic data = await req.Content.ReadAsAsync <object>(); string webhook = data?.webhook; int bundleTypeValue = data?.type; WebhookType webhookType = data?.webhookType; string bundleName = data?.bundleName; var bundleType = (BundleTypes)bundleTypeValue; if (webhook == null) { log.Error("No webhook provided"); return(req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a webhook in the request body")); } var webhookToTest = existingWebhooks.ToList().FirstOrDefault(x => x.WebhookType == (int)webhookType && x.GetDecryptedWebhook() == webhook); if (webhookToTest == null) { return(req.CreateResponse(HttpStatusCode.NotFound, $"Could not find registered webhook {webhook} for type {webhookType}")); } var currentBundles = currentTableBundles.ToList().Select(x => x.GetBundle()).ToList(); var bundleToSend = currentBundles.First(x => x.Type == bundleType || bundleType == BundleTypes.ALL); if (!string.IsNullOrEmpty(bundleName)) { bundleToSend = currentBundles.FirstOrDefault(x => (x.Type == bundleType || bundleType == BundleTypes.ALL) && x.Name.Equals(bundleName, System.StringComparison.CurrentCultureIgnoreCase)); if (bundleToSend == null) { return(req.CreateResponse(HttpStatusCode.NotFound, "Could not find bundle " + bundleName)); } } var queuedBundle = new BundleQueue() { Bundle = bundleToSend, IsUpdate = false }; if (webhookType == WebhookType.Discord) { discordMessageQueue.Add(new DiscordMessage { WebhookUrl = webhook, Payload = new DiscordWebhookPayload(queuedBundle, bundleToSend) }); } else if (webhookType == WebhookType.RawJson) { jsonMessageQueue.Add(new JsonMessage() { WebhookUrl = webhook, Payload = queuedBundle }); } return(req.CreateResponse(HttpStatusCode.OK)); }
public void HandleException(WebhookType webhookType, Exception exception) { HandleException(webhookType.ToString(), exception); }
public object Send(WebhookType webhookType, object body = null, string method = null, Dictionary <string, object> queryStringParameters = null, Dictionary <string, string> headers = null, bool ignoreNotFound = false, object originalBody = null, GetResponseObject GetResponseObject = null, HttpActionExecutedContext actionExecutedContext = null) { return(Send(webhookType.ToString(), body, method, queryStringParameters, headers, ignoreNotFound, originalBody, GetResponseObject, actionExecutedContext)); }
public async Task <IEnumerable <WebhookSubscription> > GetSubscriptionsOfType(WebhookType type) { var data = await _db.Subscriptions.Where(s => s.Type == type).ToListAsync(); return(data); }
public Request(WebhookType webhookType, string guid, string json) { WebhookType = webhookType; Guid = guid; Json = json; }
public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestMessage req, [Table("webhookRegistration")] IQueryable <WebhookRegistrationEntity> inTable, [Table("webhookRegistration")] ICollector <WebhookRegistrationEntity> outTable, TraceWriter log) { try { req.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); dynamic data = await req.Content.ReadAsAsync <object>(); int bundleTypeValue = data?.type; string webhook = data?.webhook; bool receiveUpdates = data?.sendUpdates; string partner = data?.partner; WebhookType webhookTypeValue = data?.webhookType; log.Info($"Recieved webhook registration for type {bundleTypeValue}. RecieveUpdates? {receiveUpdates}"); var lastBundleType = BundleTypes.ALL; if (bundleTypeValue < 0 || bundleTypeValue > (int)lastBundleType) { log.Error("Invalid type passed in"); return(req.CreateResponse(HttpStatusCode.BadRequest, "Please pass in a valid Bundle Type int (0 - " + (int)lastBundleType + ")")); } var bundleType = (BundleTypes)bundleTypeValue; if (webhook == null) { log.Error("No webhook provided"); return(req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a webhook in the request body")); } var webhookType = (WebhookType)webhookTypeValue; if (webhookType == WebhookType.Discord) { if (!webhook.Contains("discordapp.com/api/webhooks/") && !webhook.Contains("discord.com/api/webhooks/")) { log.Error("Invalid webhook provided"); return(req.CreateResponse(HttpStatusCode.BadRequest, "Please pass in a valid Discord Webhook URL in the request body")); } } if (inTable.ToList().Any(x => x.GetDecryptedWebhook() == webhook && x.BundleType == bundleTypeValue)) { log.Error("Webhook already registered"); return(req.CreateResponse(HttpStatusCode.Conflict, "This webhook URL is already registered for this Bundle type")); } outTable.Add(new WebhookRegistrationEntity(bundleType, webhook, receiveUpdates, webhookType, partner)); return(req.CreateResponse(HttpStatusCode.Created)); } catch (Exception e) { log.Error(e.Message); return(req.CreateResponse(HttpStatusCode.BadRequest, "Webhook registration failed - Exception: " + e.Message)); } }
public WebhookRegistrationEntity(BundleTypes type, string webhook, bool shouldRecieveUpdates, WebhookType webhookType) { PartitionKey = type.ToString(); RowKey = System.Guid.NewGuid().ToString(); EncryptedWebhook = MachineKey.Protect(Encoding.UTF8.GetBytes(webhook)); ShouldRecieveUpdates = shouldRecieveUpdates; BundleType = (int)type; WebhookType = (int)webhookType; }
public WebhookData(WebhookType hookType, object data) { When = DateTime.UtcNow; Type = hookType.ToString(); Payload = JsonConvert.SerializeObject(data); }