2026-05-18 19:39:55 +07:00
|
|
|
import { eq } from 'drizzle-orm';
|
2026-05-18 07:08:13 +07:00
|
|
|
import { nanoid } from 'nanoid';
|
2026-05-18 07:29:01 +07:00
|
|
|
import { db, files as fileSchema } from '../db';
|
2026-05-18 07:27:06 +07:00
|
|
|
import { config } from '../env';
|
2026-05-18 19:41:51 +07:00
|
|
|
import {
|
|
|
|
|
checkFileSize,
|
|
|
|
|
computeHash,
|
|
|
|
|
ensureExtension,
|
|
|
|
|
extractMimeType,
|
|
|
|
|
getFileType,
|
|
|
|
|
} from '../utils/file';
|
2026-05-18 07:29:01 +07:00
|
|
|
import logger from '../utils/logger';
|
|
|
|
|
import { forwardToStorage, getBot } from '../utils/telegram';
|
2026-05-18 07:08:13 +07:00
|
|
|
|
2026-05-18 07:27:06 +07:00
|
|
|
export const handleUpload = async (req: Request): Promise<Response> => {
|
2026-05-18 07:08:13 +07:00
|
|
|
try {
|
|
|
|
|
const contentType = req.headers.get('content-type') || '';
|
|
|
|
|
|
|
|
|
|
if (contentType.includes('multipart/form-data')) {
|
|
|
|
|
return handleMultipartUpload(req);
|
|
|
|
|
} else if (contentType.includes('application/json')) {
|
|
|
|
|
return handleJSONUpload(req);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return Response.json(
|
|
|
|
|
{ error: 'Unsupported content type. Use multipart/form-data or application/json' },
|
2026-05-18 07:29:01 +07:00
|
|
|
{ status: 400 },
|
2026-05-18 07:08:13 +07:00
|
|
|
);
|
2026-05-18 07:27:06 +07:00
|
|
|
} catch (error: any) {
|
2026-05-18 07:08:13 +07:00
|
|
|
logger.error('Upload error', { error: error.message });
|
|
|
|
|
return Response.json({ error: error.message }, { status: 500 });
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2026-05-18 07:27:06 +07:00
|
|
|
const handleMultipartUpload = async (req: Request): Promise<Response> => {
|
2026-05-18 07:08:13 +07:00
|
|
|
try {
|
|
|
|
|
const formData = await req.formData();
|
|
|
|
|
const file = formData.get('file');
|
2026-05-18 07:29:01 +07:00
|
|
|
const fileName =
|
|
|
|
|
(formData.get('fileName') as string) || (file instanceof File ? file.name : null) || 'file';
|
2026-05-18 07:08:13 +07:00
|
|
|
|
|
|
|
|
if (!file || !(file instanceof File)) {
|
|
|
|
|
return Response.json({ error: 'No file provided' }, { status: 400 });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const fileBytes = await file.arrayBuffer();
|
|
|
|
|
const fileBuffer = Buffer.from(fileBytes);
|
2026-05-18 19:39:55 +07:00
|
|
|
const hash = computeHash(fileBuffer);
|
|
|
|
|
|
|
|
|
|
// Check for duplicate in DB
|
|
|
|
|
const existing = await db
|
|
|
|
|
.select()
|
|
|
|
|
.from(fileSchema)
|
|
|
|
|
.where(eq(fileSchema.fileHash, hash))
|
|
|
|
|
.limit(1);
|
|
|
|
|
|
|
|
|
|
if (existing.length > 0) {
|
|
|
|
|
const existingFile = existing[0];
|
|
|
|
|
const responsePayload = {
|
|
|
|
|
public_id: existingFile.publicId,
|
|
|
|
|
telegram_file_id: existingFile.telegramFileId,
|
|
|
|
|
telegram_file_unique_id: existingFile.telegramFileUniqueId,
|
|
|
|
|
storage_chat_id: existingFile.storageChatId,
|
|
|
|
|
storage_message_id: existingFile.storageMessageId,
|
|
|
|
|
file_name: existingFile.fileName,
|
|
|
|
|
mime_type: existingFile.mimeType,
|
|
|
|
|
size_bytes: existingFile.sizeBytes,
|
|
|
|
|
file_type: existingFile.fileType,
|
|
|
|
|
uploader_id: existingFile.uploaderId,
|
2026-05-18 19:41:51 +07:00
|
|
|
created_at:
|
|
|
|
|
existingFile.createdAt instanceof Date
|
|
|
|
|
? existingFile.createdAt.toISOString()
|
|
|
|
|
: new Date(existingFile.createdAt).toISOString(),
|
2026-05-18 19:39:55 +07:00
|
|
|
download_url: `${config.baseUrl}/f/${existingFile.publicId}`,
|
|
|
|
|
};
|
|
|
|
|
return Response.json(responsePayload, { status: 200 });
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-18 09:20:03 +07:00
|
|
|
const rawMimeType = file.type || extractMimeType({}, req) || 'application/octet-stream';
|
|
|
|
|
const { fileName: finalFileName, mimeType } = ensureExtension(
|
|
|
|
|
fileName,
|
|
|
|
|
fileBuffer,
|
|
|
|
|
rawMimeType,
|
|
|
|
|
);
|
|
|
|
|
const fileType = getFileType(mimeType, finalFileName);
|
2026-05-18 07:08:13 +07:00
|
|
|
|
|
|
|
|
if (!checkFileSize(fileBuffer.byteLength, fileType)) {
|
|
|
|
|
return Response.json({ error: `File size exceeds ${fileType} limit` }, { status: 400 });
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-18 07:29:01 +07:00
|
|
|
const isDocument =
|
2026-05-18 09:20:03 +07:00
|
|
|
finalFileName.endsWith('.pdf') ||
|
|
|
|
|
finalFileName.endsWith('.txt') ||
|
2026-05-18 07:29:01 +07:00
|
|
|
!['photo', 'video', 'audio', 'voice', 'animation'].includes(fileType);
|
2026-05-18 09:20:03 +07:00
|
|
|
const result = await forwardToStorage(fileBuffer, finalFileName, isDocument);
|
2026-05-18 07:08:13 +07:00
|
|
|
const bot = getBot();
|
2026-05-18 07:27:06 +07:00
|
|
|
const fileInfo = (await bot.telegram.getFile(result.telegramFileId)) as any;
|
2026-05-18 07:08:13 +07:00
|
|
|
|
|
|
|
|
const uploaded = {
|
|
|
|
|
publicId: nanoid(),
|
|
|
|
|
telegramFileId: result.telegramFileId,
|
|
|
|
|
telegramFileUniqueId: result.telegramFileUniqueId,
|
|
|
|
|
storageChatId: config.storageChatId,
|
|
|
|
|
storageMessageId: result.storageMessageId,
|
2026-05-18 09:20:03 +07:00
|
|
|
fileName: finalFileName,
|
2026-05-18 07:08:13 +07:00
|
|
|
mimeType: fileInfo.mime_type || mimeType || 'application/octet-stream',
|
|
|
|
|
sizeBytes: fileInfo.file_size || fileBuffer.byteLength,
|
|
|
|
|
fileType: fileType,
|
|
|
|
|
uploaderId: 0,
|
2026-05-18 19:39:55 +07:00
|
|
|
fileHash: hash,
|
2026-05-18 07:08:13 +07:00
|
|
|
createdAt: new Date(),
|
2026-05-18 07:29:01 +07:00
|
|
|
updatedAt: new Date(),
|
2026-05-18 07:08:13 +07:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
await db.insert(fileSchema).values(uploaded);
|
|
|
|
|
|
|
|
|
|
const responsePayload = {
|
|
|
|
|
public_id: uploaded.publicId,
|
|
|
|
|
telegram_file_id: uploaded.telegramFileId,
|
|
|
|
|
telegram_file_unique_id: uploaded.telegramFileUniqueId,
|
|
|
|
|
storage_chat_id: uploaded.storageChatId,
|
|
|
|
|
storage_message_id: uploaded.storageMessageId,
|
|
|
|
|
file_name: uploaded.fileName,
|
|
|
|
|
mime_type: uploaded.mimeType,
|
|
|
|
|
size_bytes: uploaded.sizeBytes,
|
|
|
|
|
file_type: uploaded.fileType,
|
|
|
|
|
uploader_id: uploaded.uploaderId,
|
|
|
|
|
created_at: uploaded.createdAt.toISOString(),
|
2026-05-18 07:29:01 +07:00
|
|
|
download_url: `${config.baseUrl}/f/${uploaded.publicId}`,
|
2026-05-18 07:08:13 +07:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return Response.json(responsePayload, { status: 200 });
|
2026-05-18 07:27:06 +07:00
|
|
|
} catch (error: any) {
|
2026-05-18 07:08:13 +07:00
|
|
|
logger.error('Multipart upload error', { error: error.message });
|
|
|
|
|
return Response.json({ error: error.message }, { status: 500 });
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2026-05-18 07:27:06 +07:00
|
|
|
const handleJSONUpload = async (req: Request): Promise<Response> => {
|
2026-05-18 07:08:13 +07:00
|
|
|
try {
|
2026-05-18 07:27:06 +07:00
|
|
|
const { file, fileName = 'file' } = (await req.json()) as any;
|
2026-05-18 07:08:13 +07:00
|
|
|
|
|
|
|
|
if (!file || typeof file !== 'string') {
|
|
|
|
|
return Response.json(
|
|
|
|
|
{ error: 'Invalid JSON. Must include "file" (base64) and optional "fileName"' },
|
2026-05-18 07:29:01 +07:00
|
|
|
{ status: 400 },
|
2026-05-18 07:08:13 +07:00
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-18 09:20:03 +07:00
|
|
|
let base64Data = file;
|
|
|
|
|
let rawMimeType = 'application/octet-stream';
|
|
|
|
|
if (file.startsWith('data:')) {
|
|
|
|
|
const match = file.match(/^data:([^;]+);base64,(.+)$/);
|
|
|
|
|
if (match) {
|
|
|
|
|
rawMimeType = match[1];
|
|
|
|
|
base64Data = match[2];
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const fileBytes = Buffer.from(base64Data, 'base64');
|
2026-05-18 19:39:55 +07:00
|
|
|
const hash = computeHash(fileBytes);
|
|
|
|
|
|
|
|
|
|
// Check for duplicate in DB
|
|
|
|
|
const existing = await db
|
|
|
|
|
.select()
|
|
|
|
|
.from(fileSchema)
|
|
|
|
|
.where(eq(fileSchema.fileHash, hash))
|
|
|
|
|
.limit(1);
|
|
|
|
|
|
|
|
|
|
if (existing.length > 0) {
|
|
|
|
|
const existingFile = existing[0];
|
|
|
|
|
const responsePayload = {
|
|
|
|
|
public_id: existingFile.publicId,
|
|
|
|
|
telegram_file_id: existingFile.telegramFileId,
|
|
|
|
|
telegram_file_unique_id: existingFile.telegramFileUniqueId,
|
|
|
|
|
storage_chat_id: existingFile.storageChatId,
|
|
|
|
|
storage_message_id: existingFile.storageMessageId,
|
|
|
|
|
file_name: existingFile.fileName,
|
|
|
|
|
mime_type: existingFile.mimeType,
|
|
|
|
|
size_bytes: existingFile.sizeBytes,
|
|
|
|
|
file_type: existingFile.fileType,
|
|
|
|
|
uploader_id: existingFile.uploaderId,
|
2026-05-18 19:41:51 +07:00
|
|
|
created_at:
|
|
|
|
|
existingFile.createdAt instanceof Date
|
|
|
|
|
? existingFile.createdAt.toISOString()
|
|
|
|
|
: new Date(existingFile.createdAt).toISOString(),
|
2026-05-18 19:39:55 +07:00
|
|
|
download_url: `${config.baseUrl}/f/${existingFile.publicId}`,
|
|
|
|
|
};
|
|
|
|
|
return Response.json(responsePayload, { status: 200 });
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-18 09:20:03 +07:00
|
|
|
const { fileName: finalFileName, mimeType } = ensureExtension(fileName, fileBytes, rawMimeType);
|
2026-05-18 07:29:01 +07:00
|
|
|
const fileType =
|
2026-05-18 09:20:03 +07:00
|
|
|
getFileType(mimeType, finalFileName) === 'application'
|
2026-05-18 07:29:01 +07:00
|
|
|
? 'document'
|
2026-05-18 09:20:03 +07:00
|
|
|
: getFileType(mimeType, finalFileName);
|
2026-05-18 07:08:13 +07:00
|
|
|
|
|
|
|
|
if (!checkFileSize(fileBytes.byteLength, fileType)) {
|
|
|
|
|
return Response.json({ error: `File size exceeds ${fileType} limit` }, { status: 400 });
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-18 07:29:01 +07:00
|
|
|
const isDocument =
|
2026-05-18 09:20:03 +07:00
|
|
|
finalFileName.endsWith('.pdf') ||
|
|
|
|
|
finalFileName.endsWith('.txt') ||
|
2026-05-18 07:29:01 +07:00
|
|
|
!['photo', 'video', 'audio', 'voice', 'animation'].includes(fileType);
|
2026-05-18 09:20:03 +07:00
|
|
|
const result = await forwardToStorage(fileBytes, finalFileName, isDocument);
|
2026-05-18 07:08:13 +07:00
|
|
|
const bot = getBot();
|
2026-05-18 07:27:06 +07:00
|
|
|
const fileInfo = (await bot.telegram.getFile(result.telegramFileId)) as any;
|
2026-05-18 07:08:13 +07:00
|
|
|
|
|
|
|
|
const uploaded = {
|
|
|
|
|
publicId: nanoid(),
|
|
|
|
|
telegramFileId: result.telegramFileId,
|
|
|
|
|
telegramFileUniqueId: result.telegramFileUniqueId,
|
|
|
|
|
storageChatId: config.storageChatId,
|
|
|
|
|
storageMessageId: result.storageMessageId,
|
2026-05-18 09:20:03 +07:00
|
|
|
fileName: finalFileName,
|
2026-05-18 07:08:13 +07:00
|
|
|
mimeType: fileInfo.mime_type || mimeType || 'application/octet-stream',
|
|
|
|
|
sizeBytes: fileInfo.file_size || fileBytes.byteLength,
|
|
|
|
|
fileType: fileType,
|
|
|
|
|
uploaderId: 0,
|
2026-05-18 19:39:55 +07:00
|
|
|
fileHash: hash,
|
2026-05-18 07:08:13 +07:00
|
|
|
createdAt: new Date(),
|
2026-05-18 07:29:01 +07:00
|
|
|
updatedAt: new Date(),
|
2026-05-18 07:08:13 +07:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
await db.insert(fileSchema).values(uploaded);
|
|
|
|
|
|
|
|
|
|
const responsePayload = {
|
|
|
|
|
public_id: uploaded.publicId,
|
|
|
|
|
telegram_file_id: uploaded.telegramFileId,
|
|
|
|
|
telegram_file_unique_id: uploaded.telegramFileUniqueId,
|
|
|
|
|
storage_chat_id: uploaded.storageChatId,
|
|
|
|
|
storage_message_id: uploaded.storageMessageId,
|
|
|
|
|
file_name: uploaded.fileName,
|
|
|
|
|
mime_type: uploaded.mimeType,
|
|
|
|
|
size_bytes: uploaded.sizeBytes,
|
|
|
|
|
file_type: uploaded.fileType,
|
|
|
|
|
uploader_id: uploaded.uploaderId,
|
|
|
|
|
created_at: uploaded.createdAt.toISOString(),
|
2026-05-18 07:29:01 +07:00
|
|
|
download_url: `${config.baseUrl}/f/${uploaded.publicId}`,
|
2026-05-18 07:08:13 +07:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return Response.json(responsePayload, { status: 200 });
|
2026-05-18 07:27:06 +07:00
|
|
|
} catch (error: any) {
|
2026-05-18 07:08:13 +07:00
|
|
|
logger.error('JSON upload error', { error: error.message });
|
|
|
|
|
return Response.json({ error: error.message }, { status: 500 });
|
|
|
|
|
}
|
|
|
|
|
};
|