2017-07-10 19:47:03 +00:00
|
|
|
"use strict";
|
|
|
|
|
|
|
|
const _ = require("lodash");
|
2018-06-15 20:31:06 +00:00
|
|
|
const log = require("../log");
|
2017-07-10 19:47:03 +00:00
|
|
|
const fs = require("fs");
|
|
|
|
const path = require("path");
|
|
|
|
const WebPushAPI = require("web-push");
|
|
|
|
const Helper = require("../helper");
|
|
|
|
|
|
|
|
class WebPush {
|
|
|
|
constructor() {
|
2017-12-07 03:54:54 +00:00
|
|
|
const vapidPath = path.join(Helper.getHomePath(), "vapid.json");
|
2017-07-10 19:47:03 +00:00
|
|
|
|
|
|
|
if (fs.existsSync(vapidPath)) {
|
|
|
|
const data = fs.readFileSync(vapidPath, "utf-8");
|
|
|
|
const parsedData = JSON.parse(data);
|
|
|
|
|
|
|
|
if (typeof parsedData.publicKey === "string" && typeof parsedData.privateKey === "string") {
|
|
|
|
this.vapidKeys = {
|
|
|
|
publicKey: parsedData.publicKey,
|
|
|
|
privateKey: parsedData.privateKey,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!this.vapidKeys) {
|
|
|
|
this.vapidKeys = WebPushAPI.generateVAPIDKeys();
|
|
|
|
|
|
|
|
fs.writeFileSync(vapidPath, JSON.stringify(this.vapidKeys, null, "\t"));
|
|
|
|
|
|
|
|
log.info("New VAPID key pair has been generated for use with push subscription.");
|
|
|
|
}
|
|
|
|
|
|
|
|
WebPushAPI.setVapidDetails(
|
2018-02-21 17:48:22 +00:00
|
|
|
"https://github.com/thelounge/thelounge",
|
2017-07-10 19:47:03 +00:00
|
|
|
this.vapidKeys.publicKey,
|
|
|
|
this.vapidKeys.privateKey
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
push(client, payload, onlyToOffline) {
|
2017-11-22 06:39:32 +00:00
|
|
|
_.forOwn(client.config.sessions, ({pushSubscription}, token) => {
|
|
|
|
if (pushSubscription) {
|
|
|
|
if (onlyToOffline && _.find(client.attachedClients, {token}) !== undefined) {
|
2017-07-10 19:47:03 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2017-11-22 06:39:32 +00:00
|
|
|
this.pushSingle(client, pushSubscription, payload);
|
2017-07-10 19:47:03 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
pushSingle(client, subscription, payload) {
|
|
|
|
WebPushAPI
|
|
|
|
.sendNotification(subscription, JSON.stringify(payload))
|
|
|
|
.catch((error) => {
|
|
|
|
if (error.statusCode >= 400 && error.statusCode < 500) {
|
|
|
|
log.warn(`WebPush subscription for ${client.name} returned an error (${error.statusCode}), removing subscription`);
|
|
|
|
|
2017-11-22 06:39:32 +00:00
|
|
|
_.forOwn(client.config.sessions, ({pushSubscription}, token) => {
|
|
|
|
if (pushSubscription && pushSubscription.endpoint === subscription.endpoint) {
|
2017-07-10 19:47:03 +00:00
|
|
|
client.unregisterPushSubscription(token);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2017-08-26 15:47:35 +00:00
|
|
|
log.error(`WebPush Error (${error})`);
|
2017-07-10 19:47:03 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = WebPush;
|