/
UniversalPicGo.ts
298 lines (275 loc) · 8.97 KB
/
UniversalPicGo.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
/*
* GNU GENERAL PUBLIC LICENSE
* Version 3, 29 June 2007
*
* Copyright (C) 2022-2024 Terwer, Inc. <https://terwer.space/>
* Everyone is permitted to copy and distribute verbatim copies
* of this license document, but changing it is not allowed.
*/
import { ILogger, simpleLogger } from "zhi-lib-base"
import { EventEmitter } from "../utils/nodePolyfill"
import {
IConfig,
IHelper,
II18nManager,
IImgInfo,
IPicGo,
IPicGoPlugin,
IPicGoPluginInterface,
IPluginLoader,
IStringKeyMap,
} from "../types"
import { Lifecycle } from "./Lifecycle"
import uploaders from "../plugins/uploader"
import transformers from "../plugins/transformer"
import { PluginLoader } from "../lib/PluginLoader"
import { LifecyclePlugins, setCurrentPluginName } from "../lib/LifecyclePlugins"
import { PluginHandler } from "../lib/PluginHandler"
import _ from "lodash-es"
import getClipboardImage from "../utils/getClipboardImage"
import { IBuildInEvent, IBusEvent } from "../utils/enums"
import ConfigDb from "../db/config"
import { hasNodeEnv, win } from "universal-picgo-store"
import { ensureFileSync, ensureFolderSync, pathExistsSync } from "../utils/nodeUtils"
import { I18nManager } from "../i18n"
import { browserPathJoin, getBrowserDirectoryPath } from "../utils/browserUtils"
import { isConfigKeyInBlackList, isInputConfigValid } from "../utils/common"
import { eventBus } from "../utils/eventBus"
import { PicGoRequestWrapper } from "../lib/PicGoRequest"
/*
* 通用 PicGO 对象定义
*
* @version 1.6.0
* @since 1.4.5
*/
class UniversalPicGo extends EventEmitter implements IPicGo {
private _config!: IConfig
private lifecycle!: Lifecycle
private db!: ConfigDb
private _pluginLoader!: PluginLoader
configPath: string
baseDir!: string
pluginBaseDir!: string
helper!: IHelper
log: ILogger
output: IImgInfo[]
input: any[]
pluginHandler: PluginHandler
requestWrapper: PicGoRequestWrapper
i18n!: II18nManager
VERSION: string = process.env.PICGO_VERSION ?? "unknown"
private readonly isDev: boolean
get pluginLoader(): IPluginLoader {
return this._pluginLoader
}
public getLogger(name?: string): ILogger {
return simpleLogger(name ?? "universal-picgo", "universal-picgo", this.isDev)
}
get request(): PicGoRequestWrapper["PicGoRequest"] {
return this.requestWrapper.PicGoRequest.bind(this.requestWrapper)
}
constructor(configPath?: string, pluginBaseDir?: string, isDev?: boolean) {
super()
this.isDev = isDev ?? false
this.log = this.getLogger()
this.configPath = configPath ?? ""
this.pluginBaseDir = pluginBaseDir ?? ""
this.output = []
this.input = []
this.helper = {
transformer: new LifecyclePlugins("transformer"),
uploader: new LifecyclePlugins("uploader"),
beforeTransformPlugins: new LifecyclePlugins("beforeTransformPlugins"),
beforeUploadPlugins: new LifecyclePlugins("beforeUploadPlugins"),
afterUploadPlugins: new LifecyclePlugins("afterUploadPlugins"),
}
this.initConfigPath()
this.initConfig()
this.pluginHandler = new PluginHandler(this)
this.requestWrapper = new PicGoRequestWrapper(this)
this.init()
this.log.info("UniversalPicGo inited")
}
/**
* easily mannually load a plugin
* if provide plugin name, will register plugin by name
* or just instantiate a plugin
*/
use(plugin: IPicGoPlugin, name?: string): IPicGoPluginInterface {
if (name) {
this.pluginLoader.registerPlugin(name, plugin)
return this.pluginLoader.getPlugin(name)!
} else {
const pluginInstance = plugin(this)
return pluginInstance
}
}
getConfig<T>(name?: string, defaultValue?: any): T {
if (!name) {
return this._config as unknown as T
} else {
return _.get(this._config, name, defaultValue)
}
}
saveConfig(config: IStringKeyMap<any>): void {
if (!isInputConfigValid(config)) {
this.log.warn("the format of config is invalid, please provide object")
return
}
this.setConfig(config)
this.db.saveConfig(config)
}
removeConfig(key: string, propName: string): void {
if (!key || !propName) return
if (isConfigKeyInBlackList(key)) {
this.log.warn(`the config.${key} can't be removed`)
return
}
this.unsetConfig(key, propName)
this.db.unset(key, propName)
}
setConfig(config: IStringKeyMap<any>): void {
if (!isInputConfigValid(config)) {
this.log.warn("the format of config is invalid, please provide object")
return
}
Object.keys(config).forEach((name: string) => {
if (isConfigKeyInBlackList(name)) {
this.log.warn(`the config.${name} can't be modified`)
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete config[name]
}
_.set(this._config, name, config[name])
eventBus.emit(IBusEvent.CONFIG_CHANGE, {
configName: name,
value: config[name],
})
})
}
unsetConfig(key: string, propName: string): void {
if (!key || !propName) return
if (isConfigKeyInBlackList(key)) {
this.log.warn(`the config.${key} can't be unset`)
return
}
_.unset(this.getConfig(key), propName)
}
async upload(input?: any[]): Promise<IImgInfo[] | Error> {
if (this.configPath === "") {
this.log.error("The configuration file only supports JSON format.")
return []
}
// upload from clipboard
if (input === undefined || input.length === 0) {
try {
const { imgPath, shouldKeepAfterUploading } = await getClipboardImage(this)
if (imgPath === "no image") {
throw new Error("image not found in clipboard")
} else {
this.once(IBuildInEvent.FAILED, () => {
if (hasNodeEnv) {
const fs = win.fs
if (!shouldKeepAfterUploading) {
// 删除 picgo 生成的图片文件,例如 `~/.picgo/20200621205720.png`
fs.promises.rm(imgPath).catch((e: any) => {
this.log.error(e)
})
}
}
})
this.once("finished", () => {
if (hasNodeEnv) {
const fs = win.fs
if (!shouldKeepAfterUploading) {
fs.promises.rm(imgPath).catch((e: any) => {
this.log.error(e)
})
}
}
})
const { output } = await this.lifecycle.start([imgPath])
return output
}
} catch (e) {
this.emit(IBuildInEvent.FAILED, e)
throw e
}
} else {
// upload from path
const { output } = await this.lifecycle.start(input)
return output
}
}
// ===================================================================================================================
private getDefautBaseDir(): string {
if (hasNodeEnv) {
const os = win.require("os")
const fs = win.fs
const path = win.require("path")
const { homedir } = os
const dir = path.join(homedir(), ".universal-picgo")
ensureFolderSync(fs, dir)
return dir
} else {
return "universal-picgo"
}
}
private initConfigPath(): void {
if (this.configPath === "") {
this.baseDir = this.getDefautBaseDir()
if (hasNodeEnv) {
const path = win.require("path")
this.configPath = path.join(this.baseDir, "picgo.cfg.json")
} else {
this.configPath = browserPathJoin(this.baseDir, "picgo.cfg.json")
}
} else {
if (hasNodeEnv) {
const fs = win.fs
const path = win.require("path")
if (path.extname(this.configPath).toUpperCase() !== ".JSON") {
this.configPath = ""
throw Error("The configuration file only supports JSON format.")
}
this.baseDir = path.dirname(this.configPath)
const exist = pathExistsSync(fs, path, this.configPath)
if (!exist) {
ensureFileSync(fs, path, `${this.configPath}`)
}
} else {
this.baseDir = getBrowserDirectoryPath(this.configPath)
}
}
if (this.pluginBaseDir === "") {
this.pluginBaseDir = this.getDefautBaseDir()
}
this.log.debug("win =>", win)
this.log.info(`hasNodeEnv => ${hasNodeEnv}`)
this.log.info(`this.baseDir => ${this.baseDir}`)
this.log.info(`this.pluginBaseDir => ${this.pluginBaseDir}`)
}
private initConfig(): void {
this.db = new ConfigDb(this)
this._config = this.db.read(true) as IConfig
}
private init(): void {
try {
// init 18n at first
this.i18n = new I18nManager(this)
this._pluginLoader = new PluginLoader(this)
// load self plugins
setCurrentPluginName("picgo")
uploaders(this).register(this)
transformers(this).register(this)
setCurrentPluginName("")
// load third-party plugins
this._pluginLoader.load()
this.lifecycle = new Lifecycle(this)
} catch (e: any) {
this.emit(IBuildInEvent.UPLOAD_PROGRESS, -1)
this.log.error(e)
throw e
}
}
}
export { UniversalPicGo }