-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
182 lines (159 loc) · 5.66 KB
/
server.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
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const admin = require("firebase-admin");
var serviceAccount = require("./serviceAccountKey.json"); // arahkan ke lokasi serviceAccountKey.json
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://imos-unwiku-default-rtdb.asia-southeast1.firebasedatabase.app"
});
const app = express();
const api_key = "{api_key_here}";
// Daftar asal yang diizinkan
const allowedOrigins = [
'http://localhost:9000',
'https://xxx.web.app', // Tambahkan asal lain yang diizinkan
'http://another-origin.com'
];
const corsOptions = {
origin: (origin, callback) => {
if (allowedOrigins.includes(origin) || !origin) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
optionsSuccessStatus: 200 // Untuk kompatibilitas dengan beberapa browser
};
app.use(cors(corsOptions));
app.use(bodyParser.json());
// Endpoint untuk mengirim notifikasi via device token
app.post('/sendNotificationToDevice', (req, res) => {
const { key, title, body, token } = req.body;
if (key == api_key) {
const message = {
notification: {
title: title,
body: body
},
token: token // Device token yang akan menerima notifikasi
};
admin.messaging().send(message)
.then((response) => {
console.log('Successfully sent message:', response);
res.status(200).send('Successfully sent message');
})
.catch((error) => {
console.error('Error sending message:', error);
res.status(500).send('Error sending message');
});
} else {
console.error('Error sending message: wrong api_key');
res.status(500).send('Wrong api key');
}
});
// Endpoint untuk mengirim notifikasi via device token
app.post('/sendNotificationToTopic', (req, res) => {
const {key, title, body, topic } = req.body;
if (key == api_key) {
const message = {
notification: {
title: title,
body: body
},
topic: topic // Device token yang akan menerima notifikasi
};
admin.messaging().send(message)
.then((response) => {
console.log('Successfully sent message:', response);
res.status(200).send('Successfully sent message');
})
.catch((error) => {
console.error('Error sending message:', error);
res.status(500).send('Error sending message');
});
} else {
console.error('Error sending message: wrong api_key');
res.status(500).send('Wrong api key');
}
});
// Endpoint untuk mengirim notifikasi via topic dan menyimpan ke Firestore
app.post('/sendNotificationToTopicSaveFirestore', (req, res) => {
const {key, title, device_id, topic } = req.body;
let body = "";
if (key == api_key) {
// Mendapatkan data dari collection 'patients' dengan device_id yang sesuai
admin.firestore().collection('patient')
.where('device_id', '==', device_id)
.get()
.then(snapshot => {
if (snapshot.empty) {
throw new Error('No matching documents.');
}
// Ambil data dari dokumen pertama (asumsikan hanya ada satu pasien dengan device_id unik)
const data = snapshot.docs[0].data();
// Membuat pesan berdasarkan judul notifikasi
if (title === "INFUS TERSUMBAT") {
body = `Infus pada pasien bernama ${data.name} berada di ruangan ${data.room} nomor kasur ${data.bed_number}, Tersumbat!`;
} else if (title === "INFUS SEGERA HABIS") {
body = `Infus pada pasien bernama ${data.name} berada di ruangan ${data.room} nomor kasur ${data.bed_number}, Segera Habis!`;
} else {
body = `Infus pada pasien bernama ${data.name} berada di ruangan ${data.room} nomor kasur ${data.bed_number}`;
}
const message = {
notification: {
title: title,
body: body
},
topic: topic
};
// Kirim pesan menggunakan Firebase Messaging
return admin.messaging().send(message);
})
.then((response) => {
// Simpan informasi notifikasi ke Firestore collection 'notifications'
const notificationData = {
status: 'unread',
title: title,
createdAt: admin.firestore.FieldValue.serverTimestamp(),
message: body,
device_id: device_id
};
return admin.firestore().collection('notifications').add(notificationData);
})
.then((docRef) => {
res.status(200).send('Successfully sent message and saved notification: ' + docRef.id);
})
.catch((error) => {
console.error('Error sending message:', error);
res.status(500).send('Error sending message: ' + error.message);
});
} else {
console.error('Error sending message: wrong api_key');
res.status(500).send('Wrong api key');
}
});
// Endpoint untuk subscribe ke topic
app.post('/subscribe', async (req, res) => {
const { key, token } = req.body;
if (key == api_key) {
try {
await admin.messaging().subscribeToTopic(token, 'imos-alert');
res.status(200).send('Successfully subscribed to topic');
} catch (error) {
console.error('Error subscribing to topic:', error);
res.status(500).send('Error subscribing to topic');
}
} else {
console.error('Error sending message: wrong api_key');
res.status(500).send('Wrong api key');
}
});
// Endpoint root untuk memastikan server berjalan
app.get('/', (req, res) => {
res.send('Error 403 <br> Directory access is forbidden.');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});