usage: Qianfan's card counts its gift and bought credit packs beside the month (yuushabu_buyinn on X)
Baidu Qianfan's Token Plan Personal also holds credit packs, Baidu's
gifts (赠送积分包) among them, and the card read only the month's plan
quota. The card now reads the console's pack list too and shows:
- "Gift credits": the gift packs still live, credits used of their
total, and how many run out when (the soonest end with credits left);
- "Credit packs": the bought packs, the same way.
Each row shows only when the account has such packs. A pack list that
can't be read (refused, not JSON, a pack with no amount) is a "Credit
packs · Unknown" row, never 0 left. The month window goes on to credits
(Credits) while a usable pack holds some, since Baidu spends the month,
then the gift packs, then the bought ones. The pack rows are set aside
from routing. An account with no plan but live gift packs shows them as
its allowance, since Baidu spends gift packs without a plan; with no
plan and no packs (or none read) the card says there is no plan, as
before.
Endpoint: GET /api/qianfan/charge/tokenPlanPersonal/pack/list on
console.bce.baidu.com, with the cookie and headers the card already
sends for the resource list. Found in the console's public JS: the
qiankun "resource" micro-app (aip-static.cdn.bcebos.com/mb-static/
resource/), chunk index-5e21b2bb.js, which calls
send("charge/tokenPlanPersonal/pack/list", {}, {httpMethod: "GET"}) and
reads result.items: packType ("gift", "guoqing_lite", "guoqing_pro",
others bought), status ("active"), totalCredits, usedCredits,
remainingCredits, expiresAt, isUsable. The rules follow that page: a
gift pack counts while its expiresAt is ahead; bought packs while
active; guoqing packs are left out, as the page leaves them out.
No real account was used: no one here has a Baidu Cloud account with
a Token Plan or packs. The fixtures are built from the field names the
bundle reads, not a captured reply. String or number amounts are both
read.
Run at origin/main fefe3f658, then rebased on 05d46f42e (which changes
i18n.js and internal/gui); at the pushed head, on mica: gofmt clean,
go test -run 'Qianfan|Word|I18n|Tray' ./internal/provider ./internal/gui
ok, qianfan-credit-packs 2/2. At fefe3f658:
- go test -count=1 -timeout 45m ./internal/provider/ ./internal/gui/ on
mica: ok (152s, 239s).
- gofmt -l: clean. go vet ./internal/provider ./internal/gui for
darwin, GOOS=linux (-tags nogui) and GOOS=windows on mote: ok.
- GUI, on mote, both engines: qianfan-credit-packs (new) 2/2: en, zh,
zh-TW, ja and de at 360, 440 and 1000px. 47 more quota, usage-card,
credits and i18n files: the reds are the same 48 tests in 6 files
on an origin/main fefe3f658 copy, all filed: i18n-keys #6877,
quota-credits #6807, quota-curve #6789, quota-refresh-order #6180,
quota-bars-alike and usage-cards-hide #6975.
Broken by hand, each red, then green again: the Unknown row dropped
(TestQianfanPlanCardPacks), Credits never set (same), expired gift
packs counted, guoqing packs counted (TestReadQianfanPacks,
TestQianfanPlanCard), a pack with no total read as 0, gift packs
always aside, and the zh "Gift credits" translation removed
(qianfan-credit-packs).
Not tried: a real Qianfan account, the pack list's real reply, and the
enterprise plan (the bundle's pack list is the personal plan's). The
full go test ./... did not run before the push: mote and mica each had
another session's full suite going. It runs next.
This commit is contained in:
@@ -2461,6 +2461,8 @@ const I18N = {
|
||||
"Droid Core · 7 days": "Droid Core · 7 天",
|
||||
"Droid Core · 30 days": "Droid Core · 30 天",
|
||||
"Extra usage": "额外用量",
|
||||
"Gift credits": "赠送积分包",
|
||||
"Credit packs": "积分包",
|
||||
"Used up": "已用完",
|
||||
"Available": "可用",
|
||||
"Usage credits": "额外用量额度",
|
||||
@@ -7843,6 +7845,8 @@ const I18N = {
|
||||
"Droid Core · 7 days": "Droid Core · 7 天",
|
||||
"Droid Core · 30 days": "Droid Core · 30 天",
|
||||
"Extra usage": "額外用量",
|
||||
"Gift credits": "贈送積分包",
|
||||
"Credit packs": "積分包",
|
||||
"Used up": "已用完",
|
||||
"Available": "可用",
|
||||
"Usage credits": "額外用量額度",
|
||||
@@ -13198,6 +13202,8 @@ const I18N = {
|
||||
"Droid Core · 7 days": "Droid Core · 7日",
|
||||
"Droid Core · 30 days": "Droid Core · 30日",
|
||||
"Extra usage": "追加使用量",
|
||||
"Gift credits": "ギフトクレジット",
|
||||
"Credit packs": "クレジットパック",
|
||||
"Used up": "使い切り",
|
||||
"Available": "利用可能",
|
||||
"Usage credits": "追加使用量のクレジット",
|
||||
@@ -18588,6 +18594,8 @@ const I18N = {
|
||||
"Droid Core · 7 days": "Droid Core · 7 Tage",
|
||||
"Droid Core · 30 days": "Droid Core · 30 Tage",
|
||||
"Extra usage": "Zusätzliche Nutzung",
|
||||
"Gift credits": "Geschenkte Credits",
|
||||
"Credit packs": "Credit-Pakete",
|
||||
"Used up": "Aufgebraucht",
|
||||
"Available": "Verfügbar",
|
||||
"Usage credits": "Nutzungsguthaben",
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// yuushabu_buyinn on X: Baidu Qianfan's Token Plan Personal also holds
|
||||
// credit packs, Baidu's gifts (赠送积分包) among them, and the Usage card
|
||||
// counted only the month. The card now has a "Gift credits" row and a
|
||||
// "Credit packs" row under the month, each as credits used of the packs'
|
||||
// total and when the soonest left runs out, named in the reader's
|
||||
// language, at a phone's width too. Packs magpie couldn't read are an
|
||||
// "Unknown" row, never 0 left; an account with none has the month alone.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const soon = (h) => new Date(Date.now() + h * 3600e3).toISOString();
|
||||
const month = { name: "Month", used: 25, amount: 11250, limit: 45000, unit: "credits", resetsAt: soon(24 * 14), credits: true };
|
||||
// one account a card: several of one provider fold into one card
|
||||
const card = (id, windows) => ({ provider: id, name: "Baidu Qianfan " + id.slice(-1), icon: "baiducloud-color", plan: "Token Plan Pro", user: "u", windows });
|
||||
const quotas = [
|
||||
card("qianfan-a", [month,
|
||||
{ name: "Gift credits", used: 100 * 1200 / 7000, amount: 1200, limit: 7000, unit: "credits", runsOutAt: soon(30), runsOut: 3800 },
|
||||
{ name: "Credit packs", used: 25, amount: 2500, limit: 10000, unit: "credits", runsOutAt: soon(24 * 300), runsOut: 7500 }]),
|
||||
card("qianfan-b", [{ ...month, credits: false }, { name: "Credit packs", used: 0, text: true, display: "Unknown" }]),
|
||||
card("qianfan-c", [{ ...month, credits: false }]),
|
||||
];
|
||||
function serve(lang) {
|
||||
const settings = { lang, theme: "light", currency: "usd", chineseUnits: false };
|
||||
const state = { agents: [], profiles: [], settings };
|
||||
return async (r) => {
|
||||
const url = new URL(r.request().url());
|
||||
const json = (data) => r.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json(state);
|
||||
if (url.pathname === "/api/settings") return json(settings);
|
||||
if (url.pathname === "/api/gateway/trace") return url.searchParams.get("wait") ? new Promise(() => {}) : json({ mine: true, now: new Date().toISOString(), seq: 0, totals: {}, routes: [] });
|
||||
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
|
||||
if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } });
|
||||
if (url.pathname === "/api/usage/quotas") return json(quotas);
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
try { await r.fulfill({ body: await fs.readFile(file), contentType }); } catch { await r.fulfill({ status: 404, body: "" }); }
|
||||
};
|
||||
}
|
||||
|
||||
const words = {
|
||||
en: { gift: "Gift credits", packs: "Credit packs", unknown: "Unknown", expire: /^3,?800 credits expire .+ · in (29|30)h$/ },
|
||||
zh: { gift: "赠送积分包", packs: "积分包", unknown: "未知", expire: /^3,?800 积分 将于 .+ 过期 · (29|30) 小时后$/ },
|
||||
"zh-TW": { gift: "贈送積分包", packs: "積分包", unknown: "未知", expire: /^3,?800 積分 將於 .+ 過期 · (29|30) 小時後$/ },
|
||||
ja: { gift: "ギフトクレジット", packs: "クレジットパック", unknown: "不明", expire: /^3,?800 クレジットは .+ に失効 · (29|30) ?時間後$/ },
|
||||
de: { gift: "Geschenkte Credits", packs: "Credit-Pakete", unknown: "Unbekannt", expire: /^3[.,]?800 Credits verfallen .+ · in (29|30) Std\.?$/ },
|
||||
};
|
||||
|
||||
for (const [name, engine] of [["webkit", webkit], ["chromium", chromium]]) {
|
||||
test(`${name}: Qianfan's gift and bought credit packs are rows of their own beside the month, in every language, at 360, 440 and 1000px`, async () => {
|
||||
const browser = await engine.launch();
|
||||
try {
|
||||
for (const [lang, w] of Object.entries(words)) {
|
||||
for (const width of [360, 440, 1000]) {
|
||||
const page = await (await browser.newContext({ viewport: { width, height: 1200 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
await page.route("**/*", serve(lang));
|
||||
await page.goto("http://magpie.test/?view=usage");
|
||||
await page.locator(".subscription-card").nth(2).locator(".quota").first().waitFor();
|
||||
const got = await page.evaluate(() => ({
|
||||
cards: [...document.querySelectorAll(".subscription-card")].map((c) => {
|
||||
const box = c.getBoundingClientRect();
|
||||
return [...c.querySelectorAll(".quota")].map((q) => {
|
||||
const b = q.getBoundingClientRect();
|
||||
return { text: q.textContent.replace(/\s+/g, " ").trim(), reset: q.querySelector(".quota-reset")?.textContent.replace(/\s+/g, " ").trim() ?? "",
|
||||
inCard: b.left >= box.left - 1 && b.right <= box.right + 1 };
|
||||
});
|
||||
}),
|
||||
pageScroll: document.documentElement.scrollWidth > document.documentElement.clientWidth + 1,
|
||||
}));
|
||||
const at = `${lang} ${width}px`;
|
||||
assert.equal(got.cards.length, 3, at);
|
||||
const [a, b, c] = got.cards;
|
||||
assert.equal(a.length, 3, `${at}: month, gift and bought rows`);
|
||||
assert.ok(a[1].text.includes(w.gift), `${at}: gift row "${a[1].text}"`);
|
||||
assert.ok(/1,?200|1\.200/.test(a[1].text) && /7,?000|7\.000/.test(a[1].text), `${at}: gift amounts "${a[1].text}"`);
|
||||
assert.match(a[1].reset, w.expire, at);
|
||||
assert.ok(a[2].text.startsWith(w.packs) || a[2].text.includes(w.packs), `${at}: bought row "${a[2].text}"`);
|
||||
assert.ok(/10,?000|10\.000/.test(a[2].text), `${at}: bought total "${a[2].text}"`);
|
||||
assert.equal(b.length, 2, `${at}: packs not read are one row`);
|
||||
assert.ok(b[1].text.includes(w.packs) && b[1].text.includes(w.unknown), `${at}: unknown row "${b[1].text}"`);
|
||||
assert.ok(!/\b0%|100%/.test(b[1].text), `${at}: unknown packs read as a share "${b[1].text}"`);
|
||||
assert.equal(c.length, 1, `${at}: no packs, the month alone`);
|
||||
for (const q of [...a, ...b, ...c]) assert.ok(q.inCard, `${at}: "${q.text}" is past its card`);
|
||||
assert.equal(got.pageScroll, false, `${at}: the page scrolls sideways`);
|
||||
await page.close();
|
||||
}
|
||||
}
|
||||
} finally { await browser.close(); }
|
||||
});
|
||||
}
|
||||
@@ -20,6 +20,19 @@ package provider
|
||||
// fields as qnnp-me/dsh-qianfan-token-plan reads). An item Released, or
|
||||
// past its expiresAt, is no plan. The item's apiKey is never kept.
|
||||
//
|
||||
// The credit packs beside the plan (积分包, yuushabu_buyinn on X: Baidu's
|
||||
// gift packs went uncounted) are the console's
|
||||
//
|
||||
// GET console.bce.baidu.com/api/qianfan/charge/tokenPlanPersonal/pack/list
|
||||
//
|
||||
// {"success":true,"result":{"items":[{"packId","name","packType":"gift",
|
||||
// "status":"active","totalCredits","usedCredits","remainingCredits",
|
||||
// "purchasedAt","expiresAt","isUsable","consumeOrder"},…]}}
|
||||
//
|
||||
// as its Token Plan page reads them (the resource micro-app's bundle,
|
||||
// mb-static/resource/assets: the page's pack-list hook and its
|
||||
// 赠送积分包余量 and 积分包余量 rows); see readQianfanPacks.
|
||||
//
|
||||
// As StepFun's sign-in (stepfun_plan.go), the user brings the session from
|
||||
// their own browser: a bookmarklet run on the signed-in console copies its
|
||||
// cookies, or the Cookie header of the console's request is pasted from
|
||||
@@ -65,7 +78,10 @@ var qianfanConsole = "https://console.bce.baidu.com"
|
||||
|
||||
const (
|
||||
qianfanResourcePath = "/api/qianfan/charge/tokenPlanPersonal/resource"
|
||||
qianfanPlanHost = "qianfan.baidubce.com"
|
||||
// qianfanPackPath lists the account's credit packs (积分包): those
|
||||
// Baidu gives (赠送) and those bought (增购积分)
|
||||
qianfanPackPath = "/api/qianfan/charge/tokenPlanPersonal/pack/list"
|
||||
qianfanPlanHost = "qianfan.baidubce.com"
|
||||
// qianfanPaste starts what the bookmarklet copies, the JSON of a session
|
||||
qianfanPaste = "magpie-qianfan:"
|
||||
// qianfanUA is a browser's: the console is a page's API
|
||||
@@ -349,7 +365,13 @@ func qianfanClient() *http.Client {
|
||||
// as the session, and reads its result and the cookies a reply that read it
|
||||
// set.
|
||||
func qianfanResource(ctx context.Context, cookie string) (json.RawMessage, []*http.Cookie, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, qianfanConsole+qianfanResourcePath, nil)
|
||||
return qianfanAsk(ctx, cookie, qianfanResourcePath)
|
||||
}
|
||||
|
||||
// qianfanAsk asks the console's path as its page does, with the session,
|
||||
// and reads the result of a reply that succeeded and the cookies it set.
|
||||
func qianfanAsk(ctx context.Context, cookie, path string) (json.RawMessage, []*http.Cookie, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, qianfanConsole+path, nil)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
@@ -459,7 +481,7 @@ func readQianfanPlan(raw []byte, now time.Time) (plan string, until *time.Time,
|
||||
live = append(live, held{it, end})
|
||||
}
|
||||
if len(live) == 0 {
|
||||
return "", nil, "", w, errors.New("this Baidu Cloud account has no Token Plan Personal")
|
||||
return "", nil, "", w, errQianfanNoPlan
|
||||
}
|
||||
slices.SortStableFunc(live, func(a, b held) int {
|
||||
ra, rb := strings.EqualFold(a.it.Status, "Running"), strings.EqualFold(b.it.Status, "Running")
|
||||
@@ -508,6 +530,135 @@ func readQianfanPlan(raw []byte, now time.Time) (plan string, until *time.Time,
|
||||
return plan, until, renew, w, nil
|
||||
}
|
||||
|
||||
// errQianfanNoPlan is an account the console lists no running plan for.
|
||||
var errQianfanNoPlan = errors.New("this Baidu Cloud account has no Token Plan Personal")
|
||||
|
||||
// qianfanPack is one credit pack the console lists (pack/list's items), as
|
||||
// its page reads them (the bundle's Token Plan Personal page: packType
|
||||
// "gift" is Baidu's gift, 赠送积分包, counted only with an expiresAt still
|
||||
// ahead; status "active" packs that are neither gift nor guoqing_lite or
|
||||
// guoqing_pro are the ones bought, 积分包; isUsable says the credits can
|
||||
// be spent now).
|
||||
type qianfanPack struct {
|
||||
PackType string `json:"packType"`
|
||||
Status string `json:"status"`
|
||||
Total any `json:"totalCredits"`
|
||||
Used any `json:"usedCredits"`
|
||||
Remaining any `json:"remainingCredits"`
|
||||
ExpiresAt any `json:"expiresAt"`
|
||||
IsUsable any `json:"isUsable"`
|
||||
}
|
||||
|
||||
// readQianfanPacks is the console's pack/list result as the card's rows
|
||||
// beside the plan's month: "Gift credits", Baidu's gift packs still live,
|
||||
// and "Credit packs", the active ones bought, each the packs' credits
|
||||
// summed, as the console's page sums them, and when the soonest of what is
|
||||
// left in them runs out. A kind the account has none of has no row. spare
|
||||
// is whether any pack can be spent now with credits left: Baidu spends
|
||||
// them once the plan's are used up (套餐额度 → 赠送积分包 → 常规积分包), so
|
||||
// the month used up doesn't stop the account. A reply magpie can't read,
|
||||
// or a pack whose amounts it doesn't tell, is an error: unknown, never
|
||||
// none. aside sets the gift packs aside from routing, as when the account
|
||||
// has a plan, whose month is its allowance.
|
||||
func readQianfanPacks(raw []byte, now time.Time, aside bool) (ws []QuotaWindow, spare bool, err error) {
|
||||
var r struct {
|
||||
Items []qianfanPack `json:"items"`
|
||||
}
|
||||
if json.Unmarshal(raw, &r) != nil {
|
||||
return nil, false, fmt.Errorf("Baidu's console answered credit packs magpie can't read: %s", volcHead(raw))
|
||||
}
|
||||
type sum struct {
|
||||
total, left float64
|
||||
out time.Time // the soonest end of a pack with credits left
|
||||
outLeft float64
|
||||
any bool
|
||||
}
|
||||
var gift, bought sum
|
||||
for _, p := range r.Items {
|
||||
kind := strings.ToLower(p.PackType)
|
||||
end, hasEnd := qianfanTime(p.ExpiresAt)
|
||||
var s *sum
|
||||
switch {
|
||||
case kind == "gift":
|
||||
if !hasEnd || !end.After(now) {
|
||||
continue
|
||||
}
|
||||
s = &gift
|
||||
case kind == "guoqing_lite" || kind == "guoqing_pro" || !strings.EqualFold(p.Status, "active"):
|
||||
continue
|
||||
default:
|
||||
if hasEnd && !end.After(now) {
|
||||
continue
|
||||
}
|
||||
s = &bought
|
||||
}
|
||||
total, ok := number(p.Total)
|
||||
if !ok || total < 0 {
|
||||
return nil, false, errors.New("Baidu's console told no amount for a credit pack")
|
||||
}
|
||||
left, ok := number(p.Remaining)
|
||||
if !ok {
|
||||
used, uok := number(p.Used)
|
||||
if !uok {
|
||||
return nil, false, errors.New("Baidu's console told no amount for a credit pack")
|
||||
}
|
||||
left = total - used
|
||||
}
|
||||
left = max(0, left)
|
||||
s.any = true
|
||||
s.total += total
|
||||
s.left += left
|
||||
if left > 0 && hasEnd {
|
||||
switch {
|
||||
case s.out.IsZero() || end.Before(s.out):
|
||||
s.out, s.outLeft = end, left
|
||||
case end.Equal(s.out):
|
||||
s.outLeft += left
|
||||
}
|
||||
}
|
||||
if left > 0 && qianfanTrue(p.IsUsable) {
|
||||
spare = true
|
||||
}
|
||||
}
|
||||
// bought packs are spent only under a plan (积分包需订购套餐才可抵扣), so
|
||||
// they never hold the account; the gift packs are its allowance when
|
||||
// it has no plan (not aside)
|
||||
for _, k := range []struct {
|
||||
name string
|
||||
s sum
|
||||
aside bool
|
||||
}{{"Gift credits", gift, aside}, {"Credit packs", bought, true}} {
|
||||
if !k.s.any {
|
||||
continue
|
||||
}
|
||||
w := QuotaWindow{Name: k.name, Unit: "credits", Amount: k.s.total - k.s.left, Limit: k.s.total, Aside: k.aside}
|
||||
if k.s.total > 0 {
|
||||
w.Used = max(0, min(100, w.Amount/k.s.total*100))
|
||||
} else {
|
||||
w.Used = 100
|
||||
}
|
||||
if !k.s.out.IsZero() {
|
||||
out := k.s.out
|
||||
w.RunsOutAt, w.RunsOut = &out, k.s.outLeft
|
||||
}
|
||||
ws = append(ws, w)
|
||||
}
|
||||
return ws, spare, nil
|
||||
}
|
||||
|
||||
// qianfanTrue reads the console's flag: true, or "true" or 1.
|
||||
func qianfanTrue(v any) bool {
|
||||
switch x := v.(type) {
|
||||
case bool:
|
||||
return x
|
||||
case string:
|
||||
return strings.EqualFold(x, "true") || x == "1"
|
||||
case float64:
|
||||
return x == 1
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// qianfanNow is the clock readQianfanPlan is read at, a var for tests.
|
||||
var qianfanNow = time.Now
|
||||
|
||||
@@ -530,16 +681,50 @@ func qianfanPlanQuota(ctx context.Context, p Provider) SubscriptionQuota {
|
||||
q.Error = err.Error()
|
||||
return q
|
||||
}
|
||||
plan, until, renew, w, err := readQianfanPlan(raw, qianfanNow())
|
||||
if err != nil {
|
||||
now := qianfanNow()
|
||||
plan, until, renew, w, err := readQianfanPlan(raw, now)
|
||||
if err != nil && !errors.Is(err, errQianfanNoPlan) {
|
||||
q.Error = err.Error()
|
||||
return q
|
||||
}
|
||||
noPlan := err != nil
|
||||
// the credit packs beside the plan, with the session as the plan's
|
||||
// read left it
|
||||
packs, spare, perr := qianfanPacks(ctx, mergeQianfanCookies(s.Cookie, set), now, !noPlan)
|
||||
if noPlan {
|
||||
// with no plan, Baidu spends the gift packs straight away; an
|
||||
// account with none of them, or none read, has nothing to show
|
||||
if perr != nil || len(packs) == 0 {
|
||||
q.Error = errQianfanNoPlan.Error()
|
||||
return q
|
||||
}
|
||||
q.Windows = append(q.Windows, packs...)
|
||||
return q
|
||||
}
|
||||
q.Plan, q.Until, q.Renew = plan, until, renew
|
||||
// Baidu goes on to the packs once the month is used up
|
||||
w.Credits = spare
|
||||
q.Windows = append(q.Windows, w)
|
||||
if perr != nil {
|
||||
// not read is unknown, never no packs
|
||||
q.Windows = append(q.Windows, QuotaWindow{Name: "Credit packs", Text: true, Aside: true, Display: "Unknown"})
|
||||
return q
|
||||
}
|
||||
q.Windows = append(q.Windows, packs...)
|
||||
return q
|
||||
}
|
||||
|
||||
// qianfanPacks reads the account's credit packs as the card's rows
|
||||
// (readQianfanPacks), set aside from routing when the plan is the
|
||||
// account's allowance.
|
||||
func qianfanPacks(ctx context.Context, cookie string, now time.Time, aside bool) ([]QuotaWindow, bool, error) {
|
||||
raw, _, err := qianfanAsk(ctx, cookie, qianfanPackPath)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return readQianfanPacks(raw, now, aside)
|
||||
}
|
||||
|
||||
// qianfanPlanQuotas is a card for each Token Plan Personal provider in use
|
||||
// that magpie has a sign-in for: one per provider, as two can be two
|
||||
// accounts.
|
||||
|
||||
@@ -22,6 +22,25 @@ const qianfanResourceBody = `{"success":true,"status":200,"result":{"items":[` +
|
||||
`{"resourceId":"tp-old","planType":"lite","resourceStatus":"Released","billingMode":"credit","usedCredits":"6600","totalCredits":"6600","expiresAt":"2026-10-01T00:00:00Z","autoRenew":false,"apiKey":"bce-v3/ALTAK-old/secret-old"},` +
|
||||
`{"resourceId":"tp-1","planType":"pro","resourceStatus":"Running","billingMode":"credit","usedCredits":"11250.5","totalCredits":45000,"usedTokens":0,"totalTokens":0,"expiresAt":"2026-12-01T00:00:00Z","autoRenew":true,"renewTimeUnit":"month","renewTime":1,"apiKey":"bce-v3/ALTAK-live/secret-live"}]}}`
|
||||
|
||||
// qianfanPackBody is the console's tokenPlanPersonal/pack/list reply,
|
||||
// built from the fields its Token Plan page reads (the resource
|
||||
// micro-app's bundle: packId, name, packType, status, totalCredits,
|
||||
// usedCredits, remainingCredits, purchasedAt, expiresAt, isUsable,
|
||||
// consumeOrder), not a captured reply: no one here has a Baidu account.
|
||||
// Two live gift packs (one in use, one ending later), a gift pack past
|
||||
// its end and one with no end (the page counts neither), a bought pack
|
||||
// active (the bundle names no packType for these: any but gift and
|
||||
// guoqing_*), one bought pack expired, and a guoqing pack the page
|
||||
// leaves out of both rows.
|
||||
const qianfanPackBody = `{"success":true,"status":200,"result":{"items":[` +
|
||||
`{"packId":"pk-g1","name":"平台赠送积分","packType":"gift","status":"active","totalCredits":5000,"usedCredits":1200,"remainingCredits":3800,"purchasedAt":"2026-11-01 10:00:00","expiresAt":"2026-12-01 10:00:00","isUsable":true,"consumeOrder":1},` +
|
||||
`{"packId":"pk-g2","name":"邀请奖励","packType":"gift","status":"active","totalCredits":"2000","usedCredits":"0","remainingCredits":"2000","purchasedAt":"2026-11-10 00:00:00","expiresAt":"2026-12-15 00:00:00","isUsable":true,"consumeOrder":2},` +
|
||||
`{"packId":"pk-g0","name":"平台赠送积分","packType":"gift","status":"expired","totalCredits":1000,"usedCredits":0,"remainingCredits":1000,"purchasedAt":"2026-10-01 00:00:00","expiresAt":"2026-11-01 00:00:00","isUsable":false,"consumeOrder":0},` +
|
||||
`{"packId":"pk-gx","packType":"gift","status":"active","totalCredits":900,"usedCredits":0,"remainingCredits":900,"isUsable":true,"consumeOrder":3},` +
|
||||
`{"packId":"pk-b1","name":"积分包","packType":"normal","status":"active","totalCredits":10000,"usedCredits":2500,"remainingCredits":7500,"purchasedAt":"2026-11-05 00:00:00","expiresAt":"2027-11-05 00:00:00","isUsable":true,"consumeOrder":4},` +
|
||||
`{"packId":"pk-b0","name":"积分包","packType":"normal","status":"expired","totalCredits":3000,"usedCredits":3000,"remainingCredits":0,"purchasedAt":"2025-11-05 00:00:00","expiresAt":"2026-11-05 00:00:00","isUsable":false,"consumeOrder":0},` +
|
||||
`{"packId":"pk-q1","name":"国庆积分包","packType":"guoqing_pro","status":"active","totalCredits":8000,"usedCredits":0,"remainingCredits":8000,"purchasedAt":"2026-10-01 00:00:00","expiresAt":"2026-12-31 00:00:00","isUsable":true,"consumeOrder":5}]}}`
|
||||
|
||||
// fakeQianfanConsole is Baidu Cloud's console: it answers the plan's
|
||||
// resource to its one session's cookies, asked as the page asks, and sends
|
||||
// anything else to the sign-in page, as the real console does.
|
||||
@@ -29,6 +48,7 @@ type fakeQianfanConsole struct {
|
||||
srv *httptest.Server
|
||||
cookie atomic.Value // the Cookie header it takes now
|
||||
body atomic.Value
|
||||
packs atomic.Value // pack/list's reply
|
||||
asked atomic.Int32
|
||||
// renew, when set, is a session the console renews to as it answers:
|
||||
// a reply sets its bce-session, and the old one is taken no longer
|
||||
@@ -40,9 +60,10 @@ func newFakeQianfanConsole(t *testing.T) *fakeQianfanConsole {
|
||||
f := &fakeQianfanConsole{}
|
||||
f.cookie.Store("BDUSS=bd-1; bce-session=s-1; bce-user-info=u-1")
|
||||
f.body.Store(qianfanResourceBody)
|
||||
f.packs.Store(qianfanPackBody)
|
||||
f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
f.asked.Add(1)
|
||||
if r.Method != http.MethodGet || r.URL.Path != qianfanResourcePath || r.Header.Get("X-Requested-With") != "XMLHttpRequest" {
|
||||
if r.Method != http.MethodGet || r.URL.Path != qianfanResourcePath && r.URL.Path != qianfanPackPath || r.Header.Get("X-Requested-With") != "XMLHttpRequest" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
@@ -57,6 +78,10 @@ func newFakeQianfanConsole(t *testing.T) *fakeQianfanConsole {
|
||||
f.renew.Store("")
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if r.URL.Path == qianfanPackPath {
|
||||
w.Write([]byte(f.packs.Load().(string)))
|
||||
return
|
||||
}
|
||||
w.Write([]byte(f.body.Load().(string)))
|
||||
}))
|
||||
t.Cleanup(f.srv.Close)
|
||||
@@ -200,14 +225,17 @@ func TestQianfanPlanCard(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
q := qianfanPlanQuota(ctx, p)
|
||||
if q.Error != "" || q.Plan != "Token Plan Pro" || q.Renew != "auto" || q.Until == nil || len(q.Windows) != 1 || q.Windows[0].Limit != 45000 {
|
||||
if q.Error != "" || q.Plan != "Token Plan Pro" || q.Renew != "auto" || q.Until == nil || len(q.Windows) != 3 || q.Windows[0].Limit != 45000 {
|
||||
t.Fatalf("card: %+v", q)
|
||||
}
|
||||
if q.Windows[1].Name != "Gift credits" || q.Windows[1].Limit != 7000 || q.Windows[2].Name != "Credit packs" || q.Windows[2].Limit != 10000 {
|
||||
t.Fatalf("packs: %+v", q.Windows)
|
||||
}
|
||||
if b, _ := json.Marshal(q); strings.Contains(string(b), "bce-v3") || strings.Contains(string(b), "secret") {
|
||||
t.Fatalf("the plan's key reached the card: %s", b)
|
||||
}
|
||||
kr, err := accountPlanWindows(ctx, p)
|
||||
if err != nil || len(kr.ws) != 1 || kr.plan != "Token Plan Pro" {
|
||||
if err != nil || len(kr.ws) != 3 || kr.plan != "Token Plan Pro" {
|
||||
t.Fatalf("routing's reading: %+v %v", kr, err)
|
||||
}
|
||||
|
||||
@@ -309,3 +337,125 @@ func TestMergeQianfanCookies(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The credit packs beside the month, as the console's page sums them
|
||||
// (yuushabu_buyinn on X: 赠送积分包 went uncounted): Baidu's gift packs
|
||||
// still live in one row, the bought ones active in another, each with
|
||||
// when the soonest of what is left runs out. Expired packs, a gift with
|
||||
// no end and guoqing packs are left out, as the page leaves them.
|
||||
func TestReadQianfanPacks(t *testing.T) {
|
||||
now := time.Date(2026, 11, 16, 12, 0, 0, 0, time.UTC)
|
||||
var r struct{ Result json.RawMessage }
|
||||
if err := json.Unmarshal([]byte(qianfanPackBody), &r); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ws, spare, err := readQianfanPacks(r.Result, now, true)
|
||||
if err != nil || !spare || len(ws) != 2 {
|
||||
t.Fatalf("%+v %v %v", ws, spare, err)
|
||||
}
|
||||
g, b := ws[0], ws[1]
|
||||
cst := time.FixedZone("CST", 8*3600)
|
||||
if g.Name != "Gift credits" || g.Unit != "credits" || g.Limit != 7000 || g.Amount != 1200 || g.Used < 17.1 || g.Used > 17.2 || !g.Aside ||
|
||||
g.RunsOutAt == nil || !g.RunsOutAt.Equal(time.Date(2026, 12, 1, 10, 0, 0, 0, cst)) || g.RunsOut != 3800 || g.ResetsAt != nil {
|
||||
t.Fatalf("gift: %+v", g)
|
||||
}
|
||||
if b.Name != "Credit packs" || b.Limit != 10000 || b.Amount != 2500 || b.Used != 25 || !b.Aside ||
|
||||
b.RunsOutAt == nil || !b.RunsOutAt.Equal(time.Date(2027, 11, 5, 0, 0, 0, 0, cst)) || b.RunsOut != 7500 {
|
||||
t.Fatalf("bought: %+v", b)
|
||||
}
|
||||
|
||||
// with no plan the gift packs are the account's allowance; bought
|
||||
// ones are spent only under a plan
|
||||
ws, _, _ = readQianfanPacks(r.Result, now, false)
|
||||
if ws[0].Aside || !ws[1].Aside {
|
||||
t.Fatalf("no plan: %+v", ws)
|
||||
}
|
||||
|
||||
// two packs ending together run out together; a pack used up says
|
||||
// nothing runs out; remainingCredits missing is total less used
|
||||
ws, spare, err = readQianfanPacks([]byte(`{"items":[`+
|
||||
`{"packType":"gift","totalCredits":100,"usedCredits":100,"remainingCredits":0,"expiresAt":"2026-11-20 00:00:00","isUsable":true},`+
|
||||
`{"packType":"gift","totalCredits":100,"usedCredits":40,"expiresAt":"2026-11-25 00:00:00","isUsable":true},`+
|
||||
`{"packType":"gift","totalCredits":100,"usedCredits":0,"remainingCredits":100,"expiresAt":"2026-11-25 00:00:00","isUsable":true}]}`), now, true)
|
||||
if err != nil || len(ws) != 1 || ws[0].Amount != 140 || ws[0].Limit != 300 || ws[0].RunsOut != 160 || !spare {
|
||||
t.Fatalf("together: %+v %v %v", ws, spare, err)
|
||||
}
|
||||
|
||||
// none: no rows, and nothing to spend past the month
|
||||
for name, body := range map[string]string{
|
||||
"no packs": `{"items":[]}`,
|
||||
"no items": `{}`,
|
||||
"all expired": `{"items":[{"packType":"gift","totalCredits":100,"remainingCredits":100,"expiresAt":"2026-11-01 00:00:00","isUsable":false}]}`,
|
||||
} {
|
||||
if ws, spare, err := readQianfanPacks([]byte(body), now, true); err != nil || len(ws) != 0 || spare {
|
||||
t.Errorf("%s: %+v %v %v", name, ws, spare, err)
|
||||
}
|
||||
}
|
||||
// packs left that can't be spent now hold nothing past the month
|
||||
if _, spare, err := readQianfanPacks([]byte(`{"items":[{"packType":"normal","status":"active","totalCredits":100,"remainingCredits":100,"isUsable":false}]}`), now, true); err != nil || spare {
|
||||
t.Fatalf("unusable: %v %v", spare, err)
|
||||
}
|
||||
// unknown, never none
|
||||
for name, body := range map[string]string{
|
||||
"not JSON": `<html>`,
|
||||
"no amounts": `{"items":[{"packType":"gift","expiresAt":"2026-12-01 00:00:00"}]}`,
|
||||
"no left": `{"items":[{"packType":"gift","totalCredits":100,"expiresAt":"2026-12-01 00:00:00"}]}`,
|
||||
"no total": `{"items":[{"packType":"gift","remainingCredits":50,"expiresAt":"2026-12-01 00:00:00"}]}`,
|
||||
} {
|
||||
if ws, _, err := readQianfanPacks([]byte(body), now, true); err == nil || len(ws) != 0 {
|
||||
t.Errorf("%s: %+v, want an error", name, ws)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The card's pack rows: the month goes on to credits while a pack holds
|
||||
// some (Baidu spends them once the month is used up); packs not read are
|
||||
// an Unknown row, never none, and the month then holds the account as
|
||||
// before; an account with none has the month alone; one with no plan but
|
||||
// gift packs shows them.
|
||||
func TestQianfanPlanCardPacks(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
forgetPlanQuotas()
|
||||
f := newFakeQianfanConsole(t)
|
||||
ctx := context.Background()
|
||||
p := Provider{ID: "baidu-qianfan", Name: "Baidu Qianfan", Key: "bce-v3/k", Chat: "https://qianfan.baidubce.com/v2/tokenplan/personal"}
|
||||
if err := SaveQianfanPaste(ctx, p.ID, f.cookie.Load().(string)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
q := qianfanPlanQuota(ctx, p)
|
||||
if q.Error != "" || len(q.Windows) != 3 || !q.Windows[0].Credits || !q.Windows[1].Aside || !q.Windows[2].Aside {
|
||||
t.Fatalf("card: %+v", q)
|
||||
}
|
||||
|
||||
for name, body := range map[string]string{
|
||||
"refused": `{"success":false,"message":{"global":"系统繁忙"}}`,
|
||||
"not JSON": `<!doctype html><html>`,
|
||||
"unread": `{"success":true,"result":{"items":[{"packType":"gift","expiresAt":"2026-12-01 00:00:00"}]}}`,
|
||||
} {
|
||||
f.packs.Store(body)
|
||||
q = qianfanPlanQuota(ctx, p)
|
||||
if q.Error != "" || len(q.Windows) != 2 || q.Windows[0].Credits || q.Windows[0].Name != "Month" ||
|
||||
q.Windows[1].Name != "Credit packs" || !q.Windows[1].Text || q.Windows[1].Display != "Unknown" || !q.Windows[1].Aside {
|
||||
t.Fatalf("%s: %+v", name, q)
|
||||
}
|
||||
}
|
||||
|
||||
f.packs.Store(`{"success":true,"result":{"items":[]}}`)
|
||||
if q = qianfanPlanQuota(ctx, p); q.Error != "" || len(q.Windows) != 1 || q.Windows[0].Credits {
|
||||
t.Fatalf("no packs: %+v", q)
|
||||
}
|
||||
|
||||
// no plan, and gift packs: Baidu spends those straight away
|
||||
f.body.Store(`{"success":true,"result":{"items":[]}}`)
|
||||
f.packs.Store(qianfanPackBody)
|
||||
if q = qianfanPlanQuota(ctx, p); q.Error != "" || len(q.Windows) != 2 || q.Windows[0].Name != "Gift credits" || q.Windows[0].Aside {
|
||||
t.Fatalf("no plan, gift packs: %+v", q)
|
||||
}
|
||||
// no plan, and no packs or none read: no plan
|
||||
for _, body := range []string{`{"success":true,"result":{"items":[]}}`, `{"success":false}`} {
|
||||
f.packs.Store(body)
|
||||
if q = qianfanPlanQuota(ctx, p); q.Error != errQianfanNoPlan.Error() || len(q.Windows) != 0 {
|
||||
t.Fatalf("no plan %s: %+v", body, q)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user