Skip to content

Commit

Permalink
feat: 支持简书平台上传图片
Browse files Browse the repository at this point in the history
  • Loading branch information
terwer committed Sep 7, 2023
1 parent 6891ef6 commit 75768e1
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 16 deletions.
54 changes: 53 additions & 1 deletion src/adaptors/web/jianshu/jianshuWebAdaptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@

import { BaseWebApi } from "~/src/adaptors/web/base/baseWebApi.ts"
import { CategoryInfo, Post, UserBlog } from "zhi-blog-api"
import * as cheerio from "cheerio"
import { JsonUtil, StrUtil } from "zhi-common"
import { ElMessage } from "element-plus"
import { fileToBuffer } from "~/src/utils/polyfillUtils.ts"

/**
* 简书网页授权适配器
Expand Down Expand Up @@ -180,6 +180,50 @@ class JianshuWebAdaptor extends BaseWebApi {
return flag
}

public async uploadFile(file: File | Blob, filename?: string): Promise<any> {
this.logger.debug(`jianshu start uploadFile ${filename}=>`, file)
if (file instanceof Blob) {
// import
const win = this.appInstance.win
if (!win.require) {
throw new Error("非常抱歉,目前仅思源笔记PC客户端支持上传图片")
}
const { FormData, Blob } = win.require(`${this.appInstance.moduleBase}libs/node-fetch-cjs/dist/index.js`)

// uploadUrl
const uploadUrl = "https://upload.qiniup.com/"

// 获取图片二进制数据
const bits = await fileToBuffer(file)
const blob = new Blob([bits], { type: file.type })

// formData
const tokenReq = await this.webProxyFetch("https://www.jianshu.com/upload_images/token.json?filename=" + filename)
this.logger.debug("jianshu get picture token res =>", tokenReq)
const formData = new FormData()
formData.append("token", tokenReq.token)
formData.append("key", tokenReq.key)
formData.append("x:protocol", "https")
formData.append("file", blob, filename)

// 发送请求
const resJson = await this.jianshuFormFetch(uploadUrl, formData)
this.logger.debug("jianshu upload success, resJson =>", resJson)
if (!resJson.url) {
throw new Error("简书图片上传失败 =>" + filename)
}

const url = resJson.url
return {
id: tokenReq.key,
object_key: tokenReq.key,
url: url,
}
}

return {}
}

// ================
// private methods
// ================
Expand Down Expand Up @@ -253,6 +297,14 @@ class JianshuWebAdaptor extends BaseWebApi {
this.logger.error("简书文章发布失败", e)
}
}

private async jianshuFormFetch(url: string, formData: FormData) {
// header
const header = {}

const resJson = await this.webFormFetch(url, [header], formData)
return resJson
}
}

export { JianshuWebAdaptor }
24 changes: 11 additions & 13 deletions src/adaptors/web/wechat/wechatWebAdaptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -446,9 +446,14 @@ class WechatWebAdaptor extends BaseWebApi {
public async uploadFile(file: File | Blob, filename?: string): Promise<any> {
this.logger.debug(`wechat start uploadFile ${filename}=>`, file)
if (file instanceof Blob) {
// import
const win = this.appInstance.win
if (!win.require) {
throw new Error("非常抱歉,目前仅思源笔记PC客户端支持上传图片")
}
const { FormData, Blob } = win.require(`${this.appInstance.moduleBase}libs/node-fetch-cjs/dist/index.js`)

// uploadUrl
const ticket_id = this.cfg.metadata.commonData.data.user_name
const ticket = this.cfg.metadata.commonData.data.ticket
const svr_time = this.cfg.metadata.commonData.data.time
Expand All @@ -459,13 +464,14 @@ class WechatWebAdaptor extends BaseWebApi {
`&ticket_id=${ticket_id}&ticket=${ticket}&svr_time=${svr_time}&token=${token}&lang=zh_CN&seq=${seq}&t=` +
Math.random()

// 获取图片二进制数据
// const fs = win.require("fs")
// const fileData = fs.readFileSync("/Users/terwer/Documents/pictures/3259282.jpeg")
// const blob = new Blob([fileData], { type: "image/jpeg" })

const bits = await fileToBuffer(file)
const blob = new Blob([bits], { type: file.type })

// formData
const formData: any = new FormData()
formData.append("type", file.type)
formData.append("id", new Date().getTime())
Expand All @@ -474,6 +480,7 @@ class WechatWebAdaptor extends BaseWebApi {
formData.append("size", file.size)
formData.append("file", blob, filename)

// 发送请求
const resJson = await this.wechatFormFetch(uploadUrl, formData)
if (resJson.base_resp.err_msg != "ok") {
this.logger.error(`微信公众号图片上传失败, ${filename} =>`, resJson.base_resp.err_msg)
Expand Down Expand Up @@ -540,22 +547,13 @@ class WechatWebAdaptor extends BaseWebApi {
}

private async wechatFormFetch(url: string, formData: FormData) {
const win = this.appInstance.win
const doFetch = win.require(`${this.appInstance.moduleBase}libs/zhi-formdata-fetch/index.cjs`)

// headers
const headers = {
// header
const header = {
Cookie: this.cfg.password,
Referer: "https://mp.weixin.qq.com/cgi-bin/appmsg",
}
this.logger.debug("before zhi-formdata-fetch, headers =>", headers)
this.logger.debug("before zhi-formdata-fetch, url =>", url)

const resText = await doFetch(this.appInstance.moduleBase, url, headers, formData)
this.logger.debug("wechat doFetch success, resText =>", resText)
const resJson = JsonUtil.safeParse<any>(resText, {} as any)
this.logger.debug("wechat doFetch success, resJson=>", resJson)

const resJson = await this.webFormFetch(url, [header], formData)
return resJson
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/composables/useProxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ const useProxy = (middlewareUrl?: string) => {
method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH" = "GET",
contentType: string = "application/json"
) => {
const siyuanSupported = ["application/json", "text/html", "text/xml"]
const siyuanSupported = ["application/json", "text/html", "text/xml", ""]
if (isUseSiyuanProxy && siyuanSupported.includes(contentType)) {
logger.info("Using Siyuan forwardProxy, contentType=>", contentType)
let body: any
Expand Down
2 changes: 1 addition & 1 deletion src/utils/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export const DYNAMIC_CONFIG_KEY = "dynamic-config"
/**
* 必须使用平台自带的图片上传的平台
*/
export const MUST_USE_OWN_PLATFORM = ["custom_Zhihu", "custom_Csdn", "custom_Wechat"]
export const MUST_USE_OWN_PLATFORM = ["custom_Zhihu", "custom_Csdn", "custom_Wechat", "custom_Jianshu"]

/**
* 必须使用图床的平台
Expand Down

0 comments on commit 75768e1

Please sign in to comment.