/
baseWebApi.ts
307 lines (286 loc) · 9.15 KB
/
baseWebApi.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/*
* 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 {
Attachment,
CategoryInfo,
ElectronCookie,
MediaObject,
Post,
TagInfo,
WebApi,
WebConfig,
YamlConvertAdaptor,
} from "zhi-blog-api"
import { PublisherAppInstance } from "~/src/publisherAppInstance.ts"
import { createAppLogger, ILogger } from "~/src/utils/appLogger.ts"
import { useProxy } from "~/src/composables/useProxy.ts"
import { BaseExtendApi } from "~/src/adaptors/base/baseExtendApi.ts"
import { JsonUtil, StrUtil } from "zhi-common"
import { useSiyuanDevice } from "~/src/composables/useSiyuanDevice.ts"
import { Base64 } from "js-base64"
import FormDataUtils from "~/src/utils/FormDataUtils.ts"
/**
* 网页授权统一封装基类
*
* @author terwer
* @version 0.9.0
* @since 0.9.0
*/
class BaseWebApi extends WebApi {
protected appInstance: PublisherAppInstance
protected logger: ILogger
protected cfg: WebConfig
protected readonly baseExtendApi: BaseExtendApi
private readonly isUseSiyuanProxy: boolean
private readonly proxyFetch: any
private readonly corsFetch: any
/**
* 初始化网页授权 API 适配器
*
* @param appInstance 应用实例
* @param cfg 配置项
*/
constructor(appInstance: PublisherAppInstance, cfg: WebConfig) {
super()
this.appInstance = appInstance
this.cfg = cfg
this.logger = createAppLogger("base-web-api")
this.baseExtendApi = new BaseExtendApi(this, cfg)
const { isUseSiyuanProxy, proxyFetch, corsFetch } = useProxy(cfg.middlewareUrl, cfg.corsAnywhereUrl)
this.isUseSiyuanProxy = isUseSiyuanProxy
this.proxyFetch = proxyFetch
this.corsFetch = corsFetch
}
public async checkAuth(): Promise<boolean> {
return true
}
public getPostPreviewUrl(postid: string): Promise<string> {
return this.getPreviewUrl(postid)
}
public async getCategories(keyword?: string): Promise<CategoryInfo[]> {
return this.baseExtendApi.getCategories(keyword)
}
public async getTags(): Promise<TagInfo[]> {
return this.baseExtendApi.getTags()
}
// web 适配器专有
public updateCfg(cfg: WebConfig) {
this.cfg = cfg
}
public async buildCookie(cookies: ElectronCookie[]): Promise<string> {
return cookies.map((cookie) => `${cookie.name}=${cookie.value}`).join(";")
}
public getYamlAdaptor(): YamlConvertAdaptor {
return null
}
public async preEditPost(post: Post, id?: string, publishCfg?: any): Promise<Post> {
return await this.baseExtendApi.preEditPost(post, id, publishCfg)
}
// 兼容的方法
public async newPost(post: Post, publish?: boolean): Promise<string> {
try {
const res = await this.addPost(post)
if (res.status !== "success") {
throw new Error("网页授权发布文章异常")
}
return res.post_id
} catch (e) {
throw e
}
}
public async newMediaObject(mediaObject: MediaObject, customHandler?: any): Promise<Attachment> {
const bits = mediaObject.bits
this.logger.debug("newMediaObject on baseWebApi =>", mediaObject)
const blob = new Blob([bits], { type: mediaObject.type })
const res = await this.uploadFile(blob as File, mediaObject.name)
return {
attachment_id: res?.id,
date_created_gmt: new Date(),
parent: 0,
link: res?.url,
title: mediaObject.name,
caption: "",
description: "",
metadata: {
width: 0,
height: 0,
file: "",
filesize: 0,
sizes: [],
},
type: mediaObject.type,
thumbnail: "",
id: res?.article_id,
file: mediaObject.name,
url: res.url,
}
}
// ===================================================================================================================
/**
* 默认添加 Cookie 的网页授权代理
*
* @param url - 请求的 URL
* @param headers - 请求的头部信息
* @param params - 请求的参数
* @param method - 请求的 HTTP 方法
* @param contentType - 请求的内容类型
* @param forceProxy - 是否强制使用代理
* @param payloadEncoding - 请求体的编码方式,默认为 text
* @param responseEncoding - 响应体的编码方式,默认为 text
*/
public async webProxyFetch(
url: string,
headers: any[] = [],
params: any = {},
method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH" = "GET",
contentType: string = "application/json",
forceProxy: boolean = false,
payloadEncoding:
| "text"
| "base64"
| "base64-std"
| "base64-url"
| "base32"
| "base32-std"
| "base32-hex"
| "hex" = "text",
responseEncoding:
| "text"
| "base64"
| "base64-std"
| "base64-url"
| "base32"
| "base32-std"
| "base32-hex"
| "hex" = "text"
) {
const header = headers.length > 0 ? headers[0] : {}
// 如果没有可用的 CORS 代理或者没有强制使用代理,使用默认的自动检测机制
if (this.isUseSiyuanProxy || (!this.isUseSiyuanProxy && forceProxy)) {
this.logger.info("Using legency web fetch")
// remove cors fetch header
delete header["x-cors-headers"]
const webHeaders = [
{
...header,
Cookie: this.cfg.password,
},
]
return await this.proxyFetch(
url,
webHeaders,
params,
method,
contentType,
forceProxy,
payloadEncoding,
responseEncoding
)
} else {
this.logger.info("Using cors web fetch")
const webHeaders = [
{
...header,
Cookie: this.cfg.password,
},
]
return this.corsFetch(url, webHeaders, params, method)
}
}
/**
* 默认添加 Cookie 的网页授权代理
*
* @param url - 请求的 URL
* @param headers - 请求的头部信息
* @param formData - 表单数据
* @param forceProxy - 是否强制使用代理
* @param payloadEncoding - 请求体的编码方式,默认为 text
* @param responseEncoding - 响应体的编码方式,默认为 text
* */
public async webFormFetch(
url: string,
headers: any[],
formData: FormData,
forceProxy: boolean = false,
payloadEncoding:
| "text"
| "base64"
| "base64-std"
| "base64-url"
| "base32"
| "base32-std"
| "base32-hex"
| "hex" = "text",
responseEncoding:
| "text"
| "base64"
| "base64-std"
| "base64-url"
| "base32"
| "base32-std"
| "base32-hex"
| "hex" = "text"
) {
// 如果没有可用的 CORS 代理或者没有强制使用代理,使用默认的自动检测机制
if (this.isUseSiyuanProxy || (!this.isUseSiyuanProxy && forceProxy)) {
this.logger.info("Using legency web formFetch")
const { isInSiyuanOrSiyuanNewWin } = useSiyuanDevice()
if (!isInSiyuanOrSiyuanNewWin() || forceProxy) {
const fetchResult = await this.webProxyFetch(
url,
headers,
formData,
"POST",
undefined,
forceProxy,
"base64",
"base64"
)
const resText = Base64.fromBase64(fetchResult.body)
const resJson = JsonUtil.safeParse<any>(resText, {} as any)
this.logger.debug("apiForm doFetch success, resJson=>", resJson)
return resJson
} else {
// get formata fetch
const doFetch = FormDataUtils.getFormDataFetch(this.appInstance)
// headers
const header = headers.length > 0 ? headers[0] : {}
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, header, formData)
this.logger.debug("apiForm doFetch success, resText =>", resText)
const resJson = JsonUtil.safeParse<any>(resText, {} as any)
return resJson
}
} else {
this.logger.info("Using cors-anywhere web formFetch")
return this.corsFetch(url, headers, formData, "POST")
}
}
// ================
// private methods
// ================
}
export { BaseWebApi }