Browse Source

font 优化

john 7 months ago
parent
commit
58e26e6b8a
3 changed files with 116 additions and 10 deletions
  1. 78 0
      epub_node/router/epub/font.js
  2. 2 0
      epub_node/router/epub/index.js
  3. 36 10
      epub_node/router/epub/txt.js

+ 78 - 0
epub_node/router/epub/font.js

@@ -0,0 +1,78 @@
+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 saveAllFount(epub, uploadPath, book_id, author_id) {
+  dirExists(uploadPath);
+  dirExists(`${uploadPath}font/`);
+
+  // 获取原始数据源
+  const getAllCss = epub.zip.names.filter((elm) => elm.indexOf("ttf") > -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: "font/ttf",
+          };
+        }
+        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(/.*\/(.*\.ttf)/);
+
+        //
+        // 移动文件
+        // './base_files/5ae2d9158081faab184484ed1783e176/epub-extract/OEBPS/flow0001.css'
+        // ./base_files/5ae2d9158081faab184484ed1783e176/style/flow0001.css
+        //
+
+        fs.writeFile(`${uploadPath}font/${md5}.ttf`, 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}font/${md5}.ttf`,
+          source_id: md5,
+        };
+        await files_insert(params);
+        return await files_insert_link_epub({
+          file_id: md5,
+          book_id,
+          author_id,
+        });
+      })
+    );
+  }
+}

+ 2 - 0
epub_node/router/epub/index.js

@@ -16,6 +16,7 @@ import { dirExists, isFileSync, isDir, waittime } from "#utils";
 import { saveImgs, calculateMD5 } from "./image.js";
 import { saveImgs, calculateMD5 } from "./image.js";
 import { htmlParser, saveMateInfo } from "./txt.js";
 import { htmlParser, saveMateInfo } from "./txt.js";
 import { saveAllCSS } from "./style.js";
 import { saveAllCSS } from "./style.js";
+import { saveAllFount } from "./font.js";
 
 
 const router = express.Router();
 const router = express.Router();
 
 
@@ -168,6 +169,7 @@ router.put("/", async function (req, res) {
    */
    */
   await saveMateInfo(epub, uploadPath, file_md5, author_id)
   await saveMateInfo(epub, uploadPath, file_md5, author_id)
   await saveImgs(epub, uploadPath, file_md5, author_id);
   await saveImgs(epub, uploadPath, file_md5, author_id);
+  await saveAllFount(epub, uploadPath, file_md5, author_id);
   await saveAllCSS(epub, uploadPath, file_md5, author_id);
   await saveAllCSS(epub, uploadPath, file_md5, author_id);
   // 存储html数据
   // 存储html数据
   await htmlParser(epub, zipEpubExtract, file_md5, author_id);
   await htmlParser(epub, zipEpubExtract, file_md5, author_id);

+ 36 - 10
epub_node/router/epub/txt.js

@@ -15,18 +15,11 @@ const imageExtensions = [".png", ".jpg", ".jpeg", ".svg"];
 async function processFiles(elmData, file_md5) {
 async function processFiles(elmData, file_md5) {
   const rows = elmData.toString().split(/\n/);
   const rows = elmData.toString().split(/\n/);
   const promises = rows.map(async (rowtext) => {
   const promises = rows.map(async (rowtext) => {
-    if (rowtext.indexOf(".svg") > -1) {
-      console.log(191919, rowtext);
-    }
     if (
     if (
       rowtext.includes("Images") &&
       rowtext.includes("Images") &&
       imageExtensions.some((ext) => rowtext.includes(ext))
       imageExtensions.some((ext) => rowtext.includes(ext))
     ) {
     ) {
       const match = rowtext.match(/.*(..\/Images\/(.*\.(jpg|png|jpeg|svg))).*/);
       const match = rowtext.match(/.*(..\/Images\/(.*\.(jpg|png|jpeg|svg))).*/);
-      if (rowtext.indexOf(".svg") > -1) {
-        console.log(2323, match, rowtext);
-      }
-
       if (match) {
       if (match) {
         const [, imgPath, imageSrc] = match;
         const [, imgPath, imageSrc] = match;
         const imgRow = await searchFileByPath(imageSrc);
         const imgRow = await searchFileByPath(imageSrc);
@@ -49,7 +42,33 @@ async function processFiles(elmData, file_md5) {
           );
           );
         }
         }
       }
       }
+    } else if (rowtext.includes(".ttf")) {
+      // 使用正则表达式匹配路径和文件名
+      const match = rowtext.match(/.*\((.*\/?(.*ttf))\)./);
+      if (match) {
+        const [, cssPath, cssSrc] = match;
+        try {
+          // 搜索数据库中是否存在该字体文件
+          const imgRow = await searchFileByPath(cssSrc, file_md5);
+          if (imgRow) {
+            // 如果找到,替换路径为 API 端点
+            console.log(57, rowtext);
+            console.log(58, cssPath, cssSrc);
+            console.log(59, `/api/v1/epub/css/${imgRow.file_id}`);
+
+            return (
+              rowtext.replace(cssPath, `/api/v1/epub/css/${imgRow.file_id}`) +
+              "\n"
+            );
+          } else {
+            console.warn(`Font file not found for path: ${cssSrc}`);
+          }
+        } catch (error) {
+          console.error("Error searching for font file:", error);
+        }
+      }
     }
     }
+
     return rowtext + "\n";
     return rowtext + "\n";
   });
   });
 
 
@@ -62,8 +81,11 @@ export async function htmlParser(epub, zipEpubExtract, file_md5, author_id) {
     (elm) => elm.endsWith(".html") || elm.endsWith(".css")
     (elm) => elm.endsWith(".html") || elm.endsWith(".css")
   );
   );
 
 
+  const needSetFont = epub.zip.names.filter((elm) => elm.endsWith(".ttf"));
   const basePath = path.join("./base_files", file_md5, "Text");
   const basePath = path.join("./base_files", file_md5, "Text");
+  const styleBasePath = path.join("./base_files", file_md5, "style");
   dirExists(basePath);
   dirExists(basePath);
+  dirExists(styleBasePath);
 
 
   await Promise.all(
   await Promise.all(
     needSetImage.map(async (elm) => {
     needSetImage.map(async (elm) => {
@@ -75,14 +97,18 @@ export async function htmlParser(epub, zipEpubExtract, file_md5, author_id) {
         fs.writeFileSync(filePath, htmlStr);
         fs.writeFileSync(filePath, htmlStr);
 
 
         const htmlMd5 = await calculateMD5(filePath);
         const htmlMd5 = await calculateMD5(filePath);
-        const newFilePath = path.join(basePath, `${htmlMd5}.html`);
+        const isCss = elm.endsWith(".css");
+        const newFilePath = path.join(
+          isCss ? styleBasePath : basePath,
+          `${htmlMd5}.${isCss ? "css" : "html"}`
+        );
 
 
         const params = {
         const params = {
           file_id: htmlMd5,
           file_id: htmlMd5,
           md5: htmlMd5,
           md5: htmlMd5,
-          mimetype: "text/html",
+          mimetype: isCss ? "text/css" : "text/html",
           size: Buffer.byteLength(htmlStr),
           size: Buffer.byteLength(htmlStr),
-          name: `${htmlMd5}.html`,
+          name: `${htmlMd5}.${isCss ? "css" : "html"}`,
           path: newFilePath,
           path: newFilePath,
           source_id: elm,
           source_id: elm,
         };
         };