Skip to content

Commit c349a55

Browse files
committed
setup storing metrics in memory and serve by url
1 parent a850970 commit c349a55

4 files changed

Lines changed: 66 additions & 19 deletions

File tree

Excursion360.Desktop/ImageMetricsMiddleware.cs

Lines changed: 0 additions & 14 deletions
This file was deleted.

Excursion360.Desktop/Program.cs

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@
1111
Console.ForegroundColor = ConsoleColor.White;
1212

1313
var builder = WebApplication.CreateBuilder(args);
14-
1514
builder.Logging.SetMinimumLevel(LogLevel.Information);
15+
builder.Services.AddSingleton<IStateImagesMetricsStore, InMemoryIStateImagesMetricsStore>();
1616

1717
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
1818
{
@@ -24,9 +24,15 @@
2424
}
2525

2626
var app = builder.Build();
27-
app.UseMiddleware<ImageMetricsMiddleware>();
2827
var targetDirectory = GetExcursionDirectory(builder.Configuration.ExcursionDirectoryPath());
2928

29+
app.MapGet("/eapi/preload.json", (IStateImagesMetricsStore stateImagesMetrics) => {
30+
return new
31+
{
32+
images = stateImagesMetrics.MostPopularUrls(),
33+
};
34+
});
35+
3036
var fso = new FileServerOptions
3137
{
3238
FileProvider = new CompositeFileProvider(
@@ -36,8 +42,11 @@
3642
fso.DefaultFilesOptions.DefaultFileNames.Add("Resources/NotFound.html");
3743
fso.StaticFileOptions.OnPrepareResponse = (context) =>
3844
{
39-
context.Context.Response.Headers.CacheControl = "no-cache, no-store";
40-
context.Context.Response.Headers.Expires = "-1";
45+
if (context.File.Name.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && context.File.PhysicalPath is not null)
46+
{
47+
var stateImagesMetricsStore = context.Context.RequestServices.GetRequiredService<IStateImagesMetricsStore>();
48+
stateImagesMetricsStore.IncrementImageHit(context.Context.Request.Path);
49+
}
4150
};
4251
app.UseFileServer(fso);
4352

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
using System.Collections.Concurrent;
2+
using System.Text.Json;
3+
using System.Text.RegularExpressions;
4+
5+
namespace Excursion360.Desktop.Services;
6+
7+
public interface IStateImagesMetricsStore
8+
{
9+
void IncrementImageHit(string path);
10+
string[] MostPopularUrls();
11+
}
12+
13+
public partial class InMemoryIStateImagesMetricsStore : IStateImagesMetricsStore
14+
{
15+
/// <summary>
16+
/// Количества получений картинок по адресу. ключ = адрес картинки. Значение - количество получений.
17+
/// </summary>
18+
private readonly ConcurrentDictionary<string, int>
19+
hitCounts = new();
20+
private Regex stateAndImageRegex = GetStateAndImageRegex();
21+
public void IncrementImageHit(string path)
22+
{
23+
var match = stateAndImageRegex.Match(path);
24+
if (!match.Success)
25+
{
26+
return;
27+
}
28+
hitCounts.AddOrUpdate(path, 1, (_, old) => old + 1);
29+
Console.WriteLine(JsonSerializer.Serialize(hitCounts, new JsonSerializerOptions
30+
{
31+
WriteIndented = true,
32+
}));
33+
}
34+
public string[] MostPopularUrls()
35+
{
36+
return hitCounts
37+
.OrderByDescending(kvp => kvp.Value)
38+
.ThenBy(kvp => kvp.Key)
39+
.Select(kvp => kvp.Key)
40+
.Take(10)
41+
.ToArray();
42+
}
43+
44+
[GeneratedRegex(@"state_.+[/\\].+\.jpg$")]
45+
private static partial Regex GetStateAndImageRegex();
46+
47+
}

ReleaseNotes.md

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,6 @@
1-
# Возможность выбирать используемый браузер из установленных на ПК
1+
- `v4.0`
2+
- Обновлен .NET/Nuke до 8, убраны все предупреждения
3+
- Обновлена структура проекта до последней версии ASP.NET Core
4+
- Базовая папка для выбора экскурсий может выбираться через `--excursionsPath путь_к_папке`
5+
- Добавлена обработка `/eapi/preload.json`, по которому будут отдаваться адреса изображений, которые чаще всего просматриваются
6+
- `v3.0` Возможность выбирать используемый браузер из установленных на ПК

0 commit comments

Comments
 (0)