forked from chavyleung/scripts
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Env.js
299 lines (279 loc) · 9.49 KB
/
Env.js
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
function Env(name, opts) {
return new (class {
constructor(name, opts) {
this.name = name
this.data = null
this.dataFile = 'box.dat'
this.logs = []
this.logSeparator = '\n'
this.startTime = new Date().getTime()
Object.assign(this, opts)
this.log('', `🔔${this.name}, 开始!`)
}
isNode() {
return 'undefined' !== typeof module && !!module.exports
}
isQuanX() {
return 'undefined' !== typeof $task
}
isSurge() {
return 'undefined' !== typeof $httpClient
}
isLoon() {
return 'undefined' !== typeof $loon
}
loaddata() {
if (this.isNode) {
this.fs = this.fs ? this.fs : require('fs')
this.path = this.path ? this.path : require('path')
const curDirDataFilePath = this.path.resolve(this.dataFile)
const rootDirDataFilePath = this.path.resolve(process.cwd(), this.dataFile)
const isCurDirDataFile = this.fs.existsSync(curDirDataFilePath)
const isRootDirDataFile = !isCurDirDataFile && this.fs.existsSync(rootDirDataFilePath)
if (isCurDirDataFile || isRootDirDataFile) {
const datPath = isCurDirDataFile ? curDirDataFilePath : rootDirDataFilePath
try {
return JSON.parse(this.fs.readFileSync(datPath))
} catch {
return {}
}
} else return {}
} else return {}
}
writedata() {
if (this.isNode) {
this.fs = this.fs ? this.fs : require('fs')
this.path = this.path ? this.path : require('path')
const curDirDataFilePath = this.path.resolve(this.dataFile)
const rootDirDataFilePath = this.path.resolve(process.cwd(), this.dataFile)
const isCurDirDataFile = this.fs.existsSync(curDirDataFilePath)
const isRootDirDataFile = !isCurDirDataFile && this.fs.existsSync(rootDirDataFilePath)
const jsondata = JSON.stringify(this.data)
if (isCurDirDataFile) {
this.fs.writeFileSync(curDirDataFilePath, jsondata)
} else if (isRootDirDataFile) {
this.fs.writeFileSync(rootDirDataFilePath, jsondata)
} else {
this.fs.writeFileSync(curDirDataFilePath, jsondata)
}
}
}
lodash_get(source, path, defaultValue = undefined) {
const paths = path.replace(/\[(\d+)\]/g, '.$1').split('.')
let result = source
for (const p of paths) {
result = Object(result)[p]
if (result === undefined) {
return defaultValue
}
}
return result
}
lodash_set(obj, path, value) {
if (Object(obj) !== obj) return obj
if (!Array.isArray(path)) path = path.toString().match(/[^.[\]]+/g) || []
path.slice(0, -1).reduce((a, c, i) => (Object(a[c]) === a[c] ? a[c] : (a[c] = Math.abs(path[i + 1]) >> 0 === +path[i + 1] ? [] : {})), obj)[path[path.length - 1]] = value
return obj
}
getdata(key) {
let val = this.getval(key)
// 如果以 @
if (/^@/.test(key)) {
const [, objkey, paths] = /^@(.*?)\.(.*?)$/.exec(key)
const objval = objkey ? this.getval(objkey) : ''
if (objval) {
try {
const objedval = JSON.parse(objval)
val = objedval ? this.lodash_get(objedval, paths, '') : val
} catch (e) {
val = ''
}
}
}
return val
}
setdata(val, key) {
let issuc = false
if (/^@/.test(key)) {
const [, objkey, paths] = /^@(.*?)\.(.*?)$/.exec(key)
const objdat = this.getval(objkey)
const objval = objkey ? (objdat === 'null' ? null : objdat || '{}') : '{}'
try {
const objedval = JSON.parse(objval)
this.lodash_set(objedval, paths, val)
issuc = this.setval(JSON.stringify(objedval), objkey)
console.log(`${objkey}: ${JSON.stringify(objedval)}`)
} catch {
const objedval = {}
this.lodash_set(objedval, paths, val)
issuc = this.setval(JSON.stringify(objedval), objkey)
console.log(`${objkey}: ${JSON.stringify(objedval)}`)
}
} else {
issuc = $.setval(val, key)
}
return issuc
}
getval(key) {
if (this.isSurge() || this.isLoon()) {
return $persistentStore.read(key)
} else if (this.isQuanX()) {
return $prefs.valueForKey(key)
} else if (this.isNode()) {
this.data = this.loaddata()
return this.data[key]
} else {
return (this.data && this.data[key]) || null
}
}
setval(val, key) {
if (this.isSurge() || this.isLoon()) {
return $persistentStore.write(val, key)
} else if (this.isQuanX()) {
return $prefs.setValueForKey(val, key)
} else if (this.isNode()) {
this.data = this.loaddata()
this.data[key] = val
this.writedata()
return true
} else {
return (this.data && this.data[key]) || null
}
}
initGotEnv(opts) {
this.got = this.got ? this.got : require('got')
this.cktough = this.cktough ? this.cktough : require('tough-cookie')
this.ckjar = this.ckjar ? this.ckjar : new this.cktough.CookieJar()
if (opts) {
opts.headers = opts.headers ? opts.headers : {}
if (undefined === opts.headers.Cookie && undefined === opts.cookieJar) {
opts.cookieJar = this.ckjar
}
}
}
get(opts, callback = () => {}) {
if (opts.headers) {
delete opts.headers['Content-Type']
delete opts.headers['Content-Length']
}
if (this.isSurge() || this.isLoon()) {
$httpClient.get(opts, (err, resp, body) => {
if (!err && resp) {
resp.body = body
resp.statusCode = resp.status
callback(err, resp, body)
}
})
} else if (this.isQuanX()) {
$task.fetch(opts).then(
(resp) => {
const { statusCode: status, statusCode, headers, body } = resp
callback(null, { status, statusCode, headers, body }, body)
},
(err) => callback(err)
)
} else if (this.isNode()) {
this.initGotEnv(opts)
this.got(opts)
.on('redirect', (resp, nextOpts) => {
try {
const ck = resp.headers['set-cookie'].map(this.cktough.Cookie.parse).toString()
this.ckjar.setCookieSync(ck, null)
nextOpts.cookieJar = this.ckjar
} catch (e) {
this.logErr(e)
}
// this.ckjar.setCookieSync(resp.headers['set-cookie'].map(Cookie.parse).toString())
})
.then(
(resp) => {
const { statusCode: status, statusCode, headers, body } = resp
callback(null, { status, statusCode, headers, body }, body)
},
(err) => callback(err)
)
}
}
post(opts, callback = () => {}) {
// 如果指定了请求体, 但没指定`Content-Type`, 则自动生成
if (opts.body && opts.headers && !opts.headers['Content-Type']) {
opts.headers['Content-Type'] = 'application/x-www-form-urlencoded'
}
delete opts.headers['Content-Length']
if (this.isSurge() || this.isLoon()) {
$httpClient.post(opts, (err, resp, body) => {
if (!err && resp) {
resp.body = body
resp.statusCode = resp.status
callback(err, resp, body)
}
})
} else if (this.isQuanX()) {
opts.method = 'POST'
$task.fetch(opts).then(
(resp) => {
const { statusCode: status, statusCode, headers, body } = resp
callback(null, { status, statusCode, headers, body }, body)
},
(err) => callback(err)
)
} else if (this.isNode()) {
this.initGotEnv(opts)
const { url, ..._opts } = opts
this.got.post(url, _opts).then(
(resp) => {
const { statusCode: status, statusCode, headers, body } = resp
callback(null, { status, statusCode, headers, body }, body)
},
(err) => callback(err)
)
}
}
/**
* 系统通知
*
* @param {*} title 标题
* @param {*} subt 副标题
* @param {*} desc 通知详情
* @param {*} opts 通知参数
*/
msg(title = name, subt = '', desc = '', opts) {
if (this.isSurge() || this.isLoon()) {
$notification.post(title, subt, desc, opts)
} else if (this.isQuanX()) {
$notify(title, subt, desc, opts)
}
this.logs.push('', '==============📣系统通知📣==============')
this.logs.push(title)
subt ? this.logs.push(subt) : ''
desc ? this.logs.push(desc) : ''
}
log(...logs) {
if (logs.length > 0) {
this.logs = [...this.logs, ...logs]
} else {
console.log(this.logs.join(this.logSeparator))
}
}
logErr(err, msg) {
const isPrintSack = !this.isSurge() && !this.isQuanX() && !this.isLoon()
if (!isPrintSack) {
$.log('', `❗️${this.name}, 错误!`, err.message)
} else {
$.log('', `❗️${this.name}, 错误!`, err.stack)
}
}
wait(time) {
return new Promise((resolve) => setTimeout(resolve, time))
}
done(val = null) {
const endTime = new Date().getTime()
const costTime = (endTime - this.startTime) / 1000
this.log('', `🔔${this.name}, 结束! 🕛 ${costTime} 秒`)
this.log()
if (this.isSurge() || this.isQuanX() || this.isLoon()) {
$done(val)
}
}
})(name, opts)
}