-
Notifications
You must be signed in to change notification settings - Fork 80
/
PicGo.ts
198 lines (183 loc) · 5.66 KB
/
PicGo.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
import fs from 'fs-extra'
import path from 'path'
import { EventEmitter } from 'events'
import { homedir } from 'os'
import Commander from '../lib/Commander'
import Logger from '../lib/Logger'
import Lifecycle from './Lifecycle'
import LifecyclePlugins from '../lib/LifecyclePlugins'
import uploaders from '../plugins/uploader'
import transformers from '../plugins/transformer'
import PluginLoader from '../lib/PluginLoader'
import { get, set, unset } from 'lodash'
import { IHelper, IImgInfo, IConfig, IPicGo, IStringKeyMap, IPicGoPlugin } from '../types'
import getClipboardImage from '../utils/getClipboardImage'
import Request from '../lib/Request'
import DB from '../utils/db'
import PluginHandler from '../lib/PluginHandler'
import { IBuildInEvent } from '../utils/enum'
class PicGo extends EventEmitter implements IPicGo {
private config!: IConfig
private lifecycle!: Lifecycle
private db!: DB
configPath: string
baseDir!: string
helper!: IHelper
log: Logger
cmd: Commander
output: IImgInfo[]
input: any[]
pluginLoader!: PluginLoader
pluginHandler: PluginHandler
Request!: Request
constructor (configPath: string = '') {
super()
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.log = new Logger(this)
this.cmd = new Commander(this)
this.pluginHandler = new PluginHandler(this)
this.initConfig()
this.init()
}
setCurrentPluginName (name: string): void {
LifecyclePlugins.currentPlugin = name
}
private initConfigPath (): void {
if (this.configPath === '') {
this.configPath = homedir() + '/.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 = fs.pathExistsSync(this.configPath)
if (!exist) {
fs.ensureFileSync(`${this.configPath}`)
}
}
private initConfig (): void {
this.db = new DB(this)
this.config = this.db.read().value()
}
private init (): void {
try {
this.Request = new Request(this)
this.pluginLoader = new PluginLoader(this)
// load self plugins
this.setCurrentPluginName('picgo')
uploaders(this)
transformers(this)
this.setCurrentPluginName('')
// load third-party plugins
this.pluginLoader.load()
this.lifecycle = new Lifecycle(this)
} catch (e) {
this.emit(IBuildInEvent.UPLOAD_PROGRESS, -1)
this.log.error(e)
throw e
}
}
/** register command-line commands
please manually remove listeners for avoiding listeners memory leak */
registerCommands (): void {
if (this.configPath !== '') {
this.cmd.init()
this.cmd.loadCommands()
}
}
/** get config by property path, return full config if `name` is not provided */
getConfig<T> (name?: string): T {
if (!name) {
return this.config as unknown as T
} else {
return get(this.config, name)
}
}
/** save to db */
saveConfig (config: object): void {
this.setConfig(config)
this.db.saveConfig(config)
}
/** remove from db */
removeConfig (key: string, propName: string): void {
if (!key || !propName) return
this.unsetConfig(key, propName)
this.db.unset(key, propName)
}
// set config for ctx but will not be saved to db
// it's more lightweight
setConfig (config: IStringKeyMap<any>): void {
Object.keys(config).forEach((name: string) => {
set(this.config, name, config[name])
})
}
// unset config for ctx but won't be saved to db
unsetConfig (key: string, propName: string): void {
if (!key || !propName) return
unset(this.getConfig(key), propName)
}
/**
* for node project adding a plugin by a simple way
*/
addPlugin (name: string, plugin: IPicGoPlugin): void {
if (!name || !plugin || (typeof plugin !== 'function')) {
this.log.warn('Please provide valid plugin')
return
}
try {
plugin(this).register()
} catch (e) {
this.log.warn('Please provide valid plugin')
this.log.error(e)
}
}
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, isExistFile } = await getClipboardImage(this)
if (imgPath === 'no image') {
throw new Error('image not found in clipboard')
} else {
this.once('failed', () => {
if (!isExistFile) {
// 删除 picgo 生成的图片文件,例如 `~/.picgo/20200621205720.png`
fs.remove(imgPath).catch((e) => { this.log.error(e) })
}
})
this.once('finished', () => {
if (!isExistFile) {
fs.remove(imgPath).catch((e) => { this.log.error(e) })
}
})
await this.lifecycle.start([imgPath])
return this.output
}
} catch (e) {
this.log.error(e)
this.emit(IBuildInEvent.FAILED, e)
throw e
}
} else {
// upload from path
await this.lifecycle.start(input)
return this.output
}
}
}
export default PicGo