abler-api 0.1.27 → 0.1.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,18 +2,20 @@ import require$$0 from 'crypto';
2
2
  import require$$1 from 'abler-util';
3
3
  import require$$2 from 'abler-db';
4
4
  import require$$3 from 'abler-net';
5
- import require$$0$1 from 'fs';
5
+ import require$$4 from 'fs';
6
6
  import require$$1$1 from 'path';
7
7
  import require$$1$2 from 'abler-messenger';
8
+ import require$$0$1 from 'node-cron';
8
9
 
9
10
  const crypto = require$$0;
10
- const ppUtil$3 = require$$1.ppUtil;
11
+ const ppUtil$4 = require$$1.ppUtil;
11
12
  const {
12
13
  dbUtil,
13
14
  kvStorage
14
15
  } = require$$2;
15
16
  const netUtil$1 = require$$3;
16
- let conf$2, appSetting$1, err$1, dbSql;
17
+ const fs$1 = require$$4;
18
+ let conf$3, appSetting$1, err$2, dbSql;
17
19
  const pnToken = "access_token",
18
20
  hnToken = pnToken,
19
21
  pnApiKey = "apiKey",
@@ -21,22 +23,22 @@ const pnToken = "access_token",
21
23
  // 我们接收到的 headers 中的字段名总是全小写的
22
24
  pnApiSecret = "apiSecret",
23
25
  hnApiSecret = pnApiSecret.toLowerCase();
24
- const MD5 = ppUtil$3.MD5,
25
- moveProperty = ppUtil$3.moveProperty;
26
+ const MD5 = ppUtil$4.MD5,
27
+ moveProperty = ppUtil$4.moveProperty;
26
28
 
27
- class apiUtil$1 {
28
- static debugFlag = ppUtil$3.newGuid(); //应用必须设置,否则谁也不知道是啥
29
+ class apiUtil$2 {
30
+ static debugFlag = ppUtil$4.newGuid(); //应用必须设置,否则谁也不知道是啥
29
31
 
30
- static testFlag = ppUtil$3.newGuid();
32
+ static testFlag = ppUtil$4.newGuid();
31
33
  static envId_dev = "?"; // static apiCallRecSaver;
32
34
 
33
35
  static config(appConfig, appErrCfg, appDbSql) {
34
- ppUtil$3.config(appConfig, appErrCfg);
35
- conf$2 = appConfig;
36
- appSetting$1 = conf$2?.appSetting;
37
- err$1 = appErrCfg, dbSql = appDbSql;
38
- apiUtil$1.debugFlag = appSetting$1?.debugFlag || apiUtil$1.debugFlag;
39
- apiUtil$1.testFlag = appSetting$1?.testFlag || apiUtil$1.testFlag; // apiUtil.apiCallRecSaver = apiCallRecSaver;
36
+ ppUtil$4.config(appConfig, appErrCfg);
37
+ conf$3 = appConfig;
38
+ appSetting$1 = conf$3?.appSetting;
39
+ err$2 = appErrCfg, dbSql = appDbSql;
40
+ apiUtil$2.debugFlag = appSetting$1?.debugFlag || apiUtil$2.debugFlag;
41
+ apiUtil$2.testFlag = appSetting$1?.testFlag || apiUtil$2.testFlag; // apiUtil.apiCallRecSaver = apiCallRecSaver;
40
42
  } //#region ===== 需要应用系统重写的方法
41
43
 
42
44
  /**
@@ -47,7 +49,7 @@ class apiUtil$1 {
47
49
 
48
50
 
49
51
  static _getApiSecret(companyId) {
50
- return ppUtil$3.newGuid();
52
+ return ppUtil$4.newGuid();
51
53
  }
52
54
  /**
53
55
  * 保存 API 调用记录,应用系统必须重写此方法
@@ -124,7 +126,7 @@ class apiUtil$1 {
124
126
  req._requestParams = Object.assign(req.params, req._requestParams);
125
127
  }
126
128
 
127
- apiUtil$1.setParamsFunctions(req._requestParams);
129
+ apiUtil$2.setParamsFunctions(req._requestParams);
128
130
  }
129
131
 
130
132
  return req._requestParams;
@@ -135,11 +137,11 @@ class apiUtil$1 {
135
137
  return req.tokenData;
136
138
  }
137
139
 
138
- let params = apiUtil$1.extractParams(req);
140
+ let params = apiUtil$2.extractParams(req);
139
141
  let tokenData = {
140
142
  apiKey: req.headers[hnApiKey] || params[pnApiKey],
141
143
  apiSecret: req.headers[hnApiSecret] || params[pnApiSecret],
142
- clientIp: apiUtil$1.getClientIp(req)
144
+ clientIp: apiUtil$2.getClientIp(req)
143
145
  };
144
146
  return tokenData;
145
147
  }
@@ -150,18 +152,18 @@ class apiUtil$1 {
150
152
 
151
153
 
152
154
  static setParamsFunctions(params) {
153
- ppUtil$3.defUnenumProp(params, "asNumber", function (name, minValue, maxValue, defaultValue) {
155
+ ppUtil$4.defUnenumProp(params, "asNumber", function (name, minValue, maxValue, defaultValue) {
154
156
  // if (!this.hasOwnProperty(name)) // {} 定义的对象没有 hasOwnProperty 函数
155
157
  if (this[name] === undefined) return defaultValue;
156
158
  let result = +this[name];
157
159
 
158
160
  if (typeof result !== "number" || result < minValue || result > maxValue) {
159
- throw [err$1.INVALID_PARAM, `参数 ${name} 必须是 ${minValue} ~ ${maxValue} 之间的数字`];
161
+ throw [err$2.INVALID_PARAM, `参数 ${name} 必须是 ${minValue} ~ ${maxValue} 之间的数字`];
160
162
  }
161
163
 
162
164
  return result;
163
165
  });
164
- ppUtil$3.defUnenumProp(params, "asBool", function (name, defaultValue) {
166
+ ppUtil$4.defUnenumProp(params, "asBool", function (name, defaultValue) {
165
167
  if (this[name] === undefined) return defaultValue;
166
168
  let result = JSON.parse(this[name]);
167
169
  return !!result;
@@ -177,7 +179,7 @@ class apiUtil$1 {
177
179
 
178
180
  static sendOrRedirect(res, redirectUrl, data) {
179
181
  if (redirectUrl) {
180
- redirectUrl = urlAppendParams(redirectUrl, data, true);
182
+ redirectUrl = netUtil$1.urlAppendParams(redirectUrl, data, true);
181
183
  res.redirect(redirectUrl);
182
184
  } else {
183
185
  res.send(data);
@@ -226,7 +228,7 @@ class apiUtil$1 {
226
228
 
227
229
  static apiFail(error, req) {
228
230
  configNeeded();
229
- let response = err$1.ERROR(error, err$1.errorLangParamFlag + ppUtil$3.getMsgLang(req));
231
+ let response = err$2.ERROR(error, err$2.errorLangParamFlag + ppUtil$4.getMsgLang(req));
230
232
  response.datetime = new Date();
231
233
 
232
234
  if (req && req.headers) {
@@ -248,8 +250,8 @@ class apiUtil$1 {
248
250
 
249
251
 
250
252
  static spoApiSucc(data, req) {
251
- let params = apiUtil$1.extractParams(req);
252
- return apiUtil$1.apiSuccess(data, req, params.spOrderNum);
253
+ let params = apiUtil$2.extractParams(req);
254
+ return apiUtil$2.apiSuccess(data, req, params.spOrderNum);
253
255
  }
254
256
  /**
255
257
  * 生成面向服务商的API失败返回结果
@@ -260,8 +262,8 @@ class apiUtil$1 {
260
262
 
261
263
 
262
264
  static spoApiFail(error, req) {
263
- let params = apiUtil$1.extractParams(req);
264
- return apiUtil$1.apiFail(error, req, params.spOrderNum);
265
+ let params = apiUtil$2.extractParams(req);
266
+ return apiUtil$2.apiFail(error, req, params.spOrderNum);
265
267
  }
266
268
  /**
267
269
  * API 服务结束,发送响应
@@ -298,10 +300,10 @@ class apiUtil$1 {
298
300
  static async responseOf(response, promise) {
299
301
  promise.then(function (data) {
300
302
  // console.log('RES:', apiSuccess(data));
301
- if (!response.finished) response.send(apiUtil$1.apiSuccess(data, response.req));
303
+ if (!response.finished) response.send(apiUtil$2.apiSuccess(data, response.req));
302
304
  }, function (error) {
303
305
  console.log('ERROR:', error);
304
- if (!response.finished) response.send(apiUtil$1.apiFail(error, response.req));
306
+ if (!response.finished) response.send(apiUtil$2.apiFail(error, response.req));
305
307
  });
306
308
  }
307
309
  /**
@@ -313,16 +315,16 @@ class apiUtil$1 {
313
315
 
314
316
  static async spoApiResponse(response, promise) {
315
317
  promise.then(function (result) {
316
- let responseData = apiUtil$1.spoApiSucc(result, response.req);
318
+ let responseData = apiUtil$2.spoApiSucc(result, response.req);
317
319
 
318
- apiUtil$1._saveApiCallRec(response.req.apiCallRec, responseData);
320
+ apiUtil$2._saveApiCallRec(response.req.apiCallRec, responseData);
319
321
 
320
322
  if (!response.finished) response.send(responseData);
321
323
  }, function (error) {
322
324
  console.log('ERROR:', error);
323
- let responseData = apiUtil$1.spoApiFail(error, response.req);
325
+ let responseData = apiUtil$2.spoApiFail(error, response.req);
324
326
 
325
- apiUtil$1._saveApiCallRec(response.req.apiCallRec, responseData);
327
+ apiUtil$2._saveApiCallRec(response.req.apiCallRec, responseData);
326
328
 
327
329
  if (!response.finished) response.send(responseData);
328
330
  });
@@ -339,7 +341,7 @@ class apiUtil$1 {
339
341
  req.headers.timestamp = new Date().valueOf(); // let options = {replacements: {}};
340
342
 
341
343
  let options = {};
342
- let parameters = apiUtil$1.extractParams(req);
344
+ let parameters = apiUtil$2.extractParams(req);
343
345
 
344
346
  for (let qryParam in parameters) {
345
347
  if (qryParam !== 'token') {
@@ -371,7 +373,7 @@ class apiUtil$1 {
371
373
  // }
372
374
 
373
375
  options.userInfo = req.userInfo;
374
- return apiUtil$1.setOptionsPropFuncions(options, res);
376
+ return apiUtil$2.setOptionsPropFuncions(options, res);
375
377
  }
376
378
  /**
377
379
  * 为API请求 options 设置属性
@@ -436,7 +438,7 @@ class apiUtil$1 {
436
438
  let token = req.headers[hnToken] || req.headers['x-access-token']; //向后兼容
437
439
 
438
440
  if (!token) {
439
- let params = apiUtil$1.extractParams(req);
441
+ let params = apiUtil$2.extractParams(req);
440
442
  token = params[pnToken];
441
443
 
442
444
  if (token) {
@@ -447,12 +449,12 @@ class apiUtil$1 {
447
449
  delete params.token;
448
450
  } else {
449
451
  // 如果没有token,则返回错误
450
- console.log(err$1.TOKEN_NEEDED);
452
+ console.log(err$2.TOKEN_NEEDED);
451
453
 
452
454
  if (res) {
453
- res.send(err$1.ERROR(err$1.TOKEN_NEEDED));
455
+ res.send(err$2.ERROR(err$2.TOKEN_NEEDED));
454
456
  } else if (!noErr) {
455
- throw err$1.TOKEN_NEEDED;
457
+ throw err$2.TOKEN_NEEDED;
456
458
  }
457
459
  }
458
460
  }
@@ -471,10 +473,10 @@ class apiUtil$1 {
471
473
 
472
474
  static async checkInternalToken(req) {
473
475
  // return await checkInternalToken(req);
474
- const params = apiUtil$1.extractParams(req);
475
- req.accessToken = req.accessToken || apiUtil$1.extractToken(req);
476
+ const params = apiUtil$2.extractParams(req);
477
+ req.accessToken = req.accessToken || apiUtil$2.extractToken(req);
476
478
 
477
- if (req.accessToken === MD5(ppUtil$3.idNumDisturbing)) {
479
+ if (req.accessToken === MD5(ppUtil$4.idNumDisturbing)) {
478
480
  //todo: 检查IP
479
481
  params.__internal__ = true;
480
482
  req.ignoreToken = true; // if (params.idNum || params.personId) {
@@ -495,7 +497,7 @@ class apiUtil$1 {
495
497
  return true;
496
498
  } else {
497
499
  // console.log('token error.', req.accessToken);
498
- throw err$1.TOKEN_INVALID;
500
+ throw err$2.TOKEN_INVALID;
499
501
  }
500
502
  }
501
503
  /**
@@ -506,16 +508,16 @@ class apiUtil$1 {
506
508
 
507
509
 
508
510
  static async checkRequestToken(req) {
509
- req.accessToken = req.accessToken || apiUtil$1.extractToken(req);
510
- const tokenKey = apiUtil$1.userTokenStoreKey(req.accessToken);
511
- const expireTime = apiUtil$1.tokenExpireTime(req);
512
- return await apiUtil$1.restoreTokenData(tokenKey, expireTime).then(async function (data) {
513
- req.userInfo = apiUtil$1.setUserIdNo(data, data._idNo);
511
+ req.accessToken = req.accessToken || apiUtil$2.extractToken(req);
512
+ const tokenKey = apiUtil$2.userTokenStoreKey(req.accessToken);
513
+ const expireTime = apiUtil$2.tokenExpireTime(req);
514
+ return await apiUtil$2.restoreTokenData(tokenKey, expireTime).then(async function (data) {
515
+ req.userInfo = apiUtil$2.setUserIdNo(data, data._idNo);
514
516
  if (req.tokenValidater) await req.tokenValidater(req.userInfo, req);
515
517
  return true;
516
518
  }, async function (e) {
517
519
  // 如果给定的token不存在,看看是不是平台内部调用
518
- return await apiUtil$1.checkInternalToken(req);
520
+ return await apiUtil$2.checkInternalToken(req);
519
521
  });
520
522
  }
521
523
  /**
@@ -527,11 +529,11 @@ class apiUtil$1 {
527
529
 
528
530
  static isDebugMode(req) {
529
531
  if (req.__debug__ === undefined) {
530
- let dbgToken = req.headers['__debug__'] || req.headers[apiUtil$1.debugFlag];
532
+ let dbgToken = req.headers['__debug__'] || req.headers[apiUtil$2.debugFlag];
531
533
 
532
534
  if (dbgToken) {
533
535
  let envId = process.env.ECS_DEPLOY_ID;
534
- req.__debug__ = dbgToken && dbgToken === MD5(req.headers.timestamp, ppUtil$3.commonHashDisturbing) && (envId === "florist_longdan" || envId === "shuzi");
536
+ req.__debug__ = dbgToken && dbgToken === MD5(req.headers.timestamp, ppUtil$4.commonHashDisturbing) && (envId === "florist_longdan" || envId === "shuzi");
535
537
  } else {
536
538
  req.__debug__ = false;
537
539
  } // console.log("__debug__:", req.__debug__, "dbgToken:", dbgToken);
@@ -549,11 +551,11 @@ class apiUtil$1 {
549
551
 
550
552
  static isTestMode(req) {
551
553
  if (req.__postman__ === undefined) {
552
- let dbgToken = req.headers["__postman__"] || req.headers[apiUtil$1.testFlag];
554
+ let dbgToken = req.headers["__postman__"] || req.headers[apiUtil$2.testFlag];
553
555
 
554
556
  if (dbgToken) {
555
557
  let envId = process.env.ECS_DEPLOY_ID;
556
- let testToken = MD5(req.headers.timestamp, apiUtil$1.extractToken(req, null, true) || req.headers.apikey);
558
+ let testToken = MD5(req.headers.timestamp, apiUtil$2.extractToken(req, null, true) || req.headers.apikey);
557
559
  req.__postman__ = dbgToken === testToken && (envId.indexOf("myfacesign.com") < 0 || envId.indexOf(".dev.") > 0);
558
560
  } else {
559
561
  req.__postman__ = false;
@@ -570,7 +572,7 @@ class apiUtil$1 {
570
572
 
571
573
 
572
574
  static tokenExpireTime(req) {
573
- return apiUtil$1.isDebugMode(req) ? 30 * 24 * 60 * 60 : apiUtil$1.isTestMode(req) ? 4 * 60 * 60 : appSetting$1.tokenExpireTime;
575
+ return apiUtil$2.isDebugMode(req) ? 30 * 24 * 60 * 60 : apiUtil$2.isTestMode(req) ? 4 * 60 * 60 : appSetting$1.tokenExpireTime;
574
576
  }
575
577
  /**
576
578
  * 获取用户令牌保存键
@@ -613,7 +615,7 @@ class apiUtil$1 {
613
615
  static setUserIdNo(userInfo, idNum) {
614
616
  if (userInfo && idNum) {
615
617
  userInfo._idNo = idNum;
616
- userInfo.isHKIC = apiUtil$1.checkIsHKIC(idNum);
618
+ userInfo.isHKIC = apiUtil$2.checkIsHKIC(idNum);
617
619
  }
618
620
 
619
621
  return userInfo;
@@ -630,7 +632,7 @@ class apiUtil$1 {
630
632
 
631
633
  static async storeToken(token, tokenData, dataId, req) {
632
634
  // let timeout = tokenData.clientIp.substring(0, 8) == "192.168." ? 90 * 24 : 1;
633
- let timeout = apiUtil$1.tokenExpireTime(req);
635
+ let timeout = apiUtil$2.tokenExpireTime(req);
634
636
 
635
637
  if (req.certPublicKey) {
636
638
  tokenData.certPublicKey = req.certPublicKey;
@@ -711,7 +713,7 @@ class apiUtil$1 {
711
713
  };
712
714
 
713
715
  if (rec.secret !== "") {
714
- rec.secret = ppUtil$3.getEncAse192(rec.secret);
716
+ rec.secret = ppUtil$4.getEncAse192(rec.secret);
715
717
  }
716
718
 
717
719
  req.apiCallRec = rec;
@@ -778,7 +780,7 @@ class apiUtil$1 {
778
780
  return certInfo;
779
781
  }).catch(e => {
780
782
  console.log('获取企业证书失败:\n', e);
781
- throw [err$1.ACCESS_REFUSED, `获取企业证书失败:${err$1.ERROR(e).message}`];
783
+ throw [err$2.ACCESS_REFUSED, `获取企业证书失败:${err$2.ERROR(e).message}`];
782
784
  });
783
785
  }
784
786
  /**
@@ -792,27 +794,27 @@ class apiUtil$1 {
792
794
  static async verifyApiSignature(tokenData, req) {
793
795
  try {
794
796
  if (!req.headers.timestamp) {
795
- throw [err$1.ACCESS_REFUSED, `必须在请求头中设置时戳`];
797
+ throw [err$2.ACCESS_REFUSED, `必须在请求头中设置时戳`];
796
798
  }
797
799
 
798
800
  let timestamp = parseInt(req.headers.timestamp);
799
801
  let currentTime = new Date().valueOf();
800
- let maxTimeDiff = apiUtil$1.isDebugMode(req) ? 7 * 24 * 3600 : apiUtil$1.isTestMode(req) ? 4 * 3600 : 100; // 100
802
+ let maxTimeDiff = apiUtil$2.isDebugMode(req) ? 7 * 24 * 3600 : apiUtil$2.isTestMode(req) ? 4 * 3600 : 100; // 100
801
803
 
802
804
  if (timestamp.toString() == "NaN" || currentTime < timestamp - 5000 || currentTime - timestamp > maxTimeDiff * 1000) {
803
- throw [err$1.ACCESS_REFUSED, `时戳(${timestamp})无效,当前时戳:${currentTime},时差 ${(currentTime - timestamp) / 1000}秒`];
805
+ throw [err$2.ACCESS_REFUSED, `时戳(${timestamp})无效,当前时戳:${currentTime},时差 ${(currentTime - timestamp) / 1000}秒`];
804
806
  }
805
807
 
806
808
  let signature = req.headers.signature;
807
809
 
808
810
  if (!signature) {
809
- throw [err$1.ACCESS_REFUSED, `必须在请求头中提供签名`];
811
+ throw [err$2.ACCESS_REFUSED, `必须在请求头中提供签名`];
810
812
  }
811
813
 
812
- let signData = apiUtil$1.extractToken(req, null, true) || tokenData.apiKey;
814
+ let signData = apiUtil$2.extractToken(req, null, true) || tokenData.apiKey;
813
815
  signData += timestamp;
814
816
 
815
- if (apiUtil$1.isDebugMode(req) || apiUtil$1.isTestMode(req)) {
817
+ if (apiUtil$2.isDebugMode(req) || apiUtil$2.isTestMode(req)) {
816
818
  let publicKey = req.headers.publickey || req.body.publicKey || req.query.publicKey;
817
819
 
818
820
  if (publicKey) {
@@ -827,16 +829,16 @@ class apiUtil$1 {
827
829
  return await verifyResult;
828
830
  }
829
831
 
830
- return apiUtil$1.getCompanyCertificate(tokenData.apiKey).then(info => {
832
+ return apiUtil$2.getCompanyCertificate(tokenData.apiKey).then(info => {
831
833
  tokenData.certPublicKey = info.certLiving;
832
834
  tokenData.certPublicKeySpare = info.certSpare;
833
835
  tokenData.certLivingId = info.certLivingId;
834
836
  tokenData.certSpareId = info.certSpareId;
835
837
  req.certPublicKey = info.certLiving;
836
- let token = apiUtil$1.extractToken(req, null, true);
838
+ let token = apiUtil$2.extractToken(req, null, true);
837
839
 
838
840
  if (token) {
839
- apiUtil$1.storeToken(apiUtil$1.apiTokenStoreKey(token), tokenData, tokenData.apiKey, req);
841
+ apiUtil$2.storeToken(apiUtil$2.apiTokenStoreKey(token), tokenData, tokenData.apiKey, req);
840
842
  }
841
843
  }).then(() => {
842
844
  return doVerify(signData, signature, tokenData.certPublicKey);
@@ -861,7 +863,7 @@ class apiUtil$1 {
861
863
 
862
864
  if (!tokenData.certPublicKeySpare) {
863
865
  throw {
864
- eo: err$1.ACCESS_REFUSED,
866
+ eo: err$2.ACCESS_REFUSED,
865
867
  msgArgv: "签名验证异常",
866
868
  data: e
867
869
  };
@@ -898,10 +900,10 @@ class apiUtil$1 {
898
900
  delete tokenData.certLivingId;
899
901
  delete tokenData.certSpareId;
900
902
  delete tokenData.certPublicKeySpare;
901
- let token = apiUtil$1.extractToken(req);
903
+ let token = apiUtil$2.extractToken(req);
902
904
 
903
905
  if (token) {
904
- apiUtil$1.storeToken(apiTokenStoreKey(token), tokenData, tokenData.apiKey, req);
906
+ apiUtil$2.storeToken(apiTokenStoreKey(token), tokenData, tokenData.apiKey, req);
905
907
  }
906
908
 
907
909
  console.log(`公司(${tokenData.apiKey})备用证书成功转换为正式证书`);
@@ -910,7 +912,7 @@ class apiUtil$1 {
910
912
  } catch (e) {
911
913
  console.log("SPO服务签名验证异常(备用证书), ", e);
912
914
  throw {
913
- eo: err$1.ACCESS_REFUSED,
915
+ eo: err$2.ACCESS_REFUSED,
914
916
  msgArgv: "签名验证异常(spare)",
915
917
  data: e
916
918
  };
@@ -919,7 +921,7 @@ class apiUtil$1 {
919
921
 
920
922
  if (!verifyOK) {
921
923
  console.log("SPO服务签名验证失败, tokenData: ", tokenData);
922
- throw [err$1.ACCESS_REFUSED, "签名验证未通过"];
924
+ throw [err$2.ACCESS_REFUSED, "签名验证未通过"];
923
925
  }
924
926
 
925
927
  return verifyOK;
@@ -935,32 +937,32 @@ class apiUtil$1 {
935
937
 
936
938
  static async checkApiCallValid(tokenData, req) {
937
939
  if (!tokenData.companyInfo) {
938
- tokenData.companyInfo = await apiUtil$1.queryCompanyInfo(tokenData.apiKey, true).catch(e => {
940
+ tokenData.companyInfo = await apiUtil$2.queryCompanyInfo(tokenData.apiKey, true).catch(e => {
939
941
  console.log("执行企业信息查询发生异常", e);
940
- throw [err$1.API_KEY_INVALID, "执行企业信息查询发生异常:" + e.message || ""];
942
+ throw [err$2.API_KEY_INVALID, "执行企业信息查询发生异常:" + e.message || ""];
941
943
  });
942
944
  }
943
945
 
944
946
  const companyInfo = tokenData.companyInfo;
945
947
 
946
948
  if (companyInfo != null) {
947
- let secret = apiUtil$1._getApiSecret(tokenData.apiKey);
949
+ let secret = apiUtil$2._getApiSecret(tokenData.apiKey);
948
950
 
949
- if (secret !== tokenData.apiSecret) throw err$1.API_SCREPT_INVALID; // 不再检查 IP 白名单,改为验证证书签名
951
+ if (secret !== tokenData.apiSecret) throw err$2.API_SCREPT_INVALID; // 不再检查 IP 白名单,改为验证证书签名
950
952
  // console.log("fromIp:", tokenData.clientIp, "ipWhiteList:", companyInfo.ipWhiteList);
951
953
  // let whiteList = companyInfo.ipWhiteList || "";
952
954
  // // 没有设置ip白名单的就不检查了
953
955
  // if (whiteList == "" || ipMatched(tokenData.clientIp, whiteList + ",127.0.0.1,1"))
954
956
 
955
- if (apiUtil$1.signatureVerified()) return companyInfo;
956
- return apiUtil$1.verifyApiSignature(tokenData, req).then(x => {
957
+ if (apiUtil$2.signatureVerified()) return companyInfo;
958
+ return apiUtil$2.verifyApiSignature(tokenData, req).then(x => {
957
959
  return companyInfo;
958
960
  }, e => {
959
961
  throw e;
960
962
  });
961
963
  }
962
964
 
963
- throw [err$1.API_KEY_INVALID, tokenData.apiKey];
965
+ throw [err$2.API_KEY_INVALID, tokenData.apiKey];
964
966
  }
965
967
  /**
966
968
  * 检查令牌数据是否存在
@@ -1011,7 +1013,7 @@ class apiUtil$1 {
1011
1013
  paramExists = typeof params[paramName] != 'undefined' || typeof params[paramName + paramSufix] != 'undefined';
1012
1014
  }
1013
1015
 
1014
- if (!paramExists) return ppUtil$3.errorPormise(err$1.ERROR(err$1.PARAMETER_NEEDED, paramName));
1016
+ if (!paramExists) return ppUtil$4.errorPormise(err$2.ERROR(err$2.PARAMETER_NEEDED, paramName));
1015
1017
  }
1016
1018
 
1017
1019
  return Promise.resolve(paramSufix);
@@ -1059,8 +1061,8 @@ class apiUtil$1 {
1059
1061
 
1060
1062
 
1061
1063
  static async hostIsMySelf(host, req) {
1062
- let clientIp = apiUtil$1.getClientIp(req);
1063
- return ppUtil$3.getMyIp({
1064
+ let clientIp = apiUtil$2.getClientIp(req);
1065
+ return ppUtil$4.getMyIp({
1064
1066
  hosts: [host, clientIp]
1065
1067
  });
1066
1068
  }
@@ -1074,13 +1076,13 @@ class apiUtil$1 {
1074
1076
  static async checkForwardsHost(options) {
1075
1077
  configNeeded();
1076
1078
  const params = options.replacements;
1077
- const myEnvHosts = apiUtil$1.getEnvHosts(params);
1078
- const myIp = ppUtil$3.getMyIp();
1079
+ const myEnvHosts = apiUtil$2.getEnvHosts(params);
1080
+ const myIp = ppUtil$4.getMyIp();
1079
1081
  const host = params.host || myIp;
1080
- if (!myEnvHosts.hosts.contains(host)) throw [err$1.ACCESS_REFUSED, `环境${conf$2.envId}貌似无此主机:${params.host}`];
1082
+ if (!myEnvHosts.hosts.contains(host)) throw [err$2.ACCESS_REFUSED, `环境${conf$3.envId}貌似无此主机:${params.host}`];
1081
1083
 
1082
- if (!apiUtil$1.hostIsMySelf(host, options._res.req)) {
1083
- let result = await apiUtil$1.forwardsTo(host, myEnvHosts.port, params, options._res.req, myIp);
1084
+ if (!apiUtil$2.hostIsMySelf(host, options._res.req)) {
1085
+ let result = await apiUtil$2.forwardsTo(host, myEnvHosts.port, params, options._res.req, myIp);
1084
1086
 
1085
1087
  options._res.send(result);
1086
1088
 
@@ -1116,7 +1118,7 @@ class apiUtil$1 {
1116
1118
 
1117
1119
  if (result.status !== 200) {
1118
1120
  console.log(`访问 ${reqOptions.url} 出错`, result.status, result.res.statusMessage);
1119
- throw [err$1.EXCEPTION, `[${result.status}] - ${result.res.statusMessage}`];
1121
+ throw [err$2.EXCEPTION, `[${result.status}] - ${result.res.statusMessage}`];
1120
1122
  }
1121
1123
 
1122
1124
  return result.data;
@@ -1132,7 +1134,7 @@ class apiUtil$1 {
1132
1134
  let keys = Array.isArray(keyPath) ? keyPath : keyPath.split(".");
1133
1135
  let parentKey = "";
1134
1136
  let key = "config";
1135
- let value = conf$2;
1137
+ let value = conf$3;
1136
1138
  let parent = null;
1137
1139
 
1138
1140
  for (let i = 0; i < keys.length; i++) {
@@ -1142,7 +1144,7 @@ class apiUtil$1 {
1142
1144
  value = parent[key];
1143
1145
 
1144
1146
  if (value === undefined) {
1145
- throw [err$1.INVALID_PARAM, `无此配置项: ${key}`];
1147
+ throw [err$2.INVALID_PARAM, `无此配置项: ${key}`];
1146
1148
  }
1147
1149
  }
1148
1150
 
@@ -1162,10 +1164,10 @@ class apiUtil$1 {
1162
1164
 
1163
1165
  static async $checkToken(req, res, next) {
1164
1166
  try {
1165
- await apiUtil$1.checkRequestToken(req);
1167
+ await apiUtil$2.checkRequestToken(req);
1166
1168
  await next();
1167
1169
  } catch (e) {
1168
- res.send(err$1.ERROR(e));
1170
+ res.send(err$2.ERROR(e));
1169
1171
  }
1170
1172
 
1171
1173
  return false;
@@ -1182,7 +1184,7 @@ class apiUtil$1 {
1182
1184
  let token = req.headers["access_token"] || req.headers['x-access-token']; //向后兼容
1183
1185
 
1184
1186
  if (!token) {
1185
- let params = apiUtil$1.extractParams(req);
1187
+ let params = apiUtil$2.extractParams(req);
1186
1188
  token = params["access_token"];
1187
1189
 
1188
1190
  if (token) {
@@ -1205,15 +1207,15 @@ class apiUtil$1 {
1205
1207
 
1206
1208
  try {
1207
1209
  if (extractToken(req, res)) {
1208
- await apiUtil$1.restoreTokenData(apiUtil$1.userTokenStoreKey(req.accessToken), apiUtil$1.tokenExpireTime(req)).then(function (data) {
1209
- req.userInfo = apiUtil$1.setUserIdNo(data, data._idNo);
1210
+ await apiUtil$2.restoreTokenData(apiUtil$2.userTokenStoreKey(req.accessToken), apiUtil$2.tokenExpireTime(req)).then(function (data) {
1211
+ req.userInfo = apiUtil$2.setUserIdNo(data, data._idNo);
1210
1212
  }, function (e) {//no token
1211
1213
  });
1212
1214
  }
1213
1215
 
1214
1216
  return true;
1215
1217
  } catch (e) {
1216
- res.send(err$1.ERROR(e));
1218
+ res.send(err$2.ERROR(e));
1217
1219
  return false;
1218
1220
  }
1219
1221
  }
@@ -1236,7 +1238,7 @@ class apiUtil$1 {
1236
1238
  req.isMobile = true;
1237
1239
 
1238
1240
  if (!req.signatureVerified) {
1239
- let params = apiUtil$1.extractParams(req);
1241
+ let params = apiUtil$2.extractParams(req);
1240
1242
  moveProperty(params, req.headers, "access_token");
1241
1243
  moveProperty(params, req.headers, "timestamp");
1242
1244
 
@@ -1257,25 +1259,25 @@ class apiUtil$1 {
1257
1259
 
1258
1260
  static $checkApiKeyOld(req, res, next) {
1259
1261
  //检查post的信息或者url查询参数或者头信息
1260
- let tokenData = apiUtil$1.extractTokenData(req);
1261
- let params = apiUtil$1.extractParams(req);
1262
- apiUtil$1.createApiCallRec(tokenData, req);
1262
+ let tokenData = apiUtil$2.extractTokenData(req);
1263
+ let params = apiUtil$2.extractParams(req);
1264
+ apiUtil$2.createApiCallRec(tokenData, req);
1263
1265
  let errResponse = null;
1264
1266
 
1265
1267
  if (!tokenData.clientIp) {
1266
- errResponse = apiUtil$1.spoApiFail(err$1.GET_CLIENTIP_FAIL, req);
1268
+ errResponse = apiUtil$2.spoApiFail(err$2.GET_CLIENTIP_FAIL, req);
1267
1269
  } else if (!tokenData.apiKey) {
1268
- errResponse = apiUtil$1.spoApiFail([err$1.PARAMETER_NEEDED, "apiKey"], req);
1270
+ errResponse = apiUtil$2.spoApiFail([err$2.PARAMETER_NEEDED, "apiKey"], req);
1269
1271
  } else if (!tokenData.apiSecret) {
1270
- errResponse = apiUtil$1.spoApiFail([err$1.PARAMETER_NEEDED, "apiSecret"], req);
1272
+ errResponse = apiUtil$2.spoApiFail([err$2.PARAMETER_NEEDED, "apiSecret"], req);
1271
1273
  }
1272
1274
 
1273
1275
  if (errResponse != null) {
1274
- apiUtil$1._saveApiCallRec(req.apiCallRec, errResponse);
1276
+ apiUtil$2._saveApiCallRec(req.apiCallRec, errResponse);
1275
1277
 
1276
- apiUtil$1.sendOrRedirect(req, res, errResponse);
1278
+ apiUtil$2.sendOrRedirect(req, res, errResponse);
1277
1279
  } else {
1278
- apiUtil$1.checkApiCallValid(tokenData, req).then(companyInfo => {
1280
+ apiUtil$2.checkApiCallValid(tokenData, req).then(companyInfo => {
1279
1281
  params.companyId = params.companyId || companyInfo.companyId;
1280
1282
  req.companyInfo = companyInfo;
1281
1283
  next();
@@ -1283,9 +1285,9 @@ class apiUtil$1 {
1283
1285
  console.log('apiCallInvalid:', e);
1284
1286
  let errResponse = spoApiFail(e, req);
1285
1287
 
1286
- apiUtil$1._saveApiCallRec(req.apiCallRec, errResponse);
1288
+ apiUtil$2._saveApiCallRec(req.apiCallRec, errResponse);
1287
1289
 
1288
- apiUtil$1.sendOrRedirect(req, res, errResponse);
1290
+ apiUtil$2.sendOrRedirect(req, res, errResponse);
1289
1291
  });
1290
1292
  }
1291
1293
  }
@@ -1300,31 +1302,31 @@ class apiUtil$1 {
1300
1302
  return;
1301
1303
  }
1302
1304
 
1303
- let accessToken = apiUtil$1.extractToken(req);
1305
+ let accessToken = apiUtil$2.extractToken(req);
1304
1306
 
1305
1307
  if (!accessToken) {
1306
- res.send(apiUtil$1.spoApiFail(err$1.TOKEN_NEEDED, req)); // apiUtil.sendOrRedirect(req, res, spoApiFail(err.TOKEN_NEEDED, req));
1308
+ res.send(apiUtil$2.spoApiFail(err$2.TOKEN_NEEDED, req)); // apiUtil.sendOrRedirect(req, res, spoApiFail(err.TOKEN_NEEDED, req));
1307
1309
 
1308
1310
  return;
1309
1311
  }
1310
1312
 
1311
- apiUtil$1.restoreTokenData(apiUtil$1.apiTokenStoreKey(accessToken)).then(p => {
1313
+ apiUtil$2.restoreTokenData(apiUtil$2.apiTokenStoreKey(accessToken)).then(p => {
1312
1314
  // req.headers[hnApiKey] = p.apiKey || '';
1313
1315
  // req.headers[hnApiSecret] = p.apiSecret || '';
1314
1316
  if (req.isMobile) {
1315
1317
  // GET 请求的应该都是H5页面,由手机前端发起,需要把headers中的请求方ip换成服务端的
1316
1318
  // todo: 如何在API访问记录中记住请求者(手机端)的真实IP
1317
- req.headers['x-phone-ip'] = apiUtil$1.getClientIp(req);
1319
+ req.headers['x-phone-ip'] = apiUtil$2.getClientIp(req);
1318
1320
  req.headers['x-real-ip'] = p.clientIp;
1319
1321
  } else {
1320
- p.clientIp = apiUtil$1.getClientIp(req);
1322
+ p.clientIp = apiUtil$2.getClientIp(req);
1321
1323
  }
1322
1324
 
1323
1325
  req.isApiCall = true;
1324
1326
  req.tokenData = p;
1325
- return apiUtil$1.$checkApiKeyOld(req, res, next);
1327
+ return apiUtil$2.$checkApiKeyOld(req, res, next);
1326
1328
  }).catch(e => {
1327
- apiUtil$1.sendOrRedirect(req, res, apiUtil$1.spoApiFail(err$1.TOKEN_INVALID, req));
1329
+ apiUtil$2.sendOrRedirect(req, res, apiUtil$2.spoApiFail(err$2.TOKEN_INVALID, req));
1328
1330
  });
1329
1331
  }
1330
1332
  /**
@@ -1337,24 +1339,24 @@ class apiUtil$1 {
1337
1339
 
1338
1340
 
1339
1341
  static async $checkTokenOrApiKey(req, res, next) {
1340
- let accessToken = apiUtil$1.extractToken(req, res);
1342
+ let accessToken = apiUtil$2.extractToken(req, res);
1341
1343
 
1342
1344
  if (accessToken) {
1343
- let tokenExist = await apiUtil$1.tokenDataExist(apiUtil$1.userTokenStoreKey(accessToken));
1345
+ let tokenExist = await apiUtil$2.tokenDataExist(apiUtil$2.userTokenStoreKey(accessToken));
1344
1346
 
1345
1347
  if (tokenExist) {
1346
- return await apiUtil$1.$checkToken(req, res, next);
1348
+ return await apiUtil$2.$checkToken(req, res, next);
1347
1349
  }
1348
1350
 
1349
- tokenExist = await apiUtil$1.tokenDataExist(apiUtil$1.apiTokenStoreKey(accessToken));
1351
+ tokenExist = await apiUtil$2.tokenDataExist(apiUtil$2.apiTokenStoreKey(accessToken));
1350
1352
 
1351
1353
  if (tokenExist) {
1352
- return apiUtil$1.$checkApiKey(req, res, next);
1354
+ return apiUtil$2.$checkApiKey(req, res, next);
1353
1355
  } // 如果给定的token不存在,看看是不是平台内部调用
1354
1356
 
1355
1357
 
1356
- return await apiUtil$1.checkInternalToken(req).catch(e => {
1357
- res.send(apiUtil$1.apiFail(e, req));
1358
+ return await apiUtil$2.checkInternalToken(req).catch(e => {
1359
+ res.send(apiUtil$2.apiFail(e, req));
1358
1360
  return false;
1359
1361
  });
1360
1362
  }
@@ -1374,10 +1376,10 @@ class apiUtil$1 {
1374
1376
  const params = options.replacements;
1375
1377
  let item = params.item;
1376
1378
  delete params.item;
1377
- if (await apiUtil$1.checkForwardsHost(options)) return true;
1378
- let c = apiUtil$1.parseCfgPath(item);
1379
+ if (await apiUtil$2.checkForwardsHost(options)) return true;
1380
+ let c = apiUtil$2.parseCfgPath(item);
1379
1381
  delete c.parent;
1380
- c.host = ppUtil$3.getMyIp();
1382
+ c.host = ppUtil$4.getMyIp();
1381
1383
  return c;
1382
1384
  }
1383
1385
  /**
@@ -1394,40 +1396,59 @@ class apiUtil$1 {
1394
1396
  delete params.item; // if (await checkForwardsHost(options))
1395
1397
  // return true;
1396
1398
 
1397
- await apiUtil$1.parametersOK(params, "value");
1398
- let c = apiUtil$1.parseCfgPath(item);
1399
+ await apiUtil$2.parametersOK(params, "value");
1400
+ let c = apiUtil$2.parseCfgPath(item);
1399
1401
 
1400
1402
  if (typeof c.value === "object") {
1401
- throw [err$1.ACCESS_REFUSED, `暂不支持修改复杂配置`];
1403
+ throw [err$2.ACCESS_REFUSED, `暂不支持修改复杂配置`];
1402
1404
  } // c.oldValue = c.value;
1403
1405
 
1404
1406
 
1405
1407
  c.newValue = params.value;
1406
1408
  c.parent[c.key] = c.newValue;
1407
1409
  delete c.parent;
1408
- c.host = ppUtil$3.getMyIp();
1410
+ c.host = ppUtil$4.getMyIp();
1409
1411
  return c; // 应用层自行处理多机同步
1412
+ }
1413
+ /**
1414
+ * 修改重启标志文件
1415
+ * 前提,PM2监视 restart,please.flag 文件,此文件若被修改则重启服务进程
1416
+ * 此服务假设 restart,please.flag 文件最后一行是一个整数,此整数+1后保存
1417
+ * @param options
1418
+ * @returns {Promise<number>}
1419
+ */
1420
+
1421
+
1422
+ static async updateRestartFlag(options) {
1423
+ const fileName = `restart,please.flag`;
1424
+ let text = await fs$1.async_readFile(fileName, 'utf8');
1425
+ const lines = text.split('\r\n');
1426
+ const n = +lines[lines.length - 1] + 1;
1427
+ lines[lines.length - 1] = ' '.repeat(50) + n.toString();
1428
+ text = lines.join('\r\n');
1429
+ await fs$1.async_writeFile(fileName, text);
1430
+ return n;
1410
1431
  } //#endregion
1411
1432
 
1412
1433
 
1413
1434
  }
1414
1435
 
1415
1436
  function configNeeded() {
1416
- if (!conf$2 || !err$1) {
1417
- ppUtil$3.configNeeded();
1418
- conf$2 = ppUtil$3.appConfig;
1419
- appSetting$1 = conf$2.appSetting;
1420
- err$1 = ppUtil$3.appErrCfg;
1437
+ if (!conf$3 || !err$2) {
1438
+ ppUtil$4.configNeeded();
1439
+ conf$3 = ppUtil$4.appConfig;
1440
+ appSetting$1 = conf$3.appSetting;
1441
+ err$2 = ppUtil$4.appErrCfg;
1421
1442
  }
1422
1443
  }
1423
1444
 
1424
- var ppUtilApi = apiUtil$1;
1445
+ var ppUtilApi = apiUtil$2;
1425
1446
 
1426
- const fs = require$$0$1;
1447
+ const fs = require$$4;
1427
1448
  const path = require$$1$1;
1428
- const ppUtil$2 = require$$1.ppUtil;
1449
+ const ppUtil$3 = require$$1.ppUtil;
1429
1450
  const redisUtil = require$$2.redisUtil;
1430
- let conf$1, err; // const dbCheck = require('../dbupdate/dd-version');
1451
+ let conf$2, err$1; // const dbCheck = require('../dbupdate/dd-version');
1431
1452
 
1432
1453
  /**
1433
1454
  * API服务启动时前置条件检查
@@ -1446,10 +1467,10 @@ class preconditions$1 {
1446
1467
  static checkPromises = [];
1447
1468
 
1448
1469
  static setAppName(aName) {
1449
- ppUtil$2.configNeeded();
1450
- conf$1 = ppUtil$2.appConfig;
1451
- err = ppUtil$2.appErrCfg;
1452
- preconditions$1.appName = aName || conf$1.thisApp;
1470
+ ppUtil$3.configNeeded();
1471
+ conf$2 = ppUtil$3.appConfig;
1472
+ err$1 = ppUtil$3.appErrCfg;
1473
+ preconditions$1.appName = aName || conf$2.thisApp;
1453
1474
  return preconditions$1;
1454
1475
  }
1455
1476
 
@@ -1528,22 +1549,22 @@ class preconditions$1 {
1528
1549
 
1529
1550
  async function createEnvSettingFile(fileName) {
1530
1551
  try {
1531
- const cfgText = await ppUtil$2.doCreateEnvSettingFile(fileName);
1552
+ const cfgText = await ppUtil$3.doCreateEnvSettingFile(fileName);
1532
1553
 
1533
- if (cfgText.indexOf(`cfgVersion: "${conf$1._envSetting.cfgVersion}"`) > 0) {
1554
+ if (cfgText.indexOf(`cfgVersion: "${conf$2._envSetting.cfgVersion}"`) > 0) {
1534
1555
  console.log(`\n*** 已創建新的本機環境配置文件\n${fileName}\n请檢查各項內容是否正确(此项更新服务可正常运行)\n\n`);
1535
1556
  return "";
1536
1557
  }
1537
1558
 
1538
- return `已創建新的本機環境配置文件\n${fileName}\n请檢查並正確設置各項內容,然後將配置版本號修改為${conf$1._envSettings.default.cfgVersion}`;
1559
+ return `已創建新的本機環境配置文件\n${fileName}\n请檢查並正確設置各項內容,然後將配置版本號修改為${conf$2._envSettings.default.cfgVersion}`;
1539
1560
  } catch (e) {
1540
- return `創建本機環境配置文件失敗\n《${fileName}》\n${err.ERROR(e).message}`;
1561
+ return `創建本機環境配置文件失敗\n《${fileName}》\n${err$1.ERROR(e).message}`;
1541
1562
  }
1542
1563
  }
1543
1564
 
1544
1565
  async function checkExEnvSetting(loadjs) {
1545
- if (!conf$1._envSetting.localSettingImported) {
1546
- let fileName = conf$1.getEnvSettingFileName();
1566
+ if (!conf$2._envSetting.localSettingImported) {
1567
+ let fileName = conf$2.getEnvSettingFileName();
1547
1568
 
1548
1569
  if (!fs.existsSync(fileName)) {
1549
1570
  return await createEnvSettingFile(fileName);
@@ -1551,7 +1572,7 @@ async function checkExEnvSetting(loadjs) {
1551
1572
 
1552
1573
  let envSettingEx = loadjs(fileName);
1553
1574
 
1554
- if (envSettingEx.cfgVersion !== conf$1._envSettings.default.cfgVersion) {
1575
+ if (envSettingEx.cfgVersion !== conf$2._envSettings.default.cfgVersion) {
1555
1576
  if (envSettingEx.cfgVersion !== "0.0") {
1556
1577
  let fp = path.parse(fileName);
1557
1578
  let newFileName = path.join(fp.dir, fp.name + envSettingEx.cfgVersion + fp.ext);
@@ -1570,10 +1591,10 @@ async function checkExEnvSetting(loadjs) {
1570
1591
 
1571
1592
 
1572
1593
  async function checkRedis() {
1573
- if (!conf$1.redis.enabled) return "";
1594
+ if (!conf$2.redis.enabled) return "";
1574
1595
  const redis = redisUtil.newClient("io"); // console.log(`checkRedis begin:`);
1575
1596
 
1576
- await ppUtil$2.wait(15 * 1000, param => {
1597
+ await ppUtil$3.wait(15 * 1000, param => {
1577
1598
  if (redis.ready && redis.connected || redis.error) {
1578
1599
  return true;
1579
1600
  }
@@ -1595,39 +1616,39 @@ var ppPrecond = preconditions$1;
1595
1616
  // 若 redis 不可用,则将消息转发到其它主机
1596
1617
 
1597
1618
  const {
1598
- ppUtil: ppUtil$1
1619
+ ppUtil: ppUtil$2
1599
1620
  } = require$$1;
1600
1621
  const RedisMessenger = require$$1$2;
1601
1622
  const {
1602
1623
  netUtil
1603
1624
  } = require$$3;
1604
- let conf;
1625
+ let conf$1;
1605
1626
 
1606
- class commonMessenger$1 {
1627
+ class commonMessenger$2 {
1607
1628
  static myMsgAddr = "";
1608
1629
  static redisMessenger = null;
1609
1630
  static onMessage = [];
1610
1631
 
1611
1632
  static initMessenger(appConfig, appErrCfg, msgChannel) {
1612
- conf = appConfig;
1613
- this.redisMessenger = conf.redis.enabled ? new RedisMessenger(appConfig, appErrCfg, msgChannel).subscribe(msgChannel) : null;
1614
- this.myMsgAddr = commonMessenger$1.getMyMsgAddr();
1633
+ conf$1 = appConfig;
1634
+ this.redisMessenger = conf$1.redis.enabled ? new RedisMessenger(appConfig, appErrCfg, msgChannel).subscribe(msgChannel) : null;
1635
+ this.myMsgAddr = commonMessenger$2.getMyMsgAddr();
1615
1636
  }
1616
1637
 
1617
1638
  static getMyMsgAddr() {
1618
- if (!conf.myMsgAddr) {
1619
- conf.pm_id = process.env.pm_id || "0";
1620
- let myIp = ppUtil$1.getMyIp();
1639
+ if (!conf$1.myMsgAddr) {
1640
+ conf$1.pm_id = process.env.pm_id || "0";
1641
+ let myIp = ppUtil$2.getMyIp();
1621
1642
 
1622
1643
  if (this.redisMessenger) {
1623
- myIp = `${conf.pm_id}@${myIp}`;
1644
+ myIp = `${conf$1.pm_id}@${myIp}`;
1624
1645
  }
1625
1646
 
1626
- conf.myMsgAddr = myIp;
1627
- console.log(`myMsgAddr: `, conf.myMsgAddr);
1647
+ conf$1.myMsgAddr = myIp;
1648
+ console.log(`myMsgAddr: `, conf$1.myMsgAddr);
1628
1649
  }
1629
1650
 
1630
- return conf.myMsgAddr;
1651
+ return conf$1.myMsgAddr;
1631
1652
  }
1632
1653
 
1633
1654
  static setMessageHandle(messageHandle) {
@@ -1635,11 +1656,11 @@ class commonMessenger$1 {
1635
1656
  return this.redisMessenger.setMessageHandle(messageHandle, msgChannel);
1636
1657
  }
1637
1658
 
1638
- if (commonMessenger$1.onMessage.indexOf(messageHandle) < 0) {
1639
- commonMessenger$1.onMessage.push(messageHandle);
1659
+ if (commonMessenger$2.onMessage.indexOf(messageHandle) < 0) {
1660
+ commonMessenger$2.onMessage.push(messageHandle);
1640
1661
  }
1641
1662
 
1642
- return commonMessenger$1;
1663
+ return commonMessenger$2;
1643
1664
  }
1644
1665
 
1645
1666
  static async publishMessage(message) {
@@ -1650,10 +1671,10 @@ class commonMessenger$1 {
1650
1671
  if (message.destAddr) {
1651
1672
  await forwardMessage(message);
1652
1673
  } else {
1653
- for (let i = 0; i < conf.appSetting.serverHosts.length; i++) {
1654
- message.destAddr = conf.appSetting.serverHosts[i];
1674
+ for (let i = 0; i < conf$1.appSetting.serverHosts.length; i++) {
1675
+ message.destAddr = conf$1.appSetting.serverHosts[i];
1655
1676
 
1656
- if (message.destAddr !== conf.myMsgAddr) {
1677
+ if (message.destAddr !== conf$1.myMsgAddr) {
1657
1678
  await forwardMessage(message);
1658
1679
  }
1659
1680
  }
@@ -1664,8 +1685,8 @@ class commonMessenger$1 {
1664
1685
  static async handleInternalMessage(options) {
1665
1686
  const message = options.replacements;
1666
1687
 
1667
- for (let i = 0; i < commonMessenger$1.onMessage.length; i++) {
1668
- const appMsgHandle = commonMessenger$1.onMessage[i];
1688
+ for (let i = 0; i < commonMessenger$2.onMessage.length; i++) {
1689
+ const appMsgHandle = commonMessenger$2.onMessage[i];
1669
1690
 
1670
1691
  try {
1671
1692
  await appMsgHandle(message);
@@ -1690,15 +1711,293 @@ async function forwardMessage(message) {
1690
1711
  return res.data;
1691
1712
  }
1692
1713
 
1693
- var ppMessengerEx = commonMessenger$1;
1714
+ var ppMessengerEx = commonMessenger$2;
1715
+
1716
+ /**
1717
+ * CSCA 自动任务
1718
+ * ==============
1719
+ */
1720
+ const CRON = require$$0$1;
1721
+ const {
1722
+ ppUtil: ppUtil$1
1723
+ } = require$$1;
1724
+ const apiUtil$1 = ppUtilApi;
1725
+ const commonMessenger$1 = ppMessengerEx;
1726
+ const MT_SCHEDULE_STATE = 'schedule-state',
1727
+ MT_SCHEDULE_STATE_REPLY = 'schedule-state-reply';
1728
+ let conf, err;
1729
+
1730
+ class schedule$1 {
1731
+ static tasks = {};
1732
+ /**
1733
+ * 注册一个计划任务
1734
+ * @param taskName
1735
+ * @param taskCaption
1736
+ * @param cronExp
1737
+ * @param taskFunc
1738
+ * @param autoStart
1739
+ * @returns {Promise<{}|{}|{cron: *, _message_: string}|any>}
1740
+ */
1741
+
1742
+ static async registerTask(taskName, taskCaption, cronExp, taskFunc, autoStart) {
1743
+ if (!conf) {
1744
+ ppUtil$1.configNeeded();
1745
+ conf = ppUtil$1.appConfig;
1746
+ err = ppUtil$1.appErrCfg;
1747
+ }
1748
+
1749
+ if (!this.envAllowed()) return {};
1750
+ let task = this.findTask(taskName);
1751
+
1752
+ if (task) {
1753
+ if (task.cronExp !== cronExp || task.taskFunc !== taskFunc) {
1754
+ this.stop(taskName);
1755
+ task = null;
1756
+ }
1757
+ }
1758
+
1759
+ if (!task) {
1760
+ task = {
1761
+ name: taskName,
1762
+ caption: taskCaption,
1763
+ cronExp: cronExp,
1764
+ taskFunc: taskFunc,
1765
+ schedule: null,
1766
+ doScheduleTask: async function () {
1767
+ let self = this;
1768
+ if (this._pp_task) self = this._pp_task;
1769
+ console.log(new Date().format('[yyyy/MM/dd hh:mm:ss:S]'), `开始执行${self.caption}任务 ...`);
1770
+ await self.taskFunc();
1771
+ console.log(new Date().format('[yyyy/MM/dd hh:mm:ss:S]'), `${self.caption}任务执行结束`);
1772
+ }
1773
+ };
1774
+ this.tasks[taskName] = task;
1775
+
1776
+ if (autoStart) {
1777
+ return await this.start(task);
1778
+ }
1779
+
1780
+ return this.getTaskInfo(task, "任务已注册。");
1781
+ }
1782
+
1783
+ return this.getTaskInfo(task, "任务已存在。");
1784
+ }
1785
+
1786
+ static getTaskInfo(task, msg) {
1787
+ // return Object.assign({_message_: msg}, task);
1788
+ return {
1789
+ name: task.name,
1790
+ caption: task.caption,
1791
+ cronExp: task.cronExp,
1792
+ state: task.schedule ? "started" : "stopped",
1793
+ _message_: msg
1794
+ };
1795
+ }
1796
+ /**
1797
+ * 启动任务
1798
+ * @param taskOrName
1799
+ * @param cronExp
1800
+ * @returns {Promise<{}|{cron: *, _message_: string}>}
1801
+ */
1802
+
1803
+
1804
+ static async start(taskOrName, cronExp) {
1805
+ if (!this.envAllowed()) return {};
1806
+ let task = taskOrName;
1807
+
1808
+ if (typeof task === "string") {
1809
+ task = this.findTask(taskOrName);
1810
+ }
1811
+
1812
+ if (!task) throw [err.INVALID_PARAM, `任务${taskOrName}不存在`];
1813
+ cronExp = cronExp || task.cronExp;
1814
+
1815
+ if (task.cronExp !== cronExp) {
1816
+ this.stop(task);
1817
+ task.cronExp = cronExp;
1818
+ }
1819
+
1820
+ if (task.schedule) {
1821
+ return this.getTaskInfo(task, "任务已启动,无需重复启动。");
1822
+ }
1823
+
1824
+ task.schedule = CRON.schedule(cronExp, task.doScheduleTask);
1825
+ task.schedule._task._pp_task = task;
1826
+ return this.getTaskInfo(task, "任务已启动。");
1827
+ }
1828
+ /**
1829
+ * 停止任务
1830
+ * @param taskOrName
1831
+ * @returns {Promise<{}|{cron: *, _message_: string}|{_message_: string}>}
1832
+ */
1833
+
1834
+
1835
+ static async stop(taskOrName) {
1836
+ if (!this.envAllowed()) return {};
1837
+ let task = taskOrName;
1838
+
1839
+ if (typeof task === "string") {
1840
+ task = this.findTask(taskOrName);
1841
+ }
1842
+
1843
+ if (!task) throw [err.INVALID_PARAM, `任务${taskOrName}不存在`];
1844
+
1845
+ if (task.schedule) {
1846
+ task.schedule.stop();
1847
+ task.schedule = null;
1848
+ return this.getTaskInfo(task, "任务已停止。");
1849
+ }
1850
+
1851
+ return this.getTaskInfo(task, "任务未启动,无需停止。");
1852
+ }
1853
+ /**
1854
+ * 获取或设置当前状态(来自远程的API调用)
1855
+ * @param options
1856
+ * @returns {Promise<unknown>}
1857
+ */
1858
+
1859
+
1860
+ static async state(options) {
1861
+ const params = options.replacements; // await commonMessenger.parametersOK(params, "taskName");
1862
+
1863
+ const req = options._res.req;
1864
+
1865
+ if (req) {
1866
+ if (req.method === 'GET') {
1867
+ delete params.state;
1868
+ } else {
1869
+ await apiUtil$1.parametersOK(params, 'taskName', "state");
1870
+ }
1871
+ }
1872
+
1873
+ if (this.envAllowed()) {
1874
+ return this._state(params);
1875
+ } // 环境变量启用计划任务,但当前环境不能执行,
1876
+ // 说明收到此API请求的进程不是第一个进程,或者此前服务器不是第一台服务器,
1877
+ // 这种情况下,将此请求作为消息发布出去,
1878
+ // 第一台服务器的第一个进程收到消息后进行处理,再将结果作为消息发布,
1879
+ // 本进程收到处理结果后果作为响应发送回客户端
1880
+
1881
+
1882
+ if (process.env.SCHEDULE_ENABLED) {
1883
+ let replyId = ppUtil$1.newGuid();
1884
+ return await new Promise((resolve, reject) => {
1885
+ commonMessenger$1.setMessageHandle(message => {
1886
+ if (message._type === MT_SCHEDULE_STATE_REPLY && message.replyId === replyId) {
1887
+ replyId = '';
1888
+ resolve(message.result);
1889
+ return;
1890
+ }
1891
+
1892
+ if (message._type === MT_SCHEDULE_STATE) {
1893
+ if (schedule$1.enabled()) {
1894
+ message.result = schedule$1._state(message.params);
1895
+ message._type = MT_SCHEDULE_STATE_REPLY;
1896
+ message.destAddr = message.replyAddr;
1897
+ commonMessenger$1.publishMessage(message);
1898
+ }
1899
+ }
1900
+ });
1901
+ commonMessenger$1.publishMessage({
1902
+ _type: MT_SCHEDULE_STATE,
1903
+ replyId,
1904
+ replyAddr: conf.myMsgAddr,
1905
+ params
1906
+ }).catch(e => {
1907
+ replyId = '';
1908
+ reject(e);
1909
+ });
1910
+ setTimeout(() => {
1911
+ if (replyId) {
1912
+ reject("schedule.state: 等待处理结果超时");
1913
+ }
1914
+ }, 2 * 60 * 1000);
1915
+ });
1916
+ }
1917
+
1918
+ return {
1919
+ _message_: "此环境无自动任务"
1920
+ };
1921
+ }
1922
+
1923
+ static async _state(params) {
1924
+ let apiResult = {};
1925
+ let task;
1926
+
1927
+ if (params.taskName) {
1928
+ task = this.findTask(params.taskName);
1929
+ if (!task) throw [err.INVALID_PARAM, `任务${params.taskName}不存在`];
1930
+ }
1931
+
1932
+ if (params.state) {
1933
+ if ("started" === params.state) {
1934
+ apiResult = await this.start(task, params.cron);
1935
+ } else if ("stopped" === params.state) {
1936
+ apiResult = await this.stop(task);
1937
+ } else {
1938
+ throw [err.INVALID_PARAM, `(${params.state}), 只能是 started/stopped`];
1939
+ }
1940
+
1941
+ if (params.runOnce) {
1942
+ task = this.findTask(params.taskName);
1943
+ apiResult._message_ += "\n正在手动执行任务"; // await
1944
+
1945
+ task.doScheduleTask();
1946
+ }
1947
+
1948
+ return this.getTaskInfo(task, apiResult._message_);
1949
+ }
1950
+
1951
+ if (task) {
1952
+ return this.getTaskInfo(task);
1953
+ }
1954
+
1955
+ const result = [];
1956
+
1957
+ for (let k in this.tasks) {
1958
+ result.push(this.getTaskInfo(this.tasks[k]));
1959
+ }
1960
+
1961
+ return result;
1962
+ }
1963
+
1964
+ static deleteTask(taskName) {
1965
+ delete this.tasks[taskName];
1966
+ }
1967
+
1968
+ static findTask(taskName) {
1969
+ return this.tasks[taskName];
1970
+ }
1971
+ /**
1972
+ * 确定当前进程环境是否启用自动任务
1973
+ */
1974
+
1975
+
1976
+ static envAllowed() {
1977
+ let enabled = // PM2配置中指定了环境变量 SCHEDULE_ENABLED
1978
+ !!process.env.SCHEDULE_ENABLED // 如果PM2启动了多个进程,则只在第一个进程执行
1979
+ && process.env.NODE_APP_INSTANCE === '0'; // 如果有多台服务器,则只在第一台执行
1980
+
1981
+ if (enabled && conf.appSetting.serverHosts && conf.appSetting.serverHosts.length > 1) {
1982
+ enabled = conf.myMsgAddr.indexOf(conf.appSetting.serverHosts[0]) === 0;
1983
+ }
1984
+
1985
+ return enabled;
1986
+ }
1987
+
1988
+ }
1989
+
1990
+ var ppSchedule = schedule$1;
1694
1991
 
1695
1992
  const apiUtil = ppUtilApi;
1696
1993
  const preconditions = ppPrecond;
1697
1994
  const commonMessenger = ppMessengerEx;
1995
+ const schedule = ppSchedule;
1698
1996
  var ppUtil = {
1699
1997
  apiUtil,
1700
1998
  preconditions,
1701
- commonMessenger
1999
+ commonMessenger,
2000
+ schedule
1702
2001
  };
1703
2002
 
1704
2003
  export { ppUtil as default };