Skip to content

Commit

Permalink
Merge pull request #884 from terwer/feature/hotfix
Browse files Browse the repository at this point in the history
fix: 修复简书发布报错问题
  • Loading branch information
terwer committed Nov 8, 2023
2 parents b220a70 + f954feb commit d688bf1
Show file tree
Hide file tree
Showing 8 changed files with 175 additions and 27 deletions.
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"@halo-dev/api-client": "^2.10.0",
"@terwer/eslint-config-custom": "^1.3.6",
"@types/crypto-js": "^4.2.1",
"@types/katex": "^0.16.6",
"@types/lodash": "^4.14.201",
"@types/node": "^18.18.9",
"@vitejs/plugin-vue": "^4.4.0",
Expand Down Expand Up @@ -66,6 +67,7 @@
"gray-matter": "^4.0.3",
"js-base64": "^3.7.5",
"js-yaml": "^4.1.0",
"katex": "^0.16.9",
"lodash": "^4.17.21",
"pinia": "^2.1.7",
"shorthash2": "^1.0.3",
Expand Down
18 changes: 17 additions & 1 deletion pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/adaptors/api/vuepress/vuepressYamlConverterAdaptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ class VuepressYamlConverterAdaptor extends YamlConvertAdaptor {
}

// 日记
if (post.title.includes("[日记]")) {
if (post?.title?.includes("[日记]")) {
yamlFormatObj.yamlObj.article = false
}

Expand Down
4 changes: 2 additions & 2 deletions src/adaptors/base/baseExtendApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ class BaseExtendApi extends WebApi implements IBlogApi, IWebApi {
const post = _.cloneDeep(doc) as Post

if (cfg?.mdFilenameRule) {
if (cfg?.mdFilenameRule.includes("[filename]")) {
if (cfg?.mdFilenameRule?.includes("[filename]")) {
cfg.useMdFilename = true
}
// 处理文件规则
Expand Down Expand Up @@ -237,7 +237,7 @@ class BaseExtendApi extends WebApi implements IBlogApi, IWebApi {
const pathCates = []

// 笔记层级作为文件路径
if (savePath.includes(CATE_AUTO_NAME)) {
if (savePath?.toString().includes(CATE_AUTO_NAME)) {
cfg.usePathCategory = true
}
// 获取笔记层级
Expand Down
32 changes: 32 additions & 0 deletions src/adaptors/web/csdn/csdnUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
import Utf8 from "crypto-js/enc-utf8"
import CryptoJS from "crypto-js"
import Base64 from "crypto-js/enc-base64"
import * as cheerio from "cheerio"
import KatexUtils from "~/src/utils/KatexUtils.ts"

/**
* CSDN工具类,用于生成UUID和签名
Expand Down Expand Up @@ -82,6 +84,36 @@ class CsdnUtils {
// console.log(sign)
return sign
}

public static processCsdnMath(html: string): string {
// 使用Cheerio加载HTML
const $ = cheerio.load(html)

// 处理两个$符号包裹的公式
const doubleDollarRegex = /\$\$([^$]+)\$\$/g
$("*").each((index, element) => {
const content = $(element).html()
const newContent = content.replace(doubleDollarRegex, (match, mathContent) => {
const mathHtml = KatexUtils.renderToString(mathContent)
return `<span class="katex--display">${mathHtml}</span>`
})
$(element).html(newContent)
})

// 处理一个$符号包裹的公式
const singleDollarRegex = /\$([^$]+)\$/g
$("*").each((index, element) => {
const content = $(element).html()
const newContent = content.replace(singleDollarRegex, (match, mathContent) => {
const mathHtml = KatexUtils.renderToString(mathContent)
return `<span class="katex--inline">${mathHtml}</span>`
})
$(element).html(newContent)
})

// 输出修改后的HTML
return $.html()
}
}

export default CsdnUtils
37 changes: 34 additions & 3 deletions src/adaptors/web/csdn/csdnWebAdaptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,10 @@

import { BaseWebApi } from "~/src/adaptors/web/base/baseWebApi.ts"
import CsdnUtils from "~/src/adaptors/web/csdn/csdnUtils.ts"
import { CategoryInfo, Post, UserBlog } from "zhi-blog-api"
import { JsonUtil, StrUtil } from "zhi-common"
import { BlogConfig, CategoryInfo, PageTypeEnum, Post, UserBlog } from "zhi-blog-api"
import { JsonUtil } from "zhi-common"
import WebUtils from "~/src/adaptors/web/base/webUtils.ts"
import _ from "lodash"

/**
* CSDN网页授权适配器
Expand Down Expand Up @@ -139,6 +140,36 @@ class CsdnWebAdaptor extends BaseWebApi {
return cats
}

public override async preEditPost(post: Post, id?: string, publishCfg?: any): Promise<Post> {
// 公共的属性预处理
const doc = await super.preEditPost(post, id, publishCfg)

// CSDN自定义的处理
const cfg: BlogConfig = publishCfg?.cfg
const updatedPost = _.cloneDeep(doc) as Post
const html = updatedPost.html
this.logger.info("准备处理CSDN正文")
this.logger.debug("html =>", { html: html })
let updatedHtml = html

// 处理数学公式
updatedHtml = CsdnUtils.processCsdnMath(updatedHtml)

// 处理完毕
updatedPost.html = updatedHtml
this.logger.info("CSDN正文处理完毕")
this.logger.debug("updatedHtml =>", { updatedHtml: updatedHtml })

// 发布格式
if (cfg?.pageType == PageTypeEnum.Markdown) {
updatedPost.description = updatedPost.markdown
} else {
updatedPost.description = updatedPost.html
}

return updatedPost
}

public async addPost(post: Post) {
// 仅支持MD
const params = JSON.stringify({
Expand Down Expand Up @@ -220,7 +251,7 @@ class CsdnWebAdaptor extends BaseWebApi {
this.logger.debug("save csdn post res=>", res)

if (res?.code !== 200) {
throw new Error("CSDN文章更新失败,可能是等级不够导致,如过等级不够,请去掉文章标签")
throw new Error("CSDN文章更新失败,可能是等级不够导致,如果等级不够,请去掉文章标签")
}

this.logger.debug("edit csdn post res=>", res)
Expand Down
62 changes: 42 additions & 20 deletions src/adaptors/web/zhihu/zhihuUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,30 +64,52 @@ class ZhihuUtils {
// 使用Cheerio加载HTML
const $ = cheerio.load(html)

// 选择所有带有类名"language-math"的<span>元素
$("span.language-math").each((index, element) => {
// 获取元素的文本内容
const mathContent = $(element).text()
// // 选择所有带有类名"language-math"的<span>元素
// $("span.language-math").each((index, element) => {
// // 获取元素的文本内容
// const mathContent = $(element).text()
//
// // 创建替代的<img>标签
// const imgTag = `<img eeimg="1" src="//www.zhihu.com/equation?tex=${encodeURIComponent(mathContent)}"
// alt="${mathContent}" />`
//
// // 用新的<img>标签替换原始元素
// $(element).replaceWith(imgTag)
// })
//
// // 选择所有带有类名"language-math"的<div>元素
// $("div.language-math").each((index, element) => {
// // 获取元素的文本内容
// const mathContent = $(element).text()
//
// // 创建替代的<img>标签
// const imgTag = `<p><img eeimg="1" src="//www.zhihu.com/equation?tex=${encodeURIComponent(mathContent)}"
// alt="${mathContent}"/></p>`
//
// // 用新的<img>标签替换原始元素
// $(element).replaceWith(imgTag)
// })

// 创建替代的<img>标签
const imgTag = `<img eeimg="1" src="//www.zhihu.com/equation?tex=${encodeURIComponent(mathContent)}"
// 处理两个$符号包裹的公式
const doubleDollarRegex = /\$\$([^$]+)\$\$/g
$("*").each((index, element) => {
const content = $(element).html()
const newContent = content.replace(doubleDollarRegex, (match, mathContent) => {
return `<img eeimg="1" src="//www.zhihu.com/equation?tex=${encodeURIComponent(mathContent)}"
alt="${mathContent}" />`

// 用新的<img>标签替换原始元素
$(element).replaceWith(imgTag)
})
$(element).html(newContent)
})

// 选择所有带有类名"language-math"的<div>元素
$("div.language-math").each((index, element) => {
// 获取元素的文本内容
const mathContent = $(element).text()

// 创建替代的<img>标签
const imgTag = `<p><img eeimg="1" src="//www.zhihu.com/equation?tex=${encodeURIComponent(mathContent)}"
alt="${mathContent}"/></p>`

// 用新的<img>标签替换原始元素
$(element).replaceWith(imgTag)
// 处理一个$符号包裹的公式
const singleDollarRegex = /\$([^$]+)\$/g
$("*").each((index, element) => {
const content = $(element).html()
const newContent = content.replace(singleDollarRegex, (match, mathContent) => {
return `<img eeimg="1" src="//www.zhihu.com/equation?tex=${encodeURIComponent(mathContent)}"
alt="${mathContent}" />`
})
$(element).html(newContent)
})

// 输出修改后的HTML
Expand Down
45 changes: 45 additions & 0 deletions src/utils/KatexUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
* Copyright (c) 2023, Terwer . All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Terwer designates this
* particular file as subject to the "Classpath" exception as provided
* by Terwer in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Terwer, Shenzhen, Guangdong, China, youweics@163.com
* or visit www.terwer.space if you need additional information or have any
* questions.
*/

import katex from "katex"

/**
* 公式渲染
*
* @author terwer
* @since 1.18.6
*/
class KatexUtils {
/**
* 获得要渲染 KaTeX 表达式的 HTML
*
* @param mathExpression katex
*/
public static renderToString(mathExpression: string) {
return katex.renderToString(mathExpression)
}
}

export default KatexUtils

0 comments on commit d688bf1

Please sign in to comment.