UNPKG

push-notification-service

Version:

Push notification package for web applications using service worker

2 lines (1 loc) 3.12 kB
function s(s){return s&&"object"==typeof s&&"default"in s?s:{default:s}}Object.defineProperty(exports,"__esModule",{value:!0});var t=s(require("web-push"));const e="BFtsHOr4nnMmA9zvImAR-XRXZ89IpppbjYaZ93L2YqkombTbXyhYXwMLJ9BnChssfIcoS6P4LYp-W1G7pqdk-RQ",i="7JgjG-jzXykKfbpt7XtZa6Po_e1siUA_65B0jAaMBx8";exports.PushNotificationClient=class{constructor(s){this.serverUrl=s.serverUrl,this.publicVapidKey=s.publicVapidKey,this.swPath=s.swPath||"/sw.js",this.userId=s.userId}urlBase64ToUint8Array(s){const t=(s+"=".repeat((4-s.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),e=window.atob(t),i=new Uint8Array(e.length);for(let s=0;s<e.length;++s)i[s]=e.charCodeAt(s);return i}async initialize(){"serviceWorker"in navigator&&"PushManager"in window||console.log("Push notifications are not supported");"granted"!==await Notification.requestPermission()&&console.log("Notification permission not granted");try{if(!this.publicVapidKey){const s=await fetch(`${this.serverUrl}/vapid-public-key`),t=await s.json();this.publicVapidKey=t.publicKey}const s=await navigator.serviceWorker.register(this.swPath);await navigator.serviceWorker.ready;let t=await s.pushManager.getSubscription();if(!t){const e=this.urlBase64ToUint8Array(this.publicVapidKey);t=await s.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:e})}return await this.saveSubscription(t),t}catch(s){console.error(`Service Worker Registration failed: ${s.message}`)}}async saveSubscription(s){return(await fetch(`${this.serverUrl}/save-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user:this.userId,key:s})})).json()}async sendNotification(s){try{return(await fetch(`${this.serverUrl}/send-notification`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)})).json()}catch(s){console.log(s)}}},exports.PushNotificationServer=class{constructor(s){this.publicKey=s.publicKey,this.privateKey=s.privateKey,this.email=s.email,this.subscriptions=new Map,t.default.setVapidDetails(`mailto:${this.email||"jfixcoding@gmail"}`,this.publicKey||e,this.privateKey||i)}setupRoutes(s){s.post("/save-subscription",this.saveSubscription.bind(this)),s.post("/send-notification",this.sendNotification.bind(this)),s.get("/vapid-public-key",((s,t)=>{t.json({publicKey:this.publicKey||e})}))}saveSubscription(s,t){const{user:e,key:i}=s.body,r=i?.keys?.auth;this.subscriptions.has(i.endpoint)||this.subscriptions.set(i.endpoint,{userAuth:r,key:i}),t.status(200).json({status:"success",message:"Subscription saved!"})}async sendNotification(s,e){const i=s.body;if(0===this.subscriptions.size)return e.status(400).json({status:"error",message:"No subscriptions found"});try{const s=await Promise.all(Array.from(this.subscriptions.values()).map((s=>t.default.sendNotification(s.key,JSON.stringify(i)).then((()=>({success:!0}))).catch((s=>({success:!1,error:s.message})))))),r=s.filter((s=>s.success)).length,a=s.length-r;e.status(200).json({status:"success",message:`Notifications sent! Success: ${r}, Failures: ${a}`})}catch(s){e.status(500).json({status:"error",message:"Internal server error"})}}};