File size: 9,168 Bytes
1f21206
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * NotificationService โ€” ๅฎšๆ—ถไปปๅŠกๅฎŒๆˆๅŽ้€š่ฟ‡ IM ๆธ ้“ๆŽจ้€้€š็Ÿฅ
 *
 * ็›ดๆŽฅ่ฐƒ็”จ Telegram Bot API / ้ฃžไนฆ Open API๏ผˆHTTP๏ผ‰๏ผŒไธไพ่ต– adapter sidecar
 * ๆˆ–็ฌฌไธ‰ๆ–น SDK๏ผŒ็กฎไฟๅณไฝฟ adapter ่ฟ›็จ‹ๆœช่ฟ่กŒไนŸ่ƒฝๆŽจ้€ใ€‚
 */

import { adapterService, type AdapterFileConfig } from './adapterService.js'
import type { TaskRun } from './cronScheduler.js'
import type { TaskNotificationConfig } from './cronService.js'

// โ”€โ”€โ”€ Message formatting โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

function formatDuration(ms: number): string {
  if (ms < 60_000) return `${Math.round(ms / 1000)}s`
  const minutes = Math.floor(ms / 60_000)
  const seconds = Math.round((ms % 60_000) / 1000)
  return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`
}

function statusEmoji(status: TaskRun['status']): string {
  switch (status) {
    case 'completed': return 'โœ…'
    case 'failed': return 'โŒ'
    case 'timeout': return 'โฐ'
    default: return 'โ„น๏ธ'
  }
}

function statusText(status: TaskRun['status']): string {
  switch (status) {
    case 'completed': return 'Completed'
    case 'failed': return 'Failed'
    case 'timeout': return 'Timeout'
    default: return status
  }
}

/**
 * Build the markdown notification body.
 * Shared between Telegram and Feishu โ€” both support markdown.
 */
function buildMarkdown(run: TaskRun): string {
  const emoji = statusEmoji(run.status)
  const lines: string[] = []

  lines.push(`${emoji} **${run.taskName}**`)
  lines.push('')
  lines.push(`**Status**: ${statusText(run.status)}`)
  if (run.durationMs != null) {
    lines.push(`**Duration**: ${formatDuration(run.durationMs)}`)
  }

  if (run.status === 'failed' && run.error) {
    lines.push('')
    lines.push('**Error**:')
    const errorText = run.error.length > 500 ? run.error.slice(0, 500) + 'โ€ฆ' : run.error
    lines.push(errorText)
  }

  if (run.output) {
    lines.push('')
    lines.push('**Result**:')
    const outputText = run.output.length > 2000 ? run.output.slice(0, 2000) + 'โ€ฆ' : run.output
    lines.push(outputText)
  }

  return lines.join('\n')
}

// โ”€โ”€โ”€ Telegram โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

const TELEGRAM_API = 'https://api.telegram.org'
const TELEGRAM_TEXT_LIMIT = 4000

async function sendTelegram(
  botToken: string,
  chatId: number | string,
  text: string,
): Promise<void> {
  // Telegram message limit ~4096 chars; trim with margin
  const trimmed = text.length > TELEGRAM_TEXT_LIMIT
    ? text.slice(0, TELEGRAM_TEXT_LIMIT) + 'โ€ฆ'
    : text

  const resp = await fetch(`${TELEGRAM_API}/bot${botToken}/sendMessage`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      chat_id: chatId,
      text: trimmed,
      parse_mode: 'Markdown',
    }),
  })

  if (!resp.ok) {
    const body = await resp.text().catch(() => '')
    console.error(`[Notification] Telegram send failed (${resp.status}):`, body)
  }
}

// โ”€โ”€โ”€ Feishu โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

const FEISHU_API = 'https://open.feishu.cn/open-apis'

async function getFeishuTenantToken(appId: string, appSecret: string): Promise<string | null> {
  try {
    const resp = await fetch(`${FEISHU_API}/auth/v3/tenant_access_token/internal`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ app_id: appId, app_secret: appSecret }),
    })
    const data = await resp.json() as { tenant_access_token?: string; code?: number }
    if (data.code === 0 && data.tenant_access_token) {
      return data.tenant_access_token
    }
    console.error('[Notification] Feishu token failed:', data)
    return null
  } catch (err) {
    console.error('[Notification] Feishu token error:', err)
    return null
  }
}

/**
 * Get or create a P2P chat with a user (needed because Feishu send-message
 * requires a chat_id, and pairedUsers stores open_id).
 */
async function getFeishuChatId(
  token: string,
  userId: string,
): Promise<string | null> {
  try {
    const resp = await fetch(`${FEISHU_API}/im/v1/chats?user_id_type=open_id`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({
        chat_mode: 'p2p',
        user_id_type: 'open_id',
        user_id_list: [userId],
      }),
    })
    const data = await resp.json() as { code?: number; data?: { chat_id?: string } }
    if (data.code === 0 && data.data?.chat_id) {
      return data.data.chat_id
    }
    // Fallback: try sending with open_id directly using receive_id_type=open_id
    return null
  } catch (err) {
    console.error('[Notification] Feishu get chat_id error:', err)
    return null
  }
}

async function sendFeishu(
  token: string,
  userId: string,
  run: TaskRun,
): Promise<void> {
  const emoji = statusEmoji(run.status)
  const headerTemplate = run.status === 'completed' ? 'green' : 'red'
  const headerTitle = `${emoji} ${run.taskName}`

  // Meta line
  const metaLine = [
    `**Status**: ${statusText(run.status)}`,
    run.durationMs != null ? `**Duration**: ${formatDuration(run.durationMs)}` : '',
  ].filter(Boolean).join('ใ€€ใ€€')

  // Result / error content
  const bodyParts: string[] = []
  if (run.status === 'failed' && run.error) {
    const errorText = run.error.length > 500 ? run.error.slice(0, 500) + 'โ€ฆ' : run.error
    bodyParts.push(`**Error**:\n${errorText}`)
  }
  if (run.output) {
    const outputText = run.output.length > 3000 ? run.output.slice(0, 3000) + 'โ€ฆ' : run.output
    bodyParts.push(outputText)
  }

  // Schema 2.0 interactive card โ€” renders markdown correctly
  const elements: Record<string, unknown>[] = [
    { tag: 'markdown', content: metaLine, text_align: 'left' },
  ]
  if (bodyParts.length > 0) {
    elements.push({ tag: 'hr' })
    elements.push({ tag: 'markdown', content: bodyParts.join('\n\n'), text_align: 'left' })
  }

  const card = {
    schema: '2.0',
    header: {
      template: headerTemplate,
      title: { tag: 'plain_text', content: headerTitle },
    },
    body: { elements },
  }

  const resp = await fetch(`${FEISHU_API}/im/v1/messages?receive_id_type=open_id`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify({
      receive_id: userId,
      msg_type: 'interactive',
      content: JSON.stringify(card),
    }),
  })

  if (!resp.ok) {
    const body = await resp.text().catch(() => '')
    console.error(`[Notification] Feishu send failed (${resp.status}):`, body)
  }
}

// โ”€โ”€โ”€ Public API โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

export async function sendTaskNotification(
  run: TaskRun,
  notification: TaskNotificationConfig,
): Promise<void> {
  const imChannels = notification.channels.filter((channel): channel is 'telegram' | 'feishu' =>
    channel === 'telegram' || channel === 'feishu',
  )
  if (!notification.enabled || imChannels.length === 0) return

  let config: AdapterFileConfig
  try {
    config = await adapterService.getRawConfig()
  } catch (err) {
    console.error('[Notification] Failed to read adapter config:', err)
    return
  }

  const markdown = buildMarkdown(run)

  for (const channel of imChannels) {
    try {
      if (channel === 'telegram') {
        const botToken = config.telegram?.botToken
        if (!botToken) {
          console.warn('[Notification] Telegram botToken not configured, skipping')
          continue
        }
        const users = [
          ...(config.telegram?.pairedUsers ?? []),
          ...(config.telegram?.allowedUsers ?? []).map((id) => ({ userId: id })),
        ]
        for (const user of users) {
          await sendTelegram(botToken, user.userId, markdown)
        }
      }

      if (channel === 'feishu') {
        const appId = config.feishu?.appId
        const appSecret = config.feishu?.appSecret
        if (!appId || !appSecret) {
          console.warn('[Notification] Feishu credentials not configured, skipping')
          continue
        }
        const token = await getFeishuTenantToken(appId, appSecret)
        if (!token) continue

        const users = [
          ...(config.feishu?.pairedUsers ?? []),
          ...(config.feishu?.allowedUsers ?? []).map((id) => ({ userId: id })),
        ]
        for (const user of users) {
          await sendFeishu(token, String(user.userId), run)
        }
      }
    } catch (err) {
      console.error(`[Notification] ${channel} notification error:`, err)
    }
  }
}