Repository navigation
Expand file tree
/
Copy pathCodexUsageBar.cs
More file actions
738 lines (625 loc) · 27.5 KB
/
Copy pathCodexUsageBar.cs
File metadata and controls
738 lines (625 loc) · 27.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Web.Script.Serialization;
namespace CodexUsageBar
{
internal static class Program
{
[DllImport("user32.dll")]
static extern bool SetProcessDPIAware();
[STAThread]
static void Main()
{
try { SetProcessDPIAware(); } catch { }
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Run the message loop without showing the overlay at startup.
// This prevents the "random flash" that older versions could cause.
UsageOverlay overlay = new UsageOverlay();
overlay.StartMonitoring();
Application.Run();
}
}
internal sealed class UsageOverlay : Form
{
const int WS_EX_TRANSPARENT = 0x20;
const int WS_EX_NOACTIVATE = 0x08000000;
const int WS_EX_TOOLWINDOW = 0x80;
const uint GA_ROOT = 2;
const int RefreshSeconds = 60;
const uint SWP_NOACTIVATE = 0x0010;
static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
readonly System.Windows.Forms.Timer monitorTimer = new System.Windows.Forms.Timer();
readonly Font normalFont;
readonly Font strongFont;
readonly Font smallFont;
Color uiBackground = Color.FromArgb(42, 42, 42);
Color uiMain = Color.FromArgb(218, 218, 218);
Color uiMuted = Color.FromArgb(166, 166, 166);
Color uiFaint = Color.FromArgb(132, 132, 132);
Color uiTrack = Color.FromArgb(70, 70, 70);
Color uiAccent = Color.FromArgb(54, 125, 173);
DateTime nextFetch = DateTime.MinValue;
DateTime lastPaintSecond = DateTime.MinValue;
volatile bool fetching;
UsageSnapshot snapshot;
string status = "Usage unavailable";
IntPtr activeHost = IntPtr.Zero;
[DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] static extern IntPtr GetAncestor(IntPtr hWnd, uint gaFlags);
[DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
[DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll")] static extern bool IsIconic(IntPtr hWnd);
[DllImport("user32.dll")] static extern bool IsWindow(IntPtr hWnd);
[DllImport("user32.dll")] static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll")] static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("user32.dll")] static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport("gdi32.dll")] static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);
[StructLayout(LayoutKind.Sequential)]
struct RECT
{
public int Left, Top, Right, Bottom;
}
public UsageOverlay()
{
FormBorderStyle = FormBorderStyle.None;
ShowInTaskbar = false;
StartPosition = FormStartPosition.Manual;
TopMost = true;
BackColor = uiBackground;
AutoScaleMode = AutoScaleMode.None;
Width = 332;
Height = 30;
SetStyle(ControlStyles.AllPaintingInWmPaint |
ControlStyles.UserPaint |
ControlStyles.OptimizedDoubleBuffer, true);
normalFont = new Font("Segoe UI", 9.5f, FontStyle.Regular, GraphicsUnit.Point);
strongFont = new Font("Segoe UI Semibold", 9.5f, FontStyle.Regular, GraphicsUnit.Point);
smallFont = new Font("Segoe UI", 9.0f, FontStyle.Regular, GraphicsUnit.Point);
monitorTimer.Interval = 250;
monitorTimer.Tick += delegate { MonitorTick(); };
}
public void StartMonitoring()
{
monitorTimer.Start();
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= WS_EX_TRANSPARENT | WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW;
return cp;
}
}
protected override bool ShowWithoutActivation
{
get { return true; }
}
protected override void OnFormClosed(FormClosedEventArgs e)
{
monitorTimer.Stop();
normalFont.Dispose();
strongFont.Dispose();
smallFont.Dispose();
base.OnFormClosed(e);
}
void MonitorTick()
{
IntPtr fg = GetForegroundWindow();
IntPtr root = fg == IntPtr.Zero ? IntPtr.Zero : GetAncestor(fg, GA_ROOT);
// IMPORTANT: Never force-show the overlay from the positioning code.
// It may exist only while a ChatGPT/Codex host is actually foreground.
if (root == IntPtr.Zero || !IsSupportedHost(root) || IsIconic(root))
{
activeHost = IntPtr.Zero;
if (Visible) Hide();
return;
}
activeHost = root;
RECT r;
if (!GetWindowRect(activeHost, out r))
{
if (Visible) Hide();
return;
}
PositionOverComposer(r);
if (!Visible)
{
Show();
SetWindowPos(Handle, HWND_TOPMOST, Left, Top, Width, Height, SWP_NOACTIVATE);
}
if (DateTime.UtcNow >= nextFetch && !fetching)
BeginFetch();
DateTime sec = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day,
DateTime.UtcNow.Hour, DateTime.UtcNow.Minute, DateTime.UtcNow.Second,
DateTimeKind.Utc);
if (sec != lastPaintSecond)
{
lastPaintSecond = sec;
Invalidate();
}
}
static bool IsSupportedHost(IntPtr hWnd)
{
if (!IsWindow(hWnd)) return false;
uint pid;
GetWindowThreadProcessId(hWnd, out pid);
if (pid == 0) return false;
try
{
string name = Process.GetProcessById((int)pid).ProcessName;
return name.Equals("Codex", StringComparison.OrdinalIgnoreCase) ||
name.StartsWith("Codex.", StringComparison.OrdinalIgnoreCase) ||
name.Equals("ChatGPT", StringComparison.OrdinalIgnoreCase) ||
name.StartsWith("ChatGPT.", StringComparison.OrdinalIgnoreCase);
}
catch
{
return false;
}
}
void PositionOverComposer(RECT r)
{
int windowWidth = r.Right - r.Left;
// The Codex composer is centered in the content area. On the layout in
// current Windows builds, the free toolbar span between effort and model
// controls is about 500 px wide, so we keep this compact and centered.
int composerWidth = Math.Min(760, Math.Max(620, windowWidth - 420));
int composerLeft = r.Left + Math.Max(20, (windowWidth - composerWidth) / 2);
int desiredWidth;
if (snapshot != null && ((snapshot.FiveHour == null) != (snapshot.Weekly == null)))
desiredWidth = 220;
else
desiredWidth = composerWidth < 700 ? 306 : 332;
int x = composerLeft + (composerWidth - desiredWidth) / 2;
// With only the weekly quota visible, center the compact readout in the
// visual gap between the effort control and the model selector.
if (snapshot != null && snapshot.FiveHour == null && snapshot.Weekly != null)
x -= 85;
// Align the overlay centerline with the Codex composer toolbar controls.
// The offset is tuned for the current Windows desktop layout.
int y = r.Bottom - 70;
if (x + desiredWidth > r.Right - 180)
x = r.Right - 180 - desiredWidth;
if (x < r.Left + 80)
x = r.Left + 80;
if (y < r.Top + 80)
y = r.Top + 80;
UpdateThemeFromHost(r, composerLeft, composerWidth);
if (Width != desiredWidth || Height != 30)
Size = new Size(desiredWidth, 30);
SetWindowPos(Handle, HWND_TOPMOST, x, y, desiredWidth, 30, SWP_NOACTIVATE);
}
void UpdateThemeFromHost(RECT r, int composerLeft, int composerWidth)
{
// Sample a blank point in the message-entry surface just above the toolbar.
// That lets the helper blend into Codex instead of looking like a separate pill
// and also follows light/dark theme changes automatically.
int sx = composerLeft + composerWidth / 2;
int sy = r.Bottom - 78;
IntPtr dc = GetDC(IntPtr.Zero);
if (dc == IntPtr.Zero) return;
try
{
uint raw = GetPixel(dc, sx, sy);
if (raw == 0xFFFFFFFF) return;
int rr = (int)(raw & 0xFF);
int gg = (int)((raw >> 8) & 0xFF);
int bb = (int)((raw >> 16) & 0xFF);
Color sampled = Color.FromArgb(rr, gg, bb);
int lum = (rr * 299 + gg * 587 + bb * 114) / 1000;
uiBackground = sampled;
if (lum < 128)
{
uiMain = Color.FromArgb(218, 218, 218);
uiMuted = Color.FromArgb(170, 170, 170);
uiFaint = Color.FromArgb(138, 138, 138);
uiTrack = Color.FromArgb(
Math.Min(255, rr + 28),
Math.Min(255, gg + 28),
Math.Min(255, bb + 28));
uiAccent = Color.FromArgb(54, 125, 173);
}
else
{
uiMain = Color.FromArgb(45, 45, 45);
uiMuted = Color.FromArgb(92, 92, 92);
uiFaint = Color.FromArgb(120, 120, 120);
uiTrack = Color.FromArgb(
Math.Max(0, rr - 34),
Math.Max(0, gg - 34),
Math.Max(0, bb - 34));
uiAccent = Color.FromArgb(30, 103, 154);
}
if (BackColor != uiBackground)
{
BackColor = uiBackground;
Invalidate();
}
}
finally
{
ReleaseDC(IntPtr.Zero, dc);
}
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
g.Clear(uiBackground);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
if (snapshot == null)
{
DrawStatus(g, status);
return;
}
bool has5h = snapshot.FiveHour != null;
bool hasWeek = snapshot.Weekly != null;
if (!has5h && !hasWeek)
{
DrawStatus(g, "Usage unavailable");
return;
}
// If the backend only exposes one aggregate window, don't waste space
// showing a fake/missing second row. Center the real quota instead.
if (has5h && !hasWeek)
{
DrawWindowSegment(g, new RectangleF(0, 0, Width, Height),
"5h", snapshot.FiveHour);
return;
}
if (!has5h && hasWeek)
{
DrawWindowSegment(g, new RectangleF(0, 0, Width, Height),
"Weekly", snapshot.Weekly);
return;
}
float dividerX = Width / 2f;
DrawWindowSegment(g, new RectangleF(0, 0, dividerX - 5, Height),
"5h", snapshot.FiveHour);
using (Pen divider = new Pen(Color.FromArgb(
Math.Min(255, uiBackground.R + 18),
Math.Min(255, uiBackground.G + 18),
Math.Min(255, uiBackground.B + 18)), 1f))
g.DrawLine(divider, dividerX, 8, dividerX, Height - 8);
DrawWindowSegment(g, new RectangleF(dividerX + 6, 0, Width - dividerX - 6, Height),
"Weekly", snapshot.Weekly);
}
void DrawStatus(Graphics g, string value)
{
Rectangle rect = new Rectangle(0, 0, Width, Height);
TextRenderer.DrawText(g, value, normalFont, rect, uiMuted,
TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter |
TextFormatFlags.NoPadding | TextFormatFlags.SingleLine);
}
void DrawWindowSegment(Graphics g, RectangleF area, string label, LimitWindow w)
{
if (w == null) return;
double remaining = Math.Max(0.0, Math.Min(100.0, 100.0 - w.UsedPercent));
string pct = string.Format("{0:0}%", remaining);
string reset = ShortCountdown(w.ResetAt);
string labelText = label;
string pctText = " " + pct;
string resetText = " · " + reset;
Size labelSize = TextRenderer.MeasureText(labelText, normalFont,
new Size(int.MaxValue, Height), TextFormatFlags.NoPadding | TextFormatFlags.SingleLine);
Size pctSize = TextRenderer.MeasureText(pctText, strongFont,
new Size(int.MaxValue, Height), TextFormatFlags.NoPadding | TextFormatFlags.SingleLine);
Size resetSize = TextRenderer.MeasureText(resetText, smallFont,
new Size(int.MaxValue, Height), TextFormatFlags.NoPadding | TextFormatFlags.SingleLine);
int ring = 13;
int gap = 7;
int total = ring + gap + labelSize.Width + pctSize.Width + resetSize.Width;
int x = (int)area.Left + Math.Max(0, ((int)area.Width - total) / 2);
int cy = Height / 2;
Color accent = uiAccent;
if (remaining <= 10.0)
accent = Color.FromArgb(205, 82, 82);
else if (remaining <= 20.0)
accent = Color.FromArgb(194, 130, 58);
using (Pen track = new Pen(uiTrack, 2f))
using (Pen progress = new Pen(accent, 2f))
{
track.StartCap = LineCap.Round;
track.EndCap = LineCap.Round;
progress.StartCap = LineCap.Round;
progress.EndCap = LineCap.Round;
RectangleF arc = new RectangleF(x, cy - ring / 2f, ring, ring);
g.DrawArc(track, arc, -90f, 359.9f);
if (remaining > 0.1)
g.DrawArc(progress, arc, -90f, (float)(359.9 * remaining / 100.0));
}
x += ring + gap;
Rectangle labelRect = new Rectangle(x, 0, labelSize.Width + 2, Height);
TextRenderer.DrawText(g, labelText, normalFont, labelRect, uiMain,
TextFormatFlags.Left | TextFormatFlags.VerticalCenter |
TextFormatFlags.NoPadding | TextFormatFlags.SingleLine);
x += labelSize.Width;
Rectangle pctRect = new Rectangle(x, 0, pctSize.Width + 2, Height);
TextRenderer.DrawText(g, pctText, strongFont, pctRect, uiMain,
TextFormatFlags.Left | TextFormatFlags.VerticalCenter |
TextFormatFlags.NoPadding | TextFormatFlags.SingleLine);
x += pctSize.Width;
Rectangle resetRect = new Rectangle(x, 0, resetSize.Width + 2, Height);
TextRenderer.DrawText(g, resetText, smallFont, resetRect, uiFaint,
TextFormatFlags.Left | TextFormatFlags.VerticalCenter |
TextFormatFlags.NoPadding | TextFormatFlags.SingleLine);
}
static string ShortCountdown(DateTime resetUtc)
{
TimeSpan d = resetUtc - DateTime.UtcNow;
if (d.TotalSeconds <= 0) return "resetting";
if (d.TotalDays >= 1) return string.Format("{0}d {1}h", (int)d.TotalDays, d.Hours);
if (d.TotalHours >= 1) return string.Format("{0}h {1}m", (int)d.TotalHours, d.Minutes);
return string.Format("{0}m", Math.Max(1, (int)Math.Ceiling(d.TotalMinutes)));
}
void BeginFetch()
{
fetching = true;
nextFetch = DateTime.UtcNow.AddSeconds(RefreshSeconds);
ThreadPool.QueueUserWorkItem(delegate
{
try
{
UsageSnapshot fresh = UsageClient.Fetch();
snapshot = fresh;
status = "Codex usage";
}
catch (Exception ex)
{
snapshot = null;
status = FriendlyError(ex.Message);
}
finally
{
fetching = false;
try
{
if (IsHandleCreated)
BeginInvoke((MethodInvoker)delegate { Invalidate(); });
}
catch { }
}
});
}
static string FriendlyError(string msg)
{
if (msg.IndexOf("auth.json", StringComparison.OrdinalIgnoreCase) >= 0)
return "Sign in to Codex";
if (msg.IndexOf("401", StringComparison.OrdinalIgnoreCase) >= 0 ||
msg.IndexOf("403", StringComparison.OrdinalIgnoreCase) >= 0)
return "Refreshing usage…";
return "Usage unavailable";
}
}
internal sealed class UsageSnapshot
{
public LimitWindow FiveHour;
public LimitWindow Weekly;
}
internal sealed class LimitWindow
{
public double UsedPercent;
public DateTime ResetAt;
public long WindowSeconds;
}
internal static class UsageClient
{
static readonly JavaScriptSerializer Json = new JavaScriptSerializer();
public static UsageSnapshot Fetch()
{
string home = Environment.GetEnvironmentVariable("CODEX_HOME");
if (string.IsNullOrWhiteSpace(home)) home = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".codex");
string authPath = Path.Combine(home, "auth.json");
if (!File.Exists(authPath)) throw new Exception("auth.json missing");
var root = Obj(Json.DeserializeObject(File.ReadAllText(authPath, Encoding.UTF8)));
var tokens = GetObj(root, "tokens");
string access = GetString(tokens, "access_token") ?? GetString(root, "access_token");
string accountId = GetString(tokens, "account_id") ?? GetString(root, "account_id");
if (string.IsNullOrWhiteSpace(access)) throw new Exception("auth.json has no access token");
string json;
try { json = Get("https://chatgpt.com/backend-api/codex/usage", access, accountId); }
catch (WebException) { json = Get("https://chatgpt.com/backend-api/wham/usage", access, accountId); }
return ParseUsage(json);
}
static string Get(string url, string token, string accountId)
{
var req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "GET";
req.Timeout = 12000;
req.ReadWriteTimeout = 12000;
req.UserAgent = "CodexUsageBar/1.0.0";
req.Headers[HttpRequestHeader.Authorization] = "Bearer " + token;
if (!string.IsNullOrWhiteSpace(accountId)) req.Headers["ChatGPT-Account-Id"] = accountId;
using (var resp = (HttpWebResponse)req.GetResponse())
using (var sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8))
return sr.ReadToEnd();
}
static UsageSnapshot ParseUsage(string json)
{
var root = Obj(Json.DeserializeObject(json));
// Current Codex responses normally expose rate_limit, but older/newer
// clients have also used rate_limits or direct usage-window aliases.
var rate = GetObj(root, "rate_limit") ??
GetObj(root, "rate_limits") ??
GetObj(root, "usage") ??
root;
var snap = new UsageSnapshot();
// Explicitly named aliases are authoritative when present.
snap.FiveHour =
ParseWindow(GetObj(rate, "five_hour")) ??
ParseWindow(GetObj(rate, "fiveHour")) ??
ParseWindow(GetObj(root, "five_hour")) ??
ParseWindow(GetObj(root, "fiveHour"));
snap.Weekly =
ParseWindow(GetObj(rate, "weekly")) ??
ParseWindow(GetObj(root, "weekly"));
// Canonical backend names.
LimitWindow primary =
ParseWindow(GetObj(rate, "primary_window")) ??
ParseWindow(GetObj(rate, "primary"));
LimitWindow secondary =
ParseWindow(GetObj(rate, "secondary_window")) ??
ParseWindow(GetObj(rate, "secondary"));
AssignByDurationOrRole(snap, primary, true);
AssignByDurationOrRole(snap, secondary, false);
// Some wrappers put the same aggregate bucket one level deeper.
if (snap.FiveHour == null && snap.Weekly == null)
{
var codex = GetObj(rate, "codex") ?? GetObj(root, "codex");
if (codex != null)
{
snap.FiveHour =
ParseWindow(GetObj(codex, "five_hour")) ??
ParseWindow(GetObj(codex, "fiveHour"));
snap.Weekly = ParseWindow(GetObj(codex, "weekly"));
primary =
ParseWindow(GetObj(codex, "primary_window")) ??
ParseWindow(GetObj(codex, "primary"));
secondary =
ParseWindow(GetObj(codex, "secondary_window")) ??
ParseWindow(GetObj(codex, "secondary"));
AssignByDurationOrRole(snap, primary, true);
AssignByDurationOrRole(snap, secondary, false);
}
}
return snap;
}
static void AssignByDurationOrRole(UsageSnapshot snap, LimitWindow w, bool primaryRole)
{
if (w == null) return;
// Duration is the safest label. Current aggregate limits commonly use
// 18,000 seconds (5h) and 604,800 seconds (7d).
if (w.WindowSeconds >= 16200 && w.WindowSeconds <= 19800)
{
if (snap.FiveHour == null) snap.FiveHour = w;
return;
}
if (w.WindowSeconds >= 544320 && w.WindowSeconds <= 665280)
{
if (snap.Weekly == null) snap.Weekly = w;
return;
}
// When the server omits duration, preserve the conventional role mapping:
// primary = short window, secondary = long window.
if (w.WindowSeconds == 0)
{
if (primaryRole && snap.FiveHour == null)
snap.FiveHour = w;
else if (!primaryRole && snap.Weekly == null)
snap.Weekly = w;
}
}
static LimitWindow ParseWindow(IDictionary<string, object> o)
{
if (o == null) return null;
double? percentLeft =
GetDouble(o, "percent_left") ??
GetDouble(o, "remaining_percent") ??
GetDouble(o, "remainingPercent");
double? used =
GetDouble(o, "used_percent") ??
GetDouble(o, "usedPercent");
if (!used.HasValue && percentLeft.HasValue)
used = 100.0 - percentLeft.Value;
if (!used.HasValue) return null;
object reset =
GetValue(o, "reset_at") ??
GetValue(o, "resetAt") ??
GetValue(o, "resetsAt") ??
GetValue(o, "reset_time_ms");
double? resetAfter =
GetDouble(o, "reset_after_seconds") ??
GetDouble(o, "resetAfterSeconds");
double? secondsValue =
GetDouble(o, "limit_window_seconds") ??
GetDouble(o, "window_seconds") ??
GetDouble(o, "windowSecs");
if (!secondsValue.HasValue)
{
double? mins =
GetDouble(o, "window_minutes") ??
GetDouble(o, "window_duration_mins");
if (mins.HasValue)
secondsValue = mins.Value * 60.0;
}
long seconds = (long)(secondsValue ?? 0);
DateTime dt;
if (reset != null)
{
if (!TryDate(reset, out dt)) return null;
}
else if (resetAfter.HasValue)
{
dt = DateTime.UtcNow.AddSeconds(resetAfter.Value);
}
else
{
return null;
}
return new LimitWindow
{
UsedPercent = Math.Max(0.0, Math.Min(100.0, used.Value)),
ResetAt = dt,
WindowSeconds = seconds
};
}
static bool TryDate(object value, out DateTime dt)
{
dt = DateTime.MinValue;
if (value is int || value is long || value is double || value is decimal)
{
try
{
double n = Convert.ToDouble(value);
if (n > 1000000000000d) n /= 1000d;
dt = DateTimeOffset.FromUnixTimeSeconds((long)n).UtcDateTime;
return true;
}
catch { return false; }
}
DateTimeOffset dto;
if (DateTimeOffset.TryParse(Convert.ToString(value), out dto))
{
dt = dto.UtcDateTime;
return true;
}
return false;
}
static IDictionary<string, object> Obj(object v)
{
return v as IDictionary<string, object>;
}
static IDictionary<string, object> GetObj(IDictionary<string, object> d, string k)
{
object v; return d != null && d.TryGetValue(k, out v) ? Obj(v) : null;
}
static object GetValue(IDictionary<string, object> d, string k)
{
object v; return d != null && d.TryGetValue(k, out v) ? v : null;
}
static string GetString(IDictionary<string, object> d, string k)
{
object v = GetValue(d, k); return v == null ? null : Convert.ToString(v);
}
static double? GetDouble(IDictionary<string, object> d, string k)
{
object v = GetValue(d, k); if (v == null) return null;
double x; return double.TryParse(Convert.ToString(v), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out x) ? x : (double?)null;
}
}
}