Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[REFACTOR] 푸시알림 뷰 이동 가능하도록 개선 #419

Merged
merged 8 commits into from
Sep 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion functions/api/routes/room/roomRecordPOST.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ module.exports = async (req, res) => {
}

if (receiverTokens.length) {
pushAlarm.sendMulticastByTokens(req, res, title, body, receiverTokens, category, certifyingImg[0]);
pushAlarm.sendMulticastByTokens(req, res, title, body, receiverTokens, category, certifyingImg[0], roomId, record.recordId);
}

const data = {
Expand Down
2 changes: 1 addition & 1 deletion functions/api/routes/room/roomStartPOST.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ module.exports = async (req, res) => {

// 푸시알림 전송
const receiverTokens = allUsers.filter((u) => u.pushRoomStart).map((u) => u.deviceToken);
pushAlarm.sendMulticastByTokens(req, res, title, body, receiverTokens, category);
pushAlarm.sendMulticastByTokens(req, res, title, body, receiverTokens, category, null, roomId);

// notification 생성
const notifications = allUsers.map((u) => {
Expand Down
2 changes: 1 addition & 1 deletion functions/api/routes/room/roomStatusPOST.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ module.exports = async (req, res) => {
}

if (receiverTokens.length > 0) {
pushAlarm.sendMulticastByTokens(req, res, title, body, receiverTokens, category);
pushAlarm.sendMulticastByTokens(req, res, title, body, receiverTokens, category, null, roomId);
}
}

Expand Down
2 changes: 1 addition & 1 deletion functions/api/routes/room/sparkPOST.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ module.exports = async (req, res) => {

// 푸시알림 허용한 사용자일 경우
if (receiver.pushSpark) {
pushAlarm.send(req, res, title, body, receiver.deviceToken, category);
pushAlarm.send(req, res, title, body, receiver.deviceToken, category, null, roomId);
}

res.status(statusCode.OK).send(util.success(statusCode.OK, responseMessage.SEND_SPARK_SUCCESS));
Expand Down
21 changes: 16 additions & 5 deletions functions/constants/alarmMessage.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,22 @@ const FEED_LIKE = (who, roomName) => {
return { title, body, isService };
};

const REMIND_ALERT = () => {
const title = `🚨비상🚨`;
const body = `미완료 습관방 발견!👀 얼른 생명 지키러 가요!`;
const REMIND_ALERT_NONE = (roomName) => {
const title = `${roomName}방의 인증을 하지 않았어요!`;
const body = `생명이 줄어들기 전에 서둘러 인증해주세요🏃‍♂️`;
const isService = true;
const category = 'remind';

return { title, body, isService };
return { title, body, isService, category };
};

const REMIND_ALERT_DONE = (roomName) => {
const title = `${roomName}방에 인증을 안 한 친구가 있어요! `;
const body = `지금 스파크를 보내 친구를 응원해주세요 🔥`;
const isService = true;
const category = 'remind';

return { title, body, isService, category };
};

module.exports = {
Expand All @@ -74,5 +84,6 @@ module.exports = {
ROOM_NEW,
ROOM_DELETE,
FEED_LIKE,
REMIND_ALERT,
REMIND_ALERT_NONE,
REMIND_ALERT_DONE,
};
34 changes: 34 additions & 0 deletions functions/db/record.js
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,39 @@ const getNoneOrConsiderEntryIdsByDate = async (client, date) => {
return convertSnakeToCamel.keysToCamel(rows);
};

const getPushRemindUsers = async (client, date) => {
const { rows } = await client.query(
`
SELECT e.user_id, r.room_name, r.room_id, rec.status, u.device_token
FROM spark.entry e
INNER JOIN spark.room r
ON e.room_id = r.room_id
INNER JOIN spark.record rec
ON rec.entry_id = e.entry_id
INNER JOIN spark.user u
ON u.user_id = e.user_id
WHERE e.is_out = FALSE
AND e.is_deleted = FALSE
AND e.is_kicked = FALSE
AND u.is_deleted = FALSE
AND u.push_remind = TRUE
AND rec.date = $1
AND e.room_id IN (
SELECT DISTINCT e.room_id FROM spark.entry e
INNER JOIN spark.record r
ON e.entry_id = r.entry_id
WHERE r.date = $1
AND r.status IN ('NONE', 'CONSIDER')
AND e.is_kicked = FALSE
AND e.is_deleted = FALSE
AND e.is_kicked = FALSE
)
`,
[date],
);
return convertSnakeToCamel.keysToCamel(rows);
};

module.exports = {
getRecordById,
getRecentRecordByEntryId,
Expand All @@ -157,4 +190,5 @@ module.exports = {
getDonePagedRecordsByEntryId,
insertRecords,
getNoneOrConsiderEntryIdsByDate,
getPushRemindUsers,
};
83 changes: 81 additions & 2 deletions functions/lib/pushAlarm.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const util = require('./util');
const statusCode = require('../constants/statusCode');
const responseMessage = require('../constants/responseMessage');

const send = async (req, res, title, body, receiverToken, category, imageUrl = null) => {
const send = async (req, res, title, body, receiverToken, category, imageUrl = null, roomId = '', recordId = '') => {
let mutableContent = 1;
if (!imageUrl) {
mutableContent = 0;
Expand All @@ -15,14 +15,23 @@ const send = async (req, res, title, body, receiverToken, category, imageUrl = n
return true;
}

if (!roomId) roomId = '';
if (!recordId) recordId = '';

try {
const message = {
data: {
roomId: String(roomId),
recordId: String(recordId),
},
android: {
data: {
title,
body,
imageUrl,
category,
roomId: String(roomId),
recordId: String(recordId),
},
},
apns: {
Expand Down Expand Up @@ -61,13 +70,75 @@ const send = async (req, res, title, body, receiverToken, category, imageUrl = n
}
};

const sendMulticastByTokens = async (req, res, title, body, receiverTokens, category, imageUrl = null) => {
const getMessage = (title, body, receiverToken, category, imageUrl = null, roomId = '', recordId = '') => {
let mutableContent = 1;
if (!imageUrl) {
mutableContent = 0;
imageUrl = '';
}

if (!roomId) roomId = '';
if (!recordId) recordId = '';

const message = {
data: {
roomId: String(roomId),
recordId: String(recordId),
},
android: {
data: {
title,
body,
imageUrl,
category,
roomId: String(roomId),
recordId: String(recordId),
},
},
apns: {
payload: {
aps: {
alert: {
title,
body,
},
category,
'thread-id': category,
'mutable-content': mutableContent,
},
},
fcm_options: {
image: imageUrl,
},
},
token: receiverToken,
};
return message;
};

const sendMessages = async (req, res, messages) => {
admin
.messaging()
.sendAll(messages)
.then(function (response) {
return true;
})
.catch(function (err) {
console.log(err);
return false;
});
};

const sendMulticastByTokens = async (req, res, title, body, receiverTokens, category, imageUrl = null, roomId = '', recordId = '') => {
let mutableContent = 1;
if (!imageUrl) {
mutableContent = 0;
imageUrl = '';
}

if (!roomId) roomId = '';
if (!recordId) recordId = '';

// FCM Token이 empty인 경우 제외
receiverTokens = receiverTokens.filter((t) => t);
if (!receiverTokens.length) {
Expand All @@ -76,12 +147,18 @@ const sendMulticastByTokens = async (req, res, title, body, receiverTokens, cate

try {
const message = {
data: {
roomId: String(roomId),
recordId: String(recordId),
},
android: {
data: {
title,
body,
imageUrl,
category,
roomId: String(roomId),
recordId: String(recordId),
},
},
apns: {
Expand Down Expand Up @@ -123,4 +200,6 @@ const sendMulticastByTokens = async (req, res, title, body, receiverTokens, cate
module.exports = {
send,
sendMulticastByTokens,
getMessage,
sendMessages,
};
33 changes: 18 additions & 15 deletions functions/scheduler/funcs.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const db = require('../db/db');
const admin = require('firebase-admin');
const { userDB, roomDB, recordDB, scheduleDB, remindDB, dialogDB } = require('../db');
const _ = require('lodash');
const dayjs = require('dayjs');
Expand Down Expand Up @@ -120,6 +121,7 @@ const sendRemind = async () => {
let client;
try {
client = await db.connect();

const scheduleCheck = await remindDB.insertRemind(client);
if (!scheduleCheck.length) {
return;
Expand All @@ -128,20 +130,21 @@ const sendRemind = async () => {
const now = dayjs().add(9, 'hour');
const today = now.format('YYYY-MM-DD');

const noneEntryIds = await recordDB.getNoneOrConsiderEntryIdsByDate(client, today);

if (noneEntryIds.length > 0) {
const targetUserIds = await roomDB.getMemberIdsByEntryIds(
client,
noneEntryIds.map((e) => e.entryId),
);
const targetUsers = await userDB.getUsersByIds(
client,
targetUserIds.map((u) => u.userId),
);
const targetTokens = targetUsers.filter((u) => u.pushRemind).map((u) => u.deviceToken);
const { title, body } = alarmMessage.REMIND_ALERT();
pushAlarm.sendMulticastByTokens(null, null, title, body, targetTokens, 'remind');
let remindUsers = await recordDB.getPushRemindUsers(client, today);

if (remindUsers.length) {
messages = [];
remindUsers.map((u) => {
if (u.status == 'NONE' || u.status == 'CONSIDER') {
const { title, body, category } = alarmMessage.REMIND_ALERT_NONE(u.roomName);
messages.push(pushAlarm.getMessage(title, body, u.deviceToken, category, null, u.roomId));
} else {
const { title, body, category } = alarmMessage.REMIND_ALERT_DONE(u.roomName);
messages.push(pushAlarm.getMessage(title, body, u.deviceToken, category, null, u.roomId));
}
});
pushAlarm.sendMessages(null, null, messages);

const slackMessage = `[REMIND SEND SUCCESS]: To ${targetUsers.length} users: ${targetUsers.map((u) => u.nickname)}`;
slackAPI.sendMessageToSlack(slackMessage, slackAPI.DEV_WEB_HOOK_ERROR_MONITORING);
return;
Expand All @@ -153,7 +156,7 @@ const sendRemind = async () => {
const slackMessage = `[ERROR] ${error} ${JSON.stringify(error)}`;
slackAPI.sendMessageToSlack(slackMessage, slackAPI.DEV_WEB_HOOK_ERROR_MONITORING);
} finally {
console.log('relase');
console.log('release');
client.release();
}
};
Expand Down