/
Lifecycle.ts
155 lines (143 loc) · 5.13 KB
/
Lifecycle.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
/*
* GNU GENERAL PUBLIC LICENSE
* Version 3, 29 June 2007
*
* Copyright (C) 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 { EventEmitter } from "../utils/nodePolyfill"
import { ILifecyclePlugins, IPicGo, IPlugin, Undefinable } from "../types"
import { ILogger } from "zhi-lib-base"
import { createContext } from "../utils/createContext"
import { IBuildInEvent } from "../utils/enums"
export class Lifecycle extends EventEmitter {
private readonly ctx: IPicGo
private readonly logger: ILogger
constructor(ctx: IPicGo) {
super()
this.ctx = ctx
this.logger = this.ctx.getLogger("lifecycle")
this.logger.debug("lifecycle is inited")
}
async start(input: any[]): Promise<IPicGo> {
// ensure every upload process has an unique context
const ctx = createContext(this.ctx)
try {
// images input
if (!Array.isArray(input)) {
throw new Error("Input must be an array.")
}
ctx.input = input
ctx.output = []
// lifecycle main
await this.beforeTransform(ctx)
await this.doTransform(ctx)
await this.beforeUpload(ctx)
await this.doUpload(ctx)
await this.afterUpload(ctx)
return ctx
} catch (e: any) {
ctx.log.warn(IBuildInEvent.FAILED)
ctx.emit(IBuildInEvent.UPLOAD_PROGRESS, -1)
ctx.emit(IBuildInEvent.FAILED, e)
ctx.log.error(e)
// if (ctx.getConfig<Undefinable<string>>("debug")) {
// }
// should throw error to stop the process
throw e
// return ctx
}
}
private async beforeTransform(ctx: IPicGo): Promise<IPicGo> {
ctx.emit(IBuildInEvent.UPLOAD_PROGRESS, 0)
ctx.emit(IBuildInEvent.BEFORE_TRANSFORM, ctx)
ctx.log.info("Before transform")
await this.handlePlugins(ctx.helper.beforeTransformPlugins, ctx)
return ctx
}
private async doTransform(ctx: IPicGo): Promise<IPicGo> {
ctx.emit(IBuildInEvent.UPLOAD_PROGRESS, 30)
const type = ctx.getConfig<Undefinable<string>>("picBed.transformer") || "path"
let currentTransformer = type
let transformer = ctx.helper.transformer.get(type)
if (!transformer) {
transformer = ctx.helper.transformer.get("path")
currentTransformer = "path"
ctx.log.warn(`Can't find transformer - ${type}, switch to default transformer - path`)
}
ctx.log.info(`Transforming... Current transformer is [${currentTransformer}]`)
await transformer?.handle(ctx)
return ctx
}
private async beforeUpload(ctx: IPicGo): Promise<IPicGo> {
ctx.emit(IBuildInEvent.UPLOAD_PROGRESS, 60)
ctx.log.info("Before upload")
ctx.emit(IBuildInEvent.BEFORE_UPLOAD, ctx)
await this.handlePlugins(ctx.helper.beforeUploadPlugins, ctx)
return ctx
}
private async doUpload(ctx: IPicGo): Promise<IPicGo> {
let type =
ctx.getConfig<Undefinable<string>>("picBed.uploader") ||
ctx.getConfig<Undefinable<string>>("picBed.current") ||
"smms"
let uploader = ctx.helper.uploader.get(type)
let currentTransformer = type
if (!uploader) {
type = "smms"
currentTransformer = "smms"
uploader = ctx.helper.uploader.get("smms")
ctx.log.warn(`Can't find uploader - ${type}, switch to default uploader - smms`)
}
ctx.log.info(`Uploading... Current uploader is [${currentTransformer}]`)
await uploader?.handle(ctx)
for (const outputImg of ctx.output) {
outputImg.type = type
}
return ctx
}
private async afterUpload(ctx: IPicGo): Promise<IPicGo> {
ctx.emit(IBuildInEvent.AFTER_UPLOAD, ctx)
ctx.emit(IBuildInEvent.UPLOAD_PROGRESS, 100)
await this.handlePlugins(ctx.helper.afterUploadPlugins, ctx)
let msg = ""
const length = ctx.output.length
for (let i = 0; i < length; i++) {
if (typeof ctx.output[i].imgUrl !== "undefined") {
msg += ctx.output[i].imgUrl!
if (i !== length - 1) {
msg += "\n"
}
}
delete ctx.output[i].base64Image
delete ctx.output[i].buffer
}
ctx.emit(IBuildInEvent.FINISHED, ctx)
if (msg === "") {
ctx.log.warn("[after-upload] image upload occured an error, please read log for details")
throw new Error("image upload occured an error, please read log for details")
} else {
ctx.log.info(`[after-upload] upload finishied => \n${msg}`)
}
return ctx
}
// ===================================================================================================================
private async handlePlugins(lifeCyclePlugins: ILifecyclePlugins, ctx: IPicGo): Promise<IPicGo> {
const plugins = lifeCyclePlugins.getList()
const pluginNames = lifeCyclePlugins.getIdList()
const lifeCycleName = lifeCyclePlugins.getName()
await Promise.all(
plugins.map(async (plugin: IPlugin, index: number) => {
try {
ctx.log.info(`${lifeCycleName}: ${pluginNames[index]} running`)
await plugin.handle(ctx)
} catch (e) {
ctx.log.error(`${lifeCycleName}: ${pluginNames[index]} error`)
throw e
}
})
)
return ctx
}
}