Skip to content

Instantly share code, notes, and snippets.

@cpq
Created September 15, 2020 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cpq/8d1178db9d0d584ced9b7ba113fb8f41 to your computer and use it in GitHub Desktop.
Save cpq/8d1178db9d0d584ced9b7ba113fb8f41 to your computer and use it in GitHub Desktop.
// Run this catcher in a following way:
// 1. Make sure to install tmux, nodejs, and `ws` node package
// apt-get install tmux npm
// npm install -g ws
// 2. Start tmux. This is needed to let the program run after logout.
// When you log in again, `tmux attach` attaches an old session.
// 3. Run catcher in an infinite loop:
// while true; do node catcher.js YOUR_API_KEY ; sleep 1; done
const Websocket = require('ws'); // npm install -g ws
const token = process.argv[2]; // API token
const https = require('https');
let devices = {}; // device ID -> device mapping
let pubkeys = {}; // pubkey -> customer mapping
if (!token) {
console.error(`Usage: ${process.argv[1]} API_KEY`);
process.exit();
}
const fetch = uri => new Promise((resolve, reject) => {
const cb = resp => {
let data = '';
resp.on('data', chunk => data += chunk);
resp.on('end', ev => resolve(JSON.parse(data)));
};
var req = https.get(`https://mdash.net${uri}?access_token=${token}`, cb);
req.on('error', err => reject(err.message));
});
const mkpubkeys = data => {
data.forEach(c => {
for (var id in c.pubkeys) pubkeys[id] = c;
});
};
const mkdevices = data => {
data.forEach(d => devices[d.id] = d);
};
fetch('/api/v2/devices').then(data => mkdevices(data)); // Get devices
fetch('/api/v2/customers').then(data => mkpubkeys(data)); // Get customers
// Start catching notifications
const addr = `wss://mdash.net/api/v2/notify?access_token=${token}`;
const ws = new Websocket(addr, { origin: addr });
ws.on('open', () => console.log(`Connected, catching notifications...`));
ws.on('close', () => console.log(`Disconnected.`));
ws.on('message', msg => {
let notification = JSON.parse(msg.toString());
let device = devices[notification.id] || {};
let customer = pubkeys[device.acl.public_key] || {};
console.log(
'Got message:', JSON.stringify(notification),
'customer:', customer.email);
if (notification.name == 'offline' && customer.email) {
// Do something
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment