2019-01-28 22:36:24 -07:00
|
|
|
import * as push from 'web-push';
|
2021-03-23 02:43:07 -06:00
|
|
|
import config from '@/config';
|
2019-04-07 06:50:36 -06:00
|
|
|
import { SwSubscriptions } from '../models';
|
2021-03-23 02:43:07 -06:00
|
|
|
import { fetchMeta } from '@/misc/fetch-meta';
|
2020-05-22 22:19:31 -06:00
|
|
|
import { PackedNotification } from '../models/repositories/notification';
|
|
|
|
import { PackedMessagingMessage } from '../models/repositories/messaging-message';
|
2017-11-20 11:40:09 -07:00
|
|
|
|
2020-05-22 22:19:31 -06:00
|
|
|
type notificationType = 'notification' | 'unreadMessagingMessage';
|
|
|
|
type notificationBody = PackedNotification | PackedMessagingMessage;
|
|
|
|
|
|
|
|
export default async function(userId: string, type: notificationType, body: notificationBody) {
|
2019-04-12 10:43:22 -06:00
|
|
|
const meta = await fetchMeta();
|
2018-12-19 12:08:13 -07:00
|
|
|
|
2019-04-12 10:43:22 -06:00
|
|
|
if (!meta.enableServiceWorker || meta.swPublicKey == null || meta.swPrivateKey == null) return;
|
2017-11-20 11:40:09 -07:00
|
|
|
|
2019-04-12 10:43:22 -06:00
|
|
|
// アプリケーションの連絡先と、サーバーサイドの鍵ペアの情報を登録
|
|
|
|
push.setVapidDetails(config.url,
|
|
|
|
meta.swPublicKey,
|
|
|
|
meta.swPrivateKey);
|
2017-11-20 15:19:02 -07:00
|
|
|
|
2017-11-20 11:40:09 -07:00
|
|
|
// Fetch
|
2019-04-07 06:50:36 -06:00
|
|
|
const subscriptions = await SwSubscriptions.find({
|
2018-03-28 23:48:47 -06:00
|
|
|
userId: userId
|
2017-11-20 11:40:09 -07:00
|
|
|
});
|
|
|
|
|
2018-12-11 04:36:55 -07:00
|
|
|
for (const subscription of subscriptions) {
|
2017-11-20 11:40:09 -07:00
|
|
|
const pushSubscription = {
|
|
|
|
endpoint: subscription.endpoint,
|
|
|
|
keys: {
|
|
|
|
auth: subscription.auth,
|
|
|
|
p256dh: subscription.publickey
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
push.sendNotification(pushSubscription, JSON.stringify({
|
|
|
|
type, body
|
2019-10-13 10:53:28 -06:00
|
|
|
}), {
|
|
|
|
proxy: config.proxy
|
|
|
|
}).catch((err: any) => {
|
2019-02-03 02:16:57 -07:00
|
|
|
//swLogger.info(err.statusCode);
|
|
|
|
//swLogger.info(err.headers);
|
|
|
|
//swLogger.info(err.body);
|
2017-11-20 11:40:09 -07:00
|
|
|
|
2020-04-03 17:46:54 -06:00
|
|
|
if (err.statusCode === 410) {
|
2019-04-07 06:50:36 -06:00
|
|
|
SwSubscriptions.delete({
|
2018-03-28 23:48:47 -06:00
|
|
|
userId: userId,
|
2017-11-20 11:40:09 -07:00
|
|
|
endpoint: subscription.endpoint,
|
|
|
|
auth: subscription.auth,
|
|
|
|
publickey: subscription.publickey
|
|
|
|
});
|
|
|
|
}
|
|
|
|
});
|
2018-12-11 04:36:55 -07:00
|
|
|
}
|
2017-11-20 11:40:09 -07:00
|
|
|
}
|