@zhin.js/adapter-weixin-ilink 1.0.1 → 1.1.2
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/CHANGELOG.md +512 -0
- package/README.md +24 -42
- package/adapters/weixin-ilink/index.js +32 -0
- package/adapters/weixin-ilink/index.ts +43 -0
- package/commands/weixin-ilink/endpoint/add/[id]/index.js +3 -0
- package/commands/weixin-ilink/endpoint/add/[id]/index.ts +3 -0
- package/commands/weixin-ilink/endpoint/definition.js +17 -0
- package/commands/weixin-ilink/endpoint/definition.ts +17 -0
- package/commands/weixin-ilink/endpoint/list/index.js +3 -0
- package/commands/weixin-ilink/endpoint/list/index.ts +3 -0
- package/commands/weixin-ilink/endpoint/remove/[id]/index.js +3 -0
- package/commands/weixin-ilink/endpoint/remove/[id]/index.ts +3 -0
- package/lib/aes-ecb.d.ts +0 -1
- package/lib/aes-ecb.js +0 -1
- package/lib/cdn-upload.d.ts +0 -1
- package/lib/cdn-upload.js +0 -1
- package/lib/cdn-url.d.ts +0 -1
- package/lib/cdn-url.js +0 -1
- package/lib/client.d.ts +35 -0
- package/lib/client.js +89 -0
- package/lib/context-store.d.ts +15 -2
- package/lib/context-store.js +93 -2
- package/lib/credentials.d.ts +15 -8
- package/lib/credentials.js +59 -43
- package/lib/endpoint.d.ts +40 -35
- package/lib/endpoint.js +311 -262
- package/lib/ilink-api.d.ts +7 -6
- package/lib/ilink-api.js +26 -16
- package/lib/ilink-config-cache.d.ts +3 -8
- package/lib/ilink-config-cache.js +13 -15
- package/lib/ilink-logger.d.ts +0 -2
- package/lib/ilink-logger.js +11 -26
- package/lib/ilink-meta.d.ts +13 -8
- package/lib/ilink-meta.js +24 -21
- package/lib/ilink-random.d.ts +0 -1
- package/lib/ilink-random.js +0 -1
- package/lib/ilink-redact.d.ts +0 -1
- package/lib/ilink-redact.js +0 -1
- package/lib/ilink-session-guard.d.ts +13 -15
- package/lib/ilink-session-guard.js +29 -43
- package/lib/ilink-types.d.ts +0 -1
- package/lib/ilink-types.js +0 -1
- package/lib/index.d.ts +8 -20
- package/lib/index.js +7 -38
- package/lib/login.d.ts +5 -6
- package/lib/login.js +85 -77
- package/lib/media-download.d.ts +1 -2
- package/lib/media-download.js +1 -2
- package/lib/mime.d.ts +0 -1
- package/lib/mime.js +0 -1
- package/lib/outbound-media.d.ts +4 -5
- package/lib/outbound-media.js +85 -86
- package/lib/pic-decrypt.d.ts +0 -1
- package/lib/pic-decrypt.js +0 -1
- package/lib/protocol.d.ts +60 -0
- package/lib/protocol.js +127 -0
- package/lib/silk-transcode.d.ts +0 -1
- package/lib/silk-transcode.js +0 -1
- package/lib/types.d.ts +2 -26
- package/lib/types.js +0 -1
- package/lib/upload.d.ts +1 -2
- package/lib/upload.js +1 -2
- package/lib/weixin-ilink-runtime-state.d.ts +1 -0
- package/lib/weixin-ilink-runtime-state.js +6 -0
- package/lib/weixin-inbound.d.ts +4 -43
- package/lib/weixin-inbound.js +22 -162
- package/lib/weixin-send-media.d.ts +0 -1
- package/lib/weixin-send-media.js +5 -2
- package/lib/weixin-send.d.ts +1 -2
- package/lib/weixin-send.js +4 -3
- package/package.json +48 -39
- package/plugin.js +14 -0
- package/schema.json +116 -0
- package/src/client.ts +117 -0
- package/src/context-store.ts +101 -8
- package/src/credentials.ts +68 -45
- package/src/endpoint.ts +384 -315
- package/src/ilink-api.ts +31 -21
- package/src/ilink-config-cache.ts +17 -13
- package/src/ilink-logger.ts +11 -26
- package/src/ilink-meta.ts +31 -21
- package/src/ilink-session-guard.ts +29 -46
- package/src/index.ts +41 -56
- package/src/login.ts +112 -85
- package/src/media-download.ts +1 -2
- package/src/outbound-media.ts +97 -97
- package/src/protocol.ts +180 -0
- package/src/silk-wasm.d.ts +6 -2
- package/src/types.ts +5 -25
- package/src/upload.test.ts +11 -8
- package/src/upload.ts +2 -2
- package/src/weixin-ilink-runtime-state.ts +7 -0
- package/src/weixin-inbound.ts +25 -187
- package/src/weixin-send-media.ts +5 -1
- package/src/weixin-send.ts +6 -4
- package/client/LoginAssistPanel.tsx +0 -200
- package/client/WeixinIlinkManagement.tsx +0 -139
- package/client/index.tsx +0 -11
- package/client/tsconfig.json +0 -13
- package/client/utils/api.ts +0 -30
- package/dist/index.js +0 -29
- package/lib/adapter.d.ts +0 -12
- package/lib/adapter.d.ts.map +0 -1
- package/lib/adapter.js +0 -15
- package/lib/adapter.js.map +0 -1
- package/lib/aes-ecb.d.ts.map +0 -1
- package/lib/aes-ecb.js.map +0 -1
- package/lib/cdn-upload.d.ts.map +0 -1
- package/lib/cdn-upload.js.map +0 -1
- package/lib/cdn-upload.test.d.ts +0 -2
- package/lib/cdn-upload.test.d.ts.map +0 -1
- package/lib/cdn-upload.test.js +0 -150
- package/lib/cdn-upload.test.js.map +0 -1
- package/lib/cdn-url.d.ts.map +0 -1
- package/lib/cdn-url.js.map +0 -1
- package/lib/context-store.d.ts.map +0 -1
- package/lib/context-store.js.map +0 -1
- package/lib/credentials.d.ts.map +0 -1
- package/lib/credentials.js.map +0 -1
- package/lib/endpoint.d.ts.map +0 -1
- package/lib/endpoint.js.map +0 -1
- package/lib/ilink-api.d.ts.map +0 -1
- package/lib/ilink-api.js.map +0 -1
- package/lib/ilink-config-cache.d.ts.map +0 -1
- package/lib/ilink-config-cache.js.map +0 -1
- package/lib/ilink-logger.d.ts.map +0 -1
- package/lib/ilink-logger.js.map +0 -1
- package/lib/ilink-meta.d.ts.map +0 -1
- package/lib/ilink-meta.js.map +0 -1
- package/lib/ilink-random.d.ts.map +0 -1
- package/lib/ilink-random.js.map +0 -1
- package/lib/ilink-redact.d.ts.map +0 -1
- package/lib/ilink-redact.js.map +0 -1
- package/lib/ilink-session-guard.d.ts.map +0 -1
- package/lib/ilink-session-guard.js.map +0 -1
- package/lib/ilink-types.d.ts.map +0 -1
- package/lib/ilink-types.js.map +0 -1
- package/lib/index.d.ts.map +0 -1
- package/lib/index.js.map +0 -1
- package/lib/login-assist-routes.d.ts +0 -7
- package/lib/login-assist-routes.d.ts.map +0 -1
- package/lib/login-assist-routes.js +0 -29
- package/lib/login-assist-routes.js.map +0 -1
- package/lib/login.d.ts.map +0 -1
- package/lib/login.js.map +0 -1
- package/lib/media-download.d.ts.map +0 -1
- package/lib/media-download.js.map +0 -1
- package/lib/mime.d.ts.map +0 -1
- package/lib/mime.js.map +0 -1
- package/lib/mime.test.d.ts +0 -2
- package/lib/mime.test.d.ts.map +0 -1
- package/lib/mime.test.js +0 -62
- package/lib/mime.test.js.map +0 -1
- package/lib/outbound-media.d.ts.map +0 -1
- package/lib/outbound-media.js.map +0 -1
- package/lib/pic-decrypt.d.ts.map +0 -1
- package/lib/pic-decrypt.js.map +0 -1
- package/lib/routes.d.ts +0 -8
- package/lib/routes.d.ts.map +0 -1
- package/lib/routes.js +0 -29
- package/lib/routes.js.map +0 -1
- package/lib/silk-transcode.d.ts.map +0 -1
- package/lib/silk-transcode.js.map +0 -1
- package/lib/silk-transcode.test.d.ts +0 -2
- package/lib/silk-transcode.test.d.ts.map +0 -1
- package/lib/silk-transcode.test.js +0 -53
- package/lib/silk-transcode.test.js.map +0 -1
- package/lib/types.d.ts.map +0 -1
- package/lib/types.js.map +0 -1
- package/lib/typing-indicator.d.ts +0 -32
- package/lib/typing-indicator.d.ts.map +0 -1
- package/lib/typing-indicator.js +0 -95
- package/lib/typing-indicator.js.map +0 -1
- package/lib/upload.d.ts.map +0 -1
- package/lib/upload.js.map +0 -1
- package/lib/upload.test.d.ts +0 -2
- package/lib/upload.test.d.ts.map +0 -1
- package/lib/upload.test.js +0 -250
- package/lib/upload.test.js.map +0 -1
- package/lib/weixin-inbound.d.ts.map +0 -1
- package/lib/weixin-inbound.js.map +0 -1
- package/lib/weixin-send-media.d.ts.map +0 -1
- package/lib/weixin-send-media.js.map +0 -1
- package/lib/weixin-send.d.ts.map +0 -1
- package/lib/weixin-send.js.map +0 -1
- package/src/adapter.ts +0 -18
- package/src/login-assist-routes.ts +0 -36
- package/src/routes.ts +0 -39
- package/src/typing-indicator.ts +0 -139
package/src/endpoint.ts
CHANGED
|
@@ -1,354 +1,355 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* WeixinIlinkEndpoint — lifecycle, long-poll inbound, outbound send.
|
|
3
3
|
*/
|
|
4
|
-
import crypto from
|
|
5
|
-
import fs from
|
|
6
|
-
import path from
|
|
4
|
+
import crypto from 'node:crypto';
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
7
|
import {
|
|
8
8
|
Endpoint,
|
|
9
|
-
|
|
10
|
-
type
|
|
11
|
-
type
|
|
12
|
-
type
|
|
13
|
-
|
|
14
|
-
} from
|
|
15
|
-
import {
|
|
9
|
+
type EndpointFriend,
|
|
10
|
+
type EndpointControl,
|
|
11
|
+
type EndpointManagement,
|
|
12
|
+
type EndpointSendRequest,
|
|
13
|
+
} from 'zhin.js/adapter';
|
|
14
|
+
import { formatCompact, getAdapterLogger } from '@zhin.js/logger';
|
|
15
|
+
import type { CapabilityId } from 'zhin.js';
|
|
16
|
+
import { getUpdates, notifyStart, notifyStop } from './ilink-api.js';
|
|
17
|
+
import { IlinkClientMetadata } from './ilink-meta.js';
|
|
16
18
|
import {
|
|
17
|
-
configureIlinkMeta,
|
|
18
|
-
DEFAULT_API_BASE_URL,
|
|
19
|
-
DEFAULT_CDN_BASE_URL,
|
|
20
|
-
} from "./ilink-meta.js";
|
|
21
|
-
import {
|
|
22
|
-
loadSyncBuf,
|
|
23
|
-
resolveStateDir,
|
|
24
|
-
saveSyncBuf,
|
|
25
19
|
type WeixinIlinkCredentials,
|
|
26
|
-
|
|
27
|
-
|
|
20
|
+
WeixinIlinkStateStore,
|
|
21
|
+
} from './credentials.js';
|
|
22
|
+
import { resolveCredentials } from './login.js';
|
|
28
23
|
import {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
restoreContextTokens,
|
|
33
|
-
setContextToken,
|
|
34
|
-
} from "./context-store.js";
|
|
35
|
-
import { WeixinConfigManager } from "./ilink-config-cache.js";
|
|
24
|
+
WeixinContextTokenStore,
|
|
25
|
+
} from './context-store.js';
|
|
26
|
+
import { WeixinConfigManager } from './ilink-config-cache.js';
|
|
36
27
|
import {
|
|
37
|
-
|
|
38
|
-
isSessionPaused,
|
|
39
|
-
pauseSession,
|
|
28
|
+
IlinkSessionGuard,
|
|
40
29
|
SESSION_EXPIRED_ERRCODE,
|
|
41
|
-
} from
|
|
42
|
-
import { downloadMediaFromItem } from
|
|
43
|
-
import { sendMessageWeixin } from
|
|
44
|
-
import {
|
|
45
|
-
import {
|
|
46
|
-
import
|
|
47
|
-
import {
|
|
48
|
-
import { getExtensionFromMime, sniffMimeFromBuffer } from "./mime.js";
|
|
49
|
-
import type { WeixinInboundMediaOpts } from "./weixin-inbound.js";
|
|
50
|
-
import type { WeixinIlinkEndpointConfig } from "./types.js";
|
|
51
|
-
import type { WeixinIlinkAdapter } from "./adapter.js";
|
|
30
|
+
} from './ilink-session-guard.js';
|
|
31
|
+
import { downloadMediaFromItem } from './media-download.js';
|
|
32
|
+
import { sendMessageWeixin } from './weixin-send.js';
|
|
33
|
+
import { materializeOutboundMedia } from './outbound-media.js';
|
|
34
|
+
import { MessageItemType, type WeixinMessage } from './ilink-types.js';
|
|
35
|
+
import { getExtensionFromMime, sniffMimeFromBuffer } from './mime.js';
|
|
36
|
+
import type { WeixinInboundMediaOpts } from './weixin-inbound.js';
|
|
52
37
|
import {
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
38
|
+
formatInboundContent,
|
|
39
|
+
weixinInboundSegments,
|
|
40
|
+
weixinReplyTo,
|
|
41
|
+
formatOutboundSegments,
|
|
42
|
+
inboundMessageId,
|
|
43
|
+
segmentLocalPath,
|
|
44
|
+
sleep,
|
|
45
|
+
weixinIlinkInboundConversation,
|
|
46
|
+
type ResolvedWeixinIlinkConfig,
|
|
47
|
+
type WeixinMessageWithMedia,
|
|
48
|
+
type WeixinWireSegment,
|
|
49
|
+
} from './protocol.js';
|
|
50
|
+
import { WeixinIlinkClient } from './client.js';
|
|
56
51
|
|
|
57
|
-
const DEFAULT_LONG_POLL_TIMEOUT_MS = 35_000;
|
|
58
52
|
const MAX_CONSECUTIVE_FAILURES = 3;
|
|
59
53
|
const BACKOFF_DELAY_MS = 30_000;
|
|
60
54
|
const RETRY_DELAY_MS = 2_000;
|
|
61
55
|
const WEIXIN_MEDIA_MAX_BYTES = 100 * 1024 * 1024;
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
56
|
+
/** 入站媒体保留 24h,每小时清扫一次。 */
|
|
57
|
+
const INBOUND_MEDIA_TTL_MS = 24 * 60 * 60 * 1000;
|
|
58
|
+
const MEDIA_SWEEP_INTERVAL_MS = 60 * 60 * 1000;
|
|
59
|
+
|
|
60
|
+
export type WeixinIlinkSendText = typeof sendMessageWeixin;
|
|
61
|
+
export type WeixinIlinkNotifyStart = typeof notifyStart;
|
|
62
|
+
export type WeixinIlinkNotifyStop = typeof notifyStop;
|
|
63
|
+
export type WeixinIlinkGetUpdates = typeof getUpdates;
|
|
64
|
+
|
|
65
|
+
export interface WeixinIlinkEndpointOptions {
|
|
66
|
+
readonly id: CapabilityId;
|
|
67
|
+
readonly config: ResolvedWeixinIlinkConfig;
|
|
68
|
+
readonly resolveCredentials?: (
|
|
69
|
+
config: ResolvedWeixinIlinkConfig,
|
|
70
|
+
metadata: IlinkClientMetadata,
|
|
71
|
+
state: WeixinIlinkStateStore,
|
|
72
|
+
signal?: AbortSignal,
|
|
73
|
+
) => Promise<WeixinIlinkCredentials>;
|
|
74
|
+
/** Test / internal: override network side effects. */
|
|
75
|
+
readonly notifyStart?: WeixinIlinkNotifyStart;
|
|
76
|
+
readonly notifyStop?: WeixinIlinkNotifyStop;
|
|
77
|
+
readonly getUpdates?: WeixinIlinkGetUpdates;
|
|
78
|
+
readonly sendText?: WeixinIlinkSendText;
|
|
79
|
+
readonly state?: WeixinIlinkStateStore;
|
|
80
|
+
readonly contextTokens?: WeixinContextTokenStore;
|
|
81
|
+
readonly sessionGuard?: IlinkSessionGuard;
|
|
83
82
|
}
|
|
84
83
|
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
84
|
+
export class WeixinIlinkEndpoint extends Endpoint<WeixinIlinkClient> {
|
|
85
|
+
readonly client: WeixinIlinkClient;
|
|
86
|
+
readonly #logger!: ReturnType<typeof getAdapterLogger>;
|
|
87
|
+
|
|
88
|
+
readonly #options: WeixinIlinkEndpointOptions;
|
|
89
|
+
readonly #resolveCredentials: (
|
|
90
|
+
config: ResolvedWeixinIlinkConfig,
|
|
91
|
+
metadata: IlinkClientMetadata,
|
|
92
|
+
state: WeixinIlinkStateStore,
|
|
93
|
+
signal?: AbortSignal,
|
|
94
|
+
) => Promise<WeixinIlinkCredentials>;
|
|
95
|
+
readonly #notifyStart: WeixinIlinkNotifyStart;
|
|
96
|
+
readonly #notifyStop: WeixinIlinkNotifyStop;
|
|
97
|
+
readonly #getUpdates: WeixinIlinkGetUpdates;
|
|
98
|
+
readonly #sendText: WeixinIlinkSendText;
|
|
99
|
+
readonly #state: WeixinIlinkStateStore;
|
|
100
|
+
readonly #contextTokens: WeixinContextTokenStore;
|
|
101
|
+
readonly #sessionGuard: IlinkSessionGuard;
|
|
102
|
+
readonly #metadata: IlinkClientMetadata;
|
|
103
|
+
#creds: WeixinIlinkCredentials | null = null;
|
|
104
|
+
#pollAbort?: AbortController;
|
|
105
|
+
#pollPromise?: Promise<void>;
|
|
106
|
+
#loginAbort?: AbortController;
|
|
107
|
+
#configManager?: WeixinConfigManager;
|
|
108
|
+
#mediaSweepTimer?: ReturnType<typeof setInterval>;
|
|
109
|
+
#open = false;
|
|
110
|
+
#started = false;
|
|
111
|
+
readonly management: EndpointManagement = createWeixinIlinkEndpointManagement(() => this.client);
|
|
112
|
+
readonly control: EndpointControl = Object.freeze<EndpointControl>({
|
|
113
|
+
typing: async (conversation, active) => {
|
|
114
|
+
await this.client.sendTyping(
|
|
115
|
+
conversation.id,
|
|
116
|
+
active === false ? 2 : 1,
|
|
117
|
+
);
|
|
118
|
+
},
|
|
119
|
+
});
|
|
101
120
|
|
|
102
|
-
|
|
103
|
-
|
|
121
|
+
constructor(options: WeixinIlinkEndpointOptions) {
|
|
122
|
+
super();
|
|
123
|
+
this.#logger = getAdapterLogger('weixin-ilink', options.config.id);
|
|
124
|
+
this.#options = options;
|
|
125
|
+
this.#resolveCredentials = options.resolveCredentials ?? resolveCredentials;
|
|
126
|
+
this.#notifyStart = options.notifyStart ?? notifyStart;
|
|
127
|
+
this.#notifyStop = options.notifyStop ?? notifyStop;
|
|
128
|
+
this.#getUpdates = options.getUpdates ?? getUpdates;
|
|
129
|
+
this.#sendText = options.sendText ?? sendMessageWeixin;
|
|
130
|
+
this.#state = options.state
|
|
131
|
+
?? new WeixinIlinkStateStore(options.config.id, options.config.dataDir);
|
|
132
|
+
this.#contextTokens = options.contextTokens ?? new WeixinContextTokenStore(this.#state);
|
|
133
|
+
this.#sessionGuard = options.sessionGuard ?? new IlinkSessionGuard(options.config.id);
|
|
134
|
+
this.#metadata = new IlinkClientMetadata({ botAgent: options.config.botAgent });
|
|
135
|
+
this.client = new WeixinIlinkClient(
|
|
136
|
+
options.config,
|
|
137
|
+
this.#metadata,
|
|
138
|
+
() => this.#creds,
|
|
139
|
+
() => this.#configManager,
|
|
140
|
+
this.#sendText,
|
|
141
|
+
this.#contextTokens,
|
|
142
|
+
);
|
|
104
143
|
}
|
|
105
144
|
|
|
106
145
|
get hasCredentials(): boolean {
|
|
107
|
-
return
|
|
146
|
+
return this.client.authenticated;
|
|
108
147
|
}
|
|
109
148
|
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
149
|
+
async start(): Promise<void> {
|
|
150
|
+
if (this.#started) return;
|
|
151
|
+
this.#started = true;
|
|
152
|
+
try {
|
|
153
|
+
// QR 登录最长 8 分钟:stop() 必须能打断
|
|
154
|
+
this.#loginAbort = new AbortController();
|
|
155
|
+
this.#creds = await this.#resolveCredentials(
|
|
156
|
+
this.#options.config,
|
|
157
|
+
this.#metadata,
|
|
158
|
+
this.#state,
|
|
159
|
+
this.#loginAbort.signal,
|
|
160
|
+
);
|
|
161
|
+
this.#contextTokens.restore();
|
|
113
162
|
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
163
|
+
await this.#notifyStart({
|
|
164
|
+
baseUrl: this.client.apiBaseUrl,
|
|
165
|
+
metadata: this.#metadata,
|
|
166
|
+
token: this.#creds.botToken,
|
|
167
|
+
});
|
|
118
168
|
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
169
|
+
this.#configManager = new WeixinConfigManager(
|
|
170
|
+
{
|
|
171
|
+
baseUrl: this.client.apiBaseUrl,
|
|
172
|
+
metadata: this.#metadata,
|
|
173
|
+
token: this.#creds.botToken,
|
|
174
|
+
},
|
|
175
|
+
(msg) => this.#logger.debug(msg),
|
|
176
|
+
);
|
|
122
177
|
|
|
123
|
-
|
|
124
|
-
|
|
178
|
+
this.#pollAbort = new AbortController();
|
|
179
|
+
this.#pollPromise = this.#pollLoop(this.#pollAbort.signal);
|
|
180
|
+
this.#startMediaSweep();
|
|
181
|
+
this.#logger.info(formatCompact({
|
|
182
|
+
op: 'connect',
|
|
183
|
+
endpoint: this.#options.config.id,
|
|
184
|
+
}));
|
|
185
|
+
void this.#emitPlatformEvent('system.online', {
|
|
186
|
+
account: this.#options.config.id,
|
|
187
|
+
});
|
|
188
|
+
} catch (error) {
|
|
189
|
+
await this.stop();
|
|
190
|
+
this.#logger.error('Failed to connect weixin-ilink bot:', error);
|
|
191
|
+
throw error;
|
|
192
|
+
}
|
|
125
193
|
}
|
|
126
194
|
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
restoreContextTokens(this.$id);
|
|
131
|
-
|
|
132
|
-
await notifyStart({
|
|
133
|
-
baseUrl: this.apiBaseUrl(),
|
|
134
|
-
token: this.creds.botToken,
|
|
135
|
-
});
|
|
136
|
-
|
|
137
|
-
this.configManager = new WeixinConfigManager(
|
|
138
|
-
{ baseUrl: this.apiBaseUrl(), token: this.creds.botToken },
|
|
139
|
-
(msg) => this.pluginLogger.debug(msg),
|
|
140
|
-
);
|
|
141
|
-
|
|
142
|
-
if (this.$config.typingIndicator?.enabled !== false) {
|
|
143
|
-
this.$typingIndicator = new WeixinIlinkTypingIndicatorManager(
|
|
144
|
-
this,
|
|
145
|
-
this.$config.typingIndicator as WeixinIlinkTypingIndicatorConfig | undefined,
|
|
146
|
-
);
|
|
147
|
-
}
|
|
195
|
+
open(): void {
|
|
196
|
+
this.#open = true;
|
|
197
|
+
}
|
|
148
198
|
|
|
149
|
-
|
|
150
|
-
this
|
|
151
|
-
this.$connected = true;
|
|
152
|
-
this.pluginLogger.info(`weixin-ilink endpoint ${this.$id} connected`);
|
|
199
|
+
close(): void {
|
|
200
|
+
this.#open = false;
|
|
153
201
|
}
|
|
154
202
|
|
|
155
|
-
async
|
|
156
|
-
this
|
|
203
|
+
async stop(): Promise<void> {
|
|
204
|
+
this.#open = false;
|
|
205
|
+
this.#loginAbort?.abort();
|
|
206
|
+
this.#pollAbort?.abort();
|
|
157
207
|
try {
|
|
158
|
-
await this
|
|
208
|
+
await this.#pollPromise;
|
|
159
209
|
} catch {
|
|
160
210
|
/* poll loop exit */
|
|
161
211
|
}
|
|
162
|
-
|
|
212
|
+
this.#stopMediaSweep();
|
|
213
|
+
// 防抖中的 context token 落盘,避免 stop 丢尾部写入
|
|
214
|
+
this.#contextTokens.flush();
|
|
215
|
+
if (this.#creds?.botToken) {
|
|
163
216
|
try {
|
|
164
|
-
await notifyStop({
|
|
217
|
+
await this.#notifyStop({
|
|
218
|
+
baseUrl: this.client.apiBaseUrl,
|
|
219
|
+
metadata: this.#metadata,
|
|
220
|
+
token: this.#creds.botToken,
|
|
221
|
+
});
|
|
165
222
|
} catch (err) {
|
|
166
|
-
this.
|
|
223
|
+
this.#logger.warn(formatCompact({
|
|
224
|
+
op: 'notify_stop',
|
|
225
|
+
ok: false,
|
|
226
|
+
error: err instanceof Error ? err.message : String(err),
|
|
227
|
+
}));
|
|
167
228
|
}
|
|
168
229
|
}
|
|
169
|
-
this
|
|
170
|
-
this.
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
async sendTypingToUser(userId: string, status: number): Promise<void> {
|
|
174
|
-
if (!this.creds?.botToken || !this.configManager) return;
|
|
175
|
-
const contextToken = getContextToken(this.$id, userId);
|
|
176
|
-
const cfg = await this.configManager.getForUser(userId, contextToken);
|
|
177
|
-
if (!cfg.typingTicket) {
|
|
178
|
-
this.pluginLogger.debug(`sendTyping: no typing_ticket for user=${userId}`);
|
|
179
|
-
return;
|
|
180
|
-
}
|
|
181
|
-
await sendTyping({
|
|
182
|
-
baseUrl: this.apiBaseUrl(),
|
|
183
|
-
token: this.creds.botToken,
|
|
184
|
-
body: {
|
|
185
|
-
ilink_user_id: userId,
|
|
186
|
-
typing_ticket: cfg.typingTicket,
|
|
187
|
-
status,
|
|
188
|
-
},
|
|
189
|
-
});
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
async $recallMessage(_id: string): Promise<void> {
|
|
193
|
-
this.pluginLogger.debug("weixin-ilink does not support message recall");
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
$formatMessage(msg: WeixinMessageWithMedia): Message<WeixinMessage> {
|
|
197
|
-
const userId = msg.from_user_id ?? "";
|
|
198
|
-
const content = this.buildInboundContent(msg);
|
|
199
|
-
const quoteId = Message.quoteIdFromContent(content);
|
|
200
|
-
Message.alignReplySegments(content, quoteId);
|
|
201
|
-
const msgId = String(msg.message_id ?? msg.client_id ?? msg.seq ?? Date.now());
|
|
202
|
-
|
|
203
|
-
return Message.from(msg, {
|
|
204
|
-
$id: msgId,
|
|
205
|
-
$adapter: "weixin-ilink",
|
|
206
|
-
$endpoint: this.$config.name,
|
|
207
|
-
$sender: {
|
|
208
|
-
id: userId,
|
|
209
|
-
name: userId,
|
|
210
|
-
},
|
|
211
|
-
$channel: {
|
|
212
|
-
id: userId,
|
|
213
|
-
type: "private",
|
|
214
|
-
},
|
|
215
|
-
$content: content,
|
|
216
|
-
$quote_id: quoteId,
|
|
217
|
-
$raw: bodyFromItemList(msg.item_list),
|
|
218
|
-
$timestamp: msg.create_time_ms ?? Date.now(),
|
|
219
|
-
$recall: async () => this.$recallMessage(msgId),
|
|
220
|
-
$reply: async (replyContent: SendContent, _quote?: boolean | string) => {
|
|
221
|
-
if (!Array.isArray(replyContent)) replyContent = [replyContent];
|
|
222
|
-
return this.adapter.sendMessage({
|
|
223
|
-
context: "weixin-ilink",
|
|
224
|
-
endpoint: this.$config.name,
|
|
225
|
-
id: userId,
|
|
226
|
-
type: "private",
|
|
227
|
-
content: replyContent,
|
|
228
|
-
});
|
|
229
|
-
},
|
|
230
|
+
this.#started = false;
|
|
231
|
+
void this.#emitPlatformEvent('system.offline', {
|
|
232
|
+
account: this.#options.config.id,
|
|
230
233
|
});
|
|
234
|
+
this.#logger.debug(formatCompact({
|
|
235
|
+
op: 'disconnect',
|
|
236
|
+
}));
|
|
231
237
|
}
|
|
232
238
|
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
if (text) segments.push(segment.text(text));
|
|
237
|
-
|
|
238
|
-
const media = msg._media;
|
|
239
|
-
if (media?.decryptedPicPath) {
|
|
240
|
-
segments.push(segment("image", { file: media.decryptedPicPath }));
|
|
241
|
-
} else if (media?.decryptedVideoPath) {
|
|
242
|
-
segments.push(segment("video", { file: media.decryptedVideoPath }));
|
|
243
|
-
} else if (media?.decryptedFilePath) {
|
|
244
|
-
segments.push(segment("file", {
|
|
245
|
-
file: media.decryptedFilePath,
|
|
246
|
-
name: path.basename(media.decryptedFilePath),
|
|
247
|
-
}));
|
|
248
|
-
} else if (media?.decryptedVoicePath) {
|
|
249
|
-
segments.push(segment("record", { file: media.decryptedVoicePath }));
|
|
250
|
-
} else if (!text && msg.item_list?.some((i) => isMediaItem(i))) {
|
|
251
|
-
segments.push(segment.text("[媒体消息]"));
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
return segments.length ? segments : [segment.text("")];
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
async $sendMessage(options: SendOptions): Promise<string> {
|
|
258
|
-
if (!this.creds?.botToken) {
|
|
259
|
-
throw new Error("weixin-ilink bot not authenticated");
|
|
239
|
+
async send({ conversation, payload }: EndpointSendRequest): Promise<string> {
|
|
240
|
+
if (!this.#creds?.botToken) {
|
|
241
|
+
throw new Error('weixin-ilink bot not authenticated');
|
|
260
242
|
}
|
|
261
|
-
|
|
262
|
-
const
|
|
243
|
+
// 个人微信仅 private 会话,对端 user_id 即 conversation.id
|
|
244
|
+
const target = conversation.id;
|
|
245
|
+
const contextToken = this.client.contextToken(target);
|
|
263
246
|
if (!contextToken) {
|
|
264
|
-
this.
|
|
265
|
-
|
|
247
|
+
this.#logger.warn(formatCompact({
|
|
248
|
+
op: 'send',
|
|
249
|
+
ok: false,
|
|
250
|
+
reason: 'missing_context_token',
|
|
251
|
+
target,
|
|
252
|
+
}));
|
|
253
|
+
throw new Error(`missing context_token for peer ${target}`);
|
|
266
254
|
}
|
|
267
255
|
|
|
268
|
-
const
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
contextToken,
|
|
272
|
-
};
|
|
273
|
-
|
|
274
|
-
const outboundDir = path.join(resolveStateDir(), "media", "outbound");
|
|
275
|
-
const materialized = await materializeOutboundMedia(options.content, outboundDir);
|
|
256
|
+
const outboundDir = this.#state.mediaDirectory('outbound');
|
|
257
|
+
const wire = formatOutboundSegments(payload);
|
|
258
|
+
const materialized = await materializeOutboundMedia(wire, outboundDir);
|
|
276
259
|
const segments = Array.isArray(materialized) ? materialized : [materialized];
|
|
277
|
-
let lastId =
|
|
278
|
-
let pendingText =
|
|
260
|
+
let lastId = '';
|
|
261
|
+
let pendingText = '';
|
|
279
262
|
|
|
280
263
|
for (const raw of segments) {
|
|
281
|
-
if (typeof raw ===
|
|
264
|
+
if (typeof raw === 'string') {
|
|
282
265
|
pendingText += raw;
|
|
283
266
|
continue;
|
|
284
267
|
}
|
|
285
|
-
if (typeof raw !==
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
if (seg.type === "text" || seg.type === "markdown") {
|
|
290
|
-
const t = (seg.data as { text?: string }).text ?? "";
|
|
291
|
-
pendingText += t;
|
|
268
|
+
if (typeof raw !== 'object' || raw === null || !('type' in raw)) continue;
|
|
269
|
+
const seg = raw as WeixinWireSegment;
|
|
270
|
+
if (seg.type === 'text' || seg.type === 'markdown') {
|
|
271
|
+
pendingText += String((seg.data as { text?: string } | undefined)?.text ?? '');
|
|
292
272
|
continue;
|
|
293
273
|
}
|
|
294
274
|
|
|
295
275
|
const filePath = segmentLocalPath(seg);
|
|
296
276
|
if (filePath && fs.existsSync(filePath)) {
|
|
297
|
-
// 微信限制:单条消息不能图文混排 →
|
|
277
|
+
// 微信限制:单条消息不能图文混排 → 先单独发文本,再发纯媒体
|
|
298
278
|
if (pendingText.trim()) {
|
|
299
|
-
const textResult = await
|
|
300
|
-
|
|
301
|
-
text: pendingText,
|
|
302
|
-
opts: apiOpts,
|
|
303
|
-
});
|
|
304
|
-
pendingText = "";
|
|
279
|
+
const textResult = await this.client.sendText(target, pendingText);
|
|
280
|
+
pendingText = '';
|
|
305
281
|
lastId = textResult.messageId;
|
|
306
282
|
}
|
|
307
|
-
const result = await
|
|
308
|
-
filePath,
|
|
309
|
-
to: peerId,
|
|
310
|
-
text: "",
|
|
311
|
-
opts: apiOpts,
|
|
312
|
-
cdnBaseUrl: this.cdnBaseUrl(),
|
|
313
|
-
});
|
|
283
|
+
const result = await this.client.sendMedia(target, filePath);
|
|
314
284
|
lastId = result.messageId;
|
|
315
285
|
continue;
|
|
316
286
|
}
|
|
317
287
|
|
|
318
|
-
if (seg.type ===
|
|
319
|
-
this.
|
|
288
|
+
if (seg.type === 'image' || seg.type === 'video' || seg.type === 'file' || seg.type === 'record') {
|
|
289
|
+
this.#logger.warn(formatCompact({
|
|
290
|
+
op: 'send',
|
|
291
|
+
skip: 'no_local_file',
|
|
292
|
+
type: seg.type,
|
|
293
|
+
}));
|
|
320
294
|
}
|
|
321
295
|
}
|
|
322
296
|
|
|
323
297
|
if (pendingText.trim()) {
|
|
324
|
-
const result = await
|
|
325
|
-
to: peerId,
|
|
326
|
-
text: pendingText,
|
|
327
|
-
opts: apiOpts,
|
|
328
|
-
});
|
|
298
|
+
const result = await this.client.sendText(target, pendingText);
|
|
329
299
|
lastId = result.messageId;
|
|
330
300
|
}
|
|
331
301
|
|
|
332
302
|
return lastId || `weixin-ilink-${Date.now()}`;
|
|
333
303
|
}
|
|
334
304
|
|
|
335
|
-
|
|
336
|
-
|
|
305
|
+
/** Test / internal: admit a parsed message when the endpoint is open. */
|
|
306
|
+
admit(msg: WeixinMessageWithMedia): void {
|
|
307
|
+
if (!this.#open) return;
|
|
308
|
+
const userId = msg.from_user_id ?? '';
|
|
309
|
+
if (msg.context_token && userId) {
|
|
310
|
+
this.#contextTokens.set(userId, msg.context_token);
|
|
311
|
+
}
|
|
312
|
+
const conversation = weixinIlinkInboundConversation(String(this.#options.id), userId);
|
|
313
|
+
const replyTo = weixinReplyTo(msg);
|
|
314
|
+
void this.emit('message.receive', {
|
|
315
|
+
conversation,
|
|
316
|
+
message: { conversation, id: inboundMessageId(msg) },
|
|
317
|
+
content: formatInboundContent(msg),
|
|
318
|
+
segments: weixinInboundSegments(msg),
|
|
319
|
+
...(replyTo ? { replyTo } : {}),
|
|
320
|
+
sender: { id: userId },
|
|
321
|
+
endpointId: this.#options.config.id,
|
|
322
|
+
metadata: Object.freeze({
|
|
323
|
+
messageType: msg.message_type,
|
|
324
|
+
createTimeMs: msg.create_time_ms,
|
|
325
|
+
}),
|
|
326
|
+
}).catch((err) => {
|
|
327
|
+
this.#logger.warn(formatCompact({
|
|
328
|
+
op: 'weixin_ilink_gateway_receive_failed',
|
|
329
|
+
target: userId,
|
|
330
|
+
error: err instanceof Error ? err.message : String(err),
|
|
331
|
+
}));
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
async #pollLoop(abortSignal: AbortSignal): Promise<void> {
|
|
336
|
+
if (!this.#creds?.botToken) return;
|
|
337
337
|
|
|
338
|
-
let getUpdatesBuf = loadSyncBuf(
|
|
339
|
-
let nextTimeoutMs = this
|
|
338
|
+
let getUpdatesBuf = this.#state.loadSyncBuf();
|
|
339
|
+
let nextTimeoutMs = this.#options.config.longPollTimeoutMs;
|
|
340
340
|
let consecutiveFailures = 0;
|
|
341
341
|
|
|
342
342
|
while (!abortSignal.aborted) {
|
|
343
|
-
if (
|
|
344
|
-
await sleep(
|
|
343
|
+
if (this.#sessionGuard.paused) {
|
|
344
|
+
await sleep(this.#sessionGuard.remainingMs, abortSignal);
|
|
345
345
|
continue;
|
|
346
346
|
}
|
|
347
347
|
|
|
348
348
|
try {
|
|
349
|
-
const resp = await getUpdates({
|
|
350
|
-
baseUrl: this.apiBaseUrl
|
|
351
|
-
|
|
349
|
+
const resp = await this.#getUpdates({
|
|
350
|
+
baseUrl: this.client.apiBaseUrl,
|
|
351
|
+
metadata: this.#metadata,
|
|
352
|
+
token: this.#creds.botToken,
|
|
352
353
|
get_updates_buf: getUpdatesBuf,
|
|
353
354
|
timeoutMs: nextTimeoutMs,
|
|
354
355
|
abortSignal,
|
|
@@ -359,21 +360,21 @@ export class WeixinIlinkEndpoint implements Endpoint<WeixinIlinkEndpointConfig,
|
|
|
359
360
|
}
|
|
360
361
|
|
|
361
362
|
const isApiError =
|
|
362
|
-
(resp.ret !== undefined && resp.ret !== 0)
|
|
363
|
-
(resp.errcode !== undefined && resp.errcode !== 0);
|
|
363
|
+
(resp.ret !== undefined && resp.ret !== 0)
|
|
364
|
+
|| (resp.errcode !== undefined && resp.errcode !== 0);
|
|
364
365
|
|
|
365
366
|
if (isApiError) {
|
|
366
367
|
const sessionExpired =
|
|
367
368
|
resp.errcode === SESSION_EXPIRED_ERRCODE || resp.ret === SESSION_EXPIRED_ERRCODE;
|
|
368
369
|
if (sessionExpired) {
|
|
369
|
-
|
|
370
|
+
this.#sessionGuard.pause();
|
|
370
371
|
consecutiveFailures = 0;
|
|
371
|
-
await sleep(
|
|
372
|
+
await sleep(this.#sessionGuard.remainingMs, abortSignal);
|
|
372
373
|
continue;
|
|
373
374
|
}
|
|
374
375
|
consecutiveFailures += 1;
|
|
376
|
+
// 退避后不清零:对端持续挂时清零会让重试固定打满 RETRY_DELAY_MS。
|
|
375
377
|
if (consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
|
|
376
|
-
consecutiveFailures = 0;
|
|
377
378
|
await sleep(BACKOFF_DELAY_MS, abortSignal);
|
|
378
379
|
} else {
|
|
379
380
|
await sleep(RETRY_DELAY_MS, abortSignal);
|
|
@@ -382,20 +383,24 @@ export class WeixinIlinkEndpoint implements Endpoint<WeixinIlinkEndpointConfig,
|
|
|
382
383
|
}
|
|
383
384
|
|
|
384
385
|
consecutiveFailures = 0;
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
saveSyncBuf(this.$id, getUpdatesBuf);
|
|
388
|
-
}
|
|
389
|
-
|
|
386
|
+
// 先分发再推进 buf:分发途中崩溃时 buf 未推进,下一轮重拉不丢消息。
|
|
387
|
+
const nextBuf = resp.get_updates_buf;
|
|
390
388
|
for (const inbound of resp.msgs ?? []) {
|
|
391
|
-
await this
|
|
389
|
+
await this.#handleInboundMessage(inbound);
|
|
390
|
+
}
|
|
391
|
+
if (nextBuf) {
|
|
392
|
+
getUpdatesBuf = nextBuf;
|
|
393
|
+
this.#state.saveSyncBuf(getUpdatesBuf);
|
|
392
394
|
}
|
|
393
395
|
} catch (err) {
|
|
394
396
|
if (abortSignal.aborted) return;
|
|
395
397
|
consecutiveFailures += 1;
|
|
396
|
-
this.
|
|
398
|
+
this.#logger.error(formatCompact({
|
|
399
|
+
op: 'poll',
|
|
400
|
+
ok: false,
|
|
401
|
+
error: err instanceof Error ? err.message : String(err),
|
|
402
|
+
}));
|
|
397
403
|
if (consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
|
|
398
|
-
consecutiveFailures = 0;
|
|
399
404
|
await sleep(BACKOFF_DELAY_MS, abortSignal);
|
|
400
405
|
} else {
|
|
401
406
|
await sleep(RETRY_DELAY_MS, abortSignal);
|
|
@@ -404,80 +409,144 @@ export class WeixinIlinkEndpoint implements Endpoint<WeixinIlinkEndpointConfig,
|
|
|
404
409
|
}
|
|
405
410
|
}
|
|
406
411
|
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
+
async #handleInboundMessage(full: WeixinMessage): Promise<void> {
|
|
413
|
+
void this.#emitPlatformEvent(`message.${full.message_type ?? 'unknown'}`, full);
|
|
414
|
+
const fromUserId = full.from_user_id ?? '';
|
|
415
|
+
|
|
416
|
+
const mediaOpts = await this.#downloadInboundMedia(full);
|
|
417
|
+
this.admit({ ...full, _media: mediaOpts });
|
|
418
|
+
this.#logger.debug(formatCompact({
|
|
419
|
+
op: 'recv',
|
|
420
|
+
endpoint: this.#options.config.id,
|
|
421
|
+
target: fromUserId,
|
|
422
|
+
preview: formatInboundContent({ ...full, _media: mediaOpts }).slice(0, 80),
|
|
423
|
+
}));
|
|
424
|
+
}
|
|
412
425
|
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
);
|
|
426
|
+
async #emitPlatformEvent(name: string, event: unknown): Promise<void> {
|
|
427
|
+
await this.emitPlatform(name, event).catch((error) => {
|
|
428
|
+
this.#logger.warn(formatCompact({
|
|
429
|
+
op: 'weixin_ilink_platform_event_failed',
|
|
430
|
+
event: name,
|
|
431
|
+
error: error instanceof Error ? error.message : String(error),
|
|
432
|
+
}));
|
|
433
|
+
});
|
|
421
434
|
}
|
|
422
435
|
|
|
423
|
-
|
|
436
|
+
async #downloadInboundMedia(full: WeixinMessage): Promise<WeixinInboundMediaOpts> {
|
|
424
437
|
const hasDownloadableMedia = (m?: { encrypt_query_param?: string; full_url?: string }) =>
|
|
425
438
|
Boolean(m?.encrypt_query_param || m?.full_url);
|
|
426
439
|
|
|
427
440
|
const mediaItem =
|
|
428
441
|
full.item_list?.find(
|
|
429
442
|
(i) => i.type === MessageItemType.IMAGE && hasDownloadableMedia(i.image_item?.media),
|
|
430
|
-
)
|
|
431
|
-
full.item_list?.find(
|
|
443
|
+
)
|
|
444
|
+
?? full.item_list?.find(
|
|
432
445
|
(i) => i.type === MessageItemType.VIDEO && hasDownloadableMedia(i.video_item?.media),
|
|
433
|
-
)
|
|
434
|
-
full.item_list?.find(
|
|
446
|
+
)
|
|
447
|
+
?? full.item_list?.find(
|
|
435
448
|
(i) => i.type === MessageItemType.FILE && hasDownloadableMedia(i.file_item?.media),
|
|
436
|
-
)
|
|
437
|
-
full.item_list?.find(
|
|
449
|
+
)
|
|
450
|
+
?? full.item_list?.find(
|
|
438
451
|
(i) => i.type === MessageItemType.VOICE && hasDownloadableMedia(i.voice_item?.media),
|
|
439
452
|
);
|
|
440
453
|
|
|
441
454
|
if (!mediaItem) return {};
|
|
442
455
|
|
|
443
456
|
return downloadMediaFromItem(mediaItem, {
|
|
444
|
-
cdnBaseUrl: this.cdnBaseUrl
|
|
457
|
+
cdnBaseUrl: this.client.cdnBaseUrl,
|
|
445
458
|
saveMedia: (buffer, contentType, subdir, maxBytes, originalFilename) =>
|
|
446
|
-
this
|
|
447
|
-
log: (msg) => this.
|
|
448
|
-
errLog: (msg) => this.
|
|
449
|
-
label: `inbound:${
|
|
459
|
+
this.#saveInboundMedia(buffer, contentType, subdir, maxBytes, originalFilename),
|
|
460
|
+
log: (msg) => this.#logger.debug(msg),
|
|
461
|
+
errLog: (msg) => this.#logger.warn(msg),
|
|
462
|
+
label: `inbound:${full.from_user_id ?? 'unknown'}`,
|
|
450
463
|
});
|
|
451
464
|
}
|
|
452
465
|
|
|
453
|
-
|
|
466
|
+
async #saveInboundMedia(
|
|
454
467
|
buffer: Buffer,
|
|
455
468
|
contentType?: string,
|
|
456
|
-
subdir =
|
|
469
|
+
subdir = 'inbound',
|
|
457
470
|
maxBytes = WEIXIN_MEDIA_MAX_BYTES,
|
|
458
471
|
originalFilename?: string,
|
|
459
472
|
): Promise<{ path: string }> {
|
|
460
473
|
if (buffer.length > maxBytes) {
|
|
461
474
|
throw new Error(`media exceeds max size ${maxBytes}`);
|
|
462
475
|
}
|
|
463
|
-
const dir =
|
|
476
|
+
const dir = this.#state.mediaDirectory(subdir);
|
|
464
477
|
fs.mkdirSync(dir, { recursive: true });
|
|
465
478
|
const resolvedMime = contentType ?? sniffMimeFromBuffer(buffer);
|
|
466
479
|
const ext = originalFilename
|
|
467
480
|
? path.extname(originalFilename)
|
|
468
481
|
: resolvedMime
|
|
469
482
|
? getExtensionFromMime(resolvedMime)
|
|
470
|
-
:
|
|
483
|
+
: '.bin';
|
|
471
484
|
const base = originalFilename
|
|
472
485
|
? path.basename(originalFilename, ext)
|
|
473
|
-
:
|
|
474
|
-
const fileName = `${base}-${Date.now()}-${crypto.randomBytes(4).toString(
|
|
486
|
+
: 'media';
|
|
487
|
+
const fileName = `${base}-${Date.now()}-${crypto.randomBytes(4).toString('hex')}${ext}`;
|
|
475
488
|
const filePath = path.join(dir, fileName);
|
|
476
489
|
fs.writeFileSync(filePath, buffer);
|
|
477
490
|
return { path: filePath };
|
|
478
491
|
}
|
|
492
|
+
|
|
493
|
+
/** 入站媒体 TTL 清扫:start 时立即扫一次,之后每小时扫一次。 */
|
|
494
|
+
#startMediaSweep(): void {
|
|
495
|
+
this.#stopMediaSweep();
|
|
496
|
+
const sweep = () => this.#sweepInboundMedia();
|
|
497
|
+
sweep();
|
|
498
|
+
this.#mediaSweepTimer = setInterval(sweep, MEDIA_SWEEP_INTERVAL_MS);
|
|
499
|
+
(this.#mediaSweepTimer as { unref?: () => void }).unref?.();
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
#stopMediaSweep(): void {
|
|
503
|
+
if (this.#mediaSweepTimer) {
|
|
504
|
+
clearInterval(this.#mediaSweepTimer);
|
|
505
|
+
this.#mediaSweepTimer = undefined;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
#sweepInboundMedia(): void {
|
|
510
|
+
const dir = this.#state.mediaDirectory('inbound');
|
|
511
|
+
let entries: fs.Dirent[];
|
|
512
|
+
try {
|
|
513
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
514
|
+
} catch {
|
|
515
|
+
return;
|
|
516
|
+
}
|
|
517
|
+
const now = Date.now();
|
|
518
|
+
for (const entry of entries) {
|
|
519
|
+
if (!entry.isFile()) continue;
|
|
520
|
+
const filePath = path.join(dir, entry.name);
|
|
521
|
+
try {
|
|
522
|
+
const stat = fs.statSync(filePath);
|
|
523
|
+
if (now - stat.mtimeMs <= INBOUND_MEDIA_TTL_MS) continue;
|
|
524
|
+
fs.unlinkSync(filePath);
|
|
525
|
+
this.#logger.debug(formatCompact({
|
|
526
|
+
op: 'media_sweep',
|
|
527
|
+
endpoint: this.#options.config.id,
|
|
528
|
+
file: entry.name,
|
|
529
|
+
}));
|
|
530
|
+
} catch {
|
|
531
|
+
/* 单个文件失败不阻塞整体清扫 */
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
}
|
|
479
535
|
}
|
|
480
536
|
|
|
481
|
-
function
|
|
482
|
-
|
|
537
|
+
function createWeixinIlinkEndpointManagement(
|
|
538
|
+
requireClient: () => WeixinIlinkClient,
|
|
539
|
+
): EndpointManagement {
|
|
540
|
+
return Object.freeze<EndpointManagement>({
|
|
541
|
+
// 个人微信无群概念(listGroups/listGroupMembers 不接),也没有通讯录/资料接口。
|
|
542
|
+
// "好友"只能从会话推导:凡持有 context_token 的对端(来过消息,含重启后从磁盘恢复的)
|
|
543
|
+
// 即为可达私聊对端;昵称不可得,用 user_id 占位并在 remark 注明来源。
|
|
544
|
+
async listFriends(): Promise<readonly EndpointFriend[]> {
|
|
545
|
+
return requireClient().reachableUserIds().map((userId) => ({
|
|
546
|
+
user_id: userId,
|
|
547
|
+
nickname: userId,
|
|
548
|
+
remark: 'ilink: 从会话 context_token 推导,非通讯录',
|
|
549
|
+
}));
|
|
550
|
+
},
|
|
551
|
+
});
|
|
483
552
|
}
|