70 lines
2.3 KiB
JavaScript
70 lines
2.3 KiB
JavaScript
const crypto = require('crypto');
|
|
const db = require("../config/db");
|
|
const webpush = require('web-push');
|
|
|
|
const VAPID_PUBLIC_KEY = process.env.VAPID_PUBLIC_KEY;
|
|
const VAPID_PRIVATE_KEY = process.env.VAPID_PRIVATE_KEY;
|
|
|
|
webpush.setVapidDetails(
|
|
'mailto:rozenrod320@gmail.com',
|
|
VAPID_PUBLIC_KEY,
|
|
VAPID_PRIVATE_KEY
|
|
);
|
|
|
|
class PushService {
|
|
getKey() {
|
|
return new Promise((res, rej) => {
|
|
return res({ "publicKey": VAPID_PUBLIC_KEY });
|
|
});
|
|
}
|
|
|
|
createSubscribe(sheep_id, data) {
|
|
return new Promise((res, rej) => {
|
|
let sql = 'INSERT INTO subscription(sheep_id, endpoint, keys, device_name, device_model, created_at) VALUES (?, ?, ?, ?, ?, ?)';
|
|
|
|
db.run(sql, [
|
|
Number(sheep_id),
|
|
data.subscription.endpoint,
|
|
JSON.stringify(data.subscription.keys),
|
|
data.device?.name || "unknown",
|
|
data.device?.model || "unknown",
|
|
Math.floor(Date.now())
|
|
], function (err) {
|
|
if (err) {
|
|
console.error(err.message);
|
|
return res(false);
|
|
} else {
|
|
const payload = JSON.stringify(
|
|
{
|
|
"title": "Тестове повідомлення",
|
|
"body": "Ви успішно підписалися на отримання push повідомлень!",
|
|
"url": `https://${process.env.DOMAIN}`
|
|
});
|
|
|
|
webpush.sendNotification(data.subscription, payload).catch(err => {
|
|
console.error('Ошибка отправки:', err);
|
|
})
|
|
|
|
return res({ "status": "ok" });
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
deleteSubscribe(data) {
|
|
return new Promise((res, rej) => {
|
|
db.run('DELETE FROM subscription WHERE endpoint = ?', [data.endpoint], function (err) {
|
|
if (err) {
|
|
console.error(err.message);
|
|
return res(false);
|
|
} else if (this.changes === 0) {
|
|
return res(false);
|
|
} else {
|
|
res({ "status": "ok" });
|
|
}
|
|
});
|
|
});
|
|
}
|
|
}
|
|
|
|
module.exports = new PushService(); |