-
Notifications
You must be signed in to change notification settings - Fork 117
Expand file tree
/
Copy pathwatcher.ts
More file actions
285 lines (252 loc) · 9.8 KB
/
watcher.ts
File metadata and controls
285 lines (252 loc) · 9.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
/**
* Message Watcher
*/
import type { PluginManager } from '../plugins/core'
import type { WebhookConfig } from '../types/config'
import type { Message } from '../types/message'
import type { IMessageDatabase } from './database'
import { WebhookError } from './errors'
import type { OutgoingMessageManager } from './outgoing-manager'
/** Message callback */
export type MessageCallback = (message: Message) => void | Promise<void>
/** Watcher event callbacks */
export interface WatcherEvents {
/** Triggered when any new message arrives (DM or group) */
onMessage?: MessageCallback
/** Triggered when new direct message arrives */
onDirectMessage?: MessageCallback
/** Triggered when new group message arrives */
onGroupMessage?: MessageCallback
/** Triggered when error occurs */
onError?: (error: Error) => void
/** How far back (ms) to look for messages when the watcher first starts. Defaults to 10 000. */
initialLookbackMs?: number
/** Called after each successful poll with the current checkpoint time. Persist this externally
* and pass it back as `initialLookbackMs` on restart to avoid missing messages. */
onCheckpoint?: (lastCheckTime: Date) => void
}
/**
* Message Watcher Class
*/
export class MessageWatcher {
/** Whether currently running */
private isRunning = false
/** Polling timer ID */
private intervalId: ReturnType<typeof setInterval> | null = null
/** Whether currently checking */
private isChecking = false
/** Last check time (for incremental queries) */
private lastCheckTime: Date
/** Set of processed message IDs (simple deduplication) */
private seenMessageIds = new Map<string, number>()
constructor(
private database: IMessageDatabase,
private pollInterval: number,
private unreadOnly: boolean,
private excludeOwnMessages: boolean,
private webhookConfig: WebhookConfig | null,
private events: WatcherEvents = {},
private pluginManager?: PluginManager,
private debug = false,
private outgoingManager?: OutgoingMessageManager,
initialLookbackMs = 10000
) {
// Start from initialLookbackMs ago to catch recently sent messages
// Default 10 seconds helps catch messages sent just before watcher starts
// Note: This may cause duplicate processing if watcher is frequently restarted
this.lastCheckTime = new Date(Date.now() - initialLookbackMs)
}
/**
* Start watching for new messages
*/
async start(): Promise<void> {
if (this.isRunning) return
this.isRunning = true
if (this.debug) {
console.log(`[Watcher] Started (poll interval: ${this.pollInterval}ms)`)
}
try {
await this.check()
} catch (error) {
this.isRunning = false
throw error
}
this.intervalId = setInterval(() => {
this.check().catch((error) => {
this.handleError(error)
})
}, this.pollInterval)
}
/**
* Stop watching
*/
stop(): void {
if (!this.isRunning) return
this.isRunning = false
if (this.intervalId) {
clearInterval(this.intervalId)
this.intervalId = null
}
if (this.debug) {
console.log('[Watcher] Stopped')
}
}
/**
* Check for new messages
*/
private async check() {
if (this.isChecking) return
this.isChecking = true
try {
const overlapMs = Math.min(1000, this.pollInterval)
const checkStart = new Date()
const since = new Date(this.lastCheckTime.getTime() - overlapMs)
const { messages } = await this.database.getMessages({
since,
excludeOwnMessages: false, // Always fetch own messages for outgoing resolution
})
this.lastCheckTime = checkStart
this.events.onCheckpoint?.(checkStart)
/** Filter out new messages */
let newMessages = messages.filter((msg) => !this.seenMessageIds.has(msg.id))
/** Try to resolve outgoing messages BEFORE filtering (critical for reliable send) */
if (this.outgoingManager) {
for (const msg of newMessages) {
if (msg.isFromMe) {
const matched = this.outgoingManager.tryResolve(msg)
if (this.debug && matched) {
console.log(`[Watcher] Resolved outgoing message: ${msg.id}`)
}
}
}
}
/** Filter by unread status if configured */
if (this.unreadOnly) {
newMessages = newMessages.filter((msg) => !msg.isRead)
}
/** Filter out own messages if configured (default: true) */
if (this.excludeOwnMessages) {
newMessages = newMessages.filter((msg) => !msg.isFromMe)
}
/** Mark as processed */
const now = Date.now()
for (const msg of newMessages) {
this.seenMessageIds.set(msg.id, now)
}
/** Process all new messages concurrently */
await Promise.all(
newMessages.map((msg) => this.handleNewMessage(msg).catch((err) => this.handleError(err)))
)
/** Keep only messages from last 1 hour */
if (this.seenMessageIds.size > 10000) {
const hourAgo = now - 3600000
for (const [id, timestamp] of this.seenMessageIds.entries()) {
if (timestamp < hourAgo) {
this.seenMessageIds.delete(id)
}
}
}
/** Cleanup resolved outgoing message promises */
if (this.outgoingManager) {
this.outgoingManager.cleanup()
}
} catch (error) {
this.handleError(error)
} finally {
this.isChecking = false
}
}
/**
* Handle new message
* Triggers in sequence: Plugin hooks -> Event callback -> Webhook notification
* @param message New message object
*/
private async handleNewMessage(message: Message) {
try {
/** Call plugin's onNewMessage hook */
await this.pluginManager?.callHookForAll('onNewMessage', message)
/** Call onMessage for all messages */
await this.events.onMessage?.(message)
/** Dispatch to specific callbacks based on message type */
if (message.isGroupChat) {
await this.events.onGroupMessage?.(message)
} else {
await this.events.onDirectMessage?.(message)
}
/** Send webhook notification */
if (this.webhookConfig) await this.sendWebhook(message)
} catch (error) {
this.handleError(error)
}
}
/**
* Send webhook notification
* POST message data to configured webhook URL
* @param message Message to notify
*/
private async sendWebhook(message: Message): Promise<void> {
if (!this.webhookConfig) return
const retries = this.webhookConfig.retries ?? 0
const backoffMs = this.webhookConfig.backoffMs ?? 0
let lastError: unknown = null
for (let attempt = 0; attempt <= retries; attempt++) {
try {
const response = await fetch(this.webhookConfig.url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...this.webhookConfig.headers,
},
body: JSON.stringify({
event: 'new_message',
message: {
id: message.id,
text: message.text,
sender: message.sender,
senderName: message.senderName,
isRead: message.isRead,
service: message.service,
hasAttachments: message.attachments.length > 0,
attachments: message.attachments.map((a) => ({
filename: a.filename,
mimeType: a.mimeType,
size: a.size,
isImage: a.isImage,
})),
date: message.date.toISOString(),
},
timestamp: new Date().toISOString(),
}),
signal: AbortSignal.timeout(this.webhookConfig.timeout || 5000),
})
if (!response.ok) {
throw WebhookError(`Webhook failed with status ${response.status}`)
}
// Success
return
} catch (error) {
lastError = error
if (attempt < retries && backoffMs > 0) {
await new Promise((resolve) => setTimeout(resolve, backoffMs))
}
}
}
throw WebhookError(
`Failed to send webhook: ${
lastError instanceof Error ? lastError.message : String(lastError ?? 'unknown error')
}`
)
}
/**
* Unified error handling
* Output error to console and trigger error callback
* @param error Error object of any type
*/
private handleError(error: unknown) {
const err = error instanceof Error ? error : new Error(String(error))
if (this.debug) {
console.error('[Watcher] Error:', err)
}
this.events.onError?.(err)
}
}