style: format and lint codebase using Biome v2

This commit is contained in:
MythEclipse
2026-05-18 07:29:01 +07:00
parent 3f4e697733
commit cf79a1f195
22 changed files with 638 additions and 528 deletions
+84 -59
View File
@@ -1,8 +1,8 @@
import { Telegraf, type Context } from 'telegraf';
import logger from './utils/logger';
import { config } from './env';
import { db, files as fileSchema } from './db';
import { nanoid } from 'nanoid';
import { type Context, Telegraf } from 'telegraf';
import { db, files as fileSchema } from './db';
import { config } from './env';
import logger from './utils/logger';
import { forwardToStorage } from './utils/telegram';
export const startBot = async (): Promise<Telegraf<Context>> => {
@@ -12,76 +12,101 @@ export const startBot = async (): Promise<Telegraf<Context>> => {
bot.command('start', async (ctx) => {
await ctx.reply(
`👋 Halo! Kirimkan file (document, photo, video, audio, voice, animation) ke bot ini. ` +
`File akan disimpan di private channel dan kamu dapat download link permanen.`
`File akan disimpan di private channel dan kamu dapat download link permanen.`,
);
});
// Cast bot.on elements individually or explicitly as any to bypass Telegraf v4 typescript deprecation warnings on array syntax
(bot as any).on(['document', 'photo', 'video', 'audio', 'voice', 'animation'], async (ctx: any) => {
try {
const fileType: 'document' | 'photo' | 'video' | 'audio' | 'voice' | 'animation' = ctx.message.document ? 'document' :
ctx.message.photo ? 'photo' :
ctx.message.video ? 'video' :
ctx.message.audio ? 'audio' :
ctx.message.voice ? 'voice' : 'animation';
(bot as any).on(
['document', 'photo', 'video', 'audio', 'voice', 'animation'],
async (ctx: any) => {
try {
const fileType: 'document' | 'photo' | 'video' | 'audio' | 'voice' | 'animation' = ctx
.message.document
? 'document'
: ctx.message.photo
? 'photo'
: ctx.message.video
? 'video'
: ctx.message.audio
? 'audio'
: ctx.message.voice
? 'voice'
: 'animation';
const fileObj = fileType === 'photo' ? ctx.message.photo.slice(-1)[0] : ctx.message[fileType];
const { file_id, file_size, mime_type } = fileObj;
const fileName = ctx.message.document?.file_name ||
ctx.message.photo?.slice(-1)[0]?.file_name ||
ctx.message.video?.file_name ||
ctx.message.audio?.file_name ||
ctx.message.voice?.file_name ||
'file';
const fileObj =
fileType === 'photo' ? ctx.message.photo.slice(-1)[0] : ctx.message[fileType];
const { file_id, file_size, mime_type } = fileObj;
const fileName =
ctx.message.document?.file_name ||
ctx.message.photo?.slice(-1)[0]?.file_name ||
ctx.message.video?.file_name ||
ctx.message.audio?.file_name ||
ctx.message.voice?.file_name ||
'file';
const maxSize = fileType === 'photo' ? 10 * 1024 * 1024 :
fileType === 'audio' ? 200 * 1024 * 1024 :
fileType === 'voice' ? 200 * 1024 * 1024 : 2 * 1024 * 1024 * 1024;
const maxSize =
fileType === 'photo'
? 10 * 1024 * 1024
: fileType === 'audio'
? 200 * 1024 * 1024
: fileType === 'voice'
? 200 * 1024 * 1024
: 2 * 1024 * 1024 * 1024;
if (file_size > maxSize) {
return ctx.reply(`File size exceeds ${maxSize / (1024 * 1024)}MB limit`);
if (file_size > maxSize) {
return ctx.reply(`File size exceeds ${maxSize / (1024 * 1024)}MB limit`);
}
const result = await forwardToStorage(file_id, fileName);
const publicId = nanoid();
const uploaded = {
publicId: publicId,
telegramFileId: result.telegramFileId,
telegramFileUniqueId: result.telegramFileUniqueId,
storageChatId: config.storageChatId,
storageMessageId: result.storageMessageId,
fileName: fileName,
mimeType: mime_type || 'application/octet-stream',
sizeBytes: file_size,
fileType: fileType,
uploaderId: ctx.from.id,
createdAt: new Date(),
updatedAt: new Date(),
};
await db.insert(fileSchema).values(uploaded);
const url = `${config.baseUrl}/f/${publicId}`;
await ctx.reply(`File berhasil diupload! 📎\n\nDownload: ${url}`, {
reply_parameters: { message_id: ctx.message.message_id },
});
logger.info('File uploaded via bot', {
publicId,
fileType,
fileName,
uploader: ctx.from.id,
});
} catch (error: any) {
logger.error('Bot file handler error', { error: error.message, chat_id: ctx.chat?.id });
await ctx.reply('❌ Gagal mengupload file. Coba lagi nanti.');
}
const result = await forwardToStorage(file_id, fileName);
const publicId = nanoid();
const uploaded = {
publicId: publicId,
telegramFileId: result.telegramFileId,
telegramFileUniqueId: result.telegramFileUniqueId,
storageChatId: config.storageChatId,
storageMessageId: result.storageMessageId,
fileName: fileName,
mimeType: mime_type || 'application/octet-stream',
sizeBytes: file_size,
fileType: fileType,
uploaderId: ctx.from.id,
createdAt: new Date(),
updatedAt: new Date()
};
await db.insert(fileSchema).values(uploaded);
const url = `${config.baseUrl}/f/${publicId}`;
await ctx.reply(`File berhasil diupload! 📎\n\nDownload: ${url}`, {
reply_parameters: { message_id: ctx.message.message_id }
});
logger.info('File uploaded via bot', { publicId, fileType, fileName, uploader: ctx.from.id });
} catch (error: any) {
logger.error('Bot file handler error', { error: error.message, chat_id: ctx.chat?.id });
await ctx.reply('❌ Gagal mengupload file. Coba lagi nanti.');
}
});
},
);
bot.use((ctx, next) => {
logger.info('Telegram event received', { type: (ctx.update as any).type, chat_id: ctx.chat?.id });
logger.info('Telegram event received', {
type: (ctx.update as any).type,
chat_id: ctx.chat?.id,
});
return next();
});
await bot.launch();
logger.info('Telegram bot started', { botToken: config.botToken?.substring(0, 10) + '...' });
logger.info('Telegram bot started', { botToken: `${config.botToken?.substring(0, 10)}...` });
return bot;
} catch (error: any) {
+2 -2
View File
@@ -5,9 +5,9 @@ import { files } from './schema';
const client = postgres(process.env.DATABASE_URL!, {
max: 10,
idle_timeout: 20,
connect_timeout: 10
connect_timeout: 10,
});
export const db = drizzle(client, { schema: { files } });
export { files };
export default db;
export default db;
+4 -4
View File
@@ -1,5 +1,5 @@
import { pgTable, text, bigint, timestamp, uuid } from 'drizzle-orm/pg-core';
import type { InferSelectModel, InferInsertModel } from 'drizzle-orm';
import type { InferInsertModel, InferSelectModel } from 'drizzle-orm';
import { bigint, pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core';
export const files = pgTable('files', {
id: uuid('id').primaryKey().defaultRandom(),
@@ -14,8 +14,8 @@ export const files = pgTable('files', {
fileType: text('file_type').notNull(),
uploaderId: bigint('uploader_id', { mode: 'number' }).notNull(),
createdAt: timestamp('created_at').defaultNow().notNull(),
updatedAt: timestamp('updated_at').defaultNow().notNull()
updatedAt: timestamp('updated_at').defaultNow().notNull(),
});
export type File = InferSelectModel<typeof files>;
export type NewFile = InferInsertModel<typeof files>;
export type NewFile = InferInsertModel<typeof files>;
+5 -3
View File
@@ -17,7 +17,7 @@ const requiredEnv = {
STORAGE_CHANNEL_ID: process.env.STORAGE_CHANNEL_ID,
BASE_URL: process.env.BASE_URL,
DATABASE_URL: process.env.DATABASE_URL,
PORT: process.env.PORT
PORT: process.env.PORT,
};
const missing = Object.entries(requiredEnv)
@@ -38,7 +38,9 @@ export const config: AppConfig = {
nodeEnv: process.env.NODE_ENV || 'development',
logLevel: process.env.LOG_LEVEL || 'info',
rateLimitWindowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS!, 10) || 60000,
rateLimitMaxRequests: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS!, 10) || 30
rateLimitMaxRequests: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS!, 10) || 30,
};
logger.info('Environment variables loaded', { config: { ...config, botToken: config.botToken?.substring(0, 10) + '...' } });
logger.info('Environment variables loaded', {
config: { ...config, botToken: `${config.botToken?.substring(0, 10)}...` },
});
+10 -10
View File
@@ -1,28 +1,28 @@
import { serve } from 'bun';
import logger from './utils/logger';
import { config } from './env';
import { startBot } from './bot';
import { handleUpload } from './routes/upload';
import { handleFileRedirect, handleFileInfo } from './routes/files';
import { config } from './env';
import { handleFileInfo, handleFileRedirect } from './routes/files';
import { handleHealth } from './routes/health';
import { handleUpload } from './routes/upload';
import logger from './utils/logger';
import { cleanupRateLimitCache } from './utils/rateLimit';
const server = serve({
port: config.port,
routes: {
'/api/upload': {
POST: handleUpload
POST: handleUpload,
},
'/f/:public_id': {
GET: handleFileRedirect
GET: handleFileRedirect,
},
'/file/:public_id/info': {
GET: handleFileInfo
GET: handleFileInfo,
},
'/health': {
GET: handleHealth
}
}
GET: handleHealth,
},
},
});
const bot = await startBot();
+30 -16
View File
@@ -1,7 +1,7 @@
import logger from '../utils/logger';
import { db, files as fileSchema } from '../db';
import { checkRateLimit } from '../utils/rateLimit';
import { eq } from 'drizzle-orm';
import { db, files as fileSchema } from '../db';
import logger from '../utils/logger';
import { checkRateLimit } from '../utils/rateLimit';
type RequestWithParams = Request & {
params?: {
@@ -18,7 +18,11 @@ export const handleFileRedirect = async (req: RequestWithParams): Promise<Respon
return Response.json({ error: 'Rate limit exceeded' }, { status: 429 });
}
const result = await db.select().from(fileSchema).where(eq(fileSchema.publicId, public_id)).limit(1);
const result = await db
.select()
.from(fileSchema)
.where(eq(fileSchema.publicId, public_id))
.limit(1);
if (!result.length) {
logger.warn('File not found', { public_id });
@@ -34,8 +38,8 @@ export const handleFileRedirect = async (req: RequestWithParams): Promise<Respon
return new Response(null, {
status: 302,
headers: {
'Location': redirectUrl
}
Location: redirectUrl,
},
});
} catch (error: any) {
logger.error('File redirect error', { public_id, error: error.message });
@@ -50,7 +54,11 @@ export const handleFileInfo = async (req: RequestWithParams): Promise<Response>
return Response.json({ error: 'Missing file id' }, { status: 400 });
}
const result = await db.select().from(fileSchema).where(eq(fileSchema.publicId, public_id)).limit(1);
const result = await db
.select()
.from(fileSchema)
.where(eq(fileSchema.publicId, public_id))
.limit(1);
if (!result.length) {
logger.warn('File not found', { public_id });
@@ -58,15 +66,21 @@ export const handleFileInfo = async (req: RequestWithParams): Promise<Response>
}
const file = result[0];
return Response.json({
public_id: file.publicId,
file_name: file.fileName,
mime_type: file.mimeType,
size_bytes: file.sizeBytes,
file_type: file.fileType,
uploader_id: file.uploaderId,
created_at: typeof file.createdAt === 'string' ? file.createdAt : (file.createdAt as Date).toISOString()
}, { status: 200 });
return Response.json(
{
public_id: file.publicId,
file_name: file.fileName,
mime_type: file.mimeType,
size_bytes: file.sizeBytes,
file_type: file.fileType,
uploader_id: file.uploaderId,
created_at:
typeof file.createdAt === 'string'
? file.createdAt
: (file.createdAt as Date).toISOString(),
},
{ status: 200 },
);
} catch (error: any) {
logger.error('File info error', { public_id, error: error.message });
return Response.json({ error: 'Server error' }, { status: 500 });
+2 -2
View File
@@ -1,6 +1,6 @@
import logger from '../utils/logger';
import { db } from '../db';
import { sql } from 'drizzle-orm';
import { db } from '../db';
import logger from '../utils/logger';
export const handleHealth = async (_req: Request): Promise<Response> => {
try {
+24 -14
View File
@@ -1,9 +1,9 @@
import logger from '../utils/logger';
import { db, files as fileSchema } from '../db';
import { nanoid } from 'nanoid';
import { forwardToStorage, getBot } from '../utils/telegram';
import { getFileType, checkFileSize, extractMimeType } from '../utils/file';
import { db, files as fileSchema } from '../db';
import { config } from '../env';
import { checkFileSize, extractMimeType, getFileType } from '../utils/file';
import logger from '../utils/logger';
import { forwardToStorage, getBot } from '../utils/telegram';
export const handleUpload = async (req: Request): Promise<Response> => {
try {
@@ -17,7 +17,7 @@ export const handleUpload = async (req: Request): Promise<Response> => {
return Response.json(
{ error: 'Unsupported content type. Use multipart/form-data or application/json' },
{ status: 400 }
{ status: 400 },
);
} catch (error: any) {
logger.error('Upload error', { error: error.message });
@@ -29,7 +29,8 @@ const handleMultipartUpload = async (req: Request): Promise<Response> => {
try {
const formData = await req.formData();
const file = formData.get('file');
const fileName = (formData.get('fileName') as string) || (file instanceof File ? file.name : null) || 'file';
const fileName =
(formData.get('fileName') as string) || (file instanceof File ? file.name : null) || 'file';
if (!file || !(file instanceof File)) {
return Response.json({ error: 'No file provided' }, { status: 400 });
@@ -44,7 +45,10 @@ const handleMultipartUpload = async (req: Request): Promise<Response> => {
return Response.json({ error: `File size exceeds ${fileType} limit` }, { status: 400 });
}
const isDocument = fileName.endsWith('.pdf') || fileName.endsWith('.txt') || !['photo', 'video', 'audio', 'voice', 'animation'].includes(fileType);
const isDocument =
fileName.endsWith('.pdf') ||
fileName.endsWith('.txt') ||
!['photo', 'video', 'audio', 'voice', 'animation'].includes(fileType);
const result = await forwardToStorage(fileBuffer, fileName, isDocument);
const bot = getBot();
const fileInfo = (await bot.telegram.getFile(result.telegramFileId)) as any;
@@ -61,7 +65,7 @@ const handleMultipartUpload = async (req: Request): Promise<Response> => {
fileType: fileType,
uploaderId: 0,
createdAt: new Date(),
updatedAt: new Date()
updatedAt: new Date(),
};
await db.insert(fileSchema).values(uploaded);
@@ -78,7 +82,7 @@ const handleMultipartUpload = async (req: Request): Promise<Response> => {
file_type: uploaded.fileType,
uploader_id: uploaded.uploaderId,
created_at: uploaded.createdAt.toISOString(),
download_url: `${config.baseUrl}/f/${uploaded.publicId}`
download_url: `${config.baseUrl}/f/${uploaded.publicId}`,
};
return Response.json(responsePayload, { status: 200 });
@@ -95,19 +99,25 @@ const handleJSONUpload = async (req: Request): Promise<Response> => {
if (!file || typeof file !== 'string') {
return Response.json(
{ error: 'Invalid JSON. Must include "file" (base64) and optional "fileName"' },
{ status: 400 }
{ status: 400 },
);
}
const fileBytes = Buffer.from(file, 'base64');
const mimeType = 'application/octet-stream';
const fileType = getFileType(mimeType, fileName) === 'application' ? 'document' : getFileType(mimeType, fileName);
const fileType =
getFileType(mimeType, fileName) === 'application'
? 'document'
: getFileType(mimeType, fileName);
if (!checkFileSize(fileBytes.byteLength, fileType)) {
return Response.json({ error: `File size exceeds ${fileType} limit` }, { status: 400 });
}
const isDocument = fileName.endsWith('.pdf') || fileName.endsWith('.txt') || !['photo', 'video', 'audio', 'voice', 'animation'].includes(fileType);
const isDocument =
fileName.endsWith('.pdf') ||
fileName.endsWith('.txt') ||
!['photo', 'video', 'audio', 'voice', 'animation'].includes(fileType);
const result = await forwardToStorage(fileBytes, fileName, isDocument);
const bot = getBot();
const fileInfo = (await bot.telegram.getFile(result.telegramFileId)) as any;
@@ -124,7 +134,7 @@ const handleJSONUpload = async (req: Request): Promise<Response> => {
fileType: fileType,
uploaderId: 0,
createdAt: new Date(),
updatedAt: new Date()
updatedAt: new Date(),
};
await db.insert(fileSchema).values(uploaded);
@@ -141,7 +151,7 @@ const handleJSONUpload = async (req: Request): Promise<Response> => {
file_type: uploaded.fileType,
uploader_id: uploaded.uploaderId,
created_at: uploaded.createdAt.toISOString(),
download_url: `${config.baseUrl}/f/${uploaded.publicId}`
download_url: `${config.baseUrl}/f/${uploaded.publicId}`,
};
return Response.json(responsePayload, { status: 200 });
+17 -5
View File
@@ -4,7 +4,7 @@ const FILE_TYPES: Record<string, number> = {
video: 2 * 1024 * 1024 * 1024, // 2GB
audio: 200 * 1024 * 1024, // 200MB
voice: 200 * 1024 * 1024, // 200MB
animation: 2 * 1024 * 1024 * 1024 // 2GB
animation: 2 * 1024 * 1024 * 1024, // 2GB
};
export const getFileType = (mime: string | null, caption?: string): string => {
@@ -30,14 +30,26 @@ export const extractFileName = (msg: any, request: any): string => {
if (request?.headers?.['x-file-name']) {
return request.headers['x-file-name'];
}
return msg.document?.fileName || msg.photo?.slice(-1)[0]?.fileName || msg.audio?.fileName ||
msg.voice?.fileName || msg.animation?.fileName || 'file';
return (
msg.document?.fileName ||
msg.photo?.slice(-1)[0]?.fileName ||
msg.audio?.fileName ||
msg.voice?.fileName ||
msg.animation?.fileName ||
'file'
);
};
export const extractMimeType = (msg: any, request: any): string => {
if (request?.headers?.['x-mime-type']) {
return request.headers['x-mime-type'];
}
return msg.document?.mimeType || msg.photo?.slice(-1)[0]?.mimeType || msg.audio?.mimeType ||
msg.voice?.mimeType || msg.animation?.mimeType || 'application/octet-stream';
return (
msg.document?.mimeType ||
msg.photo?.slice(-1)[0]?.mimeType ||
msg.audio?.mimeType ||
msg.voice?.mimeType ||
msg.animation?.mimeType ||
'application/octet-stream'
);
};
+8 -9
View File
@@ -5,24 +5,23 @@ const logger = winston.createLogger({
format: winston.format.combine(
winston.format.timestamp(),
winston.format.errors({ stack: true }),
winston.format.json()
winston.format.json(),
),
defaultMeta: { service: 'teleuploader' },
transports: [
// Write all logs including error logs to file
new winston.transports.File({ filename: 'logs/error.log', level: 'error' }),
new winston.transports.File({ filename: 'logs/combined.log' })
]
new winston.transports.File({ filename: 'logs/combined.log' }),
],
});
// If not production, also log to console
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.combine(
winston.format.colorize(),
winston.format.simple()
)
}));
logger.add(
new winston.transports.Console({
format: winston.format.combine(winston.format.colorize(), winston.format.simple()),
}),
);
}
export default logger;
+9 -7
View File
@@ -1,6 +1,6 @@
import { Telegraf } from 'telegraf';
import logger from './logger';
import { config } from '../env';
import logger from './logger';
const bot = new Telegraf(config.botToken);
const TELEGRAM_API_URL = `https://api.telegram.org/bot${config.botToken}/`;
@@ -20,11 +20,13 @@ interface TelegramFileInfo {
export const forwardToStorage = async (
fileChunk: any,
fileName: string,
forceDocument = false
forceDocument = false,
): Promise<ForwardResult> => {
try {
const caption = forceDocument ? `📁 ${fileName}` : fileName;
const input: any = forceDocument ? { document: fileChunk, caption } : { photo: [fileChunk], caption };
const input: any = forceDocument
? { document: fileChunk, caption }
: { photo: [fileChunk], caption };
const result = await bot.telegram.sendPhoto(config.storageChatId, input);
@@ -33,7 +35,7 @@ export const forwardToStorage = async (
return {
telegramFileId: result.photo?.slice(-1)[0]?.file_id || '',
telegramFileUniqueId: result.photo?.slice(-1)[0]?.file_unique_id || '',
storageMessageId: result.message_id
storageMessageId: result.message_id,
};
} catch (error: any) {
logger.error('Failed to forward file to storage', { fileName, error: error.message });
@@ -43,7 +45,7 @@ export const forwardToStorage = async (
export const getFileInfo = async (
telegramFileId: string,
telegramFileUniqueId: string
telegramFileUniqueId: string,
): Promise<TelegramFileInfo> => {
try {
const result = await fetch(`${TELEGRAM_API_URL}getFile`);
@@ -57,7 +59,7 @@ export const getFileInfo = async (
const fileResult = await fetch(`${TELEGRAM_API_URL}getInfo`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ file_id: fileId })
body: JSON.stringify({ file_id: fileId }),
});
const fileInfo: any = await fileResult.json();
@@ -68,7 +70,7 @@ export const getFileInfo = async (
return {
file_size: fileInfo.result.file_size,
mime_type: fileInfo.result.mime_type,
file_path: fileInfo.result.file_path
file_path: fileInfo.result.file_path,
};
} catch (error: any) {
logger.error('Failed to get file info', { error: error.message });