Public release

This commit is contained in:
2026-10-09 13:43:27 +00:00
commit 3f3f73a986
36 changed files with 2424 additions and 0 deletions
+14
View File
@@ -0,0 +1,14 @@
* text=auto
*.cs text eol=crlf
*.bat text eol=crlf
*.md text eol=lf
*.py text eol=lf
*.sh text eol=lf
*.service text eol=lf
*.timer text eol=lf
*.conf text eol=lf
*.json text eol=lf
*.html text eol=lf
*.xml text eol=lf
*.ico binary
*.png binary
+23
View File
@@ -0,0 +1,23 @@
# Compiled binaries and local release staging
*.exe
*.pdb
__pycache__/
*.pyc
*.pem
*.key
/artifacts/
/bin/
/obj/
# Editor and machine-local files
.vs/
.vscode/
*.user
*.suo
.env
.env.*
# Generated previews (keep the checked-in status_preview.png)
/status_window_preview.png
/icon_*_sample.png
/opt*.png
+15
View File
@@ -0,0 +1,15 @@
# Changelog
## 0.2.0
- Automatically maintained signed pricing feed with startup/resume/hourly/manual client checks.
- Dynamic model names, per-token prices, discount calculations, schedules, and holiday exceptions.
- Explicit flat-pricing, pending-policy, cached/offline, review-required, and expired-data states.
- Separate source-verification and download timestamps; invalid updates preserve accepted cache.
- Responsive dashboard, model picker, resource cleanup, and quoted quiet-startup commands.
- Dedicated server collector and hourly timer with bounded requests and private signing state.
- Tests against the compiled release assembly, local signed HTTP updates, and official-source fixtures.
## 0.1.0
- Initial portable Windows tray utility with a fixed schedule and pricing reference.
+53
View File
@@ -0,0 +1,53 @@
# DeepSeek Primetime
A portable Windows tray app that displays DeepSeek API prices and peak/off-peak schedules from an automatically maintained, signed policy feed.
![Dynamic pricing dashboard](status_preview.png)
## Download and run
Download [DeepSeekPrimetime.exe](https://git.knickqueue.win/Knick/DeepSeekPrimetime/releases/download/v0.2.0/DeepSeekPrimetime.exe) from the [v0.2.0 release](https://git.knickqueue.win/Knick/DeepSeekPrimetime/releases/tag/v0.2.0). Verify it with the release's `SHA256SUMS.txt`.
Requires Windows with .NET Framework 4.8. Run the EXE to open the dashboard; closing the dashboard keeps the tray app running. Click the tray icon to reopen it. Right-click for pricing updates, **Start with Windows**, and Exit. Keep the file in a permanent folder before enabling startup. Startup runs quietly in the tray; `--background` does the same from the command line.
## Automatic updates
The server checks [DeepSeek's official pricing documentation](https://api-docs.deepseek.com/quick_start/pricing/) hourly. The app downloads the [policy feed](https://code.knickqueue.win/deepseek-primetime/policy.json) at startup, on resume, hourly, and when you choose **Check pricing updates**. Ordinary recognized price, model-name, and schedule changes update without reinstalling the EXE. No DeepSeek API key is required.
All displayed values come from one verified policy: the model picker, pricing table, tray state, timeline, and upcoming-window cards. Future-dated changes activate at their published time. Discounts are calculated per token category; flat pricing removes the discount countdown and peak cards.
| Color | Meaning |
|---|---|
| Green | Off-peak pricing |
| Red | Peak pricing |
| Blue | Standard pricing with no scheduled discount |
| Amber | Pricing cannot currently be confirmed |
The dashboard shows **source verification time** separately from **feed download time**. A recently downloaded feed may contain older source verification. Network failures preserve the last signed policy; after 48 hours without source verification, rates are explicitly historical and the tray turns amber. Invalid signatures, unsupported policies, missing models, and expired holiday-calendar coverage also withhold confident current-rate claims.
Prices are a reference for the official API, not account-specific billing or third-party providers. The app does not infer prices from account balances or make billable model calls.
## Policy and holiday boundaries
The collector supports the currently documented USD table, two weekday UTC peak windows, and explicit flat-pricing policies. It rejects ambiguous wording, missing prices, contradictory discounts, and unfamiliar policy structures for operator review. The parser can be repaired centrally when DeepSeek changes its page layout; a new client is needed only for rules outside the client schema or a signing-key change.
Chinese holiday exceptions use China calendar dates; local display times follow the Windows timezone and daylight saving rules. Holiday dates come from official government notices. The maintained calendar currently covers 2026, including the full notified holiday periods; adjusted working Saturdays/Sundays remain off-peak under DeepSeek's weekend rule. Additional years require adding the official notice to `collector/calendars.json`. Expired coverage is detected rather than guessed.
## Build and test
Run `build.bat` with the Windows .NET Framework compiler. It produces `DeepSeekPrimetime.exe` and the identical legacy alias `DeepSeekTray.exe`; generated binaries are excluded from Git. No SDK, installer, or extra runtime files are distributed.
Run `test.bat` for the schedule, signature, cache, HTTP, and dashboard tests. The tests reference the compiled release assembly, serve signed fixture changes locally, and verify that the same running window updates prices and handles discount removal. They do not change the public feed.
Run `python -m unittest discover -s collector/tests -v` for collector tests after installing `collector/requirements.txt`. Tests use focused official-document fixtures and simulated failures; production signing keys are never included.
## Collector deployment
See [collector/README.md](collector/README.md) for the service, timer, signing, calendar maintenance, and recovery procedure. The installed collector runs as a dedicated unprivileged system account. Only the public feed and public key are served; signing keys and source/cache state remain private on the server.
## Project files
- `src/`: native WinForms UI, policy client, policy validation, schedule evaluator, and tests.
- `policy-public-key.xml`: pinned public verification key embedded in the EXE.
- `collector/`: official-source collector, fixtures, tests, and server deployment configuration.
- `build.bat`, `test.bat`: build and test entry points.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

+23
View File
@@ -0,0 +1,23 @@
@echo off
setlocal
cd /d "%~dp0"
echo [1/3] Setting up build environment...
set "CSC=%SystemRoot%\Microsoft.NET\Framework64\v4.0.30319\csc.exe"
if not exist "%CSC%" (
echo Error: .NET Framework compiler not found at %CSC%
exit /b 1
)
echo [2/3] Compiling DeepSeekPrimetime.exe...
"%CSC%" /nologo /target:winexe /optimize+ /platform:anycpu /win32icon:app.ico /resource:policy-public-key.xml,policy-public-key.xml /out:"DeepSeekPrimetime.exe" /r:System.dll,System.Core.dll,System.Drawing.dll,System.Windows.Forms.dll,System.Runtime.Serialization.dll src\Program.cs src\AssemblyInfo.cs src\PricingPolicy.cs src\PolicyClient.cs src\DeepSeekSchedule.cs src\IconGenerator.cs src\StatusForm.cs src\TrayApplicationContext.cs
if %ERRORLEVEL% neq 0 (
echo Build failed!
exit /b %ERRORLEVEL%
)
echo [3/3] Build succeeded: DeepSeekPrimetime.exe
copy /y "DeepSeekPrimetime.exe" "DeepSeekTray.exe" >nul
echo.
+41
View File
@@ -0,0 +1,41 @@
# Policy collector operations
Production URL: `https://code.knickqueue.win/deepseek-primetime/policy.json`.
The collector fetches the official DeepSeek USD pricing page and the configured official Chinese holiday notices. It uses ETag/Last-Modified conditional requests, a 1 MiB source limit, bounded requests, and an explicit official-domain allowlist. If the host's local resolver cannot resolve an official source, the request uses Cloudflare DNS-over-HTTPS while preserving the original TLS hostname, SNI, and certificate verification. System DNS configuration is unchanged.
The HTML parser expands row/column spans, maps prices by token category and model column, and accepts only supported policy grammar. It checks table discounts against any explicitly stated percentage. Unknown wording or source contradictions publish `reviewRequired` with the last accepted rates. Network failures publish `unavailable`. Neither failure renews the source-verification timestamp or 48-hour expiry.
## Installed layout
- `/opt/deepseek-primetime/`: root-owned collector code and calendar configuration.
- `/var/lib/deepseek-primetime/`: private signing key, downloaded sources, and last policy; mode 0700.
- `/var/www/deepseek-primetime/`: signed public feed, public key, and revision history. Nginx exposes only `policy.json` and `public-key.xml`.
- `deepseek-primetime.service`: bounded, unprivileged systemd oneshot.
- `deepseek-primetime.timer`: hourly checks, enabled at boot.
RSA-3072/SHA-256 signs the exact UTF-8 payload bytes using PKCS#1 v1.5. The envelope contains base64 payload and signature plus a key identifier. The app pins the public key at build time; it does not download a replacement key. Keep the signing key out of Git and back it up using the server's private backup process. Loss/rotation of the key requires rebuilding clients with a newly pinned key.
## Install on another server
Install Python 3.10+ and `cryptography` using your system package manager or an isolated environment. Place the explicitly listed collector, calendar, service, timer, Nginx snippet, and deployment script files under `/opt/deepseek-primetime`, then run `sh deploy.sh` as root after reviewing the paths. This script is specifically configured for the existing `code-gitea` Nginx site; adjust the insertion anchor and HTTPS hostname for another server.
The initial successful collection creates the private key. Obtain `public-key.xml` over a trusted administrative connection, put it in the project root, and rebuild the app. Configure `PolicyClient.FeedUrl` for another host. Never copy the private signing key into the client or repository.
## Routine verification
Use `systemctl status deepseek-primetime.timer`, `systemctl list-timers deepseek-primetime.timer`, and `journalctl -u deepseek-primetime.service`. Trigger an immediate run with `systemctl start deepseek-primetime.service`. A network/review problem can still exit successfully because it publishes signed degraded health; inspect `sourceStatus` and `sourceVerifiedAtUtc` in the decoded payload as well as the process exit code.
The app shows an amber state for review-required data, missing calendar coverage, expired verification, or invalid updates. It keeps historical rates visible for reference without claiming they are current. Routine freshness revisions do not trigger repeated policy-change notifications.
## Calendar and parser upkeep
`calendars.json` currently names the official 2026 State Council holiday notice republished by Beijing's government. Add the following year's official notice once published. The parser expects seven named holiday ranges, understands parenthesized lunar-date/weekday notes, and ignores compensatory working-day statements for weekend pricing. Tests cover year and structure mismatch.
For a page/policy change, save a focused official fixture, update `parse_pricing` or `parse_calendar`, and run the collector tests before deployment. Arbitrary natural-language rules are not automatically interpreted. Future notices are currently recognized in the explicit `New prices take effect at YYYY-MM-DD HH:MM UTC.` format; other formats request review. The signed schema supports scheduled/flat modes, per-model rates, cross-midnight windows, explicit calendar dates, and one pending policy.
## Recovery
The feed and local accepted state are written atomically; every published envelope is retained in `history/`. Correct a source/configuration problem and run the collector again to issue a newer signed revision. Clients reject lower revisions and changed contents at the same revision, so recovery must publish a new revision rather than restoring an old public file.
Before changing the Nginx site, `deploy.sh` saves a timestamped backup. Test with `nginx -t` before reloading. To disable collection, use `systemctl disable --now deepseek-primetime.timer`; clients will progressively enter cached/expired status. Removing the Nginx include and reloading Nginx stops serving the feed. Preserve private state and the signing key when migrating or recovering.
+8
View File
@@ -0,0 +1,8 @@
{
"sources": [
{
"year": 2026,
"url": "https://www.beijing.gov.cn/zhengce/zhengcefagui/202511/t20251104_4258873.html"
}
]
}
+380
View File
@@ -0,0 +1,380 @@
"""Fetch official pricing, validate supported rules, and publish signed data only."""
import argparse
import base64
import copy
import hashlib
import http.client
import ipaddress
import json
import logging
import os
import re
import socket
import time
import urllib.error
import urllib.request
import urllib.parse
from datetime import date, datetime, timedelta, timezone
from decimal import Decimal
from html.parser import HTMLParser
from pathlib import Path
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding, rsa
SOURCE = "https://api-docs.deepseek.com/quick_start/pricing/"
MAX_BODY = 1024 * 1024
def utcnow():
return datetime.now(timezone.utc).replace(microsecond=0)
def stamp(value):
return value.strftime("%Y-%m-%dT%H:%M:%SZ")
class Document(HTMLParser):
def __init__(self):
super().__init__(convert_charrefs=True)
self.tables, self.paragraphs = [], []
self.table = self.row = self.cell = self.paragraph = None
self.skip = 0
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if tag in ("script", "style"):
self.skip += 1
if tag == "table":
self.table = []
elif tag == "tr" and self.table is not None:
self.row = []
elif tag in ("td", "th") and self.row is not None:
self.cell = [[], int(attrs.get("rowspan", 1)), int(attrs.get("colspan", 1))]
elif tag == "p":
self.paragraph = []
elif tag == "br":
self.handle_data(" ")
def handle_data(self, data):
if self.skip:
return
if self.cell is not None:
self.cell[0].append(data)
if self.paragraph is not None:
self.paragraph.append(data)
def handle_endtag(self, tag):
if tag in ("script", "style"):
self.skip = max(0, self.skip - 1)
if tag in ("td", "th") and self.cell is not None:
text, rows, cols = self.cell
self.row.append((" ".join("".join(text).split()), rows, cols))
self.cell = None
elif tag == "tr" and self.row is not None:
self.table.append(self.row)
self.row = None
elif tag == "table" and self.table is not None:
self.tables.append(self.table)
self.table = None
elif tag == "p" and self.paragraph is not None:
self.paragraphs.append(" ".join("".join(self.paragraph).split()))
self.paragraph = None
def grid(rows):
occupied, result = {}, []
for y, cells in enumerate(rows):
x = 0
for text, height, width in cells:
while (y, x) in occupied:
x += 1
if not 1 <= height <= 32 or not 1 <= width <= 32:
raise ValueError("Unsupported table spans")
for dy in range(height):
for dx in range(width):
if (y + dy, x + dx) in occupied:
raise ValueError("Overlapping table cells")
occupied[y + dy, x + dx] = text
x += width
width = max((col for row, col in occupied if row == y), default=-1) + 1
result.append([occupied.get((y, col), "") for col in range(width)])
return result
def money(text):
if not re.fullmatch(r"\$\d+(?:\.\d+)?", text.strip()):
raise ValueError("Missing or unsupported USD price")
value = Decimal(text.strip()[1:])
if value < 0 or value > 100000:
raise ValueError("Price outside supported range")
return str(value)
def parse_pricing(html):
doc = Document()
doc.feed(html)
tables = [grid(t) for t in doc.tables if t and t[0] and t[0][0][0] == "MODEL"]
if len(tables) != 1:
raise ValueError("Expected one official model/pricing table")
rows = tables[0]
headers = rows[0]
model_columns = [(i, re.sub(r"\s*\(\d+\)\s*$", "", v)) for i, v in enumerate(headers) if v.startswith("deepseek-")]
if not model_columns or len(model_columns) > 20:
raise ValueError("No recognized model identifiers")
versions = next((r for r in rows if r[0] == "MODEL VERSION"), None)
if versions is None:
raise ValueError("Model version row missing")
price_rows = [r for r in rows if r[0].startswith("PRICING")]
if not price_rows:
raise ValueError("Pricing rows missing")
scheduled = any("OFF-PEAK" in r or "PEAK" in r for r in price_rows)
rules = [p for p in doc.paragraphs if re.search(r"peak hours|all hours.*(?:same|standard).*rate|no.*(?:off-peak|time.of.day).*discount", p, re.I)]
if len(rules) != 1:
raise ValueError("Missing or ambiguous pricing policy")
rule = re.sub(r"^\(\d+\)\s*", "", rules[0])
windows = []
holidays = False
if scheduled:
match = re.fullmatch(r"(?:Off-peak rates are (?:half of|\d+(?:\.\d+)?% of) the peak rates\. )?Peak hours are (\d{2}:\d{2}) - (\d{2}:\d{2}) and (\d{2}:\d{2}) - (\d{2}:\d{2}) UTC, Monday through Friday(, excluding Chinese public holidays)?\. All other hours are off-peak, including weekends(?: and Chinese public holidays in full)?\.", rule)
if not match:
raise ValueError("Policy wording requires review")
holidays = bool(match.group(5))
ratio = Decimal('0.5') if rule.startswith('Off-peak rates are half of') else None
percentage = re.match(r'Off-peak rates are (\d+(?:\.\d+)?)% of', rule)
if percentage:
ratio = Decimal(percentage.group(1)) / 100
if holidays != ("Chinese public holidays in full" in rule):
raise ValueError("Ambiguous holiday treatment")
for start, end in ((match.group(1), match.group(2)), (match.group(3), match.group(4))):
def minutes(t):
hour, minute = map(int, t.split(":"))
if hour > 23 or minute > 59:
raise ValueError("Invalid schedule time")
return hour * 60 + minute
a, b = minutes(start), minutes(end)
if a == b:
raise ValueError("Empty schedule window")
windows.append({"startMinute": a, "endMinute": b})
elif not re.fullmatch(r"(?:All hours use the same standard rate\.|No time-of-day discounts apply\.)", rule):
raise ValueError("Flat-pricing policy requires explicit confirmation")
models = []
for column, model_id in model_columns:
tiers = {"offPeak": {}, "peak": {}} if scheduled else {"standard": {}}
for row in price_rows:
label = " ".join(row[:column]).upper()
field = "cacheHit" if "CACHE HIT" in label else "cacheMiss" if "CACHE MISS" in label else "output" if "OUTPUT TOKENS" in label else None
tier = "offPeak" if "OFF-PEAK" in row else "peak" if "PEAK" in row else "standard"
if field is None or tier not in tiers or column >= len(row) or field in tiers[tier]:
raise ValueError("Unrecognized or duplicate price row")
tiers[tier][field] = money(row[column])
if any(set(t) != {"cacheHit", "cacheMiss", "output"} for t in tiers.values()):
raise ValueError("Incomplete model prices")
if scheduled and any(Decimal(tiers['offPeak'][f]) > Decimal(tiers['peak'][f]) for f in tiers['peak']):
raise ValueError("Off-peak price exceeds peak price")
if scheduled and ratio is not None and any(Decimal(tiers['offPeak'][f]) != Decimal(tiers['peak'][f]) * ratio for f in tiers['peak']):
raise ValueError("Price table contradicts the stated discount policy")
models.append({"id": model_id, "name": versions[column], "currency": "USD", "tokenUnit": 1000000, "offPeak": tiers.get("offPeak"), "peak": tiers.get("peak"), "standard": tiers.get("standard")})
# Future effective dates are accepted only in this explicit, unambiguous format.
effective = None
for paragraph in doc.paragraphs:
if re.search(r"(?:new pric|new polic|pricing change|rates).*?(?:effective|take effect)|(?:effective|take effect).*?(?:pric|rates|policy)", paragraph, re.I):
match = re.fullmatch(r"(?:New prices|New policy) take effect at (\d{4}-\d{2}-\d{2} \d{2}:\d{2}) UTC\.", paragraph)
if not match:
raise ValueError("Pricing announcement effective date requires review")
if effective is not None:
raise ValueError("Multiple pricing announcements require review")
effective = stamp(datetime.strptime(match.group(1), "%Y-%m-%d %H:%M").replace(tzinfo=timezone.utc))
return {"mode": "scheduled" if scheduled else "flat", "scheduleTimezone": "UTC", "holidayTimezone": "China Standard Time", "weekdays": [1, 2, 3, 4, 5], "windows": windows, "holidayExempt": holidays, "models": models, "effectiveFromUtc": effective}
def parse_calendar(html, year):
doc = Document()
doc.feed(html)
text = " ".join(doc.paragraphs)
if str(year) + "年" not in text:
raise ValueError("Holiday notice year mismatch")
text = re.sub(r"([^)]*)|\([^)]*\)", "", text)
sections = re.findall(r"[一二三四五六七]、[^:]+:(.*?)(?=[一二三四五六七]、|$)", text)
if len(sections) != 7:
raise ValueError("Expected seven official holiday periods")
dates = set()
for section in sections:
clean = re.sub(r"([^)]*)|\([^)]*\)", "", section)
match = re.match(r"(\d+)月(\d+)日?至(?:(\d+)月)?(\d+)日放假", clean)
if not match:
raise ValueError("Holiday range requires review")
start = date(year, int(match.group(1)), int(match.group(2)))
end = date(year, int(match.group(3) or match.group(1)), int(match.group(4)))
if not 0 <= (end - start).days <= 15:
raise ValueError("Invalid holiday interval")
while start <= end:
dates.add(start.isoformat())
start += timedelta(days=1)
return sorted(dates)
def atomic_write(path, data, mode=0o644):
path.parent.mkdir(parents=True, exist_ok=True)
temp = path.with_suffix(path.suffix + ".tmp")
with open(temp, "wb") as handle:
handle.write(data)
handle.flush()
os.fsync(handle.fileno())
os.chmod(temp, mode)
os.replace(temp, path)
def canonical(value):
return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
def fetch(url, storage, now):
# Only this operator-configured allowlist is fetched; no URLs from remote documents.
if not url.startswith(("https://api-docs.deepseek.com/", "https://www.beijing.gov.cn/", "https://www.gov.cn/")):
raise ValueError("Source URL outside official allowlist")
key = hashlib.sha256(url.encode()).hexdigest()
file, meta_file = storage / (key + ".html"), storage / (key + ".json")
meta = json.loads(meta_file.read_text()) if meta_file.exists() else {}
headers = {"User-Agent": "DeepSeekPrimetime/0.2 (+policy reference updater)"}
if meta.get("etag") and file.exists():
headers["If-None-Match"] = meta['etag']
if meta.get("modified") and file.exists():
headers["If-Modified-Since"] = meta['modified']
try:
request = urllib.request.Request(url, headers=headers)
try:
response = urllib.request.urlopen(request, timeout=25)
except urllib.error.URLError as error:
if not isinstance(error.reason, socket.gaierror):
raise
# Some self-hosted DNS filters cannot resolve the official docs hostname.
# Resolve only this request, retaining the original Host header, TLS SNI,
# and hostname certificate validation. Never alter system DNS settings.
host = urllib.parse.urlsplit(url).hostname
query = 'https://1.1.1.1/dns-query?name=' + urllib.parse.quote(host) + '&type=A'
with urllib.request.urlopen(urllib.request.Request(query, headers={'Accept': 'application/dns-json'}), timeout=15) as dns:
answer = json.loads(dns.read(65536))
addresses = [str(ipaddress.IPv4Address(a['data'])) for a in answer.get('Answer', []) if a.get('type') == 1]
if not addresses:
raise ValueError('Official source DNS lookup returned no address')
address = addresses[0]
class ResolvedConnection(http.client.HTTPSConnection):
def connect(self):
self._create_connection = lambda original, timeout, source_address=None: socket.create_connection((address, original[1]), timeout, source_address)
super().connect()
class ResolvedHandler(urllib.request.HTTPSHandler):
def https_open(self, req):
return self.do_open(ResolvedConnection, req, context=self._context)
response = urllib.request.build_opener(ResolvedHandler()).open(request, timeout=25)
with response:
if not response.url.startswith(("https://api-docs.deepseek.com/", "https://www.beijing.gov.cn/", "https://www.gov.cn/")):
raise ValueError("Unexpected source redirect")
raw = response.read(MAX_BODY + 1)
if len(raw) > MAX_BODY:
raise ValueError("Source exceeds body limit")
meta = {"etag": response.headers.get("ETag"), "modified": response.headers.get("Last-Modified")}
atomic_write(file, raw, 0o600)
atomic_write(meta_file, canonical(meta), 0o600)
except urllib.error.HTTPError as error:
if error.code != 304 or not file.exists():
raise
raw = file.read_bytes()
return raw.decode("utf-8"), hashlib.sha256(raw).hexdigest()
def initialize_key(path):
if not path.exists():
private = rsa.generate_private_key(public_exponent=65537, key_size=3072)
atomic_write(path, private.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()), 0o600)
private = serialization.load_pem_private_key(path.read_bytes(), password=None)
numbers = private.public_key().public_numbers()
enc = lambda n: base64.b64encode(n.to_bytes((n.bit_length() + 7) // 8, 'big')).decode()
return private, '<RSAKeyValue><Modulus>' + enc(numbers.n) + '</Modulus><Exponent>' + enc(numbers.e) + '</Exponent></RSAKeyValue>'
def sign(policy, private):
payload = canonical(policy)
signature = private.sign(payload, padding.PKCS1v15(), hashes.SHA256())
return canonical({"keyId": "primetime-2026-1", "payload": base64.b64encode(payload).decode(), "signature": base64.b64encode(signature).decode()})
def collect(state, output, config_path, now=None):
now = now or utcnow()
state.mkdir(parents=True, exist_ok=True)
private, public_xml = initialize_key(state / 'signing-key.pem')
atomic_write(output / 'public-key.xml', public_xml.encode())
previous_file = state / 'last-policy.json'
previous = json.loads(previous_file.read_text()) if previous_file.exists() else None
status, message = 'current', 'Official sources verified'
try:
html, source_hash = fetch(SOURCE, state / 'sources', now)
parsed = parse_pricing(html)
calendar = json.loads(config_path.read_text(encoding='utf-8'))
holiday_dates, calendar_hashes = [], {}
for entry in calendar['sources']:
content, digest = fetch(entry['url'], state / 'sources', now)
holiday_dates.extend(parse_calendar(content, entry['year']))
calendar_hashes[str(entry['year'])] = digest
years = sorted(e['year'] for e in calendar['sources'])
if parsed['holidayExempt'] and now.astimezone(timezone(timedelta(hours=8))).year not in years:
raise ValueError('Official holiday calendar needs the current year')
policy = dict(parsed, schemaVersion=1, sourceUrl=SOURCE, sourceHash=source_hash, sourceVerifiedAtUtc=stamp(now), holidayDates=sorted(set(holiday_dates)), calendarFrom=('%04d-01-01' % min(years)), calendarValidThrough=('%04d-12-31' % max(years)), calendarSources=calendar['sources'], calendarHashes=calendar_hashes)
identity = {k: policy[k] for k in ('mode', 'scheduleTimezone', 'holidayTimezone', 'weekdays', 'windows', 'holidayExempt', 'models', 'effectiveFromUtc', 'holidayDates', 'calendarFrom', 'calendarValidThrough')}
policy['policyId'] = hashlib.sha256(canonical(identity)).hexdigest()
# Retain the announced effective date while refreshing an unchanged policy.
if not policy['effectiveFromUtc']:
policy['effectiveFromUtc'] = previous['effectiveFromUtc'] if previous and previous['policyId'] == policy['policyId'] else stamp(now)
pending = previous.get('pendingPolicy') if previous else None
if pending and pending['policyId'] == policy['policyId'] and now < datetime.fromisoformat(pending['effectiveFromUtc'].replace('Z', '+00:00')):
pending.update(policy)
policy = copy.deepcopy(previous)
policy['pendingPolicy'] = pending
policy['sourceVerifiedAtUtc'] = stamp(now)
elif datetime.fromisoformat(policy['effectiveFromUtc'].replace('Z', '+00:00')) > now and previous:
pending = policy
policy = copy.deepcopy(previous)
policy['pendingPolicy'] = pending
policy['sourceVerifiedAtUtc'] = stamp(now)
else:
policy['pendingPolicy'] = None
except Exception as error:
status = 'reviewRequired' if isinstance(error, (ValueError, KeyError, StopIteration, json.JSONDecodeError)) else 'unavailable'
message = str(error)[:200]
if not previous:
raise RuntimeError('No verified initial policy: ' + message) from error
policy = copy.deepcopy(previous)
policy.update(revision=(previous['revision'] + 1 if previous else 1), publishedAtUtc=stamp(now), sourceStatus=status, sourceMessage=message, sourceCheckedAtUtc=stamp(now))
# Source verification remains old on errors; feed publication never renews freshness.
verified = datetime.fromisoformat(policy['sourceVerifiedAtUtc'].replace('Z', '+00:00'))
policy['expiresAtUtc'] = stamp(verified + timedelta(hours=48))
raw = sign(policy, private)
atomic_write(output / 'history' / ('%012d.json' % policy['revision']), raw)
atomic_write(output / 'policy.json', raw)
atomic_write(previous_file, canonical(policy), 0o600)
logging.info('revision=%s source_status=%s policy=%s message=%s', policy['revision'], status, policy['policyId'][:12], message)
return policy
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--state', type=Path, required=True)
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--calendars', type=Path, required=True)
parser.add_argument('--loop', action='store_true')
args = parser.parse_args()
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
while True:
try:
collect(args.state, args.output, args.calendars)
except Exception:
logging.exception('Initial collection failed')
if not args.loop:
raise
if not args.loop:
break
time.sleep(3600)
if __name__ == '__main__':
main()
+18
View File
@@ -0,0 +1,18 @@
[Unit]
Description=DeepSeek Primetime official pricing policy collector
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
User=deepseek-primetime
Group=deepseek-primetime
ExecStart=/usr/bin/python3 /opt/deepseek-primetime/collector.py --state /var/lib/deepseek-primetime --output /var/www/deepseek-primetime --calendars /opt/deepseek-primetime/calendars.json
TimeoutStartSec=180
UMask=0077
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
ReadWritePaths=/var/lib/deepseek-primetime /var/www/deepseek-primetime
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
+12
View File
@@ -0,0 +1,12 @@
[Unit]
Description=Hourly DeepSeek Primetime pricing verification
[Timer]
OnBootSec=1min
OnUnitActiveSec=1h
RandomizedDelaySec=30
Persistent=true
Unit=deepseek-primetime.service
[Install]
WantedBy=timers.target
+31
View File
@@ -0,0 +1,31 @@
#!/bin/sh
set -eu
# Run as root after placing these explicitly listed files in /opt/deepseek-primetime.
python3 -c 'import cryptography'
id deepseek-primetime >/dev/null 2>&1 || useradd --system --home-dir /var/lib/deepseek-primetime --shell /usr/sbin/nologin deepseek-primetime
install -d -m 700 -o deepseek-primetime -g deepseek-primetime /var/lib/deepseek-primetime
install -d -m 755 -o deepseek-primetime -g deepseek-primetime /var/www/deepseek-primetime
install -m 644 /opt/deepseek-primetime/deepseek-primetime.service /etc/systemd/system/deepseek-primetime.service
install -m 644 /opt/deepseek-primetime/deepseek-primetime.timer /etc/systemd/system/deepseek-primetime.timer
install -m 644 /opt/deepseek-primetime/nginx-location.conf /etc/nginx/snippets/deepseek-primetime.conf
python3 - <<'PY'
from pathlib import Path
import datetime
p = Path('/etc/nginx/sites-available/code-gitea')
s = p.read_text()
include = ' include /etc/nginx/snippets/deepseek-primetime.conf;'
if include not in s:
anchor = ' client_max_body_size 512M;'
if s.count(anchor) != 1:
raise SystemExit('Expected one TLS server insertion anchor; inspect config')
backup = p.with_name(p.name + '.primetime-backup-' + datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
backup.write_text(s)
p.write_text(s.replace(anchor, anchor + '\n\n' + include))
PY
nginx -t
systemctl daemon-reload
systemctl start deepseek-primetime.service
systemctl enable --now deepseek-primetime.timer
systemctl reload nginx
systemctl is-active deepseek-primetime.timer
journalctl -u deepseek-primetime.service -n 8 --no-pager
+9
View File
@@ -0,0 +1,9 @@
<p>国务院办公厅关于2026年部分节假日安排的通知</p>
<p>经国务院批准,现将2026年元旦、春节、清明节、劳动节、端午节、中秋节和国庆节放假调休日期的具体安排通知如下。</p>
<p>一、元旦:1月1日(周四)至3日(周六)放假调休,共3天。1月4日(周日)上班。</p>
<p>二、春节:2月15日(农历腊月二十八、周日)至23日(农历正月初七、周一)放假调休,共9天。2月14日(周六)、2月28日(周六)上班。</p>
<p>三、清明节:4月4日(周六)至6日(周一)放假,共3天。</p>
<p>四、劳动节:5月1日(周五)至5日(周二)放假调休,共5天。5月9日(周六)上班。</p>
<p>五、端午节:6月19日(周五)至21日(周日)放假,共3天。</p>
<p>六、中秋节:9月25日(周五)至27日(周日)放假,共3天。</p>
<p>七、国庆节:10月1日(周四)至7日(周三)放假调休,共7天。9月20日(周日)、10月10日(周六)上班。</p>
+1
View File
@@ -0,0 +1 @@
{"calendarFrom":"2026-01-01","calendarValidThrough":"2026-12-31","effectiveFromUtc":"2026-01-01T00:00:00Z","expiresAtUtc":"2026-10-11T13:00:00Z","holidayDates":["2026-01-01","2026-01-02","2026-01-03","2026-02-15","2026-02-16","2026-02-17","2026-02-18","2026-02-19","2026-02-20","2026-02-21","2026-02-22","2026-02-23","2026-04-04","2026-04-05","2026-04-06","2026-05-01","2026-05-02","2026-05-03","2026-05-04","2026-05-05","2026-06-19","2026-06-20","2026-06-21","2026-09-25","2026-09-26","2026-09-27","2026-10-01","2026-10-02","2026-10-03","2026-10-04","2026-10-05","2026-10-06","2026-10-07"],"holidayExempt":true,"holidayTimezone":"China Standard Time","mode":"scheduled","models":[{"currency":"USD","id":"deepseek-flash","name":"DeepSeek-V4.1-Flash","offPeak":{"cacheHit":"0.003","cacheMiss":"0.15","output":"0.6"},"peak":{"cacheHit":"0.006","cacheMiss":"0.3","output":"1.2"},"standard":null,"tokenUnit":1000000},{"currency":"USD","id":"deepseek-v4-pro","name":"DeepSeek-V4-Pro-0813","offPeak":{"cacheHit":"0.022","cacheMiss":"0.66","output":"1.98"},"peak":{"cacheHit":"0.044","cacheMiss":"1.32","output":"3.96"},"standard":null,"tokenUnit":1000000}],"pendingPolicy":null,"policyId":"fixture-current","publishedAtUtc":"2026-10-09T13:00:00Z","revision":1,"scheduleTimezone":"UTC","schemaVersion":1,"sourceCheckedAtUtc":"2026-10-09T13:00:00Z","sourceMessage":"Official fixture","sourceStatus":"current","sourceUrl":"https://api-docs.deepseek.com/quick_start/pricing/","sourceVerifiedAtUtc":"2026-10-09T13:00:00Z","weekdays":[1,2,3,4,5],"windows":[{"endMinute":240,"startMinute":60},{"endMinute":600,"startMinute":360}]}
+2
View File
@@ -0,0 +1,2 @@
<table style="text-align:center"><tr><td colspan="3" style="text-align:center">MODEL</td><td>deepseek-flash<sup>(1)</sup></td><td>deepseek-v4-pro</td></tr><tr><td colspan="3">BASE URL (OpenAI Format)</td><td colspan="2"><a href="https://api.deepseek.com" target="_blank" rel="noopener noreferrer">https://api.deepseek.com</a></td></tr><tr><td colspan="3">BASE URL (Anthropic Format)</td><td colspan="2"><a href="https://api.deepseek.com/anthropic" target="_blank" rel="noopener noreferrer">https://api.deepseek.com/anthropic</a></td></tr><tr><td colspan="3" style="text-align:center">MODEL VERSION</td><td>DeepSeek-V4.1-Flash</td><td>DeepSeek-V4-Pro-0813</td></tr><tr><td colspan="3">THINKING MODE</td><td colspan="2">Supports both non-thinking and thinking (default) modes<br>See <a href="/guides/thinking_mode">Thinking Mode</a> for how to switch</td></tr><tr><td colspan="3">CONTEXT LENGTH</td><td colspan="2">1M</td></tr><tr><td colspan="3">MAX OUTPUT</td><td colspan="2">MAXIMUM: 384K</td></tr><tr><td rowspan="7">FEATURES</td><td colspan="2"><a href="/guides/json_mode">Json Output</a></td><td>✓</td><td>✓</td></tr><tr><td colspan="2"><a href="/guides/tool_calls">Tool Calls</a></td><td>✓</td><td>✓</td></tr><tr><td colspan="2"><a href="/guides/responses_api">Responses API</a></td><td>✓</td><td>✓</td></tr><tr><td colspan="2"><a href="/guides/anthropic_api">Anthropic API</a></td><td>✓</td><td>✓</td></tr><tr><td colspan="2"><a href="/guides/chat_prefix_completion">Chat Prefix Completion(Beta)</a></td><td>✓</td><td>✓</td></tr><tr><td colspan="2"><a href="/guides/fim_completion">FIM Completion(Beta)</a></td><td>Non-thinking mode only</td><td>Non-thinking mode only</td></tr><tr><td colspan="2"><a href="/guides/vision">Vision</a></td><td>✓</td><td>Not supported</td></tr><tr><td rowspan="6">PRICING<sup>(2)</sup></td><td rowspan="2">1M INPUT TOKENS<br>(CACHE HIT)</td><td>OFF-PEAK</td><td>$0.003</td><td>$0.022</td></tr><tr><td>PEAK</td><td>$0.006</td><td>$0.044</td></tr><tr><td rowspan="2">1M INPUT TOKENS<br>(CACHE MISS)</td><td>OFF-PEAK</td><td>$0.15</td><td>$0.66</td></tr><tr><td>PEAK</td><td>$0.3</td><td>$1.32</td></tr><tr><td rowspan="2">1M OUTPUT TOKENS</td><td>OFF-PEAK</td><td>$0.6</td><td>$1.98</td></tr><tr><td>PEAK</td><td>$1.2</td><td>$3.96</td></tr><tr><td colspan="3">Concurrency Limit<sup>(3)</sup></td><td>2500</td><td>500</td></tr></table>
<p>(2) Off-peak rates are half of the peak rates. Peak hours are 01:00 - 04:00 and 06:00 - 10:00 UTC, Monday through Friday, excluding Chinese public holidays. All other hours are off-peak, including weekends and Chinese public holidays in full.</p>
+11
View File
@@ -0,0 +1,11 @@
location = /deepseek-primetime/policy.json {
alias /var/www/deepseek-primetime/policy.json;
default_type application/json;
add_header Cache-Control "public, max-age=60";
add_header X-Content-Type-Options nosniff;
}
location = /deepseek-primetime/public-key.xml {
alias /var/www/deepseek-primetime/public-key.xml;
default_type application/xml;
add_header X-Content-Type-Options nosniff;
}
+1
View File
@@ -0,0 +1 @@
cryptography>=43,<47
+107
View File
@@ -0,0 +1,107 @@
import base64
import copy
import json
import tempfile
import unittest
from datetime import datetime, timedelta, timezone
from pathlib import Path
from unittest.mock import patch
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from collector import collector as c
FIXTURES = Path(__file__).resolve().parents[1] / 'fixtures'
PRICING = (FIXTURES / 'pricing.html').read_text(encoding='utf-8')
CALENDAR = (FIXTURES / 'holidays-2026.html').read_text(encoding='utf-8')
class CollectorTests(unittest.TestCase):
def test_current_prices_and_holidays(self):
policy = c.parse_pricing(PRICING)
self.assertEqual(policy['models'][0]['id'], 'deepseek-flash')
self.assertEqual(policy['models'][0]['offPeak']['cacheHit'], '0.003')
self.assertEqual(policy['windows'], [{'startMinute':60,'endMinute':240},{'startMinute':360,'endMinute':600}])
dates = c.parse_calendar(CALENDAR, 2026)
self.assertEqual(len(dates), 33)
self.assertIn('2026-02-23', dates)
self.assertIn('2026-10-07', dates)
self.assertNotIn('2026-10-10', dates) # adjusted workdays remain weekends
def test_numeric_changes(self):
updated = c.parse_pricing(PRICING.replace('$0.003', '$0.004').replace('$0.006', '$0.008').replace('01:00 - 04:00', '02:00 - 05:00'))
self.assertEqual(updated['models'][0]['offPeak']['cacheHit'], '0.004')
self.assertEqual(updated['windows'][0]['startMinute'], 120)
def test_table_policy_contradiction(self):
with self.assertRaises(ValueError): c.parse_pricing(PRICING.replace('$0.003', '$0.004'))
asymmetric = c.parse_pricing(PRICING.replace('Off-peak rates are half of the peak rates. ', '').replace('$0.003', '$0.004'))
self.assertEqual(asymmetric['models'][0]['offPeak']['cacheHit'], '0.004')
def test_ambiguous_or_missing_rows_rejected(self):
for document in (PRICING.replace('Monday through Friday', 'whenever capacity is available'), PRICING.replace('$0.003', 'contact sales'), PRICING.replace('CACHE HIT', 'UNKNOWN'), PRICING + '<p>Peak hours may change during holidays.</p>'):
with self.subTest(document=document[:20]):
with self.assertRaises(ValueError): c.parse_pricing(document)
def test_flat_policy(self):
document = '<table><tr><td colspan="3">MODEL</td><td>deepseek-flash</td></tr><tr><td colspan="3">MODEL VERSION</td><td>Flash New</td></tr>'
for i, label in enumerate(('1M INPUT TOKENS (CACHE HIT)', '1M INPUT TOKENS (CACHE MISS)', '1M OUTPUT TOKENS')):
document += '<tr>' + ('<td rowspan="3">PRICING</td>' if i == 0 else '') + '<td colspan="2">' + label + '</td><td>$0.5</td></tr>'
document += '</table><p>All hours use the same standard rate.</p>'
policy = c.parse_pricing(document)
self.assertEqual(policy['mode'], 'flat')
self.assertEqual(policy['models'][0]['standard']['output'], '0.5')
self.assertEqual(policy['windows'], [])
def test_future_notice(self):
document = PRICING + '<p>New prices take effect at 2026-10-11 04:00 UTC.</p>'
self.assertEqual(c.parse_pricing(document)['effectiveFromUtc'], '2026-10-11T04:00:00Z')
with self.assertRaises(ValueError): c.parse_pricing(PRICING + '<p>New prices take effect next Sunday.</p>')
with self.assertRaises(ValueError): c.parse_pricing(document + '<p>New prices take effect at 2026-10-12 04:00 UTC.</p>')
def test_calendar_year_and_structure(self):
with self.assertRaises(ValueError): c.parse_calendar(CALENDAR, 2027)
with self.assertRaises(ValueError): c.parse_calendar(CALENDAR.replace('七、国庆节', '国庆节'), 2026)
def test_signed_feed_failure_and_recovery(self):
now = datetime(2026,10,9,13,tzinfo=timezone.utc)
with tempfile.TemporaryDirectory() as directory:
root = Path(directory); state = root / 'state'; output = root / 'www'
config = root / 'calendars.json'; config.write_text(json.dumps({'sources':[{'year':2026,'url':'https://www.beijing.gov.cn/calendar'}]}))
def sources(url, *args): return (PRICING, 'prices-hash') if url == c.SOURCE else (CALENDAR, 'calendar-hash')
with patch.object(c, 'fetch', side_effect=sources): initial = c.collect(state, output, config, now)
envelope = json.loads((output / 'policy.json').read_bytes())
key, _ = c.initialize_key(state / 'signing-key.pem')
key.public_key().verify(base64.b64decode(envelope['signature']), base64.b64decode(envelope['payload']), padding.PKCS1v15(), hashes.SHA256())
with patch.object(c, 'fetch', side_effect=OSError('offline')): offline = c.collect(state, output, config, now+timedelta(hours=1))
self.assertEqual(offline['sourceStatus'], 'unavailable')
self.assertEqual(offline['sourceVerifiedAtUtc'], initial['sourceVerifiedAtUtc'])
self.assertEqual(offline['expiresAtUtc'], initial['expiresAtUtc'])
self.assertGreater(offline['revision'], initial['revision'])
with patch.object(c, 'fetch', side_effect=ValueError('new billing semantics')): review = c.collect(state, output, config, now+timedelta(hours=2))
self.assertEqual(review['sourceStatus'], 'reviewRequired')
self.assertEqual(review['models'], initial['models'])
with patch.object(c, 'fetch', side_effect=sources): recovered = c.collect(state, output, config, now+timedelta(hours=3))
self.assertEqual(recovered['sourceStatus'], 'current')
self.assertEqual(recovered['policyId'], initial['policyId'])
self.assertNotEqual(recovered['sourceVerifiedAtUtc'], initial['sourceVerifiedAtUtc'])
def test_pending_activation_and_calendar_expiry(self):
now = datetime(2026,10,9,13,tzinfo=timezone.utc)
with tempfile.TemporaryDirectory() as directory:
root=Path(directory); config=root/'calendars.json'; config.write_text(json.dumps({'sources':[{'year':2026,'url':'https://www.beijing.gov.cn/calendar'}]}))
current = PRICING
def sources(url,*args): return (current, 'hash') if url == c.SOURCE else (CALENDAR, 'calendar')
with patch.object(c,'fetch',side_effect=sources): original=c.collect(root/'state',root/'www',config,now)
current=PRICING.replace('$0.003','$0.004').replace('$0.006','$0.008')+'<p>New prices take effect at 2026-10-11 04:00 UTC.</p>'
with patch.object(c,'fetch',side_effect=sources): pending=c.collect(root/'state',root/'www',config,now+timedelta(hours=1))
self.assertEqual(pending['models'],original['models'])
self.assertEqual(pending['pendingPolicy']['models'][0]['offPeak']['cacheHit'],'0.004')
with patch.object(c,'fetch',side_effect=sources): activated=c.collect(root/'state',root/'www',config,datetime(2026,10,11,4,tzinfo=timezone.utc))
self.assertIsNone(activated['pendingPolicy'])
self.assertEqual(activated['models'][0]['offPeak']['cacheHit'],'0.004')
with patch.object(c,'fetch',side_effect=sources): expired=c.collect(root/'state',root/'www',config,datetime(2027,1,1,tzinfo=timezone.utc))
self.assertEqual(expired['sourceStatus'],'reviewRequired')
if __name__ == '__main__': unittest.main()
+1
View File
@@ -0,0 +1 @@
<RSAKeyValue><Modulus>nGJJoVCpNDozkRHKyUFRX6L2K7jbNCIPyh6DqoaHHpHn0AIEoNk+6s5uS/XcJ3rk3p9kZ1e5rXXpVazdQ2iZ/VrnFyf116S/gjvWh17dwc/qFD1KnZFUbv6DvqEB925BD1jeb9AG1E7kUWFXAHvZWhmsxbXhoqfqNhPMZXVpFfbsyBWN5J5XL5iR04sgPSOdG8WCV0eGmc9tLrEqbnqEtpRLvmZo34EEnapHDoH/FoQki4QLzcO/VhW/gonwl2pADpHetnzBRUTKRMsmM9He9i5lFhqsBbF1vgIYn4WJuC5VsqF/b33/gWXeO0wZo/D3hUONuORR/cYxGxLfJfmF5r3e118gsZ7pEqfSNQuuL76DIL54COv9JQtMJ/3Yv0WVzZvS3RO8L+USrYRZ26bMJjcppbEKVcLbk80666op/LIcVRU9o22f+jTwlXtyN9CA34PjUV9+O8FoqfDtqy3bI/B9DmJ1qfSeFJzr6i4mhRuZTIm8DUVJesN7jOWhoLy7</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>
+6
View File
@@ -0,0 +1,6 @@
using System.Reflection;
[assembly: AssemblyTitle("DeepSeek Primetime")]
[assembly: AssemblyDescription("Automatically updated DeepSeek pricing and schedule reference")]
[assembly: AssemblyProduct("DeepSeek Primetime")]
[assembly: AssemblyVersion("0.2.0.0")]
[assembly: AssemblyFileVersion("0.2.0.0")]
+30
View File
@@ -0,0 +1,30 @@
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
namespace DeepSeekTray
{
class CaptureWindow
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
using (StatusForm form = new StatusForm())
{
form.Show();
form.Refresh();
Application.DoEvents();
using (Bitmap bmp = new Bitmap(form.Width, form.Height))
{
form.DrawToBitmap(bmp, new Rectangle(0, 0, form.Width, form.Height));
bmp.Save("status_window_preview.png", ImageFormat.Png);
Console.WriteLine("Saved status_window_preview.png (" + form.Width + "x" + form.Height + ")");
}
form.Close();
}
}
}
}
+137
View File
@@ -0,0 +1,137 @@
using System;
using System.Collections.Generic;
using System.Globalization;
namespace DeepSeekTray
{
public class ScheduleStatus
{
public bool IsPeak;
public DateTime UtcNow, LocalNow;
public DateTime? NextTransitionUtc, NextTransitionLocal;
public TimeSpan TimeUntilTransition;
public string TransitionDescription;
}
public class PeakBlock
{
public DateTime StartUtc, EndUtc, StartLocal, EndLocal;
public bool IsActiveNow;
public TimeSpan TimeUntilStart, TimeRemaining, Duration;
public string Name;
}
public static class DeepSeekSchedule
{
// Preview/test compatibility. Production views pass a captured policy.
public static PricingPolicy CurrentPolicy;
private static DateTime ScheduleTime(PricingPolicy policy, DateTime utc)
{ return policy.ScheduleTimezone == "China Standard Time" ? utc.AddHours(8) : utc; }
public static bool IsPeakHour(DateTime utc) { return IsPeakHour(CurrentPolicy, utc); }
public static bool IsPeakHour(PricingPolicy policy, DateTime utc)
{
if (policy == null) return false;
policy = policy.At(utc);
if (policy.Mode != "scheduled") return false;
string holiday = utc.AddHours(8).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
if (policy.HolidayExempt && Array.IndexOf(policy.HolidayDates, holiday) >= 0) return false;
DateTime local = ScheduleTime(policy, utc);
double minute = local.TimeOfDay.TotalMinutes;
foreach (RateWindow window in policy.Windows)
{
if (window.StartMinute < window.EndMinute)
{
if (Array.IndexOf(policy.Weekdays, (int)local.DayOfWeek) >= 0 && minute >= window.StartMinute && minute < window.EndMinute) return true;
}
else
{
if (minute >= window.StartMinute && Array.IndexOf(policy.Weekdays, (int)local.DayOfWeek) >= 0) return true;
if (minute < window.EndMinute && Array.IndexOf(policy.Weekdays, (int)local.AddDays(-1).DayOfWeek) >= 0) return true;
}
}
return false;
}
private static SortedSet<DateTime> Boundaries(PricingPolicy policy, DateTime utc)
{
SortedSet<DateTime> dates = new SortedSet<DateTime>();
foreach (PricingPolicy candidate in policy.PendingPolicy == null ? new[] { policy } : new[] { policy, policy.PendingPolicy })
{
int offset = candidate.ScheduleTimezone == "China Standard Time" ? 8 : 0;
DateTime day = utc.AddHours(offset).Date.AddDays(-1);
for (int d = 0; d <= 33; d++)
{
DateTime current = day.AddDays(d);
foreach (RateWindow window in candidate.Windows)
{
dates.Add(current.AddMinutes(window.StartMinute).AddHours(-offset));
dates.Add(current.AddMinutes(window.EndMinute).AddHours(-offset));
}
dates.Add(current.AddHours(-offset));
dates.Add(utc.AddHours(8).Date.AddDays(d - 1).AddHours(-8));
}
}
if (policy.PendingPolicy != null) dates.Add(PricingPolicy.Utc(policy.PendingPolicy.EffectiveFromUtc));
return dates;
}
public static ScheduleStatus GetStatus(DateTime? nowUtc = null) { return GetStatus(CurrentPolicy, nowUtc ?? DateTime.UtcNow); }
private static bool CalendarKnown(PricingPolicy policy, DateTime utc)
{
policy = policy.At(utc);
string date = utc.AddHours(8).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
return !policy.HolidayExempt || (string.CompareOrdinal(date, policy.CalendarFrom) >= 0 && string.CompareOrdinal(date, policy.CalendarValidThrough) <= 0);
}
public static ScheduleStatus GetStatus(PricingPolicy policy, DateTime utc)
{
bool peak = IsPeakHour(policy, utc);
DateTime? next = null;
if (policy != null)
foreach (DateTime boundary in Boundaries(policy, utc))
{
if (boundary <= utc) continue;
if (!CalendarKnown(policy, boundary)) break;
if (IsPeakHour(policy, boundary) != peak) { next = boundary; break; }
}
TimeSpan until = next.HasValue ? next.Value - utc : TimeSpan.Zero;
string description = policy == null ? "Pricing schedule unavailable" : policy.At(utc).Mode == "flat" ? "No scheduled discount" : "No upcoming rate transition in the published schedule";
if (next.HasValue)
description = string.Format("Peak {0} in {1} ({2:h:mm tt} local / {3:HH:mm} UTC)", peak ? "ends" : "starts", FormatDuration(until), next.Value.ToLocalTime(), next.Value);
return new ScheduleStatus { IsPeak = peak, UtcNow = utc, LocalNow = utc.ToLocalTime(), NextTransitionUtc = next, NextTransitionLocal = next.HasValue ? (DateTime?)next.Value.ToLocalTime() : null, TimeUntilTransition = until, TransitionDescription = description };
}
public static List<PeakBlock> GetUpcomingPeakBlocks(DateTime? nowUtc = null, int count = 4) { return GetUpcomingPeakBlocks(CurrentPolicy, nowUtc ?? DateTime.UtcNow, count); }
public static List<PeakBlock> GetUpcomingPeakBlocks(PricingPolicy policy, DateTime utc, int count = 4)
{
List<PeakBlock> blocks = new List<PeakBlock>();
if (policy == null || count <= 0) return blocks;
bool peak = IsPeakHour(policy, utc);
DateTime? start = null;
foreach (DateTime boundary in Boundaries(policy, utc))
{
if (boundary > utc) break;
bool after = IsPeakHour(policy, boundary);
if (after && !IsPeakHour(policy, boundary.AddTicks(-1))) start = boundary;
if (!after) start = null;
}
if (peak && !start.HasValue) start = utc;
foreach (DateTime boundary in Boundaries(policy, utc))
{
if (boundary <= utc) continue;
if (!CalendarKnown(policy, boundary)) break;
bool after = IsPeakHour(policy, boundary);
if (after && !peak) start = boundary;
if (!after && peak && start.HasValue)
{
DateTime s = start.Value;
blocks.Add(new PeakBlock { StartUtc = s, EndUtc = boundary, StartLocal = s.ToLocalTime(), EndLocal = boundary.ToLocalTime(), IsActiveNow = s <= utc && boundary > utc, TimeUntilStart = s > utc ? s - utc : TimeSpan.Zero, TimeRemaining = s <= utc ? boundary - utc : TimeSpan.Zero, Duration = boundary - s, Name = "Peak pricing" });
if (blocks.Count >= count) break;
start = null;
}
peak = after;
}
return blocks;
}
public static string FormatDuration(TimeSpan span)
{
if (span.TotalDays >= 1) return string.Format("{0}d {1}h", (int)span.TotalDays, span.Hours);
if (span.TotalHours >= 1) return string.Format("{0}h {1:D2}m", (int)span.TotalHours, span.Minutes);
return string.Format("{0}m", Math.Max(1, span.Minutes));
}
}
}
+121
View File
@@ -0,0 +1,121 @@
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.IO;
namespace DeepSeekTray
{
class GenerateIco
{
static void Main()
{
int[] sizes = new int[] { 16, 32, 48 };
using (MemoryStream ms = new MemoryStream())
{
using (BinaryWriter bw = new BinaryWriter(ms))
{
bw.Write((short)0); // reserved
bw.Write((short)1); // icon type
bw.Write((short)sizes.Length); // count
byte[][] pngBytes = new byte[sizes.Length][];
for (int i = 0; i < sizes.Length; i++)
{
int s = sizes[i];
using (Bitmap bmp = new Bitmap(s, s))
{
using (Graphics g = Graphics.FromImage(bmp))
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
g.Clear(Color.Transparent);
RectangleF badgeRect = new RectangleF(1, 1, s - 2, s - 2);
float radius = s * 0.22f;
using (GraphicsPath badgePath = CreateRoundedRect(badgeRect, radius))
{
using (Brush bgBrush = new SolidBrush(Color.FromArgb(0, 200, 85)))
{
g.FillPath(bgBrush, badgePath);
}
using (Pen borderPen = new Pen(Color.FromArgb(0, 105, 40), Math.Max(1f, s * 0.05f)))
{
g.DrawPath(borderPen, badgePath);
}
}
float fontSize = s * 0.72f;
using (Font font = new Font("Arial Black", fontSize, FontStyle.Bold, GraphicsUnit.Pixel))
using (GraphicsPath path = new GraphicsPath())
{
StringFormat sf = new StringFormat
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
RectangleF rect = new RectangleF(0, -s * 0.02f, s, s);
path.AddString("$", font.FontFamily, (int)FontStyle.Bold, fontSize, rect, sf);
using (Pen shadowPen = new Pen(Color.FromArgb(90, 0, 0, 0), Math.Max(1.5f, s * 0.06f)))
{
shadowPen.LineJoin = LineJoin.Round;
g.DrawPath(shadowPen, path);
}
using (Brush brush = new SolidBrush(Color.White))
{
g.FillPath(brush, path);
}
}
}
using (MemoryStream pngMs = new MemoryStream())
{
bmp.Save(pngMs, System.Drawing.Imaging.ImageFormat.Png);
pngBytes[i] = pngMs.ToArray();
}
}
}
int offset = 6 + (sizes.Length * 16);
for (int i = 0; i < sizes.Length; i++)
{
int s = sizes[i];
bw.Write((byte)(s >= 256 ? 0 : s));
bw.Write((byte)(s >= 256 ? 0 : s));
bw.Write((byte)0);
bw.Write((byte)0);
bw.Write((short)1);
bw.Write((short)32);
bw.Write((int)pngBytes[i].Length);
bw.Write((int)offset);
offset += pngBytes[i].Length;
}
for (int i = 0; i < sizes.Length; i++)
{
bw.Write(pngBytes[i]);
}
bw.Flush();
byte[] icoData = ms.ToArray();
File.WriteAllBytes("app.ico", icoData);
Console.WriteLine("Generated app.ico successfully (" + icoData.Length + " bytes)");
}
}
}
static GraphicsPath CreateRoundedRect(RectangleF rect, float radius)
{
GraphicsPath path = new GraphicsPath();
float d = radius * 2;
path.AddArc(rect.X, rect.Y, d, d, 180, 90);
path.AddArc(rect.Right - d, rect.Y, d, d, 270, 90);
path.AddArc(rect.Right - d, rect.Bottom - d, d, d, 0, 90);
path.AddArc(rect.X, rect.Bottom - d, d, d, 90, 90);
path.CloseFigure();
return path;
}
}
}
+142
View File
@@ -0,0 +1,142 @@
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
namespace DeepSeekTray
{
class GenerateVisibilityOptions
{
static void Main()
{
// Option 1: Full-Color Rounded Tile with White $
RenderTile(false, "opt1_green_tile.png");
RenderTile(true, "opt1_red_tile.png");
// Option 2: Ultra-Bold standalone $ (strokes fill entire bounds, thick outline)
RenderBoldDollar(false, "opt2_green_dollar.png");
RenderBoldDollar(true, "opt2_red_dollar.png");
// Option 3: Diamond / Gem shape (Green / Red with White $)
RenderDiamond(false, "opt3_green_diamond.png");
RenderDiamond(true, "opt3_red_diamond.png");
Console.WriteLine("Generated all options.");
}
static void RenderTile(bool isPeak, string path)
{
int size = 32;
using (Bitmap bmp = new Bitmap(size, size))
using (Graphics g = Graphics.FromImage(bmp))
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
g.Clear(Color.Transparent);
Color bg = isPeak ? Color.FromArgb(235, 35, 55) : Color.FromArgb(0, 200, 85);
Color border = isPeak ? Color.FromArgb(140, 10, 25) : Color.FromArgb(0, 110, 45);
RectangleF rect = new RectangleF(1, 1, size - 2, size - 2);
using (GraphicsPath p = CreateRoundedRect(rect, size * 0.22f))
{
using (Brush b = new SolidBrush(bg)) g.FillPath(b, p);
using (Pen pen = new Pen(border, 1.5f)) g.DrawPath(pen, p);
}
// Bold white $
float fontSize = size * 0.72f;
using (Font font = new Font("Arial Black", fontSize, FontStyle.Bold, GraphicsUnit.Pixel))
using (GraphicsPath tp = new GraphicsPath())
{
StringFormat sf = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center };
tp.AddString("$", font.FontFamily, (int)FontStyle.Bold, fontSize, new RectangleF(0, -size * 0.02f, size, size), sf);
// Shadow
using (Pen sp = new Pen(Color.FromArgb(80, 0, 0, 0), 2f)) g.DrawPath(sp, tp);
using (Brush b = new SolidBrush(Color.White)) g.FillPath(b, tp);
}
bmp.Save(path, System.Drawing.Imaging.ImageFormat.Png);
}
}
static void RenderBoldDollar(bool isPeak, string path)
{
int size = 32;
using (Bitmap bmp = new Bitmap(size, size))
using (Graphics g = Graphics.FromImage(bmp))
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
g.Clear(Color.Transparent);
Color c = isPeak ? Color.FromArgb(255, 45, 65) : Color.FromArgb(0, 240, 95);
float fontSize = size * 0.92f;
using (Font font = new Font("Arial Black", fontSize, FontStyle.Bold, GraphicsUnit.Pixel))
using (GraphicsPath tp = new GraphicsPath())
{
StringFormat sf = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center };
tp.AddString("$", font.FontFamily, (int)FontStyle.Bold, fontSize, new RectangleF(0, -size * 0.05f, size, size), sf);
// Thick black outline for maximum visibility on any taskbar
using (Pen op = new Pen(Color.FromArgb(15, 15, 15), size * 0.16f))
{
op.LineJoin = LineJoin.Round;
g.DrawPath(op, tp);
}
using (Brush b = new SolidBrush(c)) g.FillPath(b, tp);
}
bmp.Save(path, System.Drawing.Imaging.ImageFormat.Png);
}
}
static void RenderDiamond(bool isPeak, string path)
{
int size = 32;
using (Bitmap bmp = new Bitmap(size, size))
using (Graphics g = Graphics.FromImage(bmp))
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
g.Clear(Color.Transparent);
Color bg = isPeak ? Color.FromArgb(235, 35, 55) : Color.FromArgb(0, 200, 85);
PointF[] pts = new PointF[] {
new PointF(size / 2f, 1f),
new PointF(size - 2f, size / 2f),
new PointF(size / 2f, size - 2f),
new PointF(1f, size / 2f)
};
using (GraphicsPath p = new GraphicsPath())
{
p.AddPolygon(pts);
using (Brush b = new SolidBrush(bg)) g.FillPath(b, p);
using (Pen pen = new Pen(Color.FromArgb(20, 20, 20), 1.5f)) g.DrawPath(pen, p);
}
float fontSize = size * 0.60f;
using (Font font = new Font("Arial Black", fontSize, FontStyle.Bold, GraphicsUnit.Pixel))
using (GraphicsPath tp = new GraphicsPath())
{
StringFormat sf = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center };
tp.AddString("$", font.FontFamily, (int)FontStyle.Bold, fontSize, new RectangleF(0, -size * 0.02f, size, size), sf);
using (Brush b = new SolidBrush(Color.White)) g.FillPath(b, tp);
}
bmp.Save(path, System.Drawing.Imaging.ImageFormat.Png);
}
}
static GraphicsPath CreateRoundedRect(RectangleF rect, float radius)
{
GraphicsPath path = new GraphicsPath();
float d = radius * 2;
path.AddArc(rect.X, rect.Y, d, d, 180, 90);
path.AddArc(rect.Right - d, rect.Y, d, d, 270, 90);
path.AddArc(rect.Right - d, rect.Bottom - d, d, d, 0, 90);
path.AddArc(rect.X, rect.Bottom - d, d, d, 90, 90);
path.CloseFigure();
return path;
}
}
}
+104
View File
@@ -0,0 +1,104 @@
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Runtime.InteropServices;
namespace DeepSeekTray
{
public static class IconGenerator
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern bool DestroyIcon(IntPtr handle);
public static Icon CreateDollarIcon(bool isPeak, int size = 32)
{ return CreateDollarIcon(isPeak ? RateState.Peak : RateState.OffPeak, size); }
public static Icon CreateDollarIcon(RateState state, int size = 32)
{
using (Bitmap bmp = new Bitmap(size, size, System.Drawing.Imaging.PixelFormat.Format32bppArgb))
{
using (Graphics g = Graphics.FromImage(bmp))
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.Clear(Color.Transparent);
// High-Visibility Solid Tile:
// Off-Peak: Vivid Emerald Green (#00C853)
// Peak: Bold Crimson Red (#E52538)
Color bgColor = StateColor(state);
Color borderColor = ControlPaintDark(bgColor);
RectangleF badgeRect = new RectangleF(1f, 1f, size - 2f, size - 2f);
float radius = size * 0.22f;
using (GraphicsPath badgePath = CreateRoundedRect(badgeRect, radius))
{
using (Brush bgBrush = new SolidBrush(bgColor))
{
g.FillPath(bgBrush, badgePath);
}
using (Pen borderPen = new Pen(borderColor, Math.Max(1.2f, size * 0.05f)))
{
g.DrawPath(borderPen, badgePath);
}
}
// Bold White Dollar Sign in center
float fontSize = size * 0.72f;
using (Font font = new Font("Arial Black", fontSize, FontStyle.Bold, GraphicsUnit.Pixel))
using (GraphicsPath textPath = new GraphicsPath())
{
StringFormat sf = new StringFormat
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
RectangleF textRect = new RectangleF(0, -size * 0.02f, size, size);
textPath.AddString("$", font.FontFamily, (int)FontStyle.Bold, fontSize, textRect, sf);
// Subtle drop shadow for crisp white text definition
using (Pen shadowPen = new Pen(Color.FromArgb(90, 0, 0, 0), Math.Max(1.5f, size * 0.06f)))
{
shadowPen.LineJoin = LineJoin.Round;
g.DrawPath(shadowPen, textPath);
}
using (Brush textBrush = new SolidBrush(Color.White))
{
g.FillPath(textBrush, textPath);
}
}
}
IntPtr hIcon = bmp.GetHicon();
Icon icon = (Icon)Icon.FromHandle(hIcon).Clone();
DestroyIcon(hIcon);
return icon;
}
}
private static GraphicsPath CreateRoundedRect(RectangleF rect, float radius)
{
GraphicsPath path = new GraphicsPath();
float d = radius * 2;
path.AddArc(rect.X, rect.Y, d, d, 180, 90);
path.AddArc(rect.Right - d, rect.Y, d, d, 270, 90);
path.AddArc(rect.Right - d, rect.Bottom - d, d, d, 0, 90);
path.AddArc(rect.X, rect.Bottom - d, d, d, 90, 90);
path.CloseFigure();
return path;
}
public static Color StateColor(RateState state)
{
return state == RateState.Peak ? Color.FromArgb(235, 35, 55) : state == RateState.OffPeak ? Color.FromArgb(0, 200, 85) : state == RateState.Flat ? Color.FromArgb(80, 130, 180) : Color.FromArgb(210, 145, 35);
}
private static Color ControlPaintDark(Color color) { return Color.FromArgb(color.R / 2, color.G / 2, color.B / 2); }
}
}
+161
View File
@@ -0,0 +1,161 @@
using System;
using System.IO;
using System.Net;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
namespace DeepSeekTray
{
public class PolicyClient
{
public const string FeedUrl = "https://code.knickqueue.win/deepseek-primetime/policy.json";
private readonly object gate = new object();
private readonly string cachePath;
private readonly string modelPath;
private readonly string publicKey;
private readonly string feedUrl;
private PolicySnapshot snapshot = new PolicySnapshot();
private byte[] lastRaw;
private string etag;
private int busy;
public event Action Changed;
public PolicySnapshot Snapshot { get { lock (gate) return snapshot; } }
public bool IsChecking { get { return Interlocked.CompareExchange(ref busy, 0, 0) != 0; } }
public PolicyClient() : this(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DeepSeekPrimetime"), ReadPublicKey(), FeedUrl) { }
public PolicyClient(string directory, string key, string url)
{
cachePath = Path.Combine(directory, "policy.json");
modelPath = Path.Combine(directory, "model.txt");
publicKey = key; feedUrl = url;
try { if (File.Exists(modelPath)) { string model = File.ReadAllText(modelPath).Trim(); if (model.Length > 0 && model.Length < 80) snapshot.SelectedModel = model; } } catch { }
try
{
if (File.Exists(cachePath))
{
byte[] raw = File.ReadAllBytes(cachePath);
Accept(raw, DateTime.UtcNow, false);
lock (gate) snapshot.Offline = true;
}
}
catch (Exception) { snapshot.DownloadMessage = "Saved policy could not be verified"; }
}
private static string ReadPublicKey()
{
using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("policy-public-key.xml"))
using (StreamReader reader = new StreamReader(stream)) return reader.ReadToEnd();
}
public PricingPolicy Verify(byte[] raw, DateTime now)
{
if (raw.Length > 512 * 1024) throw new InvalidDataException("Policy exceeds size limit");
SignedPolicy envelope = PricingPolicy.Read<SignedPolicy>(raw);
if (envelope.KeyId != "primetime-2026-1") throw new InvalidDataException("Unknown signing key");
byte[] payload = Convert.FromBase64String(envelope.Payload), signature = Convert.FromBase64String(envelope.Signature);
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
rsa.PersistKeyInCsp = false;
rsa.FromXmlString(publicKey);
if (!rsa.VerifyData(payload, CryptoConfig.MapNameToOID("SHA256"), signature)) throw new InvalidDataException("Policy signature is invalid");
}
PricingPolicy policy = PricingPolicy.Read<PricingPolicy>(payload);
policy.Validate();
if (PricingPolicy.Utc(policy.PublishedAtUtc) > now.AddMinutes(5)) throw new InvalidDataException("Feed publication is in the future");
return policy;
}
public void Accept(byte[] raw, DateTime now, bool persist)
{
PricingPolicy policy = Verify(raw, now);
lock (gate)
{
if (snapshot.Policy != null && policy.Revision < snapshot.Policy.Revision) throw new InvalidDataException("Older policy revision rejected");
if (snapshot.Policy != null && policy.Revision == snapshot.Policy.Revision && lastRaw != null && !Equal(raw, lastRaw))
throw new InvalidDataException("Policy revision contents changed");
if (persist) Save(raw);
lastRaw = raw;
snapshot = new PolicySnapshot { Policy = policy, DownloadedAtUtc = persist ? (DateTime?)now : null, SelectedModel = snapshot.SelectedModel };
}
}
private static bool Equal(byte[] left, byte[] right)
{
if (left.Length != right.Length) return false;
for (int i = 0; i < left.Length; i++) if (left[i] != right[i]) return false;
return true;
}
private void Save(byte[] raw)
{
Directory.CreateDirectory(Path.GetDirectoryName(cachePath));
string temporary = cachePath + ".tmp";
using (FileStream stream = new FileStream(temporary, FileMode.Create, FileAccess.Write, FileShare.None))
{ stream.Write(raw, 0, raw.Length); stream.Flush(true); }
if (File.Exists(cachePath)) File.Replace(temporary, cachePath, null);
else File.Move(temporary, cachePath);
}
public void SelectModel(string id)
{
lock (gate)
{
if (snapshot.Policy == null || snapshot.Policy.At(DateTime.UtcNow).FindModel(id) == null) return;
snapshot = new PolicySnapshot { Policy = snapshot.Policy, Offline = snapshot.Offline, UpdateRejected = snapshot.UpdateRejected, DownloadMessage = snapshot.DownloadMessage, DownloadedAtUtc = snapshot.DownloadedAtUtc, SelectedModel = id };
try { Directory.CreateDirectory(Path.GetDirectoryName(modelPath)); File.WriteAllText(modelPath, id); } catch { }
}
RaiseChanged();
}
public void Refresh()
{
if (Interlocked.Exchange(ref busy, 1) != 0) return;
ThreadPool.QueueUserWorkItem(delegate
{
try
{
ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(feedUrl);
request.Timeout = 15000; request.ReadWriteTimeout = 15000; request.AllowAutoRedirect = false;
request.UserAgent = "DeepSeekPrimetime/0.2.0";
if (etag != null) request.Headers[HttpRequestHeader.IfNoneMatch] = etag;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream input = response.GetResponseStream())
using (MemoryStream data = new MemoryStream())
{
if (response.StatusCode == HttpStatusCode.NotModified) { MarkUnchanged(); return; }
if (response.StatusCode != HttpStatusCode.OK) throw new IOException("Unexpected policy response");
byte[] buffer = new byte[8192]; int length;
while ((length = input.Read(buffer, 0, buffer.Length)) > 0)
{
data.Write(buffer, 0, length);
if (data.Length > 512 * 1024) throw new IOException("Policy response exceeds limit");
}
Accept(data.ToArray(), DateTime.UtcNow, true);
etag = response.Headers[HttpResponseHeader.ETag];
}
}
catch (WebException error)
{
HttpWebResponse response = error.Response as HttpWebResponse;
if (response == null || response.StatusCode != HttpStatusCode.NotModified) throw;
response.Dispose();
MarkUnchanged();
}
}
catch (Exception error)
{
bool rejected = !(error is WebException || error is IOException && !(error is InvalidDataException));
lock (gate) snapshot = new PolicySnapshot { Policy = snapshot.Policy, SelectedModel = snapshot.SelectedModel, DownloadedAtUtc = snapshot.DownloadedAtUtc, Offline = true, UpdateRejected = rejected, DownloadMessage = rejected ? "Update could not be verified; previous data retained" : "Update unavailable; previous data retained" };
}
finally { Interlocked.Exchange(ref busy, 0); RaiseChanged(); }
});
}
private void MarkUnchanged()
{
lock (gate)
{
if (snapshot.Policy == null) throw new IOException("No cached policy for unchanged response");
snapshot = new PolicySnapshot { Policy = snapshot.Policy, SelectedModel = snapshot.SelectedModel, DownloadedAtUtc = DateTime.UtcNow };
}
}
private void RaiseChanged() { Action callback = Changed; if (callback != null) callback(); }
}
}
+207
View File
@@ -0,0 +1,207 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace DeepSeekTray.Tests
{
public static class PolicyTests
{
private static int failures, assertions;
public static PricingPolicy Fixture()
{
using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("policy-fixture.json"))
using (MemoryStream memory = new MemoryStream()) { stream.CopyTo(memory); return PricingPolicy.Read<PricingPolicy>(memory.ToArray()); }
}
private static PricingPolicy Current()
{
PricingPolicy policy = Fixture(); DateTime now = DateTime.UtcNow;
policy.PublishedAtUtc = policy.SourceVerifiedAtUtc = policy.SourceCheckedAtUtc = Stamp(now);
policy.ExpiresAtUtc = Stamp(now.AddHours(48));
return policy;
}
private static string Stamp(DateTime value) { return value.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss'Z'"); }
private static PricingPolicy Clone(PricingPolicy policy) { return PricingPolicy.Read<PricingPolicy>(PricingPolicy.Write(policy)); }
private static void Check(bool result, string name)
{ assertions++; if (!result) { failures++; Console.WriteLine("FAIL: " + name); } }
private static void Reject(Action action, string name)
{ try { action(); Check(false, name); } catch { Check(true, name); } }
private static byte[] Sign(PricingPolicy policy, RSACryptoServiceProvider rsa)
{
byte[] payload = PricingPolicy.Write(policy);
return PricingPolicy.Write(new SignedPolicy { KeyId = "primetime-2026-1", Payload = Convert.ToBase64String(payload), Signature = Convert.ToBase64String(rsa.SignData(payload, CryptoConfig.MapNameToOID("SHA256"))) });
}
private static PolicySnapshot Snapshot(PricingPolicy policy) { return new PolicySnapshot { Policy = policy }; }
private static DateTime Date(int month, int day, int hour, int minute = 0) { return new DateTime(2026, month, day, hour, minute, 0, DateTimeKind.Utc); }
private static string Texts(Control root)
{ StringBuilder value = new StringBuilder(root.Text + "\n"); foreach (Control child in root.Controls) value.Append(Texts(child)); return value.ToString(); }
public static int Run()
{
failures = assertions = 0;
PricingPolicy policy = Current(); DateTime now = DateTime.UtcNow;
policy.Validate(); Check(true, "Current source fixture validates");
Check(!DeepSeekSchedule.IsPeakHour(policy, Date(10, 1, 2)), "National holiday off-peak");
Check(!DeepSeekSchedule.IsPeakHour(policy, Date(2, 23, 2)), "Lunar holiday final day off-peak");
Check(!DeepSeekSchedule.IsPeakHour(policy, Date(10, 10, 2)), "Adjusted Saturday still off-peak");
Check(DeepSeekSchedule.IsPeakHour(policy, Date(10, 8, 1)), "First weekday after holiday peak");
PricingPolicy cross = Clone(policy); cross.Weekdays = new[] { 1 }; cross.HolidayExempt = false; cross.Windows = new[] { new RateWindow { StartMinute = 1380, EndMinute = 60 } };
Check(DeepSeekSchedule.IsPeakHour(cross, Date(9,21,23)), "Cross-midnight start");
Check(DeepSeekSchedule.IsPeakHour(cross, Date(9,22,0)), "Cross-midnight previous weekday");
Check(!DeepSeekSchedule.IsPeakHour(cross, Date(9,22,1)), "Cross-midnight end is exclusive");
Check(DeepSeekSchedule.GetStatus(cross, Date(9,21,23,30)).NextTransitionUtc == Date(9,22,1), "Cross-midnight next transition");
PricingPolicy chinese = Clone(policy); chinese.ScheduleTimezone = "China Standard Time"; chinese.Windows = new[] { new RateWindow { StartMinute=540, EndMinute=720 } };
Check(DeepSeekSchedule.IsPeakHour(chinese,Date(9,21,1)), "China schedule maps to UTC");
Check(!DeepSeekSchedule.IsPeakHour(chinese,Date(9,21,4)), "China schedule end");
PricingPolicy holidayBoundary = Clone(cross); holidayBoundary.HolidayExempt = true; holidayBoundary.HolidayDates = new[] { "2026-09-22" }; holidayBoundary.Windows = new[] { new RateWindow { StartMinute=900, EndMinute=1080 } };
Check(DeepSeekSchedule.GetStatus(holidayBoundary,Date(9,21,15)).NextTransitionUtc == Date(9,21,16), "China holiday midnight interrupts UTC window");
Check(!DeepSeekSchedule.IsPeakHour(holidayBoundary,Date(9,21,16)), "Holiday uses China date");
PricingPolicy flat = Clone(policy); flat.Mode = "flat"; flat.Windows = new RateWindow[0]; flat.PolicyId = "flat";
foreach (ModelPrices model in flat.Models) model.Standard = new PriceSet { CacheHit="0.02", CacheMiss="0.2", Output="0.8" };
flat.Validate();
Check(Snapshot(flat).State(now) == RateState.Flat, "Flat pricing has own state");
Check(!DeepSeekSchedule.GetStatus(flat, now).NextTransitionUtc.HasValue, "Flat pricing has no invented transition");
Check(DeepSeekSchedule.GetUpcomingPeakBlocks(flat, now).Count == 0, "Flat pricing has no peak cards");
Check(Snapshot(flat).Savings(now) == "No scheduled discount", "Flat pricing has no savings claim");
PolicySnapshot missing = Snapshot(policy); missing.SelectedModel="removed";
Check(missing.State(now) == RateState.Unknown, "Missing model is unknown");
PolicySnapshot offline = Snapshot(policy); offline.Offline=true;
Check(offline.State(now) != RateState.Unknown && offline.Freshness(now).Contains("Cached"), "Fresh cache remains useful offline");
Check(offline.State(now.AddHours(49)) == RateState.Unknown, "Expired cache is unknown");
PricingPolicy review = Clone(policy); review.SourceStatus="reviewRequired";
Check(Snapshot(review).State(now) == RateState.Unknown, "Unrecognized policy withholds rates");
PricingPolicy noCalendar = Clone(policy); noCalendar.CalendarValidThrough="2026-10-08"; noCalendar.HolidayDates=new string[0];
Check(Snapshot(noCalendar).State(now) == RateState.Unknown, "Expired calendar is unknown");
PricingPolicy forecast = Clone(policy); forecast.CalendarValidThrough = "2026-10-09"; forecast.HolidayDates = new string[0];
Check(!DeepSeekSchedule.GetStatus(forecast,Date(10,9,13)).NextTransitionUtc.HasValue, "Forecast stops at maintained holiday coverage");
PricingPolicy asymmetric = Clone(policy); asymmetric.Models[0].OffPeak.CacheHit="0.004";
Check(Snapshot(asymmetric).Savings(now).Contains("hit"), "Discounts are computed per token category");
PricingPolicy future = Clone(policy); future.PendingPolicy=Clone(flat); future.PendingPolicy.EffectiveFromUtc=Stamp(now.AddMinutes(2));
future.Validate();
Check(future.At(now).Mode == "scheduled", "Pending prices do not apply early");
Check(future.At(now.AddMinutes(2)).Mode == "flat", "Pending prices activate at exact boundary");
Check(Snapshot(future).State(now.AddMinutes(2)) == RateState.Flat, "All rate state uses active pending policy");
PricingPolicy invalid = Clone(policy); invalid.SchemaVersion=2; Reject(delegate { invalid.Validate(); }, "Unsupported schema rejected");
invalid=Clone(policy); invalid.Models[0].OffPeak.CacheHit="-1"; Reject(delegate { invalid.Validate(); }, "Negative price rejected");
invalid=Clone(policy); invalid.Models[0].OffPeak.CacheHit="9"; Reject(delegate { invalid.Validate(); }, "Invalid discount rejected");
invalid=Clone(policy); invalid.ExpiresAtUtc=Stamp(now.AddDays(100)); Reject(delegate { invalid.Validate(); }, "Feed cannot extend verification indefinitely");
invalid=Clone(policy); invalid.Windows[0].StartMinute=1500; Reject(delegate { invalid.Validate(); }, "Invalid schedule rejected");
string directory = Path.Combine(Path.GetTempPath(), "DeepSeekPrimetime.Tests-" + Guid.NewGuid().ToString("N"));
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048))
{
rsa.PersistKeyInCsp=false; string key=rsa.ToXmlString(false);
byte[] initial=Sign(policy,rsa);
PolicyClient client = new PolicyClient(directory,key,"http://127.0.0.1:1/policy.json");
client.Accept(initial,now,true);
Check(client.Snapshot.Policy.PolicyId==policy.PolicyId,"Signed policy accepted");
PolicyClient restarted = new PolicyClient(directory,key,"http://127.0.0.1:1/policy.json");
Check(restarted.Snapshot.Offline && restarted.Snapshot.Policy!=null,"Offline startup restores verified cache");
PricingPolicy older=Clone(policy); older.Revision=0;
Reject(delegate { client.Accept(Sign(older,rsa),now,true); },"Older revision rejected");
PricingPolicy rollback=Clone(policy); rollback.Revision=2; rollback.PolicyId="new";
client.Accept(Sign(rollback,rsa),now,true);
Reject(delegate { client.Accept(initial,now,true); },"Rollback after newer revision rejected");
PricingPolicy sameRevision=Clone(rollback); sameRevision.Models[0].Name="Unexpected";
Reject(delegate { client.Accept(Sign(sameRevision,rsa),now,true); },"Changed contents at same revision rejected");
SignedPolicy bad=PricingPolicy.Read<SignedPolicy>(initial); byte[] payload=Convert.FromBase64String(bad.Payload); payload[0]^=1; bad.Payload=Convert.ToBase64String(payload);
Reject(delegate { client.Accept(PricingPolicy.Write(bad),now,true); },"Tampered payload rejected");
bad=PricingPolicy.Read<SignedPolicy>(initial); bad.KeyId="unknown";
Reject(delegate { client.Accept(PricingPolicy.Write(bad),now,true); },"Unknown key rejected");
Check(new PolicyClient(directory,key,"http://127.0.0.1:1").Snapshot.Policy.PolicyId=="new","Invalid updates do not overwrite cache");
restarted.SelectModel("deepseek-v4-pro");
Check(new PolicyClient(directory,key,"http://127.0.0.1:1").Snapshot.SelectedModel=="deepseek-v4-pro","Model selection persists");
using (FeedServer server = new FeedServer())
{
server.Body=initial;
PolicyClient live=new PolicyClient(Path.Combine(directory,"live"),key,server.Url);
live.Refresh(); Wait(live);
Check(live.Snapshot.Policy!=null&&!live.Snapshot.Offline,"Background HTTP fetch verifies signed policy");
DateTime verified=PricingPolicy.Utc(live.Snapshot.Policy.SourceVerifiedAtUtc);
server.NotModified=true; live.Refresh();Wait(live);
Check(!live.Snapshot.Offline&&PricingPolicy.Utc(live.Snapshot.Policy.SourceVerifiedAtUtc)==verified,"HTTP 304 does not renew source verification");
server.NotModified=false;
using(StatusForm form=new StatusForm(live))
{
form.Show();Application.DoEvents();
Check(Texts(form).Contains("$0.003"),"Dashboard uses initial feed prices");
Check(ReadableCards(form),"Upcoming cards have visible widths");
PricingPolicy updated=Clone(policy);updated.Revision=3;updated.PolicyId="updated";updated.Models[0].Name="Flash Updated";updated.Models[0].OffPeak.CacheHit="0.009";updated.Models[0].Peak.CacheHit="0.012";
server.Body=Sign(updated,rsa);live.Refresh();Wait(live);form.RefreshData();Application.DoEvents();
Check(Texts(form).Contains("$0.009")&&Texts(form).Contains("Flash Updated")&&!Texts(form).Contains("$0.003"),"Same running release assembly updates names and prices");
flat.Revision=4;server.Body=Sign(flat,rsa);live.Refresh();Wait(live);form.RefreshData();Application.DoEvents();
Check(Texts(form).Contains("STANDARD PRICING")&&Texts(form).Contains("No peak windows")&&!Texts(form).Contains("50%"),"Same window handles discount removal consistently");
server.Body=Encoding.UTF8.GetBytes("{}");live.Refresh();Wait(live);form.RefreshData();Application.DoEvents();
Check(live.Snapshot.State(now)==RateState.Unknown&&Texts(form).Contains("historical"),"Invalid update uses amber historical state");
updated.Revision=5;server.Body=Sign(updated,rsa);live.Refresh();Wait(live);form.RefreshData();
Check(!live.Snapshot.UpdateRejected&&live.Snapshot.State(now)!=RateState.Unknown,"Valid update recovers after rejection");
server.Fail=true;live.Refresh();Wait(live);form.RefreshData();
Check(live.Snapshot.Offline&&live.Snapshot.Policy.Revision==5,"Network failure preserves last accepted policy");
form.Close();
}
}
}
// This generated directory is exclusively owned by this test run.
if (Directory.Exists(directory)) Directory.Delete(directory,true);
Console.WriteLine("Policy/client/UI tests: {0} assertions, {1} failures",assertions,failures);
return failures;
}
private static bool ReadableCards(Control root)
{
foreach(Control control in root.Controls)
{
if(control.Text.StartsWith("In ") && control.Width < 400) return false;
if(!ReadableCards(control)) return false;
}
return true;
}
private static void Wait(PolicyClient client)
{
DateTime until=DateTime.UtcNow.AddSeconds(20);
while(client.IsChecking && DateTime.UtcNow<until) { Application.DoEvents();Thread.Sleep(10); }
Check(!client.IsChecking,"Background refresh completes");
}
private sealed class FeedServer : IDisposable
{
private readonly TcpListener listener;
private readonly Thread thread;
private volatile bool stopping;
public volatile byte[] Body;
public volatile bool NotModified,Fail;
public readonly string Url;
public FeedServer()
{
listener=new TcpListener(IPAddress.Loopback,0);listener.Start();
Url="http://127.0.0.1:"+((IPEndPoint)listener.LocalEndpoint).Port+"/policy.json";
thread=new Thread(Serve);thread.IsBackground=true;thread.Start();
}
private void Serve()
{
while(!stopping)
{
try
{
using(TcpClient connection=listener.AcceptTcpClient())
using(NetworkStream stream=connection.GetStream())
{
stream.ReadTimeout=3000;byte[] buffer=new byte[8192];stream.Read(buffer,0,buffer.Length);
byte[] body=Body??new byte[0];string status=Fail?"503 Service Unavailable":NotModified?"304 Not Modified":"200 OK";
if(Fail||NotModified)body=new byte[0];
byte[] header=Encoding.ASCII.GetBytes("HTTP/1.1 "+status+"\r\nContent-Length: "+body.Length+"\r\nETag: \"fixture\"\r\nConnection: close\r\n\r\n");
stream.Write(header,0,header.Length);stream.Write(body,0,body.Length);
}
}
catch { if(stopping)return; }
}
}
public void Dispose(){stopping=true;listener.Stop();thread.Join(3000);}
}
}
}
+106
View File
@@ -0,0 +1,106 @@
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
namespace DeepSeekTray
{
class PreviewIcons
{
static void Main()
{
SaveIconSample(false, "icon_offpeak_sample.png");
SaveIconSample(true, "icon_peak_sample.png");
Console.WriteLine("Saved preview samples.");
}
static void SaveIconSample(bool isPeak, string filename)
{
int size = 64;
using (Bitmap bmp = new Bitmap(size, size, System.Drawing.Imaging.PixelFormat.Format32bppArgb))
{
using (Graphics g = Graphics.FromImage(bmp))
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.Clear(Color.Transparent);
// DeepSeek Blue rounded badge
RectangleF badgeRect = new RectangleF(2, 2, size - 4, size - 4);
float radius = size * 0.24f;
using (GraphicsPath badgePath = CreateRoundedRect(badgeRect, radius))
{
// Background gradient / solid DeepSeek Blue
using (LinearGradientBrush bgBrush = new LinearGradientBrush(
badgeRect,
Color.FromArgb(20, 100, 255), // DeepSeek Blue top
Color.FromArgb(10, 60, 210), // DeepSeek Blue bottom
LinearGradientMode.Vertical))
{
g.FillPath(bgBrush, badgePath);
}
// Subtle outer border for contrast on light/dark taskbars
using (Pen borderPen = new Pen(Color.FromArgb(5, 35, 140), 1.5f))
{
g.DrawPath(borderPen, badgePath);
}
}
// Dollar sign in center
Color dollarColor = isPeak ? Color.FromArgb(255, 65, 80) : Color.FromArgb(0, 255, 136);
float fontSize = size * 0.65f;
using (Font font = new Font("Segoe UI", fontSize, FontStyle.Bold, GraphicsUnit.Pixel))
using (GraphicsPath textPath = new GraphicsPath())
{
StringFormat sf = new StringFormat
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
RectangleF textRect = new RectangleF(0, -size * 0.03f, size, size);
textPath.AddString("$", font.FontFamily, (int)FontStyle.Bold, fontSize, textRect, sf);
// Subtle dark shadow behind $ for depth
using (Matrix m = new Matrix())
{
m.Translate(0, 1f);
textPath.Transform(m);
using (Brush shadowBrush = new SolidBrush(Color.FromArgb(70, 0, 20, 80)))
{
g.FillPath(shadowBrush, textPath);
}
m.Reset();
m.Translate(0, -1f);
textPath.Transform(m);
}
using (Brush brush = new SolidBrush(dollarColor))
{
g.FillPath(brush, textPath);
}
}
}
bmp.Save(filename, System.Drawing.Imaging.ImageFormat.Png);
}
}
static GraphicsPath CreateRoundedRect(RectangleF rect, float radius)
{
GraphicsPath path = new GraphicsPath();
float d = radius * 2;
path.AddArc(rect.X, rect.Y, d, d, 180, 90);
path.AddArc(rect.Right - d, rect.Y, d, d, 270, 90);
path.AddArc(rect.Right - d, rect.Bottom - d, d, d, 0, 90);
path.AddArc(rect.X, rect.Bottom - d, d, d, 90, 90);
path.CloseFigure();
return path;
}
}
}
+202
View File
@@ -0,0 +1,202 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
namespace DeepSeekTray
{
[DataContract] public class SignedPolicy
{
[DataMember(Name="keyId")] public string KeyId;
[DataMember(Name="payload")] public string Payload;
[DataMember(Name="signature")] public string Signature;
}
[DataContract] public class PriceSet
{
[DataMember(Name="cacheHit")] public string CacheHit;
[DataMember(Name="cacheMiss")] public string CacheMiss;
[DataMember(Name="output")] public string Output;
public decimal[] Values { get { return new[] { Money(CacheHit), Money(CacheMiss), Money(Output) }; } }
private static decimal Money(string text)
{
decimal result;
if (!decimal.TryParse(text, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out result) || result < 0 || result > 100000)
throw new InvalidDataException("Invalid token price");
return result;
}
}
[DataContract] public class ModelPrices
{
[DataMember(Name="id")] public string Id;
[DataMember(Name="name")] public string Name;
[DataMember(Name="currency")] public string Currency;
[DataMember(Name="tokenUnit")] public int TokenUnit;
[DataMember(Name="offPeak")] public PriceSet OffPeak;
[DataMember(Name="peak")] public PriceSet Peak;
[DataMember(Name="standard")] public PriceSet Standard;
}
[DataContract] public class RateWindow
{
[DataMember(Name="startMinute")] public int StartMinute;
[DataMember(Name="endMinute")] public int EndMinute;
}
[DataContract] public class PricingPolicy
{
[DataMember(Name="schemaVersion")] public int SchemaVersion;
[DataMember(Name="revision")] public long Revision;
[DataMember(Name="policyId")] public string PolicyId;
[DataMember(Name="publishedAtUtc")] public string PublishedAtUtc;
[DataMember(Name="sourceVerifiedAtUtc")] public string SourceVerifiedAtUtc;
[DataMember(Name="sourceCheckedAtUtc")] public string SourceCheckedAtUtc;
[DataMember(Name="sourceStatus")] public string SourceStatus;
[DataMember(Name="sourceMessage")] public string SourceMessage;
[DataMember(Name="sourceUrl")] public string SourceUrl;
[DataMember(Name="expiresAtUtc")] public string ExpiresAtUtc;
[DataMember(Name="effectiveFromUtc")] public string EffectiveFromUtc;
[DataMember(Name="mode")] public string Mode;
[DataMember(Name="scheduleTimezone")] public string ScheduleTimezone;
[DataMember(Name="holidayTimezone")] public string HolidayTimezone;
[DataMember(Name="weekdays")] public int[] Weekdays;
[DataMember(Name="windows")] public RateWindow[] Windows;
[DataMember(Name="holidayExempt")] public bool HolidayExempt;
[DataMember(Name="holidayDates")] public string[] HolidayDates;
[DataMember(Name="calendarFrom")] public string CalendarFrom;
[DataMember(Name="calendarValidThrough")] public string CalendarValidThrough;
[DataMember(Name="models")] public ModelPrices[] Models;
[DataMember(Name="pendingPolicy")] public PricingPolicy PendingPolicy;
public static DateTime Utc(string value)
{
return DateTime.ParseExact(value, "yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
}
public static T Read<T>(byte[] bytes)
{
using (MemoryStream stream = new MemoryStream(bytes))
return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(stream);
}
public static byte[] Write<T>(T value)
{
using (MemoryStream stream = new MemoryStream())
{
new DataContractJsonSerializer(typeof(T)).WriteObject(stream, value);
return stream.ToArray();
}
}
public ModelPrices FindModel(string id)
{
foreach (ModelPrices model in Models) if (model.Id == id) return model;
return null;
}
public PricingPolicy At(DateTime now)
{
return PendingPolicy != null && Utc(PendingPolicy.EffectiveFromUtc) <= now ? PendingPolicy : this;
}
public void Validate(bool nested = false)
{
if (SchemaVersion != 1 || (!nested && Revision < 1) || string.IsNullOrEmpty(PolicyId) || PolicyId.Length > 128)
throw new InvalidDataException("Unsupported policy version");
if (!nested)
{
DateTime verified = Utc(SourceVerifiedAtUtc), published = Utc(PublishedAtUtc);
if (SourceUrl != "https://api-docs.deepseek.com/quick_start/pricing/" || (SourceStatus != "current" && SourceStatus != "unavailable" && SourceStatus != "reviewRequired"))
throw new InvalidDataException("Invalid policy source status");
if (verified > published.AddMinutes(5) || Utc(ExpiresAtUtc) > verified.AddHours(48) || Utc(ExpiresAtUtc) < verified)
throw new InvalidDataException("Invalid policy freshness");
}
Utc(EffectiveFromUtc);
if (Mode != "scheduled" && Mode != "flat") throw new InvalidDataException("Unsupported pricing policy");
if (ScheduleTimezone != "UTC" && ScheduleTimezone != "China Standard Time") throw new InvalidDataException("Unsupported schedule timezone");
if (HolidayTimezone != "China Standard Time") throw new InvalidDataException("Unsupported holiday timezone");
if (Models == null || Models.Length == 0 || Models.Length > 20) throw new InvalidDataException("Missing models");
HashSet<string> identifiers = new HashSet<string>();
foreach (ModelPrices model in Models)
{
if (string.IsNullOrEmpty(model.Id) || model.Id.Length > 80 || !identifiers.Add(model.Id) || string.IsNullOrEmpty(model.Name) || model.Name.Length > 100 || model.Currency != "USD" || model.TokenUnit != 1000000)
throw new InvalidDataException("Unsupported model or currency");
if (Mode == "flat")
{
if (model.Standard == null) throw new InvalidDataException("Missing standard prices");
decimal[] values = model.Standard.Values;
}
else
{
if (model.Peak == null || model.OffPeak == null) throw new InvalidDataException("Missing tier prices");
decimal[] peak = model.Peak.Values, off = model.OffPeak.Values;
for (int i = 0; i < 3; i++) if (off[i] > peak[i]) throw new InvalidDataException("Invalid discount prices");
}
}
if (Windows == null || Weekdays == null || Windows.Length > 16 || Weekdays.Length > 7)
throw new InvalidDataException("Invalid schedule");
if (Mode == "scheduled" && (Windows.Length == 0 || Weekdays.Length == 0)) throw new InvalidDataException("Missing peak schedule");
foreach (int day in Weekdays) if (day < 0 || day > 6) throw new InvalidDataException("Invalid weekday");
foreach (RateWindow window in Windows)
if (window.StartMinute < 0 || window.StartMinute >= 1440 || window.EndMinute < 0 || window.EndMinute >= 1440 || window.StartMinute == window.EndMinute)
throw new InvalidDataException("Invalid rate window");
if (HolidayDates == null || HolidayDates.Length > 1000) throw new InvalidDataException("Invalid holiday calendar");
DateTime from = DateTime.ParseExact(CalendarFrom, "yyyy-MM-dd", CultureInfo.InvariantCulture), through = DateTime.ParseExact(CalendarValidThrough, "yyyy-MM-dd", CultureInfo.InvariantCulture);
if (from > through) throw new InvalidDataException("Invalid calendar coverage");
foreach (string day in HolidayDates)
{
DateTime date = DateTime.ParseExact(day, "yyyy-MM-dd", CultureInfo.InvariantCulture);
if (date < from || date > through) throw new InvalidDataException("Holiday outside calendar coverage");
}
if (PendingPolicy != null)
{
if (nested || PendingPolicy.PendingPolicy != null) throw new InvalidDataException("Nested pending policy");
PendingPolicy.Validate(true);
}
}
}
public enum RateState { Unknown, OffPeak, Peak, Flat }
public class PolicySnapshot
{
public PricingPolicy Policy;
public bool Offline;
public bool UpdateRejected;
public string DownloadMessage;
public DateTime? DownloadedAtUtc;
public string SelectedModel = "deepseek-flash";
public ModelPrices Model(DateTime now) { return Policy == null ? null : Policy.At(now).FindModel(SelectedModel); }
public string Problem(DateTime now)
{
if (Policy == null) return "Pricing unavailable — checking official policy";
if (UpdateRejected) return "Latest update could not be verified";
if (Policy.SourceStatus == "reviewRequired") return "Pricing policy changed — review required";
if (PricingPolicy.Utc(Policy.SourceVerifiedAtUtc) > now.AddMinutes(5)) return "Clock differs from policy verification time";
if (now >= PricingPolicy.Utc(Policy.ExpiresAtUtc)) return "Pricing verification expired";
PricingPolicy active = Policy.At(now);
if (now < PricingPolicy.Utc(active.EffectiveFromUtc)) return "Pricing policy is not effective yet";
if (active.FindModel(SelectedModel) == null) return "Selected model is no longer listed";
string chinaDate = now.AddHours(8).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
if (active.HolidayExempt && (string.CompareOrdinal(chinaDate, active.CalendarFrom) < 0 || string.CompareOrdinal(chinaDate, active.CalendarValidThrough) > 0))
return "Holiday calendar needs updating";
return null;
}
public RateState State(DateTime now)
{
if (Problem(now) != null) return RateState.Unknown;
PricingPolicy active = Policy.At(now);
return active.Mode == "flat" ? RateState.Flat : DeepSeekSchedule.IsPeakHour(active, now) ? RateState.Peak : RateState.OffPeak;
}
public string Freshness(DateTime now)
{
if (Policy == null) return DownloadMessage ?? "Waiting for the first verified update";
return string.Format("Source verified: {0:g} local · {1}", PricingPolicy.Utc(Policy.SourceVerifiedAtUtc).ToLocalTime(), Offline || Policy.SourceStatus != "current" ? "Cached / offline" : "Official source checked");
}
public string Savings(DateTime now)
{
ModelPrices model = Model(now);
if (model == null || Policy.At(now).Mode == "flat") return "No scheduled discount";
decimal[] peak = model.Peak.Values, off = model.OffPeak.Values;
decimal[] percentages = new decimal[3];
for (int i = 0; i < 3; i++) percentages[i] = peak[i] == 0 ? 0 : (1 - off[i] / peak[i]) * 100;
if (percentages[0] == percentages[1] && percentages[1] == percentages[2])
return percentages[0].ToString("0.##", CultureInfo.InvariantCulture) + "% lower";
return string.Format(CultureInfo.InvariantCulture, "Savings: hit {0:0.##}%, miss {1:0.##}%, output {2:0.##}%", percentages[0], percentages[1], percentages[2]);
}
}
}
+31
View File
@@ -0,0 +1,31 @@
using System;
using System.Threading;
using System.Windows.Forms;
namespace DeepSeekTray
{
static class Program
{
private const string AppGuid = "Global\\DeepSeekTray_65A0D97D-4F70-4E83-84B9-A7F7C7338008";
[STAThread]
static void Main(string[] args)
{
bool createdNew;
using (Mutex mutex = new Mutex(false, AppGuid, out createdNew))
{
if (!createdNew)
{
// Already running
MessageBox.Show("DeepSeek Tray Indicator is already running in your notification area / taskbar tray.",
"DeepSeek Tray", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new TrayApplicationContext(Array.IndexOf(args, "--background") < 0));
}
}
}
}
+190
View File
@@ -0,0 +1,190 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Globalization;
using System.Windows.Forms;
namespace DeepSeekTray
{
public class TimelineBarPanel : Panel
{
public PolicySnapshot Snapshot;
public TimelineBarPanel() { DoubleBuffered = true; Height = 60; BackColor = Color.FromArgb(28, 30, 36); }
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (Snapshot == null) return;
DateTime now = DateTime.UtcNow;
float width = (ClientSize.Width - 20) / 24f;
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
using (Font small = new Font("Segoe UI", 8))
using (Brush text = new SolidBrush(Color.LightGray))
{
for (int i = 0; i < 24; i++)
{
DateTime hour = now.AddHours(i);
using (Brush fill = new SolidBrush(IconGenerator.StateColor(Snapshot.State(hour))))
e.Graphics.FillRectangle(fill, 10 + i * width, 8, Math.Max(1, width - 1), 22);
if (i % 3 == 0) e.Graphics.DrawString(hour.ToLocalTime().ToString("h tt"), small, text, 10 + i * width, 34);
}
using (Pen pen = new Pen(Color.Cyan, 2)) e.Graphics.DrawLine(pen, 10, 4, 10, 32);
}
}
}
public class StatusForm : Form
{
private readonly PolicyClient client;
private readonly Timer refreshTimer = new Timer();
private readonly Label badge, subtitle, freshness, downloaded, clock, transition, legend, note, pending;
private readonly ComboBox models;
private readonly Button check;
private readonly TimelineBarPanel timeline;
private readonly TableLayoutPanel prices;
private readonly Panel blocks;
private readonly Font bold = new Font("Segoe UI", 10, FontStyle.Bold);
private readonly Font title = new Font("Segoe UI", 16, FontStyle.Bold);
private bool choosing;
private string priceKey;
private Icon ownedIcon;
private RateState? iconState;
private bool resourcesDisposed;
public StatusForm() : this(new PolicyClient()) { }
public StatusForm(PolicyClient policyClient)
{
client = policyClient;
Text = "DeepSeek Primetime · Pricing & Schedule";
ClientSize = new Size(620, 800);
MinimumSize = new Size(580, 600);
StartPosition = FormStartPosition.CenterScreen;
BackColor = Color.FromArgb(22, 24, 28); ForeColor = Color.White;
Font = new Font("Segoe UI", 9.5f); ShowInTaskbar = true;
KeyPreview = true; KeyDown += delegate(object s, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) Close(); };
TableLayoutPanel main = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 1, RowCount = 2, Padding = new Padding(18) };
main.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));
main.RowStyles.Add(new RowStyle(SizeType.AutoSize)); main.RowStyles.Add(new RowStyle(SizeType.Percent, 100));
TableLayoutPanel header = new TableLayoutPanel { Dock = DockStyle.Top, AutoSize = true, ColumnCount = 1, Padding = new Padding(0, 0, 0, 12) };
header.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));
badge = Label("Checking pricing…", title, 40); subtitle = Label("", Font, 28);
freshness = Label("", Font, 25); downloaded = Label("", Font, 25);
header.Controls.Add(badge); header.Controls.Add(subtitle); header.Controls.Add(freshness); header.Controls.Add(downloaded);
TableLayoutPanel selection = new TableLayoutPanel { Dock = DockStyle.Top, AutoSize = true, ColumnCount = 2 };
selection.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); selection.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 180));
models = new ComboBox { Dock = DockStyle.Fill, DropDownStyle = ComboBoxStyle.DropDownList, BackColor = Color.FromArgb(40, 44, 52), ForeColor = Color.White };
models.SelectedIndexChanged += delegate { if (!choosing && models.SelectedItem != null) client.SelectModel(((ModelChoice)models.SelectedItem).Id); };
check = new Button { Text = "Check pricing updates", Dock = DockStyle.Fill, Height = 30, FlatStyle = FlatStyle.Flat, ForeColor = Color.White };
check.Click += delegate { client.Refresh(); RefreshData(); };
selection.Controls.Add(models, 0, 0); selection.Controls.Add(check, 1, 0); header.Controls.Add(selection);
FlowLayoutPanel body = new FlowLayoutPanel { Dock = DockStyle.Fill, AutoScroll = true, FlowDirection = FlowDirection.TopDown, WrapContents = false };
clock = Label("", Font, 30); transition = Label("", bold, 35); pending = Label("", Font, 42);
timeline = new TimelineBarPanel(); legend = Label("Green: off-peak · Red: peak · Blue: flat · Amber: unknown", Font, 32);
blocks = new Panel { Height = 220, Margin = new Padding(0, 0, 0, 12) };
prices = new TableLayoutPanel { Height = 150, ColumnCount = 3, BackColor = Color.FromArgb(28, 30, 36), Padding = new Padding(10), Margin = new Padding(0, 0, 0, 12) };
prices.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 46)); prices.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 27)); prices.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 27));
note = Label("", Font, 72);
LinkLabel source = new LinkLabel { Text = "View official DeepSeek pricing", AutoSize = true, LinkColor = Color.LightSkyBlue, Margin = new Padding(0, 4, 0, 12) };
source.LinkClicked += delegate { try { System.Diagnostics.Process.Start("https://api-docs.deepseek.com/quick_start/pricing/"); } catch { } };
body.Controls.Add(clock); body.Controls.Add(transition); body.Controls.Add(pending);
body.Controls.Add(Label("Next 24 hours · local clock labels", bold, 30)); body.Controls.Add(timeline); body.Controls.Add(legend);
body.Controls.Add(Label("Upcoming peak pricing windows", bold, 32)); body.Controls.Add(blocks);
body.Controls.Add(Label("USD per 1 million tokens", bold, 32)); body.Controls.Add(prices); body.Controls.Add(note); body.Controls.Add(source);
body.SizeChanged += delegate { foreach (Control control in body.Controls) control.Width = Math.Max(480, body.ClientSize.Width - 26); foreach (Control control in blocks.Controls) control.Width = Math.Max(440, body.ClientSize.Width - 34); };
main.Controls.Add(header, 0, 0); main.Controls.Add(body, 0, 1); Controls.Add(main);
refreshTimer.Interval = 5000; refreshTimer.Tick += delegate { RefreshData(); }; refreshTimer.Start();
RefreshData();
}
private Label Label(string text, Font font, int height)
{ return new Label { Text = text, Font = font, AutoSize = false, Height = height, Dock = DockStyle.Top, ForeColor = Color.LightGray, Margin = new Padding(0, 0, 0, 4) }; }
private class ModelChoice
{
public string Id, Name;
public override string ToString() { return Name; }
}
private static void ClearControls(Control container)
{ while (container.Controls.Count > 0) container.Controls[0].Dispose(); }
public void RefreshData()
{
PolicySnapshot snapshot = client.Snapshot;
DateTime now = DateTime.UtcNow;
PricingPolicy policy = snapshot.Policy == null ? null : snapshot.Policy.At(now);
ModelPrices model = snapshot.Model(now);
RateState state = snapshot.State(now);
string problem = snapshot.Problem(now);
badge.Text = state == RateState.Peak ? "● PEAK PRICING" : state == RateState.OffPeak ? "● OFF-PEAK PRICING" : state == RateState.Flat ? "● STANDARD PRICING" : "● PRICING NEEDS ATTENTION";
badge.ForeColor = IconGenerator.StateColor(state);
subtitle.Text = problem ?? (model.Name + " · " + (state == RateState.OffPeak ? snapshot.Savings(now) : state == RateState.Flat ? "No scheduled discount" : "Standard peak rates"));
freshness.Text = snapshot.Freshness(now);
downloaded.Text = snapshot.DownloadedAtUtc.HasValue ? "Feed downloaded: " + snapshot.DownloadedAtUtc.Value.ToLocalTime().ToString("g") + (snapshot.DownloadMessage == null ? "" : " · " + snapshot.DownloadMessage) : snapshot.DownloadMessage ?? "Using saved policy; checking for updates";
// Keep focus on this button during refresh; disabling it can scroll
// the body to the next focusable link. The client coalesces requests.
check.Text = client.IsChecking ? "Checking…" : "Check pricing updates";
clock.Text = string.Format("Local {0:h:mm tt} · UTC {1:HH:mm} · China {2:HH:mm}", now.ToLocalTime(), now, now.AddHours(8));
transition.Text = state == RateState.Unknown ? "Current rate cannot be confirmed" : DeepSeekSchedule.GetStatus(snapshot.Policy, now).TransitionDescription;
pending.Visible = snapshot.Policy != null && snapshot.Policy.PendingPolicy != null && now < PricingPolicy.Utc(snapshot.Policy.PendingPolicy.EffectiveFromUtc);
pending.Text = pending.Visible ? "New pricing policy activates " + PricingPolicy.Utc(snapshot.Policy.PendingPolicy.EffectiveFromUtc).ToLocalTime().ToString("f") : "";
timeline.Snapshot = snapshot; timeline.Invalidate();
legend.Text = state == RateState.Flat ? "Blue: standard pricing · No scheduled discount" : "Green: off-peak · Red: peak · Blue: flat · Amber: unknown";
string key = (policy == null ? "none" : policy.PolicyId) + snapshot.SelectedModel + state.ToString();
if (key != priceKey)
{
priceKey = key;
choosing = true; models.Items.Clear();
if (policy != null) foreach (ModelPrices item in policy.Models) models.Items.Add(new ModelChoice { Id = item.Id, Name = item.Name });
int selected = -1;
for (int i = 0; i < models.Items.Count; i++) if (((ModelChoice)models.Items[i]).Id == snapshot.SelectedModel) selected = i;
if (selected < 0) { selected = models.Items.Add(new ModelChoice { Id = snapshot.SelectedModel, Name = snapshot.SelectedModel + " (not listed)" }); }
models.SelectedIndex = selected; choosing = false;
PopulatePrices(model, policy, state);
}
ClearControls(blocks);
int cardCount = 0;
if (state == RateState.Peak || state == RateState.OffPeak)
foreach (PeakBlock block in DeepSeekSchedule.GetUpcomingPeakBlocks(snapshot.Policy, now))
{
Label card = Label(string.Format("{0} {1:ddd h:mm tt} – {2:ddd h:mm tt} local\n{3:HH:mm}–{4:HH:mm} UTC", block.IsActiveNow ? "ACTIVE · " + DeepSeekSchedule.FormatDuration(block.TimeRemaining) + " left" : "In " + DeepSeekSchedule.FormatDuration(block.TimeUntilStart), block.StartLocal, block.EndLocal, block.StartUtc, block.EndUtc), Font, 48);
card.Dock = DockStyle.None; card.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
card.BackColor = Color.FromArgb(36, 38, 46); card.Padding = new Padding(8, 3, 8, 3); card.SetBounds(0, cardCount * 54, Math.Max(440, blocks.Width - 8), 48); blocks.Controls.Add(card); cardCount++;
}
else { blocks.Controls.Add(Label(state == RateState.Flat ? "No peak windows in this policy" : "Schedule withheld until the policy can be confirmed", Font, 30)); cardCount = 1; }
blocks.Height = state == RateState.Flat || state == RateState.Unknown ? 36 : Math.Max(36, cardCount * 54);
note.Text = state == RateState.Unknown ? "Displayed prices, if present, are historical reference values.\n" + (snapshot.Policy == null ? "" : snapshot.Policy.SourceMessage) : policy.HolidayExempt ? "Weekday peak windows follow the published schedule.\nChinese public holidays and all weekends are off-peak.\nHoliday calendar covers through " + policy.CalendarValidThrough + "." : "Rates follow the published policy shown above.";
if (!iconState.HasValue || iconState.Value != state)
{
Icon next = IconGenerator.CreateDollarIcon(state), previous = ownedIcon;
Icon = next; ownedIcon = next; iconState = state;
if (previous != null) previous.Dispose();
}
}
private void PopulatePrices(ModelPrices model, PricingPolicy policy, RateState state)
{
prices.SuspendLayout(); ClearControls(prices); prices.RowStyles.Clear(); prices.RowCount = 4;
bool flat = policy != null && policy.Mode == "flat";
string suffix = state == RateState.Unknown ? " (historical)" : "";
string[] names = { "Input · cache hit", "Input · cache miss", "Output" };
AddCell("Token type", 0, 0, true); AddCell((flat ? "Standard" : "Off-peak") + suffix, 1, 0, true); AddCell(flat ? "" : "Peak" + suffix, 2, 0, true);
for (int row = 0; row < 3; row++)
{
AddCell(names[row], 0, row + 1, false);
AddCell(model == null ? "—" : "$" + (flat ? model.Standard : model.OffPeak).Values[row].ToString("0.######", CultureInfo.InvariantCulture), 1, row + 1, false);
AddCell(model == null || flat ? "" : "$" + model.Peak.Values[row].ToString("0.######", CultureInfo.InvariantCulture), 2, row + 1, false);
}
prices.ResumeLayout();
}
private void AddCell(string text, int column, int row, bool heading)
{ prices.Controls.Add(new Label { Text = text, AutoSize = true, Font = heading ? bold : Font, ForeColor = Color.White, Margin = new Padding(3, 5, 3, 5) }, column, row); }
protected override void Dispose(bool disposing)
{
if (disposing && !resourcesDisposed)
{
resourcesDisposed = true;
refreshTimer.Dispose();
// Destroy the native window before disposing only our own icon.
// Form.Icon can return a shared framework default after closing.
base.Dispose(disposing);
if (ownedIcon != null) { ownedIcon.Dispose(); ownedIcon = null; }
bold.Dispose(); title.Dispose();
}
else base.Dispose(disposing);
}
}
}
+103
View File
@@ -0,0 +1,103 @@
using System;
namespace DeepSeekTray.Tests
{
class TestRunner
{
private static int failed = 0;
private static void AssertEqual<T>(T expected, T actual, string testName)
{
if (!object.Equals(expected, actual))
{
Console.WriteLine("FAIL: {0}. Expected: {1}, Got: {2}", testName, expected, actual);
failed++;
}
else
{
Console.WriteLine("PASS: {0}", testName);
}
}
[STAThread]
static int Main()
{
System.Windows.Forms.Application.SetUnhandledExceptionMode(System.Windows.Forms.UnhandledExceptionMode.ThrowException);
DeepSeekSchedule.CurrentPolicy = PolicyTests.Fixture();
// Test 1: Monday 00:59 UTC (Off-peak)
DateTime t1 = new DateTime(2026, 9, 21, 0, 59, 0, DateTimeKind.Utc);
AssertEqual(false, DeepSeekSchedule.IsPeakHour(t1), "Monday 00:59 UTC should be Off-Peak");
// Test 2: Monday 01:00 UTC (Peak starts)
DateTime t2 = new DateTime(2026, 9, 21, 1, 0, 0, DateTimeKind.Utc);
AssertEqual(true, DeepSeekSchedule.IsPeakHour(t2), "Monday 01:00 UTC should be Peak");
// Test 3: Monday 03:59 UTC (Peak)
DateTime t3 = new DateTime(2026, 9, 21, 3, 59, 0, DateTimeKind.Utc);
AssertEqual(true, DeepSeekSchedule.IsPeakHour(t3), "Monday 03:59 UTC should be Peak");
// Test 4: Monday 04:00 UTC (Off-peak resumes)
DateTime t4 = new DateTime(2026, 9, 21, 4, 0, 0, DateTimeKind.Utc);
AssertEqual(false, DeepSeekSchedule.IsPeakHour(t4), "Monday 04:00 UTC should be Off-Peak");
// Test 5: Monday 05:59 UTC (Off-peak)
DateTime t5 = new DateTime(2026, 9, 21, 5, 59, 0, DateTimeKind.Utc);
AssertEqual(false, DeepSeekSchedule.IsPeakHour(t5), "Monday 05:59 UTC should be Off-Peak");
// Test 6: Monday 06:00 UTC (Peak starts)
DateTime t6 = new DateTime(2026, 9, 21, 6, 0, 0, DateTimeKind.Utc);
AssertEqual(true, DeepSeekSchedule.IsPeakHour(t6), "Monday 06:00 UTC should be Peak");
// Test 7: Monday 09:59 UTC (Peak)
DateTime t7 = new DateTime(2026, 9, 21, 9, 59, 0, DateTimeKind.Utc);
AssertEqual(true, DeepSeekSchedule.IsPeakHour(t7), "Monday 09:59 UTC should be Peak");
// Test 8: Monday 10:00 UTC (Off-peak resumes)
DateTime t8 = new DateTime(2026, 9, 21, 10, 0, 0, DateTimeKind.Utc);
AssertEqual(false, DeepSeekSchedule.IsPeakHour(t8), "Monday 10:00 UTC should be Off-Peak");
// Test 9: Saturday 02:00 UTC (Weekend = Off-peak)
DateTime t9 = new DateTime(2026, 9, 26, 2, 0, 0, DateTimeKind.Utc);
AssertEqual(false, DeepSeekSchedule.IsPeakHour(t9), "Saturday 02:00 UTC should be Off-Peak (Weekend)");
// Test 10: Sunday 08:00 UTC (Weekend = Off-peak)
DateTime t10 = new DateTime(2026, 9, 27, 8, 0, 0, DateTimeKind.Utc);
AssertEqual(false, DeepSeekSchedule.IsPeakHour(t10), "Sunday 08:00 UTC should be Off-Peak (Weekend)");
// Test 11: Transition calculation from Monday 00:00 UTC -> Next transition is 01:00 UTC
ScheduleStatus s1 = DeepSeekSchedule.GetStatus(new DateTime(2026, 9, 21, 0, 0, 0, DateTimeKind.Utc));
AssertEqual(new DateTime(2026, 9, 21, 1, 0, 0, DateTimeKind.Utc), s1.NextTransitionUtc, "Next transition from 00:00 UTC should be 01:00 UTC");
// Test 12: Transition calculation from Monday 02:00 UTC -> Next transition is 04:00 UTC
ScheduleStatus s2 = DeepSeekSchedule.GetStatus(new DateTime(2026, 9, 21, 2, 0, 0, DateTimeKind.Utc));
AssertEqual(new DateTime(2026, 9, 21, 4, 0, 0, DateTimeKind.Utc), s2.NextTransitionUtc, "Next transition from 02:00 UTC should be 04:00 UTC");
// Test 13: Icons generate without crashing
try
{
using (var greenIcon = IconGenerator.CreateDollarIcon(false, 32))
using (var redIcon = IconGenerator.CreateDollarIcon(true, 32))
{
AssertEqual(true, greenIcon != null && redIcon != null, "Icons generated successfully");
}
}
catch (Exception ex)
{
Console.WriteLine("Icon test failed: " + ex);
failed++;
}
// Test 14: Upcoming blocks return 4 valid windows
var blocks = DeepSeekSchedule.GetUpcomingPeakBlocks(new DateTime(2026, 9, 21, 0, 0, 0, DateTimeKind.Utc), 4);
AssertEqual(4, blocks.Count, "Should return 4 upcoming peak blocks");
AssertEqual(new DateTime(2026, 9, 21, 1, 0, 0, DateTimeKind.Utc), blocks[0].StartUtc, "First upcoming block starts at 01:00 UTC");
AssertEqual(new DateTime(2026, 9, 21, 4, 0, 0, DateTimeKind.Utc), blocks[0].EndUtc, "First upcoming block ends at 04:00 UTC");
AssertEqual(new DateTime(2026, 9, 21, 6, 0, 0, DateTimeKind.Utc), blocks[1].StartUtc, "Second upcoming block starts at 06:00 UTC");
failed += PolicyTests.Run();
Console.WriteLine("\nTotal failures: " + failed);
return failed;
}
}
}
+113
View File
@@ -0,0 +1,113 @@
using System;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.Win32;
namespace DeepSeekTray
{
public class TrayApplicationContext : ApplicationContext
{
private const string RunRegistryKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
private const string AppName = "DeepSeekTray";
private readonly PolicyClient client = new PolicyClient();
private readonly Control dispatcher = new Control();
private readonly NotifyIcon notifyIcon = new NotifyIcon();
private readonly ContextMenuStrip menu = new ContextMenuStrip();
private readonly Timer updateTimer = new Timer();
private readonly ToolStripMenuItem statusHeader, startup, check;
private StatusForm details;
private DateTime nextCheck;
private RateState? lastState;
private string lastPolicyId;
private bool exiting;
public TrayApplicationContext(bool showDashboard = false)
{
IntPtr handle = dispatcher.Handle;
statusHeader = new ToolStripMenuItem("Checking pricing…") { Enabled = false };
menu.Items.Add(statusHeader); menu.Items.Add(new ToolStripSeparator());
menu.Items.Add("Show pricing & schedule", null, delegate { ShowDetails(); });
check = new ToolStripMenuItem("Check for pricing updates", null, delegate { CheckPolicy(); }); menu.Items.Add(check);
startup = new ToolStripMenuItem("Start with Windows", null, ToggleStartup) { Checked = IsStartupEnabled() }; menu.Items.Add(startup);
menu.Items.Add("View official DeepSeek pricing", null, delegate { try { System.Diagnostics.Process.Start("https://api-docs.deepseek.com/quick_start/pricing/"); } catch { } });
menu.Items.Add(new ToolStripSeparator()); menu.Items.Add("Exit DeepSeek Primetime", null, delegate { ExitThread(); });
notifyIcon.ContextMenuStrip = menu;
notifyIcon.MouseClick += delegate(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) ShowDetails(); };
client.Changed += PolicyChanged;
SystemEvents.PowerModeChanged += PowerChanged;
updateTimer.Interval = 10000;
updateTimer.Tick += delegate { if (DateTime.UtcNow >= nextCheck) CheckPolicy(); UpdateStatus(true); };
UpdateStatus(false); notifyIcon.Visible = true; updateTimer.Start(); CheckPolicy();
if (showDashboard) ShowDetails();
}
private void Dispatch(Action action)
{
if (exiting || dispatcher.IsDisposed) return;
try { dispatcher.BeginInvoke(action); } catch (InvalidOperationException) { }
}
private void PolicyChanged() { Dispatch(delegate { UpdateStatus(true); }); }
private void PowerChanged(object sender, PowerModeChangedEventArgs e) { if (e.Mode == PowerModes.Resume) Dispatch(CheckPolicy); }
private void CheckPolicy() { nextCheck = DateTime.UtcNow.AddHours(1); client.Refresh(); UpdateStatus(false); }
private void UpdateStatus(bool notify)
{
PolicySnapshot snapshot = client.Snapshot;
DateTime now = DateTime.UtcNow;
RateState state = snapshot.State(now);
PricingPolicy policy = snapshot.Policy == null ? null : snapshot.Policy.At(now);
string name = state == RateState.Peak ? "Peak pricing" : state == RateState.OffPeak ? "Off-peak pricing" : state == RateState.Flat ? "Standard pricing · no scheduled discount" : "Pricing unconfirmed";
string tip = "DeepSeek: " + name + (snapshot.Offline ? " (cached)" : "");
notifyIcon.Text = tip.Length > 63 ? tip.Substring(0, 63) : tip;
statusHeader.Text = name; statusHeader.ForeColor = IconGenerator.StateColor(state);
check.Enabled = !client.IsChecking;
Icon old = notifyIcon.Icon; notifyIcon.Icon = IconGenerator.CreateDollarIcon(state); if (old != null) old.Dispose();
if (notify && lastState.HasValue && state != RateState.Unknown && lastState.Value != RateState.Unknown)
{
if (lastPolicyId != null && policy != null && lastPolicyId != policy.PolicyId)
notifyIcon.ShowBalloonTip(4000, "DeepSeek pricing policy updated", "The rates and schedule now use the latest verified policy.", ToolTipIcon.Info);
else if (state != lastState.Value)
notifyIcon.ShowBalloonTip(3000, "DeepSeek: " + name, state == RateState.Flat ? "No scheduled discount" : DeepSeekSchedule.GetStatus(snapshot.Policy, now).TransitionDescription, ToolTipIcon.Info);
}
lastState = state; lastPolicyId = policy == null ? null : policy.PolicyId;
if (details != null && !details.IsDisposed) details.RefreshData();
}
private void ShowDetails()
{
if (details == null || details.IsDisposed) { details = new StatusForm(client); details.Show(); }
else { details.Show(); details.BringToFront(); details.Activate(); }
}
private bool IsStartupEnabled()
{
try
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RunRegistryKey, false))
{
string value = key == null ? null : key.GetValue(AppName) as string;
return value != null && (value.Trim('"').Equals(Application.ExecutablePath, StringComparison.OrdinalIgnoreCase) || value.Equals("\"" + Application.ExecutablePath + "\" --background", StringComparison.OrdinalIgnoreCase));
}
}
catch { return false; }
}
private void ToggleStartup(object sender, EventArgs e)
{
try
{
using (RegistryKey key = Registry.CurrentUser.CreateSubKey(RunRegistryKey))
{
if (startup.Checked) key.DeleteValue(AppName, false);
else key.SetValue(AppName, "\"" + Application.ExecutablePath + "\" --background");
startup.Checked = !startup.Checked;
}
}
catch (Exception error) { MessageBox.Show("Windows startup could not be updated: " + error.Message, "DeepSeek Primetime"); }
}
protected override void ExitThreadCore()
{
exiting = true; updateTimer.Stop(); updateTimer.Dispose();
SystemEvents.PowerModeChanged -= PowerChanged; client.Changed -= PolicyChanged;
if (details != null) details.Dispose();
notifyIcon.Visible = false;
Icon icon = notifyIcon.Icon; notifyIcon.Icon = null; notifyIcon.Dispose(); if (icon != null) icon.Dispose();
menu.Dispose(); dispatcher.Dispose(); base.ExitThreadCore();
}
}
}
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

+21
View File
@@ -0,0 +1,21 @@
@echo off
setlocal
cd /d "%~dp0"
set "CSC=%SystemRoot%\Microsoft.NET\Framework64\v4.0.30319\csc.exe"
if not exist "%CSC%" (
echo Error: .NET Framework compiler not found at %CSC%
exit /b 1
)
if not exist "artifacts\tests" mkdir "artifacts\tests"
if not exist "artifacts\tests" exit /b 1
call build.bat
if errorlevel 1 exit /b 1
copy /y "DeepSeekPrimetime.exe" "artifacts\tests\DeepSeekPrimetime.exe" >nul
"%CSC%" /nologo /target:exe /optimize+ /platform:anycpu /resource:collector\fixtures\policy.json,policy-fixture.json /out:"artifacts\tests\DeepSeekPrimetime.Tests.exe" /r:System.dll,System.Core.dll,System.Drawing.dll,System.Windows.Forms.dll,System.Runtime.Serialization.dll,DeepSeekPrimetime.exe src\TestRunner.cs src\PolicyTests.cs
if errorlevel 1 exit /b 1
"artifacts\tests\DeepSeekPrimetime.Tests.exe"
exit /b %ERRORLEVEL%