mirror of
https://github.com/Portabase/portabase.git
synced 2026-07-14 11:16:13 +02:00
fix: feature-base-refactoring (#297)
* docs: add AGENTS.md with feature-based architecture conventions Defines the target src/ structure, feature list, naming conventions (kebab-case, file type patterns), import direction rules, and feature boundary guidelines for the planned big-bang refactor. * docs: add features/channel/ to architecture conventions Generic channel UI (card, modal, form) goes to features/channel/. Provider-specific sub-folders: channel/notifications/ and channel/storages/. * refactor: move event emitter to lib/, project service to db/services/, dedup use-mobile hook * fix: remove unused auth import in db/services/project.ts * refactor: migrate wrappers/common to components/common (flat) * fix: remove dead commented-out code from button-with-loading.tsx * refactor: merge features/browser into features/theme, flatten upload/updates, migrate statistics * refactor: migrate wrappers/auth to features/auth Move all auth components and forms from src/components/wrappers/auth/ into src/features/auth/ with flat kebab-case naming. Handle extra reset-password-form.tsx and differing reset-password-schema.ts by copying them as reset-password-page-form.tsx and reset-password-page.schema.ts. * refactor: remove dead auth files and fix zPassword schema Delete reset-password-section.tsx and reset-password-page-form.tsx (zero consumers). Fix reset-password-page.schema.ts to import zPassword from @/lib/zod. * refactor: migrate wrappers/dashboard/common to features/layout, rename Header.tsx to header.tsx * fix: decouple layout from theme/updates cross-feature imports Use slot props (actions, updateNotification) so app/ composes ModeToggle and UpdateNotification into Header and AppSidebar. Delete dead side-bar-logo.tsx (zero consumers). * refactor: merge features/keys into features/agents, flatten sub-dirs, migrate agent wrappers - Merge src/features/keys/keys.action.ts into src/features/agents/ - Flatten src/features/agents/components/ and hooks/ into feature root - Migrate all src/components/wrappers/dashboard/agent/ files into src/features/agents/ - Update all import paths across app/ and src/ accordingly - Fix broken code-snippet import in agent-key-modal.tsx (was pointing to non-existent wrappers path) * fix: move github-releases to lib/, remove dead code and unused imports Move GitHub release fetch logic from features/updates/github.ts to lib/github-releases.ts so both features/updates and features/agents can import it without cross-feature imports. Remove commented-out impersonation block from agent-database-card.tsx. Remove unused imports (CopyButton, Terminal, Key, Info). * refactor: flatten features/projects/components, migrate project wrappers Move project.dialog/form out of sub-dir, migrate project-card, project-database-card, and delete-project button/action from wrappers into features/projects/. Update all import paths across src/ and app/. Leave wrappers/dashboard/projects/database/ untouched for Task 10. * fix: extract DatabaseCard to components/common, remove cross-feature import DatabaseCard was imported by both features/projects and features/agents, violating the no-cross-feature-import rule. Extract to components/common/ database-card.tsx so both features import from the shared layer. Also tighten extendedProps type and remove commented-out maxCount prop. * refactor: migrate all database/backup/restore/health UI to features/database Consolidates ~40 files from 5 source locations (features/dashboard/backup, features/dashboard/restore, wrappers/dashboard/backup, wrappers/dashboard/database, wrappers/dashboard/health, wrappers/dashboard/projects/database) into the new flat features/database directory with kebab-case filenames and updated @/ imports. * fix: remove dead restore-form files and console.log from health-grid Delete restore-form.tsx (186 lines all commented-out, zero consumers) and restore-form.schema.ts (only a commented import). Remove console.log(logs) from getOldestLog helper in health-grid.tsx. Cross-feature imports (database→storages for dispatchStorage/storeBackupFiles) are accepted as known architectural coupling — storage dispatch is called from database server actions at runtime and cannot route through app/ props. * refactor: migrate wrappers/admin/users to features/users, fix table-colums typo * fix: fix relative imports, string interpolation, and console.error in users feature Replace relative imports with @/ aliases in user-actions-cell.tsx and admin-user-edit-modal.tsx. Fix string interpolation bug in dialog title (was regular string, now template literal). Remove console.error from admin-user-change-role-modal.tsx. * refactor: migrate wrappers/profile to features/profile, fix profile-apperance typo * fix: remove console.error calls and ts-ignore in profile feature Remove console.error from profile-account.tsx, 2fa-form.tsx (x2). Replace @ts-ignore on fileInput.onchange with typed cast in avatar-with-upload.tsx. * refactor: rename features/organization to features/organizations, migrate all org wrappers Moves 37 org-related files from features/organization/, features/dashboard/, hooks/, wrappers/admin/organizations/, wrappers/admin/channels/organization/, and wrappers/dashboard/organization/ into a flat features/organizations/ feature directory. Updates all import paths codebase-wide. Fixes @ts-ignore and removes unused @better-fetch/fetch import in admin-organization-form. * fix: remove console.error, @ts-ignore, and unused destructures in features/organizations * refactor: migrate wrappers/organization/migration to features/migration Move all 5 migration files to src/features/migration/, update internal imports to @/features/migration/ absolute paths, remove console.log, and delete src/components/wrappers/dashboard/organization/ entirely. * refactor: migrate wrappers/admin/settings to features/settings Move all 14 settings files (email, notification, storage, s3) from wrappers/dashboard/admin/settings/ into features/settings/, rewriting imports, replacing @ts-ignore with @ts-expect-error, and renaming error params to _error where applicable. * refactor: rename notifications files to kebab convention, migrate notification logs - Rename dispatch.ts/helpers.ts/types.ts to notifications.*.ts - Migrate notification logs components from wrappers/dashboard/admin/notifications/logs/ to features/notifications/ - Fix all import paths across codebase and in providers/ - Remove unused useRouter import, replace @ts-ignore with @ts-expect-error - Delete src/components/wrappers/dashboard/admin/notifications/ * refactor: rename storages dispatch/helpers/types to kebab convention - Rename dispatch.ts/helpers.ts/types.ts to storages.*.ts - Fix all import paths across codebase and in providers/ - Fix relative ../types and ../../types imports in all storage providers to absolute @/ paths - Replace @ts-ignore with @ts-expect-error, remove console.debug/console.error * refactor: create features/channel with generic UI and notifications/storages provider sub-folders Consolidates 4 source locations into src/features/channel/: - components/wrappers/dashboard/admin/channels/ → features/channel/ (11 generic UI files) - features/notifications/providers/ → features/channel/notifications/ (9 backend + 18 form files) - features/storages/providers/ → features/channel/storages/ (backend + forms) The two conflicting google-drive/helpers.ts files (client helpers vs OAuth action) are kept separate: helpers.ts and google-drive-refresh.action.ts. Rewrites all imports codebase-wide to point to new locations. Removes console.log/console.error calls, upgrades @ts-ignore to @ts-expect-error. * fix: remove console.error from local storage provider * fix: multi-select.tsx scroll issue * fix: multi-select.tsx scroll issue
This commit is contained in:
@@ -0,0 +1,112 @@
|
||||
"use client";
|
||||
|
||||
import {ColumnDef} from "@tanstack/react-table";
|
||||
import {NotificationLogWithRelations} from "@/db/services/notification-log";
|
||||
import {humanReadableDate} from "@/utils/date-formatting";
|
||||
import {CheckCircle2, XCircle} from "lucide-react";
|
||||
import {Badge} from "@/components/ui/badge";
|
||||
import {NotificationLogModal} from "@/features/notifications/notification-log-modal";
|
||||
import {getChannelIcon} from "@/features/channel/channels-helpers";
|
||||
|
||||
|
||||
export function notificationLogsColumns(): ColumnDef<NotificationLogWithRelations>[] {
|
||||
return [
|
||||
{
|
||||
accessorKey: "success",
|
||||
header: "Status",
|
||||
cell: ({row}) => {
|
||||
const status = row.original.success ? "delivered" : "failed";
|
||||
return(
|
||||
<Badge variant="outline" className={`gap-1.5 ${getStatusColor(status)}`}>
|
||||
{getStatusIcon(row.original.success)}
|
||||
<span className="capitalize">{status}</span>
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "channel",
|
||||
header: "Channel",
|
||||
cell: ({row}) => {
|
||||
const channel = row.original.channel
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className="flex h-10 w-10 items-center justify-center rounded-md bg-secondary border border-border">
|
||||
{getChannelIcon(channel?.provider ?? "")}
|
||||
</div>
|
||||
{channel?.name}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "sentAt",
|
||||
header: "Sent At",
|
||||
cell: ({row}) => {
|
||||
const sentAt = humanReadableDate(row.original.sentAt)
|
||||
return (
|
||||
<div>
|
||||
{sentAt}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "policy",
|
||||
header: "Event Kind",
|
||||
cell: ({ row }) => {
|
||||
const eventKind = row.original.policy?.event;
|
||||
|
||||
if (!eventKind) {
|
||||
return (
|
||||
<div className="text-muted-foreground italic">
|
||||
No event
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge>{eventKind}</Badge>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "details",
|
||||
header: "Details",
|
||||
cell: ({row}) => {
|
||||
|
||||
return (
|
||||
<div>
|
||||
<NotificationLogModal notificationLog={row.original} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
export const getStatusIcon = (status: boolean) => {
|
||||
switch (status) {
|
||||
case true:
|
||||
return <CheckCircle2 className="h-4 w-4"/>
|
||||
case false:
|
||||
return <XCircle className="h-4 w-4"/>
|
||||
}
|
||||
}
|
||||
|
||||
export const getStatusColor = (status: string) => {
|
||||
switch (status) {
|
||||
case "delivered":
|
||||
return "bg-green-100 dark:bg-green-100/10"
|
||||
case "success":
|
||||
return "bg-green-100 dark:bg-green-100/10"
|
||||
case "failed":
|
||||
return "bg-red-100 dark:bg-red-100/10"
|
||||
case "pending":
|
||||
return "bg-orange-100 dark:bg-orange-100/10"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
"use client";
|
||||
import {
|
||||
AlertCircle,
|
||||
Braces,
|
||||
Database,
|
||||
ExternalLink,
|
||||
Eye,
|
||||
Hash,
|
||||
Server,
|
||||
Sparkles,
|
||||
} from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import type { NotificationLogWithRelations } from "@/db/services/notification-log";
|
||||
|
||||
type NotificationLogModalProps = {
|
||||
notificationLog: NotificationLogWithRelations;
|
||||
};
|
||||
|
||||
const getTroubleshootingForError = (errorMsg?: any) => {
|
||||
if (!errorMsg || String(errorMsg).toLowerCase() === "null") return null;
|
||||
|
||||
const msg = String(errorMsg).toLowerCase();
|
||||
|
||||
if (msg.includes("database connection") || msg.includes("agent")) {
|
||||
return {
|
||||
title: "Agent Connection Issue",
|
||||
resolution:
|
||||
"It appears the agent cannot reach the database. Please ensure that your agent is actively running, your PostgreSQL credentials are correct, and port 5432 is open on your firewall.",
|
||||
docLink:
|
||||
"https://portabase.io/docs/agent/troubleshooting/agent-connection",
|
||||
};
|
||||
}
|
||||
|
||||
if (msg.includes("timeout")) {
|
||||
return {
|
||||
title: "Timeout",
|
||||
resolution:
|
||||
"The agent is taking too long to respond. This could be due to high server load, network issues, or a large database.",
|
||||
docLink: "https://portabase.io/docs/agent/troubleshooting/timeout",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
title: "Unexpected Execution Error",
|
||||
resolution:
|
||||
"An unexpected error occurred during execution. Please review the raw system logs or contact support if the issue persists.",
|
||||
docLink: "https://discord.gg/Wgv7xZ8fWJ",
|
||||
};
|
||||
};
|
||||
|
||||
const getIconForKey = (key: string, value: any) => {
|
||||
const isActualError =
|
||||
key.toLowerCase().includes("error") &&
|
||||
value !== null &&
|
||||
String(value).toLowerCase() !== "null";
|
||||
|
||||
if (key.toLowerCase().includes("id"))
|
||||
return <Hash className="w-3.5 h-3.5 text-muted-foreground" />;
|
||||
if (key.toLowerCase().includes("host"))
|
||||
return <Server className="w-3.5 h-3.5 text-muted-foreground" />;
|
||||
if (isActualError)
|
||||
return <AlertCircle className="w-3.5 h-3.5 text-destructive" />;
|
||||
return <Database className="w-3.5 h-3.5 text-muted-foreground" />;
|
||||
};
|
||||
|
||||
export const NotificationLogModal = ({
|
||||
notificationLog,
|
||||
}: NotificationLogModalProps) => {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
// @ts-expect-error — payload type is not fully typed yet
|
||||
const payloadError = notificationLog.payload?.error;
|
||||
const troubleshooting = getTroubleshootingForError(payloadError);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setOpen(true)}
|
||||
className="relative"
|
||||
>
|
||||
<Eye className="w-4 h-4" />
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-xl bg-background">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Notification Details</DialogTitle>
|
||||
<DialogDescription>Execution logs and payload data</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 mt-2 max-h-[70vh] overflow-y-auto px-1 pb-2">
|
||||
<div className="relative border rounded-xl bg-card shadow-sm flex flex-col">
|
||||
<div className="bg-primary/5 border-b px-4 py-2.5 flex items-center gap-2 rounded-t-xl">
|
||||
<div className="p-1 bg-primary/10 rounded-md">
|
||||
<Database className="w-4 h-4 text-primary" />
|
||||
</div>
|
||||
<span className="font-semibold text-sm text-primary">
|
||||
Event Trigger
|
||||
</span>
|
||||
</div>
|
||||
<div className="p-4 flex flex-col gap-4">
|
||||
<div className="flex flex-col sm:flex-row sm:items-start justify-between gap-1 sm:gap-4">
|
||||
<span className="text-xs font-medium text-muted-foreground min-w-20 pt-0.5">
|
||||
Title
|
||||
</span>
|
||||
<span className="text-sm sm:text-right flex-1 wrap-break-words">
|
||||
{notificationLog.content.title}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex flex-col sm:flex-row sm:items-start justify-between gap-1 sm:gap-4">
|
||||
<span className="text-xs font-medium text-muted-foreground min-w-20 pt-0.5">
|
||||
Message
|
||||
</span>
|
||||
<span className="text-sm sm:text-right flex-1 wrap-break-word text-muted-foreground">
|
||||
{notificationLog.content.message}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{notificationLog.payload && (
|
||||
<div className="absolute -bottom-1.5 left-1/2 -translate-x-1/2 w-3 h-3 bg-primary rounded-full border-2 border-background z-10" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="w-px h-6 bg-border mx-auto -my-4 relative z-0" />
|
||||
|
||||
{notificationLog.payload &&
|
||||
Object.keys(notificationLog.payload).length > 0 && (
|
||||
<div className="relative border rounded-xl bg-card shadow-sm flex flex-col">
|
||||
<div className="absolute -top-1.5 left-1/2 -translate-x-1/2 w-3 h-3 bg-primary rounded-full border-2 border-background z-10" />
|
||||
|
||||
<div className="bg-primary/5 border-b px-4 py-2.5 flex items-center justify-between rounded-t-xl">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="p-1 bg-primary/10 rounded-md">
|
||||
<Braces className="w-4 h-4 text-primary" />
|
||||
</div>
|
||||
<span className="font-semibold text-sm text-primary">
|
||||
JSON Payload
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col">
|
||||
{Object.entries(notificationLog.payload).map(
|
||||
([key, value], index, arr) => {
|
||||
const isActualError =
|
||||
key === "error" &&
|
||||
value !== null &&
|
||||
String(value).toLowerCase() !== "null";
|
||||
|
||||
return (
|
||||
<div
|
||||
key={key}
|
||||
className={`flex flex-col sm:flex-row sm:items-center justify-between gap-2 px-4 py-3 hover:bg-muted/50 transition-colors ${
|
||||
index !== arr.length - 1
|
||||
? "border-b border-border/50"
|
||||
: ""
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-[150px]">
|
||||
{getIconForKey(key, value)}
|
||||
<span className="text-sm font-medium">{key}</span>
|
||||
</div>
|
||||
<div className="flex-1 sm:text-right">
|
||||
{isActualError ? (
|
||||
<span className="inline-flex items-center px-2 py-1 rounded-md bg-destructive/10 text-destructive text-xs font-mono break-all">
|
||||
{String(value)}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-sm text-muted-foreground font-mono bg-muted px-2 py-1 rounded-md break-all">
|
||||
{String(value)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
)}
|
||||
</div>
|
||||
|
||||
{troubleshooting && (
|
||||
<div className="absolute -bottom-1.5 left-1/2 -translate-x-1/2 w-3 h-3 bg-primary rounded-full border-2 border-background z-10" />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{troubleshooting && (
|
||||
<>
|
||||
<div className="w-px h-6 bg-border mx-auto -my-4 relative z-0" />
|
||||
|
||||
<div className="relative border border-destructive/20 rounded-xl bg-gradient-to-b from-destructive/5 to-transparent shadow-sm flex flex-col">
|
||||
<div className="absolute -top-1.5 left-1/2 -translate-x-1/2 w-3 h-3 bg-destructive rounded-full border-2 border-background z-10" />
|
||||
|
||||
<div className="bg-destructive/10 border-b border-destructive/10 px-4 py-2.5 flex items-center justify-between rounded-t-xl">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="p-1 bg-destructive/20 rounded-md">
|
||||
<Sparkles className="w-4 h-4 text-destructive" />
|
||||
</div>
|
||||
<span className="font-semibold text-sm text-destructive">
|
||||
Suggested Resolution
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="p-4 flex flex-col gap-2">
|
||||
<h4 className="text-sm font-semibold text-foreground">
|
||||
{troubleshooting.title}
|
||||
</h4>
|
||||
<p className="text-sm text-muted-foreground leading-relaxed">
|
||||
{troubleshooting.resolution}
|
||||
</p>
|
||||
<div className="mt-2">
|
||||
<a
|
||||
href={troubleshooting.docLink}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="inline-flex items-center gap-1.5 text-xs font-semibold text-destructive hover:text-destructive/80 transition-colors"
|
||||
>
|
||||
Read the documentation{" "}
|
||||
<ExternalLink className="w-3.5 h-3.5" />
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
"use client"
|
||||
import {DataTable} from "@/components/common/data-table";
|
||||
import {
|
||||
notificationLogsColumns,
|
||||
} from "@/features/notifications/notification-log-columns";
|
||||
import {NotificationLogWithRelations} from "@/db/services/notification-log";
|
||||
|
||||
|
||||
type NotificationsLogsListProps = {
|
||||
notificationLogs: NotificationLogWithRelations[]
|
||||
}
|
||||
|
||||
export const NotificationLogsList = (props: NotificationsLogsListProps) => {
|
||||
return (
|
||||
<DataTable
|
||||
enableSelect={false}
|
||||
columns={notificationLogsColumns()}
|
||||
data={props.notificationLogs}
|
||||
enablePagination
|
||||
/>
|
||||
)
|
||||
}
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
"use server";
|
||||
import {eq} from "drizzle-orm";
|
||||
import {dispatchViaProvider} from "./providers";
|
||||
import type {EventPayload, DispatchResult, EventKind} from "./types";
|
||||
import {dispatchViaProvider} from "@/features/channel/notifications";
|
||||
import type {EventPayload, DispatchResult, EventKind} from "@/features/notifications/notifications.types";
|
||||
import * as drizzleDb from "@/db";
|
||||
import {db} from "@/db";
|
||||
import {notificationLog} from "@/db/schema/11_notification-log";
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
import { DatabaseWith } from "@/db/schema/07_database";
|
||||
import { EventKind, EventPayload } from "@/features/notifications/types";
|
||||
import { dispatchNotification } from "@/features/notifications/dispatch";
|
||||
import { EventKind, EventPayload } from "@/features/notifications/notifications.types";
|
||||
import { dispatchNotification } from "@/features/notifications/notifications.dispatch";
|
||||
import {db} from "@/db";
|
||||
import {eq} from "drizzle-orm";
|
||||
import * as drizzleDb from "@/db";
|
||||
@@ -1,48 +0,0 @@
|
||||
import type {EventPayload, DispatchResult} from '../types';
|
||||
|
||||
export async function sendDiscord(
|
||||
config: { discordWebhook: string },
|
||||
payload: EventPayload
|
||||
): Promise<DispatchResult> {
|
||||
const {discordWebhook: webhookUrl} = config;
|
||||
|
||||
const embeds = [
|
||||
{
|
||||
title: `[${payload.level.toUpperCase()}] ${payload.title}`,
|
||||
description: payload.message,
|
||||
color: payload.level === 'critical' ? 15158332 : payload.level === 'warning' ? 16776960 : 3447003,
|
||||
fields: payload.data ? [
|
||||
{
|
||||
name: 'Data',
|
||||
value: `
|
||||
${JSON.stringify(payload.data, null, 2).substring(0, 1000)}
|
||||
`,
|
||||
inline: false
|
||||
}
|
||||
] : [],
|
||||
timestamp: new Date().toISOString(),
|
||||
}
|
||||
];
|
||||
|
||||
const body = {
|
||||
embeds,
|
||||
};
|
||||
|
||||
const res = await fetch(webhookUrl, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const err = await res.text();
|
||||
throw new Error(`Discord error: ${res.status} ${err}`);
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
provider: 'discord',
|
||||
message: 'Sent to Discord',
|
||||
response: res.statusText,
|
||||
};
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import type {EventPayload, DispatchResult} from '../types';
|
||||
|
||||
export async function sendGotify(
|
||||
config: { gotifyServerUrl: string; gotifyAppToken: string },
|
||||
payload: EventPayload
|
||||
): Promise<DispatchResult> {
|
||||
const {gotifyServerUrl, gotifyAppToken} = config;
|
||||
|
||||
const baseUrl = gotifyServerUrl.replace(/\/$/, "");
|
||||
|
||||
const body = {
|
||||
title: `[${payload.level.toUpperCase()}] ${payload.title}`,
|
||||
message: `${payload.message}\n\n${payload.data ? `Data:\n${JSON.stringify(payload.data, null, 2)}` : ''}`,
|
||||
priority: payload.level === 'critical' ? 8 : payload.level === 'warning' ? 5 : 2,
|
||||
};
|
||||
|
||||
const res = await fetch(`${baseUrl}/message?token=${gotifyAppToken}`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const err = await res.text();
|
||||
throw new Error(`Gotify error: ${res.status} ${err}`);
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
provider: 'gotify',
|
||||
message: 'Sent to Gotify',
|
||||
response: await res.json(),
|
||||
};
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
"use server"
|
||||
import type {ProviderKind, EventPayload, DispatchResult} from '../types';
|
||||
import {sendSlack} from './slack';
|
||||
import {sendSmtp} from './smtp';
|
||||
import {sendDiscord} from "@/features/notifications/providers/discord";
|
||||
import {sendTelegram} from "@/features/notifications/providers/telegram";
|
||||
import {sendGotify} from "@/features/notifications/providers/gotify";
|
||||
import {sendNtfy} from "@/features/notifications/providers/ntfy";
|
||||
import {sendWebhook} from "@/features/notifications/providers/webhook";
|
||||
import {sendNextcloud} from "@/features/notifications/providers/nextcloud";
|
||||
|
||||
const handlers: Record<
|
||||
ProviderKind,
|
||||
(config: any, payload: EventPayload) => Promise<DispatchResult>
|
||||
> = {
|
||||
slack: sendSlack,
|
||||
smtp: sendSmtp,
|
||||
discord: sendDiscord,
|
||||
telegram: sendTelegram,
|
||||
gotify: sendGotify,
|
||||
ntfy: sendNtfy,
|
||||
webhook: sendWebhook,
|
||||
nextcloud: sendNextcloud,
|
||||
};
|
||||
|
||||
export async function dispatchViaProvider(
|
||||
kind: ProviderKind,
|
||||
config: any,
|
||||
payload: EventPayload,
|
||||
channelId: string
|
||||
): Promise<DispatchResult> {
|
||||
const handler = handlers[kind];
|
||||
if (!handler) {
|
||||
return {
|
||||
success: false,
|
||||
channelId,
|
||||
provider: kind,
|
||||
error: `Unsupported provider: ${kind}`,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
return await handler(config, payload);
|
||||
} catch (err: any) {
|
||||
return {
|
||||
success: false,
|
||||
channelId,
|
||||
provider: kind,
|
||||
error: err.message || 'Unknown error',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
import { createHmac, randomBytes } from "crypto";
|
||||
import type { EventPayload, DispatchResult } from "../types";
|
||||
|
||||
type NextcloudConfig = {
|
||||
nextcloudUrl: string;
|
||||
nextcloudBotToken: string;
|
||||
nextcloudBotSecret: string;
|
||||
};
|
||||
|
||||
function formatPayloadData(data: unknown): string {
|
||||
if (!data) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if (typeof data === "string") {
|
||||
return data;
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.stringify(data, null, 2);
|
||||
} catch {
|
||||
return String(data);
|
||||
}
|
||||
}
|
||||
|
||||
export async function sendNextcloud(
|
||||
config: NextcloudConfig,
|
||||
payload: EventPayload
|
||||
): Promise<DispatchResult> {
|
||||
const {
|
||||
nextcloudUrl,
|
||||
nextcloudBotToken,
|
||||
nextcloudBotSecret,
|
||||
} = config;
|
||||
|
||||
const payloadData = formatPayloadData(payload.data);
|
||||
|
||||
const messageParts = [
|
||||
`[${payload.level.toUpperCase()}] ${payload.title}`,
|
||||
payload.message,
|
||||
];
|
||||
|
||||
if (payloadData) {
|
||||
messageParts.push(`Payload:\n${payloadData}`);
|
||||
}
|
||||
|
||||
const message = messageParts.join("\n\n");
|
||||
|
||||
const random = randomBytes(32).toString("hex");
|
||||
|
||||
const signature = createHmac("sha256", nextcloudBotSecret)
|
||||
.update(random + message)
|
||||
.digest("hex");
|
||||
|
||||
const baseUrl = nextcloudUrl.replace(/\/$/, "");
|
||||
|
||||
const res = await fetch(
|
||||
`${baseUrl}/ocs/v2.php/apps/spreed/api/v1/bot/${nextcloudBotToken}/message`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"OCS-APIRequest": "true",
|
||||
"X-Nextcloud-Talk-Bot-Random": random,
|
||||
"X-Nextcloud-Talk-Bot-Signature": signature,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
message,
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
const err = await res.text();
|
||||
|
||||
throw new Error(
|
||||
`Nextcloud error: ${res.status} ${err}`
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
provider: "nextcloud",
|
||||
message: "Sent to Nextcloud Talk",
|
||||
response: await res.text(),
|
||||
};
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
import type {EventPayload, DispatchResult} from '../types';
|
||||
|
||||
const getPriority = (level?: string): number => {
|
||||
switch (level) {
|
||||
case 'critical': return 5;
|
||||
case 'error': return 4;
|
||||
case 'warning': return 3;
|
||||
case 'info':
|
||||
default: return 2;
|
||||
}
|
||||
};
|
||||
|
||||
const formatData = (data: any): string => {
|
||||
if (!data || typeof data !== 'object') return '';
|
||||
return '\n\nDetails:\n' + Object.entries(data)
|
||||
.map(([key, value]) => {
|
||||
const stringVal = value !== null && typeof value === 'object' ? JSON.stringify(value) : String(value);
|
||||
return `- ${key}: ${stringVal}`;
|
||||
})
|
||||
.join('\n');
|
||||
};
|
||||
|
||||
const getTags = (level?: string): string[] => {
|
||||
const baseTags = ['floppy_disk'];
|
||||
|
||||
if (level === 'critical') baseTags.push('rotating_light');
|
||||
else if (level === 'error') baseTags.push('x');
|
||||
else if (level === 'warning') baseTags.push('warning');
|
||||
else baseTags.push('information_source');
|
||||
|
||||
return baseTags;
|
||||
};
|
||||
|
||||
export async function sendNtfy(
|
||||
config: { ntfyServerUrl?: string; ntfyTopic: string; ntfyToken?: string, ntfyUsername?: string, ntfyPassword?: string },
|
||||
payload: EventPayload
|
||||
): Promise<DispatchResult> {
|
||||
const {ntfyServerUrl, ntfyTopic, ntfyToken, ntfyUsername, ntfyPassword} = config;
|
||||
|
||||
const baseUrl = (ntfyServerUrl || "https://ntfy.sh").replace(/\/$/, "");
|
||||
|
||||
const body = {
|
||||
topic: ntfyTopic,
|
||||
title: payload.title,
|
||||
message: payload.message + formatData(payload.data),
|
||||
priority: getPriority(payload.level),
|
||||
tags: getTags(payload.level),
|
||||
};
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
|
||||
if (ntfyToken) {
|
||||
headers['Authorization'] = `Bearer ${ntfyToken}`;
|
||||
}
|
||||
|
||||
if (ntfyUsername && ntfyPassword) {
|
||||
const credentials = btoa(`${ntfyUsername}:${ntfyPassword}`);
|
||||
headers['Authorization'] = `Basic ${credentials}`;
|
||||
}
|
||||
|
||||
const res = await fetch(`${baseUrl}`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
headers: headers,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const err = await res.text();
|
||||
throw new Error(`ntfy error: ${res.status} ${err}`);
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
provider: 'ntfy',
|
||||
message: 'Sent to ntfy',
|
||||
response: await res.json(),
|
||||
};
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
import type {EventPayload, DispatchResult} from '../types';
|
||||
|
||||
export async function sendSlack(
|
||||
config: { slackWebhook: string },
|
||||
payload: EventPayload
|
||||
): Promise<DispatchResult> {
|
||||
const {slackWebhook: webhookUrl} = config;
|
||||
|
||||
const text = `*[${payload.level}] ${payload.title}*\n${payload.message}`;
|
||||
const blocks = [
|
||||
{
|
||||
type: 'section',
|
||||
text: {type: 'mrkdwn', text: `*[${payload.level.toUpperCase()}] ${payload.title}*`},
|
||||
},
|
||||
{type: 'section', text: {type: 'mrkdwn', text: payload.message}},
|
||||
payload.data
|
||||
? {
|
||||
type: 'context',
|
||||
elements: [{type: 'mrkdwn', text: `*Data:* \`\`\`${JSON.stringify(payload.data, null, 2)}\`\`\``}],
|
||||
}
|
||||
: null,
|
||||
].filter(Boolean);
|
||||
|
||||
const body = {
|
||||
text,
|
||||
blocks,
|
||||
};
|
||||
|
||||
const res = await fetch(webhookUrl, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const err = await res.text();
|
||||
throw new Error(`Slack error: ${res.status} ${err}`);
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
provider: 'slack',
|
||||
message: 'Sent to Slack',
|
||||
response: await res.text(),
|
||||
};
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
"use server";
|
||||
import { render } from "@react-email/render";
|
||||
import nodemailer from "nodemailer";
|
||||
import type { EventPayload, DispatchResult } from '../types';
|
||||
import EmailNotification from "@/components/emails/email-notification";
|
||||
|
||||
export async function sendSmtp(
|
||||
config: {
|
||||
host: string;
|
||||
port: number;
|
||||
secure: boolean;
|
||||
user: string;
|
||||
password: string;
|
||||
from: string;
|
||||
to: string | string[];
|
||||
},
|
||||
payload: EventPayload
|
||||
): Promise<DispatchResult> {
|
||||
|
||||
const transporter = nodemailer.createTransport({
|
||||
pool: true,
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
secure: config.secure,
|
||||
auth: { user: config.user, pass: config.password },
|
||||
});
|
||||
|
||||
await transporter.verify();
|
||||
|
||||
|
||||
const info = await transporter.sendMail({
|
||||
from: config.from,
|
||||
to: Array.isArray(config.to) ? config.to.join(", ") : config.to,
|
||||
subject: `[${payload.level.toUpperCase()}] ${payload.title}`,
|
||||
html: await render(EmailNotification({
|
||||
payload: payload
|
||||
})),
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
provider: "smtp",
|
||||
message: `Email sent: ${config.to}`,
|
||||
response: info,
|
||||
};
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import type { EventPayload, DispatchResult } from "../types";
|
||||
|
||||
export async function sendTelegram(
|
||||
config: {
|
||||
telegramBotToken: string;
|
||||
telegramChatId: string;
|
||||
telegramTopicId?: string;
|
||||
},
|
||||
payload: EventPayload,
|
||||
): Promise<DispatchResult> {
|
||||
const { telegramBotToken, telegramChatId, telegramTopicId } = config;
|
||||
|
||||
// Helper to escape HTML characters
|
||||
const escapeHtml = (unsafe: string) => {
|
||||
return unsafe
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
};
|
||||
|
||||
const title = escapeHtml(payload.title);
|
||||
const message = escapeHtml(payload.message);
|
||||
const level = escapeHtml(payload.level.toUpperCase());
|
||||
const dataString = payload.data
|
||||
? escapeHtml(JSON.stringify(payload.data, null, 2).substring(0, 1000))
|
||||
: "";
|
||||
|
||||
const text = `<b>${title}</b>\n\n${message}\n\nLevel: <code>${level}</code>${payload.data ? `\n\nData:\n<pre>${dataString}</pre>` : ""}`;
|
||||
|
||||
const body: Record<string, any> = {
|
||||
chat_id: telegramChatId,
|
||||
text,
|
||||
parse_mode: "HTML",
|
||||
};
|
||||
|
||||
if (telegramTopicId) {
|
||||
body.message_thread_id = Number(telegramTopicId);
|
||||
}
|
||||
|
||||
const res = await fetch(
|
||||
`https://api.telegram.org/bot${telegramBotToken}/sendMessage`,
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
headers: { "Content-Type": "application/json" },
|
||||
},
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
const err = await res.text();
|
||||
throw new Error(`Telegram error: ${res.status} ${err}`);
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
provider: "telegram",
|
||||
message: "Sent to Telegram",
|
||||
response: await res.text(),
|
||||
};
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
import type { EventPayload, DispatchResult } from '../types';
|
||||
|
||||
type WebhookConfig = {
|
||||
webhookUrl: string;
|
||||
webhookHeaders?: { key: string; value: string }[];
|
||||
webhookSecret?: string;
|
||||
webhookSecretHeader?: string;
|
||||
};
|
||||
|
||||
export async function sendWebhook(
|
||||
config: WebhookConfig,
|
||||
payload: EventPayload
|
||||
): Promise<DispatchResult> {
|
||||
const { webhookUrl, webhookHeaders, webhookSecret, webhookSecretHeader } = config;
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
'User-Agent': 'Portabase-Notifier/1.0',
|
||||
};
|
||||
|
||||
// New format: iterate custom headers array
|
||||
if (webhookHeaders && webhookHeaders.length > 0) {
|
||||
const RESERVED = new Set(['content-type', 'user-agent']);
|
||||
for (const { key, value } of webhookHeaders) {
|
||||
if (key && !RESERVED.has(key.toLowerCase())) headers[key] = value;
|
||||
}
|
||||
} else if (webhookSecret) {
|
||||
// Legacy format: single secret header pair
|
||||
headers[webhookSecretHeader || 'X-Webhook-Secret'] = webhookSecret;
|
||||
}
|
||||
|
||||
const res = await fetch(webhookUrl, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload),
|
||||
headers,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const err = await res.text();
|
||||
throw new Error(`Webhook error: ${res.status} ${err}`);
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
provider: 'webhook',
|
||||
message: 'Sent to Webhook',
|
||||
response: await res.text(),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user