-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
210 lines (173 loc) · 4.9 KB
/
index.js
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
require("dotenv").config();
const express = require("express");
const bodyParser = require("body-parser");
const admin = require("firebase-admin");
const cors = require("cors");
const fs = require("fs");
const cron = require("node-cron");
const cronParser = require("cron-parser");
const { privateKey } = JSON.parse(process.env.FIREBASE_PRIVATE_KEY);
const accountData = fs.readFileSync("service-account-credentials.json");
const serviceAccount = JSON.parse(accountData);
serviceAccount["private_key_id"] = process.env.FIREBASE_PRIVATE_KEY_ID;
serviceAccount["private_key"] = privateKey;
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: process.env.FIREBASE_DATABASE_URL,
});
const app = express();
app.use(cors());
app.use(bodyParser.json());
const tokens = new Map();
const checkGeneration = (generation) => {
const generationRegex = /^[0-9]{2}-[0-9]$/;
return generationRegex.test(generation);
};
app.post("/api/register-token", (req, res) => {
const token = req.body.token;
const generation = req.body.generation;
if (!token) {
res.status(400).send({ message: "Token is missing" });
return;
}
if (!generation) {
res.status(400).send({ message: "Generation is missing" });
return;
}
if (!checkGeneration(generation)) {
res.status(400).send({ message: "Invalid generation format" });
return;
}
if (!tokens.has(generation)) {
tokens.set(generation, []);
}
if (tokens.get(generation).includes(token)) {
res.status(400).send({ message: "Token already registered" });
return;
}
tokens.get(generation).push(token);
res.status(200).send({ message: "Token received" });
});
app.get("/api/get-tokens", (req, res) => {
const object = Object.fromEntries(tokens);
res.status(200).send(object);
});
app.post("/api/clear-tokens", (req, res) => {
tokens.clear();
res.status(200).send({ message: "Tokens cleared" });
});
function sendNotification(token, title, body) {
const message = {
notification: {
title: title,
body: body,
},
token: token,
};
admin
.messaging()
.send(message)
.then((response) => {
console.log("Successfully sent message:", response);
})
.catch((error) => {
console.error("Error sending message:", error);
throw error;
});
}
app.post("/api/send-notification", (req, res) => {
const title = req.body.title;
const body = req.body.body;
const onlyForGeneration = req.body.onlyForGeneration;
if (!title) {
res.status(400).send({ message: "Title is missing" });
return;
}
if (!body) {
res.status(400).send({ message: "Body is missing" });
return;
}
if (onlyForGeneration === "None") {
tokens.forEach((value, key) => {
value.forEach((token) => {
try {
sendNotification(token, title, body);
} catch (error) {
res.status(500).send({ message: "Failed to send notification" });
return;
}
});
});
return;
}
if (!checkGeneration(onlyForGeneration)) {
res.status(400).send({ message: "Invalid generation format" });
return;
}
if (!tokens.has(onlyForGeneration)) {
res.status(400).send({ message: "No tokens for this generation" });
return;
}
tokens.get(onlyForGeneration).forEach((token) => {
try {
sendNotification(token, title, body);
} catch (error) {
res.status(500).send({ message: "Failed to send notification" });
return;
}
});
res.status(200).send({ message: "Notification sent" });
});
app.post("/api/send-personal-notification", (req, res) => {
const title = req.body.title;
const body = req.body.body;
if (!title) {
res.status(400).send({ message: "Title is missing" });
return;
}
if (!body) {
res.status(400).send({ message: "Body is missing" });
return;
}
const token = req.body.token;
if (!token) {
res.status(400).send({ message: "Token is missing" });
return;
}
try {
sendNotification(token, title, body);
} catch (error) {
res.status(500).send({ message: "Failed to send notification" });
return;
}
})
const scheduleString = "59 23 * * *";
const clearJob = cron.schedule(
scheduleString,
() => {
console.log("Clearing database..")
const db = admin.database();
const ref = db.ref();
ref
.remove()
.then(() => {
console.log("Database cleared successfully");
})
.catch((error) => {
console.error("Error clearing database:", error);
});
},
{
scheduled: true,
timezone: process.env.TZ,
}
);
const port = process.env.PORT || 3000;
app.listen(port, "0.0.0.0", () => {
console.log(`Server is running on port ${port}`);
if (clearJob !== undefined) {
console.log("Clear database job is scheduled at", new Date(cronParser.parseExpression(scheduleString).next()).toTimeString(),"everyday.");
} else {
console.log("Clear database job is not yet scheduled.");
}
});