Files
ucvl-zonghengjia-open-source/windows/UsageHistorySeries.cs
T
2026-10-11 23:23:20 +00:00

72 lines
4.8 KiB
C#

using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace UCVL.VPNPlus;
internal sealed record UsageHistoryPeriod(string Key, string Label, int Count, string Bucket)
{
internal static readonly UsageHistoryPeriod[] All = [new("12h", "近 12 小时", 12, "hour"),
new("1d", "近 1 天", 24, "hour"), new("7d", "近 7 天", 7, "day"), new("30d", "近 1 个月", 30, "day")];
public override string ToString() => Label;
}
internal sealed class UsageHistorySeries
{
[JsonPropertyName("scope")] public string Scope { get; init; } = "subscription";
[JsonPropertyName("bucket")] public string Bucket { get; init; } = "day";
[JsonPropertyName("timezone")] public string Timezone { get; init; } = "Asia/Shanghai";
[JsonPropertyName("note")] public string Note { get; init; } = "";
[JsonPropertyName("points")] public List<UsageHistoryPoint> Points { get; init; } = [];
internal static UsageHistorySeries? Select(UsageHistoryPeriod period, List<DailyUsage> legacy,
Dictionary<string, UsageHistorySeries>? ranges)
{
if (ranges?.TryGetValue(period.Key, out var series) == true && series is not null)
{
// Never plot another scope/resolution, an incomplete interval or reordered timestamps.
if (series.Scope != "subscription" || series.Bucket != period.Bucket || series.Points is null ||
series.Points.Count != period.Count || series.Points.Any(p => p is null || !p.Timestamp.HasValue || p.UploadBytes < 0 || p.DownloadBytes < 0)) return null;
for (var i = 1; i < series.Points.Count; i++)
if (series.Points[i].Timestamp - series.Points[i - 1].Timestamp != (period.Bucket == "hour" ? TimeSpan.FromHours(1) : TimeSpan.FromDays(1))) return null;
return series;
}
// Legacy daily points cannot stand in for hourly samples or a whole month.
if (period.Key != "7d") return null;
return new UsageHistorySeries { Note = "套餐全部设备 · 按自然日统计",
Points = legacy.Where(p => DateOnly.TryParseExact(p.Day, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out _))
.OrderBy(p => p.Day, StringComparer.Ordinal).TakeLast(7)
.Select(p => new UsageHistoryPoint { Time = p.Day, UploadBytes = Math.Max(0, p.UploadBytes), DownloadBytes = Math.Max(0, p.DownloadBytes) }).ToList() };
}
internal static Dictionary<string, bool> SelfTest()
{
var legacy = Enumerable.Range(0, 7).Select(i => new DailyUsage { Day = $"2026-09-{i+1:00}", UploadBytes = i }).ToList();
var hourly = new UsageHistorySeries { Bucket = "hour", Points = Enumerable.Range(0, 12).Select(i => new UsageHistoryPoint
{ Time = new DateTimeOffset(2026, 9, 9, 0, 0, 0, TimeSpan.FromHours(8)).AddHours(i).ToString("O"), UploadBytes = i == 3 ? null : i, DownloadBytes = i }).ToList() };
var ranges = new Dictionary<string, UsageHistorySeries> { ["12h"] = hourly };
var duplicate = new UsageHistorySeries { Bucket = "hour", Points = Enumerable.Repeat(hourly.Points[0], 12).ToList() };
var wrongScope = new UsageHistorySeries { Scope = "node", Bucket = "hour", Points = hourly.Points };
var oldProfile = JsonSerializer.Deserialize<Profile>("{\"usage_history\":[]}");
var newProfile = JsonSerializer.Deserialize<Profile>("{\"usage_history_ranges\":" + JsonSerializer.Serialize(ranges) + "}");
return new() {
["legacy_seven_days_supported"] = Select(UsageHistoryPeriod.All[2], legacy, null)?.Points.Count == 7,
["legacy_not_fabricated_as_hours_or_month"] = new[] { 0, 1, 3 }.All(i => Select(UsageHistoryPeriod.All[i], legacy, null) is null),
["hourly_missing_is_not_zero"] = Select(UsageHistoryPeriod.All[0], legacy, ranges)?.Points[3].UploadBytes is null,
["scope_mismatch_rejected"] = Select(UsageHistoryPeriod.All[0], legacy, new() { ["12h"] = wrongScope }) is null,
["duplicate_hour_rejected"] = Select(UsageHistoryPeriod.All[0], legacy, new() { ["12h"] = duplicate }) is null,
["json_backward_compatible"] = oldProfile is not null && oldProfile.UsageHistoryRanges is null,
["json_hourly_contract"] = newProfile?.UsageHistoryRanges?["12h"].Points.Count == 12,
["server_timezone_preserved"] = hourly.Points[0].Timestamp?.Offset == TimeSpan.FromHours(8),
};
}
}
internal sealed class UsageHistoryPoint
{
[JsonPropertyName("time")] public string Time { get; init; } = "";
[JsonPropertyName("upload_bytes")] public long? UploadBytes { get; init; }
[JsonPropertyName("download_bytes")] public long? DownloadBytes { get; init; }
[JsonIgnore] internal DateTimeOffset? Timestamp => DateTimeOffset.TryParse(Time, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var time) ? time : null;
}