|
| 1 | +#! /usr/bin/env node |
| 2 | +const fs = require('fs'); |
| 3 | +const webPush = require('web-push'); |
| 4 | +webPush.setGCMAPIKey(process.env.GCM_API_KEY); |
| 5 | + |
| 6 | +const argv = require('minimist')(process.argv.slice(2)); |
| 7 | + |
| 8 | +const usage = 'Use: web-push --endpoint=<url> --key=<browser key> [--auth=<auth secret>] [--ttl=<seconds>] [--payload=<message>] [--vapid-audience] [--vapid-subject] [--vapid-pvtkey] [--vapid-pubkey]'; |
| 9 | + |
| 10 | +if (!argv.endpoint || !argv.key) { |
| 11 | + console.log(usage); |
| 12 | + process.exit(1); |
| 13 | +} |
| 14 | + |
| 15 | +const endpoint = argv.endpoint; |
| 16 | +const key = argv.key; |
| 17 | +const ttl = argv.ttl || 0; |
| 18 | +const payload = argv.payload || ''; |
| 19 | +const auth = argv.auth || null; |
| 20 | +const vapidAudience = argv['vapid-audience'] || null; |
| 21 | +const vapidSubject = argv['vapid-subject'] || null; |
| 22 | +const vapidPubKey = argv['vapid-pubkey'] || null; |
| 23 | +const vapidPvtKey = argv['vapid-pvtkey'] || null; |
| 24 | + |
| 25 | +function getKeys() { |
| 26 | + if (vapidPubKey && vapidPvtKey) { |
| 27 | + const publicKey = fs.readFileSync(vapidPubKey); |
| 28 | + const privateKey = fs.readFileSync(vapidPvtKey); |
| 29 | + |
| 30 | + if (publicKey && privateKey) { |
| 31 | + return { |
| 32 | + privateKey, |
| 33 | + publicKey |
| 34 | + }; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + return webPush.generateVAPIDKeys(); |
| 39 | +} |
| 40 | + |
| 41 | +let params = { |
| 42 | + TTL: ttl, |
| 43 | + payload, |
| 44 | + userPublicKey: key |
| 45 | +}; |
| 46 | +if (vapidAudience && vapidSubject) { |
| 47 | + const vapidKeys = getKeys(); |
| 48 | + const vapid = { |
| 49 | + audience: vapidAudience, |
| 50 | + subject: `mailto:${vapidSubject}`, |
| 51 | + privateKey: vapidKeys.privateKey, |
| 52 | + publicKey: vapidKeys.publicKey |
| 53 | + }; |
| 54 | + params.vapid = vapid; |
| 55 | +} |
| 56 | +if (auth) { |
| 57 | + params.userAuth = auth; |
| 58 | +} |
| 59 | +webPush.sendNotification(endpoint, params).then(() => { |
| 60 | + console.log('Push message sent.'); |
| 61 | +}, (err) => { |
| 62 | + console.log('Error sending push message: ', err); |
| 63 | +}).then(() => { |
| 64 | + process.exit(0); |
| 65 | +}); |
| 66 | + |
0 commit comments