font.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. import cliProgress from 'cli-progress';
  7. export async function saveAllFount(epub, uploadPath, book_id, author_id) {
  8. dirExists(uploadPath);
  9. dirExists(`${uploadPath}font/`);
  10. // 获取原始数据源
  11. const getAllCss = epub.zip.names.filter((elm) => elm.includes("ttf"));
  12. const base_path = `${uploadPath}epub-extract/`;
  13. if (getAllCss.length) {
  14. const cssRes = await Promise.allSettled(
  15. getAllCss.map((img) => {
  16. return fs.promises.readFile(base_path + img, "utf8");
  17. })
  18. );
  19. const allCss_fulfilled = cssRes
  20. .map((img_fulfilled, index) => {
  21. const cssPath = getAllCss[index];
  22. if (img_fulfilled.status === "fulfilled") {
  23. return {
  24. index,
  25. path: base_path + cssPath,
  26. cssPath,
  27. css_data: img_fulfilled.value,
  28. mimeType: "font/ttf",
  29. };
  30. }
  31. return null;
  32. })
  33. .filter(Boolean);
  34. // Initialize the progress bar
  35. const progressBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);
  36. progressBar.start(allCss_fulfilled.length, 0);
  37. await Promise.allSettled(
  38. allCss_fulfilled.map(async (elm, index) => {
  39. try {
  40. const md5 = await calculateMD5(elm.path);
  41. const elmName = elm.cssPath.split('/').pop();
  42. // Write the font data to a file
  43. await fs.promises.writeFile(`${uploadPath}font/${md5}.ttf`, elm.css_data);
  44. logger.info("Font data saved to " + md5);
  45. const params = {
  46. file_id: md5,
  47. md5: md5,
  48. mimetype: elm.mimeType,
  49. size: elm.css_data.length,
  50. name: elmName,
  51. path: `${uploadPath}font/${md5}.ttf`,
  52. source_id: md5,
  53. };
  54. await files_insert(params);
  55. await files_insert_link_epub({
  56. file_id: md5,
  57. book_id,
  58. author_id,
  59. });
  60. // Update the progress bar
  61. progressBar.update(index + 1);
  62. } catch (err) {
  63. logger.error("Error processing font:", err);
  64. }
  65. })
  66. );
  67. // Update the progress bar
  68. progressBar.update(allCss_fulfilled.length);
  69. // Stop the progress bar
  70. progressBar.stop();
  71. }
  72. }