abler-api 0.1.27 → 0.1.28

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