style.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import logger from "#logger";
  2. import { files_insert, files_insert_link_epub } from "#db";
  3. import { dirExists } from "#utils";
  4. import fs from "node:fs";
  5. import { calculateMD5 } from "./image.js";
  6. // ./base_files/5ae2d9158081faab184484ed1783e176
  7. export async function saveAllCSS(epub, uploadPath, book_id, author_id) {
  8. dirExists(uploadPath);
  9. dirExists(`${uploadPath}style/`);
  10. // 获取原始数据源
  11. const getAllCss = epub.zip.names.filter((elm) => elm.indexOf("css") > -1);
  12. const base_path = `${uploadPath}epub-extract/`;
  13. if (getAllCss.length) {
  14. const cssRes = await Promise.allSettled(
  15. getAllCss.map((img) => {
  16. return fs.readFileSync(base_path + img, "utf8");
  17. })
  18. );
  19. const allCss_fulfilled = cssRes
  20. .map((img, index) => {
  21. const img_fulfilled = cssRes[index];
  22. const cssPath = getAllCss[index];
  23. if (img_fulfilled.status === "fulfilled") {
  24. // const file_md5 = await calculateMD5(base_path + cssPath)
  25. return {
  26. ...img,
  27. ...img_fulfilled,
  28. index,
  29. path: base_path + cssPath,
  30. cssPath, // md5: file_md5,
  31. css_data: img_fulfilled.value,
  32. mimeType: "text/css",
  33. };
  34. }
  35. return false;
  36. })
  37. .filter((elm) => elm);
  38. await Promise.allSettled(
  39. allCss_fulfilled.map(async (elm) => {
  40. const md5 = await calculateMD5(elm.path);
  41. const [elmPath, elmName] = `${elm.path}`.match(/.*\/(.*\.css)/);
  42. //
  43. // 移动文件
  44. // './base_files/5ae2d9158081faab184484ed1783e176/epub-extract/OEBPS/flow0001.css'
  45. // ./base_files/5ae2d9158081faab184484ed1783e176/style/flow0001.css
  46. //
  47. fs.writeFile(`${uploadPath}style/${md5}.css`, elm.css_data, (err) => {
  48. if (err) {
  49. logger.error("Error writing Img file:", err);
  50. } else {
  51. logger.info("Img data saved to " + md5);
  52. }
  53. });
  54. const params = {
  55. file_id: md5,
  56. md5: md5,
  57. mimetype: elm.mimeType,
  58. size: elm.css_data.length,
  59. name: elmName,
  60. path: `${uploadPath}style/${md5}.css`,
  61. source_id: md5,
  62. };
  63. await files_insert(params);
  64. return await files_insert_link_epub({
  65. file_id: md5,
  66. book_id,
  67. author_id,
  68. });
  69. })
  70. );
  71. }
  72. }