@ascegu/teamily 1.0.7 → 1.0.9

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.
Files changed (2) hide show
  1. package/package.json +2 -1
  2. package/src/monitor.ts +128 -297
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ascegu/teamily",
3
- "version": "1.0.7",
3
+ "version": "1.0.9",
4
4
  "description": "OpenClaw Teamily channel plugin - Team instant messaging server integration",
5
5
  "keywords": [
6
6
  "channel",
@@ -29,6 +29,7 @@
29
29
  "type": "module",
30
30
  "main": "index.ts",
31
31
  "dependencies": {
32
+ "@openim/client-sdk": "^3.8.3",
32
33
  "zod": "^4.3.6"
33
34
  },
34
35
  "openclaw": {
package/src/monitor.ts CHANGED
@@ -1,4 +1,3 @@
1
- import { generateOperationID } from "./probe.js";
2
1
  import type {
3
2
  ResolvedTeamilyAccount,
4
3
  TeamilyMessage,
@@ -8,11 +7,6 @@ import type {
8
7
  } from "./types.js";
9
8
  import { CONTENT_TYPES, SESSION_TYPES } from "./types.js";
10
9
 
11
- const WS_REQ = {
12
- LOGIN: 1001,
13
- HEARTBEAT: 1002,
14
- } as const;
15
-
16
10
  export type TeamilyMessageHandler = (message: TeamilyMessage) => Promise<void> | void;
17
11
  export type TeamilyConnectionState = "connecting" | "connected" | "disconnected" | "error";
18
12
 
@@ -20,358 +14,198 @@ export interface TeamilyMonitorOptions {
20
14
  account: ResolvedTeamilyAccount;
21
15
  onMessage: TeamilyMessageHandler;
22
16
  onStateChange?: (state: TeamilyConnectionState, error?: string) => void;
23
- reconnectInterval?: number;
24
- pingInterval?: number;
25
- websocketImpl?: typeof WebSocket;
17
+ }
18
+
19
+ type SdkModule = typeof import("@openim/client-sdk");
20
+ type SdkInstance = ReturnType<SdkModule["getSDK"]>;
21
+
22
+ // Lazy-loaded SDK to avoid top-level dynamic import issues
23
+ let sdkModule: SdkModule | null = null;
24
+ async function loadSDK() {
25
+ if (!sdkModule) {
26
+ sdkModule = await import("@openim/client-sdk");
27
+ }
28
+ return sdkModule;
26
29
  }
27
30
 
28
31
  /**
29
- * Monitor for incoming Teamily messages via WebSocket.
32
+ * Monitor for incoming Teamily messages using @openim/client-sdk.
30
33
  *
31
- * This class manages a WebSocket connection to the Teamily server
32
- * and handles incoming messages, reconnections, and heartbeat pings.
34
+ * Delegates WebSocket connection, authentication, heartbeat, and
35
+ * reconnection to the official OpenIM SDK.
33
36
  */
34
37
  export class TeamilyMonitor {
35
38
  private account: ResolvedTeamilyAccount;
36
39
  private onMessage: TeamilyMessageHandler;
37
40
  private onStateChange?: (state: TeamilyConnectionState, error?: string) => void;
38
- private reconnectInterval: number;
39
- private pingInterval: number;
40
- private ws: WebSocket | null = null;
41
- private pingTimer: NodeJS.Timeout | null = null;
42
- private reconnectTimer: NodeJS.Timeout | null = null;
41
+ private sdk: SdkInstance | null = null;
43
42
  private state: TeamilyConnectionState = "disconnected";
44
- private shouldReconnect = true;
45
- private authenticated = false;
46
- private wsImpl: typeof WebSocket;
43
+ private stopped = false;
47
44
 
48
45
  constructor(options: TeamilyMonitorOptions) {
49
46
  this.account = options.account;
50
47
  this.onMessage = options.onMessage;
51
48
  this.onStateChange = options.onStateChange;
52
- this.reconnectInterval = options.reconnectInterval ?? 5000;
53
- this.pingInterval = options.pingInterval ?? 30000;
54
- this.wsImpl = options.websocketImpl ?? WebSocket;
55
49
  }
56
50
 
57
- /**
58
- * Start monitoring for messages.
59
- */
60
51
  async start(): Promise<void> {
61
- this.shouldReconnect = true;
62
- await this.connect();
63
- }
64
-
65
- /**
66
- * Stop monitoring and close the connection.
67
- */
68
- stop(): void {
69
- this.shouldReconnect = false;
70
- this.authenticated = false;
71
-
72
- if (this.reconnectTimer) {
73
- clearTimeout(this.reconnectTimer);
74
- this.reconnectTimer = null;
75
- }
76
-
77
- if (this.pingTimer) {
78
- clearInterval(this.pingTimer);
79
- this.pingTimer = null;
80
- }
81
-
82
- if (this.ws) {
83
- const ws = this.ws;
84
- ws.onopen = null;
85
- ws.onmessage = null;
86
- ws.onerror = null;
87
- ws.onclose = null;
88
- this.ws = null;
89
- try {
90
- ws.close(1000, "Monitoring stopped");
91
- } catch {
92
- // Ignore – socket may already be closed.
93
- }
94
- }
95
-
96
- this.setState("disconnected");
97
- }
98
-
99
- /**
100
- * Connect to the Teamily WebSocket server.
101
- */
102
- private async connect(): Promise<void> {
103
- if (!this.shouldReconnect) {
104
- return;
105
- }
106
-
52
+ this.stopped = false;
107
53
  this.setState("connecting");
108
54
 
109
- const wsUrl = new URL(this.account.wsURL);
110
- wsUrl.searchParams.set("token", this.account.token);
111
-
112
- try {
113
- const ws = new this.wsImpl(wsUrl.toString()) as WebSocket & { isMock?: boolean };
114
- this.ws = ws;
115
-
116
- ws.onopen = () => this.handleOpen();
117
- ws.onmessage = (event) => this.handleMessage(event);
118
- ws.onerror = (error) => this.handleError(error);
119
- ws.onclose = () => this.handleClose();
120
- } catch (error) {
121
- this.handleError(error);
122
- }
123
- }
124
-
125
- /**
126
- * Handle WebSocket connection opened.
127
- */
128
- private handleOpen(): void {
129
- this.sendAuth();
130
- }
131
-
132
- /**
133
- * Send authentication message after WebSocket connection opens.
134
- */
135
- private sendAuth(): void {
136
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
137
- return;
138
- }
139
- try {
140
- this.ws.send(
141
- JSON.stringify({
142
- reqIdentifier: WS_REQ.LOGIN,
143
- operationID: generateOperationID(),
144
- sendID: this.account.userID,
145
- token: this.account.token,
146
- platformID: 5,
147
- }),
148
- );
149
- } catch (error) {
150
- this.handleError(error);
151
- }
152
- }
153
-
154
- /**
155
- * Handle incoming WebSocket message.
156
- */
157
- private async handleMessage(event: MessageEvent): Promise<void> {
158
- try {
159
- const data = JSON.parse(event.data) as {
160
- reqIdentifier?: number;
161
- errCode?: number;
162
- errMsg?: string;
163
- msgID?: string;
164
- sendID?: string;
165
- msgFrom?: string;
166
- recvID?: string;
167
- contentType?: number;
168
- content?: unknown;
169
- sessionType?: number;
170
- sendTime?: number;
171
- };
172
-
173
- // Handle login response
174
- if (data.reqIdentifier === WS_REQ.LOGIN) {
175
- if (data.errCode === 0) {
176
- this.authenticated = true;
177
- this.setState("connected");
178
- this.startPing();
179
- } else {
180
- this.setState("error", data.errMsg || "Authentication failed");
181
- this.ws?.close();
55
+ const { getSDK, CbEvents } = await loadSDK();
56
+ const sdk = getSDK();
57
+ this.sdk = sdk;
58
+
59
+ // Connection events
60
+ sdk.on(CbEvents.OnConnecting, () => {
61
+ if (!this.stopped) this.setState("connecting");
62
+ });
63
+ sdk.on(CbEvents.OnConnectSuccess, () => {
64
+ if (!this.stopped) this.setState("connected");
65
+ });
66
+ sdk.on(CbEvents.OnConnectFailed, ({ errCode, errMsg }) => {
67
+ if (!this.stopped) this.setState("error", `[${errCode}] ${errMsg}`);
68
+ });
69
+ sdk.on(CbEvents.OnKickedOffline, () => {
70
+ if (!this.stopped) this.setState("error", "Kicked offline");
71
+ });
72
+ sdk.on(CbEvents.OnUserTokenExpired, () => {
73
+ if (!this.stopped) this.setState("error", "Token expired");
74
+ });
75
+
76
+ // Incoming messages
77
+ sdk.on(CbEvents.OnRecvNewMessages, ({ data }) => {
78
+ if (this.stopped || !data) return;
79
+ for (const msg of data) {
80
+ // Skip self-sent messages
81
+ if (msg.sendID === this.account.userID) continue;
82
+ const converted = convertSdkMessage(msg, this.account.userID);
83
+ if (converted) {
84
+ // Fire-and-forget; errors are logged by the gateway dispatcher
85
+ void this.onMessage(converted);
182
86
  }
183
- return;
184
- }
185
-
186
- // Ignore heartbeat responses
187
- if (data.reqIdentifier === WS_REQ.HEARTBEAT) {
188
- return;
189
- }
190
-
191
- if (!this.authenticated) {
192
- return;
193
87
  }
88
+ });
194
89
 
195
- const contentType = data.contentType || CONTENT_TYPES.TEXT;
196
-
197
- const message: TeamilyMessage = {
198
- serverMsgID: data.msgID || `${Date.now()}_${Math.random()}`,
199
- sendID: data.sendID || data.msgFrom || "unknown",
200
- recvID: data.recvID || this.account.userID,
201
- content: parseMessageContent(data.content, contentType),
202
- contentType,
203
- sessionType: data.sessionType || SESSION_TYPES.SINGLE,
204
- sendTime: data.sendTime || Date.now(),
205
- };
206
-
207
- await this.onMessage(message);
208
- } catch (error) {
209
- console.error("Failed to parse Teamily message:", error);
210
- }
211
- }
212
-
213
- /**
214
- * Handle WebSocket error.
215
- * Detaches event handlers before closing to prevent recursive calls
216
- * (ws.close() on an errored socket can re-fire onerror → stack overflow).
217
- */
218
- private handleError(error: unknown): void {
219
- const errorMessage = error instanceof Error ? error.message : String(error);
220
- this.setState("error", errorMessage);
221
-
222
- // Detach handlers and grab ref before nulling, so close() cannot recurse.
223
- const ws = this.ws;
224
- if (ws) {
225
- ws.onopen = null;
226
- ws.onmessage = null;
227
- ws.onerror = null;
228
- ws.onclose = null;
229
- this.ws = null;
230
- try {
231
- ws.close();
232
- } catch {
233
- // Ignore – socket may already be closed/invalid.
234
- }
235
- // onclose was detached, so manually trigger reconnect logic.
236
- this.handleClose();
237
- }
238
- }
239
-
240
- /**
241
- * Handle WebSocket connection closed.
242
- */
243
- private handleClose(): void {
244
- this.stopPing();
245
- this.authenticated = false;
246
-
247
- if (this.state === "disconnected" || !this.shouldReconnect) {
248
- return;
90
+ try {
91
+ await sdk.login({
92
+ userID: this.account.userID,
93
+ token: this.account.token,
94
+ platformID: 5,
95
+ wsAddr: this.account.wsURL,
96
+ apiAddr: this.account.apiURL,
97
+ });
98
+ } catch (err) {
99
+ const msg = err instanceof Error ? err.message : String(err);
100
+ this.setState("error", msg);
101
+ throw err;
249
102
  }
250
-
251
- // Schedule reconnection
252
- this.reconnectTimer = setTimeout(() => {
253
- if (this.shouldReconnect) {
254
- this.connect();
255
- }
256
- }, this.reconnectInterval);
257
- }
258
-
259
- /**
260
- * Start heartbeat ping interval.
261
- */
262
- private startPing(): void {
263
- this.stopPing();
264
-
265
- this.pingTimer = setInterval(() => {
266
- this.sendPing();
267
- }, this.pingInterval);
268
103
  }
269
104
 
270
- /**
271
- * Stop heartbeat ping.
272
- */
273
- private stopPing(): void {
274
- if (this.pingTimer) {
275
- clearInterval(this.pingTimer);
276
- this.pingTimer = null;
105
+ stop(): void {
106
+ this.stopped = true;
107
+ if (this.sdk) {
108
+ this.sdk.logout().catch(() => {});
109
+ this.sdk = null;
277
110
  }
111
+ this.setState("disconnected");
278
112
  }
279
113
 
280
- /**
281
- * Send ping to keep connection alive.
282
- */
283
- private sendPing(): void {
284
- if (this.ws && this.ws.readyState === WebSocket.OPEN) {
285
- try {
286
- this.ws.send(
287
- JSON.stringify({
288
- reqIdentifier: WS_REQ.HEARTBEAT,
289
- operationID: generateOperationID(),
290
- sendID: this.account.userID,
291
- sendTime: Date.now(),
292
- }),
293
- );
294
- } catch (error) {
295
- console.error("Teamily ping failed:", error);
296
- }
297
- }
114
+ getState(): TeamilyConnectionState {
115
+ return this.state;
298
116
  }
299
117
 
300
- /**
301
- * Update and notify connection state.
302
- */
303
118
  private setState(state: TeamilyConnectionState, error?: string): void {
304
119
  this.state = state;
305
120
  this.onStateChange?.(state, error);
306
121
  }
307
-
308
- /**
309
- * Get current connection state.
310
- */
311
- getState(): TeamilyConnectionState {
312
- return this.state;
313
- }
314
122
  }
315
123
 
316
- /**
317
- * Parse raw OpenIM message content into normalized internal format.
318
- * OpenIM text messages use `{ content: "text" }`, not `{ text: "..." }`.
319
- */
320
- function parseMessageContent(raw: unknown, contentType: number): TeamilyMessage["content"] {
321
- if (!raw) {
322
- return {};
124
+ // ---- SDK message conversion helpers ----
125
+
126
+ import type { MessageItem } from "@openim/client-sdk";
127
+
128
+ function convertSdkMessage(msg: MessageItem, selfUserID: string): TeamilyMessage | null {
129
+ const contentType = msg.contentType ?? CONTENT_TYPES.TEXT;
130
+ const sessionType = msg.sessionType ?? SESSION_TYPES.SINGLE;
131
+
132
+ const content = parseSdkContent(msg, contentType);
133
+
134
+ // Skip messages with no usable content
135
+ if (!content.text && !content.picture && !content.video && !content.audio) {
136
+ return null;
323
137
  }
324
138
 
325
- const obj = (typeof raw === "string" ? JSON.parse(raw) : raw) as Record<string, unknown>;
139
+ return {
140
+ serverMsgID: msg.serverMsgID || msg.clientMsgID || `${Date.now()}_${Math.random()}`,
141
+ sendID: msg.sendID || "unknown",
142
+ recvID: sessionType === SESSION_TYPES.GROUP ? (msg.groupID || "") : (msg.recvID || selfUserID),
143
+ content,
144
+ contentType,
145
+ sessionType,
146
+ sendTime: msg.sendTime || Date.now(),
147
+ };
148
+ }
326
149
 
150
+ function parseSdkContent(msg: MessageItem, contentType: number): TeamilyMessage["content"] {
327
151
  switch (contentType) {
328
- case CONTENT_TYPES.TEXT:
329
- return {
330
- text: typeof obj.content === "string" ? obj.content : String(obj.content ?? ""),
331
- };
152
+ case CONTENT_TYPES.TEXT: {
153
+ // SDK puts text in textElem.content; fallback to raw content string
154
+ const text = msg.textElem?.content ?? tryParseTextContent(msg.content);
155
+ return text ? { text } : {};
156
+ }
332
157
  case CONTENT_TYPES.PICTURE:
333
- return { picture: obj as unknown as TeamilyPictureContent };
158
+ if (msg.pictureElem?.sourcePicture) {
159
+ return { picture: msg.pictureElem as unknown as TeamilyPictureContent };
160
+ }
161
+ return {};
334
162
  case CONTENT_TYPES.VIDEO:
335
- return { video: obj as unknown as TeamilyVideoContent };
163
+ if (msg.videoElem?.videoUrl) {
164
+ return { video: msg.videoElem as unknown as TeamilyVideoContent };
165
+ }
166
+ return {};
336
167
  case CONTENT_TYPES.VOICE:
337
- return { audio: obj as unknown as TeamilyAudioContent };
168
+ if (msg.soundElem?.sourceUrl) {
169
+ return { audio: msg.soundElem as unknown as TeamilyAudioContent };
170
+ }
171
+ return {};
338
172
  default:
339
173
  return {};
340
174
  }
341
175
  }
342
176
 
343
- /**
344
- * Global monitor instances per account ID.
345
- */
177
+ /** Try to extract text from the raw JSON content string (OpenIM text format: `{"content":"..."}`) */
178
+ function tryParseTextContent(raw: string | undefined): string | undefined {
179
+ if (!raw) return undefined;
180
+ try {
181
+ const obj = JSON.parse(raw) as { content?: string };
182
+ return typeof obj.content === "string" ? obj.content : undefined;
183
+ } catch {
184
+ return raw;
185
+ }
186
+ }
187
+
188
+ // ---- Global monitor registry ----
189
+
346
190
  const monitors = new Map<string, TeamilyMonitor>();
347
191
 
348
- /**
349
- * Start monitoring for a Teamily account.
350
- */
351
192
  export function startTeamilyMonitoring(
352
193
  account: ResolvedTeamilyAccount,
353
194
  onMessage: TeamilyMessageHandler,
354
195
  onStateChange?: (state: TeamilyConnectionState, error?: string) => void,
355
196
  ): () => void {
356
- const monitor = new TeamilyMonitor({
357
- account,
358
- onMessage,
359
- onStateChange,
360
- });
361
-
197
+ const monitor = new TeamilyMonitor({ account, onMessage, onStateChange });
362
198
  monitors.set(account.accountId, monitor);
363
- monitor.start();
199
+ monitor.start().catch((err) => {
200
+ console.error(`Teamily monitor start failed for ${account.accountId}:`, err);
201
+ });
364
202
 
365
- // Return cleanup function
366
203
  return () => {
367
204
  monitor.stop();
368
205
  monitors.delete(account.accountId);
369
206
  };
370
207
  }
371
208
 
372
- /**
373
- * Stop monitoring for a Teamily account.
374
- */
375
209
  export function stopTeamilyMonitoring(accountId: string): void {
376
210
  const monitor = monitors.get(accountId);
377
211
  if (monitor) {
@@ -380,9 +214,6 @@ export function stopTeamilyMonitoring(accountId: string): void {
380
214
  }
381
215
  }
382
216
 
383
- /**
384
- * Get monitor for an account.
385
- */
386
217
  export function getTeamilyMonitor(accountId: string): TeamilyMonitor | undefined {
387
218
  return monitors.get(accountId);
388
219
  }