From 1d3583c194c396948ee110882d33ba56374b166e Mon Sep 17 00:00:00 2001 From: Daniel Cazzulino Date: Fri, 27 Sep 2024 18:12:52 -0300 Subject: [PATCH] Allow retrieving a shields.io badge with nuget stats Examples: - https://img.shields.io/endpoint?url=https%3A%2F%2Fsponsorlink.devlooped.com%2Fnuget%2Fall%3Fkzu - https://img.shields.io/endpoint?url=https%3A%2F%2Fsponsorlink.devlooped.com%2Fnuget%2Fdl%3Fkzu --- src/Web/Stats.cs | 62 ++++++++++++++++++++++++++++++++++++++++++++++ src/Web/Web.csproj | 1 + 2 files changed, 63 insertions(+) create mode 100644 src/Web/Stats.cs diff --git a/src/Web/Stats.cs b/src/Web/Stats.cs new file mode 100644 index 00000000..1f5c436f --- /dev/null +++ b/src/Web/Stats.cs @@ -0,0 +1,62 @@ +using Microsoft.Azure.Functions.Worker.Http; +using Microsoft.Azure.Functions.Worker; +using System.Net; +using Humanizer; + +namespace Devlooped.Sponsors; + +public class Stats(AsyncLazy oss, SponsorsManager manager) +{ + readonly TimeSpan expiration = TimeSpan.FromDays(1); + + [Function("nuget-count")] + public async Task NuGetCountAsync([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "nuget/all")] HttpRequestData req) + { + var stats = await oss; + var manifest = await manager.GetManifestAsync(); + var owner = req.Query.Count == 1 ? req.Query.ToString() : manifest.Sponsorable; + + var count = stats.Packages + .Where(x => x.Key.StartsWith(owner + "/")) + .Sum(x => x.Value.Count); + + var output = req.CreateResponse(HttpStatusCode.OK); + + // Also cache downstream (specifically shields.io) + output.Headers.Add("Cache-Control", "public,max-age=" + expiration.TotalSeconds); + await output.WriteAsJsonAsync(new + { + schemaVersion = 1, + label = "nugets", + message = ((double)count).ToMetric(decimals: 1) + }); + + return output; + } + + [Function("nuget-downloads")] + public async Task NuGetDownloadsAsync([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "nuget/dl")] HttpRequestData req) + { + var stats = await oss; + var manifest = await manager.GetManifestAsync(); + var owner = req.Query.Count == 1 ? req.Query.ToString() : manifest.Sponsorable; + + var count = stats.Packages + .Where(x => x.Key.StartsWith(owner + "/")) + .Sum(x => x.Value.Sum(y => y.Value)); + + var output = req.CreateResponse(HttpStatusCode.OK); + + // Also cache downstream (specifically shields.io) + output.Headers.Add("Cache-Control", "public,max-age=" + expiration.TotalSeconds); + await output.WriteAsJsonAsync(new + { + schemaVersion = 1, + label = "dl/day", + message = ((double)count).ToMetric(decimals: 1) + }); + + return output; + } + +} \ No newline at end of file diff --git a/src/Web/Web.csproj b/src/Web/Web.csproj index 5b37726a..76cc0ee3 100644 --- a/src/Web/Web.csproj +++ b/src/Web/Web.csproj @@ -10,6 +10,7 @@ +