import logger from "#logger"; import { files_insert, files_insert_link_epub } from "#db"; import { dirExists } from "#utils"; import fs from "node:fs"; import { calculateMD5 } from "./image.js"; // ./base_files/5ae2d9158081faab184484ed1783e176 export async function saveAllCSS(epub, uploadPath, book_id, author_id) { dirExists(uploadPath); dirExists(`${uploadPath}style/`); // 获取原始数据源 const getAllCss = epub.zip.names.filter((elm) => elm.indexOf("css") > -1); const base_path = `${uploadPath}epub-extract/`; if (getAllCss.length) { const cssRes = await Promise.allSettled( getAllCss.map((img) => { return fs.readFileSync(base_path + img, "utf8"); }) ); const allCss_fulfilled = cssRes .map((img, index) => { const img_fulfilled = cssRes[index]; const cssPath = getAllCss[index]; if (img_fulfilled.status === "fulfilled") { // const file_md5 = await calculateMD5(base_path + cssPath) return { ...img, ...img_fulfilled, index, path: base_path + cssPath, cssPath, // md5: file_md5, css_data: img_fulfilled.value, mimeType: "text/css", }; } return false; }) .filter((elm) => elm); await Promise.allSettled( allCss_fulfilled.map(async (elm) => { const md5 = await calculateMD5(elm.path); const [elmPath, elmName] = `${elm.path}`.match(/.*\/(.*\.css)/); // // 移动文件 // './base_files/5ae2d9158081faab184484ed1783e176/epub-extract/OEBPS/flow0001.css' // ./base_files/5ae2d9158081faab184484ed1783e176/style/flow0001.css // fs.writeFile(`${uploadPath}style/${md5}.css`, elm.css_data, (err) => { if (err) { logger.error("Error writing Img file:", err); } else { logger.info("Img data saved to " + md5); } }); const params = { file_id: md5, md5: md5, mimetype: elm.mimeType, size: elm.css_data.length, name: elmName, path: `${uploadPath}style/${md5}.css`, source_id: md5, }; await files_insert(params); return await files_insert_link_epub({ file_id: md5, book_id, author_id, }); }) ); } }