-
Notifications
You must be signed in to change notification settings - Fork 46
/
pupuCheckIn.js
472 lines (457 loc) · 38.1 KB
/
pupuCheckIn.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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
/*
朴朴签到-lowking-v2.0.6
按下面配置完之后,手机朴朴短信登录获取token,下面配置只验证过surge的,其他的自行测试
⚠️只测试过surge没有其他app自行测试
************************
Surge 4.2.0+ 脚本配置(其他APP自行转换配置):
************************
[Script]
# > 朴朴签到
朴朴签到cookie = requires-body=1,type=http-response,pattern=https:\/\/cauth.pupuapi.com\/clientauth\/user\/verify_login,script-path=https://raw.githubusercontent.com/lowking/Scripts/master/pupu/pupuCheckIn.js
朴朴签到 = type=cron,cronexp="0 10 0 * * ?",wake-system=1,script-path=https://raw.githubusercontent.com/lowking/Scripts/master/pupu/pupuCheckIn.js
[MITM]
hostname = %APPEND% cauth.pupuapi.com
*/
const lk = new ToolKit(`朴朴签到`, `PuPuCheckIn`, {"httpApia": "ffff@192.168.8.117:6166"})
const pupuTokenKey = 'lkPuPuTokenKey'
let pupuToken = lk.getVal(pupuTokenKey)
const pupuRefreshTokenKey = 'lkPuPuRefreshTokenKey'
let pupuRefreshToken = lk.getVal(pupuRefreshTokenKey)
lk.userAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 15_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 D/C501C6D2-FAF6-4DA8-B65B-7B8B392901EB"
const storeId = "f8f0656f-d30e-497a-a536-e9edec17b74d"
const pupuSec = "lkPuPuSec"
const pupuMsec = "lkPuPuMsec"
const sec = lk.getVal(pupuSec, 59)
const msec = lk.getVal(pupuMsec, 0)
const pupuRunCountKey = 'pupuRunCount'
const pupuRunCount = lk.getVal(pupuRunCountKey, 2)
const checkSignInRepeatKey = 'pupuSignInRepeat'
const checkSignInRepeat = lk.getVal(checkSignInRepeatKey)
const todayAlreadyGetCouponIdsKey = 'pupuTodayAlreadyGetCouponIds'
let todayAlreadyGetCouponIds = `,${lk.getVal(todayAlreadyGetCouponIdsKey)},`
if(!lk.isExecComm) {
if (lk.isRequest()) {
getCookie()
lk.done()
} else {
lk.boxJsJsonBuilder({
"icons": [
"https://raw.githubusercontent.com/lowking/Scripts/master/doc/icon/pupua.png",
"https://raw.githubusercontent.com/lowking/Scripts/master/doc/icon/pupu.png"
],
"settings": [
{
"id": pupuTokenKey,
"name": "朴朴token",
"val": "",
"type": "text",
"desc": "朴朴token"
}, {
"id": pupuRefreshTokenKey,
"name": "朴朴refresh_token",
"val": "",
"type": "text",
"desc": "朴朴refresh_token"
}, {
"id": pupuSec,
"name": "抢券等待至xx秒",
"val": 59,
"type": "number",
"desc": "默认59s"
}, {
"id": pupuMsec,
"name": "抢券等待至xxx毫秒",
"val": 0,
"type": "number",
"desc": "默认0ms"
}, {
"id": pupuRunCountKey,
"name": "抢签到第一并发数",
"val": 2,
"type": "number",
"desc": "默认2"
}
],
"keys": [pupuTokenKey, pupuRefreshTokenKey]
}, {
"script_url": "https://github.com/lowking/Scripts/blob/master/pupu/pupuCheckIn.js",
"author": "@lowking",
"repo": "https://github.com/lowking/Scripts",
})
all()
}
}
function getCookie() {
if (lk.isMatch(/\/clientauth\/user\/verify_login/)) {
lk.log(`开始获取cookie`)
let data = lk.getResponseBody()
lk.log(`获取到的cookie:${data}`)
try {
data = data.o()
lk.setVal(pupuRefreshTokenKey, data.data["refresh_token"])
lk.appendNotifyInfo('🎉成功获取朴朴refresh_token,可以关闭相应脚本')
} catch (e) {
lk.appendNotifyInfo('❌获取朴朴token失败')
}
lk.msg('')
}
}
async function all() {
let hasNeedSendNotify = true
if (pupuRefreshToken == '') {
lk.execFail()
lk.appendNotifyInfo(`⚠️请先打开朴朴短信验证码登录获取refresh_token`)
} else {
await refreshToken()
let hasAlreadySignIn = await signIn()
lk.log(`已领取券:${todayAlreadyGetCouponIds}`)
let requestCount = await getCouponList()
// await share()
lk.log(`是否已经签到:${hasAlreadySignIn == 1}`)
lk.log(`请求领券次数:${requestCount}`)
hasNeedSendNotify = !(requestCount == 0 && hasAlreadySignIn == 1)
if (hasNeedSendNotify) {
await getScore()
}
}
if (hasNeedSendNotify) {
lk.msg(``)
}
lk.done()
}
function getCouponList() {
return new Promise((resolve, _reject) => {
const t = '获取券列表'
let requestCount = 0
let url = {
url: 'https://j1.pupuapi.com/client/coupon?type=1&store_id=' + storeId,
headers: {
Authorization: pupuToken,
"Content-Type": "application/json; charset=utf-8",
},
}
lk.get(url, async (error, _response, data) => {
try {
if (error) {
lk.execFail()
lk.appendNotifyInfo(`❌${t}失败,请稍后再试`)
} else {
let dataObj = data.o()
if (dataObj.errcode == 0) {
dataObj = dataObj.data
// 等待到整点执行
let now = new Date()
if (now.getMinutes() > 57) {
let preSec = -1
while (1) {
let nsec = now.getSeconds()
let nmsec = now.getMilliseconds()
if (nsec >= sec && nmsec >= msec || nsec < preSec) {
lk.log("跳出等待")
break
}
lk.log(`${nsec}.${nmsec}等待中。。。`)
preSec = nsec
await lk.sleep(50)
now = new Date()
}
}
let couponListFunc = []
for (let curCount = 0; curCount < pupuRunCount; curCount++) {
for (let i = 0; i < dataObj.items.length; i++) {
const item = dataObj.items[i];
lk.log(item.s())
if (todayAlreadyGetCouponIds.indexOf(`,${item["discount_id"]},`) != -1) {
lk.log(`该券今天已经领取,跳过`)
continue
}
requestCount++
couponListFunc.push(getCoupon(item["discount_id"], item["discount_group_id"], item["style_info"]["condition_amount_desc"], item["discount_amount"]/100))
}
}
await Promise.all(couponListFunc).then(res => {
res.sort()
res.reverse()
let preCounponName = ""
let toNextCoupon = false
let getResSet = new Set()
let todayAlreadyGetCouponIdSet = new Set()
for (let i = 0; i < res.length; i++) {
const ret = res[i];
let msg = ret.split("\n")
let counponName = msg[0]
let getRes = msg[1]
let discountId = msg[2]
if (counponName != preCounponName) {
toNextCoupon = false
getResSet.forEach((s) => {
lk.appendNotifyInfo(s)
})
getResSet = new Set()
lk.appendNotifyInfo(counponName)
}
if (getRes.indexOf("成功") != -1) {
toNextCoupon = true
if (todayAlreadyGetCouponIds.indexOf(`,${discountId},`) == -1) {
todayAlreadyGetCouponIdSet.add(discountId)
}
} else if (toNextCoupon) {
if (i >= res.length - 1) {
getResSet.forEach((s) => {
lk.appendNotifyInfo(s)
})
}
continue
}
getResSet.add(getRes)
preCounponName = counponName
if (i >= res.length - 1) {
getResSet.forEach((s) => {
lk.appendNotifyInfo(s)
})
}
}
if (todayAlreadyGetCouponIdSet.size > 0) {
lk.setVal(todayAlreadyGetCouponIdsKey, Array.from(todayAlreadyGetCouponIdSet).join(","))
}
})
} else {
lk.execFail()
lk.appendNotifyInfo(dataObj.errmsg)
}
}
} catch (e) {
lk.logErr(e)
lk.log(`朴朴返回数据:${data}`)
lk.execFail()
lk.appendNotifyInfo(`❌${t}错误,请带上日志联系作者,或稍后再试`)
} finally {
resolve(requestCount)
}
})
})
}
function getCoupon(discount, discountGroup, discountName, discountAmount) {
return new Promise((resolve, _reject) => {
const t = '抢券'
let url = {
url: 'https://j1.pupuapi.com/client/coupon/entity',
headers: {
Authorization: pupuToken,
"Content-Type": "application/json; charset=utf-8",
},
body: {
"discount": discount,
"time_type": 1,
"discount_group": discountGroup,
"store_id": storeId,
}.s(),
}
lk.post(url, (error, _response, data) => {
try {
if (error) {
lk.execFail()
lk.appendNotifyInfo(`❌${t}失败,请稍后再试`)
} else {
lk.log(data)
let dataObj = data.o()
if (dataObj.errcode == 0) {
resolve(`【${discountAmount}元-${discountName}】\n ${dataObj.data}\n${discount}`)
} else {
resolve(`【${discountAmount}元-${discountName}】\n ${dataObj.errmsg}\n${discount}`)
}
}
} catch (e) {
lk.logErr(e)
lk.log(`朴朴返回数据:${data}`)
lk.execFail()
lk.appendNotifyInfo(`❌${t}错误,请带上日志联系作者,或稍后再试`)
} finally {
resolve()
}
})
})
}
function refreshToken() {
return new Promise((resolve, _reject) => {
const t = '获取token'
let url = {
url: 'https://cauth.pupuapi.com/clientauth/user/refresh_token',
headers: {
"Content-Type": "application/json; charset=utf-8",
},
body: {
"refresh_token": pupuRefreshToken
}.s()
}
lk.put(url, (error, _response, data) => {
try {
if (error) {
lk.execFail()
lk.appendNotifyInfo(`❌${t}失败,请稍后再试`)
} else {
lk.log(data)
let dataObj = data.o()
if (dataObj.errcode == 0) {
dataObj = dataObj.data
pupuToken = `Bearer ${dataObj["access_token"]}`
pupuRefreshToken = dataObj["refresh_token"]
lk.setVal(pupuTokenKey, pupuToken)
lk.setVal(pupuRefreshTokenKey, pupuRefreshToken)
} else {
lk.execFail()
lk.appendNotifyInfo(dataObj.errmsg)
}
}
} catch (e) {
lk.logErr(e)
lk.log(`朴朴返回数据:${data}`)
lk.execFail()
lk.appendNotifyInfo(`❌${t}错误,请带上日志联系作者,或稍后再试`)
} finally {
resolve()
}
})
})
}
function getScore() {
return new Promise((resolve, _reject) => {
const t = '获取积分'
let url = {
url: 'https://j1.pupuapi.com/client/account/asserts',
headers: {
Authorization: pupuToken,
"User-Agent": lk.userAgent
}
}
lk.get(url, (error, _response, data) => {
try {
if (error) {
lk.execFail()
lk.appendNotifyInfo(`❌${t}失败,请稍后再试`)
} else {
let dataObj = data.o()
if (dataObj.errcode == 0) {
dataObj = dataObj.data
lk.prependNotifyInfo(`🎉${t}成功,当前积分:${dataObj.coin}`)
} else {
lk.execFail()
lk.appendNotifyInfo(dataObj.errmsg)
}
}
} catch (e) {
lk.logErr(e)
lk.log(`朴朴返回数据:${data}`)
lk.execFail()
lk.appendNotifyInfo(`❌${t}错误,请带上日志联系作者,或稍后再试`)
} finally {
resolve()
}
})
})
}
function signIn() {
return new Promise((resolve, _reject) => {
let nowString = lk.formatDate(new Date(), 'yyyyMMdd')
if (nowString == checkSignInRepeat) {
lk.prependNotifyInfo('今日已经签到,无法重复签到~~')
resolve(1)
return
}
const t = '签到'
let url = {
url: 'https://j1.pupuapi.com/client/game/sign/v2?city_zip=350100&supplement_id=',
headers: {
Authorization: pupuToken,
"User-Agent": lk.userAgent
}
}
lk.post(url, (error, _response, data) => {
try {
if (error) {
lk.execFail()
lk.appendNotifyInfo(`❌${t}失败,请稍后再试`)
} else {
let dataObj = data.o()
if (dataObj.errcode == 0) {
dataObj = dataObj.data
lk.prependNotifyInfo(`🎉${t}成功,获得【${dataObj['daily_sign_coin']}】积分`)
lk.setVal(checkSignInRepeatKey, nowString)
// 签到成功之后清除已领取券id
lk.setVal(todayAlreadyGetCouponIdsKey, "")
todayAlreadyGetCouponIds = ""
} else {
lk.execFail()
lk.prependNotifyInfo(dataObj.errmsg)
}
}
} catch (e) {
lk.logErr(e)
lk.log(`朴朴返回数据:${data}`)
lk.execFail()
lk.appendNotifyInfo(`❌${t}错误,请带上日志联系作者,或稍后再试`)
} finally {
resolve()
}
})
})
}
function share() {
return new Promise((resolve, _reject) => {
const t = '分享'
let url = {
url: 'https://j1.pupuapi.com/client/game/sign/share',
headers: {
Authorization: pupuToken,
"User-Agent": lk.userAgent
}
}
lk.post(url, (error, _response, data) => {
try {
if (error) {
lk.execFail()
lk.appendNotifyInfo(`❌${t}失败,请稍后再试`)
} else {
let dataObj = data.o()
if (dataObj.errcode == 0) {
dataObj = dataObj.data
lk.appendNotifyInfo(`🎉${t}成功`)
} else {
lk.execFail()
lk.appendNotifyInfo(dataObj.errmsg)
}
}
} catch (e) {
lk.logErr(e)
lk.log(`朴朴返回数据:${data}`)
lk.execFail()
lk.appendNotifyInfo(`❌${t}错误,请带上日志联系作者,或稍后再试`)
} finally {
resolve()
}
})
})
}
// * ToolKit v1.3.2 build 144
function ToolKit(scriptName,scriptId,options){class Request{constructor(tk){this.tk=tk}fetch(options,method="GET"){options=typeof options=="string"?{url:options}:options;let fetcher;switch(method){case"PUT":fetcher=this.put;break;case"POST":fetcher=this.post;break;default:fetcher=this.get}const doFetch=new Promise((resolve,reject)=>{fetcher.call(this,options,(error,resp,data)=>error?reject({error,resp,data}):resolve({error,resp,data}))}),delayFetch=(promise,timeout=5e3)=>Promise.race([promise,new Promise((_,reject)=>setTimeout(()=>reject(new Error("请求超时")),timeout))]);return options.timeout>0?delayFetch(doFetch,options.timeout):doFetch}async get(options){return this.fetch.call(this.tk,options)}async post(options){return this.fetch.call(this.tk,options,"POST")}async put(options){return this.fetch.call(this.tk,options,"PUT")}}return new class{constructor(scriptName,scriptId,options){Object.prototype.s=function(replacer,space){return typeof this=="string"?this:JSON.stringify(this,replacer,space)},Object.prototype.o=function(reviver){return JSON.parse(this,reviver)},this.userAgent=`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.2 Safari/605.1.15`,this.prefix=`lk`,this.name=scriptName,this.id=scriptId,this.req=new Request(this),this.data=null,this.dataFile=this.getRealPath(`${this.prefix}${this.id}.dat`),this.boxJsJsonFile=this.getRealPath(`${this.prefix}${this.id}.boxjs.json`),this.options=options,this.isExecComm=!1,this.isEnableLog=this.getVal(`${this.prefix}IsEnableLog${this.id}`),this.isEnableLog=!!this.isEmpty(this.isEnableLog)||this.isEnableLog.o(),this.isNotifyOnlyFail=this.getVal(`${this.prefix}NotifyOnlyFail${this.id}`),this.isNotifyOnlyFail=!this.isEmpty(this.isNotifyOnlyFail)&&this.isNotifyOnlyFail.o(),this.isEnableTgNotify=this.getVal(`${this.prefix}IsEnableTgNotify${this.id}`),this.isEnableTgNotify=!this.isEmpty(this.isEnableTgNotify)&&this.isEnableTgNotify.o(),this.tgNotifyUrl=this.getVal(`${this.prefix}TgNotifyUrl${this.id}`),this.isEnableTgNotify=this.isEnableTgNotify?!this.isEmpty(this.tgNotifyUrl):this.isEnableTgNotify,this.costTotalStringKey=`${this.prefix}CostTotalString${this.id}`,this.costTotalString=this.getVal(this.costTotalStringKey),this.costTotalString=this.isEmpty(this.costTotalString)?`0,0`:this.costTotalString.replace('"',""),this.costTotalMs=this.costTotalString.split(",")[0],this.execCount=this.costTotalString.split(",")[1],this.sleepTotalMs=0,this.logSeparator=`
██`,this.twoSpace=" ",this.now=new Date,this.startTime=this.now.getTime(),this.node=(()=>{if(this.isNode()){const request=require("request");return{request}}return null})(),this.execStatus=!0,this.notifyInfo=[],this.boxjsCurSessionKey="chavy_boxjs_cur_sessions",this.boxjsSessionsKey="chavy_boxjs_sessions",this.preTgEscapeCharMapping={"|`|":",backQuote,"},this.finalTgEscapeCharMapping={",backQuote,":"`","%2CbackQuote%2C":"`"},this.tgEscapeCharMapping={"_":"\\_","*":"\\*","`":"\\`"},this.tgEscapeCharMappingV2={"_":"\\_","*":"\\*","[":"\\[","]":"\\]","(":"\\(",")":"\\)","~":"\\~","`":"\\`",">":"\\>","#":"\\#","+":"\\+","-":"\\-","=":"\\=","|":"\\|","{":"\\{","}":"\\}",".":"\\.","!":"\\!"},this.log(`${this.name}, 开始执行!`),this.execComm()}getRealPath(fileName){if(!this.isNode())return fileName;let targetPath=process.argv.slice(1,2)[0].split("/");return targetPath[targetPath.length-1]=fileName,targetPath.join("/")}checkPath(fileName){const curDirDataFilePath=this.path.resolve(fileName),rootDirDataFilePath=this.path.resolve(process.cwd(),fileName),isCurDirDataFile=this.fs.existsSync(curDirDataFilePath),isRootDirDataFile=!isCurDirDataFile&&this.fs.existsSync(rootDirDataFilePath);return{curDirDataFilePath,rootDirDataFilePath,isCurDirDataFile,isRootDirDataFile}}async execComm(){if(!this.isNode())return;if(this.comm=process.argv.slice(1),this.comm[1]!="p")return;this.isExecComm=!0,this.log(`开始执行指令【${this.comm[1]}】=> 发送到其他终端测试脚本!`);let httpApi=this.options?.httpApi,targetDevice;if(this.isEmpty(this?.options?.httpApi))this.log(`未设置options,使用默认值`),this.isEmpty(this?.options)&&(this.options={}),this.options.httpApi=`ffff@10.0.0.6:6166`,httpApi=this.options.httpApi,targetDevice=httpApi.split("@")[1];else{if(typeof httpApi=="object")if(targetDevice=this.isNumeric(this.comm[2])?this.comm[3]||"unknown":this.comm[2],httpApi[targetDevice])httpApi=httpApi[targetDevice];else{const keys=Object.keys(httpApi);keys[0]?(targetDevice=keys[0],httpApi=httpApi[keys[0]]):httpApi="error"}if(!/.*?@.*?:[0-9]+/.test(httpApi)){this.log(`❌httpApi格式错误!格式: ffff@3.3.3.18:6166`),this.done();return}}this.callApi(this.comm[2],targetDevice,httpApi)}callApi(timeout,targetDevice,httpApi){let fname=this.comm[0];const[xKey,httpApiHost]=httpApi.split("@");this.log(`获取【${fname}】内容传给【${targetDevice||httpApiHost}】`),this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const{curDirDataFilePath,rootDirDataFilePath,isCurDirDataFile,isRootDirDataFile}=this.checkPath(fname);if(!isCurDirDataFile&&!isRootDirDataFile){lk.done();return}const datPath=isCurDirDataFile?curDirDataFilePath:rootDirDataFilePath;let options={url:`http://${httpApiHost}/v1/scripting/evaluate`,headers:{"X-Key":xKey},body:{script_text:String(this.fs.readFileSync(datPath)),mock_type:"cron",timeout:!this.isEmpty(timeout)&&timeout>5?timeout:5},json:!0};this.req.post(options).then(({error,resp,data})=>{this.log(`已将脚本【${fname}】发给【${targetDevice}】,执行结果:
${this.twoSpace}error: ${error}
${this.twoSpace}resp: ${resp?.s()}
${this.twoSpace}data: ${this.responseDataAdapter(data)}`),this.done()})}boxJsJsonBuilder(info,param){if(!this.isNode())return;if(!this.isJsonObject(info)||!this.isJsonObject(param)){this.log("构建BoxJsJson传入参数格式错误,请传入json对象");return}let boxjsJsonPath=param?.targetBoxjsJsonPath||"/Users/lowking/Desktop/Scripts/lowking.boxjs.json";if(!this.fs.existsSync(boxjsJsonPath))return;this.log("using node");let needAppendKeys=["settings","keys"];const domain="https://raw.githubusercontent.com/Orz-3";let boxJsJson={},scritpUrl="#lk{script_url}";if(boxJsJson.id=`${this.prefix}${this.id}`,boxJsJson.name=this.name,boxJsJson.desc_html=`⚠️使用说明</br>详情【<a href='${scritpUrl}?raw=true'><font class='red--text'>点我查看</font></a>】`,boxJsJson.icons=[`${domain}/mini/master/Alpha/${this.id.toLocaleLowerCase()}.png`,`${domain}/mini/master/Color/${this.id.toLocaleLowerCase()}.png`],boxJsJson.keys=[],boxJsJson.settings=[{id:`${this.prefix}IsEnableLog${this.id}`,name:"开启/关闭日志",val:!0,type:"boolean",desc:"默认开启"},{id:`${this.prefix}NotifyOnlyFail${this.id}`,name:"只当执行失败才通知",val:!1,type:"boolean",desc:"默认关闭"},{id:`${this.prefix}IsEnableTgNotify${this.id}`,name:"开启/关闭Telegram通知",val:!1,type:"boolean",desc:"默认关闭"},{id:`${this.prefix}TgNotifyUrl${this.id}`,name:"Telegram通知地址",val:"",type:"text",desc:"Tg的通知地址,如: https://api.telegram.org/bot-token/sendMessage?chat_id=-100140&parse_mode=Markdown&text="}],boxJsJson.author="#lk{author}",boxJsJson.repo="#lk{repo}",boxJsJson.script=`${scritpUrl}?raw=true`,!this.isEmpty(info))for(let key of needAppendKeys){if(this.isEmpty(info[key]))break;if(key==="settings")for(let i=0;i<info[key].length;i++){let input=info[key][i];for(let j=0;j<boxJsJson.settings.length;j++){let def=boxJsJson.settings[j];input.id===def.id&&boxJsJson.settings.splice(j,1)}}boxJsJson[key]=boxJsJson[key].concat(info[key]),delete info[key]}Object.assign(boxJsJson,info),this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const{curDirDataFilePath,rootDirDataFilePath,isCurDirDataFile,isRootDirDataFile}=this.checkPath(this.boxJsJsonFile),jsondata=boxJsJson.s(null," ");isCurDirDataFile?this.fs.writeFileSync(curDirDataFilePath,jsondata):isRootDirDataFile?this.fs.writeFileSync(rootDirDataFilePath,jsondata):this.fs.writeFileSync(curDirDataFilePath,jsondata);let boxjsJson=this.fs.readFileSync(boxjsJsonPath).o();if(!boxjsJson?.apps||!Array.isArray(boxjsJson.apps)){this.log(`⚠️请在boxjs订阅json文件中添加根属性: apps, 否则无法自动构建`);return}let apps=boxjsJson.apps,targetIdx=apps.indexOf(apps.filter(app=>app.id==boxJsJson.id)[0]);targetIdx>=0?boxjsJson.apps[targetIdx]=boxJsJson:boxjsJson.apps.push(boxJsJson);let ret=boxjsJson.s(null,2);if(!this.isEmpty(param))for(const key in param){let val=param[key];if(!val)switch(key){case"author":val="@lowking";break;case"repo":val="https://github.com/lowking/Scripts";break;default:continue}ret=ret.replaceAll(`#lk{${key}}`,val)}const regex=/(?:#lk\{)(.+?)(?=\})/;let m=regex.exec(ret);m!==null&&this.log(`⚠️生成BoxJs还有未配置的参数,请参考:
${this.twoSpace}https://github.com/lowking/Scripts/blob/master/util/example/ToolKitDemo.js#L17-L19
${this.twoSpace}传入参数: `);let loseParamSet=new Set;for(;(m=regex.exec(ret))!==null;)loseParamSet.add(m[1]),ret=ret.replace(`#lk{${m[1]}}`,``);loseParamSet.forEach(p=>console.log(`${this.twoSpace}${p}`)),this.fs.writeFileSync(boxjsJsonPath,ret)}isJsonObject(obj){return typeof obj=="object"&&Object.prototype.toString.call(obj).toLowerCase()=="[object object]"&&!obj.length}appendNotifyInfo(info,type){type==1?this.notifyInfo=info:this.notifyInfo.push(info)}prependNotifyInfo(info){this.notifyInfo.splice(0,0,info)}execFail(){this.execStatus=!1}isRequest(){return typeof $request!="undefined"}isSurge(){return typeof $httpClient!="undefined"}isQuanX(){return typeof $task!="undefined"}isLoon(){return typeof $loon!="undefined"}isJSBox(){return typeof $app!="undefined"&&typeof $http!="undefined"}isStash(){return"undefined"!=typeof $environment&&$environment["stash-version"]}isNode(){return typeof require=="function"&&!this.isJSBox()}sleep(ms){return this.sleepTotalMs+=ms,new Promise(resolve=>setTimeout(resolve,ms))}randomSleep(minMs,maxMs){return this.sleep(this.randomNumber(minMs,maxMs))}randomNumber(min,max){return Math.floor(Math.random()*(max-min+1)+min)}log(message){this.isEnableLog&&console.log(`${this.logSeparator}${message}`)}logErr(message){if(this.execStatus=!0,this.isEnableLog){let msg="";this.isEmpty(message.error)||(msg=`${msg}
${this.twoSpace}${message.error.s()}`),this.isEmpty(message.message)||(msg=`${msg}
${this.twoSpace}${message.message.s()}`),msg=`${this.logSeparator}${this.name}执行异常:${this.twoSpace}${msg}`,message&&(msg=`${msg}
${this.twoSpace}${message.s()}`),console.log(msg)}}replaceUseMap(mapping,message){for(let key in mapping){if(!mapping.hasOwnProperty(key))continue;message=message.replaceAll(key,mapping[key])}return message}msg(subtitle,message,openUrl,mediaUrl,copyText,disappearS){if(!this.isRequest()&&this.isNotifyOnlyFail&&this.execStatus)return;if(this.isEmpty(message)&&(Array.isArray(this.notifyInfo)?message=this.notifyInfo.join(`
`):message=this.notifyInfo),this.isEmpty(message))return;if(this.isEnableTgNotify){this.log(`${this.name}Tg通知开始`);const isMarkdown=this.tgNotifyUrl&&this.tgNotifyUrl.indexOf("parse_mode=Markdown")!=-1;if(isMarkdown){message=this.replaceUseMap(this.preTgEscapeCharMapping,message);let targetMapping=this.tgEscapeCharMapping;this.tgNotifyUrl.indexOf("parse_mode=MarkdownV2")!=-1&&(targetMapping=this.tgEscapeCharMappingV2),message=this.replaceUseMap(targetMapping,message)}message=`📌${this.name}
${message}`,isMarkdown&&(message=this.replaceUseMap(this.finalTgEscapeCharMapping,message));let u=`${this.tgNotifyUrl}${encodeURIComponent(message)}`;this.req.get({url:u})}else{let options={};const hasOpenUrl=!this.isEmpty(openUrl),hasMediaUrl=!this.isEmpty(mediaUrl),hasCopyText=!this.isEmpty(copyText),hasAutoDismiss=disappearS>0;this.isSurge()||this.isLoon()||this.isStash()?(hasOpenUrl&&(options.url=openUrl,options.action="open-url"),hasCopyText&&(options.text=copyText,options.action="clipboard"),this.isSurge()&&hasAutoDismiss&&(options["auto-dismiss"]=disappearS),hasMediaUrl&&(options["media-url"]=mediaUrl),$notification.post(this.name,subtitle,message,options)):this.isQuanX()?(hasOpenUrl&&(options["open-url"]=openUrl),hasMediaUrl&&(options["media-url"]=mediaUrl),$notify(this.name,subtitle,message,options)):this.isNode()?this.log("⭐️"+this.name+`
`+subtitle+`
`+message):this.isJSBox()&&$push.schedule({title:this.name,body:subtitle?subtitle+`
`+message:message})}}getVal(key,defaultValue){let value;return this.isSurge()||this.isLoon()||this.isStash()?value=$persistentStore.read(key):this.isQuanX()?value=$prefs.valueForKey(key):this.isNode()?(this.data=this.loadData(),value=process.env[key]||this.data[key]):value=this.data&&this.data[key]||null,value||defaultValue}updateBoxjsSessions(key,val){if(key==this.boxjsSessionsKey)return;const boxJsId=`${this.prefix}${this.id}`;let boxjsCurSession=this.getVal(this.boxjsCurSessionKey,"{}").o();if(!boxjsCurSession.hasOwnProperty(boxJsId))return;let curSessionId=boxjsCurSession[boxJsId],boxjsSessions=this.getVal(this.boxjsSessionsKey,"[]").o();if(boxjsSessions.length==0)return;let curSessionDatas=[];if(boxjsSessions.forEach(session=>{session.id==curSessionId&&(curSessionDatas=session.datas)}),curSessionDatas.length==0)return;let isExists=!1;curSessionDatas.forEach(kv=>{kv.key==key&&(kv.val=val,isExists=!0)}),isExists||curSessionDatas.push({key,val}),boxjsSessions.forEach(session=>{session.id==curSessionId&&(session.datas=curSessionDatas)}),this.setVal(this.boxjsSessionsKey,boxjsSessions.s())}setVal(key,val){return this.isSurge()||this.isLoon()||this.isStash()?(this.updateBoxjsSessions(key,val),$persistentStore.write(val,key)):this.isQuanX()?(this.updateBoxjsSessions(key,val),$prefs.setValueForKey(val,key)):this.isNode()?(this.data=this.loadData(),this.data[key]=val,this.writeData(),!0):this.data&&this.data[key]||null}loadData(){if(!this.isNode())return{};this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const{curDirDataFilePath,rootDirDataFilePath,isCurDirDataFile,isRootDirDataFile}=this.checkPath(this.dataFile);if(isCurDirDataFile||isRootDirDataFile){const datPath=isCurDirDataFile?curDirDataFilePath:rootDirDataFilePath;return this.fs.readFileSync(datPath).o()}return{}}writeData(){if(!this.isNode())return;this.fs=this.fs?this.fs:require("fs"),this.path=this.path?this.path:require("path");const{curDirDataFilePath,rootDirDataFilePath,isCurDirDataFile,isRootDirDataFile}=this.checkPath(this.dataFile),jsondata=this.data.s();isCurDirDataFile?this.fs.writeFileSync(curDirDataFilePath,jsondata):isRootDirDataFile?this.fs.writeFileSync(rootDirDataFilePath,jsondata):this.fs.writeFileSync(curDirDataFilePath,jsondata)}responseDataAdapter(data){const tabString=`${this.twoSpace}${this.twoSpace}`;let ret="";return Object.keys(data).forEach(key=>{let lines=data[key]?.s().split(`
`);key=="output"&&(lines=lines.slice(0,-2)),ret=`${ret}
${tabString}${key}:
${tabString}${this.twoSpace}${lines?.join(`
${tabString}${this.twoSpace}`)}`}),ret}statusAdapter(response){return response&&(response.status=response?.status||response?.statusCode,delete response.statusCode,response)}get(options,callback=()=>{}){this.isSurge()||this.isLoon()||this.isStash()?$httpClient.get(options,(error,response,body)=>{callback(error,this.statusAdapter(response),body)}):this.isQuanX()?(typeof options=="string"&&(options={url:options}),options.method="GET",$task.fetch(options).then(response=>{callback(null,this.statusAdapter(response),response.body)},reason=>callback(reason.error,null,null))):this.isNode()?this.node.request(options,(error,response,body)=>{callback(error,this.statusAdapter(response),body)}):this.isJSBox()&&(typeof options=="string"&&(options={url:options}),options.header=options.headers,options.handler=function(resp){let error=resp.error;error&&(error=resp.error.s());let body=resp.data;typeof body=="object"&&(body=resp.data.s()),callback(error,this.adapterStatus(resp.response),body)},$http.get(options))}post(options,callback=()=>{}){this.isSurge()||this.isLoon()||this.isStash()?$httpClient.post(options,(error,response,body)=>{callback(error,this.statusAdapter(response),body)}):this.isQuanX()?(typeof options=="string"&&(options={url:options}),options.method="POST",$task.fetch(options).then(response=>{callback(null,this.statusAdapter(response),response.body)},reason=>callback(reason.error,null,null))):this.isNode()?this.node.request.post(options,(error,response,body)=>{callback(error,this.statusAdapter(response),body)}):this.isJSBox()&&(typeof options=="string"&&(options={url:options}),options.header=options.headers,options.handler=function(resp){let error=resp.error;error&&(error=resp.error.s());let body=resp.data;typeof body=="object"&&(body=resp.data.s()),callback(error,this.adapterStatus(resp.response),body)},$http.post(options))}put(options,callback=()=>{}){this.isSurge()||this.isLoon()||this.isStash()?(options.method="PUT",$httpClient.put(options,(error,response,body)=>{callback(error,this.statusAdapter(response),body)})):this.isQuanX()?(typeof options=="string"&&(options={url:options}),options.method="PUT",$task.fetch(options).then(response=>{callback(null,this.statusAdapter(response),response.body)},reason=>callback(reason.error,null,null))):this.isNode()?(options.method="PUT",this.node.request.put(options,(error,response,body)=>{callback(error,this.statusAdapter(response),body)})):this.isJSBox()&&(typeof options=="string"&&(options={url:options}),options.header=options.headers,options.handler=function(resp){let error=resp.error;error&&(error=resp.error.s());let body=resp.data;typeof body=="object"&&(body=resp.data.s()),callback(error,this.adapterStatus(resp.response),body)},$http.post(options))}sum(a,b){let aa=Array.from(a,Number),bb=Array.from(b,Number),ret=[],c=0,i=Math.max(a.length,b.length);for(;i--;)c+=(aa.pop()||0)+(bb.pop()||0),ret.unshift(c%10),c=Math.floor(c/10);for(;c;)ret.unshift(c%10),c=Math.floor(c/10);return ret.join("")}costTime(){let info=`${this.name}, 执行完毕!`;this.isNode()&&this.isExecComm&&(info=`指令【${this.comm[1]}】执行完毕!`);const endTime=(new Date).getTime(),ms=endTime-this.startTime,costTime=ms/1e3,count=this.sum(this.execCount,"1"),total=this.sum(this.costTotalMs,ms.s()),average=(Number(total)/Number(count)/1e3).toFixed(4);info=`${info}
${this.twoSpace}耗时【${costTime}】秒(含休眠${this.sleepTotalMs?(this.sleepTotalMs/1e3).toFixed(4):0}秒)`,info=`${info}
${this.twoSpace}总共执行【${count}】次,平均耗时【${average}】秒`,info=`${info}
${this.twoSpace}ToolKit v1.3.2 build 144.`,this.log(info),this.setVal(this.costTotalStringKey,`${total},${count}`.s())}done(value={}){this.costTime(),(this.isSurge()||this.isQuanX()||this.isLoon()||this.isStash())&&$done(value)}getRequestUrl(){return $request.url}getResponseBody(){return $response.body}isMatch(reg){return!!($request.method!="OPTIONS"&&this.getRequestUrl().match(reg))}isEmpty(obj){return typeof obj=="undefined"||obj==null||obj.s()=="{}"||obj==""||obj.s()=='""'||obj.s()=="null"||obj.s()=="undefined"||obj.length===0}isNumeric(s){return!isNaN(parseFloat(s))&&isFinite(s)}randomString(len,chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"){len=len||32;let maxPos=chars.length,pwd="";for(let i=0;i<len;i++)pwd+=chars.charAt(Math.floor(Math.random()*maxPos));return pwd}autoComplete(str,prefix,suffix,fill,len,direction,ifCode,clen,startIndex,cstr){if(str+=``,str.length<len)for(;str.length<len;)direction==0?str+=fill:str=fill+str;if(ifCode){let temp=``;for(let i=0;i<clen;i++)temp+=cstr;str=str.substring(0,startIndex)+temp+str.substring(clen+startIndex)}return str=prefix+str+suffix,this.toDBC(str)}customReplace(str,param,prefix,suffix){try{this.isEmpty(prefix)&&(prefix="#{"),this.isEmpty(suffix)&&(suffix="}");for(let i in param)str=str.replace(`${prefix}${i}${suffix}`,param[i])}catch(e){this.logErr(e)}return str}toDBC(txtstring){let tmp="";for(let i=0;i<txtstring.length;i++)txtstring.charCodeAt(i)==32?tmp=tmp+String.fromCharCode(12288):txtstring.charCodeAt(i)<127&&(tmp=tmp+String.fromCharCode(txtstring.charCodeAt(i)+65248));return tmp}hash(str){let h=0,i,chr;for(i=0;i<str.length;i++)chr=str.charCodeAt(i),h=(h<<5)-h+chr,h|=0;return String(h)}formatDate(date,format){let o={"M+":date.getMonth()+1,"d+":date.getDate(),"H+":date.getHours(),"m+":date.getMinutes(),"s+":date.getSeconds(),"q+":Math.floor((date.getMonth()+3)/3),S:date.getMilliseconds()};/(y+)/.test(format)&&(format=format.replace(RegExp.$1,(date.getFullYear()+"").substr(4-RegExp.$1.length)));for(let k in o)new RegExp("("+k+")").test(format)&&(format=format.replace(RegExp.$1,RegExp.$1.length==1?o[k]:("00"+o[k]).substr((""+o[k]).length)));return format}getCookieProp(ca,cname){const name=cname+"=";ca=ca.split(";");for(let i=0;i<ca.length;i++){let c=ca[i].trim();if(c.indexOf(name)==0)return c.substring(name.length).replace('"',"").trim()}return""}parseHTML(htmlString){let parser=new DOMParser,document=parser.parseFromString(htmlString,"text/html");return document.body}}(scriptName,scriptId,options)}