Skip to content

Commit

Permalink
fix: 统一代理地址获取
Browse files Browse the repository at this point in the history
  • Loading branch information
terwer committed Jan 10, 2023
1 parent 45cea7e commit 8b8f466
Show file tree
Hide file tree
Showing 5 changed files with 134 additions and 144 deletions.
81 changes: 40 additions & 41 deletions api/index.js
Expand Up @@ -25,8 +25,7 @@

import express from "express"
import fetch from "cross-fetch"
import { imageToBase64 } from "../utils/otherlib/imageToBase64"

// import { imageToBase64 } from "../utils/otherlib/imageToBase64"
import { SimpleXmlRpcClient } from "../libs/simple-xmlrpc/custom/SimpleXmlRpcClient"

const app = express()
Expand Down Expand Up @@ -165,61 +164,61 @@ app.post("/api/middleware/fetch", (req, res) => {
},
body: resJson,
}
// console.log(finalRes)
console.log(finalRes)
console.log("请求处理已成功")
writeStatusData(res, finalRes, response.status)
// console.log("请求处理已成功")
})
} catch (e) {
err = e
console.error(e)
writeStatusError(res, err, response.status)
// console.log("请求处理异常")
console.log("请求处理异常")
console.error(e)
}
})
.catch((reason) => {
// console.log("methodPromise catch=>")
console.log("请求处理失败")
console.error("fetch middleware error=>", reason)
writeError(res, reason)
// console.log("请求处理失败")
})
// ========================================
// ========================================
})

app.post("/api/middleware/imageToBase64", (req, res) => {
const body = req.body

// =====================================
// =====================================
const imgUrl = body.fetchParams.imgUrl
imageToBase64({ uri: imgUrl })
.then((response) => {
const base64str = response.base64

const resJson = {
base64str,
}

const finalRes = {
headers: {
status: 200,
statusText: "ok",
},
body: resJson,
}
// console.log(finalRes)
writeStatusData(res, finalRes, 200)
// console.log("请求处理已成功")
})
.catch((reason) => {
// console.log("methodPromise catch=>")
console.error("imageToBase64 middleware error=>", reason)
writeError(res, reason)
// console.log("请求处理失败")
})
// ========================================
// ========================================
})
// app.post("/api/middleware/imageToBase64", (req, res) => {
// const body = req.body
//
// // =====================================
// // =====================================
// const imgUrl = body.fetchParams.imgUrl
// imageToBase64({ uri: imgUrl })
// .then((response) => {
// const base64str = response.base64
//
// const resJson = {
// base64str,
// }
//
// const finalRes = {
// headers: {
// status: 200,
// statusText: "ok",
// },
// body: resJson,
// }
// // console.log(finalRes)
// writeStatusData(res, finalRes, 200)
// // console.log("请求处理已成功")
// })
// .catch((reason) => {
// // console.log("methodPromise catch=>")
// console.error("imageToBase64 middleware error=>", reason)
// writeError(res, reason)
// // console.log("请求处理失败")
// })
// // ========================================
// // ========================================
// })

/**
* 输出数据
Expand Down
7 changes: 2 additions & 5 deletions libs/simple-xmlrpc/impl/middlewareXmlrpc.ts
Expand Up @@ -23,8 +23,8 @@
* questions.
*/

import { getEnvOrDefault } from "~/utils/envUtil"
import { LogFactory } from "~/utils/logUtil"
import { getSiyuanCfg } from "~/utils/platform/siyuan/siYuanConfig"

const logger = LogFactory.getLogger(
"libs/simple-xmlrpc/impl/middlewareXmlrpc.ts"
Expand All @@ -41,10 +41,7 @@ export async function fetchMiddleware(
reqMethod: string,
reqParams: string[]
): Promise<string> {
const middlewareUrl = getEnvOrDefault(
"VITE_MIDDLEWARE_URL",
"/api/middleware"
)
const middlewareUrl = getSiyuanCfg().middlewareUrl
const middleApiUrl = middlewareUrl + "/xmlrpc"
logger.debug("apiUrl=>", apiUrl)
const fetchCORSParams = {
Expand Down
56 changes: 28 additions & 28 deletions utils/otherlib/imageToBase64.js
Expand Up @@ -22,31 +22,31 @@
* or visit www.terwer.space if you need additional information or have any
* questions.
*/

import * as fs from "fs/promises"
import * as path from "path"
import fetch from "cross-fetch"

const imageRegex = /.(gif|jpe?g|tiff?|png|webp|bmp|ico)$/i

export async function imageToBase64(image) {
let base64 = ""
if (image.uri) {
const uri = new URL(image.uri)
const fetchResponse = await fetch(uri)
const imageBuffer = await fetchResponse.buffer()
base64 = imageBuffer.toString("base64")
} else if (image.path && imageRegex.test(image.path)) {
const response = await fs.stat(image.path)
const isFile = response.isFile()
if (isFile) {
const imageBuffer = await fs.readFile(path.resolve(image.path))
base64 = imageBuffer.toString("base64")
}
} else {
throw new Error(
"Didn't get an image or a good uri for the appropriate param"
)
}
return { base64 }
}
//
// import * as fs from "fs/promises"
// import * as path from "path"
// import fetch from "cross-fetch"
//
// const imageRegex = /.(gif|jpe?g|tiff?|png|webp|bmp|ico)$/i
//
// export async function imageToBase64(image) {
// let base64 = ""
// if (image.uri) {
// const uri = new URL(image.uri)
// const fetchResponse = await fetch(uri)
// const imageBuffer = await fetchResponse.buffer()
// base64 = imageBuffer.toString("base64")
// } else if (image.path && imageRegex.test(image.path)) {
// const response = await fs.stat(image.path)
// const isFile = response.isFile()
// if (isFile) {
// const imageBuffer = await fs.readFile(path.resolve(image.path))
// base64 = imageBuffer.toString("base64")
// }
// } else {
// throw new Error(
// "Didn't get an image or a good uri for the appropriate param"
// )
// }
// return { base64 }
// }
127 changes: 62 additions & 65 deletions utils/parser/imageParser.ts
Expand Up @@ -24,10 +24,7 @@
*/

import { LogFactory } from "~/utils/logUtil"
import { inSiyuan } from "~/utils/platform/siyuan/siyuanUtil"
import { imageToBase64 } from "~/utils/otherlib/imageToBase64"
import { getEnvOrDefault } from "~/utils/envUtil"
import { appendStr } from "~/utils/strUtil"
// import { imageToBase64 } from "~/utils/otherlib/imageToBase64"
import { ImageItem } from "~/utils/models/imageItem"

/**
Expand Down Expand Up @@ -78,67 +75,67 @@ export class ImageParser {
* 将外链外链图片替换为base64
* @param content
*/
public async replaceImagesWithBase64(content: string): Promise<string> {
let newcontent = content

const imgRegex = /!\[.*]\((http|https):\/.*\/.*\)/g
const matches = newcontent.match(imgRegex)
// 没有图片,无需处理
if (matches == null || matches.length === 0) {
return newcontent
}

for (let i = 0; i < matches.length; i++) {
const match = matches[i]
this.logger.debug("img=>", match)

const src = match.replace(/!\[.*]\(/g, "").replace(/\)/, "")
this.logger.debug("src=>", src)

let newImg
if (inSiyuan()) {
const imageBase64WithURI = await imageToBase64({ uri: src })
newImg = imageBase64WithURI?.base64 ?? "no pic"
} else {
const middlewareUrl = getEnvOrDefault(
"VITE_MIDDLEWARE_URL",
"/api/middleware"
)
const middleApiUrl = middlewareUrl + "/imageToBase64"

const data = {
fetchParams: {
imgUrl: src,
},
}

const middleFetchOption = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
}

this.logger.debug("middleApiUrl=>", middleApiUrl)
this.logger.debug("middleFetchOption=>", middleFetchOption)

const response: Response = await fetch(middleApiUrl, middleFetchOption)
const resJson = await response.json()
this.logger.debug("resJson=>", resJson)
newImg = resJson?.body?.base64str ?? "parse error"
}

newImg = appendStr(
'<img src="data:image/png;base64,',
newImg,
'" alt="base64Image"/>'
)
newcontent = newcontent.replace(match, newImg)
}

return newcontent
}
// public async replaceImagesWithBase64(content: string): Promise<string> {
// let newcontent = content
//
// const imgRegex = /!\[.*]\((http|https):\/.*\/.*\)/g
// const matches = newcontent.match(imgRegex)
// // 没有图片,无需处理
// if (matches == null || matches.length === 0) {
// return newcontent
// }
//
// for (let i = 0; i < matches.length; i++) {
// const match = matches[i]
// this.logger.debug("img=>", match)
//
// const src = match.replace(/!\[.*]\(/g, "").replace(/\)/, "")
// this.logger.debug("src=>", src)
//
// let newImg
// if (inSiyuan()) {
// const imageBase64WithURI = await imageToBase64({ uri: src })
// newImg = imageBase64WithURI?.base64 ?? "no pic"
// } else {
// const middlewareUrl = getEnvOrDefault(
// "VITE_MIDDLEWARE_URL",
// "/api/middleware"
// )
// const middleApiUrl = middlewareUrl + "/imageToBase64"
//
// const data = {
// fetchParams: {
// imgUrl: src,
// },
// }
//
// const middleFetchOption = {
// method: "POST",
// headers: {
// "Content-Type": "application/json",
// },
// body: JSON.stringify(data),
// }
//
// this.logger.debug("middleApiUrl=>", middleApiUrl)
// this.logger.debug("middleFetchOption=>", middleFetchOption)
//
// const response: Response = await fetch(middleApiUrl, middleFetchOption)
// const resJson = await response.json()
// this.logger.debug("resJson=>", resJson)
// newImg = resJson?.body?.base64str ?? "parse error"
// }
//
// newImg = appendStr(
// '<img src="data:image/png;base64,',
// newImg,
// '" alt="base64Image"/>'
// )
// newcontent = newcontent.replace(match, newImg)
// }
//
// return newcontent
// }

/**
* 解析图片块为图片链接
Expand Down
7 changes: 2 additions & 5 deletions utils/platform/commonblog/commonblogApi.ts
Expand Up @@ -23,7 +23,6 @@
* questions.
*/

import { getEnvOrDefault } from "~/utils/envUtil"
import { Logger } from "loglevel"
import { LogFactory } from "~/utils/logUtil"
import {
Expand All @@ -33,6 +32,7 @@ import {
import { getWidgetId } from "~/utils/platform/siyuan/siyuanUtil"
import { isEmptyString } from "~/utils/util"
import { isElectron, isLocalhost } from "~/utils/browserUtil"
import { getSiyuanCfg } from "~/utils/platform/siyuan/siYuanConfig"

export class CommonblogApi {
protected logger: Logger
Expand All @@ -54,10 +54,7 @@ export class CommonblogApi {
fetchOptions: RequestInit,
formJson?: any[]
): Promise<Response> {
const middlewareUrl = getEnvOrDefault(
"VITE_MIDDLEWARE_URL",
"/api/middleware"
)
const middlewareUrl = getSiyuanCfg().middlewareUrl
const middleApiUrl = middlewareUrl + "/fetch"
this.logger.debug("apiUrl=>", apiUrl)

Expand Down

0 comments on commit 8b8f466

Please sign in to comment.