feat: Docker audit + Telegram bot service + send UI

Docker:
- Harden docker-compose.yml: parameterized DB creds, required AUTH_SECRET,
  health checks, resource limits, network isolation, removed exposed DB port
- Add profiles (telegram/bot/full) so base 'docker compose up' needs only AUTH_SECRET
- Fix docker-entrypoint.sh: AUTH_SECRET startup guard
- Fix Dockerfile: copy prisma.config.ts + dotenv into production image
- Update .env.example with all new variables
- Update .dockerignore

Telegram Bot Service (bot/):
- TDLib-based bot using bot token auth (not HTTP Bot API)
- Commands: /search, /latest, /package, /link, /unlink, /subscribe, /unsubscribe
- pg_notify listener for send requests (bot_send) and new packages (new_package)
- Subscription-based notifications when matching packages arrive
- Dockerfile with multi-stage build (bookworm-slim for glibc/TDLib)

API & Database:
- Prisma: TelegramLink, BotSendRequest, BotSubscription models + migration
- POST /api/telegram/bot/send - queue package delivery to linked TG account
- GET /api/telegram/bot/send/[id] - poll send request status
- Server actions: generateTelegramLinkCode, unlinkTelegram, getBotSendHistory
- Worker: emit pg_notify('new_package') after creating packages

Frontend:
- Settings: TelegramLinkCard for account linking via one-time code
- STL table + drawer: SendToTelegramButton with send dialog and status polling
- Telegram admin: Bot Sends tab with delivery history table
- Shared SendHistoryRow type

README: Updated with bot docs, profiles, config vars, project structure
This commit is contained in:
2026-03-03 21:36:57 +01:00
parent 4d0df6b1a4
commit 575ffdbc31
36 changed files with 4516 additions and 37 deletions

View File

@@ -0,0 +1,209 @@
"use client";
import { useState, useTransition } from "react";
import { Send, Link2, Unlink, Copy, Loader2, CheckCircle2 } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
generateTelegramLinkCode,
unlinkTelegram,
} from "../telegram-actions";
interface TelegramLinkCardProps {
linked: boolean;
telegramName: string | null;
telegramUserId: string | null;
linkedAt: string | null;
botUsername?: string | null;
}
export function TelegramLinkCard({
linked: initialLinked,
telegramName: initialName,
telegramUserId: initialUserId,
linkedAt: initialLinkedAt,
botUsername,
}: TelegramLinkCardProps) {
const [isPending, startTransition] = useTransition();
const [linked, setLinked] = useState(initialLinked);
const [telegramName, setTelegramName] = useState(initialName);
const [telegramUserId, setTelegramUserId] = useState(initialUserId);
const [linkedAt, setLinkedAt] = useState(initialLinkedAt);
const [linkCode, setLinkCode] = useState<string | null>(null);
const [codeExpiresAt, setCodeExpiresAt] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
function handleGenerateCode() {
startTransition(async () => {
const result = await generateTelegramLinkCode();
if (!result.success) {
toast.error(result.error);
return;
}
setLinkCode(result.data.code);
setCodeExpiresAt(result.data.expiresAt);
toast.success("Link code generated! Send it to the bot within 10 minutes.");
});
}
function handleUnlink() {
startTransition(async () => {
const result = await unlinkTelegram();
if (!result.success) {
toast.error(result.error);
return;
}
setLinked(false);
setTelegramName(null);
setTelegramUserId(null);
setLinkedAt(null);
setLinkCode(null);
toast.success("Telegram account unlinked");
});
}
async function handleCopy() {
if (!linkCode) return;
const command = `/link ${linkCode}`;
await navigator.clipboard.writeText(command);
setCopied(true);
toast.success("Copied to clipboard");
setTimeout(() => setCopied(false), 2000);
}
const botLink = botUsername
? `https://t.me/${botUsername}?start=link_${linkCode}`
: null;
return (
<Card>
<CardHeader>
<div className="flex items-center gap-2">
<Send className="h-5 w-5 text-primary" />
<CardTitle>Telegram Link</CardTitle>
{linked ? (
<Badge variant="default" className="ml-auto">
Linked
</Badge>
) : (
<Badge variant="secondary" className="ml-auto">
Not linked
</Badge>
)}
</div>
<CardDescription>
Link your account to receive packages via the Telegram bot.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{linked ? (
<>
<div className="rounded-lg border p-4 space-y-2 bg-muted/30">
<div className="flex items-center gap-2 text-sm">
<span className="text-muted-foreground">Telegram:</span>
<span className="font-medium">
{telegramName ?? `User ${telegramUserId}`}
</span>
</div>
{linkedAt && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<span>Linked:</span>
<span>{new Date(linkedAt).toLocaleDateString()}</span>
</div>
)}
</div>
<Button
variant="destructive"
size="sm"
onClick={handleUnlink}
disabled={isPending}
>
{isPending ? (
<Loader2 className="h-4 w-4 animate-spin mr-1" />
) : (
<Unlink className="h-4 w-4 mr-1" />
)}
Unlink Account
</Button>
</>
) : (
<>
{linkCode ? (
<div className="space-y-3">
<div className="rounded-lg border p-4 space-y-2 bg-muted/30">
<p className="text-sm text-muted-foreground">
Send this command to the bot:
</p>
<div className="flex items-center gap-2">
<code className="flex-1 rounded bg-background px-3 py-2 text-sm font-mono border">
/link {linkCode}
</code>
<Button
variant="outline"
size="icon"
className="h-9 w-9 shrink-0"
onClick={handleCopy}
>
{copied ? (
<CheckCircle2 className="h-4 w-4 text-green-500" />
) : (
<Copy className="h-4 w-4" />
)}
</Button>
</div>
{codeExpiresAt && (
<p className="text-xs text-muted-foreground">
Expires:{" "}
{new Date(codeExpiresAt).toLocaleTimeString()}
</p>
)}
</div>
{botLink && (
<a
href={botLink}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-sm text-primary hover:underline"
>
<Send className="h-3.5 w-3.5" />
Or click here to open the bot directly
</a>
)}
<Button
variant="outline"
size="sm"
onClick={handleGenerateCode}
disabled={isPending}
>
{isPending && <Loader2 className="h-4 w-4 animate-spin mr-1" />}
Generate New Code
</Button>
</div>
) : (
<Button
variant="default"
onClick={handleGenerateCode}
disabled={isPending}
>
{isPending ? (
<Loader2 className="h-4 w-4 animate-spin mr-1" />
) : (
<Link2 className="h-4 w-4 mr-1" />
)}
Generate Link Code
</Button>
)}
</>
)}
</CardContent>
</Card>
);
}

View File

@@ -3,12 +3,19 @@ import { redirect } from "next/navigation";
import { getUserSettings } from "@/data/settings.queries";
import { PageHeader } from "@/components/shared/page-header";
import { SettingsForm } from "./_components/settings-form";
import { TelegramLinkCard } from "./_components/telegram-link-card";
import { prisma } from "@/lib/prisma";
export default async function SettingsPage() {
const session = await auth();
if (!session?.user?.id) redirect("/login");
const settings = await getUserSettings(session.user.id);
const [settings, telegramLink] = await Promise.all([
getUserSettings(session.user.id),
prisma.telegramLink.findUnique({
where: { userId: session.user.id },
}),
]);
return (
<div className="space-y-6">
@@ -16,10 +23,17 @@ export default async function SettingsPage() {
title="Settings"
description="Manage your application preferences"
/>
<div className="max-w-2xl">
<div className="max-w-2xl space-y-6">
<SettingsForm
settings={JSON.parse(JSON.stringify(settings))}
/>
<TelegramLinkCard
linked={!!telegramLink}
telegramName={telegramLink?.telegramName ?? null}
telegramUserId={telegramLink?.telegramUserId?.toString() ?? null}
linkedAt={telegramLink?.createdAt?.toISOString() ?? null}
botUsername={process.env.BOT_USERNAME ?? null}
/>
</div>
</div>
);

View File

@@ -0,0 +1,171 @@
"use server";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { revalidatePath } from "next/cache";
import type { ActionResult } from "@/types/api.types";
import { randomBytes } from "crypto";
/**
* Generate a one-time link code for the current user.
* The user sends `/link <code>` to the bot to complete the link.
* Code is stored in GlobalSetting as `link_code:<code>` → userId.
* Codes expire after 10 minutes (checked by the bot).
*/
export async function generateTelegramLinkCode(): Promise<
ActionResult<{ code: string; expiresAt: string }>
> {
const session = await auth();
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
// Check if user already has a link
const existing = await prisma.telegramLink.findUnique({
where: { userId: session.user.id },
});
if (existing) {
return {
success: false,
error: "You already have a linked Telegram account. Unlink first to generate a new code.",
};
}
// Generate a short random code
const code = randomBytes(4).toString("hex"); // 8 hex chars
const expiresAt = new Date(Date.now() + 10 * 60 * 1000); // 10 minutes
// Store in GlobalSetting — overwrites any previous code for this user
// First, clean up any previous codes for this user
const existingCodes = await prisma.globalSetting.findMany({
where: { key: { startsWith: "link_code:" } },
});
for (const setting of existingCodes) {
try {
const parsed = JSON.parse(setting.value);
if (parsed.userId === session.user.id) {
await prisma.globalSetting.delete({ where: { key: setting.key } });
}
} catch {
// Skip malformed entries
}
}
// Store the new code
await prisma.globalSetting.upsert({
where: { key: `link_code:${code}` },
update: {
value: JSON.stringify({
userId: session.user.id,
expiresAt: expiresAt.toISOString(),
}),
},
create: {
key: `link_code:${code}`,
value: JSON.stringify({
userId: session.user.id,
expiresAt: expiresAt.toISOString(),
}),
},
});
return {
success: true,
data: { code, expiresAt: expiresAt.toISOString() },
};
}
/**
* Get the current user's Telegram link status.
*/
export async function getTelegramLinkStatus(): Promise<
ActionResult<{
linked: boolean;
telegramName: string | null;
telegramUserId: string | null;
linkedAt: string | null;
}>
> {
const session = await auth();
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
const link = await prisma.telegramLink.findUnique({
where: { userId: session.user.id },
});
return {
success: true,
data: {
linked: !!link,
telegramName: link?.telegramName ?? null,
telegramUserId: link?.telegramUserId?.toString() ?? null,
linkedAt: link?.createdAt?.toISOString() ?? null,
},
};
}
/**
* Unlink the current user's Telegram account.
*/
export async function unlinkTelegram(): Promise<ActionResult> {
const session = await auth();
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
const link = await prisma.telegramLink.findUnique({
where: { userId: session.user.id },
});
if (!link) {
return { success: false, error: "No linked Telegram account found" };
}
await prisma.telegramLink.delete({ where: { id: link.id } });
revalidatePath("/settings");
return { success: true, data: undefined };
}
/**
* Get recent bot send requests for the current user (or all for admins).
*/
export async function getBotSendHistory(
limit = 20
): Promise<
ActionResult<
Array<{
id: string;
packageName: string;
recipientName: string | null;
status: string;
error: string | null;
createdAt: string;
completedAt: string | null;
}>
>
> {
const session = await auth();
if (!session?.user?.id) return { success: false, error: "Unauthorized" };
const isAdmin = session.user.role === "ADMIN";
const requests = await prisma.botSendRequest.findMany({
where: isAdmin ? {} : { requestedByUserId: session.user.id },
orderBy: { createdAt: "desc" },
take: limit,
include: {
package: { select: { fileName: true } },
telegramLink: { select: { telegramName: true } },
},
});
return {
success: true,
data: requests.map((r: typeof requests[number]) => ({
id: r.id,
packageName: r.package.fileName,
recipientName: r.telegramLink.telegramName,
status: r.status,
error: r.error,
createdAt: r.createdAt.toISOString(),
completedAt: r.completedAt?.toISOString() ?? null,
})),
};
}

View File

@@ -5,6 +5,7 @@ import { FileArchive, Eye, ImageIcon } from "lucide-react";
import { DataTableColumnHeader } from "@/components/shared/data-table-column-header";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { SendToTelegramButton } from "./send-to-telegram-button";
export interface PackageRow {
id: string;
@@ -139,14 +140,21 @@ export function getPackageColumns({
{
id: "actions",
cell: ({ row }) => (
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => onViewFiles(row.original)}
>
<Eye className="h-4 w-4" />
</Button>
<div className="flex items-center gap-0.5">
<SendToTelegramButton
packageId={row.original.id}
packageName={row.original.fileName}
variant="icon"
/>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => onViewFiles(row.original)}
>
<Eye className="h-4 w-4" />
</Button>
</div>
),
enableHiding: false,
},

View File

@@ -23,6 +23,7 @@ import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import type { PackageRow } from "./package-columns";
import { SendToTelegramButton } from "./send-to-telegram-button";
interface FileItem {
id: string;
@@ -306,6 +307,14 @@ export function PackageFilesDrawer({ pkg, open, onOpenChange }: PackageFilesDraw
<DialogDescription className="mt-1">
{total.toLocaleString()} file{total !== 1 ? "s" : ""} in archive
</DialogDescription>
{pkg && (
<div className="mt-2">
<SendToTelegramButton
packageId={pkg.id}
packageName={pkg.fileName}
/>
</div>
)}
</div>
</div>

View File

@@ -0,0 +1,214 @@
"use client";
import { useState, useTransition, useEffect, useRef } from "react";
import { Send, Loader2, CheckCircle2, AlertCircle } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
interface SendToTelegramButtonProps {
packageId: string;
packageName: string;
/** variant for inline row actions vs larger button */
variant?: "icon" | "default";
}
type SendStatus = "idle" | "sending" | "polling" | "sent" | "failed";
export function SendToTelegramButton({
packageId,
packageName,
variant = "default",
}: SendToTelegramButtonProps) {
const [open, setOpen] = useState(false);
const [status, setStatus] = useState<SendStatus>("idle");
const [error, setError] = useState<string | null>(null);
const [isPending, startTransition] = useTransition();
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
// Clean up polling on unmount
useEffect(() => {
return () => {
if (pollRef.current) clearInterval(pollRef.current);
};
}, []);
function handleSend() {
startTransition(async () => {
setStatus("sending");
setError(null);
try {
const res = await fetch("/api/telegram/bot/send", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ packageId }),
});
const data = await res.json();
if (!res.ok) {
setStatus("failed");
setError(data.error ?? "Failed to queue send");
return;
}
// Start polling for status
setStatus("polling");
const requestId = data.requestId;
pollRef.current = setInterval(async () => {
try {
const statusRes = await fetch(`/api/telegram/bot/send/${requestId}`);
const statusData = await statusRes.json();
if (statusData.status === "SENT") {
setStatus("sent");
toast.success(`"${packageName}" sent to Telegram`);
if (pollRef.current) clearInterval(pollRef.current);
} else if (statusData.status === "FAILED") {
setStatus("failed");
setError(statusData.error ?? "Send failed");
if (pollRef.current) clearInterval(pollRef.current);
}
// PENDING / SENDING — keep polling
} catch {
// Network error — keep trying
}
}, 2000);
// Stop polling after 60 seconds
setTimeout(() => {
if (pollRef.current) {
clearInterval(pollRef.current);
pollRef.current = null;
}
setStatus((s: SendStatus) => {
if (s === "polling") return "sent"; // Assume queued successfully
return s;
});
}, 60000);
} catch {
setStatus("failed");
setError("Network error");
}
});
}
function handleClose() {
if (pollRef.current) {
clearInterval(pollRef.current);
pollRef.current = null;
}
setOpen(false);
// Reset after animation
setTimeout(() => {
setStatus("idle");
setError(null);
}, 200);
}
const trigger =
variant === "icon" ? (
<Button variant="ghost" size="icon" className="h-8 w-8" title="Send to Telegram">
<Send className="h-4 w-4" />
</Button>
) : (
<Button variant="outline" size="sm" className="gap-1.5">
<Send className="h-3.5 w-3.5" />
Send to Telegram
</Button>
);
return (
<Dialog open={open} onOpenChange={(o: boolean) => (o ? setOpen(true) : handleClose())}>
<DialogTrigger asChild>{trigger}</DialogTrigger>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Send to Telegram</DialogTitle>
<DialogDescription>
Send &ldquo;{packageName}&rdquo; to your linked Telegram account.
</DialogDescription>
</DialogHeader>
<div className="py-4">
{status === "idle" && (
<p className="text-sm text-muted-foreground">
The bot will forward the archive files from the destination channel
to your linked Telegram account.
</p>
)}
{(status === "sending" || status === "polling") && (
<div className="flex items-center gap-3 p-4 rounded-lg bg-muted/30 border">
<Loader2 className="h-5 w-5 animate-spin text-primary" />
<div>
<p className="text-sm font-medium">
{status === "sending" ? "Queuing…" : "Sending…"}
</p>
<p className="text-xs text-muted-foreground">
The bot is forwarding the files to your Telegram.
</p>
</div>
</div>
)}
{status === "sent" && (
<div className="flex items-center gap-3 p-4 rounded-lg bg-green-500/10 border border-green-500/20">
<CheckCircle2 className="h-5 w-5 text-green-500" />
<div>
<p className="text-sm font-medium text-green-500">Sent!</p>
<p className="text-xs text-muted-foreground">
Check your Telegram messages.
</p>
</div>
</div>
)}
{status === "failed" && (
<div className="flex items-center gap-3 p-4 rounded-lg bg-destructive/10 border border-destructive/20">
<AlertCircle className="h-5 w-5 text-destructive" />
<div>
<p className="text-sm font-medium text-destructive">Failed</p>
<p className="text-xs text-muted-foreground">{error}</p>
</div>
</div>
)}
</div>
<DialogFooter>
{status === "idle" && (
<>
<Button variant="outline" onClick={handleClose}>
Cancel
</Button>
<Button onClick={handleSend} disabled={isPending}>
{isPending ? (
<Loader2 className="h-4 w-4 animate-spin mr-1" />
) : (
<Send className="h-4 w-4 mr-1" />
)}
Send
</Button>
</>
)}
{(status === "sent" || status === "failed") && (
<Button variant="outline" onClick={handleClose}>
Close
</Button>
)}
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,111 @@
"use client";
import { Badge } from "@/components/ui/badge";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Send } from "lucide-react";
import type { SendHistoryRow } from "@/types/telegram.types";
interface BotSendsTabProps {
history: SendHistoryRow[];
}
function statusBadge(status: string) {
switch (status) {
case "SENT":
return <Badge variant="default" className="bg-green-600">Sent</Badge>;
case "SENDING":
return <Badge variant="secondary">Sending</Badge>;
case "PENDING":
return <Badge variant="outline">Pending</Badge>;
case "FAILED":
return <Badge variant="destructive">Failed</Badge>;
default:
return <Badge variant="outline">{status}</Badge>;
}
}
export function BotSendsTab({ history }: BotSendsTabProps) {
return (
<Card>
<CardHeader>
<div className="flex items-center gap-2">
<Send className="h-5 w-5 text-primary" />
<CardTitle>Bot Send History</CardTitle>
</div>
<CardDescription>
Recent package deliveries via the Telegram bot.
</CardDescription>
</CardHeader>
<CardContent>
{history.length === 0 ? (
<div className="flex flex-col items-center justify-center gap-2 py-12 text-muted-foreground text-sm">
<Send className="h-6 w-6 text-muted-foreground/50" />
No sends yet. Use the &ldquo;Send to Telegram&rdquo; button on a
package to get started.
</div>
) : (
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead>Package</TableHead>
<TableHead>Recipient</TableHead>
<TableHead>Status</TableHead>
<TableHead>Requested</TableHead>
<TableHead>Completed</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{history.map((row) => (
<TableRow key={row.id}>
<TableCell className="max-w-[200px] truncate font-medium">
{row.packageName}
</TableCell>
<TableCell className="text-muted-foreground">
{row.recipientName ?? "—"}
</TableCell>
<TableCell>
<div className="flex items-center gap-2">
{statusBadge(row.status)}
{row.error && (
<span
className="text-xs text-destructive truncate max-w-[150px]"
title={row.error}
>
{row.error}
</span>
)}
</div>
</TableCell>
<TableCell className="text-muted-foreground text-sm">
{new Date(row.createdAt).toLocaleString()}
</TableCell>
<TableCell className="text-muted-foreground text-sm">
{row.completedAt
? new Date(row.completedAt).toLocaleString()
: "—"}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
</CardContent>
</Card>
);
}

View File

@@ -5,14 +5,17 @@ import { PageHeader } from "@/components/shared/page-header";
import { AccountsTab } from "./accounts-tab";
import { ChannelsTab } from "./channels-tab";
import { WorkerStatusPanel } from "./worker-status-panel";
import { BotSendsTab } from "./bot-sends-tab";
import type { AccountRow, ChannelRow, GlobalDestination } from "@/lib/telegram/admin-queries";
import type { IngestionAccountStatus } from "@/lib/telegram/types";
import type { SendHistoryRow } from "@/types/telegram.types";
interface TelegramAdminProps {
accounts: AccountRow[];
channels: ChannelRow[];
ingestionStatus: IngestionAccountStatus[];
globalDestination: GlobalDestination;
sendHistory: SendHistoryRow[];
}
export function TelegramAdmin({
@@ -20,6 +23,7 @@ export function TelegramAdmin({
channels,
ingestionStatus,
globalDestination,
sendHistory,
}: TelegramAdminProps) {
return (
<div className="space-y-4">
@@ -38,6 +42,9 @@ export function TelegramAdmin({
<TabsTrigger value="channels">
Channels ({channels.length})
</TabsTrigger>
<TabsTrigger value="sends">
Bot Sends ({sendHistory.length})
</TabsTrigger>
</TabsList>
<TabsContent value="accounts">
@@ -46,6 +53,9 @@ export function TelegramAdmin({
<TabsContent value="channels">
<ChannelsTab channels={channels} globalDestination={globalDestination} />
</TabsContent>
<TabsContent value="sends">
<BotSendsTab history={sendHistory} />
</TabsContent>
</Tabs>
</div>
);

View File

@@ -2,6 +2,7 @@ import { auth } from "@/lib/auth";
import { redirect } from "next/navigation";
import { listAccounts, listChannels, getGlobalDestination } from "@/lib/telegram/admin-queries";
import { getIngestionStatus } from "@/lib/telegram/queries";
import { prisma } from "@/lib/prisma";
import { TelegramAdmin } from "./_components/telegram-admin";
export default async function TelegramPage() {
@@ -9,19 +10,38 @@ export default async function TelegramPage() {
if (!session?.user?.id) redirect("/login");
if (session.user.role !== "ADMIN") redirect("/dashboard");
const [accounts, channels, ingestionStatus, globalDestination] = await Promise.all([
const [accounts, channels, ingestionStatus, globalDestination, sendHistory] = await Promise.all([
listAccounts(),
listChannels(),
getIngestionStatus(),
getGlobalDestination(),
prisma.botSendRequest.findMany({
orderBy: { createdAt: "desc" },
take: 50,
include: {
package: { select: { fileName: true } },
telegramLink: { select: { telegramName: true } },
},
}),
]);
const serializedHistory = sendHistory.map((r) => ({
id: r.id,
packageName: r.package.fileName,
recipientName: r.telegramLink.telegramName,
status: r.status,
error: r.error,
createdAt: r.createdAt.toISOString(),
completedAt: r.completedAt?.toISOString() ?? null,
}));
return (
<TelegramAdmin
accounts={accounts}
channels={channels}
ingestionStatus={ingestionStatus}
globalDestination={globalDestination}
sendHistory={serializedHistory}
/>
);
}

View File

@@ -0,0 +1,58 @@
import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
export const dynamic = "force-dynamic";
/**
* GET /api/telegram/bot/send/[id]
* Poll the status of a bot send request.
*/
export async function GET(
_request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const session = await auth();
if (!session?.user?.id) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const { id } = await params;
const sendRequest = await prisma.botSendRequest.findUnique({
where: { id },
select: {
id: true,
status: true,
error: true,
requestedByUserId: true,
createdAt: true,
completedAt: true,
package: { select: { id: true, fileName: true } },
telegramLink: { select: { userId: true } },
},
});
if (!sendRequest) {
return NextResponse.json({ error: "Send request not found" }, { status: 404 });
}
// Users can only see their own requests unless admin
const isOwner =
sendRequest.requestedByUserId === session.user.id ||
sendRequest.telegramLink.userId === session.user.id;
if (!isOwner && session.user.role !== "ADMIN") {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
return NextResponse.json({
id: sendRequest.id,
status: sendRequest.status,
error: sendRequest.error,
packageId: sendRequest.package.id,
fileName: sendRequest.package.fileName,
createdAt: sendRequest.createdAt,
completedAt: sendRequest.completedAt,
});
}

View File

@@ -0,0 +1,98 @@
import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
export const dynamic = "force-dynamic";
/**
* POST /api/telegram/bot/send
* Queue a package to be sent to a user's linked Telegram account via the bot.
*
* Body: { packageId: string, targetUserId?: string }
* - targetUserId: optional, admin-only — send to another user's linked TG
*/
export async function POST(request: Request) {
const session = await auth();
if (!session?.user?.id) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
let body: { packageId?: string; targetUserId?: string };
try {
body = await request.json();
} catch {
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
}
if (!body.packageId) {
return NextResponse.json({ error: "packageId is required" }, { status: 400 });
}
// Determine whose TelegramLink to use
const targetUserId = body.targetUserId ?? session.user.id;
// Only admins can send to other users
if (body.targetUserId && body.targetUserId !== session.user.id) {
if (session.user.role !== "ADMIN") {
return NextResponse.json(
{ error: "Only admins can send to other users" },
{ status: 403 }
);
}
}
// Verify the target user has a linked Telegram account
const telegramLink = await prisma.telegramLink.findUnique({
where: { userId: targetUserId },
});
if (!telegramLink) {
return NextResponse.json(
{ error: "Target user has no linked Telegram account. Link one in Settings → Telegram." },
{ status: 400 }
);
}
// Verify the package exists and has a destination message
const pkg = await prisma.package.findUnique({
where: { id: body.packageId },
select: { id: true, fileName: true, destChannelId: true, destMessageId: true },
});
if (!pkg) {
return NextResponse.json({ error: "Package not found" }, { status: 404 });
}
if (!pkg.destChannelId || !pkg.destMessageId) {
return NextResponse.json(
{ error: "Package has not been uploaded to a destination channel yet" },
{ status: 400 }
);
}
// Create the send request
const sendRequest = await prisma.botSendRequest.create({
data: {
packageId: body.packageId,
telegramLinkId: telegramLink.id,
requestedByUserId: session.user.id,
status: "PENDING",
},
});
// Notify the bot via pg_notify
try {
await prisma.$queryRawUnsafe(
`SELECT pg_notify('bot_send', $1)`,
sendRequest.id
);
} catch {
// Best-effort — the bot also polls periodically
}
return NextResponse.json({
requestId: sendRequest.id,
status: "PENDING",
message: `Queued "${pkg.fileName}" for delivery to Telegram`,
});
}