Move mediaproxy URL rewriting to ProxyService

This shows full size avatars in API / cards.

Also, rewrite URLs currently stored with media.discordapp.net "back" to
cdn.discordapp.com before sending them to users.
This commit is contained in:
spiral
2021-08-01 12:51:54 -04:00
parent 2bb8c084c9
commit dcc15dc847
15 changed files with 44 additions and 35 deletions

View File

@@ -1,6 +1,7 @@
using System;
using System.Linq;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using PluralKit.Core;
@@ -28,6 +29,8 @@ namespace PluralKit.Bot {
if (!PluralKit.Core.MiscUtils.TryMatchUri(url, out var uri))
throw Errors.InvalidUrl(url);
url = TryRewriteCdnUrl(url);
var response = await client.GetAsync(uri);
if (!response.IsSuccessStatusCode) // Check status code
throw Errors.AvatarServerError(response.StatusCode);
@@ -46,5 +49,13 @@ namespace PluralKit.Bot {
throw Errors.AvatarDimensionsTooLarge(image.Width, image.Height);
}
}
// Rewrite cdn.discordapp.com URLs to media.discordapp.net for jpg/png files
// This lets us add resizing parameters to "borrow" their media proxy server to downsize the image
// which in turn makes it more likely to be underneath the size limit!
private static readonly Regex DiscordCdnUrl = new Regex(@"^https?://(?:cdn\.discordapp\.com|media\.discordapp\.net)/attachments/(\d{17,19})/(\d{17,19})/([^/\\&\?]+)\.(png|jpg|jpeg|webp)(\?.*)?$");
private static readonly string DiscordMediaUrlReplacement = "https://media.discordapp.net/attachments/$1/$2/$3.$4?width=256&height=256";
public static string TryRewriteCdnUrl(string url) =>
DiscordCdnUrl.Replace(url, DiscordMediaUrlReplacement);
}
}

View File

@@ -11,7 +11,7 @@ namespace PluralKit.Bot
member.NameFor(ctx.LookupContextFor(member));
public static string AvatarFor(this PKMember member, Context ctx) =>
member.AvatarFor(ctx.LookupContextFor(member));
member.AvatarFor(ctx.LookupContextFor(member)).TryGetCleanCdnUrl();
public static string DisplayName(this PKMember member) =>
member.DisplayName ?? member.Name;