koishi-plugin-rina-currency 0.0.2 → 0.0.4

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/lib/index.js CHANGED
@@ -215,32 +215,43 @@ async function renderTrendChart(metrics, rateType, options) {
215
215
  const padding = { top: 184, right: 72, bottom: 76, left: 88 };
216
216
  const plotWidth = width - padding.left - padding.right;
217
217
  const plotHeight = height - padding.top - padding.bottom;
218
- const values = metrics.points.map((point) => point[rateType]);
218
+ const rangeStart = metrics.rangeStart.getTime();
219
+ const rangeEnd = metrics.rangeEnd.getTime();
220
+ const chartPoints = metrics.points.map((point) => ({
221
+ ...point,
222
+ collectedAt: new Date(Math.max(point.collectedAt.getTime(), rangeStart))
223
+ }));
224
+ const lastPoint = chartPoints.at(-1);
225
+ if (lastPoint.collectedAt.getTime() < rangeEnd) {
226
+ chartPoints.push({ ...metrics.latest, collectedAt: new Date(rangeEnd) });
227
+ }
228
+ const values = chartPoints.map((point) => point[rateType]);
219
229
  const min = Math.min(...values);
220
230
  const max = Math.max(...values);
221
231
  const spread = Math.max(max - min, Math.max(max, 1) * 2e-3);
222
232
  const lower = min - spread * 0.14;
223
233
  const upper = max + spread * 0.14;
224
234
  const range = upper - lower;
225
- const firstTime = metrics.points[0].publishedAt.getTime();
226
- const lastTime = metrics.latest.publishedAt.getTime();
227
- const timeRange = Math.max(lastTime - firstTime, 1);
228
- const xFor = /* @__PURE__ */ __name((time) => padding.left + (time - firstTime) / timeRange * plotWidth, "xFor");
235
+ const timeRange = Math.max(rangeEnd - rangeStart, 1);
236
+ const xFor = /* @__PURE__ */ __name((time) => padding.left + (time - rangeStart) / timeRange * plotWidth, "xFor");
229
237
  const yFor = /* @__PURE__ */ __name((value) => padding.top + (upper - value) / range * plotHeight, "yFor");
230
- const coordinates = metrics.points.map((point) => `${xFor(point.publishedAt.getTime()).toFixed(1)},${yFor(point[rateType]).toFixed(1)}`).join(" ");
231
- const latestX = xFor(metrics.latest.publishedAt.getTime());
238
+ const coordinates = chartPoints.map((point) => `${xFor(point.collectedAt.getTime()).toFixed(1)},${yFor(point[rateType]).toFixed(1)}`).join(" ");
239
+ const latestX = xFor(rangeEnd);
232
240
  const latestY = yFor(metrics.latest[rateType]);
233
241
  const highPoint = metrics.points.reduce((best, point) => point[rateType] > best[rateType] ? point : best);
234
242
  const lowPoint = metrics.points.reduce((best, point) => point[rateType] < best[rateType] ? point : best);
235
- const highX = xFor(highPoint.publishedAt.getTime());
243
+ const highX = xFor(Math.max(highPoint.collectedAt.getTime(), rangeStart));
236
244
  const highY = yFor(highPoint[rateType]);
237
- const lowX = xFor(lowPoint.publishedAt.getTime());
245
+ const lowX = xFor(Math.max(lowPoint.collectedAt.getTime(), rangeStart));
238
246
  const lowY = yFor(lowPoint[rateType]);
239
247
  const change = metrics.change == null ? "暂无前日数据" : `${metrics.change >= 0 ? "+" : ""}${formatRate(metrics.change)} ${metrics.changePercent >= 0 ? "+" : ""}${metrics.changePercent.toFixed(2)}%`;
240
248
  const changeColor = metrics.change == null ? "#94a3b8" : metrics.change > 0 ? "#fb7185" : "#34d399";
241
249
  const ticks = Array.from({ length: 4 }, (_, index) => lower + (upper - lower) * index / 3);
242
- const middlePoint = metrics.points[Math.floor(metrics.points.length / 2)];
243
- const labels = [metrics.points[0], middlePoint, metrics.latest];
250
+ const labels = [
251
+ new Date(rangeStart),
252
+ new Date((rangeStart + rangeEnd) / 2),
253
+ new Date(rangeEnd)
254
+ ];
244
255
  const grid = ticks.map((value) => {
245
256
  const y = yFor(value);
246
257
  return `<line x1="${padding.left}" x2="${width - padding.right}" y1="${y}" y2="${y}" stroke="#26334a" stroke-width="1" />
@@ -248,7 +259,7 @@ async function renderTrendChart(metrics, rateType, options) {
248
259
  }).join("");
249
260
  const xLabels = labels.map((point, index) => {
250
261
  const anchor = index === 0 ? "start" : index === labels.length - 1 ? "end" : "middle";
251
- return `<text x="${xFor(point.publishedAt.getTime())}" y="${height - 30}" text-anchor="${anchor}" class="axis">${dateLabel(point.publishedAt)}</text>`;
262
+ return `<text x="${xFor(point.getTime())}" y="${height - 30}" text-anchor="${anchor}" class="axis">${dateLabel(point)}</text>`;
252
263
  }).join("");
253
264
  const title = `${BANK_LABELS[metrics.latest.bank]} · 日元${RATE_TYPE_LABELS[rateType]}走势`;
254
265
  const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">
@@ -392,11 +403,35 @@ function extendModel(ctx) {
392
403
  __name(extendModel, "extendModel");
393
404
 
394
405
  // src/providers/common.ts
406
+ var import_node_http = require("node:http");
395
407
  var BOC_SOURCE_URL = "https://www.boc.cn/sourcedb/whpj/index.html";
396
408
  var ICBC_SOURCE_URL = "http://papi.icbc.com.cn/exchanges/ns/getLatest";
397
- async function fetchText(url, timeoutMs, init = {}, retry = { attempts: 1, retryDelay: 0 }) {
409
+ function describeError(error) {
410
+ if (!(error instanceof Error)) return String(error);
411
+ const details = [`${error.name}: ${error.message}`];
412
+ const code = error.code;
413
+ if (code) details.push(`code=${code}`);
414
+ if (error.cause && error.cause !== error) details.push(`cause=${describeError(error.cause)}`);
415
+ return details.join(", ");
416
+ }
417
+ __name(describeError, "describeError");
418
+ async function withRetries(url, retry, operation) {
398
419
  let lastError;
399
420
  for (let attempt = 1; attempt <= retry.attempts; attempt++) {
421
+ try {
422
+ return await operation();
423
+ } catch (error) {
424
+ lastError = error;
425
+ }
426
+ if (attempt < retry.attempts) {
427
+ await new Promise((resolve) => setTimeout(resolve, retry.retryDelay * attempt));
428
+ }
429
+ }
430
+ throw new Error(`请求 ${url} 失败,已尝试 ${retry.attempts} 次:${describeError(lastError)}`);
431
+ }
432
+ __name(withRetries, "withRetries");
433
+ async function fetchText(url, timeoutMs, init = {}, retry = { attempts: 1, retryDelay: 0 }) {
434
+ return withRetries(url, retry, async () => {
400
435
  const controller = new AbortController();
401
436
  const timer = setTimeout(() => controller.abort(), timeoutMs);
402
437
  try {
@@ -405,19 +440,49 @@ async function fetchText(url, timeoutMs, init = {}, retry = { attempts: 1, retry
405
440
  throw new Error(`${response.status} ${response.statusText}`);
406
441
  }
407
442
  return await response.text();
408
- } catch (error) {
409
- lastError = error;
410
443
  } finally {
411
444
  clearTimeout(timer);
412
445
  }
413
- if (attempt < retry.attempts) {
414
- await new Promise((resolve) => setTimeout(resolve, retry.retryDelay * attempt));
415
- }
416
- }
417
- const reason = lastError instanceof Error ? `${lastError.name}: ${lastError.message}` : String(lastError);
418
- throw new Error(`请求 ${url} 失败,已尝试 ${retry.attempts} 次:${reason}`);
446
+ });
419
447
  }
420
448
  __name(fetchText, "fetchText");
449
+ function postJsonText(url, timeoutMs, retry, body = "{}") {
450
+ return withRetries(url, retry, () => new Promise((resolve, reject) => {
451
+ const endpoint = new URL(url);
452
+ const request = (0, import_node_http.request)({
453
+ protocol: endpoint.protocol,
454
+ hostname: endpoint.hostname,
455
+ port: endpoint.port || void 0,
456
+ method: "POST",
457
+ path: `${endpoint.pathname}${endpoint.search}`,
458
+ agent: false,
459
+ headers: {
460
+ "content-type": "application/json",
461
+ "content-length": Buffer.byteLength(body),
462
+ "connection": "close",
463
+ "user-agent": "koishi-plugin-rina-currency/0.1"
464
+ }
465
+ }, (response) => {
466
+ let responseBody = "";
467
+ response.setEncoding("utf8");
468
+ response.on("data", (chunk) => {
469
+ responseBody += chunk;
470
+ });
471
+ response.on("error", reject);
472
+ response.on("end", () => {
473
+ if (response.statusCode == null || response.statusCode < 200 || response.statusCode >= 300) {
474
+ reject(new Error(`${response.statusCode || 0} ${response.statusMessage || ""}`.trim()));
475
+ return;
476
+ }
477
+ resolve(responseBody);
478
+ });
479
+ });
480
+ request.setTimeout(timeoutMs, () => request.destroy(new Error(`请求超时(${timeoutMs}ms)`)));
481
+ request.on("error", reject);
482
+ request.end(body);
483
+ }));
484
+ }
485
+ __name(postJsonText, "postJsonText");
421
486
  function asRate(value, field) {
422
487
  const parsed = Number.parseFloat(String(value).trim());
423
488
  if (!Number.isFinite(parsed) || parsed <= 0) {
@@ -513,14 +578,10 @@ var IcbcProvider = class {
513
578
  }
514
579
  id = "icbc";
515
580
  async fetch() {
516
- const body = await fetchText(ICBC_SOURCE_URL, this.timeoutMs, {
517
- method: "POST",
518
- headers: {
519
- "content-type": "application/json",
520
- "user-agent": "koishi-plugin-rina-currency/0.1"
521
- },
522
- body: "{}"
523
- }, { attempts: this.attempts, retryDelay: this.retryDelay });
581
+ const body = await postJsonText(ICBC_SOURCE_URL, this.timeoutMs, {
582
+ attempts: this.attempts,
583
+ retryDelay: this.retryDelay
584
+ });
524
585
  return parseIcbcJpy(JSON.parse(body));
525
586
  }
526
587
  };
@@ -558,13 +619,56 @@ var Scheduler = class {
558
619
  __name(this, "Scheduler");
559
620
  }
560
621
  sentBroadcasts = /* @__PURE__ */ new Set();
622
+ lastCollectionSlot;
561
623
  start() {
562
624
  this.ctx.on("ready", async () => {
563
- if (this.config.collectOnStart) await this.collectAndAlert();
564
- this.ctx.setInterval(() => void this.collectAndAlert(), this.config.collectIntervalMinutes * 6e4);
625
+ const due = this.getDueCollection();
626
+ if (due) {
627
+ this.lastCollectionSlot = due.key;
628
+ await this.collectAndAlert({
629
+ recordUnchanged: due.isDailyAnchor,
630
+ collectedAt: due.at
631
+ });
632
+ } else if (this.config.collectOnStart) {
633
+ await this.collectAndAlert();
634
+ }
635
+ this.scheduleAlignedCollections();
565
636
  this.ctx.setInterval(() => void this.runBroadcasts(), 3e4);
566
637
  });
567
638
  }
639
+ /** Runs on China-time minute boundaries, with 17:00 as the daily anchor. */
640
+ scheduleAlignedCollections() {
641
+ const now = /* @__PURE__ */ new Date();
642
+ const delay = 6e4 - now.getSeconds() * 1e3 - now.getMilliseconds();
643
+ this.ctx.setTimeout(() => {
644
+ void this.collectIfDue();
645
+ this.ctx.setInterval(() => void this.collectIfDue(), 6e4);
646
+ }, delay);
647
+ }
648
+ getDueCollection(now = /* @__PURE__ */ new Date()) {
649
+ const clock = chinaClock(now);
650
+ const minutesSinceMidnight = clock.hour * 60 + clock.minute;
651
+ const dailyAnchor = 17 * 60;
652
+ const minutesSinceAnchor = minutesSinceMidnight >= dailyAnchor ? minutesSinceMidnight - dailyAnchor : minutesSinceMidnight + 24 * 60 - dailyAnchor;
653
+ const isDailyAnchor = minutesSinceMidnight === dailyAnchor;
654
+ if (!isDailyAnchor && minutesSinceAnchor % this.config.collectIntervalMinutes !== 0) return;
655
+ const at = new Date(now);
656
+ at.setSeconds(0, 0);
657
+ return {
658
+ key: `${clock.date}:${clock.hour}:${clock.minute}`,
659
+ at,
660
+ isDailyAnchor
661
+ };
662
+ }
663
+ async collectIfDue() {
664
+ const due = this.getDueCollection();
665
+ if (!due || due.key === this.lastCollectionSlot) return;
666
+ this.lastCollectionSlot = due.key;
667
+ await this.collectAndAlert({
668
+ recordUnchanged: due.isDailyAnchor,
669
+ collectedAt: due.at
670
+ });
671
+ }
568
672
  getBot(target) {
569
673
  return this.ctx.bots.find((bot) => bot.platform === target.platform && bot.selfId === target.selfId);
570
674
  }
@@ -577,9 +681,9 @@ var Scheduler = class {
577
681
  await bot.sendMessage(target.channelId, content);
578
682
  if (image) await bot.sendMessage(target.channelId, import_koishi3.h.image(image, "image/png"));
579
683
  }
580
- async collectAndAlert() {
684
+ async collectAndAlert(options = {}) {
581
685
  try {
582
- const result = await this.service.collect();
686
+ const result = await this.service.collect(options);
583
687
  await Promise.all(result.collected.map((item) => this.maybeAlert(item)));
584
688
  } catch (error) {
585
689
  this.logger.warn(`定时采集日元牌价失败:${String(error)}`);
@@ -646,10 +750,10 @@ function toQuote(record) {
646
750
  return { ...record };
647
751
  }
648
752
  __name(toQuote, "toQuote");
649
- function sortByPublishedAt(records) {
650
- return records.sort((left, right) => left.publishedAt.getTime() - right.publishedAt.getTime());
753
+ function sortByCollectedAt(records) {
754
+ return records.sort((left, right) => left.collectedAt.getTime() - right.collectedAt.getTime());
651
755
  }
652
- __name(sortByPublishedAt, "sortByPublishedAt");
756
+ __name(sortByCollectedAt, "sortByCollectedAt");
653
757
  var RateService = class {
654
758
  constructor(ctx, logger, providers) {
655
759
  this.ctx = ctx;
@@ -659,11 +763,12 @@ var RateService = class {
659
763
  static {
660
764
  __name(this, "RateService");
661
765
  }
662
- async collect() {
766
+ async collect(options = {}) {
663
767
  const settled = await Promise.allSettled(this.providers.map(async (provider) => {
664
768
  const previous = await this.getLatest(provider.id);
665
769
  const quote = await provider.fetch();
666
- if (previous?.publishedAt.getTime() === quote.publishedAt.getTime()) {
770
+ if (options.collectedAt) quote.collectedAt = options.collectedAt;
771
+ if (previous?.publishedAt.getTime() === quote.publishedAt.getTime() && !options.recordUnchanged) {
667
772
  return { quote: previous, previous, isNew: false };
668
773
  }
669
774
  await this.ctx.database.create("rina_currency_rate", quote);
@@ -685,7 +790,7 @@ var RateService = class {
685
790
  async getLatest(bank) {
686
791
  const rows = await this.ctx.database.get("rina_currency_rate", { bank, currency: "JPY" });
687
792
  if (!rows.length) return;
688
- return sortByPublishedAt(rows.map(toQuote)).at(-1);
793
+ return sortByCollectedAt(rows.map(toQuote)).at(-1);
689
794
  }
690
795
  async getLatestAll() {
691
796
  const entries = await Promise.all(["boc", "icbc"].map(async (bank) => [bank, await this.getLatest(bank)]));
@@ -698,18 +803,20 @@ var RateService = class {
698
803
  snapshot = await this.getLatestAll();
699
804
  return snapshot;
700
805
  }
701
- async getTrend(bank, rateType, days) {
702
- const since = new Date(Date.now() - days * 24 * 60 * 60 * 1e3);
806
+ async getTrend(bank, rateType, days, now = /* @__PURE__ */ new Date()) {
807
+ const since = new Date(now.getTime() - days * 24 * 60 * 60 * 1e3);
703
808
  const rows = await this.ctx.database.get("rina_currency_rate", {
704
809
  bank,
705
- currency: "JPY",
706
- publishedAt: { $gte: since }
810
+ currency: "JPY"
707
811
  });
708
- const points = sortByPublishedAt(rows.map(toQuote));
812
+ const history = sortByCollectedAt(rows.map(toQuote));
813
+ const prior = [...history].reverse().find((point) => point.collectedAt.getTime() < since.getTime());
814
+ const points = history.filter((point) => point.collectedAt.getTime() >= since.getTime());
815
+ if (prior) points.unshift(prior);
709
816
  if (!points.length) return;
710
817
  const latest = points.at(-1);
711
- const dayBefore = latest.publishedAt.getTime() - 24 * 60 * 60 * 1e3;
712
- const previous = [...points].reverse().find((point) => point.publishedAt.getTime() <= dayBefore);
818
+ const dayBefore = now.getTime() - 24 * 60 * 60 * 1e3;
819
+ const previous = [...history].reverse().find((point) => point.collectedAt.getTime() <= dayBefore);
713
820
  const values = points.map((point) => point[rateType]);
714
821
  const change = previous ? latest[rateType] - previous[rateType] : void 0;
715
822
  return {
@@ -719,7 +826,9 @@ var RateService = class {
719
826
  changePercent: change == null ? void 0 : change / previous[rateType] * 100,
720
827
  high: Math.max(...values),
721
828
  low: Math.min(...values),
722
- points
829
+ points,
830
+ rangeStart: since,
831
+ rangeEnd: now
723
832
  };
724
833
  }
725
834
  };
@@ -10,5 +10,11 @@ export interface RetryOptions {
10
10
  retryDelay: number;
11
11
  }
12
12
  export declare function fetchText(url: string, timeoutMs: number, init?: RequestInit, retry?: RetryOptions): Promise<string>;
13
+ /**
14
+ * ICBC's legacy public endpoint is plain HTTP. Keep this request on a fresh
15
+ * Node socket instead of the process-wide fetch pool, which can retain a
16
+ * connection that the upstream has already closed.
17
+ */
18
+ export declare function postJsonText(url: string, timeoutMs: number, retry: RetryOptions, body?: string): Promise<string>;
13
19
  export declare function asRate(value: unknown, field: string): number;
14
20
  export declare function chinaTime(date: string, time?: string): Date;
@@ -7,8 +7,13 @@ export declare class Scheduler {
7
7
  private service;
8
8
  private config;
9
9
  private sentBroadcasts;
10
+ private lastCollectionSlot?;
10
11
  constructor(ctx: Context, logger: Logger, service: RateService, config: Config);
11
12
  start(): void;
13
+ /** Runs on China-time minute boundaries, with 17:00 as the daily anchor. */
14
+ private scheduleAlignedCollections;
15
+ private getDueCollection;
16
+ private collectIfDue;
12
17
  private getBot;
13
18
  private send;
14
19
  private collectAndAlert;
package/lib/service.d.ts CHANGED
@@ -13,14 +13,20 @@ export interface CollectionResult {
13
13
  error: unknown;
14
14
  }>;
15
15
  }
16
+ export interface CollectOptions {
17
+ /** Store an unchanged quote as a scheduled confirmation point. */
18
+ recordUnchanged?: boolean;
19
+ /** The scheduler slot represented by this collection. */
20
+ collectedAt?: Date;
21
+ }
16
22
  export declare class RateService {
17
23
  private ctx;
18
24
  private logger;
19
25
  private providers;
20
26
  constructor(ctx: Context, logger: Logger, providers: RateProvider[]);
21
- collect(): Promise<CollectionResult>;
27
+ collect(options?: CollectOptions): Promise<CollectionResult>;
22
28
  getLatest(bank: BankId): Promise<ExchangeRateQuote | undefined>;
23
29
  getLatestAll(): Promise<Partial<Record<BankId, ExchangeRateQuote>>>;
24
30
  ensureSnapshot(): Promise<Partial<Record<BankId, ExchangeRateQuote>>>;
25
- getTrend(bank: BankId, rateType: RateType, days: number): Promise<TrendMetrics | undefined>;
31
+ getTrend(bank: BankId, rateType: RateType, days: number, now?: Date): Promise<TrendMetrics | undefined>;
26
32
  }
package/lib/types.d.ts CHANGED
@@ -21,6 +21,8 @@ export interface TrendMetrics {
21
21
  high: number;
22
22
  low: number;
23
23
  points: ExchangeRateQuote[];
24
+ rangeStart: Date;
25
+ rangeEnd: Date;
24
26
  }
25
27
  export declare const BANK_LABELS: Record<BankId, string>;
26
28
  export declare const RATE_TYPE_LABELS: Record<RateType, string>;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "koishi-plugin-rina-currency",
3
3
  "description": "面向购汇决策的日元汇率插件,基于中行和工行数据",
4
- "version": "0.0.2",
4
+ "version": "0.0.4",
5
5
  "main": "lib/index.js",
6
6
  "typings": "lib/index.d.ts",
7
7
  "files": [
package/readme.md CHANGED
@@ -30,7 +30,7 @@ plugins:
30
30
 
31
31
  ## 采集和来源
32
32
 
33
- 插件启动时可立即采集,之后默认每 60 分钟采集一次。查询优先读取 Koishi 数据库中的历史记录,只有历史库为空时才会补采集一次。
33
+ 插件启动时可立即采集,之后按北京时间以每日 17:00 为基准、按 `collectIntervalMinutes` 分钟间隔采集,不受插件启动时刻影响。趋势图按采样时间绘制并始终延伸至查询当下;周末等未更新时会保持水平线。若每日 17:00 的牌价与上一次相同,仍会保存一条确认采样点,表示此前一天内牌价未变。
34
34
 
35
35
  - 中国银行:公开外汇牌价页面(HTML 表格)
36
36
  - 中国工商银行:公开最新牌价接口(JSON)