Skip to content

Commit

Permalink
fix: 兼容平台图片上传
Browse files Browse the repository at this point in the history
  • Loading branch information
terwer committed Aug 12, 2023
1 parent 75712b8 commit 47472af
Show file tree
Hide file tree
Showing 24 changed files with 153 additions and 81 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@
"shorthash2": "^1.0.3",
"simple-xmlrpc": "^1.4.2",
"siyuan": "^0.7.9",
"siyuan-plugin-picgo": "^1.4.3",
"siyuan-plugin-picgo": "^1.4.4",
"uuid": "^9.0.0",
"vue": "^3.3.4",
"vue-i18n": "^9.2.2",
Expand Down
8 changes: 4 additions & 4 deletions pnpm-lock.yaml

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

23 changes: 20 additions & 3 deletions src/adaptors/api/base/baseBlogApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,14 @@ export class BaseBlogApi extends BlogApi {
// ================
// private methods
// ================
protected async readFileToBlob(url: string) {
const response = await this.proxyFetch(url, [], {}, "GET", "image/jpeg")
const body = response.body
const blobData = new Blob([body], { type: response.contentType })
this.logger.debug("blobData =>", blobData)
return blobData
}

/**
* 网页授权通用的请求代理
*
Expand Down Expand Up @@ -107,9 +115,18 @@ export class BaseBlogApi extends BlogApi {
})
const fetchResult = await this.kernelApi.forwardProxy(apiUrl, headers, body, method, contentType, 7000)
this.logger.debug("siyuan forwardProxy result=>", fetchResult)
const resText = fetchResult?.body
const res = JsonUtil.safeParse<any>(resText, {} as any)
return res
// 后续调试可打开这个日志
// this.logger.debug("proxyFetch resText=>", resText)
if (contentType === "application/json") {
const resText = fetchResult?.body
const res = JsonUtil.safeParse<any>(resText, {} as any)
return res
} else if (contentType === "text/html") {
const resText = fetchResult?.body
return resText
} else {
return fetchResult
}
} else {
this.logger.info("using commonFetchClient")
const header = headers.length > 0 ? headers[0] : {}
Expand Down
21 changes: 20 additions & 1 deletion src/adaptors/api/base/metaweblog/metaweblogBlogApiAdaptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,16 @@
* questions.
*/

import { CategoryInfo, Post, PostStatusEnum, UserBlog } from "zhi-blog-api"
import { Attachment, CategoryInfo, MediaObject, Post, PostStatusEnum, UserBlog } from "zhi-blog-api"
import { createAppLogger } from "~/src/utils/appLogger.ts"
import { CommonXmlrpcClient } from "zhi-xmlrpc-middleware"
import { MetaweblogConstants } from "~/src/adaptors/api/base/metaweblog/metaweblogConstants.ts"
import { StrUtil } from "zhi-common"
import { BrowserUtil } from "zhi-device"
import { BaseBlogApi } from "~/src/adaptors/api/base/baseBlogApi.ts"
import { MetaweblogConfig } from "~/src/adaptors/api/base/metaweblog/metaweblogConfig.ts"
import { result } from "lodash-es"
import { data } from "cheerio/lib/api/attributes"

/**
* MetaweblogBlogApi 类继承自 BaseBlogApi 类,并为 Metaweblog API 提供了额外的功能
Expand Down Expand Up @@ -210,6 +212,23 @@ class MetaweblogBlogApiAdaptor extends BaseBlogApi {
return result
}

public async newMediaObject(mediaObject: MediaObject, customHandler?: any): Promise<Attachment> {
let ret: Attachment
try {
ret = await this.metaweblogCall(MetaweblogConstants.METHOD_NEW_MEDIA_OBJECT, [
this.cfg.blogid,
this.cfg.username,
this.cfg.password,
mediaObject,
])
this.logger.debug("上传媒体完成, ret =>", ret)
} catch (e) {
this.logger.error("媒体上传失败", e)
}

return ret
}

protected async metaweblogCall(method: string, params: any[]) {
return await this.commonXmlrpcClient.methodCall(method, params, this.cfg.middlewareUrl)
}
Expand Down
1 change: 1 addition & 0 deletions src/adaptors/api/base/metaweblog/metaweblogConstants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ class MetaweblogConstants {
public static METHOD_GET_RECENT_POSTS = "metaWeblog.getRecentPosts"
public static METHOD_GET_POST = "metaWeblog.getPost"
public static METHOD_GET_CATEGORIES = "metaWeblog.getCategories"
public static METHOD_NEW_MEDIA_OBJECT = "metaWeblog.newMediaObject"
}

export { MetaweblogConstants }
32 changes: 31 additions & 1 deletion src/adaptors/api/cnblogs/cnblogsApiAdaptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,13 @@
* questions.
*/

import { Post, UserBlog } from "zhi-blog-api"
import {MediaObject, Post, UserBlog} from "zhi-blog-api"
import { CnblogsConfig } from "~/src/adaptors/api/cnblogs/cnblogsConfig.ts"
import { AppInstance } from "~/src/appInstance.ts"
import { createAppLogger } from "~/src/utils/appLogger.ts"
import { CnblogsConstants } from "~/src/adaptors/api/cnblogs/cnblogsConstants.ts"
import { MetaweblogBlogApiAdaptor } from "~/src/adaptors/api/base/metaweblog/metaweblogBlogApiAdaptor.ts"
import {usePicgoBridge} from "~/src/composables/usePicgoBridge.ts";

/**
* 博客园 API 适配器
Expand Down Expand Up @@ -63,6 +64,35 @@ class CnblogsApiAdaptor extends MetaweblogBlogApiAdaptor {
return result
}

public async preEditPost(post: Post, id?: string, publishCfg?: any): Promise<Post> {
// const pubCfg = publishCfg as IPublishCfg
// 找到所有的图片
const { getImageItemsFromMd } = usePicgoBridge()
const images = await getImageItemsFromMd(id, post.markdown)
if (images.length === 0) {
this.logger.info("未找到图片,不处理")
return post
}
// 批量处理图片上传
this.logger.info(`找到${images.length}张图片,开始上传`)

for (const image of images) {
const imageBlob = await this.readFileToBlob(image.url)
this.logger.debug("read blob from image", { imageBlob })
const file = new File([imageBlob], image.name, { type: imageBlob.type, lastModified: Date.now() })
this.logger.debug("convert blob to file", { imageBlob })

const mediaObject = new MediaObject(image.name, imageBlob.type, file as any)
const attachResult = await this.newMediaObject(mediaObject)
this.logger.debug("attachResult =>", attachResult)
throw new Error("开发中")
}

this.logger.info("图片全部上传完成")
return post
}


public async newPost(post: Post, publish?: boolean): Promise<string> {
// 设置markdown分类
post = this.assignMdCategory(post)
Expand Down
4 changes: 2 additions & 2 deletions src/adaptors/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,8 @@ class Adaptors {
// break
// }
case SubPlatformType.System_Siyuan: {
const { cfg } = useSiyuanApi()
conf = cfg
const { siyuanConfig } = useSiyuanApi()
conf = siyuanConfig
break
}
default: {
Expand Down
15 changes: 13 additions & 2 deletions src/adaptors/web/base/baseWebApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,14 @@ class BaseWebApi extends WebApi {
// ================
// private methods
// ================
protected async readFileToBlob(url: string) {
const response = await this.proxyFetch(url, [], {}, "GET", "image/jpeg")
const body = response.body
const blobData = new Blob([body], { type: response.contentType })
this.logger.debug("blobData =>", blobData)
return blobData
}

/**
* 网页授权通用的请求代理
*
Expand Down Expand Up @@ -149,14 +157,17 @@ class BaseWebApi extends WebApi {
7000
)
this.logger.debug("proxyFetch result=>", fetchResult)
const resText = fetchResult?.body
// 后续调试可打开这个日志
// this.logger.debug("proxyFetch resText=>", resText)
if (contentType === "application/json") {
const resText = fetchResult?.body
const res = JsonUtil.safeParse<any>(resText, {} as any)
return res
} else {
} else if (contentType === "text/html") {
const resText = fetchResult?.body
return resText
} else {
return fetchResult
}
} else {
this.logger.info("using middleware proxy")
Expand Down
19 changes: 14 additions & 5 deletions src/adaptors/web/zhihu/zhihuWebAdaptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ class ZhihuWebAdaptor extends BaseWebApi {
}

public async preEditPost(post: Post, id?: string, publishCfg?: any): Promise<Post> {
const pubCfg = publishCfg as IPublishCfg
// const pubCfg = publishCfg as IPublishCfg
// 找到所有的图片
const { getImageItemsFromMd } = usePicgoBridge()
const images = await getImageItemsFromMd(id, post.markdown)
Expand All @@ -108,10 +108,19 @@ class ZhihuWebAdaptor extends BaseWebApi {
}
// 批量处理图片上传
this.logger.info(`找到${images.length}张图片,开始上传`)
const file = null
const mediaObject = new MediaObject("20220616-132401-001.jpg", "image/jpeg", file)
this.newMediaObject(mediaObject)
throw new Error("开发中")

for (const image of images) {
const imageBlob = await this.readFileToBlob(image.url)
this.logger.debug("read blob from image", { imageBlob })
const file = new File([imageBlob], image.name, { type: imageBlob.type, lastModified: Date.now() })
this.logger.debug("convert blob to file", { imageBlob })

const mediaObject = new MediaObject(image.name, imageBlob.type, file as any)
const attachResult = await this.newMediaObject(mediaObject)
this.logger.debug("attachResult =>", attachResult)
throw new Error("开发中")
}

this.logger.info("图片全部上传完成")
return post
}
Expand Down
6 changes: 4 additions & 2 deletions src/appInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@

import { createAppLogger } from "~/src/utils/appLogger.ts"
import { DeviceDetection } from "zhi-device"
import xmlbuilder2 from "xmlbuilder2"
import { Deserializer, Serializer, SimpleXmlRpcClient, XmlrpcUtil } from "simple-xmlrpc"
import fetch from "cross-fetch"
import { create } from "xmlbuilder2"

/**
* 应用实例
Expand All @@ -45,7 +45,9 @@ export class AppInstance {
this.deviceType = DeviceDetection.getDevice()

this.fetch = fetch
this.xmlbuilder2 = xmlbuilder2
this.xmlbuilder2 = {
create,
}
this.simpleXmlrpc = {
SimpleXmlRpcClient: SimpleXmlRpcClient,
Serializer: Serializer,
Expand Down
14 changes: 9 additions & 5 deletions src/components/test/CnblogsTest.vue
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,15 @@ import { Utils } from "~/src/utils/utils.ts"
import { reactive, ref } from "vue"
import { fileToBuffer } from "~/src/utils/polyfillUtils.ts"
import { SimpleXmlRpcClient } from "simple-xmlrpc"
import {MediaObject, Post} from "zhi-blog-api"
import { MediaObject, Post } from "zhi-blog-api"
import { createAppLogger } from "~/src/utils/appLogger.ts"
import Adaptors from "~/src/adaptors"
import {SiYuanApiAdaptor, SiyuanConfig} from "zhi-siyuan-api";
import { useVueI18n } from "~/src/composables/useVueI18n.ts"
const logger = createAppLogger("cnblogs-test")
const { t } = useVueI18n()
const params = ref("{}")
const showParamFile = ref(false)
const paramFile = ref(null)
Expand Down Expand Up @@ -297,6 +299,8 @@ const cnblogsHandleApi = async () => {
break
}
case METHOD_NEW_MEDIA_OBJECT: {
const key = "metaweblog_Cnblogs"
const file = paramFile.value
const bits = await fileToBuffer(file)
const mediaObject = new MediaObject(file.name, file.type, bits)
Expand All @@ -309,9 +313,9 @@ const cnblogsHandleApi = async () => {
bits: mediaObject.bits,
overwrite: true,
}
const xmlrpcApiUrl = "http://127.0.0.1:3000/xmlrpc.php"
const client = new SimpleXmlRpcClient(xmlrpcApiUrl, "", {})
const result = await client.methodCall("metaWeblog.newMediaObject", ["", "terwer", "123456", metadata])
const cfg = await Adaptors.getCfg(key)
const client = new SimpleXmlRpcClient(appInstance, cfg.apiUrl, {})
const result = await client.methodCall("metaWeblog.newMediaObject", ["", cfg.username, cfg.password, metadata])
logMessage.value = JSON.stringify(result)
logger.info("cnblogs new mediaObject result=>", result)
break
Expand Down
3 changes: 3 additions & 0 deletions src/components/test/HexoTest.vue
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,12 @@ import { fileToBuffer } from "~/src/utils/polyfillUtils.ts"
import { SimpleXmlRpcClient } from "simple-xmlrpc"
import { MediaObject } from "zhi-blog-api"
import { createAppLogger } from "~/src/utils/appLogger.ts"
import { useVueI18n } from "~/src/composables/useVueI18n.ts"
const logger = createAppLogger("wordpress-test")
const { t } = useVueI18n()
const params = ref("{}")
const showParamFile = ref(false)
const paramFile = ref(null)
Expand Down
5 changes: 4 additions & 1 deletion src/components/test/HugoTest.vue
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,12 @@ import { fileToBuffer } from "~/src/utils/polyfillUtils.ts"
import { SimpleXmlRpcClient } from "simple-xmlrpc"
import { MediaObject } from "zhi-blog-api"
import { createAppLogger } from "~/src/utils/appLogger.ts"
import { useVueI18n } from "~/src/composables/useVueI18n.ts"
const logger = createAppLogger("wordpress-test")
const { t } = useVueI18n()
const params = ref("{}")
const showParamFile = ref(false)
const paramFile = ref(null)
Expand Down Expand Up @@ -285,4 +288,4 @@ const wordpressHandleApi = async () => {
.method-list
margin-bottom 16px
</style>
</style>
4 changes: 4 additions & 0 deletions src/components/test/SiyuanTest.vue
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,13 @@ import { Utils } from "~/src/utils/utils.ts"
import { SiYuanApiAdaptor, SiyuanConfig, SiyuanKernelApi } from "zhi-siyuan-api"
import { MediaObject, Post } from "zhi-blog-api"
import { fileToBuffer } from "~/src/utils/polyfillUtils.ts"
import { useVueI18n } from "~/src/composables/useVueI18n.ts"
const logger = createAppLogger("siyuan-test")
// uses
const { t } = useVueI18n()
const params = ref("{}")
const showParamFile = ref(false)
const paramFile = ref(null)
Expand Down
3 changes: 3 additions & 0 deletions src/components/test/VitepressTest.vue
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,12 @@ import { fileToBuffer } from "~/src/utils/polyfillUtils.ts"
import { SimpleXmlRpcClient } from "simple-xmlrpc"
import { MediaObject } from "zhi-blog-api"
import { createAppLogger } from "~/src/utils/appLogger.ts"
import { useVueI18n } from "~/src/composables/useVueI18n.ts"
const logger = createAppLogger("wordpress-test")
const { t } = useVueI18n()
const params = ref("{}")
const showParamFile = ref(false)
const paramFile = ref(null)
Expand Down
5 changes: 4 additions & 1 deletion src/components/test/WordpressTest.vue
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,12 @@ import { SimpleXmlRpcClient } from "simple-xmlrpc"
import { MediaObject } from "zhi-blog-api"
import { createAppLogger } from "~/src/utils/appLogger.ts"
import Adaptors from "~/src/adaptors"
import { useVueI18n } from "~/src/composables/useVueI18n.ts"
const logger = createAppLogger("wordpress-test")
const { t } = useVueI18n()
const params = ref("{}")
const showParamFile = ref(false)
const paramFile = ref(null)
Expand Down Expand Up @@ -292,4 +295,4 @@ const wordpressHandleApi = async () => {
.method-list
margin-bottom 16px
</style>
</style>
Loading

0 comments on commit 47472af

Please sign in to comment.