462 lines
18 KiB
C#
462 lines
18 KiB
C#
using Microsoft.Web.WebView2.Core;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.ComponentModel;
|
|
using System.Linq;
|
|
using System.Net.Http;
|
|
using System.Runtime.CompilerServices;
|
|
using System.Text.Json;
|
|
using System.Threading.Tasks;
|
|
using System.Windows;
|
|
|
|
namespace ClaudeCheckerWindows;
|
|
|
|
public class UsageViewModel : INotifyPropertyChanged
|
|
{
|
|
private static readonly JsonSerializerOptions JsonOpts = new() { PropertyNameCaseInsensitive = true };
|
|
|
|
private List<AgentLimit> _limits = [];
|
|
private bool _isLoading;
|
|
private string? _errorMessage;
|
|
private bool _isSignedIn;
|
|
private string _userEmail = "";
|
|
private string _planLabel = "Pro";
|
|
private DateTime? _lastUpdated;
|
|
private OverageSpendLimit? _overage;
|
|
private PrepaidCredits? _prepaid;
|
|
|
|
private readonly Dictionary<string, List<double>> _burnHistory = [];
|
|
private const int MaxHistorySamples = 24;
|
|
|
|
public List<AgentLimit> Limits { get => _limits; set => Set(ref _limits, value); }
|
|
public bool IsLoading { get => _isLoading; set => Set(ref _isLoading, value); }
|
|
public string? ErrorMessage { get => _errorMessage; set => Set(ref _errorMessage, value); }
|
|
public bool IsSignedIn { get => _isSignedIn; set => Set(ref _isSignedIn, value); }
|
|
public string UserEmail { get => _userEmail; set => Set(ref _userEmail, value); }
|
|
public string PlanLabel { get => _planLabel; set => Set(ref _planLabel, value); }
|
|
public DateTime? LastUpdated { get => _lastUpdated; set => Set(ref _lastUpdated, value); }
|
|
public OverageSpendLimit? Overage { get => _overage; set => Set(ref _overage, value); }
|
|
public PrepaidCredits? Prepaid { get => _prepaid; set => Set(ref _prepaid, value); }
|
|
|
|
private int _refreshInterval = 120;
|
|
public int RefreshInterval
|
|
{
|
|
get => _refreshInterval;
|
|
set
|
|
{
|
|
Set(ref _refreshInterval, value);
|
|
AppSettings.Default.RefreshInterval = value;
|
|
AppSettings.Default.Save();
|
|
}
|
|
}
|
|
|
|
private bool _showInTaskbar = true;
|
|
public bool ShowInTaskbar
|
|
{
|
|
get => _showInTaskbar;
|
|
set
|
|
{
|
|
Set(ref _showInTaskbar, value);
|
|
AppSettings.Default.ShowInTaskbar = value;
|
|
AppSettings.Default.Save();
|
|
}
|
|
}
|
|
|
|
public UsageViewModel()
|
|
{
|
|
_refreshInterval = AppSettings.Default.RefreshInterval > 0
|
|
? AppSettings.Default.RefreshInterval : 120;
|
|
_showInTaskbar = AppSettings.Default.ShowInTaskbar;
|
|
LoadBurnHistory();
|
|
LoadPlaceholders();
|
|
}
|
|
|
|
public async Task RefreshAsync()
|
|
{
|
|
await Application.Current.Dispatcher.InvokeAsync(() => IsLoading = true);
|
|
|
|
try
|
|
{
|
|
var cookies = await GetCookiesAsync();
|
|
|
|
// Check if we have any persistent proof that the user authenticated
|
|
bool hasCookies = cookies.Count > 0;
|
|
bool hasCachedAuth = !string.IsNullOrEmpty(AppSettings.Default.Email) ||
|
|
!string.IsNullOrEmpty(AppSettings.Default.OrgId);
|
|
|
|
if (!hasCookies && !hasCachedAuth)
|
|
{
|
|
await Application.Current.Dispatcher.InvokeAsync(() =>
|
|
{
|
|
IsSignedIn = false;
|
|
ErrorMessage = "Not signed in — click Sign In to authenticate.";
|
|
IsLoading = false;
|
|
});
|
|
return;
|
|
}
|
|
|
|
// Try HttpClient first (fast path) — may be rejected by server CORS/header checks
|
|
var (limits, overage, prepaid, email, orgId, ok) = hasCookies
|
|
? await TryHttpRefreshAsync(cookies)
|
|
: ([], null, null, null, null, false);
|
|
|
|
// Fall back to WebView2 (uses the shared browser session, not HttpClient)
|
|
if (!ok)
|
|
(limits, email, orgId) = await TryWebView2RefreshAsync();
|
|
|
|
// Fill in any blanks from cached values saved at login time
|
|
if (string.IsNullOrEmpty(email)) email = AppSettings.Default.Email;
|
|
if (string.IsNullOrEmpty(orgId)) orgId = AppSettings.Default.OrgId;
|
|
if (limits.Count == 0 && !string.IsNullOrEmpty(AppSettings.Default.UsageJson))
|
|
{
|
|
try
|
|
{
|
|
var cached = System.Text.Json.JsonSerializer.Deserialize<UsageResponse>(
|
|
AppSettings.Default.UsageJson, JsonOpts);
|
|
limits = BuildLimits(cached);
|
|
}
|
|
catch { }
|
|
}
|
|
|
|
foreach (var limit in limits)
|
|
{
|
|
var key = limit.Window.ToString();
|
|
if (!_burnHistory.ContainsKey(key)) _burnHistory[key] = [];
|
|
_burnHistory[key].Add(limit.UsedPercent);
|
|
if (_burnHistory[key].Count > MaxHistorySamples)
|
|
_burnHistory[key].RemoveAt(0);
|
|
limit.BurnHistory = [.. _burnHistory[key]];
|
|
}
|
|
SaveBurnHistory();
|
|
|
|
await Application.Current.Dispatcher.InvokeAsync(() =>
|
|
{
|
|
Limits = limits;
|
|
Overage = overage;
|
|
Prepaid = prepaid;
|
|
if (!string.IsNullOrEmpty(email)) UserEmail = email;
|
|
// Trust that cookies / cached auth mean the user IS signed in,
|
|
// even if the live fetch failed this cycle.
|
|
IsSignedIn = true;
|
|
ErrorMessage = null;
|
|
LastUpdated = DateTime.Now;
|
|
IsLoading = false;
|
|
});
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
await Application.Current.Dispatcher.InvokeAsync(() =>
|
|
{
|
|
ErrorMessage = ex.Message;
|
|
IsLoading = false;
|
|
});
|
|
}
|
|
}
|
|
|
|
private async Task<(List<AgentLimit>, OverageSpendLimit?, PrepaidCredits?, string?, string?, bool)>
|
|
TryHttpRefreshAsync(List<(string Name, string Value, string Domain, string Path)> cookies)
|
|
{
|
|
try
|
|
{
|
|
using var http = BuildClient(cookies);
|
|
var bootstrapResp = await http.GetAsync("https://claude.ai/api/bootstrap");
|
|
if (!bootstrapResp.IsSuccessStatusCode)
|
|
return ([], null, null, null, null, false);
|
|
|
|
var (email, orgId) = ParseBootstrap(await bootstrapResp.Content.ReadAsStringAsync());
|
|
|
|
if (string.IsNullOrEmpty(orgId))
|
|
orgId = await FetchOrgIdFromListAsync(http);
|
|
if (string.IsNullOrEmpty(orgId) && !string.IsNullOrEmpty(AppSettings.Default.OrgId))
|
|
orgId = AppSettings.Default.OrgId;
|
|
|
|
if (string.IsNullOrEmpty(orgId))
|
|
return ([], null, null, email, orgId, true);
|
|
|
|
AppSettings.Default.OrgId = orgId;
|
|
AppSettings.Default.Save();
|
|
|
|
var ut = FetchAsync<UsageResponse>(http, $"https://claude.ai/api/organizations/{orgId}/usage");
|
|
var ot = FetchAsync<OverageSpendLimit>(http, $"https://claude.ai/api/organizations/{orgId}/overage_spend_limit");
|
|
var pt = FetchAsync<PrepaidCredits>(http, $"https://claude.ai/api/organizations/{orgId}/prepaid/credits");
|
|
await Task.WhenAll(ut, ot, pt);
|
|
|
|
return (BuildLimits(ut.Result), ot.Result, pt.Result, email, orgId, true);
|
|
}
|
|
catch { return ([], null, null, null, null, false); }
|
|
}
|
|
|
|
private static async Task<(List<AgentLimit>, string?, string?)> TryWebView2RefreshAsync()
|
|
{
|
|
try
|
|
{
|
|
const string script = @"(async()=>{try{
|
|
const b=await(await fetch('/api/bootstrap',{headers:{accept:'application/json'}})).json();
|
|
const id=b?.memberships?.[0]?.organization?.uuid||b?.organizations?.[0]?.uuid
|
|
||b?.default_organization?.uuid||null;
|
|
const em=b?.account?.email_address||b?.account?.email||b?.email||null;
|
|
if(!id)return{email:em,orgId:null,usage:null};
|
|
const u=await(await fetch('/api/organizations/'+id+'/usage',{headers:{accept:'application/json'}})).json();
|
|
return{email:em,orgId:id,usage:u};
|
|
}catch(ex){return null;}})()";
|
|
|
|
var resultJson = await Application.Current.Dispatcher.InvokeAsync(async () =>
|
|
{
|
|
var host = new WebViewFetchWindow();
|
|
host.Show();
|
|
try { return await host.FetchAsync("https://claude.ai", script); }
|
|
finally { host.Close(); }
|
|
}).Task.Unwrap();
|
|
|
|
if (resultJson == null || resultJson == "null") return ([], null, null);
|
|
|
|
using var doc = System.Text.Json.JsonDocument.Parse(resultJson);
|
|
var root = doc.RootElement;
|
|
|
|
string? email = root.TryGetProperty("email", out var em) && em.ValueKind == System.Text.Json.JsonValueKind.String
|
|
? em.GetString() : null;
|
|
string? orgId = root.TryGetProperty("orgId", out var oi) && oi.ValueKind == System.Text.Json.JsonValueKind.String
|
|
? oi.GetString() : null;
|
|
|
|
List<AgentLimit> limits = [];
|
|
if (root.TryGetProperty("usage", out var us) && us.ValueKind == System.Text.Json.JsonValueKind.Object)
|
|
{
|
|
var usage = System.Text.Json.JsonSerializer.Deserialize<UsageResponse>(
|
|
us.GetRawText(), new System.Text.Json.JsonSerializerOptions { PropertyNameCaseInsensitive = true });
|
|
limits = BuildLimits(usage);
|
|
|
|
// Cache for next time
|
|
AppSettings.Default.UsageJson = us.GetRawText();
|
|
if (!string.IsNullOrEmpty(orgId)) AppSettings.Default.OrgId = orgId;
|
|
if (!string.IsNullOrEmpty(email)) AppSettings.Default.Email = email;
|
|
AppSettings.Default.Save();
|
|
}
|
|
|
|
return (limits, email, orgId);
|
|
}
|
|
catch { return ([], null, null); }
|
|
}
|
|
|
|
public async Task SignOutAsync()
|
|
{
|
|
AppSettings.Default.CookieStore = "";
|
|
AppSettings.Default.OrgId = "";
|
|
AppSettings.Default.Email = "";
|
|
AppSettings.Default.UsageJson = "";
|
|
AppSettings.Default.Save();
|
|
|
|
await Application.Current.Dispatcher.InvokeAsync(() =>
|
|
{
|
|
IsSignedIn = false;
|
|
UserEmail = "";
|
|
ErrorMessage = "Signed out.";
|
|
Limits = [];
|
|
});
|
|
}
|
|
|
|
public static async Task<List<(string Name, string Value, string Domain, string Path)>> GetCookiesAsync()
|
|
{
|
|
var raw = AppSettings.Default.CookieStore;
|
|
if (string.IsNullOrEmpty(raw)) return [];
|
|
try
|
|
{
|
|
return JsonSerializer.Deserialize<List<CookieEntry>>(raw)
|
|
?.Select(c => (c.Name, c.Value, c.Domain, c.Path))
|
|
.ToList() ?? [];
|
|
}
|
|
catch { return []; }
|
|
}
|
|
|
|
public static void SaveCookies(IEnumerable<CoreWebView2Cookie> cookies)
|
|
{
|
|
var entries = cookies
|
|
.Where(c => c.Domain.Contains("claude.ai") || c.Domain.Contains("anthropic.com"))
|
|
.Select(c => new CookieEntry { Name = c.Name, Value = c.Value, Domain = c.Domain, Path = c.Path })
|
|
.ToList();
|
|
AppSettings.Default.CookieStore = JsonSerializer.Serialize(entries);
|
|
AppSettings.Default.Save();
|
|
}
|
|
|
|
private static HttpClient BuildClient(List<(string Name, string Value, string Domain, string Path)> cookies)
|
|
{
|
|
var handler = new HttpClientHandler { UseCookies = false };
|
|
var http = new HttpClient(handler);
|
|
http.DefaultRequestHeaders.Add("accept", "application/json");
|
|
http.DefaultRequestHeaders.Add("User-Agent",
|
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +
|
|
"(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36");
|
|
var cookieHeader = string.Join("; ", cookies.Select(c => $"{c.Name}={c.Value}"));
|
|
http.DefaultRequestHeaders.Add("Cookie", cookieHeader);
|
|
return http;
|
|
}
|
|
|
|
private static async Task<T?> FetchAsync<T>(HttpClient http, string url) where T : class
|
|
{
|
|
try
|
|
{
|
|
var resp = await http.GetAsync(url);
|
|
if (!resp.IsSuccessStatusCode) return null;
|
|
var json = await resp.Content.ReadAsStringAsync();
|
|
return JsonSerializer.Deserialize<T>(json, JsonOpts);
|
|
}
|
|
catch { return null; }
|
|
}
|
|
|
|
// Parse email and org ID out of bootstrap JSON (multiple fallback paths for org ID)
|
|
private static (string? Email, string? OrgId) ParseBootstrap(string json)
|
|
{
|
|
try
|
|
{
|
|
using var doc = JsonDocument.Parse(json);
|
|
var root = doc.RootElement;
|
|
|
|
string? email = null;
|
|
string? orgId = null;
|
|
|
|
if (root.TryGetProperty("account", out var acct) &&
|
|
acct.TryGetProperty("email_address", out var em))
|
|
email = em.GetString();
|
|
|
|
// Path 1: memberships[0].organization.uuid
|
|
if (root.TryGetProperty("memberships", out var mems) && mems.GetArrayLength() > 0)
|
|
{
|
|
var first = mems[0];
|
|
if (first.TryGetProperty("organization", out var org) &&
|
|
org.TryGetProperty("uuid", out var uuid))
|
|
orgId = uuid.GetString();
|
|
}
|
|
|
|
// Path 2: organizations[0].uuid (flat list on root)
|
|
if (string.IsNullOrEmpty(orgId) &&
|
|
root.TryGetProperty("organizations", out var orgs) && orgs.GetArrayLength() > 0)
|
|
{
|
|
if (orgs[0].TryGetProperty("uuid", out var uuid))
|
|
orgId = uuid.GetString();
|
|
}
|
|
|
|
return (email, orgId);
|
|
}
|
|
catch { return (null, null); }
|
|
}
|
|
|
|
private static async Task<string?> FetchOrgIdFromListAsync(HttpClient http)
|
|
{
|
|
try
|
|
{
|
|
var resp = await http.GetAsync("https://claude.ai/api/organizations");
|
|
if (!resp.IsSuccessStatusCode) return null;
|
|
var json = await resp.Content.ReadAsStringAsync();
|
|
using var doc = JsonDocument.Parse(json);
|
|
var root = doc.RootElement;
|
|
if (root.ValueKind == JsonValueKind.Array && root.GetArrayLength() > 0)
|
|
{
|
|
var first = root[0];
|
|
if (first.TryGetProperty("uuid", out var uuid))
|
|
return uuid.GetString();
|
|
}
|
|
return null;
|
|
}
|
|
catch { return null; }
|
|
}
|
|
|
|
private static List<AgentLimit> BuildLimits(UsageResponse? usage)
|
|
{
|
|
if (usage == null) return [];
|
|
var now = DateTime.Now;
|
|
var result = new List<AgentLimit>();
|
|
|
|
if (usage.FiveHour != null)
|
|
{
|
|
var reset = ParseDate(usage.FiveHour.ResetsAt, now);
|
|
var pct = Math.Clamp(usage.FiveHour.Utilization, 0, 100);
|
|
result.Add(new AgentLimit
|
|
{
|
|
Window = WindowKind.FiveHour,
|
|
UsedPercent = pct,
|
|
TimeRemaining = TimeLeft(reset, now),
|
|
ResetDate = reset,
|
|
BurnRate = pct / 5.0,
|
|
IsLive = true,
|
|
});
|
|
}
|
|
|
|
if (usage.SevenDay != null)
|
|
{
|
|
var reset = ParseDate(usage.SevenDay.ResetsAt, now);
|
|
var pct = Math.Clamp(usage.SevenDay.Utilization, 0, 100);
|
|
result.Add(new AgentLimit
|
|
{
|
|
Window = WindowKind.SevenDay,
|
|
UsedPercent = pct,
|
|
TimeRemaining = TimeLeft(reset, now),
|
|
ResetDate = reset,
|
|
BurnRate = pct / (7 * 24.0),
|
|
IsLive = true,
|
|
});
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
private static DateTime ParseDate(string? s, DateTime fallback)
|
|
{
|
|
if (s == null) return fallback.AddHours(1);
|
|
return DateTime.TryParse(s, null, System.Globalization.DateTimeStyles.RoundtripKind, out var d)
|
|
? d.ToLocalTime() : fallback.AddHours(1);
|
|
}
|
|
|
|
private static string TimeLeft(DateTime reset, DateTime now)
|
|
{
|
|
var diff = reset - now;
|
|
if (diff <= TimeSpan.Zero) return "resetting...";
|
|
if (diff.TotalDays >= 1)
|
|
return $"{(int)diff.TotalDays}d {diff.Hours}h";
|
|
return $"{diff.Hours}h {diff.Minutes}m";
|
|
}
|
|
|
|
private void LoadPlaceholders()
|
|
{
|
|
var now = DateTime.Now;
|
|
Limits =
|
|
[
|
|
new() { Window = WindowKind.FiveHour, UsedPercent = 0, TimeRemaining = "—", ResetDate = now.AddHours(1) },
|
|
new() { Window = WindowKind.SevenDay, UsedPercent = 0, TimeRemaining = "—", ResetDate = now.AddDays(7) },
|
|
];
|
|
}
|
|
|
|
private void LoadBurnHistory()
|
|
{
|
|
try
|
|
{
|
|
var raw = AppSettings.Default.BurnHistory;
|
|
if (string.IsNullOrEmpty(raw)) return;
|
|
var saved = JsonSerializer.Deserialize<Dictionary<string, List<double>>>(raw);
|
|
if (saved != null)
|
|
foreach (var kv in saved) _burnHistory[kv.Key] = kv.Value;
|
|
}
|
|
catch { }
|
|
}
|
|
|
|
private void SaveBurnHistory()
|
|
{
|
|
AppSettings.Default.BurnHistory = JsonSerializer.Serialize(_burnHistory);
|
|
AppSettings.Default.Save();
|
|
}
|
|
|
|
public event PropertyChangedEventHandler? PropertyChanged;
|
|
private void Set<T>(ref T field, T value, [CallerMemberName] string? name = null)
|
|
{
|
|
if (EqualityComparer<T>.Default.Equals(field, value)) return;
|
|
field = value;
|
|
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
|
|
}
|
|
|
|
private class CookieEntry
|
|
{
|
|
public string Name { get; set; } = "";
|
|
public string Value { get; set; } = "";
|
|
public string Domain { get; set; } = "";
|
|
public string Path { get; set; } = "/";
|
|
}
|
|
}
|