Skip to content

Commit

Permalink
feat: #790 支持外链转换
Browse files Browse the repository at this point in the history
  • Loading branch information
terwer committed Oct 29, 2023
1 parent bc311e1 commit 7fc9cfe
Show file tree
Hide file tree
Showing 10 changed files with 121 additions and 24 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -76,15 +76,15 @@
"vue-i18n": "^9.6.1",
"vue-router": "^4.2.5",
"xmlbuilder2": "^3.1.1",
"zhi-blog-api": "^1.47.0",
"zhi-blog-api": "^1.49.0",
"zhi-common": "^1.25.0",
"zhi-device": "^2.10.0",
"zhi-fetch-middleware": "^0.7.11",
"zhi-github-middleware": "^0.4.8",
"zhi-gitlab-middleware": "^0.6.18",
"zhi-lib-base": "^0.8.0",
"zhi-notion-markdown": "^0.1.4",
"zhi-siyuan-api": "^2.11.6",
"zhi-siyuan-api": "^2.11.8",
"zhi-xmlrpc-middleware": "^0.6.11"
}
}
20 changes: 10 additions & 10 deletions pnpm-lock.yaml

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

4 changes: 4 additions & 0 deletions src/adaptors/api/base/baseBlogApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,10 @@ export class BaseBlogApi extends BlogApi {
return null
}

public getPostPreviewUrl(postid: string): Promise<string> {
return this.getPreviewUrl(postid)
}

public async preEditPost(post: Post, id?: string, publishCfg?: any): Promise<Post> {
return await this.baseExtendApi.preEditPost(post, id, publishCfg)
}
Expand Down
9 changes: 4 additions & 5 deletions src/adaptors/api/base/github/commonGithubApiAdaptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,9 @@ import { createAppLogger } from "~/src/utils/appLogger.ts"
import { CategoryInfo, Post, UserBlog, YamlConvertAdaptor, YamlFormatObj } from "zhi-blog-api"
import { CommonGithubClient, GithubConfig } from "zhi-github-middleware"
import { CommonGithubConfig } from "~/src/adaptors/api/base/github/commonGithubConfig.ts"
import { DateUtil, HtmlUtil, StrUtil, YamlUtil } from "zhi-common"
import { StrUtil, YamlUtil } from "zhi-common"
import { toRaw } from "vue"
import { Base64 } from "js-base64"
import { CommonGitlabConfig } from "~/src/adaptors/api/base/gitlab/commonGitlabConfig.ts"
import sypIdUtil from "~/src/utils/sypIdUtil.ts"

/**
Expand Down Expand Up @@ -212,12 +211,12 @@ class CommonGithubApiAdaptor extends BaseBlogApi {
return previewUrl
}

public async getPostPreviewUrl(postid: string): Promise<string> {
public override async getPostPreviewUrl(postid: string): Promise<string> {
let previewUrl: string
const newPostid = postid.substring(postid.lastIndexOf("/") + 1).replace(".md", "")
previewUrl = this.cfg.previewUrl.replace("[postid]", newPostid)
previewUrl = this.cfg.previewPostUrl.replace("[postid]", newPostid)
// 路径组合
previewUrl = StrUtil.pathJoin(StrUtil.pathJoin(this.cfg.home, this.cfg.username), previewUrl)
// previewUrl = StrUtil.pathJoin(this.cfg.postHome, previewUrl)

return previewUrl
}
Expand Down
2 changes: 1 addition & 1 deletion src/adaptors/api/base/github/commonGithubConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ class CommonGithubConfig extends CommonBlogConfig {
/**
* 预览规则(占位符:[yyyy] [MM] [dd] [postid])
*/
public previewPostUrl: string
public override previewPostUrl: string = ""

/**
* MD文件预览规则(占位符:[user] [repo] [branch] [docpath])
Expand Down
4 changes: 2 additions & 2 deletions src/adaptors/api/base/gitlab/commonGitlabApiAdaptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,9 +222,9 @@ class CommonGitlabApiAdaptor extends BaseBlogApi {
public async getPostPreviewUrl(postid: string): Promise<string> {
let previewUrl: string
const newPostid = postid.substring(postid.lastIndexOf("/") + 1).replace(".md", "")
previewUrl = this.cfg.previewUrl.replace("[postid]", newPostid)
previewUrl = this.cfg.previewPostUrl.replace("[postid]", newPostid)
// 路径组合
previewUrl = StrUtil.pathJoin(StrUtil.pathJoin(this.cfg.home, this.cfg.username), previewUrl)
// previewUrl = StrUtil.pathJoin(this.cfg.postHome, previewUrl)

return previewUrl
}
Expand Down
75 changes: 73 additions & 2 deletions src/adaptors/base/baseExtendApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,17 +41,18 @@ import { createAppLogger, ILogger } from "~/src/utils/appLogger.ts"
import { LuteUtil } from "~/src/utils/luteUtil.ts"
import { usePicgoBridge } from "~/src/composables/usePicgoBridge.ts"
import { base64ToBuffer, remoteImageToBase64Info, toBase64Info } from "~/src/utils/polyfillUtils.ts"
import { DateUtil, HtmlUtil, StrUtil, YamlUtil } from "zhi-common"
import { DateUtil, HtmlUtil, ObjectUtil, StrUtil, YamlUtil } from "zhi-common"
import { useSiyuanDevice } from "~/src/composables/useSiyuanDevice.ts"
import { isFileExists } from "~/src/utils/siyuanUtils.ts"
import { useSiyuanApi } from "~/src/composables/useSiyuanApi.ts"
import { SiyuanKernelApi } from "zhi-siyuan-api"
import { SiyuanAttr, SiyuanKernelApi } from "zhi-siyuan-api"
import { DynamicConfig } from "~/src/platforms/dynamicConfig.ts"
import { CATE_AUTO_NAME, MUST_USE_OWN_PLATFORM, MUST_USE_PICBED_PLATFORM } from "~/src/utils/constants.ts"
import { toRaw } from "vue"
import _ from "lodash"
import { usePublishPreferenceSetting } from "~/src/stores/usePublishPreferenceSetting.ts"
import { SiyuanDevice } from "zhi-device"
import { SypConfig } from "~/syp.config.ts"

/**
* 各种模式共享的扩展基类
Expand Down Expand Up @@ -241,6 +242,7 @@ class BaseExtendApi extends WebApi implements IBlogApi, IWebApi {
*/
private async handleMd(doc: Post, id?: string, publishCfg?: any) {
const cfg: BlogConfig = publishCfg?.cfg
const setting: typeof SypConfig = publishCfg?.setting
const post = _.cloneDeep(doc) as Post

// 处理MD
Expand All @@ -260,9 +262,16 @@ class BaseExtendApi extends WebApi implements IBlogApi, IWebApi {
// md = md.replace(/\*\*(.*?)\*\*/g, '<span style="font-weight: bold;" data-type="strong">$1</span>')
md = md.replace(/\*\*(.*?)\*\*/g, '<span style="font-weight: bold;" data-type="strong">$1</span>')

// 处理外链
const { getReadOnlyPublishPreferenceSetting } = usePublishPreferenceSetting()
const pref = getReadOnlyPublishPreferenceSetting()
const outerLinkRegex = /\[(.+?)]\(siyuan:\/\/blocks\/(\d+-\w+)\)/g
md = await this.replaceOuterLinks(md, outerLinkRegex, { pref, cfg, setting })

// 汇总结果
post.markdown = md
this.logger.debug("markdown处理完毕,post", { post: toRaw(post) })

return post
}

Expand Down Expand Up @@ -497,6 +506,68 @@ class BaseExtendApi extends WebApi implements IBlogApi, IWebApi {
this.logger.debug("readFileToBase64 proxyFetch base64Info =>", { base64Info })
return base64Info
}

/**
* 替换链接
*
* @param text 文本
* @param regex 正则
* @param options 选项
* @private
*/
private async replaceOuterLinks(
text: string,
regex: RegExp,
options: { pref: any; cfg: any; setting: typeof SypConfig }
) {
const { pref, cfg, setting } = options
const that = this
const win = SiyuanDevice.siyuanWindow()
const path = win.require("path")

const matches = Array.from(text.matchAll(regex))

let replacedText = text
for (const match of matches) {
const [fullMatch, title, id] = match

// processedTitle
let processedTitle = title
if (pref.value.fixTitle) {
processedTitle = HtmlUtil.removeTitleNumber(processedTitle)
}

// outerLink
let outerLink: string
// 获取预览链接
// 如果已发布替换成别名
const postMeta = ObjectUtil.getProperty(setting, id, {})
const posidKey = cfg.posidKey
if (!postMeta.hasOwnProperty(posidKey)) {
outerLink = `siyuan://blocks/${id}`
this.logger.warn("引用的文档尚未发布,取消外链 =>", id)
} else {
let previewUrl: string
const postid = postMeta[posidKey]
previewUrl = await that.api.getPostPreviewUrl(postid)
if (cfg?.mdFilenameRule?.includes("[filename]")) {
const slug = postMeta[SiyuanAttr.Custom_slug]
const filename = path.basename(postid).replace(/\.md/g, "")
previewUrl = previewUrl.replace(filename, slug)
}
previewUrl = previewUrl.replace(cfg.home, "")
// 使用绝对路径
if (!previewUrl.startsWith("/")) {
previewUrl = `/${previewUrl}`
}
outerLink = previewUrl
}

replacedText = replacedText.replace(fullMatch, `[${processedTitle}](${outerLink})`)
}

return replacedText
}
}

export { BaseExtendApi }
4 changes: 4 additions & 0 deletions src/adaptors/web/base/baseWebApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ class BaseWebApi extends WebApi {
return true
}

public getPostPreviewUrl(postid: string): Promise<string> {
return this.getPreviewUrl(postid)
}

// web 适配器专有
public updateCfg(cfg: WebConfig) {
this.cfg = cfg
Expand Down
19 changes: 19 additions & 0 deletions src/platforms/dynamicConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -458,3 +458,22 @@ export function getDynPostidKey(platformKey: string): string {
export function getDynYamlKey(platformKey: string): string {
return "custom-" + platformKey.replace(/_/g, "-") + "-yaml"
}

/**
* 获取元数据 key
*
* @param postidKey 文章 key
*/
// export function getDynYamlKeyFromPostidKey(postidKey: string): string {
// // 匹配postidKey的正则表达式
// const regex = /^custom-(.+?)-post-id$/
// const match = postidKey.match(regex)
// if (match && match[1]) {
// // 提取platformKey
// const platformKey = match[1]
// const yamlKey = getDynYamlKey(platformKey)
// return yamlKey
// } else {
// throw new Error("Invalid postidKey format")
// }
// }
4 changes: 2 additions & 2 deletions src/workers/QuickPublish.vue
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ onMounted(async () => {
{{ singleFormData.isAdd ? "发布到" : "更新文章到" }}
<span :title="formData.processResult.key">[{{ HtmlUtil.parseHtml(formData.processResult.key, 8) }}]</span>
<span :title="formData.processResult.name" v-if="!StrUtil.isEmptyString(formData.processResult.name)">
{{ `[${HtmlUtil.parseHtml(formData.processResult.name, 6)}]` }}
{{ `[${HtmlUtil.parseHtml(formData.processResult.name, 8)}]` }}
</span>
成功,
<a :href="formData.processResult.previewUrl" target="_blank">查看文章</a>
Expand All @@ -121,7 +121,7 @@ onMounted(async () => {
{{ singleFormData.isAdd ? "发布到" : "更新文章到" }}
<span :title="formData.processResult.key">[{{ HtmlUtil.parseHtml(formData.processResult.key, 8) }}]</span>
<span :title="formData.processResult.name" v-if="!StrUtil.isEmptyString(formData.processResult.name)">
{{ `[${HtmlUtil.parseHtml(formData.processResult.name, 6)}]` }}
{{ `[${HtmlUtil.parseHtml(formData.processResult.name, 8)}]` }}
</span>
失败!
<loading-timer :loading-time="loadingTime" style="padding: 0 10px 0 10px; display: inline-block" />
Expand Down

0 comments on commit 7fc9cfe

Please sign in to comment.