@droppii-org/chat-sdk
Version:
Droppii React Chat SDK
85 lines (84 loc) • 3.19 kB
JavaScript
import { message as antdMessage } from "antd";
export const ACCEPTED_IMAGE_TYPES = ["image/jpeg", "image/png", "image/jpg"];
export const MAX_IMAGE_SIZE_MB = 5;
export const MAX_VIDEO_SIZE_MB = 200;
/**
* Validates a single file for type and size
*/
export const validateFile = (file, t) => {
const isImage = ACCEPTED_IMAGE_TYPES.includes(file.type);
const isVideo = file.type.startsWith("video/");
if (!isImage && !isVideo) {
const error = t("invalid_file_format", {
defaultValue: `${file.name} không đúng định dạng JPG, JPEG, PNG hoặc VIDEO`,
fileName: file.name,
});
return { isValid: false, error };
}
const maxSize = isVideo ? MAX_VIDEO_SIZE_MB : MAX_IMAGE_SIZE_MB;
const fileSizeMB = file.size / 1024 / 1024;
if (fileSizeMB > maxSize) {
const error = t("file_size_exceeded", {
defaultValue: `${file.name} có kích thước tập tin vượt quá ${maxSize}MB`,
fileName: file.name,
maxSize,
});
return { isValid: false, error };
}
return { isValid: true };
};
/**
* Validates video count limit (max 1 video)
*/
export const validateVideoLimit = (newFiles, currentUploadedFiles, t) => {
const newVideos = newFiles.filter((f) => f.type.startsWith("video/"));
const currentVideos = currentUploadedFiles.filter((f) => { var _a; return (_a = f.type) === null || _a === void 0 ? void 0 : _a.startsWith("video/"); });
if (newVideos.length > 1 || currentVideos.length + newVideos.length > 1) {
const error = t("video_limit_exceeded", {
defaultValue: "Chỉ được phép tải lên 1 video duy nhất",
});
return { isValid: false, error };
}
return { isValid: true };
};
/**
* Process and validate multiple files, converting to UploadFile format
*/
export const processAndValidateFiles = (files, options) => {
const { t, currentUploadedFiles = [] } = options;
try {
const validFiles = [];
// Check video limit first
const videoLimitCheck = validateVideoLimit(files, currentUploadedFiles, t);
if (!videoLimitCheck.isValid) {
antdMessage.error(videoLimitCheck.error);
return [];
}
// Validate each file
files.forEach((file) => {
const validation = validateFile(file, t);
if (validation.isValid) {
const uploadFile = {
uid: `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`,
name: file.name,
status: "done",
type: file.type,
size: file.size,
originFileObj: file,
};
validFiles.push(uploadFile);
}
else {
antdMessage.error(validation.error);
}
});
return validFiles;
}
catch (error) {
console.error("Error processing files:", error);
antdMessage.error(t("file_processing_error", {
defaultValue: "Đã xảy ra lỗi khi xử lý tệp",
}));
return [];
}
};