koishi-plugin-prism 0.1.40 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +44 -18
- package/lib/display-time.d.ts +10 -0
- package/lib/display-time.js +36 -0
- package/lib/index.d.ts +89 -5
- package/lib/index.js +488 -290
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -3,20 +3,21 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.PrismBotClientError = exports.Config = exports.version = exports.name = void 0;
|
|
6
|
+
exports.PrismSocket = exports.PrismBotClientError = exports.Config = exports.version = exports.name = void 0;
|
|
7
7
|
exports.apply = apply;
|
|
8
8
|
exports.applyPrismKoishiPlugin = applyPrismKoishiPlugin;
|
|
9
|
+
exports.platformSocketUrl = platformSocketUrl;
|
|
9
10
|
exports.humanReadableBotError = humanReadableBotError;
|
|
10
11
|
exports.resolveMahjongTableConfigs = resolveMahjongTableConfigs;
|
|
12
|
+
const display_time_js_1 = require("./display-time.js");
|
|
11
13
|
const koishi_1 = require("koishi");
|
|
12
14
|
const package_json_1 = __importDefault(require("../package.json"));
|
|
13
15
|
exports.name = "prism";
|
|
14
16
|
exports.version = package_json_1.default.version;
|
|
15
17
|
exports.Config = koishi_1.Schema.object({
|
|
16
|
-
provider: koishi_1.Schema.string().required().description("平台提供商 (如 qq)"),
|
|
17
18
|
autoRegister: koishi_1.Schema.boolean().default(true).description("是否自动注册"),
|
|
18
|
-
shopCode: koishi_1.Schema.string().description("
|
|
19
|
-
baseUrl: koishi_1.Schema.string().description("PRiSM
|
|
19
|
+
shopCode: koishi_1.Schema.string().required().description("统一平台店铺编号"),
|
|
20
|
+
baseUrl: koishi_1.Schema.string().required().description("PRiSM 后端地址,例如 https://link.neri.moe"),
|
|
20
21
|
integrationToken: koishi_1.Schema.string().role("secret").description("集成 API Token"),
|
|
21
22
|
currencyName: koishi_1.Schema.string().default("猫粮").description("代币名称"),
|
|
22
23
|
defaultDoorDeviceId: koishi_1.Schema.string().default("front-door").description("默认开门设备名或别名"),
|
|
@@ -24,10 +25,16 @@ exports.Config = koishi_1.Schema.object({
|
|
|
24
25
|
loginPricingConfigIds: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("默认入场绑定的计费策略ID"),
|
|
25
26
|
loginSessionLabel: koishi_1.Schema.string().default("音游区间").description("默认入场场次标签 (防重复入场)"),
|
|
26
27
|
enableStaffCommands: koishi_1.Schema.boolean().default(false).description("是否启用管理员指令"),
|
|
27
|
-
staffUserIds: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("
|
|
28
|
+
staffUserIds: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("允许执行管理员指令的平台身份列表(如 onebot:123456、telegram:123456)"),
|
|
28
29
|
powerCommandsAdminOnly: koishi_1.Schema.boolean().default(false).description("关机是否仅允许管理员使用;开机始终仅已入场玩家可用"),
|
|
29
|
-
|
|
30
|
-
|
|
30
|
+
playerCommands: koishi_1.Schema.union([
|
|
31
|
+
koishi_1.Schema.const("all").description("全部:玩家可以在 Bot 里入场、结账、上下桌和操作设备"),
|
|
32
|
+
koishi_1.Schema.const("readonly").description("只读:玩家只能绑定身份、查询和兑换;入场、结账、上下桌和设备操作仅管理员可用"),
|
|
33
|
+
]).default("all").description("玩家可用的命令"),
|
|
34
|
+
readOnlyNotice: koishi_1.Schema.string().default("请扫描设备上的二维码或碰 NFC,在网页或 App Clip 里操作").description("只读模式下玩家使用受限命令时的回复"),
|
|
35
|
+
logoutNotifyUserIds: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("结账账单私聊通知的平台身份列表(如 onebot:123456)"),
|
|
36
|
+
idleNotifyChannelIds: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("闲置自动关机的提醒发到哪里:群写 onebot:群号,私聊写 onebot:private:QQ号"),
|
|
37
|
+
idleReminderMinutes: koishi_1.Schema.number().min(0).max(120).default(5).description("自动关机前几分钟提醒(0 为不提醒)"),
|
|
31
38
|
mahjongTableConfigs: koishi_1.Schema.array(koishi_1.Schema.object({
|
|
32
39
|
displayName: koishi_1.Schema.string().required().description("桌位显示名称和 session 标签"),
|
|
33
40
|
aliases: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("命令别名(至少一个),例如 a、四麻A"),
|
|
@@ -53,14 +60,15 @@ class PrismBotClientError extends Error {
|
|
|
53
60
|
}
|
|
54
61
|
}
|
|
55
62
|
exports.PrismBotClientError = PrismBotClientError;
|
|
56
|
-
const LOCAL_TZ_OFFSET_MINUTES = 8 * 60;
|
|
57
63
|
const USAGE = {
|
|
58
64
|
mahjong_join: "/上桌 <桌号>",
|
|
59
65
|
mahjong_leave: "/下桌",
|
|
60
66
|
mahjong_list: "/麻将列表",
|
|
61
67
|
api_benchmark: "/api测速 [次数]",
|
|
68
|
+
ws_benchmark: "/ws测速 [次数]",
|
|
62
69
|
prism_on: "/prism on <设备名|别名|all>",
|
|
63
70
|
prism_off: "/prism off <设备名|别名|all>",
|
|
71
|
+
prism_keep: "/keep <设备名或别名>",
|
|
64
72
|
prism_coin: "/prism coin <设备名或别名> [数量]",
|
|
65
73
|
prism_scan: "/prism scan <设备名或别名>",
|
|
66
74
|
prism_redeem: "/prism redeem <兑换码>",
|
|
@@ -79,109 +87,275 @@ function applyPrismKoishiPlugin(ctx, config) {
|
|
|
79
87
|
return context.session?.messageId ? `${(0, koishi_1.h)("quote", { id: context.session.messageId })}${message}` : message;
|
|
80
88
|
}
|
|
81
89
|
};
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
ctx.command("
|
|
97
|
-
ctx.command("
|
|
98
|
-
ctx.command("
|
|
99
|
-
ctx.command("mahjong <tableId>", "加入指定麻将桌").action(wrap(async (context, tableId) => service.mahjongJoin(await service.sender(context), tableId)));
|
|
100
|
-
ctx.command("上桌 [tableId]", "加入指定麻将桌").action(wrap(async (context, tableId) => service.mahjongJoin(await service.sender(context), tableId)));
|
|
101
|
-
ctx.command("下桌", "离开当前所在麻将桌").action(wrap(async (context) => service.mahjongLeave(await service.sender(context))));
|
|
90
|
+
const bind = wrap(async (context, code) => service.bind(await service.sender(context), code));
|
|
91
|
+
ctx.command("bind <code:string>", "绑定网页登录账号到当前平台身份").action(bind);
|
|
92
|
+
// Instructions already handed to players may still say prism.bind.
|
|
93
|
+
ctx.command("prism.bind <code:string>", "绑定网页登录账号到当前平台身份(旧命令,同 bind)").action(bind);
|
|
94
|
+
// In read-only mode a player may look things up and redeem, but anything that
|
|
95
|
+
// starts billing, settles a bill or drives a device is left to staff.
|
|
96
|
+
const effect = (handler) => wrap(async (context, ...args) => {
|
|
97
|
+
if (config.playerCommands === "readonly" && !matchesPlatformIdentity(config.staffUserIds ?? [], await service.sender(context))) {
|
|
98
|
+
return config.readOnlyNotice || "请扫描设备上的二维码或碰 NFC,在网页或 App Clip 里操作";
|
|
99
|
+
}
|
|
100
|
+
return handler(context, ...args);
|
|
101
|
+
});
|
|
102
|
+
ctx.command("login [target:user]", "开启玩家计费场次").action(effect(async (context, target) => service.loginForTarget(await service.sender(context), target, context.session?.bot)));
|
|
103
|
+
ctx.command("入场 [target:user]", "入场").action(effect(async (context, target) => service.loginForTarget(await service.sender(context), target, context.session?.bot)));
|
|
104
|
+
ctx.command("mahjong <tableId>", "加入指定麻将桌").action(effect(async (context, tableId) => service.mahjongJoin(await service.sender(context), tableId)));
|
|
105
|
+
ctx.command("上桌 [tableId]", "加入指定麻将桌").action(effect(async (context, tableId) => service.mahjongJoin(await service.sender(context), tableId)));
|
|
106
|
+
ctx.command("下桌", "离开当前所在麻将桌").action(effect(async (context) => service.mahjongLeave(await service.sender(context))));
|
|
102
107
|
ctx.command("麻将列表", "查看麻将机状态与别名").action(wrap(async () => service.listMahjongTables()));
|
|
103
|
-
ctx.command("logout [target:user]", "结算玩家计费场次").action(
|
|
108
|
+
ctx.command("logout [target:user]", "结算玩家计费场次").action(effect(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.logout(sender, context.session?.bot), context.session?.bot)));
|
|
104
109
|
ctx.command("billing [target:user]", "预览玩家结账费用").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.billing(sender), context.session?.bot)));
|
|
105
110
|
ctx.command("wallet [target:user]", "查看玩家钱包").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.wallet(sender), context.session?.bot)));
|
|
106
|
-
ctx.command("api测速 [count:number]", "测试 Bot 到 PRiSM
|
|
111
|
+
ctx.command("api测速 [count:number]", "测试 Bot 走 HTTP 到 PRiSM 的延迟").action(wrap(async (context, count) => service.benchmarkApi(await service.sender(context), count)));
|
|
112
|
+
ctx.command("ws测速 [count:number]", "测试 Bot 走 WebSocket 到 PRiSM 的延迟").action(wrap(async (context, count) => service.benchmarkWs(await service.sender(context), count)));
|
|
107
113
|
ctx.command("versions", "查看 Bot 与 PRiSM 后端版本").action(wrap(async () => service.versions()));
|
|
108
114
|
ctx.command("items [target:user]", "查看玩家资产").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.items(sender), context.session?.bot)));
|
|
109
115
|
ctx.command("list", "查看当前在线玩家列表").action(wrap(async (context) => service.listActiveSessions(await service.sender(context))));
|
|
110
116
|
ctx.command("show [deviceId]", "查看设备电源状态").action(wrap(async (context, deviceId) => service.listDeviceStates(deviceId)));
|
|
111
117
|
ctx.command("history [target:user]", "查看玩家历史").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.history(sender), context.session?.bot)));
|
|
112
|
-
ctx.command("lock", "向默认门锁设备发送开门指令").action(
|
|
113
|
-
ctx.command("on <deviceRef>", "请求启动指定设备电源").action(
|
|
114
|
-
ctx.command("off <deviceRef>", "请求关闭指定设备电源").action(
|
|
115
|
-
|
|
116
|
-
|
|
118
|
+
ctx.command("lock", "向默认门锁设备发送开门指令").action(effect(async (context) => service.lock(await service.sender(context))));
|
|
119
|
+
ctx.command("on <deviceRef>", "请求启动指定设备电源").action(effect(async (context, deviceRef) => service.powerOn(await service.sender(context), deviceRef)));
|
|
120
|
+
ctx.command("off <deviceRef>", "请求关闭指定设备电源").action(effect(async (context, deviceRef) => service.powerOff(await service.sender(context), deviceRef)));
|
|
121
|
+
// Not limited by read-only mode: it never switches anything on, and the
|
|
122
|
+
// platform only accepts it from an entered player for a device that is on.
|
|
123
|
+
ctx.command("keep <deviceRef>", "延迟闲置设备的自动关机").action(wrap(async (context, deviceRef) => service.keep(await service.sender(context), deviceRef)));
|
|
124
|
+
ctx.command("coin <deviceRef> [count]", "请求向指定设备投币").action(effect(async (context, deviceRef, count) => service.coin(await service.sender(context), deviceRef, count)));
|
|
125
|
+
ctx.command("scan <deviceRef>", "使用当前玩家绑定的 Aime 卡刷卡").action(effect(async (context, deviceRef) => service.scan(await service.sender(context), deviceRef)));
|
|
117
126
|
ctx.command("redeem <code>", "兑换 PRiSM 礼物码").action(wrap(async (context, code) => service.redeem(await service.sender(context), code)));
|
|
118
127
|
ctx.command("add <target:user> <amount:number>", "增加玩家余额").action(wrap(async (context, target, amount) => service.adjustTargetBalance(await service.sender(context), target, amount, 1, context.session?.bot)));
|
|
119
128
|
ctx.command("del <target:user> <amount:number>", "扣除玩家余额").action(wrap(async (context, target, amount) => service.adjustTargetBalance(await service.sender(context), target, amount, -1, context.session?.bot)));
|
|
120
129
|
ctx.command("overwrite <target:user> <amount:number> [reason:text]", "覆盖结账金额并立即结账").action(wrap(async (context, target, amount, reason) => service.overwriteTargetCheckout(await service.sender(context), target, amount, reason, context.session?.bot)));
|
|
121
|
-
|
|
122
|
-
if (intervalMs > 0 && typeof ctx.setInterval === "function") {
|
|
123
|
-
ctx.setInterval(() => {
|
|
124
|
-
service.autoPowerOffLoop().catch(() => {
|
|
125
|
-
/* swallow */
|
|
126
|
-
});
|
|
127
|
-
}, intervalMs);
|
|
128
|
-
}
|
|
130
|
+
ctx.on?.("dispose", () => service.dispose());
|
|
129
131
|
}
|
|
130
|
-
/*
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
132
|
+
/* --------------------------- platform connection --------------------------- */
|
|
133
|
+
const SOCKET_OPEN = 1;
|
|
134
|
+
const REQUEST_TIMEOUT_MS = 30_000;
|
|
135
|
+
const PING_MS = 30_000;
|
|
136
|
+
const FIRST_RETRY_MS = 1000;
|
|
137
|
+
const MAX_RETRY_MS = 30_000;
|
|
138
|
+
/**
|
|
139
|
+
* The one connection to PRiSM. Requests go out as frames and are matched to
|
|
140
|
+
* their replies by id; the platform also pushes events down it. While it is
|
|
141
|
+
* down a request fails at once: queueing a checkout or a top-up to run later
|
|
142
|
+
* would make players repeat it, and a resend could run it twice.
|
|
143
|
+
*/
|
|
144
|
+
class PrismSocket {
|
|
145
|
+
open;
|
|
146
|
+
url;
|
|
147
|
+
token;
|
|
148
|
+
hello;
|
|
149
|
+
onEvent;
|
|
150
|
+
logger;
|
|
151
|
+
socket = null;
|
|
152
|
+
pending = new Map();
|
|
153
|
+
retryMs = FIRST_RETRY_MS;
|
|
154
|
+
retryTimer = null;
|
|
155
|
+
pingTimer = null;
|
|
156
|
+
lastHeard = 0;
|
|
157
|
+
stopped = false;
|
|
158
|
+
sequence = 0;
|
|
159
|
+
pongWaiters = [];
|
|
160
|
+
constructor(open, url, token, hello, onEvent, logger) {
|
|
161
|
+
this.open = open;
|
|
162
|
+
this.url = url;
|
|
163
|
+
this.token = token;
|
|
164
|
+
this.hello = hello;
|
|
165
|
+
this.onEvent = onEvent;
|
|
166
|
+
this.logger = logger;
|
|
167
|
+
}
|
|
168
|
+
start() {
|
|
169
|
+
this.stopped = false;
|
|
170
|
+
this.connect();
|
|
171
|
+
}
|
|
172
|
+
stop() {
|
|
173
|
+
this.stopped = true;
|
|
174
|
+
if (this.retryTimer)
|
|
175
|
+
clearTimeout(this.retryTimer);
|
|
176
|
+
if (this.pingTimer)
|
|
177
|
+
clearInterval(this.pingTimer);
|
|
178
|
+
this.socket?.close(1000, "dispose");
|
|
179
|
+
this.socket = null;
|
|
180
|
+
this.failPending();
|
|
181
|
+
}
|
|
182
|
+
connect() {
|
|
183
|
+
let socket;
|
|
184
|
+
try {
|
|
185
|
+
socket = this.open(this.url, { Authorization: `Bearer ${this.token}` });
|
|
186
|
+
}
|
|
187
|
+
catch (error) {
|
|
188
|
+
this.logger?.warn("PRiSM connection failed", error);
|
|
189
|
+
this.reconnectLater();
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
this.socket = socket;
|
|
193
|
+
socket.addEventListener("open", () => {
|
|
194
|
+
this.retryMs = FIRST_RETRY_MS;
|
|
195
|
+
this.lastHeard = Date.now();
|
|
196
|
+
socket.send(JSON.stringify({ type: "hello", ...this.hello }));
|
|
197
|
+
if (this.pingTimer)
|
|
198
|
+
clearInterval(this.pingTimer);
|
|
199
|
+
this.pingTimer = setInterval(() => {
|
|
200
|
+
// Two missed pings: the connection is gone even if no close arrived.
|
|
201
|
+
if (Date.now() - this.lastHeard > PING_MS * 2)
|
|
202
|
+
socket.close(4000, "silent");
|
|
203
|
+
else if (socket.readyState === SOCKET_OPEN)
|
|
204
|
+
socket.send("ping");
|
|
205
|
+
}, PING_MS);
|
|
206
|
+
});
|
|
207
|
+
socket.addEventListener("message", (event) => this.receive(String(event?.data ?? "")));
|
|
208
|
+
socket.addEventListener("close", () => {
|
|
209
|
+
if (this.socket !== socket)
|
|
210
|
+
return;
|
|
211
|
+
this.socket = null;
|
|
212
|
+
if (this.pingTimer)
|
|
213
|
+
clearInterval(this.pingTimer);
|
|
214
|
+
this.failPending();
|
|
215
|
+
this.reconnectLater();
|
|
216
|
+
});
|
|
217
|
+
socket.addEventListener("error", (error) => this.logger?.warn("PRiSM connection error", error?.message ?? error));
|
|
142
218
|
}
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
219
|
+
reconnectLater() {
|
|
220
|
+
if (this.stopped)
|
|
221
|
+
return;
|
|
222
|
+
if (this.retryTimer)
|
|
223
|
+
clearTimeout(this.retryTimer);
|
|
224
|
+
this.retryTimer = setTimeout(() => this.connect(), this.retryMs);
|
|
225
|
+
this.retryMs = Math.min(this.retryMs * 2, MAX_RETRY_MS);
|
|
226
|
+
}
|
|
227
|
+
failPending() {
|
|
228
|
+
for (const [, waiter] of this.pending) {
|
|
229
|
+
clearTimeout(waiter.timer);
|
|
230
|
+
waiter.reject(unreachable());
|
|
149
231
|
}
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
if (
|
|
155
|
-
|
|
232
|
+
this.pending.clear();
|
|
233
|
+
}
|
|
234
|
+
receive(raw) {
|
|
235
|
+
this.lastHeard = Date.now();
|
|
236
|
+
if (raw === "pong") {
|
|
237
|
+
this.pongWaiters.shift()?.();
|
|
238
|
+
return;
|
|
156
239
|
}
|
|
240
|
+
let frame;
|
|
157
241
|
try {
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
242
|
+
frame = JSON.parse(raw);
|
|
243
|
+
}
|
|
244
|
+
catch {
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
if (frame?.type === "response" && typeof frame.id === "string") {
|
|
248
|
+
const waiter = this.pending.get(frame.id);
|
|
249
|
+
if (!waiter)
|
|
250
|
+
return;
|
|
251
|
+
this.pending.delete(frame.id);
|
|
252
|
+
clearTimeout(waiter.timer);
|
|
253
|
+
waiter.resolve({ status: Number(frame.status) || 500, body: frame.body, serverMs: typeof frame.serverMs === "number" ? frame.serverMs : null });
|
|
254
|
+
}
|
|
255
|
+
else if (frame?.type === "event" && typeof frame.event === "string") {
|
|
256
|
+
try {
|
|
257
|
+
this.onEvent({ event: frame.event, data: frame.data });
|
|
168
258
|
}
|
|
169
|
-
|
|
170
|
-
|
|
259
|
+
catch (error) {
|
|
260
|
+
this.logger?.warn("PRiSM event handling failed", error);
|
|
171
261
|
}
|
|
172
|
-
return response && typeof response === "object" && Object.hasOwn(response, "data") ? response.data : response;
|
|
173
262
|
}
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
263
|
+
}
|
|
264
|
+
/** One heartbeat round trip in milliseconds: the network to the platform and nothing else. */
|
|
265
|
+
ping() {
|
|
266
|
+
const socket = this.socket;
|
|
267
|
+
if (!socket || socket.readyState !== SOCKET_OPEN)
|
|
268
|
+
return Promise.reject(unreachable());
|
|
269
|
+
return new Promise((resolve, reject) => {
|
|
270
|
+
const startedAt = performance.now();
|
|
271
|
+
const timer = setTimeout(() => {
|
|
272
|
+
const index = this.pongWaiters.indexOf(answered);
|
|
273
|
+
if (index >= 0)
|
|
274
|
+
this.pongWaiters.splice(index, 1);
|
|
275
|
+
reject(new PrismBotClientError("服务器没有及时回应", "API_TIMEOUT", 0, {}));
|
|
276
|
+
}, REQUEST_TIMEOUT_MS);
|
|
277
|
+
const answered = () => {
|
|
278
|
+
clearTimeout(timer);
|
|
279
|
+
resolve(performance.now() - startedAt);
|
|
280
|
+
};
|
|
281
|
+
this.pongWaiters.push(answered);
|
|
282
|
+
socket.send("ping");
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
request(frame) {
|
|
286
|
+
const socket = this.socket;
|
|
287
|
+
if (!socket || socket.readyState !== SOCKET_OPEN)
|
|
288
|
+
return Promise.reject(unreachable());
|
|
289
|
+
const id = `${Date.now().toString(36)}-${(this.sequence++).toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
290
|
+
return new Promise((resolve, reject) => {
|
|
291
|
+
const timer = setTimeout(() => {
|
|
292
|
+
this.pending.delete(id);
|
|
293
|
+
reject(new PrismBotClientError("服务器没有及时回应,请稍后确认结果", "API_TIMEOUT", 0, {}));
|
|
294
|
+
}, REQUEST_TIMEOUT_MS);
|
|
295
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
296
|
+
try {
|
|
297
|
+
socket.send(JSON.stringify({ type: "request", id, ...frame }));
|
|
298
|
+
}
|
|
299
|
+
catch {
|
|
300
|
+
clearTimeout(timer);
|
|
301
|
+
this.pending.delete(id);
|
|
302
|
+
reject(unreachable());
|
|
182
303
|
}
|
|
183
|
-
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
exports.PrismSocket = PrismSocket;
|
|
308
|
+
function unreachable() {
|
|
309
|
+
return new PrismBotClientError("暂时连不上服务器", "API_UNREACHABLE", 0, {});
|
|
310
|
+
}
|
|
311
|
+
function replyError(status, body) {
|
|
312
|
+
const err = body && typeof body === "object" && typeof body.error === "object" ? body.error : {};
|
|
313
|
+
return new PrismBotClientError(typeof err.message === "string" ? err.message : `Backend request failed with HTTP ${status}.`, typeof err.code === "string" ? err.code : `HTTP_${status}`, status, body ?? {});
|
|
314
|
+
}
|
|
315
|
+
function benchmarkCount(raw) {
|
|
316
|
+
const count = raw == null || raw === "" ? 5 : Number(raw);
|
|
317
|
+
return Number.isInteger(count) && count >= 1 && count <= 10 ? count : null;
|
|
318
|
+
}
|
|
319
|
+
function spread(samples) {
|
|
320
|
+
const average = samples.reduce((sum, sample) => sum + sample, 0) / samples.length;
|
|
321
|
+
return `最小 ${Math.round(Math.min(...samples))} / 平均 ${Math.round(average)} / 最大 ${Math.round(Math.max(...samples))} ms`;
|
|
322
|
+
}
|
|
323
|
+
function serverLine(timings) {
|
|
324
|
+
const known = timings.map((timing) => timing.serverMs).filter((value) => value !== null);
|
|
325
|
+
if (!known.length)
|
|
326
|
+
return [];
|
|
327
|
+
return [`服务端处理:平均 ${Math.round(known.reduce((sum, value) => sum + value, 0) / known.length)} ms`];
|
|
328
|
+
}
|
|
329
|
+
/** The platform connection URL for a shop. */
|
|
330
|
+
function platformSocketUrl(baseUrl, shopCode) {
|
|
331
|
+
const base = baseUrl.trim().replace(/\/+$/, "").replace(/^http/i, "ws");
|
|
332
|
+
return `${base}/api/v1/shops/${encodeURIComponent(shopCode)}/integration/ws`;
|
|
333
|
+
}
|
|
334
|
+
/* ----------------------------- api client ---------------------------------- */
|
|
335
|
+
class PrismApiClient {
|
|
336
|
+
socket;
|
|
337
|
+
http;
|
|
338
|
+
constructor(socket, http) {
|
|
339
|
+
this.socket = socket;
|
|
340
|
+
this.http = http;
|
|
341
|
+
}
|
|
342
|
+
async request(method, path, options) {
|
|
343
|
+
let target = path.replace(/^\/rpc\//, "");
|
|
344
|
+
for (const [key, value] of Object.entries(options.params ?? {})) {
|
|
345
|
+
target = target.replace(`:${key}`, encodeURIComponent(String(value)));
|
|
184
346
|
}
|
|
347
|
+
const { status, body } = await this.socket.request({
|
|
348
|
+
method,
|
|
349
|
+
path: target,
|
|
350
|
+
...(options.query ? { query: options.query } : {}),
|
|
351
|
+
...(method === "GET" ? {} : { body: options.body ?? {} }),
|
|
352
|
+
});
|
|
353
|
+
if (status >= 400)
|
|
354
|
+
throw replyError(status, body);
|
|
355
|
+
return body && typeof body === "object" && Object.hasOwn(body, "data") ? body.data : body;
|
|
356
|
+
}
|
|
357
|
+
confirmPlatformBinding(code, provider, subject) {
|
|
358
|
+
return this.request("POST", "/rpc/integration/platform-binding/confirm", { body: { code, provider, subject } });
|
|
185
359
|
}
|
|
186
360
|
identityBody(identity) {
|
|
187
361
|
return {
|
|
@@ -198,17 +372,15 @@ class PrismApiClient {
|
|
|
198
372
|
? "/rpc/integration/players/by-identity/register"
|
|
199
373
|
: "/rpc/integration/players/by-identity/resolve";
|
|
200
374
|
const result = await this.request("POST", endpoint, {
|
|
201
|
-
token: this.config.integrationToken,
|
|
202
375
|
body: this.identityBody(identity),
|
|
203
376
|
});
|
|
204
377
|
return result.player;
|
|
205
378
|
}
|
|
206
379
|
async getVersion() {
|
|
207
|
-
return this.request("GET", "
|
|
380
|
+
return this.request("GET", "version", {});
|
|
208
381
|
}
|
|
209
382
|
async startSessionByIdentity(identity, body) {
|
|
210
383
|
return this.request("POST", "/rpc/integration/players/by-identity/session/start", {
|
|
211
|
-
token: this.config.integrationToken,
|
|
212
384
|
body: {
|
|
213
385
|
...this.identityBody(identity),
|
|
214
386
|
...(body ?? {}),
|
|
@@ -217,44 +389,63 @@ class PrismApiClient {
|
|
|
217
389
|
}
|
|
218
390
|
async stopSessionByIdentity(identity, sessionId) {
|
|
219
391
|
return this.request("POST", "/rpc/integration/players/by-identity/sessions/:sessionId/stop", {
|
|
220
|
-
token: this.config.integrationToken,
|
|
221
392
|
params: { sessionId },
|
|
222
393
|
body: this.identityBody(identity),
|
|
223
394
|
});
|
|
224
395
|
}
|
|
225
396
|
async getWalletByIdentity(identity) {
|
|
226
397
|
return this.request("POST", "/rpc/integration/players/by-identity/wallet", {
|
|
227
|
-
token: this.config.integrationToken,
|
|
228
398
|
body: this.identityBody(identity),
|
|
229
399
|
});
|
|
230
400
|
}
|
|
401
|
+
/** The wallet query over the platform connection, timed. */
|
|
402
|
+
async timeWalletOverSocket(identity) {
|
|
403
|
+
const startedAt = performance.now();
|
|
404
|
+
const reply = await this.socket.request({ method: "POST", path: "integration/players/by-identity/wallet", body: this.identityBody(identity) });
|
|
405
|
+
const ms = performance.now() - startedAt;
|
|
406
|
+
if (reply.status >= 400)
|
|
407
|
+
throw replyError(reply.status, reply.body);
|
|
408
|
+
return { ms, serverMs: reply.serverMs ?? null };
|
|
409
|
+
}
|
|
410
|
+
/** The same wallet query as a plain HTTP request, the way the Bot used to call, timed. */
|
|
411
|
+
async timeWalletOverHttp(identity) {
|
|
412
|
+
if (!this.http)
|
|
413
|
+
throw new PrismBotClientError("HTTP 测速不可用", "HTTP_UNAVAILABLE", 0, {});
|
|
414
|
+
const { post, baseUrl, shopCode, token } = this.http;
|
|
415
|
+
const url = `${baseUrl.trim().replace(/\/+$/, "")}/api/v1/shops/${encodeURIComponent(shopCode)}/integration/players/by-identity/wallet`;
|
|
416
|
+
const startedAt = performance.now();
|
|
417
|
+
const response = await post(url, { authorization: `Bearer ${token}`, "content-type": "application/json" }, this.identityBody(identity));
|
|
418
|
+
const ms = performance.now() - startedAt;
|
|
419
|
+
if (response.status >= 400)
|
|
420
|
+
throw replyError(response.status, response.data);
|
|
421
|
+
const server = Number.parseFloat(response.headers.get("x-response-time") ?? "");
|
|
422
|
+
return { ms, serverMs: Number.isFinite(server) ? server : null, colo: response.headers.get("cf-ray")?.split("-").pop() ?? null };
|
|
423
|
+
}
|
|
424
|
+
pingSocket() {
|
|
425
|
+
return this.socket.ping();
|
|
426
|
+
}
|
|
231
427
|
async getAssetsByIdentity(identity) {
|
|
232
428
|
return this.request("POST", "/rpc/integration/players/by-identity/assets", {
|
|
233
|
-
token: this.config.integrationToken,
|
|
234
429
|
body: this.identityBody(identity),
|
|
235
430
|
});
|
|
236
431
|
}
|
|
237
432
|
async getSessionHistoryByIdentity(identity) {
|
|
238
433
|
return this.request("POST", "/rpc/integration/players/by-identity/history", {
|
|
239
|
-
token: this.config.integrationToken,
|
|
240
434
|
body: this.identityBody(identity),
|
|
241
435
|
});
|
|
242
436
|
}
|
|
243
437
|
async previewCheckoutByIdentity(identity) {
|
|
244
438
|
return this.request("POST", "/rpc/integration/players/by-identity/checkout/preview", {
|
|
245
|
-
token: this.config.integrationToken,
|
|
246
439
|
body: this.identityBody(identity),
|
|
247
440
|
});
|
|
248
441
|
}
|
|
249
442
|
async confirmCheckoutByIdentity(identity, closeSessionsBeforeBalanceCheck = true) {
|
|
250
443
|
return this.request("POST", "/rpc/integration/players/by-identity/checkout/confirm", {
|
|
251
|
-
token: this.config.integrationToken,
|
|
252
444
|
body: { ...this.identityBody(identity), closeSessionsBeforeBalanceCheck },
|
|
253
445
|
});
|
|
254
446
|
}
|
|
255
447
|
async redeemCodeByIdentity(identity, code) {
|
|
256
448
|
return this.request("POST", "/rpc/integration/players/by-identity/redeem", {
|
|
257
|
-
token: this.config.integrationToken,
|
|
258
449
|
body: {
|
|
259
450
|
...this.identityBody(identity),
|
|
260
451
|
code,
|
|
@@ -263,7 +454,6 @@ class PrismApiClient {
|
|
|
263
454
|
}
|
|
264
455
|
async requestDeviceCommandByIdentity(identity, command, options) {
|
|
265
456
|
return this.request("POST", "/rpc/integration/players/by-identity/device-actions", {
|
|
266
|
-
token: this.config.integrationToken,
|
|
267
457
|
body: {
|
|
268
458
|
...this.identityBody(identity),
|
|
269
459
|
...(options?.staffOverride ? { staffOverride: true } : {}),
|
|
@@ -277,7 +467,6 @@ class PrismApiClient {
|
|
|
277
467
|
}
|
|
278
468
|
async requestScanByIdentity(identity, scan) {
|
|
279
469
|
return this.request("POST", "/rpc/integration/players/by-identity/device-actions", {
|
|
280
|
-
token: this.config.integrationToken,
|
|
281
470
|
body: {
|
|
282
471
|
...this.identityBody(identity),
|
|
283
472
|
target: {
|
|
@@ -294,83 +483,108 @@ class PrismApiClient {
|
|
|
294
483
|
});
|
|
295
484
|
}
|
|
296
485
|
async listActiveSessions() {
|
|
297
|
-
return this.request("GET", "/rpc/integration/sessions/active", {
|
|
298
|
-
token: this.config.integrationToken,
|
|
299
|
-
});
|
|
486
|
+
return this.request("GET", "/rpc/integration/sessions/active", {});
|
|
300
487
|
}
|
|
301
488
|
async listDeviceStates() {
|
|
302
|
-
return this.request("GET", "/rpc/integration/device-states", {
|
|
303
|
-
token: this.config.integrationToken,
|
|
304
|
-
});
|
|
489
|
+
return this.request("GET", "/rpc/integration/device-states", {});
|
|
305
490
|
}
|
|
306
491
|
async adjustAssetsByIdentity(identity, adjustments) {
|
|
307
492
|
return this.request("POST", "/rpc/integration/players/by-identity/assets/adjustments", {
|
|
308
|
-
token: this.config.integrationToken,
|
|
309
493
|
body: { ...this.identityBody(identity), adjustments },
|
|
310
494
|
});
|
|
311
495
|
}
|
|
312
496
|
async adjustWalletByIdentity(identity, amount, reason) {
|
|
313
497
|
return this.request("POST", "/rpc/integration/players/by-identity/wallet/adjustment", {
|
|
314
|
-
token: this.config.integrationToken,
|
|
315
498
|
body: { ...this.identityBody(identity), amount, reason },
|
|
316
499
|
});
|
|
317
500
|
}
|
|
318
501
|
async checkoutWithOverrideByIdentity(identity, total, reason) {
|
|
319
502
|
return this.request("POST", "/rpc/integration/players/by-identity/checkout/override", {
|
|
320
|
-
token: this.config.integrationToken,
|
|
321
503
|
body: { ...this.identityBody(identity), total, reason },
|
|
322
504
|
});
|
|
323
505
|
}
|
|
324
506
|
}
|
|
325
|
-
/* ------------------------------- service ----------------------------------- */
|
|
326
507
|
class PrismKoishiService {
|
|
508
|
+
ctx;
|
|
327
509
|
config;
|
|
328
510
|
mahjongTables = new Map();
|
|
329
511
|
logoutInFlight = new Map();
|
|
330
512
|
client;
|
|
331
513
|
logger;
|
|
514
|
+
socket = null;
|
|
332
515
|
constructor(ctx, config) {
|
|
516
|
+
this.ctx = ctx;
|
|
333
517
|
this.config = config;
|
|
334
518
|
this.logger = ctx.logger?.("prism");
|
|
335
519
|
if (config.client) {
|
|
336
520
|
this.client = config.client;
|
|
521
|
+
return;
|
|
337
522
|
}
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
if (!res.ok)
|
|
361
|
-
throw { response: { data: await res.json(), status: res.status } };
|
|
362
|
-
return res.json();
|
|
363
|
-
}
|
|
364
|
-
};
|
|
365
|
-
this.client = new PrismApiClient(http, {
|
|
366
|
-
baseUrl: config.baseUrl,
|
|
367
|
-
shopCode: config.shopCode,
|
|
368
|
-
integrationToken: config.integrationToken,
|
|
523
|
+
if (!config.shopCode || !config.baseUrl || !config.integrationToken) {
|
|
524
|
+
throw new Error("PRiSM Koishi plugin requires 'shopCode', 'baseUrl' and 'integrationToken'.");
|
|
525
|
+
}
|
|
526
|
+
const open = config.socket ?? ((url, headers) => {
|
|
527
|
+
const http = ctx.http;
|
|
528
|
+
if (!http?.ws)
|
|
529
|
+
throw new Error("Koishi http service with WebSocket support is required.");
|
|
530
|
+
return http.ws(url, { headers });
|
|
531
|
+
});
|
|
532
|
+
const lead = Math.max(0, config.idleReminderMinutes ?? 5);
|
|
533
|
+
this.socket = new PrismSocket(open, platformSocketUrl(config.baseUrl, config.shopCode), config.integrationToken,
|
|
534
|
+
// Without anywhere to send it, the platform need not plan a reminder.
|
|
535
|
+
lead > 0 && (config.idleNotifyChannelIds ?? []).length ? { reminderLeadSeconds: lead * 60 } : {}, (event) => {
|
|
536
|
+
if (event.event === "idle.reminder")
|
|
537
|
+
void this.remindIdle(event.data);
|
|
538
|
+
}, this.logger);
|
|
539
|
+
const post = config.httpPost ?? (async (url, headers, body) => {
|
|
540
|
+
const http = ctx.http;
|
|
541
|
+
if (typeof http !== "function")
|
|
542
|
+
throw new PrismBotClientError("HTTP 测速需要 Koishi 的 http 服务", "HTTP_UNAVAILABLE", 0, {});
|
|
543
|
+
const response = await http(url, {
|
|
544
|
+
method: "POST", headers, data: body, keepAlive: true, timeout: REQUEST_TIMEOUT_MS, validateStatus: () => true,
|
|
369
545
|
});
|
|
546
|
+
return { status: response.status, headers: response.headers, data: response.data };
|
|
547
|
+
});
|
|
548
|
+
this.client = new PrismApiClient(this.socket, { post, baseUrl: config.baseUrl, shopCode: config.shopCode, token: config.integrationToken });
|
|
549
|
+
this.socket.start();
|
|
550
|
+
}
|
|
551
|
+
dispose() {
|
|
552
|
+
this.socket?.stop();
|
|
553
|
+
}
|
|
554
|
+
async bind(sender, code) {
|
|
555
|
+
try {
|
|
556
|
+
await this.client.confirmPlatformBinding(code, sender.provider, sender.id);
|
|
557
|
+
return "绑定成功,请返回网页继续操作";
|
|
558
|
+
}
|
|
559
|
+
catch (error) {
|
|
560
|
+
if (error instanceof PrismBotClientError && error.status > 0)
|
|
561
|
+
return error.message || "绑定失败,请重新生成验证码";
|
|
562
|
+
throw error;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
/** Tell the configured channels a power-off is coming. Short: they can read a device name. */
|
|
566
|
+
async remindIdle(reminder) {
|
|
567
|
+
const channels = this.config.idleNotifyChannelIds ?? [];
|
|
568
|
+
if (!channels.length || typeof this.ctx.broadcast !== "function")
|
|
569
|
+
return;
|
|
570
|
+
const now = (this.config.now?.() ?? new Date()).getTime();
|
|
571
|
+
const minutes = Math.max(1, Math.round((reminder.at - now) / 60_000));
|
|
572
|
+
const names = reminder.devices.map((device) => device.name).join("、");
|
|
573
|
+
const message = reminder.reason === "shop_empty"
|
|
574
|
+
? `店里没人,${minutes} 分钟后全部关机`
|
|
575
|
+
: `${names} 闲置中,${minutes} 分钟后关机。已入场的玩家发送 keep 设备名 可以延迟`;
|
|
576
|
+
try {
|
|
577
|
+
await this.ctx.broadcast(channels, message);
|
|
578
|
+
}
|
|
579
|
+
catch (error) {
|
|
580
|
+
this.logger?.warn("PRiSM idle reminder failed", error);
|
|
370
581
|
}
|
|
371
582
|
}
|
|
372
583
|
async sender(context) {
|
|
373
|
-
const id = context.session?.
|
|
584
|
+
const id = cleanText(context.session?.userId);
|
|
585
|
+
const provider = cleanText(context.session?.platform || context.session?.bot?.platform).toLowerCase();
|
|
586
|
+
if (!id || !/^[a-z][a-z0-9_-]{0,63}$/.test(provider))
|
|
587
|
+
throw new PrismBotClientError("无法获取发送人的平台身份", "INVALID_PLATFORM_IDENTITY", 400, null);
|
|
374
588
|
let name = context.session?.username || context.session?.senderName || id;
|
|
375
589
|
try {
|
|
376
590
|
if (context.session?.bot?.getUser) {
|
|
@@ -381,7 +595,7 @@ class PrismKoishiService {
|
|
|
381
595
|
}
|
|
382
596
|
}
|
|
383
597
|
catch { }
|
|
384
|
-
return { id, name };
|
|
598
|
+
return { id, name, provider };
|
|
385
599
|
}
|
|
386
600
|
async register(sender) {
|
|
387
601
|
await this.client.resolveOrRegisterIdentity(this.identity(sender));
|
|
@@ -390,7 +604,7 @@ class PrismKoishiService {
|
|
|
390
604
|
async loginForTarget(actor, targetSubject, bot) {
|
|
391
605
|
return this.withTarget(actor, targetSubject, async (sender, isTargeted) => {
|
|
392
606
|
await this.client.startSessionByIdentity(this.identity(sender), this.loginSessionBody());
|
|
393
|
-
return isTargeted ? `✅ 已为用户 ${formatPlayerReference(sender
|
|
607
|
+
return isTargeted ? `✅ 已为用户 ${formatPlayerReference(sender)} 入场成功` : "✅ 入场成功";
|
|
394
608
|
}, bot);
|
|
395
609
|
}
|
|
396
610
|
async login(sender) {
|
|
@@ -410,7 +624,7 @@ class PrismKoishiService {
|
|
|
410
624
|
return "金额必须大于 0";
|
|
411
625
|
const isAddition = direction === 1;
|
|
412
626
|
await this.client.adjustWalletByIdentity(this.identity(sender), amount * direction, isAddition ? "Koishi 管理员增加余额" : "Koishi 管理员扣除余额");
|
|
413
|
-
return `✅ 已为用户 ${formatPlayerReference(sender
|
|
627
|
+
return `✅ 已为用户 ${formatPlayerReference(sender)}${isAddition ? "增加" : "扣除"} ${formatNumber(amount)} ${this.config.currencyName}`;
|
|
414
628
|
}, bot);
|
|
415
629
|
}
|
|
416
630
|
async overwriteTargetCheckout(actor, targetSubject, rawAmount, rawReason, bot) {
|
|
@@ -458,6 +672,7 @@ class PrismKoishiService {
|
|
|
458
672
|
const result = (await this.client.startSessionByIdentity(this.identity(sender), {
|
|
459
673
|
pricingConfigIds: tableConfig.pricingConfigIds,
|
|
460
674
|
label,
|
|
675
|
+
entry: false,
|
|
461
676
|
}));
|
|
462
677
|
const session = (result?.session ?? {});
|
|
463
678
|
const sessionId = String(session.id ?? "");
|
|
@@ -482,6 +697,7 @@ class PrismKoishiService {
|
|
|
482
697
|
const result = (await this.client.startSessionByIdentity(seat.identity, {
|
|
483
698
|
pricingConfigIds: tableConfig.pricingConfigIds,
|
|
484
699
|
label,
|
|
700
|
+
entry: false,
|
|
485
701
|
}));
|
|
486
702
|
const session = (result?.session ?? {});
|
|
487
703
|
const sessionId = String(session.id ?? "");
|
|
@@ -511,10 +727,12 @@ class PrismKoishiService {
|
|
|
511
727
|
const sessionId = state.activeSessions[playerId];
|
|
512
728
|
if (!sessionId)
|
|
513
729
|
return "你当前未在任何麻将桌上。";
|
|
730
|
+
// Do not show an available seat while the backend session is still running.
|
|
731
|
+
// Failed stop requests must preserve the table state for safe retry.
|
|
732
|
+
await this.client.stopSessionByIdentity(this.identity(sender), sessionId);
|
|
514
733
|
delete state.activeSessions[playerId];
|
|
515
734
|
const remainingCount = Object.keys(state.activeSessions).length;
|
|
516
735
|
const tableSize = this.config.mahjongTableSize ?? 4;
|
|
517
|
-
await this.client.stopSessionByIdentity(this.identity(sender), sessionId);
|
|
518
736
|
return `已离开 ${tableSubject},麻将计费已停止。当前还剩 ${remainingCount}/${tableSize} 人。`;
|
|
519
737
|
}
|
|
520
738
|
async listMahjongTables() {
|
|
@@ -542,17 +760,20 @@ class PrismKoishiService {
|
|
|
542
760
|
return this.formatCheckoutPreview(result, sender, "【结算账单】", true);
|
|
543
761
|
}
|
|
544
762
|
async logout(sender, bot) {
|
|
545
|
-
|
|
763
|
+
// A Koishi instance can receive identical userId values from different adapters.
|
|
764
|
+
// In-flight settlement coalescing must use the same composite identity as Bot RPC.
|
|
765
|
+
const key = `${sender.provider}:${sender.id}`;
|
|
766
|
+
const existing = this.logoutInFlight.get(key);
|
|
546
767
|
if (existing)
|
|
547
768
|
return existing;
|
|
548
769
|
const task = this.performLogout(sender, bot);
|
|
549
|
-
this.logoutInFlight.set(
|
|
770
|
+
this.logoutInFlight.set(key, task);
|
|
550
771
|
try {
|
|
551
772
|
return await task;
|
|
552
773
|
}
|
|
553
774
|
finally {
|
|
554
|
-
if (this.logoutInFlight.get(
|
|
555
|
-
this.logoutInFlight.delete(
|
|
775
|
+
if (this.logoutInFlight.get(key) === task)
|
|
776
|
+
this.logoutInFlight.delete(key);
|
|
556
777
|
}
|
|
557
778
|
}
|
|
558
779
|
async performLogout(sender, bot) {
|
|
@@ -605,34 +826,57 @@ class PrismKoishiService {
|
|
|
605
826
|
};
|
|
606
827
|
const receipt = await this.formatCheckoutPreview(synthetic, sender, title, false);
|
|
607
828
|
const recipients = [...new Set([...(this.config.staffUserIds ?? []), ...(this.config.logoutNotifyUserIds ?? [])])];
|
|
608
|
-
|
|
609
|
-
|
|
829
|
+
const channelIds = recipients.flatMap(identity => {
|
|
830
|
+
if (identity.startsWith(`${sender.provider}:`))
|
|
831
|
+
return [`private:${identity.slice(sender.provider.length + 1)}`];
|
|
832
|
+
if (sender.provider === "onebot" && (!identity.includes(":") || identity.startsWith("private:")))
|
|
833
|
+
return [identity.startsWith("private:") ? identity : `private:${identity}`];
|
|
834
|
+
return [];
|
|
835
|
+
});
|
|
836
|
+
if (channelIds.length > 0 && bot?.broadcast)
|
|
610
837
|
await bot.broadcast(channelIds, receipt);
|
|
611
|
-
}
|
|
612
838
|
return receipt;
|
|
613
839
|
}
|
|
614
840
|
async wallet(sender) {
|
|
615
841
|
const result = (await this.client.getWalletByIdentity(this.identity(sender)));
|
|
616
842
|
return formatWallet(result.wallet, this.config.currencyName);
|
|
617
843
|
}
|
|
844
|
+
/**
|
|
845
|
+
* The wallet query over plain HTTP. The first request usually has to open a
|
|
846
|
+
* connection (DNS, TCP, TLS), so it is reported apart from the reused ones.
|
|
847
|
+
*/
|
|
618
848
|
async benchmarkApi(sender, rawCount) {
|
|
619
|
-
const count =
|
|
620
|
-
if (
|
|
849
|
+
const count = benchmarkCount(rawCount);
|
|
850
|
+
if (count === null)
|
|
621
851
|
return "次数须为 1 到 10 的整数。";
|
|
622
|
-
const
|
|
623
|
-
for (let index = 0; index < count; index++)
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
852
|
+
const timings = [];
|
|
853
|
+
for (let index = 0; index < count; index++)
|
|
854
|
+
timings.push(await this.client.timeWalletOverHttp(this.identity(sender)));
|
|
855
|
+
const [first, ...rest] = timings;
|
|
856
|
+
return [
|
|
857
|
+
`📡 API 测速(HTTP,钱包查询 ${count} 次)`,
|
|
858
|
+
`首次:${Math.round(first.ms)} ms(含建立连接)`,
|
|
859
|
+
...(rest.length ? [`之后:${spread(rest.map((timing) => timing.ms))}`] : []),
|
|
860
|
+
...serverLine(timings),
|
|
861
|
+
...(first.colo ? [`节点:${first.colo}`] : []),
|
|
862
|
+
].join("\n");
|
|
863
|
+
}
|
|
864
|
+
/** Heartbeats (the network alone) and the same wallet query over the platform connection. */
|
|
865
|
+
async benchmarkWs(sender, rawCount) {
|
|
866
|
+
const count = benchmarkCount(rawCount);
|
|
867
|
+
if (count === null)
|
|
868
|
+
return "次数须为 1 到 10 的整数。";
|
|
869
|
+
const pings = [];
|
|
870
|
+
for (let index = 0; index < count; index++)
|
|
871
|
+
pings.push(await this.client.pingSocket());
|
|
872
|
+
const timings = [];
|
|
873
|
+
for (let index = 0; index < count; index++)
|
|
874
|
+
timings.push(await this.client.timeWalletOverSocket(this.identity(sender)));
|
|
631
875
|
return [
|
|
632
|
-
`📡
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
876
|
+
`📡 WS 测速(${count} 次)`,
|
|
877
|
+
`心跳:${spread(pings)}`,
|
|
878
|
+
`钱包查询:${spread(timings.map((timing) => timing.ms))}`,
|
|
879
|
+
...serverLine(timings),
|
|
636
880
|
].join("\n");
|
|
637
881
|
}
|
|
638
882
|
async versions() {
|
|
@@ -763,7 +1007,7 @@ class PrismKoishiService {
|
|
|
763
1007
|
table,
|
|
764
1008
|
]));
|
|
765
1009
|
const players = groupSessionsByPlayer(sessions);
|
|
766
|
-
const groups = await this.buildPlayerGroups(players, tableByLabel);
|
|
1010
|
+
const groups = await this.buildPlayerGroups(players, tableByLabel, sender.provider);
|
|
767
1011
|
this.mergeWaitingSeats(groups);
|
|
768
1012
|
const tables = result.mahjongTables;
|
|
769
1013
|
if (!tables)
|
|
@@ -797,27 +1041,29 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
797
1041
|
.map((d) => `${d.label || d.deviceId}: ${normalizeDeviceState(d.state)}`)
|
|
798
1042
|
.join("\n");
|
|
799
1043
|
}
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
1044
|
+
/** Keep a running device from being switched off as idle; never switches one on. */
|
|
1045
|
+
async keep(sender, deviceRef) {
|
|
1046
|
+
try {
|
|
1047
|
+
const result = await this.client.requestDeviceCommandByIdentity(this.identity(sender), {
|
|
1048
|
+
type: "power.keep",
|
|
1049
|
+
target: { kind: "facility", ref: deviceRef },
|
|
1050
|
+
});
|
|
1051
|
+
if (this.getCommandFailureMessage(result)) {
|
|
1052
|
+
this.logDeviceCommandFailure(result);
|
|
1053
|
+
return `延迟失败,${deviceCommandFailureReason(result)}`;
|
|
1054
|
+
}
|
|
1055
|
+
return `✅ ${result.action.payload.deviceLabel} 已延迟关机`;
|
|
1056
|
+
}
|
|
1057
|
+
catch (error) {
|
|
1058
|
+
this.logCommandError(error);
|
|
1059
|
+
return `延迟失败,${powerFailureReason(error)}`;
|
|
1060
|
+
}
|
|
815
1061
|
}
|
|
816
1062
|
/* ---------------------------- helpers ---------------------------------- */
|
|
817
|
-
async power(sender, deviceRef, state
|
|
1063
|
+
async power(sender, deviceRef, state) {
|
|
818
1064
|
const operation = state === "on" ? "启动" : "关闭";
|
|
819
|
-
const staffOverride =
|
|
820
|
-
if (
|
|
1065
|
+
const staffOverride = state === "off" && this.config.powerCommandsAdminOnly === true;
|
|
1066
|
+
if (staffOverride && !matchesPlatformIdentity(this.config.staffUserIds ?? [], sender)) {
|
|
821
1067
|
return `${operation}失败,权限不足`;
|
|
822
1068
|
}
|
|
823
1069
|
try {
|
|
@@ -846,24 +1092,24 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
846
1092
|
}
|
|
847
1093
|
return null;
|
|
848
1094
|
}
|
|
849
|
-
async resolvePlatformName(subject) {
|
|
1095
|
+
async resolvePlatformName(subject, provider) {
|
|
850
1096
|
if (!this.config.resolveDisplayName)
|
|
851
1097
|
return null;
|
|
852
1098
|
try {
|
|
853
|
-
return (await this.config.resolveDisplayName(subject)) ?? null;
|
|
1099
|
+
return (await this.config.resolveDisplayName(subject, provider)) ?? null;
|
|
854
1100
|
}
|
|
855
1101
|
catch {
|
|
856
1102
|
return null;
|
|
857
1103
|
}
|
|
858
1104
|
}
|
|
859
|
-
async displayNameForPlayer(player) {
|
|
1105
|
+
async displayNameForPlayer(player, provider) {
|
|
860
1106
|
let identitySubject;
|
|
861
1107
|
for (const session of player.sessions) {
|
|
862
|
-
const subject = findSubjectForSession(session,
|
|
1108
|
+
const subject = findSubjectForSession(session, provider);
|
|
863
1109
|
if (!subject)
|
|
864
1110
|
continue;
|
|
865
1111
|
identitySubject ??= subject;
|
|
866
|
-
const platformName = await this.resolvePlatformName(subject);
|
|
1112
|
+
const platformName = await this.resolvePlatformName(subject, provider);
|
|
867
1113
|
if (platformName)
|
|
868
1114
|
return platformName;
|
|
869
1115
|
}
|
|
@@ -873,12 +1119,12 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
873
1119
|
|| player.playerId
|
|
874
1120
|
|| "未知玩家";
|
|
875
1121
|
}
|
|
876
|
-
async buildPlayerGroups(players, tableByLabel) {
|
|
1122
|
+
async buildPlayerGroups(players, tableByLabel, provider) {
|
|
877
1123
|
const groups = { groups: [] };
|
|
878
1124
|
const groupByLabel = new Map();
|
|
879
1125
|
const musicLabel = this.config.loginSessionLabel?.trim() || "音游区间";
|
|
880
1126
|
for (const player of players.values()) {
|
|
881
|
-
player.displayName = await this.displayNameForPlayer(player);
|
|
1127
|
+
player.displayName = await this.displayNameForPlayer(player, provider);
|
|
882
1128
|
const nonMusic = player.sessions.filter((session) => Boolean(session.label) && session.label !== "entry" && session.label !== musicLabel);
|
|
883
1129
|
const source = nonMusic.length > 0 ? nonMusic : player.sessions;
|
|
884
1130
|
const selected = source.reduce((latest, session) => !latest || sessionStartedAt(session) > sessionStartedAt(latest) ? session : latest, undefined);
|
|
@@ -920,11 +1166,11 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
920
1166
|
async resolvePlayerDisplay(sender, playerId) {
|
|
921
1167
|
if (!sender)
|
|
922
1168
|
return playerId || "未知玩家";
|
|
923
|
-
const platformName = await this.resolvePlatformName(sender.id);
|
|
1169
|
+
const platformName = await this.resolvePlatformName(sender.id, sender.provider);
|
|
924
1170
|
const name = platformName
|
|
925
1171
|
|| (sender.name && sender.name !== sender.id ? sender.name : "")
|
|
926
1172
|
|| "未知昵称";
|
|
927
|
-
return `玩家:${name}(${
|
|
1173
|
+
return `玩家:${name}(${sender.provider}:${sender.id})`;
|
|
928
1174
|
}
|
|
929
1175
|
mahjongTableForPlayer(playerId) {
|
|
930
1176
|
for (const [tableId, state] of this.mahjongTables) {
|
|
@@ -984,25 +1230,32 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
984
1230
|
}
|
|
985
1231
|
identity(sender) {
|
|
986
1232
|
return {
|
|
987
|
-
provider:
|
|
1233
|
+
provider: sender.provider,
|
|
988
1234
|
subject: sender.id,
|
|
989
1235
|
autoRegister: this.config.autoRegister,
|
|
990
|
-
displayName: sender.name || `${
|
|
1236
|
+
displayName: sender.name || `${sender.provider} ${sender.id}`,
|
|
991
1237
|
};
|
|
992
1238
|
}
|
|
993
1239
|
async targetSender(actor, targetSubject, bot) {
|
|
994
|
-
const
|
|
995
|
-
if (!
|
|
1240
|
+
const raw = cleanText(targetSubject);
|
|
1241
|
+
if (!raw)
|
|
996
1242
|
return actor;
|
|
1243
|
+
const separator = raw.indexOf(":");
|
|
1244
|
+
const provider = separator > 0 ? raw.slice(0, separator).toLowerCase() : actor.provider;
|
|
1245
|
+
const subject = separator > 0 ? raw.slice(separator + 1) : raw;
|
|
1246
|
+
if (provider !== actor.provider)
|
|
1247
|
+
return "请在目标平台使用该命令";
|
|
1248
|
+
if (!subject)
|
|
1249
|
+
return "无法获取目标平台身份";
|
|
997
1250
|
const denied = this.targetStaffDenied(actor);
|
|
998
1251
|
if (denied)
|
|
999
1252
|
return denied;
|
|
1000
1253
|
try {
|
|
1001
1254
|
const user = await bot?.getUser?.(subject);
|
|
1002
|
-
return { id: subject, name: user?.name || subject };
|
|
1255
|
+
return { id: subject, name: user?.name || subject, provider };
|
|
1003
1256
|
}
|
|
1004
1257
|
catch {
|
|
1005
|
-
return { id: subject, name: subject };
|
|
1258
|
+
return { id: subject, name: subject, provider };
|
|
1006
1259
|
}
|
|
1007
1260
|
}
|
|
1008
1261
|
loginSessionBody() {
|
|
@@ -1010,9 +1263,8 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
1010
1263
|
.map((id) => id.trim())
|
|
1011
1264
|
.filter(Boolean);
|
|
1012
1265
|
const label = this.config.loginSessionLabel?.trim();
|
|
1013
|
-
if (pricingConfigIds.length === 0 && !label)
|
|
1014
|
-
return undefined;
|
|
1015
1266
|
return {
|
|
1267
|
+
entry: true,
|
|
1016
1268
|
...(pricingConfigIds.length === 0 ? {} : { pricingConfigIds }),
|
|
1017
1269
|
...(label ? { label } : {}),
|
|
1018
1270
|
};
|
|
@@ -1021,7 +1273,7 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
1021
1273
|
if (!this.config.enableStaffCommands)
|
|
1022
1274
|
return "员工命令未启用";
|
|
1023
1275
|
const allowed = this.config.staffUserIds ?? [];
|
|
1024
|
-
if (allowed.length > 0 && !allowed
|
|
1276
|
+
if (allowed.length > 0 && !matchesPlatformIdentity(allowed, sender))
|
|
1025
1277
|
return "权限不足";
|
|
1026
1278
|
return null;
|
|
1027
1279
|
}
|
|
@@ -1029,7 +1281,7 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
1029
1281
|
if (!this.config.enableStaffCommands)
|
|
1030
1282
|
return "员工命令未启用";
|
|
1031
1283
|
const allowed = this.config.staffUserIds ?? [];
|
|
1032
|
-
if (!allowed
|
|
1284
|
+
if (!matchesPlatformIdentity(allowed, sender))
|
|
1033
1285
|
return "权限不足";
|
|
1034
1286
|
return null;
|
|
1035
1287
|
}
|
|
@@ -1039,7 +1291,7 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
1039
1291
|
const playerId = preview.playerId;
|
|
1040
1292
|
const subtotal = preview.subtotal;
|
|
1041
1293
|
const total = preview.total;
|
|
1042
|
-
const previewedAt = parseDateTime(preview.previewedAt);
|
|
1294
|
+
const previewedAt = (0, display_time_js_1.parseDateTime)(preview.previewedAt);
|
|
1043
1295
|
const sessionPreviews = result.sessionPreviews;
|
|
1044
1296
|
const pricingCapAdjustments = result.pricingCapAdjustments;
|
|
1045
1297
|
const checkoutAdjustments = result.checkoutAdjustments;
|
|
@@ -1057,16 +1309,17 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
1057
1309
|
lines.push(`余额:${formatNumber(isPreview ? balanceBefore : balanceAfter)}${currency}`);
|
|
1058
1310
|
return lines.join("\n");
|
|
1059
1311
|
}
|
|
1060
|
-
const validStarts = sessionPreviews.map(
|
|
1061
|
-
const validEnds = sessionPreviews.map(
|
|
1312
|
+
const validStarts = sessionPreviews.map(s => s.startedAt).filter(value => (0, display_time_js_1.parseDateTime)(value));
|
|
1313
|
+
const validEnds = sessionPreviews.map(s => s.endedAt || (s.status === "active" ? preview.previewedAt : null)).filter(value => (0, display_time_js_1.parseDateTime)(value));
|
|
1062
1314
|
if (validStarts.length > 0) {
|
|
1063
|
-
const overallStart =
|
|
1064
|
-
const overallEnd = validEnds.length > 0 ?
|
|
1065
|
-
|
|
1315
|
+
const overallStart = validStarts.reduce((a, b) => Date.parse(a) < Date.parse(b) ? a : b);
|
|
1316
|
+
const overallEnd = validEnds.length > 0 ? validEnds.reduce((a, b) => Date.parse(a) > Date.parse(b) ? a : b) : now(this.config).toISOString();
|
|
1317
|
+
const offsets = [...new Set([(0, display_time_js_1.apiOffsetLabel)(overallStart), (0, display_time_js_1.apiOffsetLabel)(overallEnd)])].join(" / ");
|
|
1318
|
+
lines.push(`⏰ 游玩时间:${(0, display_time_js_1.formatHM)(overallStart)}–${(0, display_time_js_1.formatHM)(overallEnd)}(${offsets})`);
|
|
1066
1319
|
}
|
|
1067
1320
|
for (const sPrev of sessionPreviews) {
|
|
1068
1321
|
const label = sPrev?.label === "entry" ? this.config.loginSessionLabel?.trim() || "音游区间" : sPrev?.label || "计时区间";
|
|
1069
|
-
const startDt = parseDateTime(sPrev?.startedAt);
|
|
1322
|
+
const startDt = (0, display_time_js_1.parseDateTime)(sPrev?.startedAt);
|
|
1070
1323
|
const endDt = sessionDisplayEnd(sPrev, previewedAt);
|
|
1071
1324
|
const status = sPrev?.status ?? "active";
|
|
1072
1325
|
const sTotal = toNumber(sPrev?.total ?? 0);
|
|
@@ -1074,11 +1327,11 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
1074
1327
|
lines.push(label);
|
|
1075
1328
|
if (startDt && endDt) {
|
|
1076
1329
|
const minutes = Math.floor((endDt.getTime() - startDt.getTime()) / 60_000);
|
|
1077
|
-
lines.push(`游玩时段:${formatHM(
|
|
1330
|
+
lines.push(`游玩时段:${(0, display_time_js_1.formatHM)(sPrev.startedAt)}-${(0, display_time_js_1.formatHM)(sPrev.endedAt || preview.previewedAt || endDt.toISOString())}`);
|
|
1078
1331
|
lines.push(`游玩时长:${formatDurationValue(minutes)}|计价:${formatNumber(sTotal)}${currency}`);
|
|
1079
1332
|
}
|
|
1080
1333
|
else if (startDt) {
|
|
1081
|
-
lines.push(`入场:${formatHM(
|
|
1334
|
+
lines.push(`入场:${(0, display_time_js_1.formatHM)(sPrev.startedAt)} (${status === "active" ? "计费中" : "已关闭"})`);
|
|
1082
1335
|
}
|
|
1083
1336
|
const sessionAdjustments = (sPrev?.adjustments ?? []);
|
|
1084
1337
|
for (const adj of sessionAdjustments) {
|
|
@@ -1095,8 +1348,8 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
1095
1348
|
lines.push("封顶:");
|
|
1096
1349
|
for (const window of cappedWindows) {
|
|
1097
1350
|
const label = window.ruleLabel || "封顶时段";
|
|
1098
|
-
const startedAt = parseDateTime(window.windowStartedAt);
|
|
1099
|
-
const datedLabel = startedAt ? `${formatMD(
|
|
1351
|
+
const startedAt = (0, display_time_js_1.parseDateTime)(window.windowStartedAt);
|
|
1352
|
+
const datedLabel = startedAt ? `${(0, display_time_js_1.formatMD)(window.windowStartedAt)} ${label}` : label;
|
|
1100
1353
|
const currentAmount = toNumber(window.currentAmount);
|
|
1101
1354
|
const amountApplied = toNumber(window.amountApplied);
|
|
1102
1355
|
const priceCap = toNumber(window.priceCap);
|
|
@@ -1161,6 +1414,8 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
1161
1414
|
}
|
|
1162
1415
|
}
|
|
1163
1416
|
function humanReadableBotError(error) {
|
|
1417
|
+
if (error.code === "INVALID_PLATFORM_IDENTITY")
|
|
1418
|
+
return error.message;
|
|
1164
1419
|
if (error.code === "DUPLICATE_SESSION_LABEL") {
|
|
1165
1420
|
return "❌ 您已经处于入场状态,请勿重复发送入场命令。";
|
|
1166
1421
|
}
|
|
@@ -1179,7 +1434,9 @@ function humanReadableBotError(error) {
|
|
|
1179
1434
|
if (error.code === "INSUFFICIENT_BALANCE") {
|
|
1180
1435
|
return "余额不足,暂时不能结账。请先充值,或由店员在后台改价后再结账。";
|
|
1181
1436
|
}
|
|
1182
|
-
if (error.code === "API_UNREACHABLE"
|
|
1437
|
+
if (error.code === "API_UNREACHABLE")
|
|
1438
|
+
return "操作失败,暂时连不上服务器。";
|
|
1439
|
+
if (error.code === "NETWORK_ERROR" || error.code === "HTTP_0") {
|
|
1183
1440
|
return genericCommandFailure();
|
|
1184
1441
|
}
|
|
1185
1442
|
if (error.code === "API_TIMEOUT") {
|
|
@@ -1330,14 +1587,14 @@ function formatReleaseVersion(value) {
|
|
|
1330
1587
|
const revision = cleanText(record.revision);
|
|
1331
1588
|
return !revision || revision === "unknown" ? release : `${release} (${revision})`;
|
|
1332
1589
|
}
|
|
1333
|
-
function
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1590
|
+
function matchesPlatformIdentity(identities, sender) {
|
|
1591
|
+
return identities.includes(`${sender.provider}:${sender.id}`)
|
|
1592
|
+
// Legacy unqualified staff lists belong to the original adapter only.
|
|
1593
|
+
|| (sender.provider === "onebot" && identities.includes(sender.id));
|
|
1337
1594
|
}
|
|
1338
|
-
function formatPlayerReference(sender
|
|
1595
|
+
function formatPlayerReference(sender) {
|
|
1339
1596
|
const name = sender.name && sender.name !== sender.id ? sender.name : "未知昵称";
|
|
1340
|
-
return `${name}(${provider
|
|
1597
|
+
return `${name}(${sender.provider}:${sender.id})`;
|
|
1341
1598
|
}
|
|
1342
1599
|
function adjustmentKey(adjustment) {
|
|
1343
1600
|
const id = cleanText(adjustment?.id);
|
|
@@ -1387,63 +1644,6 @@ function formatNumber(value) {
|
|
|
1387
1644
|
}
|
|
1388
1645
|
return String(value);
|
|
1389
1646
|
}
|
|
1390
|
-
function parseDateTime(value) {
|
|
1391
|
-
if (!value)
|
|
1392
|
-
return null;
|
|
1393
|
-
if (value instanceof Date) {
|
|
1394
|
-
return ensureLocal(value);
|
|
1395
|
-
}
|
|
1396
|
-
const text = String(value).trim();
|
|
1397
|
-
if (!text)
|
|
1398
|
-
return null;
|
|
1399
|
-
let normalized = text;
|
|
1400
|
-
if (normalized.endsWith("Z"))
|
|
1401
|
-
normalized = `${normalized.slice(0, -1)}+00:00`;
|
|
1402
|
-
const dt = new Date(normalized);
|
|
1403
|
-
if (!Number.isNaN(dt.getTime()))
|
|
1404
|
-
return ensureLocal(dt);
|
|
1405
|
-
return null;
|
|
1406
|
-
}
|
|
1407
|
-
function ensureLocal(dt) {
|
|
1408
|
-
const offsetMs = LOCAL_TZ_OFFSET_MINUTES * 60_000;
|
|
1409
|
-
const local = new Date(dt.getTime() + offsetMs);
|
|
1410
|
-
void local;
|
|
1411
|
-
return dt;
|
|
1412
|
-
}
|
|
1413
|
-
function formatHM(dt) {
|
|
1414
|
-
const pad = (n) => String(n).padStart(2, "0");
|
|
1415
|
-
return `${pad(dt.getHours())}:${pad(dt.getMinutes())}`;
|
|
1416
|
-
}
|
|
1417
|
-
function formatMD(dt) {
|
|
1418
|
-
const pad = (n) => String(n).padStart(2, "0");
|
|
1419
|
-
return `${pad(dt.getMonth() + 1)}-${pad(dt.getDate())}`;
|
|
1420
|
-
}
|
|
1421
|
-
function formatDateTime(value) {
|
|
1422
|
-
const dt = parseDateTime(value);
|
|
1423
|
-
if (!dt)
|
|
1424
|
-
return "永不过期";
|
|
1425
|
-
const pad = (n) => String(n).padStart(2, "0");
|
|
1426
|
-
return `${dt.getFullYear()}/${pad(dt.getMonth() + 1)}/${pad(dt.getDate())} ${pad(dt.getHours())}:${pad(dt.getMinutes())}:${pad(dt.getSeconds())}`;
|
|
1427
|
-
}
|
|
1428
|
-
function formatTimeRange(start, end) {
|
|
1429
|
-
const startDt = parseDateTime(start);
|
|
1430
|
-
const endDt = parseDateTime(end);
|
|
1431
|
-
if (!startDt || !endDt)
|
|
1432
|
-
return `${formatDateTime(start)} - ${formatDateTime(end)}`;
|
|
1433
|
-
const pad = (n) => String(n).padStart(2, "0");
|
|
1434
|
-
const startTime = `${pad(startDt.getHours())}:${pad(startDt.getMinutes())}:${pad(startDt.getSeconds())}`;
|
|
1435
|
-
const endTime = `${pad(endDt.getHours())}:${pad(endDt.getMinutes())}:${pad(endDt.getSeconds())}`;
|
|
1436
|
-
if (startDt.toDateString() === endDt.toDateString())
|
|
1437
|
-
return `${startTime} - ${endTime}`;
|
|
1438
|
-
return `${startDt.getMonth() + 1}/${startDt.getDate()} ${startTime} - ${endDt.getMonth() + 1}/${endDt.getDate()} ${endTime}`;
|
|
1439
|
-
}
|
|
1440
|
-
function formatDurationMinutes(start, end) {
|
|
1441
|
-
const startDt = parseDateTime(start);
|
|
1442
|
-
const endDt = parseDateTime(end);
|
|
1443
|
-
if (!startDt || !endDt)
|
|
1444
|
-
return "0分钟";
|
|
1445
|
-
return formatDurationValue(Math.floor((endDt.getTime() - startDt.getTime()) / 60_000));
|
|
1446
|
-
}
|
|
1447
1647
|
function formatDurationValue(minutes) {
|
|
1448
1648
|
const total = Math.floor(toNumber(minutes));
|
|
1449
1649
|
if (total >= 60) {
|
|
@@ -1454,7 +1654,7 @@ function formatDurationValue(minutes) {
|
|
|
1454
1654
|
return `${total}分钟`;
|
|
1455
1655
|
}
|
|
1456
1656
|
function sessionDisplayEnd(session, previewedAt) {
|
|
1457
|
-
const endedAt = parseDateTime(session?.endedAt);
|
|
1657
|
+
const endedAt = (0, display_time_js_1.parseDateTime)(session?.endedAt);
|
|
1458
1658
|
if (endedAt)
|
|
1459
1659
|
return endedAt;
|
|
1460
1660
|
if (session?.status === "active")
|
|
@@ -1473,7 +1673,7 @@ function maxDate(dates) {
|
|
|
1473
1673
|
function formatInventoryItem(row) {
|
|
1474
1674
|
let line = `- ${row.assetName || row.assetCode || "资产"} (x${formatNumber(row.quantity)})`;
|
|
1475
1675
|
if (row.expiresAt)
|
|
1476
|
-
line += `\n 到期: ${formatDateTime(row.expiresAt)}`;
|
|
1676
|
+
line += `\n 到期: ${(0, display_time_js_1.formatDateTime)(row.expiresAt)}`;
|
|
1477
1677
|
return line;
|
|
1478
1678
|
}
|
|
1479
1679
|
function formatRedeemedItem(row) {
|
|
@@ -1505,9 +1705,9 @@ function formatHistory(sessions, currency) {
|
|
|
1505
1705
|
return "暂无历史记录";
|
|
1506
1706
|
const lines = [`📜 最近 ${sessions.length} 条记录:`];
|
|
1507
1707
|
for (const session of sessions) {
|
|
1508
|
-
const end = session.endedAt ? formatDateTime(session.endedAt) : "进行中";
|
|
1708
|
+
const end = session.endedAt ? (0, display_time_js_1.formatDateTime)(session.endedAt) : "进行中";
|
|
1509
1709
|
const cost = session.total == null ? "未结算" : `${formatNumber(session.total)} ${currency}`;
|
|
1510
|
-
lines.push(`- [${session.sessionId}] ${formatDateTime(session.startedAt)} -> ${end} (${cost})`);
|
|
1710
|
+
lines.push(`- [${session.sessionId}] ${(0, display_time_js_1.formatDateTime)(session.startedAt)} -> ${end} (${cost})`);
|
|
1511
1711
|
}
|
|
1512
1712
|
return lines.join("\n");
|
|
1513
1713
|
}
|
|
@@ -1515,10 +1715,8 @@ function findSubjectForSession(session, provider) {
|
|
|
1515
1715
|
const identities = session.identities ?? [];
|
|
1516
1716
|
if (identities.length === 0)
|
|
1517
1717
|
return null;
|
|
1518
|
-
const
|
|
1519
|
-
|
|
1520
|
-
return qq.subject;
|
|
1521
|
-
return identities[0].subject ?? null;
|
|
1718
|
+
const identity = provider ? identities.find((id) => id.provider === provider) : identities[0];
|
|
1719
|
+
return identity?.subject ?? null;
|
|
1522
1720
|
}
|
|
1523
1721
|
exports.default = {
|
|
1524
1722
|
name: exports.name,
|