@mathrunet/masamune
Version:
Manages packages for the server portion (NodeJS) of the Masamune framework.
386 lines • 16.8 kB
JavaScript
"use strict";
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 () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__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());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendNotification = sendNotification;
const functions = __importStar(require("firebase-functions/v2"));
const admin = __importStar(require("firebase-admin"));
const firestore = __importStar(require("./firestore"));
const utils_1 = require("../utils");
/**
* Define the process for PUSH notification.
*
* PUSH通知を行うための処理を定義します。
*
* @param title
* The title of the notice should be listed.
*
* 通知タイトルを記載します。
*
* @param body
* The contents of the notice will be described.
*
* 通知内容を記載します。
*
* @param channel_id
* Describe ChannelId for Android.
*
* Android向けのChannelIdを記載します。
*
* @param data
* Specify the data to be placed on the notification.
*
* 通知に乗せるデータを指定します。
*
* @param link
* Specify the link to be opened when the notification is clicked.
*
* 通知がクリックされたときに開くリンクを指定します。
*
* @param badgeCount
* Specifies the badge count of the notification.
*
* 通知のバッジカウントを指定します。
*
* @param sound
* Specifies the sound of the notification.
*
* 通知のサウンドを指定します。
*
* @param targetToken
* Specifies the FCM token.
*
* FCMトークンを指定します。
*
* @param targetTopic
* Specifies the topic of the FCM.
*
* FCMのトピックを指定します。
*
* @param targetCollectionPath
* Specifies the path of the collection to be notified.
*
* 通知対象のコレクションのパスを指定します。
*
* @param targetDocumentPath
* Specifies the path of the document to be notified.
*
* 通知対象のドキュメントのパスを指定します。
*
* @param targetTokenField
* Specifies the key of the field used to retrieve the token to be notified.
*
* 通知対象のトークンを取得する際のフィールドのキーを指定します。
*
* @param targetWheres
* Specify the conditions for retrieving the collections to be notified.
*
* 通知対象のコレクションを取得する際の条件を指定します。
*
* @param targetConditions
* Specify the conditions under which data is to be notified.
*
* データを通知対象とする条件を指定します。
*
* @param responseTokenList
* Specifies whether to return the token list for debugging.
*
* デバッグ用にトークンリストを返すかどうかを指定します。
*/
function sendNotification(_a) {
return __awaiter(this, arguments, void 0, function* ({ title, body, data, link, channelId, badgeCount, sound, targetToken, targetTopic, targetCollectionPath, targetDocumentPath, targetTokenField, targetWheres, targetConditions, responseTokenList, firestoreInstance, showLog, }) {
var _b, _c;
const res = {};
try {
if ((targetToken === undefined || targetToken === null) && (targetTopic === undefined || targetTopic === null) && (targetCollectionPath === undefined || targetCollectionPath === null) && (targetDocumentPath === undefined || targetDocumentPath === null)) {
throw new functions.https.HttpsError("invalid-argument", "Either [token] or [topic], [targetCollectionPath], [targetDocumentPath] must be specified.");
}
// Linkがあればdataに追加
if (link) {
data = Object.assign(Object.assign({}, data !== null && data !== void 0 ? data : {}), { "@link": link });
}
// トークンによる通知
if (targetToken !== undefined && targetToken !== null) {
if (showLog) {
console.log(`Notification target token: ${targetToken}`);
}
if (typeof targetToken === "string") {
targetToken = [targetToken];
}
const tokenList = (0, utils_1.splitArray)([...new Set(targetToken)], 500);
if (responseTokenList) {
return {
success: true,
results: tokenList,
};
}
for (let t in tokenList) {
try {
const messageId = yield admin.messaging().sendEachForMulticast({
notification: {
title: title,
body: body,
},
android: {
priority: "high",
notification: {
title: title,
body: body,
clickAction: "FLUTTER_NOTIFICATION_CLICK",
channelId: channelId !== null && channelId !== void 0 ? channelId : undefined,
sound: sound !== null && sound !== void 0 ? sound : undefined,
},
},
apns: {
payload: {
aps: {
sound: sound !== null && sound !== void 0 ? sound : undefined,
badge: badgeCount !== null && badgeCount !== void 0 ? badgeCount : undefined,
},
}
},
data: data,
tokens: tokenList[t],
});
res[t] = messageId;
}
catch (e) {
console.log(e);
console.log({
notification: {
title: title,
body: body,
},
android: {
priority: "high",
notification: {
title: title,
body: body,
clickAction: "FLUTTER_NOTIFICATION_CLICK",
channelId: channelId !== null && channelId !== void 0 ? channelId : undefined,
sound: sound !== null && sound !== void 0 ? sound : undefined,
},
},
apns: {
payload: {
aps: {
sound: sound !== null && sound !== void 0 ? sound : undefined,
badge: badgeCount !== null && badgeCount !== void 0 ? badgeCount : undefined,
},
}
},
data: data,
tokens: tokenList[t],
});
}
}
return {
success: true,
results: res,
};
// トピックによる通知
}
else if (targetTopic !== undefined && targetTopic !== null) {
if (showLog) {
console.log(`Notification target topic: ${targetTopic}`);
}
if (responseTokenList) {
return {
success: true,
results: targetTopic,
};
}
try {
const messageId = yield admin.messaging().send({
notification: {
title: title,
body: body,
},
android: {
priority: "high",
notification: {
title: title,
body: body,
clickAction: "FLUTTER_NOTIFICATION_CLICK",
channelId: channelId !== null && channelId !== void 0 ? channelId : undefined,
},
},
data: data,
topic: targetTopic,
});
res[targetTopic] = messageId;
}
catch (e) {
console.log(e);
console.log({
notification: {
title: title,
body: body,
},
android: {
priority: "high",
notification: {
title: title,
body: body,
clickAction: "FLUTTER_NOTIFICATION_CLICK",
channelId: channelId !== null && channelId !== void 0 ? channelId : undefined,
},
},
data: data,
topic: targetTopic,
});
}
return {
success: true,
results: res,
};
// コレクションパスによる通知
}
else if (targetCollectionPath !== undefined && targetCollectionPath !== null && targetTokenField != undefined && targetTokenField !== null) {
if (showLog) {
console.log(`Notification target collection path: ${targetCollectionPath} wheres: ${JSON.stringify(targetWheres)} conditions: ${JSON.stringify(targetConditions)}`);
}
const collectionRef = firestore.where({
query: firestoreInstance.collection(targetCollectionPath),
wheres: targetWheres,
});
const results = [];
const tokens = [];
let cursor = null;
let collection = null;
do {
collection = yield firestore.cursor({ query: collectionRef, limit: 500, cursor: cursor }).get();
for (let doc of collection.docs) {
const docData = doc.data();
if (showLog) {
console.log(`Document: ${JSON.stringify(docData)}`);
}
if (!(yield firestore.hasMatch({ data: docData, conditions: targetConditions }))) {
continue;
}
const token = yield firestore.get({ data: docData, field: targetTokenField });
if (typeof token === "string") {
tokens.push(token);
}
else if (Array.isArray(token)) {
tokens.push(...token);
}
}
const res = yield sendNotification({
title: title,
body: body,
data: data,
channelId: channelId,
badgeCount: badgeCount,
sound: sound,
responseTokenList: responseTokenList,
targetToken: tokens,
firestoreInstance: firestoreInstance,
});
results.push((_b = res.results) !== null && _b !== void 0 ? _b : []);
if (collection.docs.length < 500) {
break;
}
cursor = collection.docs[collection.docs.length - 1];
} while (collection.docs.length >= 500);
if (responseTokenList) {
return {
success: true,
results: results,
};
}
// ドキュメントパスによる通知
}
else if (targetDocumentPath !== undefined && targetDocumentPath !== null && targetTokenField != undefined && targetTokenField !== null) {
if (showLog) {
console.log(`Notification target document path: ${targetDocumentPath} conditions: ${JSON.stringify(targetConditions)}`);
}
const documentRef = firestoreInstance.doc(targetDocumentPath);
const results = [];
const doc = yield documentRef.get();
const docData = doc.data();
if (docData) {
if (showLog) {
console.log(`Document: ${JSON.stringify(docData)}`);
}
if (yield firestore.hasMatch({ data: docData, conditions: targetConditions })) {
const token = yield firestore.get({ data: docData, field: targetTokenField });
const tokens = [];
if (typeof token === "string") {
tokens.push(token);
}
else if (Array.isArray(token)) {
tokens.push(...token);
}
const res = yield sendNotification({
title: title,
body: body,
data: data,
channelId: channelId,
badgeCount: badgeCount,
sound: sound,
responseTokenList: responseTokenList,
targetToken: tokens,
firestoreInstance: firestoreInstance,
});
results.push((_c = res.results) !== null && _c !== void 0 ? _c : []);
}
}
if (responseTokenList) {
return {
success: true,
results: results,
};
}
}
}
catch (err) {
throw err;
}
return {
success: true,
results: res,
};
});
}
//# sourceMappingURL=send_notification.js.map