/
UniversalPicGo.ts
254 lines (235 loc) · 7.42 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
/*
* 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 { PluginLoader } from "../lib/PluginLoader"
import { LifecyclePlugins } from "../lib/LifecyclePlugins"
import { PluginHandler } from "../lib/PluginHandler"
import _ from "lodash-es"
import getClipboardImage from "../utils/getClipboardImage"
import { IBuildInEvent } from "../utils/enums"
import DB from "../utils/db"
import { hasNodeEnv, win } from "universal-picgo-store"
import { ensureFileSync, pathExistsSync } from "../utils/nodeUtils"
import { I18nManager } from "../i18n"
import { getBrowserDirectoryPath } from "../utils/browserUtils"
/*
* 通用 PicGO 对象定义
*
* @version 1.6.0
* @since 1.4.5
*/
class UniversalPicGo extends EventEmitter implements IPicGo {
private _config!: IConfig
private lifecycle!: Lifecycle
private db!: DB
private _pluginLoader!: PluginLoader
configPath: string
baseDir!: string
helper!: IHelper
log: ILogger
// cmd: Commander
output: IImgInfo[]
input: any[]
pluginHandler: PluginHandler
i18n!: II18nManager
VERSION: string = process.env.PICGO_VERSION ?? "unknown"
// GUI_VERSION?: string
get pluginLoader(): IPluginLoader {
return this._pluginLoader
}
constructor(configPath = "", isDev?: boolean) {
super()
this.log = simpleLogger("universal-picgo-api", "universal-picgo", isDev ?? false)
this.configPath = configPath
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.cmd = new Commander(this)
this.pluginHandler = new PluginHandler(this)
this.initConfig()
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
}
}
// registerCommands(): void {
// if (this.configPath !== "") {
// this.cmd.init()
// this.cmd.loadCommands()
// }
// }
getConfig<T>(name?: string): T {
if (!name) {
return this._config as unknown as T
} else {
return _.get(this._config, name)
}
}
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 (!shouldKeepAfterUploading) {
// 删除 picgo 生成的图片文件,例如 `~/.picgo/20200621205720.png`
// fs.remove(imgPath).catch((e) => {
// this.log.error(e)
// })
}
})
this.once("finished", () => {
if (!shouldKeepAfterUploading) {
// fs.remove(imgPath).catch((e) => {
// 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 initConfigPath(): void {
this.log.debug("win =>", win)
this.log.info(`hasNodeEnv => ${hasNodeEnv}`)
if (hasNodeEnv) {
const os = win.require("os")
const fs = win.fs
const path = win.require("path")
const { homedir } = os
if (this.configPath === "") {
this.configPath = homedir() + "/.universal-picgo/config.json"
}
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 {
if (this.configPath === "") {
this.baseDir = ""
this.configPath = `universal-picgo-config.json`
} else {
// 模拟 path.dirname 的功能,获取路径的目录部分赋值给 baseDir
this.baseDir = getBrowserDirectoryPath(this.configPath)
}
}
}
private initConfig(): void {
this.db = new DB(this)
this._config = this.db.read(true) as IConfig
}
private init(): void {
try {
// init 18n at first
this.i18n = new I18nManager(this)
} catch (e: any) {
this.emit(IBuildInEvent.UPLOAD_PROGRESS, -1)
this.log.error(e)
throw e
}
}
}
export { UniversalPicGo }