mirror of
https://github.com/xCyanGrizzly/DragonsStash.git
synced 2026-05-10 22:01:16 +00:00
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:
@@ -6,9 +6,11 @@ node_modules
|
||||
.env.*
|
||||
!.env.example
|
||||
*.md
|
||||
Dockerfile
|
||||
LICENSE
|
||||
telegram_test.html
|
||||
docker-compose*.yml
|
||||
.dockerignore
|
||||
.claude
|
||||
.vscode
|
||||
.idea
|
||||
tmp_zips
|
||||
|
||||
12
.env.example
12
.env.example
@@ -1,5 +1,8 @@
|
||||
# Database
|
||||
DATABASE_URL="postgresql://dragons:stash@localhost:5432/dragonsstash?schema=public"
|
||||
POSTGRES_USER="dragons"
|
||||
POSTGRES_PASSWORD="stash"
|
||||
POSTGRES_DB="dragonsstash"
|
||||
|
||||
# Auth.js
|
||||
AUTH_SECRET="generate-with-openssl-rand-base64-32"
|
||||
@@ -11,14 +14,23 @@ AUTH_GITHUB_SECRET=""
|
||||
|
||||
# App
|
||||
NEXT_PUBLIC_APP_URL="http://localhost:3000"
|
||||
APP_PORT=3000
|
||||
|
||||
# API key for external access to package/ingestion endpoints (optional)
|
||||
TELEGRAM_API_KEY=""
|
||||
|
||||
# Telegram integration (get from https://my.telegram.org/apps)
|
||||
TELEGRAM_API_ID=""
|
||||
TELEGRAM_API_HASH=""
|
||||
|
||||
# Telegram Bot (create via @BotFather on Telegram)
|
||||
BOT_TOKEN=""
|
||||
BOT_USERNAME="" # e.g. "MyDragonsStashBot" — enables deep link in Settings
|
||||
|
||||
# Worker (only needed when running worker container)
|
||||
WORKER_INTERVAL_MINUTES=60
|
||||
WORKER_TEMP_DIR="/tmp/zips"
|
||||
TDLIB_STATE_DIR="/data/tdlib"
|
||||
WORKER_MAX_ZIP_SIZE_MB=4096
|
||||
MULTIPART_TIMEOUT_HOURS=0
|
||||
LOG_LEVEL="info"
|
||||
|
||||
@@ -34,6 +34,7 @@ COPY --from=builder /app/public ./public
|
||||
|
||||
# Copy prisma schema + migrations for runtime migrate deploy
|
||||
COPY --from=builder /app/prisma ./prisma
|
||||
COPY --from=builder /app/prisma.config.ts ./prisma.config.ts
|
||||
|
||||
# Copy standalone build output
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
|
||||
@@ -43,6 +44,7 @@ COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
|
||||
COPY --from=builder /app/node_modules/.prisma ./node_modules/.prisma
|
||||
COPY --from=builder /app/node_modules/@prisma ./node_modules/@prisma
|
||||
COPY --from=builder /app/node_modules/prisma ./node_modules/prisma
|
||||
COPY --from=builder /app/node_modules/dotenv ./node_modules/dotenv
|
||||
|
||||
# Copy entrypoint script
|
||||
COPY --chown=nextjs:nodejs docker-entrypoint.sh ./
|
||||
|
||||
53
README.md
53
README.md
@@ -28,6 +28,14 @@ A self-hosted inventory management system for 3D printing filament, SLA resin, a
|
||||
- **Upload verification** — confirms files reached the destination before marking them complete
|
||||
- **Preview matching** — associates photo messages with their corresponding archive sets
|
||||
|
||||
### Telegram Bot
|
||||
|
||||
- **Direct delivery** — send any indexed package to a linked Telegram account with one click from the UI
|
||||
- **Account linking** — users link their Telegram account via a one-time code from Settings
|
||||
- **Package search** — search or browse indexed packages directly from conversation with the bot
|
||||
- **Subscription notifications** — subscribe to keyword patterns and get notified when matching packages arrive
|
||||
- **Automatic forwarding** — the bot copies files from the destination channel, no manual download needed
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **Framework**: Next.js 16 (App Router)
|
||||
@@ -38,6 +46,7 @@ A self-hosted inventory management system for 3D printing filament, SLA resin, a
|
||||
- **Tables**: TanStack Table v8 with server-side pagination
|
||||
- **Validation**: Zod v4 + React Hook Form
|
||||
- **Worker**: Node.js + TDLib (via tdl)
|
||||
- **Bot**: Node.js + TDLib (bot token auth)
|
||||
- **Archive handling**: unrar, zlib
|
||||
|
||||
## Quick Start
|
||||
@@ -110,12 +119,30 @@ Run the entire application from Docker:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
# Edit .env — set TELEGRAM_API_ID, TELEGRAM_API_HASH, and a secure AUTH_SECRET
|
||||
# Edit .env — set AUTH_SECRET (required)
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
The app will be available at [http://localhost:3000](http://localhost:3000).
|
||||
|
||||
### Adding Telegram Services
|
||||
|
||||
The worker and bot run as optional profiles so `docker compose up` works with just the app + database:
|
||||
|
||||
```bash
|
||||
# App + DB + Telegram worker (needs TELEGRAM_API_ID + TELEGRAM_API_HASH in .env)
|
||||
docker compose --profile telegram up -d
|
||||
|
||||
# App + DB + Worker + Bot (also needs BOT_TOKEN in .env)
|
||||
docker compose --profile full up -d
|
||||
|
||||
# Or just the bot (alongside app + db)
|
||||
docker compose --profile bot up -d
|
||||
```
|
||||
|
||||
> **Tip:** Create a bot token via [@BotFather](https://t.me/BotFather) on Telegram and set `BOT_TOKEN` in `.env`.
|
||||
> Get Telegram API credentials from [my.telegram.org/apps](https://my.telegram.org/apps).
|
||||
|
||||
### Seeding the Database
|
||||
|
||||
To seed the database with sample data on first run:
|
||||
@@ -157,6 +184,7 @@ docker compose build worker && docker compose up -d worker --force-recreate
|
||||
|
||||
```bash
|
||||
docker compose logs -f worker # Worker logs
|
||||
docker compose logs -f bot # Bot logs
|
||||
docker compose logs -f app # App logs
|
||||
docker compose logs -f db # Database logs
|
||||
```
|
||||
@@ -174,10 +202,13 @@ src/
|
||||
paints/ # Paint CRUD
|
||||
vendors/ # Vendor management
|
||||
locations/ # Location management
|
||||
settings/ # User preferences
|
||||
settings/ # User preferences + Telegram link
|
||||
stls/ # STL package browser
|
||||
telegram/ # Telegram admin (accounts, channels, bot sends)
|
||||
api/
|
||||
auth/ # NextAuth API routes
|
||||
health/ # Health check endpoint
|
||||
telegram/bot/ # Bot send API endpoints
|
||||
components/
|
||||
layout/ # Sidebar, header, navigation
|
||||
shared/ # Reusable data table components
|
||||
@@ -197,6 +228,14 @@ worker/
|
||||
util/ # Config, logger
|
||||
worker.ts # Main processing pipeline
|
||||
index.ts # Entry point + scheduler
|
||||
bot/
|
||||
src/
|
||||
commands.ts # Bot command handlers (/search, /link, /subscribe, etc.)
|
||||
send-listener.ts # pg_notify listener for send requests + subscriptions
|
||||
tdlib/ # TDLib client with bot token auth
|
||||
db/ # Database queries for links, packages, subscriptions
|
||||
util/ # Config, logger
|
||||
index.ts # Entry point
|
||||
prisma/
|
||||
schema.prisma # Database schema
|
||||
seed.ts # Seed data
|
||||
@@ -231,6 +270,16 @@ Environment variables (see `.env.example`):
|
||||
| `MULTIPART_TIMEOUT_HOURS` | Max time span for multipart set parts (0 = no limit) | `0` |
|
||||
| `LOG_LEVEL` | Worker log level (`debug`, `info`, `warn`, `error`) | `info` |
|
||||
|
||||
### Telegram Bot
|
||||
|
||||
| Variable | Description | Default |
|
||||
|----------|-------------|---------|
|
||||
| `BOT_TOKEN` | Bot token from [@BotFather](https://t.me/BotFather) | Optional (bot disabled if unset) |
|
||||
| `TELEGRAM_API_ID` | Same API ID as worker | Required (if bot enabled) |
|
||||
| `TELEGRAM_API_HASH` | Same API hash as worker | Required (if bot enabled) |
|
||||
| `BOT_TDLIB_STATE_DIR` | TDLib state directory for bot | `/data/tdlib_bot` |
|
||||
| `LOG_LEVEL` | Bot log level | `info` |
|
||||
|
||||
## Health Check
|
||||
|
||||
The application exposes a health check endpoint at `/api/health` that verifies database connectivity.
|
||||
|
||||
2
bot/.gitignore
vendored
Normal file
2
bot/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
node_modules/
|
||||
dist/
|
||||
46
bot/Dockerfile
Normal file
46
bot/Dockerfile
Normal file
@@ -0,0 +1,46 @@
|
||||
# ── Stage 1: Install production deps ─────────────────────────
|
||||
FROM node:20-bookworm-slim AS deps
|
||||
|
||||
RUN apt-get update && apt-get install -y \
|
||||
libssl-dev zlib1g-dev \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY bot/package.json bot/package-lock.json* ./
|
||||
COPY prisma/ ./prisma/
|
||||
|
||||
# Install ALL deps (including devDependencies for tsc) and generate Prisma
|
||||
RUN npm ci && npx prisma generate
|
||||
|
||||
# ── Stage 2: Build TypeScript ─────────────────────────────────
|
||||
FROM deps AS builder
|
||||
|
||||
COPY bot/tsconfig.json ./
|
||||
COPY bot/src/ ./src/
|
||||
RUN npx tsc
|
||||
|
||||
# ── Stage 3: Production runner ────────────────────────────────
|
||||
FROM node:20-bookworm-slim AS runner
|
||||
|
||||
RUN apt-get update && apt-get install -y \
|
||||
libssl3 zlib1g \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy only production node_modules
|
||||
COPY --from=builder /app/node_modules ./node_modules
|
||||
COPY --from=builder /app/prisma ./prisma
|
||||
COPY --from=builder /app/dist ./dist
|
||||
|
||||
# Re-generate Prisma client
|
||||
RUN npx prisma generate
|
||||
|
||||
RUN addgroup --system botuser && adduser --system --ingroup botuser botuser
|
||||
RUN mkdir -p /data/tdlib && chown -R botuser:botuser /data/tdlib
|
||||
USER botuser
|
||||
|
||||
VOLUME ["/data/tdlib"]
|
||||
|
||||
CMD ["node", "dist/index.js"]
|
||||
2100
bot/package-lock.json
generated
Normal file
2100
bot/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
26
bot/package.json
Normal file
26
bot/package.json
Normal file
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "dragonsstash-bot",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"start": "node dist/index.js",
|
||||
"dev": "tsx watch src/index.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@prisma/adapter-pg": "^7.4.0",
|
||||
"@prisma/client": "^7.4.0",
|
||||
"pg": "^8.18.0",
|
||||
"pino": "^9.6.0",
|
||||
"prebuilt-tdlib": "^0.1008050.0",
|
||||
"tdl": "^8.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20",
|
||||
"@types/pg": "^8.16.0",
|
||||
"prisma": "^7.4.0",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^5"
|
||||
}
|
||||
}
|
||||
440
bot/src/commands.ts
Normal file
440
bot/src/commands.ts
Normal file
@@ -0,0 +1,440 @@
|
||||
import { childLogger } from "./util/logger.js";
|
||||
import {
|
||||
searchPackages,
|
||||
getLatestPackages,
|
||||
getPackageById,
|
||||
findLinkByTelegramUserId,
|
||||
validateLinkCode,
|
||||
deleteLinkCode,
|
||||
createTelegramLink,
|
||||
getSubscriptions,
|
||||
addSubscription,
|
||||
removeSubscription,
|
||||
} from "./db/queries.js";
|
||||
import { sendTextMessage, sendPhotoMessage } from "./tdlib/client.js";
|
||||
|
||||
const log = childLogger("commands");
|
||||
|
||||
interface IncomingMessage {
|
||||
chatId: bigint;
|
||||
userId: bigint;
|
||||
text: string;
|
||||
firstName: string;
|
||||
lastName?: string;
|
||||
username?: string;
|
||||
}
|
||||
|
||||
function formatSize(bytes: bigint): string {
|
||||
const mb = Number(bytes) / (1024 * 1024);
|
||||
if (mb >= 1024) return `${(mb / 1024).toFixed(1)} GB`;
|
||||
return `${mb.toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
function formatDate(date: Date): string {
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
export async function handleMessage(msg: IncomingMessage): Promise<void> {
|
||||
const { chatId, userId, text } = msg;
|
||||
|
||||
// Parse command and args
|
||||
const trimmed = text.trim();
|
||||
const spaceIdx = trimmed.indexOf(" ");
|
||||
const command = (spaceIdx > 0 ? trimmed.slice(0, spaceIdx) : trimmed).toLowerCase();
|
||||
const args = spaceIdx > 0 ? trimmed.slice(spaceIdx + 1).trim() : "";
|
||||
|
||||
try {
|
||||
switch (command) {
|
||||
case "/start":
|
||||
await handleStart(chatId, userId, args, msg);
|
||||
break;
|
||||
case "/help":
|
||||
await handleHelp(chatId);
|
||||
break;
|
||||
case "/search":
|
||||
await handleSearch(chatId, args);
|
||||
break;
|
||||
case "/latest":
|
||||
await handleLatest(chatId, args);
|
||||
break;
|
||||
case "/package":
|
||||
await handlePackage(chatId, args);
|
||||
break;
|
||||
case "/link":
|
||||
await handleLink(chatId, userId, args, msg);
|
||||
break;
|
||||
case "/unlink":
|
||||
await handleUnlink(chatId, userId);
|
||||
break;
|
||||
case "/subscribe":
|
||||
await handleSubscribe(chatId, userId, args);
|
||||
break;
|
||||
case "/unsubscribe":
|
||||
await handleUnsubscribe(chatId, userId, args);
|
||||
break;
|
||||
case "/subscriptions":
|
||||
await handleListSubscriptions(chatId, userId);
|
||||
break;
|
||||
case "/status":
|
||||
await handleStatus(chatId, userId);
|
||||
break;
|
||||
default:
|
||||
await sendTextMessage(
|
||||
chatId,
|
||||
"Unknown command. Use /help to see available commands.",
|
||||
"textParseModeHTML"
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
log.error({ err, command, userId: userId.toString() }, "Command handler error");
|
||||
await sendTextMessage(
|
||||
chatId,
|
||||
"An error occurred processing your command. Please try again.",
|
||||
"textParseModeHTML"
|
||||
).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
async function handleStart(
|
||||
chatId: bigint,
|
||||
userId: bigint,
|
||||
args: string,
|
||||
msg: IncomingMessage
|
||||
): Promise<void> {
|
||||
// Deep link: /start link_<code>
|
||||
if (args.startsWith("link_")) {
|
||||
const code = args.slice(5);
|
||||
await handleLink(chatId, userId, code, msg);
|
||||
return;
|
||||
}
|
||||
|
||||
const welcome = [
|
||||
`🐉 <b>Dragon's Stash Bot</b>`,
|
||||
``,
|
||||
`I can help you search and receive indexed archive packages.`,
|
||||
``,
|
||||
`<b>Commands:</b>`,
|
||||
`/search <query> — Search packages`,
|
||||
`/latest [n] — Show latest packages`,
|
||||
`/package <id> — Package details`,
|
||||
`/link <code> — Link your Telegram to your web account`,
|
||||
`/subscribe <keyword> — Get notified for new packages`,
|
||||
`/subscriptions — View your subscriptions`,
|
||||
`/unsubscribe <keyword> — Remove a subscription`,
|
||||
`/status — Check your link status`,
|
||||
`/help — Show this help message`,
|
||||
].join("\n");
|
||||
|
||||
await sendTextMessage(chatId, welcome, "textParseModeHTML");
|
||||
}
|
||||
|
||||
async function handleHelp(chatId: bigint): Promise<void> {
|
||||
const help = [
|
||||
`<b>Available Commands:</b>`,
|
||||
``,
|
||||
`🔍 <b>Search & Browse</b>`,
|
||||
`/search <query> — Search by filename or creator`,
|
||||
`/latest [n] — Show n most recent packages (default: 5)`,
|
||||
`/package <id> — View package details and file list`,
|
||||
``,
|
||||
`🔗 <b>Account Linking</b>`,
|
||||
`/link <code> — Link Telegram to your web account`,
|
||||
`/unlink — Unlink your Telegram account`,
|
||||
`/status — Check link status`,
|
||||
``,
|
||||
`🔔 <b>Notifications</b>`,
|
||||
`/subscribe <keyword> — Get alerts for matching packages`,
|
||||
`/unsubscribe <keyword> — Remove a subscription`,
|
||||
`/subscriptions — List your subscriptions`,
|
||||
].join("\n");
|
||||
|
||||
await sendTextMessage(chatId, help, "textParseModeHTML");
|
||||
}
|
||||
|
||||
async function handleSearch(chatId: bigint, query: string): Promise<void> {
|
||||
if (!query) {
|
||||
await sendTextMessage(chatId, "Usage: /search <query>", "textParseModeHTML");
|
||||
return;
|
||||
}
|
||||
|
||||
const results = await searchPackages(query, 10);
|
||||
|
||||
if (results.length === 0) {
|
||||
await sendTextMessage(
|
||||
chatId,
|
||||
`No packages found for "<b>${escapeHtml(query)}</b>".`,
|
||||
"textParseModeHTML"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const lines = results.map((pkg, i) => {
|
||||
const creator = pkg.creator ? ` by ${pkg.creator}` : "";
|
||||
return `${i + 1}. <b>${escapeHtml(pkg.fileName)}</b>${creator}\n 📦 ${pkg.fileCount} files · ${formatSize(pkg.fileSize)} · ${formatDate(pkg.indexedAt)}\n ID: <code>${pkg.id}</code>`;
|
||||
});
|
||||
|
||||
const response = [
|
||||
`🔍 <b>Search results for "${escapeHtml(query)}":</b>`,
|
||||
``,
|
||||
...lines,
|
||||
``,
|
||||
`Use /package <id> for details.`,
|
||||
].join("\n");
|
||||
|
||||
await sendTextMessage(chatId, response, "textParseModeHTML");
|
||||
}
|
||||
|
||||
async function handleLatest(chatId: bigint, args: string): Promise<void> {
|
||||
const limit = Math.min(Math.max(parseInt(args) || 5, 1), 20);
|
||||
const results = await getLatestPackages(limit);
|
||||
|
||||
if (results.length === 0) {
|
||||
await sendTextMessage(chatId, "No packages indexed yet.", "textParseModeHTML");
|
||||
return;
|
||||
}
|
||||
|
||||
const lines = results.map((pkg, i) => {
|
||||
const creator = pkg.creator ? ` by ${pkg.creator}` : "";
|
||||
return `${i + 1}. <b>${escapeHtml(pkg.fileName)}</b>${creator}\n 📦 ${pkg.fileCount} files · ${formatSize(pkg.fileSize)} · ${formatDate(pkg.indexedAt)}\n ID: <code>${pkg.id}</code>`;
|
||||
});
|
||||
|
||||
const response = [
|
||||
`📋 <b>Latest ${results.length} packages:</b>`,
|
||||
``,
|
||||
...lines,
|
||||
``,
|
||||
`Use /package <id> for details.`,
|
||||
].join("\n");
|
||||
|
||||
await sendTextMessage(chatId, response, "textParseModeHTML");
|
||||
}
|
||||
|
||||
async function handlePackage(chatId: bigint, id: string): Promise<void> {
|
||||
if (!id) {
|
||||
await sendTextMessage(chatId, "Usage: /package <id>", "textParseModeHTML");
|
||||
return;
|
||||
}
|
||||
|
||||
const pkg = await getPackageById(id.trim());
|
||||
if (!pkg) {
|
||||
await sendTextMessage(chatId, "Package not found.", "textParseModeHTML");
|
||||
return;
|
||||
}
|
||||
|
||||
const fileList = pkg.files
|
||||
.slice(0, 15)
|
||||
.map((f) => ` ${escapeHtml(f.path)}`)
|
||||
.join("\n");
|
||||
const moreFiles = pkg.files.length > 15 ? `\n ... and ${pkg.fileCount - 15} more` : "";
|
||||
|
||||
const details = [
|
||||
`📦 <b>${escapeHtml(pkg.fileName)}</b>`,
|
||||
``,
|
||||
`Type: ${pkg.archiveType}`,
|
||||
`Size: ${formatSize(pkg.fileSize)}`,
|
||||
`Files: ${pkg.fileCount}`,
|
||||
pkg.creator ? `Creator: ${escapeHtml(pkg.creator)}` : null,
|
||||
`Source: ${escapeHtml(pkg.sourceChannel.title)}`,
|
||||
`Indexed: ${formatDate(pkg.indexedAt)}`,
|
||||
pkg.isMultipart ? `Parts: ${pkg.partCount}` : null,
|
||||
``,
|
||||
`<b>File listing:</b>`,
|
||||
`<code>${fileList}${moreFiles}</code>`,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
|
||||
// Send preview if available
|
||||
if (pkg.previewData) {
|
||||
await sendPhotoMessage(
|
||||
chatId,
|
||||
Buffer.from(pkg.previewData),
|
||||
details
|
||||
);
|
||||
} else {
|
||||
await sendTextMessage(chatId, details, "textParseModeHTML");
|
||||
}
|
||||
}
|
||||
|
||||
async function handleLink(
|
||||
chatId: bigint,
|
||||
userId: bigint,
|
||||
code: string,
|
||||
msg: IncomingMessage
|
||||
): Promise<void> {
|
||||
if (!code) {
|
||||
await sendTextMessage(
|
||||
chatId,
|
||||
"Usage: /link <code>\n\nGet your link code from Settings → Telegram in the web app.",
|
||||
"textParseModeHTML"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if already linked
|
||||
const existing = await findLinkByTelegramUserId(userId);
|
||||
if (existing) {
|
||||
await sendTextMessage(
|
||||
chatId,
|
||||
"Your Telegram account is already linked to a web account. Use /unlink first if you want to re-link.",
|
||||
"textParseModeHTML"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate the code
|
||||
const webUserId = await validateLinkCode(code.trim());
|
||||
if (!webUserId) {
|
||||
await sendTextMessage(
|
||||
chatId,
|
||||
"Invalid or expired link code. Please generate a new one from Settings → Telegram.",
|
||||
"textParseModeHTML"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Create the link
|
||||
const displayName = [msg.firstName, msg.lastName].filter(Boolean).join(" ");
|
||||
await createTelegramLink(webUserId, userId, displayName || msg.username || null);
|
||||
await deleteLinkCode(code.trim());
|
||||
|
||||
await sendTextMessage(
|
||||
chatId,
|
||||
`✅ <b>Account linked successfully!</b>\n\nYou can now receive packages sent from the web app. Use /status to verify.`,
|
||||
"textParseModeHTML"
|
||||
);
|
||||
|
||||
log.info({ userId: userId.toString(), webUserId }, "Telegram account linked");
|
||||
}
|
||||
|
||||
async function handleUnlink(chatId: bigint, userId: bigint): Promise<void> {
|
||||
const existing = await findLinkByTelegramUserId(userId);
|
||||
if (!existing) {
|
||||
await sendTextMessage(
|
||||
chatId,
|
||||
"Your Telegram account is not linked to any web account.",
|
||||
"textParseModeHTML"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const { db } = await import("./db/client.js");
|
||||
await db.telegramLink.delete({ where: { telegramUserId: userId } });
|
||||
|
||||
await sendTextMessage(
|
||||
chatId,
|
||||
"🔓 Account unlinked. You will no longer receive packages from the web app.",
|
||||
"textParseModeHTML"
|
||||
);
|
||||
|
||||
log.info({ userId: userId.toString() }, "Telegram account unlinked");
|
||||
}
|
||||
|
||||
async function handleSubscribe(
|
||||
chatId: bigint,
|
||||
userId: bigint,
|
||||
pattern: string
|
||||
): Promise<void> {
|
||||
if (!pattern) {
|
||||
await sendTextMessage(
|
||||
chatId,
|
||||
"Usage: /subscribe <keyword>\n\nYou'll be notified when new packages matching this keyword are indexed.",
|
||||
"textParseModeHTML"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
await addSubscription(userId, pattern.toLowerCase().trim());
|
||||
|
||||
await sendTextMessage(
|
||||
chatId,
|
||||
`🔔 Subscribed to "<b>${escapeHtml(pattern.trim())}</b>".\n\nYou'll be notified when matching packages are indexed.`,
|
||||
"textParseModeHTML"
|
||||
);
|
||||
}
|
||||
|
||||
async function handleUnsubscribe(
|
||||
chatId: bigint,
|
||||
userId: bigint,
|
||||
pattern: string
|
||||
): Promise<void> {
|
||||
if (!pattern) {
|
||||
await sendTextMessage(
|
||||
chatId,
|
||||
"Usage: /unsubscribe <keyword>",
|
||||
"textParseModeHTML"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await removeSubscription(userId, pattern.toLowerCase().trim());
|
||||
|
||||
if (result.count === 0) {
|
||||
await sendTextMessage(
|
||||
chatId,
|
||||
`No subscription found for "<b>${escapeHtml(pattern.trim())}</b>".`,
|
||||
"textParseModeHTML"
|
||||
);
|
||||
} else {
|
||||
await sendTextMessage(
|
||||
chatId,
|
||||
`🔕 Unsubscribed from "<b>${escapeHtml(pattern.trim())}</b>".`,
|
||||
"textParseModeHTML"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleListSubscriptions(
|
||||
chatId: bigint,
|
||||
userId: bigint
|
||||
): Promise<void> {
|
||||
const subs = await getSubscriptions(userId);
|
||||
|
||||
if (subs.length === 0) {
|
||||
await sendTextMessage(
|
||||
chatId,
|
||||
"You have no active subscriptions. Use /subscribe <keyword> to add one.",
|
||||
"textParseModeHTML"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const lines = subs.map(
|
||||
(s, i) => `${i + 1}. <b>${escapeHtml(s.pattern)}</b> (since ${formatDate(s.createdAt)})`
|
||||
);
|
||||
|
||||
const response = [
|
||||
`🔔 <b>Your subscriptions:</b>`,
|
||||
``,
|
||||
...lines,
|
||||
``,
|
||||
`Use /unsubscribe <keyword> to remove one.`,
|
||||
].join("\n");
|
||||
|
||||
await sendTextMessage(chatId, response, "textParseModeHTML");
|
||||
}
|
||||
|
||||
async function handleStatus(chatId: bigint, userId: bigint): Promise<void> {
|
||||
const link = await findLinkByTelegramUserId(userId);
|
||||
|
||||
if (link) {
|
||||
await sendTextMessage(
|
||||
chatId,
|
||||
`✅ <b>Linked</b>\n\nYour Telegram account is linked to a web account.\nLinked since: ${formatDate(link.createdAt)}`,
|
||||
"textParseModeHTML"
|
||||
);
|
||||
} else {
|
||||
await sendTextMessage(
|
||||
chatId,
|
||||
`❌ <b>Not linked</b>\n\nUse /link <code> to connect your web account.`,
|
||||
"textParseModeHTML"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function escapeHtml(text: string): string {
|
||||
return text
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">");
|
||||
}
|
||||
13
bot/src/db/client.ts
Normal file
13
bot/src/db/client.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import { PrismaPg } from "@prisma/adapter-pg";
|
||||
import pg from "pg";
|
||||
import { config } from "../util/config.js";
|
||||
|
||||
const pool = new pg.Pool({
|
||||
connectionString: config.databaseUrl,
|
||||
max: 5,
|
||||
});
|
||||
|
||||
const adapter = new PrismaPg(pool);
|
||||
export const db = new PrismaClient({ adapter });
|
||||
export { pool };
|
||||
180
bot/src/db/queries.ts
Normal file
180
bot/src/db/queries.ts
Normal file
@@ -0,0 +1,180 @@
|
||||
import { db } from "./client.js";
|
||||
|
||||
// ── Link management ──
|
||||
|
||||
export async function findLinkByTelegramUserId(telegramUserId: bigint) {
|
||||
return db.telegramLink.findUnique({
|
||||
where: { telegramUserId },
|
||||
});
|
||||
}
|
||||
|
||||
export async function findLinkByUserId(userId: string) {
|
||||
return db.telegramLink.findUnique({
|
||||
where: { userId },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a link code stored in global_settings as `link_code:<code>`.
|
||||
* Returns the userId if the code is valid, null otherwise.
|
||||
*/
|
||||
export async function validateLinkCode(code: string): Promise<string | null> {
|
||||
const key = `link_code:${code}`;
|
||||
const setting = await db.globalSetting.findUnique({ where: { key } });
|
||||
return setting?.value ?? null;
|
||||
}
|
||||
|
||||
export async function deleteLinkCode(code: string): Promise<void> {
|
||||
const key = `link_code:${code}`;
|
||||
await db.globalSetting.delete({ where: { key } }).catch(() => {});
|
||||
}
|
||||
|
||||
export async function createTelegramLink(
|
||||
userId: string,
|
||||
telegramUserId: bigint,
|
||||
telegramName: string | null
|
||||
) {
|
||||
return db.telegramLink.upsert({
|
||||
where: { userId },
|
||||
create: { userId, telegramUserId, telegramName },
|
||||
update: { telegramUserId, telegramName },
|
||||
});
|
||||
}
|
||||
|
||||
// ── Package search ──
|
||||
|
||||
export async function searchPackages(query: string, limit = 10) {
|
||||
const packages = await db.package.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ fileName: { contains: query, mode: "insensitive" } },
|
||||
{ creator: { contains: query, mode: "insensitive" } },
|
||||
],
|
||||
},
|
||||
orderBy: { indexedAt: "desc" },
|
||||
take: limit,
|
||||
select: {
|
||||
id: true,
|
||||
fileName: true,
|
||||
fileSize: true,
|
||||
archiveType: true,
|
||||
fileCount: true,
|
||||
creator: true,
|
||||
indexedAt: true,
|
||||
destChannelId: true,
|
||||
destMessageId: true,
|
||||
},
|
||||
});
|
||||
return packages;
|
||||
}
|
||||
|
||||
export async function getLatestPackages(limit = 5) {
|
||||
return db.package.findMany({
|
||||
orderBy: { indexedAt: "desc" },
|
||||
take: limit,
|
||||
select: {
|
||||
id: true,
|
||||
fileName: true,
|
||||
fileSize: true,
|
||||
archiveType: true,
|
||||
fileCount: true,
|
||||
creator: true,
|
||||
indexedAt: true,
|
||||
destChannelId: true,
|
||||
destMessageId: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getPackageById(id: string) {
|
||||
return db.package.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
files: { take: 20, orderBy: { path: "asc" } },
|
||||
sourceChannel: { select: { title: true } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ── Send requests ──
|
||||
|
||||
export async function getPendingSendRequest(requestId: string) {
|
||||
return db.botSendRequest.findUnique({
|
||||
where: { id: requestId },
|
||||
include: {
|
||||
package: {
|
||||
select: {
|
||||
id: true,
|
||||
fileName: true,
|
||||
destChannelId: true,
|
||||
destMessageId: true,
|
||||
previewData: true,
|
||||
},
|
||||
},
|
||||
telegramLink: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateSendRequest(
|
||||
requestId: string,
|
||||
status: "SENDING" | "SENT" | "FAILED",
|
||||
error?: string
|
||||
) {
|
||||
return db.botSendRequest.update({
|
||||
where: { id: requestId },
|
||||
data: {
|
||||
status,
|
||||
error: error ?? undefined,
|
||||
completedAt: status === "SENT" || status === "FAILED" ? new Date() : undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ── Subscriptions ──
|
||||
|
||||
export async function getSubscriptions(telegramUserId: bigint) {
|
||||
return db.botSubscription.findMany({
|
||||
where: { telegramUserId },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
}
|
||||
|
||||
export async function addSubscription(telegramUserId: bigint, pattern: string) {
|
||||
return db.botSubscription.upsert({
|
||||
where: {
|
||||
telegramUserId_pattern: { telegramUserId, pattern },
|
||||
},
|
||||
create: { telegramUserId, pattern },
|
||||
update: {},
|
||||
});
|
||||
}
|
||||
|
||||
export async function removeSubscription(telegramUserId: bigint, pattern: string) {
|
||||
return db.botSubscription.deleteMany({
|
||||
where: { telegramUserId, pattern },
|
||||
});
|
||||
}
|
||||
|
||||
export async function findMatchingSubscriptions(fileName: string, creator: string | null) {
|
||||
// Get all subscriptions and filter in-memory (simpler for pattern matching)
|
||||
const subs = await db.botSubscription.findMany();
|
||||
return subs.filter((sub) => {
|
||||
const p = sub.pattern.toLowerCase();
|
||||
if (fileName.toLowerCase().includes(p)) return true;
|
||||
if (creator && creator.toLowerCase().includes(p)) return true;
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
// ── Destination channel ──
|
||||
|
||||
export async function getGlobalDestinationChannel() {
|
||||
const setting = await db.globalSetting.findUnique({
|
||||
where: { key: "destination_channel_id" },
|
||||
});
|
||||
if (!setting) return null;
|
||||
return db.telegramChannel.findFirst({
|
||||
where: { id: setting.value, type: "DESTINATION", isActive: true },
|
||||
});
|
||||
}
|
||||
92
bot/src/index.ts
Normal file
92
bot/src/index.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
import { config } from "./util/config.js";
|
||||
import { logger } from "./util/logger.js";
|
||||
import { db, pool } from "./db/client.js";
|
||||
import { createBotClient, closeBotClient, onBotUpdate } from "./tdlib/client.js";
|
||||
import { startSendListener, stopSendListener } from "./send-listener.js";
|
||||
import { handleMessage } from "./commands.js";
|
||||
import { mkdir } from "fs/promises";
|
||||
|
||||
const log = logger.child({ module: "main" });
|
||||
|
||||
async function main(): Promise<void> {
|
||||
log.info("DragonsStash Telegram Bot starting");
|
||||
|
||||
if (!config.botToken) {
|
||||
log.fatal("BOT_TOKEN environment variable is required");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (!config.telegramApiId || !config.telegramApiHash) {
|
||||
log.fatal("TELEGRAM_API_ID and TELEGRAM_API_HASH are required");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Ensure TDLib state directory exists
|
||||
await mkdir(config.tdlibStateDir, { recursive: true });
|
||||
await mkdir(`${config.tdlibStateDir}/bot`, { recursive: true });
|
||||
await mkdir(`${config.tdlibStateDir}/bot_files`, { recursive: true });
|
||||
|
||||
// Initialize TDLib bot client
|
||||
await createBotClient();
|
||||
|
||||
// Start pg_notify listener for send requests and new package notifications
|
||||
await startSendListener();
|
||||
|
||||
// Listen for incoming messages from Telegram users
|
||||
onBotUpdate((update) => {
|
||||
if (update._ === "updateNewMessage") {
|
||||
const message = update.message as Record<string, unknown>;
|
||||
const content = message.content as Record<string, unknown>;
|
||||
const chatId = message.chat_id as number;
|
||||
const senderId = message.sender_id as Record<string, unknown> | undefined;
|
||||
|
||||
// Only handle text messages from users (not channels or service messages)
|
||||
if (
|
||||
content?._ === "messageText" &&
|
||||
senderId?._ === "messageSenderUser"
|
||||
) {
|
||||
const text = (content.text as Record<string, unknown>)?.text as string;
|
||||
const userId = senderId.user_id as number;
|
||||
|
||||
if (text && userId) {
|
||||
// Get user info for display name (async but fire-and-forget for perf)
|
||||
handleMessage({
|
||||
chatId: BigInt(chatId),
|
||||
userId: BigInt(userId),
|
||||
text,
|
||||
firstName: "User", // TDLib provides this via a separate getUser call
|
||||
username: undefined,
|
||||
}).catch((err) => {
|
||||
log.error({ err, chatId, userId }, "Failed to handle message");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
log.info("Bot is running and listening for messages");
|
||||
}
|
||||
|
||||
// Graceful shutdown
|
||||
function shutdown(signal: string): void {
|
||||
log.info({ signal }, "Shutdown signal received");
|
||||
stopSendListener();
|
||||
|
||||
Promise.all([closeBotClient(), db.$disconnect(), pool.end()])
|
||||
.then(() => {
|
||||
log.info("Shutdown complete");
|
||||
process.exit(0);
|
||||
})
|
||||
.catch((err) => {
|
||||
log.error({ err }, "Error during shutdown");
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
process.on("SIGTERM", () => shutdown("SIGTERM"));
|
||||
process.on("SIGINT", () => shutdown("SIGINT"));
|
||||
|
||||
main().catch((err) => {
|
||||
log.fatal({ err }, "Bot failed to start");
|
||||
process.exit(1);
|
||||
});
|
||||
162
bot/src/send-listener.ts
Normal file
162
bot/src/send-listener.ts
Normal file
@@ -0,0 +1,162 @@
|
||||
import type pg from "pg";
|
||||
import { pool } from "./db/client.js";
|
||||
import { childLogger } from "./util/logger.js";
|
||||
import {
|
||||
getPendingSendRequest,
|
||||
updateSendRequest,
|
||||
findMatchingSubscriptions,
|
||||
getGlobalDestinationChannel,
|
||||
} from "./db/queries.js";
|
||||
import { copyMessageToUser, sendTextMessage, sendPhotoMessage } from "./tdlib/client.js";
|
||||
|
||||
const log = childLogger("send-listener");
|
||||
|
||||
let pgClient: pg.PoolClient | null = null;
|
||||
|
||||
/**
|
||||
* Start listening for pg_notify signals:
|
||||
* - `bot_send` — payload = requestId → send a package to a user
|
||||
* - `new_package` — payload = JSON { packageId, fileName, creator } → notify subscribers
|
||||
*/
|
||||
export async function startSendListener(): Promise<void> {
|
||||
pgClient = await pool.connect();
|
||||
await pgClient.query("LISTEN bot_send");
|
||||
await pgClient.query("LISTEN new_package");
|
||||
|
||||
pgClient.on("notification", (msg) => {
|
||||
if (msg.channel === "bot_send" && msg.payload) {
|
||||
handleBotSend(msg.payload);
|
||||
} else if (msg.channel === "new_package" && msg.payload) {
|
||||
handleNewPackage(msg.payload);
|
||||
}
|
||||
});
|
||||
|
||||
log.info("Send listener started (bot_send, new_package)");
|
||||
}
|
||||
|
||||
export function stopSendListener(): void {
|
||||
if (pgClient) {
|
||||
pgClient.release();
|
||||
pgClient = null;
|
||||
}
|
||||
log.info("Send listener stopped");
|
||||
}
|
||||
|
||||
// ── bot_send handler ──
|
||||
|
||||
let sendQueue: Promise<void> = Promise.resolve();
|
||||
|
||||
function handleBotSend(requestId: string): void {
|
||||
sendQueue = sendQueue.then(() => processSendRequest(requestId)).catch((err) => {
|
||||
log.error({ err, requestId }, "Send request processing failed");
|
||||
});
|
||||
}
|
||||
|
||||
async function processSendRequest(requestId: string): Promise<void> {
|
||||
const request = await getPendingSendRequest(requestId);
|
||||
if (!request || request.status !== "PENDING") {
|
||||
log.warn({ requestId }, "Send request not found or not pending");
|
||||
return;
|
||||
}
|
||||
|
||||
log.info(
|
||||
{
|
||||
requestId,
|
||||
packageId: request.packageId,
|
||||
targetTgId: request.telegramLink.telegramUserId.toString(),
|
||||
},
|
||||
"Processing send request"
|
||||
);
|
||||
|
||||
await updateSendRequest(requestId, "SENDING");
|
||||
|
||||
try {
|
||||
const pkg = request.package;
|
||||
const targetUserId = request.telegramLink.telegramUserId;
|
||||
|
||||
if (!pkg.destChannelId || !pkg.destMessageId) {
|
||||
throw new Error("Package has no destination message — cannot forward");
|
||||
}
|
||||
|
||||
// Get the destination channel's Telegram ID
|
||||
const destChannel = await getGlobalDestinationChannel();
|
||||
if (!destChannel) {
|
||||
throw new Error("No global destination channel configured");
|
||||
}
|
||||
|
||||
// Send preview if available
|
||||
if (pkg.previewData) {
|
||||
const caption = `📦 *${pkg.fileName}*\n\nSent from Dragon's Stash`;
|
||||
await sendPhotoMessage(targetUserId, Buffer.from(pkg.previewData), caption);
|
||||
}
|
||||
|
||||
// Forward the actual archive file(s) from destination channel
|
||||
await copyMessageToUser(
|
||||
destChannel.telegramId,
|
||||
pkg.destMessageId,
|
||||
targetUserId
|
||||
);
|
||||
|
||||
await updateSendRequest(requestId, "SENT");
|
||||
log.info({ requestId }, "Send request completed successfully");
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
log.error({ err, requestId }, "Send request failed");
|
||||
await updateSendRequest(requestId, "FAILED", message);
|
||||
}
|
||||
}
|
||||
|
||||
// ── new_package handler ──
|
||||
|
||||
async function handleNewPackage(payload: string): Promise<void> {
|
||||
try {
|
||||
const data = JSON.parse(payload) as {
|
||||
packageId: string;
|
||||
fileName: string;
|
||||
creator: string | null;
|
||||
};
|
||||
|
||||
const subs = await findMatchingSubscriptions(data.fileName, data.creator);
|
||||
if (subs.length === 0) return;
|
||||
|
||||
log.info(
|
||||
{ packageId: data.packageId, matchedSubscriptions: subs.length },
|
||||
"Notifying subscribers of new package"
|
||||
);
|
||||
|
||||
// Group by user to send one notification per user
|
||||
const userSubs = new Map<string, string[]>();
|
||||
for (const sub of subs) {
|
||||
const key = sub.telegramUserId.toString();
|
||||
const patterns = userSubs.get(key) ?? [];
|
||||
patterns.push(sub.pattern);
|
||||
userSubs.set(key, patterns);
|
||||
}
|
||||
|
||||
const creator = data.creator ? ` by ${data.creator}` : "";
|
||||
for (const [telegramUserId, patterns] of userSubs) {
|
||||
const msg = [
|
||||
`🔔 <b>New package matching your subscriptions:</b>`,
|
||||
``,
|
||||
`📦 <b>${escapeHtml(data.fileName)}</b>${creator}`,
|
||||
``,
|
||||
`Matched: ${patterns.map((p) => `"${escapeHtml(p)}"`).join(", ")}`,
|
||||
``,
|
||||
`Use /package ${data.packageId} for details.`,
|
||||
].join("\n");
|
||||
|
||||
await sendTextMessage(BigInt(telegramUserId), msg, "textParseModeHTML").catch((err) => {
|
||||
log.warn(
|
||||
{ err, telegramUserId, packageId: data.packageId },
|
||||
"Failed to notify subscriber"
|
||||
);
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
log.error({ err, payload }, "Failed to process new_package notification");
|
||||
}
|
||||
}
|
||||
|
||||
function escapeHtml(text: string): string {
|
||||
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
}
|
||||
155
bot/src/tdlib/client.ts
Normal file
155
bot/src/tdlib/client.ts
Normal file
@@ -0,0 +1,155 @@
|
||||
import tdl from "tdl";
|
||||
import { getTdjson } from "prebuilt-tdlib";
|
||||
import { config } from "../util/config.js";
|
||||
import { childLogger } from "../util/logger.js";
|
||||
|
||||
const log = childLogger("tdlib-bot");
|
||||
|
||||
tdl.configure({ tdjson: getTdjson() });
|
||||
|
||||
let client: tdl.Client | null = null;
|
||||
|
||||
/**
|
||||
* Create and authenticate a TDLib client using the bot token.
|
||||
* Bot accounts have different capabilities from user accounts —
|
||||
* they can't read channel history but can send/forward/copy messages
|
||||
* to users who have interacted with them.
|
||||
*/
|
||||
export async function createBotClient(): Promise<tdl.Client> {
|
||||
if (client) return client;
|
||||
|
||||
log.info("Creating TDLib bot client");
|
||||
|
||||
client = tdl.createClient({
|
||||
apiId: config.telegramApiId,
|
||||
apiHash: config.telegramApiHash,
|
||||
databaseDirectory: `${config.tdlibStateDir}/bot`,
|
||||
filesDirectory: `${config.tdlibStateDir}/bot_files`,
|
||||
});
|
||||
|
||||
client.on("error", (err) => {
|
||||
log.error({ err }, "TDLib client error");
|
||||
});
|
||||
|
||||
await client.login(() => ({
|
||||
type: "bot",
|
||||
token: config.botToken,
|
||||
}));
|
||||
|
||||
log.info("Bot client authenticated successfully");
|
||||
return client;
|
||||
}
|
||||
|
||||
export async function closeBotClient(): Promise<void> {
|
||||
if (client) {
|
||||
try {
|
||||
await client.close();
|
||||
} catch {
|
||||
// Ignore close errors
|
||||
}
|
||||
client = null;
|
||||
log.info("Bot client closed");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Forward a message from a channel to a user's DM.
|
||||
* Uses copyMessage to make it appear as sent by the bot.
|
||||
*/
|
||||
export async function copyMessageToUser(
|
||||
fromChatId: bigint,
|
||||
messageId: bigint,
|
||||
toUserId: bigint
|
||||
): Promise<void> {
|
||||
if (!client) throw new Error("Bot client not initialized");
|
||||
|
||||
// TDLib uses negative chat IDs for channels/supergroups
|
||||
// The telegramId from the DB is the raw Telegram ID; for channels it needs -100 prefix
|
||||
const fromChatIdNum = Number(-100n * 1n) + Number(fromChatId);
|
||||
|
||||
await client.invoke({
|
||||
_: "forwardMessages",
|
||||
chat_id: Number(toUserId),
|
||||
from_chat_id: Number(fromChatId) > 0 ? -Number(fromChatId) : Number(fromChatId),
|
||||
message_ids: [Number(messageId)],
|
||||
send_copy: true,
|
||||
remove_caption: false,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a text message to a user.
|
||||
*/
|
||||
export async function sendTextMessage(
|
||||
chatId: bigint,
|
||||
text: string,
|
||||
parseMode: "textParseModeMarkdown" | "textParseModeHTML" = "textParseModeMarkdown"
|
||||
): Promise<void> {
|
||||
if (!client) throw new Error("Bot client not initialized");
|
||||
|
||||
// Parse the text first
|
||||
const parsed = await client.invoke({
|
||||
_: "parseTextEntities",
|
||||
text,
|
||||
parse_mode: { _: parseMode, version: parseMode === "textParseModeMarkdown" ? 2 : 0 },
|
||||
});
|
||||
|
||||
await client.invoke({
|
||||
_: "sendMessage",
|
||||
chat_id: Number(chatId),
|
||||
input_message_content: {
|
||||
_: "inputMessageText",
|
||||
text: parsed,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a photo with caption to a user (for preview images).
|
||||
*/
|
||||
export async function sendPhotoMessage(
|
||||
chatId: bigint,
|
||||
photoData: Buffer,
|
||||
caption: string
|
||||
): Promise<void> {
|
||||
if (!client) throw new Error("Bot client not initialized");
|
||||
|
||||
// Write the photo to a temp file
|
||||
const { writeFile, unlink } = await import("fs/promises");
|
||||
const path = await import("path");
|
||||
const tempPath = path.join(config.tdlibStateDir, `preview_${Date.now()}.jpg`);
|
||||
|
||||
try {
|
||||
await writeFile(tempPath, photoData);
|
||||
|
||||
const parsedCaption = await client.invoke({
|
||||
_: "parseTextEntities",
|
||||
text: caption,
|
||||
parse_mode: { _: "textParseModeMarkdown", version: 2 },
|
||||
});
|
||||
|
||||
await client.invoke({
|
||||
_: "sendMessage",
|
||||
chat_id: Number(chatId),
|
||||
input_message_content: {
|
||||
_: "inputMessagePhoto",
|
||||
photo: { _: "inputFileLocal", path: tempPath },
|
||||
caption: parsedCaption,
|
||||
width: 0,
|
||||
height: 0,
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await unlink(tempPath).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get updates from TDLib. The bot listens for new messages this way.
|
||||
*/
|
||||
export function onBotUpdate(
|
||||
handler: (update: Record<string, unknown>) => void
|
||||
): void {
|
||||
if (!client) throw new Error("Bot client not initialized");
|
||||
client.on("update", handler);
|
||||
}
|
||||
8
bot/src/util/config.ts
Normal file
8
bot/src/util/config.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
export const config = {
|
||||
databaseUrl: process.env.DATABASE_URL ?? "",
|
||||
botToken: process.env.BOT_TOKEN ?? "",
|
||||
telegramApiId: parseInt(process.env.TELEGRAM_API_ID ?? "0", 10),
|
||||
telegramApiHash: process.env.TELEGRAM_API_HASH ?? "",
|
||||
logLevel: (process.env.LOG_LEVEL ?? "info") as "debug" | "info" | "warn" | "error",
|
||||
tdlibStateDir: process.env.TDLIB_STATE_DIR ?? "/data/tdlib",
|
||||
} as const;
|
||||
14
bot/src/util/logger.ts
Normal file
14
bot/src/util/logger.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import pino from "pino";
|
||||
import { config } from "./config.js";
|
||||
|
||||
export const logger = pino({
|
||||
level: config.logLevel,
|
||||
transport:
|
||||
config.logLevel === "debug"
|
||||
? { target: "pino/file", options: { destination: 1 } }
|
||||
: undefined,
|
||||
});
|
||||
|
||||
export function childLogger(module: string, extra?: Record<string, unknown>) {
|
||||
return logger.child({ module, ...extra });
|
||||
}
|
||||
19
bot/tsconfig.json
Normal file
19
bot/tsconfig.json
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"lib": ["ES2022"],
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"declaration": true,
|
||||
"sourceMap": true
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
@@ -4,25 +4,26 @@ services:
|
||||
ports:
|
||||
- "5432:5432"
|
||||
environment:
|
||||
POSTGRES_USER: dragons
|
||||
POSTGRES_PASSWORD: stash
|
||||
POSTGRES_DB: dragonsstash
|
||||
POSTGRES_USER: ${POSTGRES_USER:-dragons}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-stash}
|
||||
POSTGRES_DB: ${POSTGRES_DB:-dragonsstash}
|
||||
volumes:
|
||||
- postgres_dev_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U dragons -d dragonsstash"]
|
||||
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-dragons} -d ${POSTGRES_DB:-dragonsstash}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
worker:
|
||||
profiles: ["telegram", "full"]
|
||||
build:
|
||||
context: .
|
||||
dockerfile: worker/Dockerfile
|
||||
env_file:
|
||||
- .env.local
|
||||
environment:
|
||||
- DATABASE_URL=postgresql://dragons:stash@db:5432/dragonsstash
|
||||
- DATABASE_URL=postgresql://${POSTGRES_USER:-dragons}:${POSTGRES_PASSWORD:-stash}@db:5432/${POSTGRES_DB:-dragonsstash}
|
||||
- WORKER_INTERVAL_MINUTES=5
|
||||
- WORKER_TEMP_DIR=/tmp/zips
|
||||
- TDLIB_STATE_DIR=/data/tdlib
|
||||
@@ -35,7 +36,24 @@ services:
|
||||
db:
|
||||
condition: service_healthy
|
||||
|
||||
bot:
|
||||
profiles: ["bot", "full"]
|
||||
build:
|
||||
context: .
|
||||
dockerfile: bot/Dockerfile
|
||||
env_file:
|
||||
- .env.local
|
||||
environment:
|
||||
- DATABASE_URL=postgresql://${POSTGRES_USER:-dragons}:${POSTGRES_PASSWORD:-stash}@db:5432/${POSTGRES_DB:-dragonsstash}
|
||||
- LOG_LEVEL=debug
|
||||
volumes:
|
||||
- tdlib_dev_bot_state:/data/tdlib
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
|
||||
volumes:
|
||||
postgres_dev_data:
|
||||
tdlib_dev_state:
|
||||
tdlib_dev_bot_state:
|
||||
tmp_dev_zips:
|
||||
|
||||
@@ -4,29 +4,46 @@ services:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
ports:
|
||||
- "3000:3000"
|
||||
- "${APP_PORT:-3000}:3000"
|
||||
environment:
|
||||
- DATABASE_URL=postgresql://dragons:stash@db:5432/dragonsstash
|
||||
- AUTH_SECRET=change-me-to-a-random-secret-in-production
|
||||
- DATABASE_URL=postgresql://${POSTGRES_USER:-dragons}:${POSTGRES_PASSWORD:-stash}@db:5432/${POSTGRES_DB:-dragonsstash}
|
||||
- AUTH_SECRET=${AUTH_SECRET:?Set AUTH_SECRET in .env}
|
||||
- AUTH_TRUST_HOST=true
|
||||
- NEXT_PUBLIC_APP_URL=http://localhost:3000
|
||||
- NEXT_PUBLIC_APP_URL=${NEXT_PUBLIC_APP_URL:-http://localhost:3000}
|
||||
- TELEGRAM_API_KEY=${TELEGRAM_API_KEY:-}
|
||||
- BOT_TOKEN=${BOT_TOKEN:-}
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "--spider", "http://localhost:3000/api/health"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 30s
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 512M
|
||||
networks:
|
||||
- frontend
|
||||
|
||||
worker:
|
||||
profiles: ["telegram", "full"]
|
||||
build:
|
||||
context: .
|
||||
dockerfile: worker/Dockerfile
|
||||
environment:
|
||||
- DATABASE_URL=postgresql://dragons:stash@db:5432/dragonsstash
|
||||
- WORKER_INTERVAL_MINUTES=60
|
||||
- DATABASE_URL=postgresql://${POSTGRES_USER:-dragons}:${POSTGRES_PASSWORD:-stash}@db:5432/${POSTGRES_DB:-dragonsstash}
|
||||
- TELEGRAM_API_ID=${TELEGRAM_API_ID:?Set TELEGRAM_API_ID in .env}
|
||||
- TELEGRAM_API_HASH=${TELEGRAM_API_HASH:?Set TELEGRAM_API_HASH in .env}
|
||||
- WORKER_INTERVAL_MINUTES=${WORKER_INTERVAL_MINUTES:-60}
|
||||
- WORKER_TEMP_DIR=/tmp/zips
|
||||
- TDLIB_STATE_DIR=/data/tdlib
|
||||
- WORKER_MAX_ZIP_SIZE_MB=4096
|
||||
- LOG_LEVEL=info
|
||||
- WORKER_MAX_ZIP_SIZE_MB=${WORKER_MAX_ZIP_SIZE_MB:-4096}
|
||||
- MULTIPART_TIMEOUT_HOURS=${MULTIPART_TIMEOUT_HOURS:-0}
|
||||
- LOG_LEVEL=${LOG_LEVEL:-info}
|
||||
volumes:
|
||||
- tdlib_state:/data/tdlib
|
||||
- tmp_zips:/tmp/zips
|
||||
@@ -40,25 +57,63 @@ services:
|
||||
memory: 1G
|
||||
reservations:
|
||||
memory: 256M
|
||||
networks:
|
||||
- backend
|
||||
|
||||
bot:
|
||||
profiles: ["bot", "full"]
|
||||
build:
|
||||
context: .
|
||||
dockerfile: bot/Dockerfile
|
||||
environment:
|
||||
- DATABASE_URL=postgresql://${POSTGRES_USER:-dragons}:${POSTGRES_PASSWORD:-stash}@db:5432/${POSTGRES_DB:-dragonsstash}
|
||||
- BOT_TOKEN=${BOT_TOKEN:?Set BOT_TOKEN in .env}
|
||||
- TELEGRAM_API_ID=${TELEGRAM_API_ID:?Set TELEGRAM_API_ID in .env}
|
||||
- TELEGRAM_API_HASH=${TELEGRAM_API_HASH:?Set TELEGRAM_API_HASH in .env}
|
||||
- LOG_LEVEL=${LOG_LEVEL:-info}
|
||||
volumes:
|
||||
- tdlib_bot_state:/data/tdlib
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 512M
|
||||
reservations:
|
||||
memory: 128M
|
||||
networks:
|
||||
- backend
|
||||
|
||||
db:
|
||||
image: postgres:16-alpine
|
||||
ports:
|
||||
- "5432:5432"
|
||||
environment:
|
||||
POSTGRES_USER: dragons
|
||||
POSTGRES_PASSWORD: stash
|
||||
POSTGRES_DB: dragonsstash
|
||||
POSTGRES_USER: ${POSTGRES_USER:-dragons}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-stash}
|
||||
POSTGRES_DB: ${POSTGRES_DB:-dragonsstash}
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U dragons -d dragonsstash"]
|
||||
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-dragons} -d ${POSTGRES_DB:-dragonsstash}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 1G
|
||||
networks:
|
||||
- frontend
|
||||
- backend
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
tdlib_state:
|
||||
tdlib_bot_state:
|
||||
tmp_zips:
|
||||
|
||||
networks:
|
||||
frontend:
|
||||
backend:
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
# Guard: refuse to start with the placeholder AUTH_SECRET
|
||||
if [ "$AUTH_SECRET" = "change-me-to-a-random-secret-in-production" ] || [ -z "$AUTH_SECRET" ]; then
|
||||
echo "ERROR: AUTH_SECRET is not set or still uses the placeholder value."
|
||||
echo "Generate one with: openssl rand -base64 32"
|
||||
echo "Then set it in your .env file."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Running database migrations..."
|
||||
npx prisma migrate deploy
|
||||
|
||||
|
||||
1
package-lock.json
generated
1
package-lock.json
generated
@@ -7,6 +7,7 @@
|
||||
"": {
|
||||
"name": "dragons-stash",
|
||||
"version": "0.1.0",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@auth/prisma-adapter": "^2.11.1",
|
||||
"@hookform/resolvers": "^5.2.2",
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "BotSendStatus" AS ENUM ('PENDING', 'SENDING', 'SENT', 'FAILED');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "telegram_links" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"telegramUserId" BIGINT NOT NULL,
|
||||
"telegramName" VARCHAR(128),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "telegram_links_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "bot_send_requests" (
|
||||
"id" TEXT NOT NULL,
|
||||
"packageId" TEXT NOT NULL,
|
||||
"telegramLinkId" TEXT NOT NULL,
|
||||
"requestedByUserId" TEXT NOT NULL,
|
||||
"status" "BotSendStatus" NOT NULL DEFAULT 'PENDING',
|
||||
"error" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"completedAt" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "bot_send_requests_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "bot_subscriptions" (
|
||||
"id" TEXT NOT NULL,
|
||||
"telegramUserId" BIGINT NOT NULL,
|
||||
"pattern" VARCHAR(256) NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "bot_subscriptions_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "telegram_links_userId_key" ON "telegram_links"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "telegram_links_telegramUserId_key" ON "telegram_links"("telegramUserId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "bot_send_requests_status_idx" ON "bot_send_requests"("status");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "bot_send_requests_telegramLinkId_idx" ON "bot_send_requests"("telegramLinkId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "bot_send_requests_createdAt_idx" ON "bot_send_requests"("createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "bot_subscriptions_telegramUserId_pattern_key" ON "bot_subscriptions"("telegramUserId", "pattern");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "bot_subscriptions_telegramUserId_idx" ON "bot_subscriptions"("telegramUserId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "telegram_links" ADD CONSTRAINT "telegram_links_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "bot_send_requests" ADD CONSTRAINT "bot_send_requests_packageId_fkey" FOREIGN KEY ("packageId") REFERENCES "packages"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "bot_send_requests" ADD CONSTRAINT "bot_send_requests_telegramLinkId_fkey" FOREIGN KEY ("telegramLinkId") REFERENCES "telegram_links"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -4,6 +4,7 @@ generator client {
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
// ───────────────────────────────────────
|
||||
@@ -34,9 +35,10 @@ model User {
|
||||
supplies Supply[]
|
||||
vendors Vendor[]
|
||||
locations Location[]
|
||||
usageLogs UsageLog[]
|
||||
tags Tag[]
|
||||
settings UserSettings?
|
||||
usageLogs UsageLog[]
|
||||
tags Tag[]
|
||||
settings UserSettings?
|
||||
telegramLink TelegramLink?
|
||||
}
|
||||
|
||||
model Account {
|
||||
@@ -469,6 +471,7 @@ model Package {
|
||||
files PackageFile[]
|
||||
ingestionRun IngestionRun? @relation(fields: [ingestionRunId], references: [id])
|
||||
ingestionRunId String?
|
||||
sendRequests BotSendRequest[]
|
||||
|
||||
@@index([sourceChannelId])
|
||||
@@index([destChannelId])
|
||||
@@ -566,3 +569,61 @@ model ChannelFetchRequest {
|
||||
@@index([accountId, status])
|
||||
@@map("channel_fetch_requests")
|
||||
}
|
||||
|
||||
// ───────────────────────────────────────
|
||||
// Telegram Bot models
|
||||
// ───────────────────────────────────────
|
||||
|
||||
enum BotSendStatus {
|
||||
PENDING
|
||||
SENDING
|
||||
SENT
|
||||
FAILED
|
||||
}
|
||||
|
||||
/// Links a NextAuth user to a Telegram user ID.
|
||||
/// Created when a user sends /link <code> to the bot.
|
||||
model TelegramLink {
|
||||
id String @id @default(cuid())
|
||||
userId String @unique
|
||||
telegramUserId BigInt @unique
|
||||
telegramName String? @db.VarChar(128)
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
sendRequests BotSendRequest[]
|
||||
|
||||
@@map("telegram_links")
|
||||
}
|
||||
|
||||
/// A queued request to send a package to a Telegram user via the bot.
|
||||
model BotSendRequest {
|
||||
id String @id @default(cuid())
|
||||
packageId String
|
||||
telegramLinkId String
|
||||
requestedByUserId String
|
||||
status BotSendStatus @default(PENDING)
|
||||
error String?
|
||||
createdAt DateTime @default(now())
|
||||
completedAt DateTime?
|
||||
|
||||
package Package @relation(fields: [packageId], references: [id])
|
||||
telegramLink TelegramLink @relation(fields: [telegramLinkId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([status])
|
||||
@@index([telegramLinkId])
|
||||
@@index([createdAt])
|
||||
@@map("bot_send_requests")
|
||||
}
|
||||
|
||||
/// Subscriptions for new-package notifications via the bot.
|
||||
model BotSubscription {
|
||||
id String @id @default(cuid())
|
||||
telegramUserId BigInt
|
||||
pattern String @db.VarChar(256)
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@unique([telegramUserId, pattern])
|
||||
@@index([telegramUserId])
|
||||
@@map("bot_subscriptions")
|
||||
}
|
||||
|
||||
209
src/app/(app)/settings/_components/telegram-link-card.tsx
Normal file
209
src/app/(app)/settings/_components/telegram-link-card.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
|
||||
171
src/app/(app)/settings/telegram-actions.ts
Normal file
171
src/app/(app)/settings/telegram-actions.ts
Normal 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,
|
||||
})),
|
||||
};
|
||||
}
|
||||
@@ -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,
|
||||
},
|
||||
|
||||
@@ -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>
|
||||
|
||||
|
||||
214
src/app/(app)/stls/_components/send-to-telegram-button.tsx
Normal file
214
src/app/(app)/stls/_components/send-to-telegram-button.tsx
Normal 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 “{packageName}” 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>
|
||||
);
|
||||
}
|
||||
111
src/app/(app)/telegram/_components/bot-sends-tab.tsx
Normal file
111
src/app/(app)/telegram/_components/bot-sends-tab.tsx
Normal 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 “Send to Telegram” 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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
|
||||
@@ -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}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
58
src/app/api/telegram/bot/send/[id]/route.ts
Normal file
58
src/app/api/telegram/bot/send/[id]/route.ts
Normal 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,
|
||||
});
|
||||
}
|
||||
98
src/app/api/telegram/bot/send/route.ts
Normal file
98
src/app/api/telegram/bot/send/route.ts
Normal 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`,
|
||||
});
|
||||
}
|
||||
9
src/types/telegram.types.ts
Normal file
9
src/types/telegram.types.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
export interface SendHistoryRow {
|
||||
id: string;
|
||||
packageName: string;
|
||||
recipientName: string | null;
|
||||
status: string;
|
||||
error: string | null;
|
||||
createdAt: string;
|
||||
completedAt: string | null;
|
||||
}
|
||||
@@ -116,7 +116,7 @@ export interface CreatePackageInput {
|
||||
}
|
||||
|
||||
export async function createPackageWithFiles(input: CreatePackageInput) {
|
||||
return db.package.create({
|
||||
const pkg = await db.package.create({
|
||||
data: {
|
||||
contentHash: input.contentHash,
|
||||
fileName: input.fileName,
|
||||
@@ -139,6 +139,22 @@ export async function createPackageWithFiles(input: CreatePackageInput) {
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Notify the bot service about the new package (for subscription alerts)
|
||||
try {
|
||||
await db.$queryRawUnsafe(
|
||||
`SELECT pg_notify('new_package', $1)`,
|
||||
JSON.stringify({
|
||||
packageId: pkg.id,
|
||||
fileName: input.fileName,
|
||||
creator: input.creator ?? null,
|
||||
})
|
||||
);
|
||||
} catch {
|
||||
// Best-effort — don't fail the ingestion if notification fails
|
||||
}
|
||||
|
||||
return pkg;
|
||||
}
|
||||
|
||||
export async function createIngestionRun(accountId: string) {
|
||||
|
||||
Reference in New Issue
Block a user