swadhinbiswas feat: implement air-gapped mode, UI fixes, and project management integrations · 7/9/2026
e3bd4a1
391 lines · 12.3 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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
/**
 * Notification Dispatcher
 * Central hub for sending notifications to configured integrations
 */

import { getDatabase, schema } from "@/db";
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { eq, and } from "drizzle-orm";
import { logger } from "../logger";
import { sendTeamsMessage, createPRCard, createIssueCard, createCICard } from "./teams";
import { sendDiscordMessage, createPREmbed, createIssueEmbed, createCIEmbed, createPushEmbed, type DiscordWebhookPayload } from "./discord";

export type NotificationEvent =
    | { type: "pr"; action: "opened" | "merged" | "closed" | "review_requested"; data: PRNotificationData }
    | { type: "issue"; action: "opened" | "closed" | "commented"; data: IssueNotificationData }
    | { type: "ci"; action: "completed"; data: CINotificationData }
    | { type: "push"; data: PushNotificationData };

interface PRNotificationData {
    prTitle: string;
    prNumber: number;
    prUrl: string;
    author: string;
    authorAvatar?: string;
    repository: string;
    description?: string;
    additions?: number;
    deletions?: number;
}

interface IssueNotificationData {
    issueTitle: string;
    issueNumber: number;
    issueUrl: string;
    author: string;
    authorAvatar?: string;
    repository: string;
    labels?: string[];
    body?: string;
}

interface CINotificationData {
    status: "success" | "failure" | "pending" | "running";
    workflowName: string;
    repository: string;
    branch: string;
    commitSha: string;
    commitUrl: string;
    runUrl: string;
    duration?: string;
}

interface PushNotificationData {
    repository: string;
    branch: string;
    pusher: string;
    pusherAvatar?: string;
    commits: { sha: string; message: string; url: string }[];
    compareUrl: string;
}

/**
 * Get configured webhooks for a repository
 */
async function getWebhooks(repositoryId: string) {
    const db = getDatabase() as NodePgDatabase<typeof schema>;

    return db.query.webhooks.findMany({
        where: and(
            eq(schema.webhooks.repositoryId, repositoryId),
            eq(schema.webhooks.enabled, true)
        ),
    });
}

/**
 * Send notification to all configured integrations
 */
export async function sendNotification(
    repositoryId: string,
    event: NotificationEvent
): Promise<{ sent: number; failed: number }> {
    let sent = 0;
    let failed = 0;

    try {
        const webhooks = await getWebhooks(repositoryId);

        for (const webhook of webhooks) {
            // Check if this event type is enabled (events is stored as JSON string)
            let events: string[] = [];
            try {
                events = JSON.parse(webhook.events || '["*"]');
            } catch {
                events = ["*"];
            }

            if (!events.includes(event.type) && !events.includes("*")) {
                continue;
            }

            try {
                let success = false;

                if (webhook.provider === "teams") {
                    success = await sendToTeams(webhook.url, event);
                } else if (webhook.provider === "discord") {
                    success = await sendToDiscord(webhook.url, event);
                } else if (webhook.provider === "slack") {
                    success = await sendToSlack(webhook.url, event);
                } else if (webhook.provider === "linear") {
                    success = await sendToLinear(webhook.url, event);
                } else if (webhook.provider === "trello") {
                    success = await sendToTrello(webhook.url, event);
                } else if (webhook.provider === "clickup") {
                    success = await sendToClickUp(webhook.url, event);
                }

                if (success) {
                    sent++;
                } else {
                    failed++;
                }
            } catch (error) {
                logger.error({ error, webhookId: webhook.id }, "Webhook delivery failed");
                failed++;
            }
        }
    } catch (error) {
        logger.error({ error, repositoryId }, "Failed to send notifications");
    }

    return { sent, failed };
}

/**
 * Send to Microsoft Teams
 */
async function sendToTeams(webhookUrl: string, event: NotificationEvent): Promise<boolean> {
    switch (event.type) {
        case "pr":
            return sendTeamsMessage(webhookUrl, createPRCard({
                action: event.action,
                ...event.data,
            }));

        case "issue":
            return sendTeamsMessage(webhookUrl, createIssueCard({
                action: event.action,
                ...event.data,
            }));

        case "ci":
            return sendTeamsMessage(webhookUrl, createCICard(event.data));

        default:
            return false;
    }
}

/**
 * Send to Discord
 */
async function sendToDiscord(webhookUrl: string, event: NotificationEvent): Promise<boolean> {
    const payload: DiscordWebhookPayload = {
        username: "OpenCodeHub",
        embeds: [],
    };

    switch (event.type) {
        case "pr":
            payload.embeds = [createPREmbed({
                action: event.action,
                ...event.data,
            })];
            break;

        case "issue":
            payload.embeds = [createIssueEmbed({
                action: event.action,
                ...event.data,
            })];
            break;

        case "ci":
            payload.embeds = [createCIEmbed({
                ...event.data,
                status: event.data.status,
            })];
            break;

        case "push":
            payload.embeds = [createPushEmbed(event.data)];
            break;

        default:
            return false;
    }

    return sendDiscordMessage(webhookUrl, payload);
}

/**
 * Send to Slack (simplified webhook)
 */
async function sendToSlack(webhookUrl: string, event: NotificationEvent): Promise<boolean> {
    let text = "";

    switch (event.type) {
        case "pr":
            text = `*${event.action === "opened" ? "🆕" : event.action === "merged" ? "✅" : "❌"} PR #${event.data.prNumber}*: ${event.data.prTitle}\nBy ${event.data.author} in ${event.data.repository}`;
            break;

        case "issue":
            text = `*${event.action === "opened" ? "🐛" : "✅"} Issue #${event.data.issueNumber}*: ${event.data.issueTitle}\nBy ${event.data.author} in ${event.data.repository}`;
            break;

        case "ci":
            text = `*${event.data.status === "success" ? "✅" : "❌"} CI ${event.data.status}*: ${event.data.workflowName}\nBranch: ${event.data.branch}`;
            break;

        case "push":
            text = `*📤 ${event.data.commits.length} commits pushed* to \`${event.data.branch}\` by ${event.data.pusher}`;
            break;
    }

    try {
        const response = await fetch(webhookUrl, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ text }),
        });
        return response.ok;
    } catch {
        return false;
    }
}

/**
 * Test a webhook connection
 */
export async function testWebhook(
    provider: "teams" | "discord" | "slack",
    webhookUrl: string
): Promise<{ success: boolean; error?: string }> {
    try {
        let success = false;

        if (provider === "teams") {
            success = await sendTeamsMessage(webhookUrl, {
                "@type": "MessageCard",
                "@context": "http://schema.org/extensions",
                themeColor: "0078d4",
                summary: "Test notification from OpenCodeHub",
                sections: [{
                    activityTitle: "**✅ Webhook Connected!**",
                    activitySubtitle: "OpenCodeHub notifications are working correctly.",
                    markdown: true,
                }],
            });
        } else if (provider === "discord") {
            success = await sendDiscordMessage(webhookUrl, {
                username: "OpenCodeHub",
                embeds: [{
                    title: "✅ Webhook Connected!",
                    description: "OpenCodeHub notifications are working correctly.",
                    color: 0x28a745,
                    timestamp: new Date().toISOString(),
                }],
            });
        } else if (provider === "slack") {
            const response = await fetch(webhookUrl, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ text: "✅ OpenCodeHub webhook connected successfully!" }),
            });
            success = response.ok;
        }

        return { success };
    } catch (error) {
        return {
            success: false,
            error: error instanceof Error ? error.message : "Connection failed"
        };
    }
}

/**
 * Send to Linear (Project Management)
 */
async function sendToLinear(webhookUrl: string, event: NotificationEvent): Promise<boolean> {
    try {
        let title = "";
        let description = "";

        if (event.type === "issue") {
            title = `[${event.data.repository}] ${event.action} Issue: ${event.data.issueTitle}`;
            description = `Issue #${event.data.issueNumber} was ${event.action} by ${event.data.author}.\n\n[View Issue](${event.data.issueUrl})`;
        } else if (event.type === "pr") {
            title = `[${event.data.repository}] ${event.action} PR: ${event.data.prTitle}`;
            description = `Pull Request #${event.data.prNumber} was ${event.action} by ${event.data.author}.\n\n[View PR](${event.data.prUrl})`;
        } else {
            return true;
        }

        const payload = {
            title,
            description,
            state: event.action === "closed" || event.action === "merged" ? "Done" : "Todo",
        };

        const response = await fetch(webhookUrl, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(payload),
        });
        return response.ok;
    } catch (error) {
        logger.error({ error }, "Failed to send to Linear");
        return false;
    }
}

/**
 * Send to Trello (Project Management)
 */
async function sendToTrello(webhookUrl: string, event: NotificationEvent): Promise<boolean> {
    try {
        let name = "";
        let desc = "";

        if (event.type === "issue") {
            name = `Issue: ${event.data.issueTitle}`;
            desc = `Repo: ${event.data.repository}\nAction: ${event.action}\nActor: ${event.data.author}\nURL: ${event.data.issueUrl}`;
        } else if (event.type === "pr") {
            name = `PR: ${event.data.prTitle}`;
            desc = `Repo: ${event.data.repository}\nAction: ${event.action}\nActor: ${event.data.author}\nURL: ${event.data.prUrl}`;
        } else {
            return true;
        }

        const payload = { name, desc };

        const response = await fetch(webhookUrl, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(payload),
        });
        return response.ok;
    } catch (error) {
        logger.error({ error }, "Failed to send to Trello");
        return false;
    }
}

/**
 * Send to ClickUp (Project Management)
 */
async function sendToClickUp(webhookUrl: string, event: NotificationEvent): Promise<boolean> {
    try {
        let name = "";
        let description = "";
        let status = "Open";

        if (event.type === "issue") {
            name = `Issue: ${event.data.issueTitle}`;
            description = `Action: ${event.action}\nActor: ${event.data.author}\nURL: ${event.data.issueUrl}`;
            status = event.action === "closed" ? "Closed" : "Open";
        } else if (event.type === "pr") {
            name = `PR: ${event.data.prTitle}`;
            description = `Action: ${event.action}\nActor: ${event.data.author}\nURL: ${event.data.prUrl}`;
            status = event.action === "merged" || event.action === "closed" ? "Closed" : "Open";
        } else {
            return true;
        }

        const payload = { name, description, status };

        const response = await fetch(webhookUrl, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(payload),
        });
        return response.ok;
    } catch (error) {
        logger.error({ error }, "Failed to send to ClickUp");
        return false;
    }
}