138 lines
5.7 KiB
JavaScript
138 lines
5.7 KiB
JavaScript
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
};
|
|
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
};
|
|
var MediaService_1;
|
|
import { randomUUID } from "node:crypto";
|
|
import { BadRequestException, ConflictException, Injectable, Logger, NotFoundException, } from "@nestjs/common";
|
|
import { env } from "../config/env.js";
|
|
import { AuditService, RevalidateService } from "../common/common.module.js";
|
|
import { PrismaService } from "../prisma/prisma.service.js";
|
|
import { ACCEPTED_IMAGE_TYPES, S3Storage, toWebp } from "./s3-storage.js";
|
|
let MediaService = MediaService_1 = class MediaService {
|
|
prisma;
|
|
audit;
|
|
revalidate;
|
|
logger = new Logger(MediaService_1.name);
|
|
storage = new S3Storage();
|
|
constructor(prisma, audit, revalidate) {
|
|
this.prisma = prisma;
|
|
this.audit = audit;
|
|
this.revalidate = revalidate;
|
|
}
|
|
async onModuleInit() {
|
|
if (!env.S3_ENSURE_BUCKET)
|
|
return;
|
|
try {
|
|
await this.storage.ensureBucket();
|
|
}
|
|
catch (e) {
|
|
this.logger.error(`could not prepare bucket "${env.S3_BUCKET}": ${String(e)}`);
|
|
}
|
|
}
|
|
url(key) {
|
|
return this.storage.publicUrl(key);
|
|
}
|
|
toDto(m) {
|
|
return {
|
|
id: m.id,
|
|
url: this.url(m.key),
|
|
alt: m.alt,
|
|
mime: m.mime,
|
|
size: m.size,
|
|
width: m.width,
|
|
height: m.height,
|
|
originalName: m.originalName,
|
|
createdAt: m.createdAt.toISOString(),
|
|
};
|
|
}
|
|
async list(page, pageSize, q) {
|
|
const where = q
|
|
? {
|
|
OR: [
|
|
{ originalName: { contains: q, mode: "insensitive" } },
|
|
{ alt: { contains: q, mode: "insensitive" } },
|
|
],
|
|
}
|
|
: {};
|
|
const [items, total] = await this.prisma.$transaction([
|
|
this.prisma.media.findMany({
|
|
where,
|
|
orderBy: { id: "desc" },
|
|
skip: (page - 1) * pageSize,
|
|
take: pageSize,
|
|
}),
|
|
this.prisma.media.count({ where }),
|
|
]);
|
|
return { items: items.map((m) => this.toDto(m)), total, page, pageSize };
|
|
}
|
|
async upload(file, alt, userId) {
|
|
if (!file)
|
|
throw new BadRequestException("فایلی ارسال نشده است");
|
|
if (!ACCEPTED_IMAGE_TYPES.includes(file.mimetype)) {
|
|
throw new BadRequestException("فقط تصاویر JPG، PNG، WebP، AVIF و GIF پذیرفته میشوند");
|
|
}
|
|
let image;
|
|
try {
|
|
image = await toWebp(file.buffer);
|
|
}
|
|
catch {
|
|
throw new BadRequestException("فایل تصویر قابل پردازش نیست");
|
|
}
|
|
const now = new Date();
|
|
const month = String(now.getMonth() + 1).padStart(2, "0");
|
|
const key = `uploads/${now.getFullYear()}/${month}/${randomUUID()}.webp`;
|
|
await this.storage.put(key, image.data, "image/webp");
|
|
const media = await this.prisma.media.create({
|
|
data: {
|
|
key,
|
|
mime: "image/webp",
|
|
size: image.size,
|
|
width: image.width,
|
|
height: image.height,
|
|
alt: alt.trim().slice(0, 200),
|
|
originalName: Buffer.from(file.originalname, "latin1").toString("utf8").slice(0, 200),
|
|
},
|
|
});
|
|
this.audit.log(userId, "upload", "media", media.id, media.originalName);
|
|
return this.toDto(media);
|
|
}
|
|
async updateAlt(id, alt, userId) {
|
|
const media = await this.prisma.media.update({ where: { id }, data: { alt } });
|
|
this.audit.log(userId, "update", "media", id, media.originalName);
|
|
this.revalidate.trigger();
|
|
return this.toDto(media);
|
|
}
|
|
async remove(id, userId) {
|
|
const media = await this.prisma.media.findUnique({
|
|
where: { id },
|
|
include: { _count: { select: { categoryCovers: true, productImages: true, productGallery: true } } },
|
|
});
|
|
if (!media)
|
|
throw new NotFoundException("فایل پیدا نشد");
|
|
const { categoryCovers, productImages, productGallery } = media._count;
|
|
const sections = await this.prisma.$queryRaw `
|
|
SELECT key FROM "SiteSection" WHERE data::text LIKE ${"%" + media.key + "%"}`;
|
|
if (categoryCovers + productImages + productGallery + sections.length > 0) {
|
|
throw new ConflictException("این تصویر در محصولات، دستهها یا بخشهای سایت استفاده شده و قابل حذف نیست");
|
|
}
|
|
await this.prisma.media.delete({ where: { id } });
|
|
await this.storage.remove(media.key).catch((e) => {
|
|
this.logger.warn(`could not delete object ${media.key}: ${String(e)}`);
|
|
});
|
|
this.audit.log(userId, "delete", "media", id, media.originalName);
|
|
}
|
|
};
|
|
MediaService = MediaService_1 = __decorate([
|
|
Injectable(),
|
|
__metadata("design:paramtypes", [PrismaService,
|
|
AuditService,
|
|
RevalidateService])
|
|
], MediaService);
|
|
export { MediaService };
|
|
//# sourceMappingURL=media.service.js.map
|