Repository navigation
feat: sync OpenShock control stats to Discord profile widgets #89
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
e7f055c
feat: sync OpenShock control stats to Discord profile widgets
LucHeart 0be599f
Merge remote-tracking branch 'origin/master' into feat/profile-widget
LucHeart b88d5f0
chore: upgrade to .NET 11
LucHeart 44982e3
fix: don't drop widget grants when Discord refuses the whole application
LucHeart 0e54e39
chore(activity): upgrade to SvelteKit 3
LucHeart bf0314b
fix: delete stale widget identities and keep track of them across res…
LucHeart File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| using System.Net.Http.Json; | ||
|
|
||
| namespace OpenShock.DiscordBot.Services.Widget; | ||
|
|
||
| /// <summary> | ||
| /// Client for the OpenShock API's integration endpoint that reports users' lifetime control stats, but only | ||
| /// for users whose stats changed since a cursor. | ||
| /// </summary> | ||
| public sealed class ControlStatsClient | ||
| { | ||
| public const string AutomationTokenHeader = "X-OpenShock-Automation-Token"; | ||
|
|
||
| /// <summary>Server side limit of user ids per request.</summary> | ||
| private const int MaxUserIds = 1000; | ||
|
|
||
| private readonly HttpClient _http; | ||
|
|
||
| public ControlStatsClient(HttpClient http) | ||
| { | ||
| _http = http; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Totals of every user in <paramref name="userIds"/> whose stats changed since <paramref name="since"/>, or of | ||
| /// all of them when it is null. The returned cursor is the oldest one of all chunks. | ||
| /// </summary> | ||
| public async Task<ControlStatChanges> GetChangesAsync(DateTime? since, IReadOnlyCollection<Guid> userIds, | ||
| CancellationToken ct) | ||
| { | ||
| DateTime? cursor = null; | ||
| var users = new List<UserControlStatTotals>(); | ||
|
|
||
| foreach (var chunk in userIds.Chunk(MaxUserIds)) | ||
| { | ||
| using var response = await _http.PostAsJsonAsync("1/integrations/control-stats/changes", | ||
| new { since, userIds = chunk }, ct); | ||
| response.EnsureSuccessStatusCode(); | ||
|
|
||
| var page = await response.Content.ReadFromJsonAsync<ControlStatChanges>(ct) | ||
| ?? throw new InvalidOperationException("Empty control stats response"); | ||
| users.AddRange(page.Users); | ||
| if (cursor is null || page.Cursor < cursor) cursor = page.Cursor; | ||
| } | ||
|
|
||
| return new ControlStatChanges(cursor ?? DateTime.UtcNow, users); | ||
| } | ||
| } | ||
|
|
||
| public sealed record ControlStatChanges(DateTime Cursor, IReadOnlyList<UserControlStatTotals> Users); | ||
|
|
||
| public sealed record UserControlStatTotals(Guid UserId, ControlStatTotals[] Received, ControlStatTotals[] Given); | ||
|
|
||
| /// <summary>One control type's totals, <see cref="Type"/> is the API's enum name (Shock, Vibrate, Sound).</summary> | ||
| public sealed record ControlStatTotals( | ||
| string Type, | ||
| bool Live, | ||
| long Count, | ||
| long DurationMs, | ||
| double AverageIntensity, | ||
| byte MaxIntensity); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| using System.Net; | ||
| using System.Net.Http.Headers; | ||
| using System.Net.Http.Json; | ||
| using System.Text.Json.Nodes; | ||
| using Microsoft.Extensions.Logging; | ||
|
|
||
| namespace OpenShock.DiscordBot.Services.Widget; | ||
|
|
||
| public enum ProfileWidgetResult | ||
| { | ||
| Success, | ||
|
|
||
| /// <summary> | ||
| /// Discord answered 403. Either the user no longer grants <c>application_identities.write</c>, or the whole | ||
| /// application isn't allowed to write game stats (e.g. the game isn't claimed); the response doesn't tell which. | ||
| /// </summary> | ||
| Forbidden, | ||
|
|
||
| /// <summary>Anything else (rate limits, outages), worth retrying later.</summary> | ||
| Failed | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Writes Game Stats Widget data through Discord's Application Identity Profile API, authorized with the bot token. | ||
| /// </summary> | ||
| public sealed class ProfileWidgetClient | ||
| { | ||
| private readonly HttpClient _http; | ||
| private readonly DiscordBotConfig _config; | ||
| private readonly ILogger<ProfileWidgetClient> _logger; | ||
|
|
||
| public ProfileWidgetClient(HttpClient http, DiscordBotConfig config, ILogger<ProfileWidgetClient> logger) | ||
| { | ||
| _http = http; | ||
| _config = config; | ||
| _logger = logger; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Replaces the user's widget data for the given OpenShock identity. Discord replaces the whole data object on | ||
| /// every PATCH, so <paramref name="data"/> must always be complete; an empty object clears it. | ||
| /// </summary> | ||
| public async Task<ProfileWidgetResult> UpdateAsync(ulong applicationId, ulong discordId, Guid openShockId, | ||
| JsonObject data, CancellationToken ct) | ||
| { | ||
| using var request = new HttpRequestMessage(HttpMethod.Patch, | ||
| $"https://discord.com/api/v10/applications/{applicationId}/users/{discordId}/identities/{openShockId}/profile"); | ||
| request.Headers.Authorization = new AuthenticationHeaderValue("Bot", _config.Token); | ||
| request.Content = JsonContent.Create(new JsonObject { ["data"] = data }); | ||
|
|
||
| using var response = await _http.SendAsync(request, ct); | ||
| if (response.IsSuccessStatusCode) return ProfileWidgetResult.Success; | ||
|
|
||
| _logger.LogWarning("Profile widget update for {DiscordId} failed with {Status}: {Error}", | ||
| discordId, response.StatusCode, await response.Content.ReadAsStringAsync(ct)); | ||
|
|
||
| return response.StatusCode == HttpStatusCode.Forbidden | ||
| ? ProfileWidgetResult.Forbidden | ||
| : ProfileWidgetResult.Failed; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Deletes the profile-only identity (provider type <c>NONE</c>) the first <see cref="UpdateAsync"/> created, | ||
| /// widget data included. Discord only accepts writes for the provider issued user id of an existing identity, | ||
| /// so the old one has to go before writing for another OpenShock account. An identity that's already gone | ||
| /// counts as deleted. | ||
| /// </summary> | ||
| public async Task<ProfileWidgetResult> DeleteAsync(ulong applicationId, ulong discordId, Guid openShockId, | ||
| CancellationToken ct) | ||
| { | ||
| using var request = new HttpRequestMessage(HttpMethod.Post, | ||
| $"https://discord.com/api/v10/users/{discordId}/application-identities/{applicationId}/NONE/{openShockId}/delete"); | ||
| request.Headers.Authorization = new AuthenticationHeaderValue("Bot", _config.Token); | ||
|
|
||
| using var response = await _http.SendAsync(request, ct); | ||
| if (response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.NotFound) | ||
| return ProfileWidgetResult.Success; | ||
|
|
||
| _logger.LogWarning("Profile widget identity delete for {DiscordId} failed with {Status}: {Error}", | ||
| discordId, response.StatusCode, await response.Content.ReadAsStringAsync(ct)); | ||
|
|
||
| return response.StatusCode == HttpStatusCode.Forbidden | ||
| ? ProfileWidgetResult.Forbidden | ||
| : ProfileWidgetResult.Failed; | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Configure the required Discord User-Agent.
ProfileWidgetClientsets noUser-Agent, and this registration supplies none. Discord requiresDiscordBot ($url, $versionNumber)and may block requests that omit it. This can prevent widget writes and clears. Configure the header on this typed client; the header onControlStatsClientdoes not apply here. (docs.discord.com)