-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnotification.js
More file actions
334 lines (287 loc) · 11.3 KB
/
notification.js
File metadata and controls
334 lines (287 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
const express = require('express');
const app = express();
const aws_key = require('./config').aws_access;
const aws = require('aws-sdk');
const multer = require('multer');
const multer_s3 = require('multer-s3');
const db = require('./db');
const firebase = require('firebase-admin')
const firebaseCredential = require('./config').firebase;
const scheduler = require('node-schedule');
app.use(express.json())
const s3 = new aws.S3({
accessKeyId: aws_key.access,
secretAccessKey: aws_key.secret,
region: aws_key.region
});
const storage = multer_s3({
s3: s3,
bucket: 'ggdjang',
contentType: multer_s3.AUTO_CONTENT_TYPE,
acl: 'public-read',
metadata: function(req, file, cb) {
cb(null, {fieldName: file.fieldname});
},
key: function (req, file, cb) {
cb(null, `notification/${Date.now()}_${file.originalname}`);
}
})
const upload = multer({
storage: storage
})
firebase.initializeApp({
credential: firebase.credential.cert(firebaseCredential),
});
/** 알림을 보낼 사용자 조회 */
app.get('/user', async (req, res) => {
try {
const [result, field] = await db.execute(`SELECT user_no, user_id, user_name FROM user`);
console.log(`USER_READ_SUCCESS :: `);
res.send({msg: 'USER_READ_SUCCESS', data: result});
} catch (e) {
console.log(`USER_READ_FAILED :: msg = ${e}`);
res.status(500).send({msg: 'USER_READ_FAILED'});
}
})
/** 알림 리스트 조회 */
app.get('/', async (req, res) => {
const body = req.body;
const filter = req.query.filter;
const resBody = {msg: 'NOTIFICATION_READ_SUCCESS'};
try {
if (!filter) {
const [result, field] = await db.execute(`SELECT *
FROM notification
ORDER BY createdAt DESC`);
resBody['data'] = result;
} else {
const [result, field] = await db.execute(`SELECT *
FROM notification WHERE notification_target = ?
ORDER BY createdAt DESC`, [filter]);
resBody['data'] = result;
}
console.log(`NOTIFICATION_READ_SUCCESS :: `);
res.send(resBody);
} catch (e) {
console.log(`NOTIFICATION_READ_FAILED :: msg = ${e}`);
res.status(500).send({msg: 'NOTIFICATION_READ_FAILED'});
}
})
/** 개별 알림 조회 */
app.get('/:notificationId', async (req, res) => {
const notificationId = req.params.notificationId;
const resBody = {msg: 'NOTIFICATION_READ_SUCCESS'};
try {
const [result, field] = await db.execute(`SELECT *FROM notification WHERE notification_id = ?`, [notificationId]);
resBody['data'] = result[0];
console.log(`NOTIFICATION_READ_SUCCESS :: notificationId = ${notificationId}`);
res.send(resBody);
} catch (e) {
console.log(`NOTIFICATION_READ_FAILED :: msg = ${e}`);
res.status(500).send({msg: 'NOTIFICATION_READ_FAILED'});
}
})
/** 사용자 아이디로 토큰 찾기 */
const getTokensByUser = async (userIds) => {
let tokens = [];
for (let userId of userIds) {
const [result, field] = await db.execute(`SELECT fcm_token FROM user WHERE user_no = ?`, [userId]);
tokens.push(result[0].fcm_token);
}
return tokens;
}
/** 사용자별 알림 리스트 생성 */
const createNotificationByUser = async (noticeId, userIds, status) => {
for (let userId of userIds) {
if (status === 'SENT')
await db.execute(`INSERT INTO notification_by_user (notification_user, notification_id) VALUES (?, ?)`,
[userId, noticeId]);
else
await db.execute(`INSERT INTO notification_by_user (notification_user, notification_id, status) VALUES (?, ?, ?)`,
[userId, noticeId, 'SCHEDULED']);
}
}
/** 알림 생성 */
const createNotification = async (body, image) => {
const title = body.title;
const content = body.content;
const type = body.type;
const target = body.target;
const pushType = body.pushType;
const date = body.date;
const [result, fields] = await db.execute(`INSERT INTO notification (notification_title, notification_content, notification_type, notification_target, notification_img,
notification_push_type, notification_date) VALUES (?, ?, ?, ?, ?, ?, ?)`, [title, content, type, target, image, pushType, date]);
return result;
}
const createTokenMessage = (userIds, tokens, title, content, image) => {
let message;
if (image !== null) {
const url = encodeURI(`https://ggdjang.s3.ap-northeast-2.amazonaws.com/${image}`)
message = {
notification: {
title: title,
body: content,
imageUrl: url
},
data: {
title: title,
body: content,
// userId: userIds
},
tokens: tokens
}
} else {
message = {
notification: {
title: title,
body: content
},
data: {
title: title,
body: content,
// uerId: userIds
},
tokens: tokens
}
}
return message;
}
const createTopicMessage = (topic, title, content, image) => {
let message;
if (image !== null) {
const url = encodeURI(`https://ggdjang.s3.ap-northeast-2.amazonaws.com/${image}`)
message = {
notification: {
title: title,
body: content,
imageUrl: url
},
data: {
title: title,
body: content
},
topic: topic
}
} else {
message = {
notification: {
title: title,
body: content
},
data: {
title: title,
body: content
},
topic: topic
}
}
return message;
}
/** 토큰으로 알림 전송 */
app.post('/token', upload.single('image'), async (req, res) => {
const body = req.body;
let userIds = req.body.userIds;
if (!Array.isArray(userIds)) {
userIds = userIds.split(',')
}
const tokens = await getTokensByUser(userIds);
const title = body.title;
const content = body.content;
const pushType = body.pushType;
let image = null;
if (req.file !== undefined) image = req.file.key;
try {
const noticeResult = await createNotification(body, image);
if (pushType === '실시간') {
const message = createTokenMessage(userIds, tokens, title, content, image);
const msgResult = await firebase.messaging().sendMulticast(message);
await createNotificationByUser(noticeResult.insertId, userIds, 'SENT');
console.log(`NOTIFICATION_SEND_SUCCESS :: notificationId = ${noticeResult.insertId}`);
res.send({
msg: "NOTIFICATION_SEND_SUCCESS",
data: {
successCount: msgResult.successCount,
failureCount: msgResult.failureCount
}}
);
} else {
await createNotificationByUser(noticeResult.insertId, userIds, 'SCHEDULED');
console.log(`NOTIFICATION_RESERVE_SUCCESS :: notificationId = ${noticeResult.insertId}`);
res.send({msg: "NOTIFICATION_RESERVE_SUCCESS"});
}
} catch (e) {
console.log(`NOTIFICATION_SEND_FAILED :: msg = ${e}`);
res.status(500).send({msg: 'NOTIFICATION_SEND_FAILED'});
}
})
/** 토픽으로 알림 전송 */
app.post('/topic', upload.single('image'), async (req, res) => {
const body = req.body;
const topic = body.topic;
const title = body.title;
const content = body.content;
const pushType = body.pushType;
let image = null;
if (req.file !== undefined) image = req.file.key;
try {
const noticeResult = await createNotification(body, image);
const [userResult, field] = await db.execute('SELECT user_no FROM user');
let userIds = [];
for (let user of userResult) {
userIds.push(user.user_no);
}
if (pushType === '실시간') {
const message = createTopicMessage(topic, title, content, image);
const msgResult = await firebase.messaging().send(message);
await createNotificationByUser(noticeResult.insertId, userIds, 'SENT');
console.log(`NOTIFICATION_SEND_SUCCESS (topic) :: notificationId = ${noticeResult.insertId}`);
res.send({
msg: "NOTIFICATION_SEND_SUCCESS",
data: {
successCount: msgResult.successCount,
failureCount: msgResult.failureCount
}}
);
} else {
await createNotificationByUser(noticeResult.insertId, userIds, 'SCHEDULED');
console.log(`NOTIFICATION_RESERVE_SUCCESS (topic) :: notificationId = ${noticeResult.insertId}`);
res.send({msg: "NOTIFICATION_RESERVE_SUCCESS"});
}
} catch (e) {
console.log(`NOTIFICATION_SEND_FAILED (topic) :: msg = ${e}`);
res.status(500).send({msg: 'NOTIFICATION_SEND_FAILED'});
}
})
/** 매 정각에 예약된 알림(정각 ~ 5분 사이) 확인 후 발송 */
scheduler.scheduleJob('0 * * * *', async () => {
try {
const [notifications, field] = await db.execute(`SELECT notification_id, notification_target, notification_title, notification_content FROM notification
WHERE notification_push_type = ? AND notification_date BETWEEN NOW() and NOW() + INTERVAL 5 MINUTE`, ['예약']);
for (const notification of notifications) {
const notificationId = notification.notification_id;
const target = notification.notification_target;
const title = notification.notification_title;
const content = notification.notification_content;
const image = notification.notification_img;
const [users, fields] = await db.execute(`SELECT notification_user FROM notification_by_user WHERE notification_id = ?`, [notificationId]);
let userIds = [];
for (let user of users) {
userIds.push(user.notification_user);
}
if (target === '개인') {
const tokens = await getTokensByUser(userIds);
const message = createTokenMessage(tokens, title, content, image);
const msgResult = await firebase.messaging().sendMulticast(message);
} else if (target === '소비자') {
const message = createTopicMessage('userTopic', title, content, image);
const msgResult = await firebase.messaging().send(message);
}
// TODO: 관리자 알림 개발 완료 후 추가
await db.execute(`UPDATE notification_by_user SET status = ? WHERE notification_id = ?`, ['SENT', notificationId]);
console.log(`NOTIFICATION_SEND_SUCCESS (schedule) :: notificationId = ${notificationId}`);
}
} catch (e) {
console.log(`NOTIFICATION_SEND_FAILED (schedule) :: msg = ${e}`);
}
})
module.exports = app;