feat: add async SQLite on Node 24 and improve messaging diagnostics (#520)
Move database work off the main thread on Node.js 24 and improve message handling and runtime diagnostics. Preserve migration, restart, and concurrency coverage with the async SQLite driver.
This commit is contained in:
1 parent
20f48d11ec
commit
c7428363cb
170 files changed
+7748
-3913
No files matched your search
@@ -1,19 +1,137 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { ImageUrlResolver } from '../event-converter';
|
||||
import type { MediaStore } from '../media-store';
|
||||
import type { CachedImage, MediaStore } from '../media-store';
|
||||
import type { MessageStore } from '../message-store';
|
||||
import type { OneBotInstanceContext } from '../instance-context';
|
||||
import { resolveRemoteMediaUrl } from '../media-url-resolver';
|
||||
import { segmentsToRawMessage } from '../helper/cq';
|
||||
import {
|
||||
deliverPttTransText,
|
||||
failPttTransWaiter,
|
||||
pttTransKey,
|
||||
waitPttTransText,
|
||||
} from './ptt-trans-waiter';
|
||||
import type { JsonObject } from '../types';
|
||||
import type { JsonObject, JsonValue } from '../types';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
type StoredMediaSegment = JsonObject & { type: 'image' | 'record' | 'video'; data: JsonObject };
|
||||
|
||||
function isStoredMediaSegment(segment: JsonValue): segment is StoredMediaSegment {
|
||||
return (
|
||||
segment !== null &&
|
||||
typeof segment === 'object' &&
|
||||
!Array.isArray(segment) &&
|
||||
(segment.type === 'image' || segment.type === 'record' || segment.type === 'video') &&
|
||||
segment.data !== null &&
|
||||
typeof segment.data === 'object' &&
|
||||
!Array.isArray(segment.data)
|
||||
);
|
||||
}
|
||||
|
||||
export async function refreshMessageMedia(
|
||||
ref: Pick<OneBotInstanceContext, 'bridge' | 'messageStore' | 'mediaStore' | 'converterCtx'>,
|
||||
messageId: number,
|
||||
event: JsonObject,
|
||||
): Promise<void> {
|
||||
if (!Array.isArray(event.message)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const segments = event.message.filter(isStoredMediaSegment);
|
||||
const voiceVideoSegments = segments.filter((segment) => segment.type !== 'image');
|
||||
const media =
|
||||
voiceVideoSegments.length > 0
|
||||
? (await ref.messageStore.findMedia(messageId))?.filter(
|
||||
(element) => element.type !== 'image',
|
||||
)
|
||||
: null;
|
||||
const meta = voiceVideoSegments.length > 0 ? await ref.messageStore.findMeta(messageId) : null;
|
||||
// Validate the ordered association once; a filename lookup can select another upload.
|
||||
const voiceVideo =
|
||||
meta &&
|
||||
media &&
|
||||
media.length === voiceVideoSegments.length &&
|
||||
media.every((element, index) => element.type === voiceVideoSegments[index]!.type)
|
||||
? { media, meta }
|
||||
: null;
|
||||
|
||||
if (voiceVideoSegments.length > 0 && !voiceVideo) {
|
||||
log.warn('[get_msg] media metadata missing or inconsistent message_id=%d', messageId);
|
||||
}
|
||||
|
||||
let voiceVideoIndex = 0;
|
||||
let changed = false;
|
||||
|
||||
for (const [index, segment] of segments.entries()) {
|
||||
try {
|
||||
let url: string | null;
|
||||
|
||||
if (segment.type === 'image') {
|
||||
const file =
|
||||
typeof segment.data.file === 'string'
|
||||
? segment.data.file
|
||||
: segment.data.file_id;
|
||||
|
||||
if (typeof file !== 'string' || !file) {
|
||||
continue;
|
||||
}
|
||||
|
||||
url = await resolveImageUrl(
|
||||
await ref.mediaStore.findImage(file),
|
||||
ref.converterCtx.imageUrlResolver,
|
||||
);
|
||||
} else {
|
||||
if (!voiceVideo) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const element = voiceVideo.media[voiceVideoIndex++]!;
|
||||
url = await resolveRemoteMediaUrl(
|
||||
ref.bridge,
|
||||
element.type,
|
||||
element.mediaNode,
|
||||
voiceVideo.meta.isGroup,
|
||||
voiceVideo.meta.targetId,
|
||||
);
|
||||
}
|
||||
|
||||
if (url && url !== segment.data.url) {
|
||||
segment.data.url = url;
|
||||
changed = true;
|
||||
}
|
||||
} catch (err) {
|
||||
// Refresh failure preserves this message's URL, never a different cached URL.
|
||||
log.warn(
|
||||
'[get_msg] media URL refresh failed message_id=%d type=%s media_index=%d: %s',
|
||||
messageId,
|
||||
segment.type,
|
||||
index,
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
event.raw_message = segmentsToRawMessage(event.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveImageUrl(
|
||||
cached: CachedImage | null,
|
||||
resolver?: ImageUrlResolver | null,
|
||||
): Promise<string | null> {
|
||||
if (!cached?.imageUrl || !resolver) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return resolver(
|
||||
{ type: 'image', imageUrl: cached.imageUrl, subType: cached.subType },
|
||||
cached.isGroup,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Voice-to-text for a received ptt (issue #79 / NapCat `fetch_ptt_text`).
|
||||
* Resolves the message's `record` segment to its cached fingerprint
|
||||
@@ -27,7 +145,7 @@ export async function fetchPttText(
|
||||
selfId: number,
|
||||
messageId: number,
|
||||
): Promise<{ text: string }> {
|
||||
const event = messageStore.findEvent(messageId);
|
||||
const event = await messageStore.findEvent(messageId);
|
||||
|
||||
if (!event) {
|
||||
throw new Error('消息不存在或已被撤回');
|
||||
@@ -59,16 +177,16 @@ export async function fetchPttText(
|
||||
throw new Error('消息中不包含语音');
|
||||
}
|
||||
|
||||
const snapshot = messageStore
|
||||
.findMedia(messageId)
|
||||
?.find((element) => element.type === 'record');
|
||||
const snapshot = (await messageStore.findMedia(messageId))?.find(
|
||||
(element) => element.type === 'record',
|
||||
);
|
||||
const cached = snapshot
|
||||
? {
|
||||
...snapshot,
|
||||
isGroup: event.message_type === 'group',
|
||||
sessionId: Number(event.group_id) || selfId,
|
||||
}
|
||||
: mediaStore.findRecord(file, 'legacy');
|
||||
: await mediaStore.findRecord(file, 'legacy');
|
||||
|
||||
if (!cached) {
|
||||
throw new Error('语音不在缓存中,无法转写');
|
||||
@@ -114,7 +232,7 @@ export async function getImageInfo(
|
||||
file: string,
|
||||
imageUrlResolver?: ImageUrlResolver | null,
|
||||
): Promise<JsonObject | null> {
|
||||
const cached = mediaStore.findImage(file);
|
||||
const cached = await mediaStore.findImage(file);
|
||||
|
||||
if (!cached) {
|
||||
return null;
|
||||
@@ -122,27 +240,17 @@ export async function getImageInfo(
|
||||
|
||||
let url = cached.url || cached.imageUrl || '';
|
||||
|
||||
// Re-sign with a current rkey at lookup time. The stored `url` was signed
|
||||
// when the message first arrived and its rkey may have since expired — the
|
||||
// CDN then rejects the download with
|
||||
// `{"retcode":-5503010,"retmsg":"invalid rkey"}`. Resolving from the raw
|
||||
// (unsigned) `imageUrl` mints a fresh rkey, mirroring NapCat which
|
||||
// re-signs on every getImageUrl call instead of handing back a baked URL.
|
||||
if (imageUrlResolver && cached.imageUrl) {
|
||||
try {
|
||||
const element: MessageElement = {
|
||||
type: 'image',
|
||||
imageUrl: cached.imageUrl,
|
||||
subType: cached.subType,
|
||||
};
|
||||
const fresh = await imageUrlResolver(element, cached.isGroup);
|
||||
try {
|
||||
const fresh = await resolveImageUrl(cached, imageUrlResolver);
|
||||
|
||||
if (fresh) {
|
||||
url = fresh;
|
||||
}
|
||||
} catch {
|
||||
// Best-effort: fall back to the stored URL on any resolver failure.
|
||||
if (fresh) {
|
||||
url = fresh;
|
||||
}
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
'get_image URL refresh failed: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -158,34 +266,23 @@ export async function getRecordInfo(
|
||||
mediaStore: MediaStore,
|
||||
file: string,
|
||||
): Promise<JsonObject | null> {
|
||||
const cached = mediaStore.findRecord(file);
|
||||
const cached = await mediaStore.findRecord(file);
|
||||
|
||||
if (!cached) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let url = cached.url;
|
||||
|
||||
if (!url && cached.mediaNode) {
|
||||
try {
|
||||
url = cached.isGroup
|
||||
? await bridge.apis.groupFile.getPttUrl(cached.sessionId, cached.mediaNode)
|
||||
: await bridge.apis.groupFile.getPrivatePttUrl(cached.mediaNode);
|
||||
|
||||
if (url) {
|
||||
mediaStore.updateRecordUrl(file, url);
|
||||
}
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
'get_record url refetch failed: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const url = await resolveRemoteMediaUrl(
|
||||
bridge,
|
||||
'record',
|
||||
cached.mediaNode,
|
||||
cached.isGroup,
|
||||
cached.sessionId,
|
||||
);
|
||||
await mediaStore.updateRecordUrl(file, url);
|
||||
return {
|
||||
file: url || cached.file,
|
||||
url: url || '',
|
||||
file: url,
|
||||
url,
|
||||
file_size: String(cached.fileSize ?? 0),
|
||||
file_name: cached.fileName || cached.file,
|
||||
};
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { mapWithConcurrency } from '@snowluma/common/concurrency';
|
||||
import { isMessageMedia, type MessageMedia } from '../message-media';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
@@ -26,6 +27,7 @@ import {
|
||||
} from '../message-parser';
|
||||
import type { MessageStore } from '../message-store';
|
||||
import { sameSelfSentMessage } from '../self-sent-event';
|
||||
import { replyPreviewElements } from '../reply-preview';
|
||||
import {
|
||||
hasAuthoritativeSequence,
|
||||
type JsonArray,
|
||||
@@ -36,49 +38,6 @@ import {
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
function replyPreviewElements(message: unknown): MessageElement[] {
|
||||
if (!Array.isArray(message)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const labels: Record<string, string> = {
|
||||
image: '[图片]',
|
||||
record: '[语音]',
|
||||
video: '[视频]',
|
||||
file: '[文件]',
|
||||
face: '[表情]',
|
||||
mface: '[表情]',
|
||||
forward: '[聊天记录]',
|
||||
json: '[卡片]',
|
||||
xml: '[卡片]',
|
||||
markdown: '[Markdown]',
|
||||
};
|
||||
const parts: string[] = [];
|
||||
|
||||
for (const segment of message) {
|
||||
if (!segment || typeof segment !== 'object') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const data = segment.data;
|
||||
|
||||
if (!data || typeof data !== 'object') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (segment.type === 'text' && typeof data.text === 'string') {
|
||||
parts.push(data.text);
|
||||
} else if (segment.type === 'at') {
|
||||
parts.push(data.qq === 'all' ? '@全体成员' : `@${data.qq ?? ''}`);
|
||||
} else if (typeof segment.type === 'string' && labels[segment.type]) {
|
||||
parts.push(labels[segment.type]);
|
||||
}
|
||||
}
|
||||
|
||||
const text = parts.join('');
|
||||
return text ? [{ type: 'text', text }] : [];
|
||||
}
|
||||
|
||||
// A video larger than QQ's Highway video ceiling can't be sent through the
|
||||
// element pipeline — it must fall back to a regular file upload. The fallback
|
||||
// is decided at the OneBot layer (not element-builder) because building a
|
||||
@@ -167,7 +126,7 @@ export async function getGroupMsgHistory(
|
||||
let anchorSequence: number | undefined;
|
||||
|
||||
if (hasAnchor) {
|
||||
const meta = messageStore.findMeta(messageId as number);
|
||||
const meta = await messageStore.findMeta(messageId as number);
|
||||
|
||||
if (!hasAuthoritativeSequence(meta) || !meta.isGroup || meta.targetId !== groupId) {
|
||||
return [];
|
||||
@@ -176,7 +135,7 @@ export async function getGroupMsgHistory(
|
||||
anchorSequence = meta.sequence;
|
||||
}
|
||||
|
||||
const events = messageStore.listSessionEvents(
|
||||
const events = await messageStore.listSessionEvents(
|
||||
true,
|
||||
groupId,
|
||||
limit,
|
||||
@@ -212,7 +171,7 @@ export async function getFriendMsgHistory(
|
||||
let anchorSequence: number | undefined;
|
||||
|
||||
if (hasAnchor) {
|
||||
const meta = messageStore.findMeta(messageId as number);
|
||||
const meta = await messageStore.findMeta(messageId as number);
|
||||
|
||||
if (!hasAuthoritativeSequence(meta) || meta.isGroup || meta.targetId !== userId) {
|
||||
return [];
|
||||
@@ -221,7 +180,7 @@ export async function getFriendMsgHistory(
|
||||
anchorSequence = meta.sequence;
|
||||
}
|
||||
|
||||
const events = messageStore.listSessionEvents(
|
||||
const events = await messageStore.listSessionEvents(
|
||||
false,
|
||||
userId,
|
||||
limit,
|
||||
@@ -272,7 +231,7 @@ export async function getGroupHistory(
|
||||
let anchorSeq = 0;
|
||||
|
||||
if (hasAnchor) {
|
||||
const meta = ref.messageStore.findMeta(messageId as number);
|
||||
const meta = await ref.messageStore.findMeta(messageId as number);
|
||||
|
||||
if (!hasAuthoritativeSequence(meta) || !meta.isGroup || meta.targetId !== groupId) {
|
||||
// Anchor we don't know — best effort from the local store.
|
||||
@@ -281,7 +240,7 @@ export async function getGroupHistory(
|
||||
|
||||
anchorSeq = meta.sequence;
|
||||
} else {
|
||||
anchorSeq = ref.messageStore.findLatestAuthoritativeSequence(true, groupId) ?? 0;
|
||||
anchorSeq = (await ref.messageStore.findLatestAuthoritativeSequence(true, groupId)) ?? 0;
|
||||
}
|
||||
|
||||
log.debug(
|
||||
@@ -309,7 +268,7 @@ export async function getGroupHistory(
|
||||
continue;
|
||||
}
|
||||
|
||||
persistHistoryEvent(ref.messageStore, json); // full event → reply/get_msg + future listing
|
||||
await persistHistoryEvent(ref.messageStore, json); // full event → reply/get_msg + future listing
|
||||
out.push(sanitizeMessageEventForApi(json)); // sanitized for the API (matches the local path)
|
||||
}
|
||||
|
||||
@@ -365,13 +324,15 @@ export async function getFriendHistory(
|
||||
let anchorSeq = 0;
|
||||
|
||||
if (hasAnchor) {
|
||||
const meta = ref.messageStore.findMeta(messageId as number);
|
||||
const meta = await ref.messageStore.findMeta(messageId as number);
|
||||
// Older self-sent rows may be keyed by selfId. Only accept one of those
|
||||
// when its stored target_id proves that it belongs to this peer; otherwise
|
||||
// a message_id from another private conversation could select the wrong
|
||||
// server sequence.
|
||||
const storedEvent =
|
||||
meta?.targetId === ref.selfId ? ref.messageStore.findEvent(messageId as number) : null;
|
||||
meta?.targetId === ref.selfId
|
||||
? await ref.messageStore.findEvent(messageId as number)
|
||||
: null;
|
||||
const belongsToPeer =
|
||||
meta?.targetId === userId ||
|
||||
(meta?.targetId === ref.selfId && toHistoryInt(storedEvent?.target_id) === userId);
|
||||
@@ -422,11 +383,15 @@ export async function getFriendHistory(
|
||||
continue;
|
||||
}
|
||||
|
||||
// Conversion can await media resolution, so consult the tombstone only
|
||||
// after it settles. From this check through persistence/return there is no
|
||||
// async gap in which a recall could race past us.
|
||||
// Conversion can await media resolution, so check again after it settles.
|
||||
// Persistence also checks recalls queued while this lookup is in flight.
|
||||
if (
|
||||
ref.messageStore.isPrivateMessageRecalled(userId, clientSequence, sentBySelf, ev.time)
|
||||
await ref.messageStore.isPrivateMessageRecalled(
|
||||
userId,
|
||||
clientSequence,
|
||||
sentBySelf,
|
||||
ev.time,
|
||||
)
|
||||
) {
|
||||
log.debug(
|
||||
'friend history omitted recalled message: user=%d clientSeq=%d self=%s',
|
||||
@@ -443,8 +408,9 @@ export async function getFriendHistory(
|
||||
json.target_id = userId;
|
||||
}
|
||||
|
||||
persistHistoryEvent(ref.messageStore, json, userId, ev);
|
||||
out.push(sanitizeMessageEventForApi(json));
|
||||
if (await persistHistoryEvent(ref.messageStore, json, userId, ev)) {
|
||||
out.push(sanitizeMessageEventForApi(json));
|
||||
}
|
||||
}
|
||||
|
||||
log.debug(
|
||||
@@ -505,7 +471,7 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
|
||||
const eventName = isGroup
|
||||
? GROUP_MESSAGE_EVENT
|
||||
: privateMessageEventName(quotedSender === ref.selfId, false);
|
||||
const resolvedId = ref.converterCtx.messageIdResolver?.(
|
||||
const resolvedId = await ref.converterCtx.messageIdResolver?.(
|
||||
isGroup,
|
||||
session,
|
||||
replySeq,
|
||||
@@ -517,7 +483,7 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
|
||||
? (resolvedId as number)
|
||||
: hashMessageIdInt32(replySeq, session, eventName);
|
||||
|
||||
if (ref.messageStore.findEvent(targetId)) {
|
||||
if (await ref.messageStore.findEvent(targetId)) {
|
||||
return;
|
||||
} // Tier 0: already have the full event
|
||||
|
||||
@@ -568,12 +534,19 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
|
||||
json.message_id = targetId;
|
||||
|
||||
if (fetched.kind === 'group_message') {
|
||||
ref.messageStore.storeEvent(targetId, true, session, replySeq, eventName, json);
|
||||
await ref.messageStore.storeEvent(
|
||||
targetId,
|
||||
true,
|
||||
session,
|
||||
replySeq,
|
||||
eventName,
|
||||
json,
|
||||
);
|
||||
} else {
|
||||
const serverSequence = fetched.ntMsgSeq ?? 0;
|
||||
const sequenceAuthoritative =
|
||||
fetched.sequenceAuthoritative !== false && serverSequence > 0;
|
||||
ref.messageStore.storeMeta(targetId, {
|
||||
await ref.messageStore.storeMeta(targetId, {
|
||||
isGroup: false,
|
||||
targetId: session,
|
||||
sequence: serverSequence,
|
||||
@@ -585,16 +558,14 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
|
||||
random: fetched.msgId,
|
||||
timestamp: fetched.time,
|
||||
});
|
||||
ref.messageStore.storeEvent(
|
||||
await ref.messageStore.storeEvent(
|
||||
targetId,
|
||||
false,
|
||||
session,
|
||||
serverSequence,
|
||||
eventName,
|
||||
json,
|
||||
{
|
||||
sequenceAuthoritative,
|
||||
},
|
||||
{ sequenceAuthoritative },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -632,9 +603,15 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
|
||||
// Inline quote metadata proves what was displayed, but not that replySeq
|
||||
// still names a server-backed roam message. Keep it queryable via
|
||||
// get_msg without letting it become a history/recall/reply anchor.
|
||||
ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, fallback, {
|
||||
sequenceAuthoritative: false,
|
||||
});
|
||||
await ref.messageStore.storeEvent(
|
||||
targetId,
|
||||
isGroup,
|
||||
session,
|
||||
replySeq,
|
||||
eventName,
|
||||
fallback,
|
||||
{ sequenceAuthoritative: false },
|
||||
);
|
||||
return;
|
||||
} catch (err) {
|
||||
log.warn(
|
||||
@@ -657,9 +634,15 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
|
||||
isGroup,
|
||||
session,
|
||||
);
|
||||
ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, placeholder, {
|
||||
sequenceAuthoritative: false,
|
||||
});
|
||||
await ref.messageStore.storeEvent(
|
||||
targetId,
|
||||
isGroup,
|
||||
session,
|
||||
replySeq,
|
||||
eventName,
|
||||
placeholder,
|
||||
{ sequenceAuthoritative: false },
|
||||
);
|
||||
}
|
||||
|
||||
// Build a stored-message event for a backfilled reply target (Tier 2/3).
|
||||
@@ -743,7 +726,7 @@ export async function setEssenceMessage(
|
||||
messageId: number,
|
||||
enable: boolean,
|
||||
): Promise<void> {
|
||||
const meta = messageStore.findMeta(messageId);
|
||||
const meta = await messageStore.findMeta(messageId);
|
||||
|
||||
if (!meta || !meta.isGroup) {
|
||||
throw new Error('message not found or not a group message');
|
||||
@@ -757,30 +740,9 @@ export async function setEssenceMessage(
|
||||
}
|
||||
|
||||
/**
|
||||
* Build + store a synthetic OneBot event for a just-sent message so
|
||||
* `/get_msg` can find it.
|
||||
*
|
||||
* The QQ server doesn't always echo self-sent messages back on the
|
||||
* receive channel — Lagrange and NapCat both work around this by
|
||||
* writing a local copy at send time (Lagrange persists into Realm DB
|
||||
* inside `SendMessageOperation`; NapCat caches in-memory via its msg
|
||||
* service). Without it, callers that hit `/get_msg` with a freshly-
|
||||
* returned `message_id` get "message not found" even though the recall
|
||||
* path works fine (recall uses the lighter `cacheMessageMeta` already).
|
||||
*
|
||||
* Stored event has `post_type: 'message_sent'` so OneBot clients that
|
||||
* inspect it through `/get_msg` can distinguish their own outbound
|
||||
* messages from incoming ones.
|
||||
*/
|
||||
/**
|
||||
* The shared "record a self-sent message" tail: derive the OneBot message id
|
||||
* from (sequence, target, event), then cache both the meta and the self-sent
|
||||
* copy. Centralizes the `isGroup ↔ eventName ↔ hashMessageIdInt32 event
|
||||
* constant` coupling that was hand-paired in six send/forward paths — a
|
||||
* mismatch there silently produced a wrong message_id or wrong event
|
||||
* attribution. Returns the derived message id and, for an eligible plain C2C
|
||||
* Action send, an event for the OneBot dispatch path when QQ has not already
|
||||
* supplied the canonical echo.
|
||||
* Derive the same message id for send/receive paths and persist the sent
|
||||
* message for get_msg, since QQ does not always echo it. Eligible C2C sends
|
||||
* also return a message_sent event when no canonical echo has arrived.
|
||||
*/
|
||||
async function finalizeSend(
|
||||
ref: OneBotInstanceContext,
|
||||
@@ -810,7 +772,7 @@ async function finalizeSend(
|
||||
: Number.isInteger(opaqueMessageId) && opaqueMessageId !== 0
|
||||
? opaqueMessageId
|
||||
: hashMessageIdInt32(isGroup ? 0 : receipt.clientSequence, targetId, eventName);
|
||||
ref.cacheMessageMeta(messageId, {
|
||||
await ref.cacheMessageMeta(messageId, {
|
||||
isGroup,
|
||||
targetId,
|
||||
sequence: receipt.sequence,
|
||||
@@ -865,35 +827,16 @@ async function cacheSelfSentMessage(
|
||||
elements,
|
||||
} = options;
|
||||
|
||||
if (!Number.isInteger(messageId) || messageId === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Defensive: tests may mock `ref.messageStore` without the full MessageStore
|
||||
// surface. Production always has it. Without storage, recall still works via
|
||||
// cacheMessageMeta, but `/get_msg` and the synthetic event are unavailable.
|
||||
const storeEvent = (ref.messageStore as { storeEvent?: typeof ref.messageStore.storeEvent })
|
||||
.storeEvent;
|
||||
|
||||
if (typeof storeEvent !== 'function') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
// We deliberately pass no URL resolvers — for a synthetic self-sent
|
||||
// event the file/url fields in segments are best-effort (they're
|
||||
// already what the OneBot caller passed in). Image/video URLs would
|
||||
// need a real resolver to render in `/get_msg`, but the existing
|
||||
// resolver is async and bound to the receive pipeline; skipping it
|
||||
// means /get_msg returns the segment with the original `file` path
|
||||
// and an empty `url`, which is what Lagrange does too.
|
||||
// Persist upload metadata without another QQ request on the send path.
|
||||
// get_msg / get_record resolve remote media URLs when the consumer reads.
|
||||
const segments = (await elementsToOneBotSegments(
|
||||
{
|
||||
selfId: ref.selfId,
|
||||
imageUrlResolver: null,
|
||||
mediaUrlResolver: null,
|
||||
messageIdResolver: null,
|
||||
mediaSegmentSink: null,
|
||||
mediaSegmentSink: ref.converterCtx.mediaSegmentSink,
|
||||
},
|
||||
elements,
|
||||
isGroup,
|
||||
@@ -939,7 +882,7 @@ async function cacheSelfSentMessage(
|
||||
// QQ can win the race between the send receipt and local event
|
||||
// construction. Keep its richer canonical event and let the already-run
|
||||
// bridge dispatch remain the single downstream notification.
|
||||
const existing = ref.messageStore.findEvent(messageId);
|
||||
const existing = await ref.messageStore.findEvent(messageId);
|
||||
|
||||
if (existing && sameSelfSentMessage(existing, event)) {
|
||||
return null;
|
||||
@@ -947,17 +890,14 @@ async function cacheSelfSentMessage(
|
||||
|
||||
// Persist before dispatch so `/get_msg` is immediately consistent for a
|
||||
// client reacting to the synthetic message_sent notification.
|
||||
storeEvent.call(
|
||||
ref.messageStore,
|
||||
await ref.messageStore.storeEvent(
|
||||
messageId,
|
||||
isGroup,
|
||||
sessionId,
|
||||
sequence,
|
||||
eventName,
|
||||
event,
|
||||
{
|
||||
sequenceAuthoritative,
|
||||
},
|
||||
{ sequenceAuthoritative },
|
||||
);
|
||||
return event;
|
||||
} catch (err) {
|
||||
@@ -999,7 +939,7 @@ export async function sendPrivateMessage(
|
||||
/** When set, reply into this group's temp session instead of friend c2c. */
|
||||
tempGroupId?: number,
|
||||
/** Reports each actual friend message as soon as its authoritative receipt arrives. */
|
||||
onSelfSent?: (event: JsonObject) => void,
|
||||
onSelfSent?: (event: JsonObject) => void | Promise<void>,
|
||||
): Promise<MessageSendResult> {
|
||||
// A temp-session reply is only allowed into a session the peer opened.
|
||||
const isTempReply = tempGroupId !== undefined && ref.tempSessions.has(userId, tempGroupId);
|
||||
@@ -1030,10 +970,10 @@ export async function sendPrivateMessage(
|
||||
}
|
||||
|
||||
const elements = await parseMessage(message, autoEscape, {
|
||||
resolveReplySequence: (replyMessageId) => {
|
||||
return ref.messageStore.resolveReplySequence(false, userId, replyMessageId);
|
||||
resolveReplySequence: async (replyMessageId) => {
|
||||
return await ref.messageStore.resolveReplySequence(false, userId, replyMessageId);
|
||||
},
|
||||
resolveReplyMeta: (replyMessageId) => {
|
||||
resolveReplyMeta: async (replyMessageId) => {
|
||||
// Prefer the cached event (it carries the REAL sender). When only
|
||||
// meta exists — typically because the message we're replying to was
|
||||
// sent by the bot itself and never round-tripped through dispatch
|
||||
@@ -1041,7 +981,7 @@ export async function sendPrivateMessage(
|
||||
// selfId. The previous code used `meta.targetId` here, which is the
|
||||
// conversation PEER and shows the wrong "回复 @某人" in QQ for any
|
||||
// self-reply.
|
||||
const event = ref.messageStore.findEvent(replyMessageId);
|
||||
const event = await ref.messageStore.findEvent(replyMessageId);
|
||||
|
||||
if (event) {
|
||||
const senderUin =
|
||||
@@ -1052,7 +992,7 @@ export async function sendPrivateMessage(
|
||||
typeof event.time === 'number'
|
||||
? event.time
|
||||
: parseInt(String(event.time || '0'), 10);
|
||||
const meta = ref.messageStore.findMeta(replyMessageId);
|
||||
const meta = await ref.messageStore.findMeta(replyMessageId);
|
||||
return {
|
||||
senderUin,
|
||||
time,
|
||||
@@ -1062,7 +1002,7 @@ export async function sendPrivateMessage(
|
||||
};
|
||||
}
|
||||
|
||||
const meta = ref.messageStore.findMeta(replyMessageId);
|
||||
const meta = await ref.messageStore.findMeta(replyMessageId);
|
||||
|
||||
if (meta) {
|
||||
return {
|
||||
@@ -1209,7 +1149,7 @@ export async function sendPrivateMessage(
|
||||
lastResult = result;
|
||||
|
||||
if (result.echoEvent) {
|
||||
onSelfSent?.(result.echoEvent);
|
||||
await onSelfSent?.(result.echoEvent);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1346,17 +1286,17 @@ export async function sendGroupMessage(
|
||||
}
|
||||
|
||||
const elements = await parseMessage(message, autoEscape, {
|
||||
resolveReplySequence: (replyMessageId) => {
|
||||
return ref.messageStore.resolveReplySequence(true, groupId, replyMessageId);
|
||||
resolveReplySequence: async (replyMessageId) => {
|
||||
return await ref.messageStore.resolveReplySequence(true, groupId, replyMessageId);
|
||||
},
|
||||
resolveReplyMeta: (replyMessageId) => {
|
||||
const meta = ref.messageStore.findMeta(replyMessageId);
|
||||
resolveReplyMeta: async (replyMessageId) => {
|
||||
const meta = await ref.messageStore.findMeta(replyMessageId);
|
||||
|
||||
if (!meta || !meta.isGroup || meta.targetId !== groupId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const event = ref.messageStore.findEvent(replyMessageId);
|
||||
const event = await ref.messageStore.findEvent(replyMessageId);
|
||||
|
||||
if (event) {
|
||||
return {
|
||||
@@ -1527,7 +1467,7 @@ export async function sendPrivateForwardMessage(
|
||||
userId: number,
|
||||
messages: JsonValue,
|
||||
meta?: ForwardPreviewMeta,
|
||||
onSelfSent?: (event: JsonObject) => void,
|
||||
onSelfSent?: (event: JsonObject) => void | Promise<void>,
|
||||
): Promise<{ messageId: number; forwardId: string }> {
|
||||
const nodes = await parseForwardNodes(ref, messages, { userId });
|
||||
// userId is plumbed through so inner image/record/video can be uploaded
|
||||
@@ -1546,7 +1486,7 @@ export async function sendPrivateForwardMessage(
|
||||
);
|
||||
|
||||
if (result.echoEvent) {
|
||||
onSelfSent?.(result.echoEvent);
|
||||
await onSelfSent?.(result.echoEvent);
|
||||
}
|
||||
|
||||
return { messageId: result.messageId, forwardId };
|
||||
@@ -1577,13 +1517,13 @@ export async function forwardSingleMessage(
|
||||
ref: OneBotInstanceContext,
|
||||
messageId: number,
|
||||
target: { groupId?: number; userId?: number },
|
||||
onSelfSent?: (event: JsonObject) => void,
|
||||
onSelfSent?: (event: JsonObject) => void | Promise<void>,
|
||||
): Promise<{ messageId: number }> {
|
||||
if (!target.groupId && !target.userId) {
|
||||
throw new Error('forward target group_id or user_id is required');
|
||||
}
|
||||
|
||||
const event = ref.messageStore.findEvent(messageId);
|
||||
const event = await ref.messageStore.findEvent(messageId);
|
||||
|
||||
if (!event) {
|
||||
throw new Error(`message not found: ${messageId}`);
|
||||
@@ -1599,7 +1539,7 @@ export async function forwardSingleMessage(
|
||||
|
||||
const elements = await prepareSingleForwardElements(
|
||||
ref,
|
||||
restoreHistoricalMedia(ref, parsed, messageId),
|
||||
await restoreHistoricalMedia(ref, parsed, messageId),
|
||||
target,
|
||||
);
|
||||
|
||||
@@ -1628,7 +1568,7 @@ export async function forwardSingleMessage(
|
||||
messageIdOut = result.messageId;
|
||||
|
||||
if (result.echoEvent) {
|
||||
onSelfSent?.(result.echoEvent);
|
||||
await onSelfSent?.(result.echoEvent);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1644,7 +1584,7 @@ async function prepareSingleForwardElements(
|
||||
|
||||
for (const element of elements) {
|
||||
if (element.type !== 'forward') {
|
||||
out.push(isMessageMedia(element) ? element : enrichForForward(ref, element));
|
||||
out.push(isMessageMedia(element) ? element : await enrichForForward(ref, element));
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1710,15 +1650,30 @@ async function expandForwardNodeForTarget(
|
||||
target: { groupId?: number; userId?: number },
|
||||
depth: number,
|
||||
): Promise<ForwardNodePayload> {
|
||||
const forwards = node.elements.filter(
|
||||
// Fetched nodes already carry protocol media metadata, but their URLs may
|
||||
// lack an rkey (or only be a file UUID). Reuse complete fingerprints in the
|
||||
// target's upload scene, just as historical single-message forwarding does.
|
||||
// Legacy/incomplete images still need the existing byte-source upload path.
|
||||
const preparedElements = await mapWithConcurrency(node.elements, 8, async (element) => {
|
||||
if (!isMessageMedia(element) || !element.md5Hex || !element.sha1Hex) {
|
||||
return element;
|
||||
}
|
||||
|
||||
if (element.type === 'image' && (!element.width || !element.height || !element.picFormat)) {
|
||||
return element;
|
||||
}
|
||||
|
||||
return await enrichForForward(ref, element, element);
|
||||
});
|
||||
const forwards = preparedElements.filter(
|
||||
(element): element is MessageElementOf<'forward'> => element.type === 'forward',
|
||||
);
|
||||
|
||||
if (forwards.length === 0) {
|
||||
return node;
|
||||
return { ...node, elements: preparedElements };
|
||||
}
|
||||
|
||||
if (forwards.length === node.elements.length && forwards.length === 1) {
|
||||
if (forwards.length === preparedElements.length && forwards.length === 1) {
|
||||
const innerId = forwards[0]!.resId.trim();
|
||||
|
||||
if (!innerId) {
|
||||
@@ -1734,7 +1689,7 @@ async function expandForwardNodeForTarget(
|
||||
|
||||
const elements: MessageElement[] = [];
|
||||
|
||||
for (const element of node.elements) {
|
||||
for (const element of preparedElements) {
|
||||
if (element.type !== 'forward') {
|
||||
elements.push(element);
|
||||
continue;
|
||||
@@ -1761,18 +1716,18 @@ async function expandForwardNodeForTarget(
|
||||
return { ...node, elements };
|
||||
}
|
||||
|
||||
function restoreHistoricalMedia(
|
||||
async function restoreHistoricalMedia(
|
||||
ref: OneBotInstanceContext,
|
||||
elements: MessageElement[],
|
||||
messageId: number,
|
||||
): MessageElement[] {
|
||||
): Promise<MessageElement[]> {
|
||||
if (!elements.some(isMessageMedia)) {
|
||||
return elements;
|
||||
}
|
||||
|
||||
const snapshots = ref.messageStore.findMedia(messageId);
|
||||
const snapshots = await ref.messageStore.findMedia(messageId);
|
||||
let index = 0;
|
||||
const restored = elements.map((element) => {
|
||||
const restored = await mapWithConcurrency(elements, 8, async (element) => {
|
||||
if (!isMessageMedia(element)) {
|
||||
return element;
|
||||
}
|
||||
@@ -1783,7 +1738,7 @@ function restoreHistoricalMedia(
|
||||
throw new Error(`historical media metadata does not match message ${messageId}`);
|
||||
}
|
||||
|
||||
return enrichForForward(ref, element, snapshot);
|
||||
return await enrichForForward(ref, element, snapshot);
|
||||
});
|
||||
|
||||
if (snapshots && index !== snapshots.length) {
|
||||
@@ -1793,11 +1748,11 @@ function restoreHistoricalMedia(
|
||||
return restored;
|
||||
}
|
||||
|
||||
function enrichForForward(
|
||||
async function enrichForForward(
|
||||
ref: OneBotInstanceContext,
|
||||
element: MessageElement,
|
||||
snapshot?: MessageMedia,
|
||||
): MessageElement {
|
||||
): Promise<MessageElement> {
|
||||
if (element.type === 'forward') {
|
||||
throw new Error('merged forward must be regenerated for the target chat');
|
||||
}
|
||||
@@ -1833,7 +1788,9 @@ function enrichForForward(
|
||||
|
||||
if (element.type === 'image') {
|
||||
const cached =
|
||||
snapshot?.type === 'image' ? snapshot : ref.mediaStore.findImage(lookupKey, 'legacy');
|
||||
snapshot?.type === 'image'
|
||||
? snapshot
|
||||
: await ref.mediaStore.findImage(lookupKey, 'legacy');
|
||||
|
||||
if (
|
||||
!cached ||
|
||||
@@ -1866,7 +1823,9 @@ function enrichForForward(
|
||||
|
||||
if (element.type === 'record') {
|
||||
const cached =
|
||||
snapshot?.type === 'record' ? snapshot : ref.mediaStore.findRecord(lookupKey, 'legacy');
|
||||
snapshot?.type === 'record'
|
||||
? snapshot
|
||||
: await ref.mediaStore.findRecord(lookupKey, 'legacy');
|
||||
|
||||
if (!cached || !cached.md5Hex || !cached.sha1Hex) {
|
||||
throw new Error(
|
||||
@@ -1890,7 +1849,9 @@ function enrichForForward(
|
||||
|
||||
if (element.type === 'video') {
|
||||
const cached =
|
||||
snapshot?.type === 'video' ? snapshot : ref.mediaStore.findVideo(lookupKey, 'legacy');
|
||||
snapshot?.type === 'video'
|
||||
? snapshot
|
||||
: await ref.mediaStore.findVideo(lookupKey, 'legacy');
|
||||
|
||||
if (!cached || !cached.md5Hex || !cached.sha1Hex) {
|
||||
throw new Error(
|
||||
@@ -1939,6 +1900,7 @@ export async function getForwardMessage(
|
||||
node.elements,
|
||||
isGroup,
|
||||
sessionId,
|
||||
{ includeReplyContent: true },
|
||||
);
|
||||
|
||||
const sender: JsonObject = {
|
||||
@@ -1966,7 +1928,7 @@ export async function getForwardMessage(
|
||||
raw_message: '',
|
||||
font: 14,
|
||||
sub_type: isGroup ? 'normal' : 'friend',
|
||||
message: segments as unknown as JsonValue,
|
||||
message: segments,
|
||||
message_format: 'array',
|
||||
post_type: 'message',
|
||||
};
|
||||
@@ -2111,7 +2073,7 @@ function isNestedNodeArray(value: JsonValue): boolean {
|
||||
for (const item of value) {
|
||||
const seg = asJsonObject(item);
|
||||
|
||||
if (!seg || String(seg.type ?? '') !== 'node') {
|
||||
if (!seg || seg.type !== 'node') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -2119,7 +2081,13 @@ function isNestedNodeArray(value: JsonValue): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
function assertForwardNodeMetadata(nodeData: JsonObject, index: number): void {
|
||||
type ForwardNodeData = JsonObject &
|
||||
Pick<ForwardNodePayload, 'news' | 'title' | 'source' | 'summary' | 'prompt'>;
|
||||
|
||||
function assertForwardNodeMetadata(
|
||||
nodeData: JsonObject,
|
||||
index: number,
|
||||
): asserts nodeData is ForwardNodeData {
|
||||
for (const [field, value] of Object.entries(nodeData)) {
|
||||
if (field === 'content' || field === 'message') {
|
||||
continue;
|
||||
@@ -2190,11 +2158,11 @@ function isForwardNewsArray(value: JsonValue): value is Array<{ text: string }>
|
||||
return true;
|
||||
}
|
||||
|
||||
function assertForwardMessageInputPolicies(
|
||||
async function assertForwardMessageInputPolicies(
|
||||
ref: OneBotInstanceContext,
|
||||
messages: JsonValue,
|
||||
depth = 0,
|
||||
): void {
|
||||
): Promise<void> {
|
||||
if (!Array.isArray(messages) || depth >= MAX_FORWARD_DEPTH) {
|
||||
return;
|
||||
}
|
||||
@@ -2217,11 +2185,11 @@ function assertForwardMessageInputPolicies(
|
||||
const messageId = parseForwardMessageId(nodeData.id ?? nodeData.message_id);
|
||||
|
||||
if (messageId !== 0) {
|
||||
const event = ref.messageStore.findEvent(messageId);
|
||||
const event = await ref.messageStore.findEvent(messageId);
|
||||
|
||||
if (event) {
|
||||
assertOutboundMessageInput(
|
||||
(event.message ?? event.raw_message ?? '') as JsonValue,
|
||||
event.message ?? event.raw_message ?? '',
|
||||
false,
|
||||
'forward',
|
||||
);
|
||||
@@ -2230,10 +2198,10 @@ function assertForwardMessageInputPolicies(
|
||||
continue;
|
||||
}
|
||||
|
||||
const content = (nodeData.content ?? nodeData.message ?? '') as JsonValue;
|
||||
const content = nodeData.content ?? nodeData.message ?? '';
|
||||
|
||||
if (isNestedNodeArray(content)) {
|
||||
assertForwardMessageInputPolicies(ref, content, depth + 1);
|
||||
await assertForwardMessageInputPolicies(ref, content, depth + 1);
|
||||
} else {
|
||||
assertOutboundMessageInput(content, false, 'forward');
|
||||
}
|
||||
@@ -2323,7 +2291,7 @@ async function parseForwardNodes(
|
||||
}
|
||||
|
||||
assertForwardNodeMetadata(nodeData, index);
|
||||
return { segment, nodeData };
|
||||
return nodeData;
|
||||
}
|
||||
|
||||
// Preserve the existing bare-node compatibility form, but require it to
|
||||
@@ -2338,22 +2306,22 @@ async function parseForwardNodes(
|
||||
}
|
||||
|
||||
assertForwardNodeMetadata(segment, index);
|
||||
return { segment, nodeData: segment };
|
||||
return segment;
|
||||
});
|
||||
|
||||
// Scan the complete raw tree before parsing any earlier node. Some segment
|
||||
// codecs perform identity lookups or HTTP signing, so discovering an
|
||||
// unsupported message combination during the normal loop would already be
|
||||
// too late.
|
||||
assertForwardMessageInputPolicies(ref, messages, depth);
|
||||
await assertForwardMessageInputPolicies(ref, messages, depth);
|
||||
|
||||
const nodes: ForwardNodePayload[] = [];
|
||||
|
||||
for (const { nodeData } of prepared) {
|
||||
for (const nodeData of prepared) {
|
||||
const messageId = parseForwardMessageId(nodeData.id ?? nodeData.message_id);
|
||||
|
||||
if (messageId !== 0) {
|
||||
const event = ref.messageStore.findEvent(messageId);
|
||||
const event = await ref.messageStore.findEvent(messageId);
|
||||
|
||||
if (!event) {
|
||||
throw new MessageElementValidationError(
|
||||
@@ -2385,10 +2353,15 @@ async function parseForwardNodes(
|
||||
);
|
||||
}
|
||||
|
||||
const content = (event.message ?? event.raw_message ?? '') as JsonValue;
|
||||
const elements = restoreHistoricalMedia(
|
||||
const content = event.message ?? event.raw_message ?? '';
|
||||
const elements = await restoreHistoricalMedia(
|
||||
ref,
|
||||
await parseMessage(content, false),
|
||||
await parseMessage(content, false, {
|
||||
forwardReply: {
|
||||
senderUin: userUin,
|
||||
time: toPositiveInt(event.time) || undefined,
|
||||
},
|
||||
}),
|
||||
messageId,
|
||||
);
|
||||
|
||||
@@ -2424,7 +2397,10 @@ async function parseForwardNodes(
|
||||
}
|
||||
|
||||
const nickname = String(nodeData.nickname ?? nodeData.name ?? userUin);
|
||||
const content = (nodeData.content ?? nodeData.message ?? '') as JsonValue;
|
||||
const content = nodeData.content ?? nodeData.message ?? '';
|
||||
// Preserve the node-time policy for both the node and its custom quotes.
|
||||
const nodeTime = toPositiveInt(nodeData.time);
|
||||
const time = nodeTime > 0 && nodeTime < 0xffffffff ? nodeTime : undefined;
|
||||
|
||||
let elements: MessageElement[];
|
||||
let innerForward: ForwardNodePayload[] | undefined;
|
||||
@@ -2455,7 +2431,9 @@ async function parseForwardNodes(
|
||||
// uuid in hand.
|
||||
elements = [];
|
||||
} else {
|
||||
elements = await parseMessage(content, false);
|
||||
elements = await parseMessage(content, false, {
|
||||
forwardReply: { senderUin: userUin, time },
|
||||
});
|
||||
}
|
||||
|
||||
if (!innerForward && elements.length === 0) {
|
||||
@@ -2464,41 +2442,18 @@ async function parseForwardNodes(
|
||||
|
||||
const node: ForwardNodePayload = { userUin, nickname, elements };
|
||||
|
||||
// Forward optional preview news lines (OneBot `data.news`) onto the
|
||||
// payload so nested-forward bubble previews can prefer caller-supplied
|
||||
// lines over auto-generated ones. Only accepted when the array shape
|
||||
// is valid (already asserted by assertForwardNodeMetadata).
|
||||
if (isForwardNewsArray(nodeData.news)) {
|
||||
if (nodeData.news !== undefined) {
|
||||
node.news = nodeData.news.map((item) => ({ text: item.text }));
|
||||
}
|
||||
|
||||
// Forward optional OneBot bubble-preview metadata so nested-forward
|
||||
// cards can prefer caller-supplied titles/source/summary/prompt over
|
||||
// auto-derived ones (types already asserted above).
|
||||
if (nodeData.title !== undefined && typeof nodeData.title === 'string') {
|
||||
node.title = nodeData.title;
|
||||
for (const field of ['title', 'source', 'summary', 'prompt'] as const) {
|
||||
if (nodeData[field] !== undefined) {
|
||||
node[field] = nodeData[field];
|
||||
}
|
||||
}
|
||||
|
||||
if (nodeData.source !== undefined && typeof nodeData.source === 'string') {
|
||||
node.source = nodeData.source;
|
||||
}
|
||||
|
||||
if (nodeData.summary !== undefined && typeof nodeData.summary === 'string') {
|
||||
node.summary = nodeData.summary;
|
||||
}
|
||||
|
||||
if (nodeData.prompt !== undefined && typeof nodeData.prompt === 'string') {
|
||||
node.prompt = nodeData.prompt;
|
||||
}
|
||||
|
||||
// Honour an explicit per-node display time (OneBot `data.time`, unix
|
||||
// seconds) so a custom forward can set/back-date each node's timestamp
|
||||
// (#209). The wire field is uint32, so reject a millisecond value or any
|
||||
// out-of-range input (it would overflow/throw) and fall back to now.
|
||||
const nodeTime = toPositiveInt(nodeData.time);
|
||||
|
||||
if (nodeTime > 0 && nodeTime < 0xffffffff) {
|
||||
node.time = nodeTime;
|
||||
if (time !== undefined) {
|
||||
node.time = time;
|
||||
}
|
||||
|
||||
if (innerForward) {
|
||||
|
||||
Reference in new issue
Block a user