@ckstack/ck-push-sender
Version:
push sender server module
647 lines (646 loc) • 35.7 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __asyncValues = (this && this.__asyncValues) || function (o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const JSON5 = __importStar(require("json5"));
const _ = __importStar(require("underscore"));
const firebase_admin_1 = __importDefault(require("firebase-admin"));
const fs = __importStar(require("fs"));
const dk_lib_1 = require("@dkpkg/dk-lib");
const ck_lib_sequelize_1 = require("@ckstack/ck-lib-sequelize");
const ck_lib_models_1 = require("@ckstack/ck-lib-models");
const dk_lib_slack_1 = require("@dkpkg/dk-lib-slack");
const ck_lib_gw_1 = require("@ckstack/ck-lib-gw");
const MyConfig_1 = require("../../../MyConfig");
const MyValues_1 = require("../../../MyValues");
class PushGoogleFCM {
constructor(delayVendor) {
this.delayVendor = delayVendor;
if (!fs.existsSync(MyConfig_1.conf.HTF_PUSH_VENDOR_FCM_AUTH_FILE_PATH)) {
dk_lib_1.CkLogger.errLog2(`not found google FCM auth json file [${MyConfig_1.conf.HTF_PUSH_VENDOR_FCM_AUTH_FILE_PATH}]. process terminate.`, MyValues_1.PROC_LHD.LHD);
dk_lib_slack_1.CkSlack.sendMessageServerStartFailAndProcessKill(`not found google FCM auth json file [${MyConfig_1.conf.HTF_PUSH_VENDOR_FCM_AUTH_FILE_PATH}]. process terminate.`);
return;
}
const cert = require(MyConfig_1.conf.HTF_PUSH_VENDOR_FCM_AUTH_FILE_PATH);
const credential = firebase_admin_1.default.credential.cert(cert);
this.FCM_APP = firebase_admin_1.default.initializeApp({
credential,
databaseURL: '',
});
this.FCM_MSG_HANDLER = firebase_admin_1.default.messaging(this.FCM_APP);
dk_lib_1.CkLogger.infoLog('create Google FCM Push client', MyValues_1.PROC_LHD.LHD);
}
connect() {
return __awaiter(this, void 0, void 0, function* () {
dk_lib_1.CkLogger.debugLog('using FCM. not need connect push server', MyValues_1.PROC_LHD.LHD);
});
}
validateMessage(_lhd, _msgData) {
const lhd = _lhd || `${MyValues_1.PROC_LHD.IP_LHD_HTTP}`;
const msgData = _msgData;
if (!msgData.yyyymm) {
dk_lib_1.CkLogger.warnLog2(`invalid request. no yyyymm. yyyymm [${msgData.yyyymm}]`, lhd);
return undefined;
}
if (msgData.tokens === undefined || msgData.tokens.length <= 0) {
dk_lib_1.CkLogger.warnLog2(`invalid request. no fcm token. tokens [${JSON5.stringify(msgData.tokens)}]`, lhd);
return undefined;
}
if (msgData.tokens.length > 500) {
dk_lib_1.CkLogger.errLog2(`fcm broadcast target max count is 500. request target count is [${msgData.tokens.length}]`, lhd);
return undefined;
}
msgData.isBearerArrivalCb = true;
if (!msgData.targetUserIds || msgData.targetUserIds.length <= 0) {
msgData.targetUserIds = [];
for (const row of msgData.tokens) {
msgData.targetUserIds.push(dk_lib_1.CkCrypto.md5Hash(row));
}
msgData.isBearerArrivalCb = false;
}
if (msgData.targetUserIds && msgData.targetUserIds.length > 0 && (msgData.targetUserIds.length !== msgData.tokens.length)) {
dk_lib_1.CkLogger.errLog2('invalid request. targetUserIds, tokens length is different. '
+ `targetUserIds length [${msgData.targetUserIds.length}], tokens length [${msgData.tokens.length}]`, lhd);
return undefined;
}
if (!msgData.title && !msgData.body && (msgData.data === undefined || _.size(msgData.data) <= 0)) {
dk_lib_1.CkLogger.warnLog2(`invalid request. no title [${msgData.title}], body [${msgData.body}], `
+ `data [${JSON5.stringify(msgData.data)}]`, lhd);
return undefined;
}
msgData.pushVendor = dk_lib_1.CkValue.PUSH_VENDOR_TYPE.FCM;
if (msgData.maxRetryCount && msgData.maxRetryCount > MyConfig_1.conf.HTF_PUSH_SEND_MAX_RETRY_COUNT) {
dk_lib_1.CkLogger.infoLog2(`The maximum number of resends is too large. Force the number of times. request number [${msgData.maxRetryCount}], force set number [${MyConfig_1.conf.HTF_PUSH_SEND_MAX_RETRY_COUNT}]`, lhd);
msgData.maxRetryCount = MyConfig_1.conf.HTF_PUSH_SEND_MAX_RETRY_COUNT;
}
if (msgData.maxRetryCount && msgData.maxRetryCount > 9999) {
dk_lib_1.CkLogger.warnLog2(`The maximum number of resends is too large. Force the static number. setting number [${MyConfig_1.conf.HTF_PUSH_SEND_MAX_RETRY_COUNT}], force set number [9999]`, lhd);
msgData.maxRetryCount = 9999;
}
if (msgData.currentRetryCount === undefined) {
msgData.currentRetryCount = 0;
}
const isBroadcast = (msgData.tokens.length > 1);
return { msgData, isBroadcast };
}
getPayload(_lhd, _msgData) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
const lhd = _lhd || `${MyValues_1.PROC_LHD.IP_LHD_HTTP}`;
const msgData = _msgData;
const payload = { tokens: msgData.tokens };
if (msgData.title || msgData.body) {
payload.notification = {};
payload.android = {
notification: {},
};
payload.apns = {
payload: {
aps: {
alert: {},
},
},
};
}
if (msgData.title) {
payload.notification.title = msgData.title;
payload.android.notification.title = msgData.title;
payload.apns.payload.aps.alert.title = msgData.title;
}
if (msgData.body) {
payload.notification.body = msgData.body;
payload.android.notification.body = msgData.body;
payload.apns.payload.aps.alert.body = msgData.body;
}
if (payload.notification && msgData.imageUrl) {
payload.notification.imageUrl = msgData.imageUrl;
payload.android.notification.imageUrl = msgData.imageUrl;
payload.apns.fcmOptions = { imageUrl: msgData.imageUrl };
}
if (((_a = payload.android) === null || _a === void 0 ? void 0 : _a.notification) && msgData.defaultSound !== undefined) {
payload.android.notification.defaultSound = msgData.defaultSound;
}
if (((_b = payload.android) === null || _b === void 0 ? void 0 : _b.notification)
&& ((_d = (_c = payload.apns) === null || _c === void 0 ? void 0 : _c.payload) === null || _d === void 0 ? void 0 : _d.aps)
&& msgData.sound) {
payload.android.notification.sound = msgData.sound;
payload.apns.payload.aps.sound = msgData.sound;
}
if (((_f = (_e = payload.apns) === null || _e === void 0 ? void 0 : _e.payload) === null || _f === void 0 ? void 0 : _f.aps) && msgData.badge !== undefined) {
payload.apns.payload.aps.badge = msgData.badge;
}
let isSetIosBackground = false;
let isSetAndroidBackground = false;
if (msgData.isBackground) {
if ((_h = (_g = payload.apns) === null || _g === void 0 ? void 0 : _g.payload) === null || _h === void 0 ? void 0 : _h.aps) {
payload.apns.payload.aps.contentAvailable = true;
payload.apns.headers = {};
payload.apns.headers['apns-priority'] = '5';
payload.apns.headers['apns-push-type'] = 'background';
dk_lib_1.CkLogger.debugLog2('background fcm message. set ios background push. it will add payload.apns background setup [1]', lhd);
isSetIosBackground = true;
}
if (payload.notification) {
delete payload.notification;
dk_lib_1.CkLogger.debugLog2('background fcm message. set android background push. remove notification attribute [1]', lhd);
isSetAndroidBackground = true;
}
if (payload.android && payload.android.notification) {
delete payload.android.notification;
dk_lib_1.CkLogger.debugLog2('background fcm message. set android background push. remove android.notification attribute [1]', lhd);
isSetAndroidBackground = true;
}
}
if (((_k = (_j = payload.apns) === null || _j === void 0 ? void 0 : _j.payload) === null || _k === void 0 ? void 0 : _k.aps) && msgData.isBackgroundIOS && !isSetIosBackground) {
payload.apns.payload.aps.contentAvailable = true;
payload.apns.headers = {};
payload.apns.headers['apns-priority'] = '5';
payload.apns.headers['apns-push-type'] = 'background';
dk_lib_1.CkLogger.debugLog2('background fcm message. set ios background push. it will add payload.apns background setup [2]', lhd);
}
if (payload.notification && msgData.isBackgroundAndroid && !isSetAndroidBackground) {
delete payload.notification;
dk_lib_1.CkLogger.debugLog2('background fcm message. set android background push. remove notification attribute [2]', lhd);
}
if (payload.android && payload.android.notification && msgData.isBackgroundAndroid && !isSetAndroidBackground) {
delete payload.android.notification;
dk_lib_1.CkLogger.debugLog2('background fcm message. set android background push. remove android.notification attribute [2]', lhd);
}
if (payload.android && _.size(payload.android) <= 0) {
delete payload.android;
}
if (msgData.data && _.size(msgData.data) > 0) {
payload.data = msgData.data;
}
if (!payload.data) {
payload.data = {};
}
if (msgData.arrivalCb && msgData.arrivalCb.trim()) {
payload.data.xpCb = msgData.arrivalCb.trim();
payload.data.xpCbBearer = msgData.isBearerArrivalCb ? 'true' : 'false';
dk_lib_1.CkLogger.debugLog2(`set fcm arrival callback url [${payload.data.xpCb}], isBearer [${payload.data.xpCbBearer}]`, lhd);
}
else {
dk_lib_1.CkLogger.debugLog2(`not set fcm arrival callback url. msgData.arrivalCb [${msgData.arrivalCb}]`, lhd);
}
if (!payload.data.xpTid) {
payload.data.xpTid = `${Date.now()}`;
}
if (!payload.data.xpTm) {
payload.data.xpTm = `${Math.floor(Date.now() / 1000)}`;
}
return payload;
}
sendPush(_lhd, _payload, _msgData, isBroadCast) {
var _a, e_1, _b, _c;
return __awaiter(this, void 0, void 0, function* () {
const lhd = _lhd || `${MyValues_1.PROC_LHD.IP_LHD_HTTP}`;
const payload = _payload;
const msgData = _msgData;
let { broadcastId } = msgData;
if (msgData.currentRetryCount === undefined || msgData.currentRetryCount === 0 || !broadcastId) {
broadcastId = dk_lib_1.CkUtils.getUUIDV5(`${dk_lib_1.CkUtils.getUUID()}-${Date.now()}`);
msgData.broadcastId = broadcastId;
}
if (isBroadCast === true) {
const pushId = ck_lib_gw_1.CommonService.makePushId({
broadcastId,
yyyymm: msgData.yyyymm,
retryIndex: msgData.currentRetryCount === undefined ? 0 : msgData.currentRetryCount,
}, MyConfig_1.conf.HTF_PUSH_ID_JWT_SECRET_KEY);
dk_lib_1.CkLogger.debugLog2(`send multi fcm. token count [${payload.tokens.length}], fcm payload [${JSON5.stringify(payload)}]`, lhd);
yield this.sendMultiFCM(lhd, payload, msgData, pushId, broadcastId, true);
return;
}
dk_lib_1.CkLogger.debugLog2(`send single fcm. token count [${payload.tokens.length}]`, lhd);
let idx = 0;
try {
for (var _d = true, _e = __asyncValues(payload.tokens), _f; _f = yield _e.next(), _a = _f.done, !_a;) {
_c = _f.value;
_d = false;
try {
const token = _c;
const singlePayload = Object.assign({ token }, payload);
singlePayload.tokens = undefined;
broadcastId = dk_lib_1.CkUtils.getUUIDV5(`${dk_lib_1.CkUtils.getUUID()}-${Date.now()}`);
msgData.broadcastId = broadcastId;
const userId = msgData.targetUserIds !== undefined && msgData.targetUserIds.length > 0 ? msgData.targetUserIds[idx] : undefined;
const pushId = ck_lib_gw_1.CommonService.makePushId({
broadcastId,
yyyymm: msgData.yyyymm,
retryIndex: msgData.currentRetryCount === undefined ? 0 : msgData.currentRetryCount,
userId,
}, MyConfig_1.conf.HTF_PUSH_ID_JWT_SECRET_KEY);
yield this.sendSingleFCM(lhd, singlePayload, msgData, pushId, broadcastId);
idx += 1;
}
finally {
_d = true;
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);
}
finally { if (e_1) throw e_1.error; }
}
});
}
sendSingleFCM(lhd, payload, msgData, pushId, broadcastId) {
return __awaiter(this, void 0, void 0, function* () {
const _payload = payload;
if (_payload.data) {
_payload.data.xpPushId = pushId;
}
const _msgData = msgData;
if (_msgData.data) {
_msgData.data.xpPushId = pushId;
}
_msgData.pushId = pushId;
_msgData.broadcastId = broadcastId;
const startTm = Date.now();
let bRet = false;
if (!this.FCM_MSG_HANDLER) {
dk_lib_1.CkLogger.errLog2('The fcm sender handler was not created normally.', lhd);
return false;
}
dk_lib_1.CkLogger.debugLog2(`push(single) message payload [${JSON5.stringify(payload)}]`, lhd);
const _upsertPushHistoryToRDBMS = this.upsertPushHistoryToRDBMS.bind(this);
dk_lib_1.CkLogger.infoLog2(`<< try send single fcm. dryRun [${_msgData.dryRun === true}]`, lhd);
yield this.FCM_MSG_HANDLER.send(_payload, _msgData.dryRun === true)
.then((response) => {
dk_lib_1.CkLogger.printElapsedLog2(lhd, startTm, 'send single fcm', MyConfig_1.conf.HTF_PUSH_ELAPSED_MILLI_SEC);
dk_lib_1.CkLogger.debugLog2(`fcm result [${JSON5.stringify(response)}]`, lhd);
dk_lib_1.CkLogger.infoLog2(`>> success send single fcm. dryRun [${_msgData.dryRun === true}], response(msg id) [${response}]`, lhd);
if (_.size(response) <= 0) {
dk_lib_1.CkLogger.errLog2(`>> failed send sing fcm. invalid response. dryRun [${_msgData.dryRun === true}], response [${response}]. can't insert to db.`, lhd);
return false;
}
return response;
})
.then((response) => {
if (response === false) {
bRet = response;
return false;
}
const sendResult = { success: true, messageId: `${response}` };
return sendResult;
})
.catch((err) => {
dk_lib_1.CkLogger.printElapsedLog2(lhd, startTm, 'send single fcm', MyConfig_1.conf.HTF_PUSH_ELAPSED_MILLI_SEC);
let code = '';
let message = '';
if (err.errorInfo) {
code = err.errorInfo.code || '';
message = err.errorInfo.message || '';
}
dk_lib_1.CkLogger.infoLog2(`>> failed send single fcm. dryRun [${_msgData.dryRun === true}], error code [${code}], error message [${message}]`, lhd);
const sendResult = {
success: false,
messageId: '',
error: { code, message },
};
return sendResult;
})
.then((response) => {
if (response === false) {
return response;
}
const retFCMMsgs = [];
const fcmMsg = {
tokens: [_payload.token],
title: _msgData.title,
body: _msgData.body,
imageUrl: _msgData.imageUrl,
defaultSound: _msgData.defaultSound,
sound: _msgData.sound,
badge: _msgData.badge,
data: _msgData.data ? Object.assign({}, _msgData.data) : {},
dryRun: _msgData.dryRun,
isBackground: _msgData.isBackground,
isBackgroundIOS: _msgData.isBackgroundIOS === true,
isBackgroundAndroid: _msgData.isBackgroundAndroid === true,
pushId,
broadcastId,
currentRetryCount: _msgData.currentRetryCount,
maxRetryCount: _msgData.maxRetryCount,
yyyymm: _msgData.yyyymm,
lhd: _msgData.lhd,
result: response,
targetUserIds: [_msgData.targetUserIds[0]],
pushVendor: _msgData.pushVendor,
};
if (_msgData.clientIds && _msgData.clientIds.length > 0) {
fcmMsg.clientIds = [_msgData.clientIds[0]];
}
if (_msgData.userTerminalIds && _msgData.userTerminalIds.length > 0) {
fcmMsg.userTerminalIds = [_msgData.userTerminalIds[0]];
}
retFCMMsgs.push(fcmMsg);
return _upsertPushHistoryToRDBMS(lhd, retFCMMsgs);
})
.then((ret) => {
bRet = ret;
})
.catch((err) => {
dk_lib_1.CkLogger.errLog2(`failed send single fcm and insert history DB. err [${err.toString()}]`, lhd);
bRet = false;
});
return bRet;
});
}
sendMultiFCM(lhd, payload, msgData, pushId, broadcastId, isBroadcast) {
return __awaiter(this, void 0, void 0, function* () {
const _payload = payload;
if (_payload.data) {
dk_lib_1.CkLogger.debugLog2(`change payload.data.xpPushId. from [${_payload.data.xpPushId}], to [${pushId}]`, lhd);
_payload.data.xpPushId = pushId;
}
const _msgData = msgData;
if (_msgData.data) {
dk_lib_1.CkLogger.debugLog2(`change msgData.data.xpPushId. from [${_msgData.data.xpPushId}], to [${pushId}]`, lhd);
_msgData.data.xpPushId = pushId;
}
_msgData.pushId = pushId;
_msgData.broadcastId = broadcastId;
const startTm = Date.now();
let bRet = false;
if (!this.FCM_MSG_HANDLER) {
dk_lib_1.CkLogger.errLog2('The fcm sender handler was not created normally.', lhd);
return false;
}
dk_lib_1.CkLogger.debugLog2(`push(multicast) message payload [${JSON5.stringify(payload)}]`, lhd);
const _upsertPushHistoryToRDBMS = this.upsertPushHistoryToRDBMS.bind(this);
dk_lib_1.CkLogger.infoLog2(`<< try send multicast fcm. broadcast [${isBroadcast}], dryRun [${_msgData.dryRun === true}], token count [${payload.tokens.length}]`, lhd);
yield this.FCM_MSG_HANDLER.sendMulticast(_payload, _msgData.dryRun === true)
.then((response) => {
dk_lib_1.CkLogger.printElapsedLog2(lhd, startTm, 'send multicast fcm', MyConfig_1.conf.HTF_PUSH_ELAPSED_MILLI_SEC);
dk_lib_1.CkLogger.debugLog2(`fcm result [${JSON5.stringify(response)}]`, lhd);
dk_lib_1.CkLogger.infoLog2(`>> success send multicast fcm. broadcast [${isBroadcast}], `
+ `dryRun [${_msgData.dryRun === true}], result success count [${response.successCount}], `
+ `failure count [${response.failureCount}]`, lhd);
if (_.size(response) <= 0) {
dk_lib_1.CkLogger.errLog2(`>> failed send multicast fcm. invalid response. broadcast [${isBroadcast}], `
+ `dryRun [${_msgData.dryRun === true}], `
+ `response [${JSON5.stringify(response)}]. can't insert to db.`, lhd);
return false;
}
if (!response.responses || _.size(response.responses) <= 0) {
dk_lib_1.CkLogger.errLog2('>> failed send multicast fcm. not found responses in response. broadcast '
+ `[${isBroadcast}], dryRun `
+ `[${_msgData.dryRun === true}], response [${JSON5.stringify(response.responses)}]. `
+ "can't inser to db.", lhd);
return false;
}
let idx = 0;
const retFCMMsgs = [];
for (const row of response.responses) {
const fcmMsg = {
tokens: [_payload.tokens[idx]],
title: _msgData.title,
body: _msgData.body,
imageUrl: _msgData.imageUrl,
defaultSound: _msgData.defaultSound,
sound: _msgData.sound,
badge: _msgData.badge,
data: _msgData.data ? Object.assign({}, _msgData.data) : {},
dryRun: _msgData.dryRun,
isBackground: _msgData.isBackground,
isBackgroundIOS: _msgData.isBackgroundIOS === true,
isBackgroundAndroid: _msgData.isBackgroundAndroid === true,
pushId,
broadcastId,
currentRetryCount: _msgData.currentRetryCount,
maxRetryCount: _msgData.maxRetryCount,
yyyymm: _msgData.yyyymm,
lhd: _msgData.lhd,
result: row,
targetUserIds: [_msgData.targetUserIds[idx]],
};
if (_msgData.clientIds && _msgData.clientIds.length > 0) {
fcmMsg.clientIds = [_msgData.clientIds[idx]];
}
if (_msgData.userTerminalIds && _msgData.userTerminalIds.length > 0) {
fcmMsg.userTerminalIds = [_msgData.userTerminalIds[idx]];
}
retFCMMsgs.push(fcmMsg);
idx += 1;
}
return _upsertPushHistoryToRDBMS(lhd, retFCMMsgs);
})
.then((ret) => {
bRet = ret;
})
.catch((err) => {
dk_lib_1.CkLogger.errLog2(`failed send multicast fcm and insert history DB. err [${err.toString()}]`, lhd);
bRet = false;
});
return bRet;
});
}
upsertPushHistoryToRDBMS(lhd, msgs) {
var _a, msgs_1, msgs_1_1;
var _b, e_2, _c, _d, _e, e_3, _f, _g;
return __awaiter(this, void 0, void 0, function* () {
const rdb = ck_lib_sequelize_1.CkSequelize.getSequelize2(lhd, 0);
if (!rdb) {
dk_lib_1.CkLogger.errLog2("can't start transaction", lhd);
return false;
}
const transaction = yield rdb.transaction();
dk_lib_1.CkLogger.debugLog2('start transaction', lhd);
const delayedMessages = [];
const now = new Date();
const nowMilliSec = now.getTime();
const nowSec = Math.floor(nowMilliSec / 1000);
try {
for (_a = true, msgs_1 = __asyncValues(msgs); msgs_1_1 = yield msgs_1.next(), _b = msgs_1_1.done, !_b;) {
_d = msgs_1_1.value;
_a = false;
try {
const msg = _d;
const newData = new ck_lib_models_1.TbFcmHistoryTmp();
newData.rid = dk_lib_1.CkUtils.getUUIDV5(`${dk_lib_1.CkUtils.getUUID()}-${Date.now()}`);
newData.yyyymm = msg.yyyymm;
newData.retry_index = (msg.currentRetryCount === undefined ? 0 : msg.currentRetryCount);
newData.user_id = msg.targetUserIds !== undefined && msg.targetUserIds.length > 0 ? msg.targetUserIds[0] : '';
if (msg.result) {
if (msg.result.success) {
newData.fcm_msg_id = msg.result.messageId || '';
newData.fcm_send_flag = dk_lib_1.CkValue.PUSH_SEND_RESULT.SUCCESS;
newData.fcm_err_code = '';
newData.fcm_err_msg = '';
}
else {
newData.fcm_msg_id = '';
newData.fcm_send_flag = dk_lib_1.CkValue.PUSH_SEND_RESULT.FAIL;
if (msg.result.error) {
newData.fcm_err_code = msg.result.error.code || '';
newData.fcm_err_msg = msg.result.error.message || '';
}
else {
newData.fcm_err_code = '';
newData.fcm_err_msg = '';
}
}
}
if (MyConfig_1.conf.HTF_PUSH_SEND_MAX_RETRY_COUNT > 0) {
newData.arrival_flag = dk_lib_1.CkValue.PUSH_ALLIVAL.NO;
newData.read_flag = dk_lib_1.CkValue.PUSH_READ.NO;
}
else {
newData.arrival_flag = dk_lib_1.CkValue.PUSH_ALLIVAL.UNKNOWN;
newData.read_flag = dk_lib_1.CkValue.PUSH_READ.UNKNOWN;
}
newData.limit_retry_count = (msg.maxRetryCount === undefined ? 0 : msg.maxRetryCount);
newData.fcm_msg = Object.assign({}, msg);
delete newData.fcm_msg.result;
if (newData.fcm_msg.currentRetryCount === undefined) {
newData.fcm_msg.currentRetryCount = 0;
}
if (newData.fcm_msg.maxRetryCount === undefined) {
newData.fcm_msg.maxRetryCount = 0;
}
newData.broadcast_id = msg.broadcastId || dk_lib_1.CkUtils.getUUIDV5(`${dk_lib_1.CkUtils.getUUID()}-${Date.now()}`);
newData.extra = {};
newData.push_vendor = dk_lib_1.CkValue.PUSH_VENDOR_TYPE.FCM;
if (msg.clientIds && msg.clientIds.length > 0) {
[newData.client_id] = msg.clientIds;
}
else {
newData.client_id = '';
}
if (msg.userTerminalIds && msg.userTerminalIds.length > 0) {
[newData.user_terminal_id] = msg.userTerminalIds;
}
else {
newData.user_terminal_id = 0;
}
newData.c_date = new Date(nowSec * 1000);
newData.u_date = new Date(nowSec * 1000);
const savedData = yield ck_lib_sequelize_1.DatabaseService.createData(lhd, newData, transaction);
if (typeof savedData === 'string') {
yield transaction.rollback();
dk_lib_1.CkLogger.debugLog2('rollback transaction', lhd);
if (msg.clientIds && msg.clientIds.length > 0) {
dk_lib_1.CkLogger.errLog2(`can't save fcm send history. pushId [${msg.pushId}], targetUserId [${msg.targetUserIds ? msg.targetUserIds[0] : ''}], currentRetryCount [${msg.currentRetryCount}]. data [${JSON5.stringify(newData)}]`, lhd);
}
else {
dk_lib_1.CkLogger.errLog2(`can't save fcm send history. pushId [${msg.pushId}], targetUserId [${msg.targetUserIds ? msg.targetUserIds[0] : ''}], currentRetryCount [${msg.currentRetryCount}], clientIds [${JSON5.stringify(msg.clientIds)}]. data [${JSON5.stringify(newData)}]`, lhd);
}
return false;
}
dk_lib_1.CkLogger.infoLog2(`insert fcm push message history DB. rid [${newData.rid}], yyyymm [${newData.yyyymm}], retry index [${newData.retry_index}], user id [${newData.user_id}]`, lhd);
if (newData.fcm_send_flag === dk_lib_1.CkValue.PUSH_SEND_RESULT.SUCCESS
&& (newData.fcm_msg.maxRetryCount > newData.fcm_msg.currentRetryCount)) {
delayedMessages.push(JSON5.stringify(newData.fcm_msg));
}
else {
dk_lib_1.CkLogger.infoLog2(`not use push message send retry. fcm send result [${newData.fcm_send_flag}] is not success or limited max retry count, maxRetryCount [${newData.fcm_msg.maxRetryCount}], currentRetryCount [${newData.fcm_msg.currentRetryCount}]`, lhd);
}
}
finally {
_a = true;
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (!_a && !_b && (_c = msgs_1.return)) yield _c.call(msgs_1);
}
finally { if (e_2) throw e_2.error; }
}
yield transaction.commit();
dk_lib_1.CkLogger.debugLog2('commit transaction', lhd);
if (MyConfig_1.conf.HTF_PUSH_SEND_MAX_RETRY_COUNT > 0) {
if (!this.delayVendor) {
dk_lib_1.CkLogger.errLog2('The delayed queue for retry was not created normally.', lhd);
}
else {
if (delayedMessages.length > 10) {
const messageParts = [];
let idx = 0;
for (const retryMsg of delayedMessages) {
if (idx % 10 === 0) {
messageParts.push([]);
}
const partIdx = Math.floor(idx / 10);
messageParts[partIdx].push(retryMsg);
idx += 1;
}
try {
for (var _h = true, messageParts_1 = __asyncValues(messageParts), messageParts_1_1; messageParts_1_1 = yield messageParts_1.next(), _e = messageParts_1_1.done, !_e;) {
_g = messageParts_1_1.value;
_h = false;
try {
const msgPart = _g;
yield this.delayVendor.pushMulti(lhd, msgPart);
}
finally {
_h = true;
}
}
}
catch (e_3_1) { e_3 = { error: e_3_1 }; }
finally {
try {
if (!_h && !_e && (_f = messageParts_1.return)) yield _f.call(messageParts_1);
}
finally { if (e_3) throw e_3.error; }
}
}
else if (delayedMessages.length === 1) {
yield this.delayVendor.pushOne(lhd, delayedMessages[0]);
}
else if (delayedMessages.length > 1 && delayedMessages.length <= 10) {
yield this.delayVendor.pushMulti(lhd, delayedMessages);
}
}
}
return true;
});
}
}
exports.default = PushGoogleFCM;