188 lines
5.3 KiB
TypeScript
188 lines
5.3 KiB
TypeScript
import { Injectable, BadRequestException } from "@nestjs/common";
|
|
import { PrismaService } from "../prisma/prisma.service";
|
|
import * as path from "path";
|
|
import * as fs from "fs";
|
|
|
|
@Injectable()
|
|
export class MediaService {
|
|
constructor(private prisma: PrismaService) {}
|
|
|
|
async getAllMedia() {
|
|
const items = await this.prisma.media.findMany({
|
|
orderBy: { createdAt: "desc" },
|
|
});
|
|
|
|
const seenUrls = new Set<string>();
|
|
const deduplicated = [];
|
|
|
|
for (const item of items) {
|
|
const normalizedUrl = (item.url || "").trim().toLowerCase();
|
|
if (normalizedUrl && seenUrls.has(normalizedUrl)) {
|
|
continue;
|
|
}
|
|
if (normalizedUrl) {
|
|
seenUrls.add(normalizedUrl);
|
|
}
|
|
|
|
let cleanFilename = item.filename;
|
|
// Check if filename contains common mojibake patterns from latin1 decoding
|
|
if (cleanFilename && /[ØÙÚÛ]/.test(cleanFilename)) {
|
|
try {
|
|
const decoded = Buffer.from(cleanFilename, "latin1").toString("utf8");
|
|
if (decoded && !decoded.includes("")) {
|
|
cleanFilename = decoded;
|
|
}
|
|
} catch {
|
|
// Keep original if decoding fails
|
|
}
|
|
}
|
|
|
|
deduplicated.push({
|
|
...item,
|
|
filename: cleanFilename,
|
|
});
|
|
}
|
|
|
|
return deduplicated;
|
|
}
|
|
|
|
async uploadFile(file: Express.Multer.File) {
|
|
if (!file) {
|
|
throw new BadRequestException("No file uploaded");
|
|
}
|
|
|
|
const uploadDir = path.join(process.cwd(), "uploads");
|
|
if (!fs.existsSync(uploadDir)) {
|
|
fs.mkdirSync(uploadDir, { recursive: true });
|
|
}
|
|
|
|
// Fix Multer/Busboy ISO-8859-1 (latin1) to UTF-8 filename encoding for Persian/Arabic/Unicode characters
|
|
let originalname = file.originalname;
|
|
try {
|
|
originalname = Buffer.from(file.originalname, "latin1").toString("utf8");
|
|
} catch {
|
|
originalname = file.originalname;
|
|
}
|
|
|
|
const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
|
|
const ext = path.extname(originalname).toLowerCase();
|
|
const ALLOWED_EXTENSIONS = [
|
|
".jpg",
|
|
".jpeg",
|
|
".png",
|
|
".webp",
|
|
".gif",
|
|
".pdf",
|
|
];
|
|
if (!ALLOWED_EXTENSIONS.includes(ext)) {
|
|
throw new BadRequestException(
|
|
"پسوند فایل ارسالی مجاز نیست (فرمت SVG و فایلهای اجرایی مسدود هستند).",
|
|
);
|
|
}
|
|
|
|
// SEC-01: Magic number verification for uploaded binary content
|
|
const buf = file.buffer;
|
|
if (!buf || buf.length < 4) {
|
|
throw new BadRequestException("فایل نامعتبر یا آسیبدیده است.");
|
|
}
|
|
|
|
const isJpeg = buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff;
|
|
const isPng = buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47;
|
|
const isGif = buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46; // GIF87a or GIF89a
|
|
const isPdf = buf[0] === 0x25 && buf[1] === 0x50 && buf[2] === 0x44 && buf[3] === 0x46; // %PDF
|
|
const isWebp =
|
|
buf.length >= 12 &&
|
|
buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 && // RIFF
|
|
buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50; // WEBP
|
|
|
|
if (!isJpeg && !isPng && !isGif && !isPdf && !isWebp) {
|
|
throw new BadRequestException(
|
|
"محتوای باینری فایل با پسوند یا هدر ادعایی همخوانی ندارد (اعتبارسنجی امضای فایل رد شد).",
|
|
);
|
|
}
|
|
|
|
const filename = `${uniqueSuffix}${ext}`;
|
|
const filePath = path.join(uploadDir, filename);
|
|
|
|
fs.writeFileSync(filePath, file.buffer);
|
|
|
|
// Assuming we serve static files from '/uploads' route prefix
|
|
const url = `/uploads/${filename}`;
|
|
|
|
const media = await this.prisma.media.create({
|
|
data: {
|
|
filename: originalname,
|
|
url,
|
|
mimetype: file.mimetype,
|
|
size: file.size,
|
|
},
|
|
});
|
|
|
|
return media;
|
|
}
|
|
|
|
async deleteMedia(id: string) {
|
|
const media = await this.prisma.media.findUnique({ where: { id } });
|
|
if (!media) throw new BadRequestException("Media not found");
|
|
|
|
const filePath = path.join(
|
|
process.cwd(),
|
|
"uploads",
|
|
path.basename(media.url),
|
|
);
|
|
if (fs.existsSync(filePath)) {
|
|
fs.unlinkSync(filePath);
|
|
}
|
|
|
|
await this.prisma.media.delete({ where: { id } });
|
|
return { success: true };
|
|
}
|
|
|
|
async deleteManyMedia(ids: string[]) {
|
|
const mediaItems = await this.prisma.media.findMany({
|
|
where: { id: { in: ids } },
|
|
});
|
|
|
|
for (const media of mediaItems) {
|
|
const filePath = path.join(
|
|
process.cwd(),
|
|
"uploads",
|
|
path.basename(media.url),
|
|
);
|
|
if (fs.existsSync(filePath)) {
|
|
try {
|
|
fs.unlinkSync(filePath);
|
|
} catch {
|
|
// Ignore individual unlink errors
|
|
}
|
|
}
|
|
}
|
|
|
|
await this.prisma.media.deleteMany({
|
|
where: { id: { in: ids } },
|
|
});
|
|
|
|
return { success: true, count: mediaItems.length };
|
|
}
|
|
|
|
async updateMedia(
|
|
id: string,
|
|
data: {
|
|
altText?: string;
|
|
title?: string;
|
|
description?: string;
|
|
caption?: string;
|
|
},
|
|
) {
|
|
return this.prisma.media.update({
|
|
where: { id },
|
|
data: {
|
|
altText: data.altText,
|
|
title: data.title,
|
|
description: data.description,
|
|
caption: data.caption,
|
|
},
|
|
});
|
|
}
|
|
}
|