1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | module.exports = (RED) => { "use strict"; let onvif = require("node-onvif"); let isSharpAvailable = false; let sharp; try { sharp = require('sharp'); isSharpAvailable = true; } catch (ex) {} function snapshot(config) { RED.nodes.createNode(this, config); let node = this; node.on("input", function (msg) { config.name = msg.payload.name || config.name; config.url = msg.payload.url || config.url; config.username = msg.payload.username || config.username; config.password = msg.payload.password || config.password; config.resize = msg.payload.resize || config.resize; if(msg.hasOwnProperty("payload")) { msg._payload = msg.payload; } msg.node = this.type; if (!config.url) { node.warn("No URL is specified. Please specify in node configuration."); return; } run(msg, node, config); }); } RED.nodes.registerType("ONVIF Snapshot", snapshot); function run(msg, node, config) { let onvifInstance = new onvif.OnvifDevice({ xaddr: config.url, user : config.username, pass : config.password }); onvifInstance.init().then((info) => { node.log('Fetching snapshot from ' + config.url); return onvifInstance.fetchSnapshot(); }).then((res) => { let prefix = 'data:' + res.headers['content-type'] + ';base64,'; if (config.resize && isSharpAvailable) { sharp(Buffer.from(res.body, 'binary')) .resize(config.resize) .toFormat('png') .toBuffer() .then( data => { msg.payload = { config: config, image: { base64: (prefix + data.toString('base64')), binary: res.body } }; node.send(msg); }).catch( err => { }); } else { let base64Image = Buffer.from(res.body, 'binary').toString('base64'); msg.payload = { config: config, image: { base64: (prefix + base64Image), binary: res.body } }; node.send(msg); } }).catch((error) => { msg.payload = null; msg.error = error; node.send(msg); }); } } |